Add some UTF16 utilities
Signed-off-by: Gabriel Adrian Samfira <gsamfira@cloudbasesolutions.com>
This commit is contained in:
parent
c6f29c8a47
commit
2fd170ec6f
1 changed files with 37 additions and 0 deletions
37
util/util.go
37
util/util.go
|
|
@ -22,6 +22,7 @@ import (
|
|||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/big"
|
||||
|
|
@ -31,6 +32,7 @@ import (
|
|||
"regexp"
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf16"
|
||||
|
||||
"github.com/cloudbase/garm/cloudconfig"
|
||||
"github.com/cloudbase/garm/config"
|
||||
|
|
@ -392,3 +394,38 @@ func NewID() string {
|
|||
newUUID := uuid.New()
|
||||
return toBase62(newUUID[:])
|
||||
}
|
||||
|
||||
func UTF16FromString(s string) ([]uint16, error) {
|
||||
buf := make([]uint16, 0, len(s)*2+1)
|
||||
for _, r := range s {
|
||||
buf = utf16.AppendRune(buf, r)
|
||||
}
|
||||
return utf16.AppendRune(buf, '\x00'), nil
|
||||
}
|
||||
|
||||
func UTF16ToString(s []uint16) string {
|
||||
for i, v := range s {
|
||||
if v == 0 {
|
||||
s = s[0:i]
|
||||
break
|
||||
}
|
||||
}
|
||||
return string(utf16.Decode(s))
|
||||
}
|
||||
|
||||
func Uint16ToByteArray(u []uint16) []byte {
|
||||
ret := make([]byte, (len(u)-1)*2)
|
||||
for i := 1; i < len(u)-1; i++ {
|
||||
binary.LittleEndian.PutUint16(ret[i*2:], uint16(u[i]))
|
||||
}
|
||||
return ret
|
||||
}
|
||||
|
||||
func UTF16EncodedByteArrayFromString(s string) ([]byte, error) {
|
||||
asUint16, err := UTF16FromString(s)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to encode to uint16: %w", err)
|
||||
}
|
||||
asBytes := Uint16ToByteArray(asUint16)
|
||||
return asBytes, nil
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue