utils.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package winapi
  2. import (
  3. "errors"
  4. "syscall"
  5. "unicode/utf16"
  6. "unsafe"
  7. )
  8. type UnicodeString struct {
  9. Length uint16
  10. MaximumLength uint16
  11. Buffer *uint16
  12. }
  13. //String converts a UnicodeString to a golang string
  14. func (uni UnicodeString) String() string {
  15. p := (*[0xffff]uint16)(unsafe.Pointer(uni.Buffer))
  16. // UnicodeString is not guaranteed to be null terminated, therefore
  17. // use the UnicodeString's Length field
  18. lengthInChars := uni.Length / 2
  19. return syscall.UTF16ToString(p[:lengthInChars])
  20. }
  21. // NewUnicodeString allocates a new UnicodeString and copies `s` into
  22. // the buffer of the new UnicodeString.
  23. func NewUnicodeString(s string) (*UnicodeString, error) {
  24. ws := utf16.Encode(([]rune)(s))
  25. if len(ws) > 32767 {
  26. return nil, syscall.ENAMETOOLONG
  27. }
  28. uni := &UnicodeString{
  29. Length: uint16(len(ws) * 2),
  30. MaximumLength: uint16(len(ws) * 2),
  31. Buffer: &make([]uint16, len(ws))[0],
  32. }
  33. copy((*[32768]uint16)(unsafe.Pointer(uni.Buffer))[:], ws)
  34. return uni, nil
  35. }
  36. // ConvertStringSetToSlice is a helper function used to convert the contents of
  37. // `buf` into a string slice. `buf` contains a set of null terminated strings
  38. // with an additional null at the end to indicate the end of the set.
  39. func ConvertStringSetToSlice(buf []byte) ([]string, error) {
  40. var results []string
  41. prev := 0
  42. for i := range buf {
  43. if buf[i] == 0 {
  44. if prev == i {
  45. // found two null characters in a row, return result
  46. return results, nil
  47. }
  48. results = append(results, string(buf[prev:i]))
  49. prev = i + 1
  50. }
  51. }
  52. return nil, errors.New("string set malformed: missing null terminator at end of buffer")
  53. }