module scheme import encoding.binary import encoding.utf8 import encoding.utf16 import strings // Byte input is borrowed only for one synchronous step/refill. The decoder // retains at most four owned prefix bytes, never this view or its owner. struct CodecInput { data &u8 = unsafe { nil } length int final bool mut: position int } // The caller retains the byte owner for this synchronous step. Scalar fields // avoid generic mutable-argument promotion of a struct with an array header. @[inline] fn codec_input(bytes []u8, final bool) CodecInput { return CodecInput{ data: bytes.data, length: bytes.len, final: final } } @[inline] fn (input &CodecInput) byte(at int) u8 { return unsafe { input.data[at] } } enum CodecStepKind { scalar need_input finished malformed } struct CodecStep { kind CodecStepKind scalar rune } struct CodecDecoder { codec CodecKind mut: pending u32 count int started bool little bool } // Keep four owned prefix bytes in one scalar word. Mutable V structs with // fixed-array fields are promoted by this compiler even with copied C views; // scalar state keeps the resumable cursor on the stack. @[inline] fn (decoder &CodecDecoder) byte(index int) u8 { return u8(decoder.pending >> (index * 8)) } @[inline] fn (mut decoder CodecDecoder) push(byte u8) { shift := decoder.count * 8 decoder.pending = (decoder.pending & ~(u32(255) << shift)) | (u32(byte) << shift) } @[direct_array_access] fn (mut decoder CodecDecoder) fill(mut input CodecInput, count int) bool { for decoder.count < count && input.position < input.length { decoder.push(input.byte(input.position)) decoder.count++ input.position++ } return decoder.count >= count } fn codec_input_end(input &CodecInput) CodecStep { return CodecStep{ kind: if input.final { CodecStepKind.finished } else { CodecStepKind.need_input } } } // Ordinary and boundary-tracked streams specialize the same kernel. Keeping // these call contexts separate lets the C optimizer fuse the codec into each // caller without a shared out-of-line call for every scalar. struct CodecScalarStream {} struct CodecBoundaryStream {} @[inline] fn (mut decoder CodecDecoder) next(mut input CodecInput) CodecStep { return decoder.next_stream[CodecScalarStream](mut input) } @[direct_array_access] fn (mut decoder CodecDecoder) next_stream[S](mut input CodecInput) CodecStep { if decoder.codec == .latin1 { if input.position == input.length { return codec_input_end(input) } ch := input.byte(input.position) input.position++ return CodecStep{ kind: .scalar, scalar: rune(ch) } } if decoder.codec == .utf16 { return decoder.next_utf16[S](mut input) } if decoder.count == 0 && !decoder.fill(mut input, 1) { return codec_input_end(input) } lead := decoder.byte(0) if lead < 128 { decoder.count = 0 decoder.pending = 0 return CodecStep{ kind: .scalar, scalar: rune(lead) } } needed := if lead >= 0xc2 && lead <= 0xdf { 2 } else if lead >= 0xe0 && lead <= 0xef { 3 } else if lead >= 0xf0 && lead <= 0xf4 { 4 } else { 0 } if needed == 0 { decoder.count = 0 decoder.pending = 0 return CodecStep{ kind: .malformed } } for decoder.count < needed { if input.position == input.length { if !input.final { return CodecStep{ kind: .need_input } } decoder.count = 0 decoder.pending = 0 return CodecStep{ kind: .malformed } } byte := input.byte(input.position) if byte & 0xc0 != 0x80 { // Keep the noncontinuation in the caller's input; the consumed prefix // is one malformed subsequence, even when split over previous refills. decoder.count = 0 decoder.pending = 0 return CodecStep{ kind: .malformed } } decoder.push(byte) decoder.count++ input.position++ } // The pinned scalar decoder validates range/overlong/surrogate forms. // A thin synchronous C boundary avoids a temporary string borrow that this // compiler would otherwise promote the containing cursor to heap storage. mut ch := i32(0) source := [decoder.byte(0), decoder.byte(1), decoder.byte(2), decoder.byte(3)]! width := C.vile_unicode17_decode(&source[0], i32(needed), &ch) decoder.count = 0 decoder.pending = 0 return if width == needed { CodecStep{ kind: .scalar, scalar: rune(ch) } } else { CodecStep{ kind: .malformed } } } fn (decoder &CodecDecoder) unit(at int) u16 { pair := [decoder.byte(at), decoder.byte(at + 1)]! return if decoder.little { binary.little_endian_u16_fixed(pair) } else { binary.big_endian_u16_fixed(pair) } } // Called after fill(2). Both ordinary and tracked decoders share this header // decision; the tracked caller can observe the consumed BOM boundary separately. @[inline] fn (mut decoder CodecDecoder) accept_utf16_header() bool { if decoder.started { return false } decoder.started = true be := decoder.byte(0) == 0xfe && decoder.byte(1) == 0xff le := decoder.byte(0) == 0xff && decoder.byte(1) == 0xfe if !be && !le { return false } if le { decoder.little = true } decoder.count = 0 decoder.pending = 0 return true } fn (mut decoder CodecDecoder) next_utf16[S](mut input CodecInput) CodecStep { for { if !decoder.fill(mut input, 2) { if !input.final { return CodecStep{ kind: .need_input } } if decoder.count == 0 { return CodecStep{ kind: .finished } } decoder.count = 0 decoder.pending = 0 return CodecStep{ kind: .malformed } } if decoder.accept_utf16_header() { continue } first := decoder.unit(0) if first >= 0xd800 && first <= 0xdbff { if !decoder.fill(mut input, 4) { if !input.final { return CodecStep{ kind: .need_input } } // A high surrogate and an odd tail are two malformed pieces. Retain // the odd byte for the next step rather than swallowing it here. if decoder.count == 3 { decoder.pending >>= 16 decoder.count = 1 } else { decoder.count = 0 decoder.pending = 0 } return CodecStep{ kind: .malformed } } second := decoder.unit(2) if second >= 0xdc00 && second <= 0xdfff { decoder.count = 0 decoder.pending = 0 return CodecStep{ kind: .scalar, scalar: bytevector_utf16_scalar(first, second) } } decoder.pending >>= 16 decoder.count = 2 return CodecStep{ kind: .malformed } } decoder.count = 0 decoder.pending = 0 return if utf16.is_surrogate(rune(first)) { CodecStep{ kind: .malformed } } else { CodecStep{ kind: .scalar, scalar: rune(first) } } } return CodecStep{ kind: .finished } } // Input newline normalization owns one CR and at most one decoded lookahead. // It can suspend without flushing CR; ignored malformed data leaves that carry // intact, and a raised decoding error has already consumed the invalid prefix. struct TranscoderDecoder { eol EolStyle mode ErrorHandlingMode mut: decoder CodecDecoder pending_cr bool queued rune has_queued bool } // One raw step applies the error policy without hiding ignored bytes. Attached // duplex ports use each consumed boundary to synchronize a shared file cursor. // Ordinary decoders keep the same loop and newline state below. @[inline] fn (mut cursor TranscoderDecoder) next_decoded(mut input CodecInput) !CodecStep { step := cursor.decoder.next_stream[CodecBoundaryStream](mut input) if step.kind == .malformed { return cursor.decoding_error() } return step } // Keep Result construction and error-policy dispatch off the ordinary scalar // path. The whole-value decoder calls the raw codec directly, while tracked // readers use next_decoded to expose every ignored step. fn (cursor &TranscoderDecoder) decoding_error() !CodecStep { return match cursor.mode { .ignore { CodecStep{ kind: .malformed } } .raise { failure('transcoder decoding error') } .replace { CodecStep{ kind: .scalar, scalar: 0xfffd } } } } // The boolean says whether this scalar produced output. CR holds one scalar // of lookahead; a non-LF/NEL successor remains queued for the next call. @[inline] fn (mut cursor TranscoderDecoder) normalize_scalar(ch rune) (rune, bool) { if cursor.eol == .none { return ch, true } if cursor.pending_cr { cursor.pending_cr = false if ch != `\n` && ch != 0x85 { cursor.queued = ch cursor.has_queued = true } return `\n`, true } if ch == `\r` { cursor.pending_cr = true return 0, false } return if ch == `\n` || ch == 0x85 || ch == 0x2028 { rune(`\n`) } else { ch }, true } fn (mut cursor TranscoderDecoder) next(mut input CodecInput) !CodecStep { for { mut ch := rune(0) if cursor.has_queued { ch = cursor.queued cursor.has_queued = false } else { step := cursor.decoder.next(mut input) match step.kind { .need_input { return step } .finished { if cursor.pending_cr { cursor.pending_cr = false return CodecStep{ kind: .scalar, scalar: `\n` } } return step } .malformed { handled := cursor.decoding_error()! if handled.kind == .malformed { continue } ch = handled.scalar } .scalar { ch = step.scalar } } } scalar, produced := cursor.normalize_scalar(ch) if produced { return CodecStep{ kind: .scalar, scalar: scalar } } } return CodecStep{ kind: .finished } } struct TranscoderEncoder { text string codec CodecKind eol EolStyle mode ErrorHandlingMode mut: offset int pending rune has_pending bool } fn (mut cursor TranscoderEncoder) next() !CodecStep { for { mut ch := rune(0) if cursor.has_pending { ch = cursor.pending cursor.has_pending = false } else { if cursor.offset == cursor.text.len { return CodecStep{ kind: .finished } } scalar, width := utf8.decode_rune_at(cursor.text, cursor.offset) cursor.offset += width ch = scalar if ch == `\n` { match cursor.eol { .lf, .none {} .cr { ch = `\r` } .nel { ch = 0x85 } .ls { ch = 0x2028 } .crlf { ch = `\r` cursor.pending = `\n` cursor.has_pending = true } .crnel { ch = `\r` cursor.pending = 0x85 cursor.has_pending = true } } } } if cursor.codec == .latin1 && ch > 255 { match cursor.mode { .ignore { continue } .raise { return failure('transcoder encoding error') } .replace { ch = `?` } } } return CodecStep{ kind: .scalar, scalar: ch } } return CodecStep{ kind: .finished } } fn codec_scalar_length(codec CodecKind, ch rune) int { return match codec { .latin1 { 1 } .utf8 { ch.length_in_bytes() } .utf16 { 2 * utf16.rune_len(ch) } } } fn transcode_text(text string, codec CodecKind, eol EolStyle, mode ErrorHandlingMode) !Value { mut cursor := TranscoderEncoder{ text: text, codec: codec, eol: eol, mode: mode } mut length := 0 for { step := cursor.next()! if step.kind == .finished { break } needed := codec_scalar_length(codec, step.scalar) if needed > max_int - length { return failure('transcoded bytevector exceeds supported length') } length += needed } mut bytes := []u8{cap: length} unsafe { bytes.len = length } cursor = TranscoderEncoder{ text: text, codec: codec, eol: eol, mode: mode } mut at := 0 mut scalar := [4]u8{} for { step := cursor.next()! if step.kind == .finished { break } match codec { .latin1 { unsafe { (&u8(bytes.data))[at] = u8(step.scalar) } at++ } .utf8 { needed := unsafe { utf32_decode_to_buffer(u32(step.scalar), mut &scalar[0]) } unsafe { vmemcpy(&u8(bytes.data) + at, &scalar[0], needed) } at += needed } .utf16 { at += bytevector_put_utf16(mut bytes, at, false, step.scalar) } } } return owned_bytevector(bytes) } fn transcode_bytes(bytes []u8, codec CodecKind, eol EolStyle, mode ErrorHandlingMode) !Value { mut input := codec_input(bytes, true) mut cursor := TranscoderDecoder{ eol: eol, mode: mode, decoder: CodecDecoder{ codec: codec } } mut length, mut characters := 0, 0 for { step := cursor.next(mut input)! if step.kind == .finished { break } needed := step.scalar.length_in_bytes() if needed > max_int - 1 - length { return failure('transcoded string exceeds supported length') } length += needed characters++ } if length == 0 { return owned_string('', 0) } mut output := strings.new_buffer(length) input.position = 0 cursor = TranscoderDecoder{ eol: eol, mode: mode, decoder: CodecDecoder{ codec: codec } } mut scalar := [5]u8{} for { step := cursor.next(mut input)! if step.kind == .finished { break } fragment := unsafe { utf32_to_str_no_malloc(u32(step.scalar), mut &scalar[0]) } output.write_string(fragment) } return owned_string(output.take_string(), characters) }