utils.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package winapi
  2. import (
  3. "errors"
  4. "reflect"
  5. "syscall"
  6. "unsafe"
  7. "golang.org/x/sys/windows"
  8. )
  9. // Uint16BufferToSlice wraps a uint16 pointer-and-length into a slice
  10. // for easier interop with Go APIs
  11. func Uint16BufferToSlice(buffer *uint16, bufferLength int) (result []uint16) {
  12. hdr := (*reflect.SliceHeader)(unsafe.Pointer(&result))
  13. hdr.Data = uintptr(unsafe.Pointer(buffer))
  14. hdr.Cap = bufferLength
  15. hdr.Len = bufferLength
  16. return
  17. }
  18. type UnicodeString struct {
  19. Length uint16
  20. MaximumLength uint16
  21. Buffer *uint16
  22. }
  23. //String converts a UnicodeString to a golang string
  24. func (uni UnicodeString) String() string {
  25. // UnicodeString is not guaranteed to be null terminated, therefore
  26. // use the UnicodeString's Length field
  27. return syscall.UTF16ToString(Uint16BufferToSlice(uni.Buffer, int(uni.Length/2)))
  28. }
  29. // NewUnicodeString allocates a new UnicodeString and copies `s` into
  30. // the buffer of the new UnicodeString.
  31. func NewUnicodeString(s string) (*UnicodeString, error) {
  32. // Get length of original `s` to use in the UnicodeString since the `buf`
  33. // created later will have an additional trailing null character
  34. length := len(s)
  35. if length > 32767 {
  36. return nil, syscall.ENAMETOOLONG
  37. }
  38. buf, err := windows.UTF16FromString(s)
  39. if err != nil {
  40. return nil, err
  41. }
  42. uni := &UnicodeString{
  43. Length: uint16(length * 2),
  44. MaximumLength: uint16(length * 2),
  45. Buffer: &buf[0],
  46. }
  47. return uni, nil
  48. }
  49. // ConvertStringSetToSlice is a helper function used to convert the contents of
  50. // `buf` into a string slice. `buf` contains a set of null terminated strings
  51. // with an additional null at the end to indicate the end of the set.
  52. func ConvertStringSetToSlice(buf []byte) ([]string, error) {
  53. var results []string
  54. prev := 0
  55. for i := range buf {
  56. if buf[i] == 0 {
  57. if prev == i {
  58. // found two null characters in a row, return result
  59. return results, nil
  60. }
  61. results = append(results, string(buf[prev:i]))
  62. prev = i + 1
  63. }
  64. }
  65. return nil, errors.New("string set malformed: missing null terminator at end of buffer")
  66. }