-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathutils.go
55 lines (51 loc) · 1.88 KB
/
utils.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
//
// Copyright (c) 2017 Cossack Labs Limited
//
// This file is a part of Hermes-core.
//
// Hermes-core is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Hermes-core is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with Hermes-core. If not, see <http://www.gnu.org/licenses/>.
//
//
package gohermes
// #include <string.h>
// #include <stdint.h>
import "C"
import (
"errors"
"reflect"
"unsafe"
)
var ErrCAlloc = errors.New("can't allocate memory")
//CArrayToSlice return buffer as byte slice with len/cap equals to bufferLength
func CArrayToSlice(buffer unsafe.Pointer, bufferLength int) []byte {
sliceHeader := reflect.SliceHeader{Data: uintptr(buffer), Len: int(bufferLength), Cap: bufferLength}
data := *(*[]byte)(unsafe.Pointer(&sliceHeader))
return data
}
// SetOutBufferPointerFromByteSlice allocate memory, set pointer of memory into outBuffer, copy value to outBuffer and set size
// of memory to outBufferLength
func SetOutBufferPointerFromByteSlice(value []byte, outBuffer, outBufferLength unsafe.Pointer) error {
if value == nil {
*(**C.uint8_t)(outBuffer) = nil
*(*C.size_t)(outBufferLength) = 0
return nil
}
*(**C.uint8_t)(outBuffer) = (*C.uint8_t)(C.malloc(C.size_t(len(value))))
if *(**C.uint8_t)(outBuffer) == nil {
return ErrCAlloc
}
*(*C.size_t)(outBufferLength) = C.size_t(len(value))
C.memcpy(unsafe.Pointer(*(**C.uint8_t)(outBuffer)), unsafe.Pointer(&value[0]), (C.size_t)(len(value)))
return nil
}