github.com/linuxboot/fiano@v1.2.0/pkg/unicode/ucs2.go (about)

     1  // Copyright 2018 the LinuxBoot Authors. All rights reserved
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package unicode converts between UCS2 cand UTF8.
     6  package unicode
     7  
     8  import (
     9  	"github.com/linuxboot/fiano/pkg/log"
    10  	"golang.org/x/text/encoding/unicode"
    11  	"golang.org/x/text/transform"
    12  )
    13  
    14  // UCS2ToUTF8 converts from UCS2 to UTF8.
    15  func UCS2ToUTF8(input []byte) string {
    16  	e := unicode.UTF16(unicode.LittleEndian, unicode.IgnoreBOM)
    17  	output, _, err := transform.Bytes(e.NewDecoder(), input)
    18  	if err != nil {
    19  		log.Errorf("could not decode UCS2: %v", err)
    20  		return string(input)
    21  	}
    22  	// Remove null terminator if one exists.
    23  	if output[len(output)-1] == 0 {
    24  		output = output[:len(output)-1]
    25  	}
    26  	return string(output)
    27  }
    28  
    29  // UTF8ToUCS2 converts from UTF8 to UCS2.
    30  func UTF8ToUCS2(input string) []byte {
    31  	e := unicode.UTF16(unicode.LittleEndian, unicode.IgnoreBOM)
    32  	input = input + "\000" // null terminator
    33  	output, _, err := transform.Bytes(e.NewEncoder(), []byte(input))
    34  	if err != nil {
    35  		log.Errorf("could not encode UCS2: %v", err)
    36  		return []byte(input)
    37  	}
    38  	return output
    39  }