github.com/Microsoft/azure-vhd-utils@v0.0.0-20230613175315-7c30a3748a1b/vhdcore/common/utils.go (about)

     1  package common
     2  
     3  import (
     4  	"encoding/binary"
     5  	"unicode/utf16"
     6  	"unicode/utf8"
     7  )
     8  
     9  // Utf16BytesToStringLE decode the given UTF16 encoded byte sequence and returns
    10  // Go UTF8 encoded string, the byte order of the given sequence is little-endian.
    11  //
    12  func Utf16BytesToStringLE(b []byte) string {
    13  	return Utf16BytesToString(b, binary.LittleEndian)
    14  }
    15  
    16  // Utf16BytesToStringBE decode the given UTF16 encoded byte sequence and returns
    17  // Go UTF8 encoded string, the byte order of the given sequence is big-endian.
    18  //
    19  func Utf16BytesToStringBE(b []byte) string {
    20  	return Utf16BytesToString(b, binary.BigEndian)
    21  }
    22  
    23  // Utf16BytesToString decode the given UTF16 encoded byte sequence and returns
    24  // Go UTF8 encoded string, the byte order of the sequence is determined by the
    25  // given binary.ByteOrder parameter.
    26  //
    27  func Utf16BytesToString(b []byte, o binary.ByteOrder) string {
    28  	var u []uint16
    29  	l := len(b)
    30  	if l&1 == 0 {
    31  		u = make([]uint16, l>>1)
    32  	} else {
    33  		u = make([]uint16, l>>1+1)
    34  		u[len(u)-1] = utf8.RuneError
    35  	}
    36  
    37  	for i, j := 0, 0; j+1 < l; i, j = i+1, j+2 {
    38  		u[i] = o.Uint16(b[j:])
    39  	}
    40  
    41  	return string(utf16.Decode(u))
    42  }
    43  
    44  // CreateByteSliceCopy creates and returns a copy of the given slice.
    45  //
    46  func CreateByteSliceCopy(b []byte) []byte {
    47  	r := make([]byte, len(b))
    48  	copy(r, b)
    49  	return r
    50  }