gitee.com/quant1x/gox@v1.7.6/text/encoding/convert_string.go (about)

     1  package encoding
     2  
     3  // ConvertString converts a  string from UTF-8 to e's encoding.
     4  func (e Encoder) ConvertString(s string) string {
     5  	dest := make([]byte, len(s)+10)
     6  	destPos := 0
     7  
     8  	for _, _rune := range s {
     9  	retry:
    10  		size, status := e(dest[destPos:], _rune)
    11  
    12  		if status == NO_ROOM {
    13  			newDest := make([]byte, len(dest)*2)
    14  			copy(newDest, dest)
    15  			dest = newDest
    16  			goto retry
    17  		}
    18  
    19  		if status == STATE_ONLY {
    20  			destPos += size
    21  			goto retry
    22  		}
    23  
    24  		destPos += size
    25  	}
    26  
    27  	return string(dest[:destPos])
    28  }
    29  
    30  // ConvertString converts a string from d's encoding to UTF-8.
    31  func (d Decoder) ConvertString(s string) string {
    32  	bytes := []byte(s)
    33  	runes := make([]rune, len(s))
    34  	destPos := 0
    35  
    36  	for len(bytes) > 0 {
    37  		c, size, status := d(bytes)
    38  
    39  		if status == STATE_ONLY {
    40  			bytes = bytes[size:]
    41  			continue
    42  		}
    43  
    44  		if status == NO_ROOM {
    45  			c = 0xfffd
    46  			size = len(bytes)
    47  			status = INVALID_CHAR
    48  		}
    49  
    50  		bytes = bytes[size:]
    51  		runes[destPos] = c
    52  		destPos++
    53  	}
    54  
    55  	return string(runes[:destPos])
    56  }