ucs16.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package uefi
  15. import (
  16. "unicode/utf16"
  17. )
  18. // ExtractUCS16String extracts a UCS-16 string from a byte array
  19. // Returns the string data and the total length (including null terminator)
  20. func ExtractUCS16String(data []byte) ([]byte, uint32) {
  21. // Find the null terminator (two consecutive zero bytes)
  22. var i int
  23. for i = 0; i < len(data)-1; i += 2 {
  24. if data[i] == 0 && data[i+1] == 0 {
  25. break
  26. }
  27. }
  28. // Include the null terminator in the length
  29. strLen := i + 2
  30. // If we reached the end without finding a null terminator,
  31. // use the entire data length
  32. if i >= len(data)-1 {
  33. strLen = len(data)
  34. i = len(data)
  35. if i%2 != 0 {
  36. i--
  37. }
  38. }
  39. // Return the string data and length
  40. return data[:i], uint32(strLen)
  41. }
  42. // DecodeUTF16LE decodes a UTF-16LE byte array to a string
  43. func DecodeUTF16LE(b []byte) string {
  44. // Check if the byte array is empty
  45. if len(b) == 0 {
  46. return ""
  47. }
  48. // Convert bytes to uint16 array
  49. u16s := make([]uint16, len(b)/2)
  50. for i := range u16s {
  51. // Little-endian: low byte first, then high byte
  52. u16s[i] = uint16(b[i*2]) | (uint16(b[i*2+1]) << 8)
  53. }
  54. // Decode UTF-16 to UTF-8
  55. return string(utf16.Decode(u16s))
  56. }
  57. // EncodeUTF16LE encodes a string to UTF-16LE bytes
  58. func EncodeUTF16LE(s string) []byte {
  59. u16s := utf16.Encode([]rune(s))
  60. bytes := make([]byte, len(u16s)*2)
  61. for i, u16 := range u16s {
  62. bytes[i*2] = byte(u16)
  63. bytes[i*2+1] = byte(u16 >> 8)
  64. }
  65. return bytes
  66. }