strings.go 1001 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. // SPDX-License-Identifier: Apache-2.0
  2. // SPDX-FileCopyrightText: 2022 The Ebitengine Authors
  3. package strings
  4. import (
  5. "unsafe"
  6. )
  7. // hasSuffix tests whether the string s ends with suffix.
  8. func hasSuffix(s, suffix string) bool {
  9. return len(s) >= len(suffix) && s[len(s)-len(suffix):] == suffix
  10. }
  11. // CString converts a go string to *byte that can be passed to C code.
  12. func CString(name string) *byte {
  13. if hasSuffix(name, "\x00") {
  14. return &(*(*[]byte)(unsafe.Pointer(&name)))[0]
  15. }
  16. b := make([]byte, len(name)+1)
  17. copy(b, name)
  18. return &b[0]
  19. }
  20. // GoString copies a null-terminated char* to a Go string.
  21. func GoString(c uintptr) string {
  22. // We take the address and then dereference it to trick go vet from creating a possible misuse of unsafe.Pointer
  23. ptr := *(*unsafe.Pointer)(unsafe.Pointer(&c))
  24. if ptr == nil {
  25. return ""
  26. }
  27. var length int
  28. for {
  29. if *(*byte)(unsafe.Add(ptr, uintptr(length))) == '\x00' {
  30. break
  31. }
  32. length++
  33. }
  34. return string(unsafe.Slice((*byte)(ptr), length))
  35. }