~dobey/go-unityscopes/fix-typo

« back to all changes in this revision

Viewing changes to helpers.go

  • Committer: Rodney Dawes
  • Author(s): James Henstridge
  • Date: 2016-10-03 20:26:39 UTC
  • mfrom: (73.1.11 v2)
  • Revision ID: rodney.dawes@canonical.com-20161003202639-6qnaojpfps0vk11q
Update code to work with Go 1.6's new cgo pointer handling rules.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
package scopes
 
2
 
 
3
// #include <stdlib.h>
 
4
// #include "shim.h"
 
5
import "C"
 
6
import (
 
7
        "reflect"
 
8
        "unsafe"
 
9
)
 
10
 
 
11
// strData transforms a string to a form that can be passed to cgo
 
12
// without copying data.
 
13
func strData(s string) C.StrData {
 
14
        h := (*reflect.StringHeader)(unsafe.Pointer(&s))
 
15
        return C.StrData{
 
16
                data: (*C.char)(unsafe.Pointer(h.Data)),
 
17
                length: C.long(len(s)),
 
18
        }
 
19
}
 
20
 
 
21
// byteData transforms a byte array into the same format strData() produces.
 
22
func byteData(b []byte) C.StrData {
 
23
        if len(b) == 0 {
 
24
                return C.StrData{
 
25
                        data: nil,
 
26
                        length: 0,
 
27
                }
 
28
        }
 
29
        return C.StrData{
 
30
                data: (*C.char)(unsafe.Pointer(&b[0])),
 
31
                length: C.long(len(b)),
 
32
        }
 
33
}
 
34
 
 
35
 
 
36
func joinedStrData(a []string) C.StrData {
 
37
        total := 0
 
38
        for _, s := range a {
 
39
                total += len(s) + 1
 
40
        }
 
41
        buf := make([]byte, total)
 
42
        i := 0
 
43
        for _, s := range a {
 
44
                copy(buf[i:i+len(s)], s)
 
45
                buf[i+len(s)] = 0
 
46
                i += len(s) + 1
 
47
        }
 
48
        return byteData(buf)
 
49
}