-
-
Notifications
You must be signed in to change notification settings - Fork 662
/
conversions.go
53 lines (49 loc) · 1.36 KB
/
conversions.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
// SPDX-License-Identifier: MIT
package gl
import (
"fmt"
"reflect"
"strings"
"unsafe"
)
// Ptr takes a slice or pointer (to a singular scalar value or the first
// element of an array or slice) and returns its GL-compatible address.
//
// For example:
//
// var data []uint8
// ...
// gl.TexImage2D(gl.TEXTURE_2D, ..., gl.UNSIGNED_BYTE, gl.Ptr(&data[0]))
func Ptr(data interface{}) unsafe.Pointer {
if data == nil {
return unsafe.Pointer(nil)
}
var addr unsafe.Pointer
switch v := data.(type) {
case *uint8:
addr = unsafe.Pointer(v)
case *uint16:
addr = unsafe.Pointer(v)
case *float32:
addr = unsafe.Pointer(v)
case []uint8:
addr = unsafe.Pointer(&v[0])
case []uint16:
addr = unsafe.Pointer(&v[0])
case []float32:
addr = unsafe.Pointer(&v[0])
default:
panic(fmt.Errorf("unsupported type %T; must be a slice or pointer to a singular scalar value or the first element of an array or slice", v))
}
return addr
}
// Str takes a null-terminated Go string and returns its GL-compatible address.
// This function reaches into Go string storage in an unsafe way so the caller
// must ensure the string is not garbage collected.
func Str(str string) *uint8 {
if !strings.HasSuffix(str, "\x00") {
panic("str argument missing null terminator: " + str)
}
header := (*reflect.StringHeader)(unsafe.Pointer(&str))
return (*uint8)(unsafe.Pointer(header.Data))
}