vile / scheme / transcoder_codec.v
437 lines · 409 sloc · 12.25 KB · 76646891b77a3d5c6af4a1e42b122cd61dc1654b
Raw
1module scheme
2
3import encoding.binary
4import encoding.utf8
5import encoding.utf16
6import strings
7
8// Byte input is borrowed only for one synchronous step/refill. The decoder
9// retains at most four owned prefix bytes, never this view or its owner.
10struct CodecInput {
11 data &u8 = unsafe { nil }
12 length int
13 final bool
14mut:
15 position int
16}
17
18// The caller retains the byte owner for this synchronous step. Scalar fields
19// avoid generic mutable-argument promotion of a struct with an array header.
20@[inline]
21fn codec_input(bytes []u8, final bool) CodecInput {
22 return CodecInput{ data: bytes.data, length: bytes.len, final: final }
23}
24
25@[inline]
26fn (input &CodecInput) byte(at int) u8 {
27 return unsafe { input.data[at] }
28}
29
30enum CodecStepKind {
31 scalar
32 need_input
33 finished
34 malformed
35}
36
37struct CodecStep {
38 kind CodecStepKind
39 scalar rune
40}
41
42struct CodecDecoder {
43 codec CodecKind
44mut:
45 pending u32
46 count int
47 started bool
48 little bool
49}
50
51// Keep four owned prefix bytes in one scalar word. Mutable V structs with
52// fixed-array fields are promoted by this compiler even with copied C views;
53// scalar state keeps the resumable cursor on the stack.
54@[inline]
55fn (decoder &CodecDecoder) byte(index int) u8 { return u8(decoder.pending >> (index * 8)) }
56
57@[inline]
58fn (mut decoder CodecDecoder) push(byte u8) {
59 shift := decoder.count * 8
60 decoder.pending = (decoder.pending & ~(u32(255) << shift)) | (u32(byte) << shift)
61}
62
63@[direct_array_access]
64fn (mut decoder CodecDecoder) fill(mut input CodecInput, count int) bool {
65 for decoder.count < count && input.position < input.length {
66 decoder.push(input.byte(input.position))
67 decoder.count++
68 input.position++
69 }
70 return decoder.count >= count
71}
72
73fn codec_input_end(input &CodecInput) CodecStep {
74 return CodecStep{
75 kind: if input.final {
76 CodecStepKind.finished
77 } else {
78 CodecStepKind.need_input
79 }
80 }
81}
82
83// Ordinary and boundary-tracked streams specialize the same kernel. Keeping
84// these call contexts separate lets the C optimizer fuse the codec into each
85// caller without a shared out-of-line call for every scalar.
86struct CodecScalarStream {}
87
88struct CodecBoundaryStream {}
89
90@[inline]
91fn (mut decoder CodecDecoder) next(mut input CodecInput) CodecStep {
92 return decoder.next_stream[CodecScalarStream](mut input)
93}
94
95@[direct_array_access]
96fn (mut decoder CodecDecoder) next_stream[S](mut input CodecInput) CodecStep {
97 if decoder.codec == .latin1 {
98 if input.position == input.length { return codec_input_end(input) }
99 ch := input.byte(input.position)
100 input.position++
101 return CodecStep{ kind: .scalar, scalar: rune(ch) }
102 }
103 if decoder.codec == .utf16 { return decoder.next_utf16[S](mut input) }
104 if decoder.count == 0 && !decoder.fill(mut input, 1) { return codec_input_end(input) }
105 lead := decoder.byte(0)
106 if lead < 128 {
107 decoder.count = 0
108 decoder.pending = 0
109 return CodecStep{ kind: .scalar, scalar: rune(lead) }
110 }
111 needed := if lead >= 0xc2 && lead <= 0xdf {
112 2
113 } else if lead >= 0xe0 && lead <= 0xef {
114 3
115 } else if lead >= 0xf0 && lead <= 0xf4 {
116 4
117 } else {
118 0
119 }
120 if needed == 0 {
121 decoder.count = 0
122 decoder.pending = 0
123 return CodecStep{ kind: .malformed }
124 }
125 for decoder.count < needed {
126 if input.position == input.length {
127 if !input.final { return CodecStep{ kind: .need_input } }
128 decoder.count = 0
129 decoder.pending = 0
130 return CodecStep{ kind: .malformed }
131 }
132 byte := input.byte(input.position)
133 if byte & 0xc0 != 0x80 {
134 // Keep the noncontinuation in the caller's input; the consumed prefix
135 // is one malformed subsequence, even when split over previous refills.
136 decoder.count = 0
137 decoder.pending = 0
138 return CodecStep{ kind: .malformed }
139 }
140 decoder.push(byte)
141 decoder.count++
142 input.position++
143 }
144 // The pinned scalar decoder validates range/overlong/surrogate forms.
145 // A thin synchronous C boundary avoids a temporary string borrow that this
146 // compiler would otherwise promote the containing cursor to heap storage.
147 mut ch := i32(0)
148 source := [decoder.byte(0), decoder.byte(1), decoder.byte(2), decoder.byte(3)]!
149 width := C.vile_unicode17_decode(&source[0], i32(needed), &ch)
150 decoder.count = 0
151 decoder.pending = 0
152 return if width == needed {
153 CodecStep{ kind: .scalar, scalar: rune(ch) }
154 } else {
155 CodecStep{ kind: .malformed }
156 }
157}
158
159fn (decoder &CodecDecoder) unit(at int) u16 {
160 pair := [decoder.byte(at), decoder.byte(at + 1)]!
161 return if decoder.little {
162 binary.little_endian_u16_fixed(pair)
163 } else {
164 binary.big_endian_u16_fixed(pair)
165 }
166}
167
168// Called after fill(2). Both ordinary and tracked decoders share this header
169// decision; the tracked caller can observe the consumed BOM boundary separately.
170@[inline]
171fn (mut decoder CodecDecoder) accept_utf16_header() bool {
172 if decoder.started { return false }
173 decoder.started = true
174 be := decoder.byte(0) == 0xfe && decoder.byte(1) == 0xff
175 le := decoder.byte(0) == 0xff && decoder.byte(1) == 0xfe
176 if !be && !le { return false }
177 if le { decoder.little = true }
178 decoder.count = 0
179 decoder.pending = 0
180 return true
181}
182
183fn (mut decoder CodecDecoder) next_utf16[S](mut input CodecInput) CodecStep {
184 for {
185 if !decoder.fill(mut input, 2) {
186 if !input.final { return CodecStep{ kind: .need_input } }
187 if decoder.count == 0 { return CodecStep{ kind: .finished } }
188 decoder.count = 0
189 decoder.pending = 0
190 return CodecStep{ kind: .malformed }
191 }
192 if decoder.accept_utf16_header() { continue }
193 first := decoder.unit(0)
194 if first >= 0xd800 && first <= 0xdbff {
195 if !decoder.fill(mut input, 4) {
196 if !input.final { return CodecStep{ kind: .need_input } }
197 // A high surrogate and an odd tail are two malformed pieces. Retain
198 // the odd byte for the next step rather than swallowing it here.
199 if decoder.count == 3 {
200 decoder.pending >>= 16
201 decoder.count = 1
202 } else {
203 decoder.count = 0
204 decoder.pending = 0
205 }
206 return CodecStep{ kind: .malformed }
207 }
208 second := decoder.unit(2)
209 if second >= 0xdc00 && second <= 0xdfff {
210 decoder.count = 0
211 decoder.pending = 0
212 return CodecStep{ kind: .scalar, scalar: bytevector_utf16_scalar(first, second) }
213 }
214 decoder.pending >>= 16
215 decoder.count = 2
216 return CodecStep{ kind: .malformed }
217 }
218 decoder.count = 0
219 decoder.pending = 0
220 return if utf16.is_surrogate(rune(first)) {
221 CodecStep{ kind: .malformed }
222 } else {
223 CodecStep{ kind: .scalar, scalar: rune(first) }
224 }
225 }
226 return CodecStep{ kind: .finished }
227}
228
229// Input newline normalization owns one CR and at most one decoded lookahead.
230// It can suspend without flushing CR; ignored malformed data leaves that carry
231// intact, and a raised decoding error has already consumed the invalid prefix.
232struct TranscoderDecoder {
233 eol EolStyle
234 mode ErrorHandlingMode
235mut:
236 decoder CodecDecoder
237 pending_cr bool
238 queued rune
239 has_queued bool
240}
241
242// One raw step applies the error policy without hiding ignored bytes. Attached
243// duplex ports use each consumed boundary to synchronize a shared file cursor.
244// Ordinary decoders keep the same loop and newline state below.
245@[inline]
246fn (mut cursor TranscoderDecoder) next_decoded(mut input CodecInput) !CodecStep {
247 step := cursor.decoder.next_stream[CodecBoundaryStream](mut input)
248 if step.kind == .malformed { return cursor.decoding_error() }
249 return step
250}
251
252// Keep Result construction and error-policy dispatch off the ordinary scalar
253// path. The whole-value decoder calls the raw codec directly, while tracked
254// readers use next_decoded to expose every ignored step.
255fn (cursor &TranscoderDecoder) decoding_error() !CodecStep {
256 return match cursor.mode {
257 .ignore { CodecStep{ kind: .malformed } }
258 .raise { failure('transcoder decoding error') }
259 .replace { CodecStep{ kind: .scalar, scalar: 0xfffd } }
260 }
261}
262
263// The boolean says whether this scalar produced output. CR holds one scalar
264// of lookahead; a non-LF/NEL successor remains queued for the next call.
265@[inline]
266fn (mut cursor TranscoderDecoder) normalize_scalar(ch rune) (rune, bool) {
267 if cursor.eol == .none { return ch, true }
268 if cursor.pending_cr {
269 cursor.pending_cr = false
270 if ch != `\n` && ch != 0x85 {
271 cursor.queued = ch
272 cursor.has_queued = true
273 }
274 return `\n`, true
275 }
276 if ch == `\r` {
277 cursor.pending_cr = true
278 return 0, false
279 }
280 return if ch == `\n` || ch == 0x85 || ch == 0x2028 { rune(`\n`) } else { ch }, true
281}
282
283fn (mut cursor TranscoderDecoder) next(mut input CodecInput) !CodecStep {
284 for {
285 mut ch := rune(0)
286 if cursor.has_queued {
287 ch = cursor.queued
288 cursor.has_queued = false
289 } else {
290 step := cursor.decoder.next(mut input)
291 match step.kind {
292 .need_input { return step }
293 .finished {
294 if cursor.pending_cr {
295 cursor.pending_cr = false
296 return CodecStep{ kind: .scalar, scalar: `\n` }
297 }
298 return step
299 }
300 .malformed {
301 handled := cursor.decoding_error()!
302 if handled.kind == .malformed { continue }
303 ch = handled.scalar
304 }
305 .scalar { ch = step.scalar }
306 }
307 }
308 scalar, produced := cursor.normalize_scalar(ch)
309 if produced { return CodecStep{ kind: .scalar, scalar: scalar } }
310 }
311 return CodecStep{ kind: .finished }
312}
313
314struct TranscoderEncoder {
315 text string
316 codec CodecKind
317 eol EolStyle
318 mode ErrorHandlingMode
319mut:
320 offset int
321 pending rune
322 has_pending bool
323}
324
325fn (mut cursor TranscoderEncoder) next() !CodecStep {
326 for {
327 mut ch := rune(0)
328 if cursor.has_pending {
329 ch = cursor.pending
330 cursor.has_pending = false
331 } else {
332 if cursor.offset == cursor.text.len { return CodecStep{ kind: .finished } }
333 scalar, width := utf8.decode_rune_at(cursor.text, cursor.offset)
334 cursor.offset += width
335 ch = scalar
336 if ch == `\n` {
337 match cursor.eol {
338 .lf, .none {}
339 .cr { ch = `\r` }
340 .nel { ch = 0x85 }
341 .ls { ch = 0x2028 }
342 .crlf {
343 ch = `\r`
344 cursor.pending = `\n`
345 cursor.has_pending = true
346 }
347 .crnel {
348 ch = `\r`
349 cursor.pending = 0x85
350 cursor.has_pending = true
351 }
352 }
353 }
354 }
355 if cursor.codec == .latin1 && ch > 255 {
356 match cursor.mode {
357 .ignore { continue }
358 .raise { return failure('transcoder encoding error') }
359 .replace { ch = `?` }
360 }
361 }
362 return CodecStep{ kind: .scalar, scalar: ch }
363 }
364 return CodecStep{ kind: .finished }
365}
366
367fn codec_scalar_length(codec CodecKind, ch rune) int {
368 return match codec {
369 .latin1 { 1 }
370 .utf8 { ch.length_in_bytes() }
371 .utf16 { 2 * utf16.rune_len(ch) }
372 }
373}
374
375fn transcode_text(text string, codec CodecKind, eol EolStyle, mode ErrorHandlingMode) !Value {
376 mut cursor := TranscoderEncoder{ text: text, codec: codec, eol: eol, mode: mode }
377 mut length := 0
378 for {
379 step := cursor.next()!
380 if step.kind == .finished { break }
381 needed := codec_scalar_length(codec, step.scalar)
382 if needed > max_int - length {
383 return failure('transcoded bytevector exceeds supported length')
384 }
385 length += needed
386 }
387 mut bytes := []u8{cap: length}
388 unsafe { bytes.len = length }
389 cursor = TranscoderEncoder{ text: text, codec: codec, eol: eol, mode: mode }
390 mut at := 0
391 mut scalar := [4]u8{}
392 for {
393 step := cursor.next()!
394 if step.kind == .finished { break }
395 match codec {
396 .latin1 {
397 unsafe { (&u8(bytes.data))[at] = u8(step.scalar) }
398 at++
399 }
400 .utf8 {
401 needed := unsafe { utf32_decode_to_buffer(u32(step.scalar), mut &scalar[0]) }
402 unsafe { vmemcpy(&u8(bytes.data) + at, &scalar[0], needed) }
403 at += needed
404 }
405 .utf16 { at += bytevector_put_utf16(mut bytes, at, false, step.scalar) }
406 }
407 }
408 return owned_bytevector(bytes)
409}
410
411fn transcode_bytes(bytes []u8, codec CodecKind, eol EolStyle, mode ErrorHandlingMode) !Value {
412 mut input := codec_input(bytes, true)
413 mut cursor := TranscoderDecoder{ eol: eol, mode: mode, decoder: CodecDecoder{ codec: codec } }
414 mut length, mut characters := 0, 0
415 for {
416 step := cursor.next(mut input)!
417 if step.kind == .finished { break }
418 needed := step.scalar.length_in_bytes()
419 if needed > max_int - 1 - length {
420 return failure('transcoded string exceeds supported length')
421 }
422 length += needed
423 characters++
424 }
425 if length == 0 { return owned_string('', 0) }
426 mut output := strings.new_buffer(length)
427 input.position = 0
428 cursor = TranscoderDecoder{ eol: eol, mode: mode, decoder: CodecDecoder{ codec: codec } }
429 mut scalar := [5]u8{}
430 for {
431 step := cursor.next(mut input)!
432 if step.kind == .finished { break }
433 fragment := unsafe { utf32_to_str_no_malloc(u32(step.scalar), mut &scalar[0]) }
434 output.write_string(fragment)
435 }
436 return owned_string(output.take_string(), characters)
437}
438