unicode.go 727 B

1234567891011121314151617181920212223242526272829
  1. package encoder
  2. import (
  3. "bytes"
  4. "encoding/binary"
  5. "errors"
  6. "unicode/utf16"
  7. )
  8. func FromUnicode(d []byte) (string, error) {
  9. // Credit to https://github.com/Azure/go-ntlmssp/blob/master/unicode.go for logic
  10. if len(d)%2 > 0 {
  11. return "", errors.New("Unicode (UTF 16 LE) specified, but uneven data length")
  12. }
  13. s := make([]uint16, len(d)/2)
  14. err := binary.Read(bytes.NewReader(d), binary.LittleEndian, &s)
  15. if err != nil {
  16. return "", err
  17. }
  18. return string(utf16.Decode(s)), nil
  19. }
  20. func ToUnicode(s string) []byte {
  21. // Credit to https://github.com/Azure/go-ntlmssp/blob/master/unicode.go for logic
  22. uints := utf16.Encode([]rune(s))
  23. b := bytes.Buffer{}
  24. binary.Write(&b, binary.LittleEndian, &uints)
  25. return b.Bytes()
  26. }