ui/app: merge goString implementations and add test

Fixes gio#30

Signed-off-by: Elias Naur <mail@eliasnaur.com>
This commit is contained in:
Elias Naur
2019-08-26 21:19:58 +01:00
parent 7d47fe0fc9
commit 069bb0e7cd
4 changed files with 45 additions and 48 deletions
+1 -24
View File
@@ -4,7 +4,6 @@ package app
import (
"os"
"reflect"
"unsafe"
syscall "golang.org/x/sys/windows"
@@ -135,27 +134,5 @@ func eglTerminate(disp _EGLDisplay) bool {
func eglQueryString(disp _EGLDisplay, name _EGLint) string {
r, _, _ := _eglQueryString.Call(uintptr(disp), uintptr(name))
return goString(r)
}
func goString(s uintptr) string {
if s == 0 {
return ""
}
sh := reflect.SliceHeader{
Data: s,
Len: 1 << 30,
Cap: 1 << 30,
}
sl := *(*[]byte)(unsafe.Pointer(&sh))
var v string
for i, c := range sl {
if c == 0 {
if i > 0 {
v = string(sl[:i-1])
}
break
}
}
return v
return gl.GoString(gl.SliceOf(r))
}
+1 -24
View File
@@ -4,7 +4,6 @@ package gl
import (
"math"
"reflect"
"syscall"
"unsafe"
@@ -284,7 +283,7 @@ func (c *Functions) GetShaderInfoLog(s Shader) string {
}
func (c *Functions) GetString(pname Enum) string {
s, _, _ := syscall.Syscall(_glGetString.Addr(), 1, uintptr(pname), 0, 0)
return goString(s)
return GoString(SliceOf(s))
}
func (c *Functions) GetUniformLocation(p Program, name string) Uniform {
cname := cString(name)
@@ -365,25 +364,3 @@ func cString(s string) []byte {
copy(b, s)
return b
}
func goString(s uintptr) string {
if s == 0 {
return ""
}
sh := reflect.SliceHeader{
Data: s,
Len: 1 << 30,
Cap: 1 << 30,
}
sl := *(*[]byte)(unsafe.Pointer(&sh))
var v string
for i, c := range sl {
if c == 0 {
if i > 0 {
v = string(sl[:i-1])
}
break
}
}
return v
}
+25
View File
@@ -87,3 +87,28 @@ func ParseGLVersion(glVer string) ([2]int, error) {
}
return ver, fmt.Errorf("failed to parse OpenGL ES version (%s)", glVer)
}
func SliceOf(s uintptr) []byte {
if s == 0 {
return nil
}
sh := reflect.SliceHeader{
Data: s,
Len: 1 << 30,
Cap: 1 << 30,
}
return *(*[]byte)(unsafe.Pointer(&sh))
}
// GoString convert a NUL-terminated C string
// to a Go string.
func GoString(s []byte) string {
i := 0
for {
if s[i] == 0 {
break
}
i++
}
return string(s[:i])
}
+18
View File
@@ -0,0 +1,18 @@
package gl
import (
"testing"
)
func TestGoString(t *testing.T) {
tests := [][2]string{
{"Hello\x00", "Hello"},
{"\x00", ""},
}
for _, test := range tests {
got := GoString([]byte(test[0]))
if exp := test[1]; exp != got {
t.Errorf("expected %q got %q", exp, got)
}
}
}