1- decoding
2- decode: aString
3- " Convert the given string from UTF-8 using the fast path if converting to Latin-1"
4- | outStream byte1 byte2 byte3 byte4 unicode stream |
5- stream := aString readStream.
6- outStream := WriteStream on: (String new : aString size).
7- [ stream atEnd not ] whileTrue: [
8- byte1 := stream next asInteger.
9- unicode := byte1.
10- (byte1 bitAnd: 16rE0) = 192 ifTrue: [ " two bytes"
11- byte2 := stream next asInteger.
12- (byte2 bitAnd: 16rC0) = 16r80 ifFalse: [ self invalidUtf8 ].
13- unicode := ((byte1 bitAnd: 31 ) bitShift: 6 ) + (byte2 bitAnd: 63 ) ].
14- (byte1 bitAnd: 16rF0) = 224 ifTrue: [ " three bytes"
15- byte2 := stream next asInteger.
16- (byte2 bitAnd: 16rC0) = 16r80 ifFalse: [ self invalidUtf8 ].
17- byte3 := stream next asInteger.
18- (byte3 bitAnd: 16rC0) = 16r80 ifFalse: [ self invalidUtf8 ].
19- unicode := ((byte1 bitAnd: 15 ) bitShift: 12 ) + ((byte2 bitAnd: 63 ) bitShift: 6 )
20- + (byte3 bitAnd: 63 ) ].
21- (byte1 bitAnd: 16rF8) = 240 ifTrue: [ " four bytes"
22- byte2 := stream next asInteger.
23- (byte2 bitAnd: 16rC0) = 16r80 ifFalse: [ self invalidUtf8 ].
24- byte3 := stream next asInteger.
25- (byte3 bitAnd: 16rC0) = 16r80 ifFalse: [ self invalidUtf8 ].
26- byte4 := stream next asInteger.
27- (byte4 bitAnd: 16rC0) = 16r80 ifFalse: [ self invalidUtf8 ].
28- unicode := ((byte1 bitAnd: 16r7) bitShift: 18 ) +
29- ((byte2 bitAnd: 63 ) bitShift: 12 ) +
30- ((byte3 bitAnd: 63 ) bitShift: 6 ) +
31- (byte4 bitAnd: 63 ) ].
32- unicode ifNil: [ self invalidUtf8 ].
33- unicode = 16rFEFF " ignore BOM" ifFalse: [
34- outStream nextPut: (Character codePoint: unicode) ].
35- unicode := nil ].
36- ^ outStream contents
1+ convenience
2+ decode: aByteArray
3+ ^ aByteArray utf8Decoded
0 commit comments