Skip to content
File

Blob: src/workerd/api/encoding-legacy.h

cpp52 lines
1// Copyright (c) 2017-2022 Cloudflare, Inc.
2// Licensed under the Apache 2.0 license found in the LICENSE file or at:
3// https://opensource.org/licenses/Apache-2.0
4 
5// WHATWG-compliant legacy decoders (CJK multi-byte, windows-1252,
6// x-user-defined) implemented via the encoding_rs Rust crate through
7// a CXX bridge. A single LegacyDecoder class wraps an opaque Rust-side
8// decoder that handles all the encoding-specific state machines.
9 
10#pragma once
11 
12#include "encoding-shared.h"
13 
14#include <workerd/rust/encoding/lib.rs.h>
15 
16#include <rust/cxx.h>
17 
18#include <kj/common.h>
19 
20namespace workerd::api {
21 
22// Unified legacy decoder using encoding_rs via Rust CXX bridge.
23// encoding_rs implements the full WHATWG decoder algorithms for all
24// legacy encodings, including streaming, error recovery, and ASCII
25// byte pushback.
26//
27// According to WHATWG spec, any encoding except UTF-8 and UTF-16 is considered legacy.
28class LegacyDecoder final: public Decoder {
29 public:
30 LegacyDecoder(Encoding encoding, DecoderFatal fatal);
31 ~LegacyDecoder() noexcept = default;
32 LegacyDecoder(LegacyDecoder&&) noexcept = default;
33 LegacyDecoder& operator=(LegacyDecoder&&) noexcept = default;
34 KJ_DISALLOW_COPY(LegacyDecoder);
35 
36 Encoding getEncoding() override {
37 return encoding;
38 }
39 
40 kj::Maybe<jsg::JsString> decode(
41 jsg::Lock& js, kj::ArrayPtr<const kj::byte> buffer, bool flush = false) override;
42 
43 void reset() override;
44 
45 private:
46 Encoding encoding;
47 DecoderFatal fatal;
48 ::rust::Box<::workerd::rust::encoding::Decoder> state;
49};
50 
51} // namespace workerd::api