Debian Codegraph @

decode.go

raw symbols SCIP
1 package scsu
2
3 import (
4 "bytes"
5 "errors"
6 "fmt"
7 "io"
8 "strings"
9 "unicode/utf16"
10 )
11
12 type Reader struct {
13 scsu
14 brd io.ByteReader
15 bytesRead int
16 }
17
18 var (
19 ErrIllegalInput = errors.New("illegal input")
20 )
21
22 func NewReader(r io.ByteReader) *Reader {
23 d := &Reader{
24 brd: r,
25 }
26 d.init()
27 return d
28 }
29
30 func (r *Reader) readByte() (byte, error) {
31 b, err := r.brd.ReadByte()
32 if err == nil {
33 r.bytesRead++
34 }
35 return b, err
36 }
37
38 /** (re-)define (and select) a dynamic window
39 A sliding window position cannot start at any Unicode value,
40 so rather than providing an absolute offset, this function takes
41 an index value which selects among the possible starting values.
42
43 Most scripts in Unicode start on or near a half-block boundary
44 so the default behaviour is to multiply the index by 0x80. Han,
45 Hangul, Surrogates and other scripts between 0x3400 and 0xDFFF
46 show very poor locality--therefore no sliding window can be set
47 there. A jumpOffset is added to the index value to skip that region,
48 and only 167 index values total are required to select all eligible
49 half-blocks.
50
51 Finally, a few scripts straddle half block boundaries. For them, a
52 table of fixed offsets is used, and the index values from 0xF9 to
53 0xFF are used to select these special offsets.
54
55 After (re-)defining a windows location it is selected so it is ready
56 for use.
57
58 Recall that all Windows are of the same length (128 code positions).
59 */
60 func (r *Reader) defineWindow(iWindow int, offset byte) error {
61 // 0 is a reserved value
62 if offset == 0 {
63 return ErrIllegalInput
64 }
65 if offset < gapThreshold {
66 r.dynamicOffset[iWindow] = int32(offset) << 7
67 } else if offset < reservedStart {
68 r.dynamicOffset[iWindow] = (int32(offset) << 7) + gapOffset
69 } else if offset < fixedThreshold {
70 return fmt.Errorf("offset = %d", offset)
71 } else {
72 r.dynamicOffset[iWindow] = fixedOffset[offset-fixedThreshold]
73 }
74
75 // make the redefined window the active one
76 r.window = iWindow
77 return nil
78 }
79
80 /** (re-)define (and select) a window as an extended dynamic window
81 The surrogate area in Unicode allows access to 2**20 codes beyond the
82 first 64K codes by combining one of 1024 characters from the High
83 Surrogate Area with one of 1024 characters from the Low Surrogate
84 Area (see Unicode 2.0 for the details).
85
86 The tags SDX and UDX set the window such that each subsequent byte in
87 the range 80 to FF represents a surrogate pair. The following diagram
88 shows how the bits in the two bytes following the SDX or UDX, and a
89 subsequent data byte, map onto the bits in the resulting surrogate pair.
90
91 hbyte lbyte data
92 nnnwwwww zzzzzyyy 1xxxxxxx
93
94 high-surrogate low-surrogate
95 110110wwwwwzzzzz 110111yyyxxxxxxx
96
97 @param chOffset - Since the three top bits of chOffset are not needed to
98 set the location of the extended Window, they are used instead
99 to select the window, thereby reducing the number of needed command codes.
100 The bottom 13 bits of chOffset are used to calculate the offset relative to
101 a 7 bit input data byte to yield the 20 bits expressed by each surrogate pair.
102 **/
103 func (r *Reader) defineExtendedWindow(chOffset uint16) {
104 // The top 3 bits of iOffsetHi are the window index
105 window := chOffset >> 13
106
107 // Calculate the new offset
108 r.dynamicOffset[window] = ((int32(chOffset) & 0x1FFF) << 7) + (1 << 16)
109
110 // make the redefined window the active one
111 r.window = int(window)
112 }
113
114 // convert an io.EOF into io.ErrUnexpectedEOF
115 func unexpectedEOF(e error) error {
116 if errors.Is(e, io.EOF) {
117 return io.ErrUnexpectedEOF
118 }
119
120 return e
121 }
122
123 func (r *Reader) expandUnicode() (rune, error) {
124 for {
125 b, err := r.readByte()
126 if err != nil {
127 return 0, err
128 }
129 if b >= UC0 && b <= UC7 {
130 r.window = int(b) - UC0
131 r.unicodeMode = false
132 return -1, nil
133 }
134 if b >= UD0 && b <= UD7 {
135 b1, err := r.readByte()
136 if err != nil {
137 return 0, unexpectedEOF(err)
138 }
139 r.unicodeMode = false
140 return -1, r.defineWindow(int(b)-UD0, b1)
141 }
142 if b == UDX {
143 c, err := r.readUint16()
144 if err != nil {
145 return 0, unexpectedEOF(err)
146 }
147 r.defineExtendedWindow(c)
148 r.unicodeMode = false
149 return -1, nil
150 }
151 if b == UQU {
152 r, err := r.readUint16()
153 if err != nil {
154 return 0, err
155 }
156 return rune(r), nil
157 } else {
158 b1, err := r.readByte()
159 if err != nil {
160 return 0, unexpectedEOF(err)
161 }
162 ch := rune(uint16FromTwoBytes(b, b1))
163 if utf16.IsSurrogate(ch) {
164 ch1, err := r.readUint16()
165 if err != nil {
166 return 0, unexpectedEOF(err)
167 }
168 surrLo := rune(ch1)
169 if !utf16.IsSurrogate(surrLo) {
170 return 0, ErrIllegalInput
171 }
172 return utf16.DecodeRune(ch, surrLo), nil
173 }
174 return ch, nil
175 }
176 }
177 }
178
179 func (r *Reader) readUint16() (uint16, error) {
180 b1, err := r.readByte()
181 if err != nil {
182 return 0, unexpectedEOF(err)
183 }
184 b2, err := r.readByte()
185 if err != nil {
186 return 0, unexpectedEOF(err)
187 }
188 return uint16FromTwoBytes(b1, b2), nil
189 }
190
191 func uint16FromTwoBytes(hi, lo byte) uint16 {
192 return uint16(hi)<<8 | uint16(lo)
193 }
194
195 /** expand portion of the input that is in single byte mode **/
196 func (r *Reader) expandSingleByte() (rune, error) {
197 for {
198 b, err := r.readByte()
199 if err != nil {
200 return 0, err
201 }
202 staticWindow := 0
203 dynamicWindow := r.window
204
205 switch b {
206 case SQ0, SQ1, SQ2, SQ3, SQ4, SQ5, SQ6, SQ7:
207 // Select window pair to quote from
208 dynamicWindow = int(b) - SQ0
209 staticWindow = dynamicWindow
210 b, err = r.readByte()
211 if err != nil {
212 return 0, unexpectedEOF(err)
213 }
214 fallthrough
215 default:
216 // output as character
217 if b < 0x80 {
218 // use static window
219 return int32(b) + staticOffset[staticWindow], nil
220 } else {
221 ch := int32(b) - 0x80
222 ch += r.dynamicOffset[dynamicWindow]
223 return ch, nil
224 }
225 case SDX:
226 // define a dynamic window as extended
227 ch, err := r.readUint16()
228 if err != nil {
229 return 0, unexpectedEOF(err)
230 }
231 r.defineExtendedWindow(ch)
232 case SD0, SD1, SD2, SD3, SD4, SD5, SD6, SD7:
233 // Position a dynamic Window
234 b1, err := r.readByte()
235 if err != nil {
236 return 0, unexpectedEOF(err)
237 }
238 err = r.defineWindow(int(b)-SD0, b1)
239 if err != nil {
240 return 0, err
241 }
242 case SC0, SC1, SC2, SC3, SC4, SC5, SC6, SC7:
243 // Select a new dynamic Window
244 r.window = int(b) - SC0
245 case SCU:
246 // switch to Unicode mode and continue parsing
247 r.unicodeMode = true
248 return -1, nil
249 case SQU:
250 // directly extract one Unicode character
251 ch, err := r.readUint16()
252 if err != nil {
253 return 0, err
254 }
255 return rune(ch), nil
256 case Srs:
257 return 0, ErrIllegalInput
258 }
259 }
260 }
261
262 func (r *Reader) readRune() (rune, error) {
263 for {
264 var c rune
265 var err error
266 if r.unicodeMode {
267 c, err = r.expandUnicode()
268 } else {
269 c, err = r.expandSingleByte()
270 }
271 if err != nil {
272 return 0, err
273 }
274 if c == -1 {
275 continue
276 }
277 return c, nil
278 }
279 }
280
281 // ReadRune reads a single SCSU encoded Unicode character
282 // and returns the rune and the amount of bytes consumed. If no character is
283 // available, err will be set.
284 func (r *Reader) ReadRune() (rune, int, error) {
285 pr := r.bytesRead
286 c, err := r.readRune()
287 return c, r.bytesRead - pr, err
288 }
289
290 // ReadStringSizeHint is like ReadString, but takes a hint about the expected string size.
291 // Note this is the size of the UTF-8 encoded string in bytes.
292 func (r *Reader) ReadStringSizeHint(sizeHint int) (string, error) {
293 var sb strings.Builder
294 if sizeHint > 0 {
295 sb.Grow(sizeHint)
296 }
297 for {
298 r, err := r.readRune()
299 if err != nil {
300 if errors.Is(err, io.EOF) {
301 break
302 }
303 return "", err
304 }
305 sb.WriteRune(r)
306 }
307 return sb.String(), nil
308 }
309
310 // ReadString reads all available input as a string.
311 // It keeps reading the source reader until it returns io.EOF or an error occurs.
312 // In case of io.EOF the error returned by ReadString will be nil.
313 func (r *Reader) ReadString() (string, error) {
314 return r.ReadStringSizeHint(0)
315 }
316
317 func (r *Reader) Reset(rd io.ByteReader) {
318 r.brd, r.bytesRead = rd, 0
319 r.reset()
320 r.init()
321 }
322
323 // Decode a byte array as a string.
324 func Decode(b []byte) (string, error) {
325 return NewReader(bytes.NewBuffer(b)).ReadStringSizeHint(len(b))
326 }