formats#
bounded JSON with exact numbers, typed JSON records, an XML subset, the text encodings of the web -- crate root lib/formats/src/lib.rs
formats -- data formats as text: JSON, typed JSON records, an XML subset, Unicode encodings
json strict bounded JSON (RFC 8259; duplicate member names and lone surrogates are
errors): Value, Number (the exact token, no rounding through f64), parse /
parse_with_limits, stringify / stringify_with_limits / stringify_pretty, Limits,
Error { offset, kind }
jmap typed mapping of records and string enums over json::Value: Field, Json,
record! / wire_enum!, list / from_list, str_of / u64_of / obj / empty_object
xml Reader: the strict pull reader (well-formed XML 1.0 with namespaces, events, offsets,
skip; DOCTYPE refused); Lenient: the forgiving reader of files from editors (tokens,
a DOCTYPE's entities within a budget); parse / parse_with(Limits) -> Node: a bounded
tree of the strict subset (Unsupported for comments, CDATA, processing instructions
and mixed content); escape, valid_char
encoding decode(bytes, limit) -> (String, Encoding) / encode(text, Encoding): UTF-8 with
and without BOM, UTF-16 LE / BE, strict and without guessing; Charset: the single-byte
sets of the web (WHATWG: windows-1252, ISO-8859-x, KOI8 ...) and of old files (the DOS
code pages); MultiByte: Shift_JIS, EUC-JP, ISO-2022-JP, GBK, gb18030, Big5, EUC-KR;
Decoder for input in pieces; label / decode_label / from_code_page: the WHATWG Encoding
Standard's labels and decode, Windows code page numbers
Every reader takes untrusted input: it checks the size before it reads and the nesting, the
values or the elements while it reads, and reports a malformed or too large input as an error,
never a panic. Only alloc; no I/O.
The encodings' tables and the WHATWG labels are generated (charsets.rs, cjk.rs and cjk.bin,
tools/gen_encodings.py).
json and jmap came from agent_core, xml and encoding from base (0.3.0); agent_core::{json,
jmap, record!, wire_enum!} and base::{xml, encoding} remain as re-exports of these modules.
formats/src/charsets.rs#
Source: lib/formats/src/charsets.rs
charsets -- the single-byte character sets of formats::encoding (generated by tools/gen_encodings.py,
do not edit): the WHATWG Encoding Standard's single-byte encodings and labels, the DOS code pages of old
files. Tables: bytes 0x80..0xFF -> Unicode, 0 unassigned (below 0x80 every set is ASCII). The labels and
the standard's tables: Copyright © WHATWG (Apple, Google, Mozilla, Microsoft), BSD 3-Clause License
(licenses/WHATWG-LICENSE.txt).
enum Charseta single-byte character set: the bytes below 0x80 are ASCII, the others come from its table. The single-byte encodings of the WHATWG Encoding Standard (what browsers, HTML and mail use;whatwg()) and the DOS code pages of old files (byfrom_code_pageor by name here; no web label names them)Ibm866-- IBM866: DOS CyrillicIso8859_2-- ISO-8859-2: Latin 2, Central EuropeanIso8859_3-- ISO-8859-3: Latin 3, South EuropeanIso8859_4-- ISO-8859-4: Latin 4, North EuropeanIso8859_5-- ISO-8859-5: CyrillicIso8859_6-- ISO-8859-6: ArabicIso8859_7-- ISO-8859-7: GreekIso8859_8-- ISO-8859-8: Hebrew, visual orderIso8859_8I-- ISO-8859-8-I: Hebrew, logical order (the same bytes as ISO-8859-8)Iso8859_10-- ISO-8859-10: Latin 6, NordicIso8859_13-- ISO-8859-13: Latin 7, BalticIso8859_14-- ISO-8859-14: Latin 8, CelticIso8859_15-- ISO-8859-15: Latin 9, Latin 1 with the euro signIso8859_16-- ISO-8859-16: Latin 10, South-Eastern EuropeanKoi8R-- KOI8-R: RussianKoi8U-- KOI8-U: Ukrainian and Belarusian (WHATWG's KOI8-RU)Macintosh-- macintosh: Mac OS RomanWindows874-- windows-874: Thai (also TIS-620 and ISO-8859-11)Windows1250-- windows-1250: Windows Central EuropeanWindows1251-- windows-1251: Windows CyrillicWindows1252-- windows-1252: Windows Western (also ISO-8859-1 and ASCII on the web)Windows1253-- windows-1253: Windows GreekWindows1254-- windows-1254: Windows Turkish (also ISO-8859-9)Windows1255-- windows-1255: Windows HebrewWindows1256-- windows-1256: Windows ArabicWindows1257-- windows-1257: Windows BalticWindows1258-- windows-1258: Windows VietnameseXMacCyrillic-- x-mac-cyrillic: Mac OS CyrillicXUserDefined-- x-user-defined: bytes 0x80..0xFF as U+F780..U+F7FF (WHATWG)Latin1-- ISO-8859-1: ISO-8859-1 exactly: each byte is its code point (the web reads the label as windows-1252) (not WHATWG)Ibm437-- IBM437: DOS United States (also ZIP names without the UTF-8 flag) (not WHATWG)Ibm737-- IBM737: DOS Greek (not WHATWG)Ibm775-- IBM775: DOS Baltic (not WHATWG)Ibm850-- IBM850: DOS Western European (not WHATWG)Ibm852-- IBM852: DOS Central European (not WHATWG)Ibm855-- IBM855: DOS Cyrillic (IBM) (not WHATWG)Ibm857-- IBM857: DOS Turkish (not WHATWG)Ibm858-- IBM00858: DOS Western European with the euro sign (not WHATWG)Ibm860-- IBM860: DOS Portuguese (not WHATWG)Ibm861-- IBM861: DOS Icelandic (not WHATWG)Ibm862-- IBM862: DOS Hebrew (not WHATWG)Ibm863-- IBM863: DOS Canadian French (not WHATWG)Ibm864-- IBM864: DOS Arabic (not WHATWG)Ibm865-- IBM865: DOS Nordic (not WHATWG)Ibm869-- IBM869: DOS Greek 2 (not WHATWG)
impl Charset
const ALL: &'static [Charset] = &[ Charset::Ibm866, Charset::Iso8859_2, Charset::Iso8859_ ...every character set, in declaration orderconst fn name(self) -> &'static strits name: the WHATWG Encoding Standard's, else IANA's ("IBM437", "ISO-8859-1")const fn whatwg(self) -> boolwhether it is one of the WHATWG Encoding Standard's encodings (the others have no web label)const fn code_page(self) -> Option<u16>its Windows code page number (None: ISO-8859-10, -14 and -16 and x-user-defined have none)const fn from_code_page(cp: u16) -> Option<Charset>the character set of a Windows code page number: 437 to 869 (DOS), 874, 1250 to 1258, 10000 and 10007 (Mac), 20866 and 21866 (KOI8), 28591 to 28605 (ISO-8859; 28599, ISO-8859-9, is windows-1254 as on the web), 38598
formats/src/decode.rs#
Source: lib/formats/src/decode.rs
decode -- formats::encoding's Decoder: the decoders of the WHATWG Encoding Standard for input in pieces,
UTF-8, UTF-16, the single-byte sets, the replacement encoding and the multi-byte encodings, each the
standard's algorithm byte by byte (with a fast path for ASCII where no sequence is open).
The standard lets a decoder "restore" bytes it has read: they are read again, before the rest of the input.
They wait in a small queue here, so a sequence may end in one piece of input and be read again from the next.
struct DecoderA decoder for input in pieces:decode(piece, last, out)appends the text of each piece toout; a sequence cut between two pieces is finished by the next one. The output is the same as decoding the whole input at once withdecode_label(without its byte-order mark rule; seeDecoder::sniffing). Shift_JIS's "あ" in two pieces, 0x82 and then 0xA0 withlast, gives "あ".
impl Decoder
fn new(label: Label) -> DecoderA decoder of the encoding a label names (encoding::label).fn sniffing(label: Label) -> DecoderA decoder with the standard's byte-order mark rule (its "decode"): a UTF-8, UTF-16LE or UTF-16BE byte-order mark at the start wins over the label and is dropped.fn label(&self) -> LabelThe encoding decoded: the label's, or the byte-order mark's once one was found.fn malformed(&self) -> boolWhether some input was malformed (a U+FFFD in the output came from an error, not from the input).fn decode(&mut self, input: &[u8], last: bool, out: &mut String)Append the text ofinputtoout.last: no more input follows; an open sequence becomes U+FFFD, and a following call starts a new input in the encodinglabelnames (a byte-order mark is not looked for again). The output grows by at most three bytes per input byte, and by six for what an earlier piece left open.
formats/src/encoding.rs#
Source: lib/formats/src/encoding.rs
encoding -- text encodings: strict Unicode interchange, every encoding of the WHATWG Encoding Standard
(the single-byte character sets of the web, the multi-byte encodings of Chinese, Japanese and Korean) and
the DOS code pages of old files. New native library functionality.
decode(bytes, limit) -> (String, Encoding) strict UTF-8 / UTF-16 by the byte-order mark, no guessing
encode(text, Encoding) -> bytes
Charset: the WHATWG single-byte encodings (windows-1252, ISO-8859-x, KOI8, macintosh, IBM866 ...) and
the DOS code pages (IBM437 ... 869), an exact ISO-8859-1; from_label (WHATWG), from_code_page
(Windows numbers), name, code_page, decode (U+FFFD for unassigned bytes), decode_char,
encode (Unmappable), encode_char
MultiByte: Shift_JIS, EUC-JP, ISO-2022-JP, GBK, gb18030, Big5, EUC-KR; from_label, from_code_page,
name, code_page, decode, encode (Unmappable), encode_html (character references)
Decoder: the standard's decoders for input in pieces (new / sniffing, decode(piece, last, out),
malformed)
label(name) -> Label what a WHATWG label names: UTF-8, UTF-16, a Charset, a MultiByte or the
replacement encoding; from_code_page(n) -> Label: the same for a Windows number
decode_label(label, bytes, limit) -> String the standard's decode: a byte-order mark wins over the
label, then the label's encoding, errors become U+FFFD
The tables and labels are generated (charsets.rs, cjk.rs and cjk.bin, tools/gen_encodings.py): Python's
codecs, made the standard's indexes where they differ (checked against the standard's data with --verify).
enum EncodingExplicit text encodings; unmarked input is interpreted as UTF-8.Utf8Utf8BomUtf16LeUtf16Be
enum ErrorInvalid Unicode, an encoding this crate does not decode (UTF-32, an unknown label), a caller-specified byte limit, or a character the encoding cannot encode.InvalidUnsupportedLimitUnmappable(char)
fn decode(bytes: &[u8], limit: usize) -> Result<(String, Encoding), Error>Decode without replacement characters or guessed legacy code pages.fn encode(text: &str, enc: Encoding) -> Vec<u8>Encode Unicode; UTF-16 output always includes its byte-order mark.enum LabelWhat a label of the WHATWG Encoding Standard names (label).Utf8-- UTF-8Utf16Le-- UTF-16 little-endian (also the label "utf-16")Utf16Be-- UTF-16 big-endianSingle(Charset)-- a single-byte character set of this crateMulti(MultiByte)-- a multi-byte encoding: Shift_JIS, EUC-JP, ISO-2022-JP, GBK, gb18030, Big5, EUC-KRReplacement-- the standard's replacement encoding (ISO-2022-KR, HZ and other labels it closes): any input is one U+FFFD
impl Label
const fn name(self) -> &'static strIts name in the WHATWG Encoding Standard ("UTF-8", "UTF-16LE", "windows-1252", "Shift_JIS", "replacement" ...; a character set without a web label by its IANA name, "IBM437").fn from_code_page(cp: u16) -> Option<Label>The encoding of a Windows code page number: 65001 (UTF-8), 1200 and 1201 (UTF-16), the single-byte sets (Charset::from_code_page) and the multi-byte encodings (MultiByte::from_code_page); None for the others. What RTF's\ansicpg, DXF's $DWGCODEPAGE or a DBF's language driver name.fn label(name: &str) -> Option<Label>The encoding a label names, as the WHATWG Encoding Standard reads it ("get an encoding"): leading and trailing ASCII white space ignored, ASCII case ignored, the standard's labels only ("latin1", "iso-8859-1" and "ascii" are windows-1252, "utf-16" is UTF-16LE). None: no label of the standard.fn decode_label(label: &str, bytes: &[u8], limit: usize) -> Result<String, Error>Decode as the WHATWG Encoding Standard's "decode": a UTF-8 or UTF-16 byte-order mark wins over the label (and is dropped), else the label's encoding; malformed input becomes U+FFFD, never an error. Limit: more thanlimitbytes in or out; Unsupported: no label of the standard (and no byte-order mark).
impl Charset
fn from_label(name: &str) -> Option<Charset>The character set a WHATWG label names (label, single-byte sets only): "windows-1252", "latin1", "koi8-r", "cp1251", "iso8859-2" ... The DOS code pages and the exact ISO-8859-1 have no web label:from_code_pageor the variant.fn decode(self, bytes: &[u8]) -> StringThe text of these bytes; an unassigned byte becomes U+FFFD.fn decode_char(self, b: u8) -> Option<char>The character of one byte (None: unassigned in this set).fn encode_char(self, c: char) -> Option<u8>The byte of one character (None: not in this set; the first byte where a set has two).fn encode(self, text: &str) -> Result<Vec<u8>, Error>The bytes of a text; Unmappable: the first character this set does not have.
formats/src/jmap.rs#
Source: lib/formats/src/jmap.rs
jmap -- typed JSON mapping for records and string enums over json::Value: the Field trait
for member values, the Json trait for records, and the record! / wire_enum! macros that
declare a type and its mapping in one place. Missing or mistyped members read as their
default; unknown members are ignored, so old and new programs read each other's data
(protocols, project files, settings).
record! { pub struct P { pub a: String, pub n: u32, pub items: Vec<Item> } }
wire_enum! { pub enum Kind { Pc = "pc", Router = "router" } } // Default = first variant
p.to_json() / P::from_json(&v) / Field::put / Field::take
list(&[T]) / from_list(&v) / str_of / u64_of / obj([...]) / empty_object()
Field is implemented for String, bool, the integer types, Value (kept as is), Vec<T>,
Option<T> (null = None) and BTreeMap<String, T> (an object). Floating point has no exact
JSON token here: store fixed-point integers instead.
trait Field: Sized + Defaulta value that maps to one JSON memberfn put(&self) -> Valuefn take(v: Option<&Value>) -> Self
trait Json: Sizeda record (a JSON object)fn to_json(&self) -> Valuefn from_json(v: &Value) -> Option<Self>
fn empty_object() -> Valuean empty JSON object (used by record!)record!(...)declare a record: the struct (Clone, Debug, Default, PartialEq) and its Json / Field mapping; the JSON member names are the field nameswire_enum!(...)declare an enum carried as a string: Default is the first variant, ALL, as_str / parse, Fieldfn list<T: Json>(items: &[T]) -> Valuea list of records as a JSON arrayfn from_list<T: Json>(v: &Value) -> Vec<T>the records of a JSON array (or of the array underitemsof an object)fn str_of<'a>(v: &'a Value, k: &str) -> &'a stra string member of an object ("" when missing)fn u64_of(v: &Value, k: &str) -> u64an unsigned member of an object (0 when missing)fn obj<const N: usize>(fields: [(&str, Value); N]) -> Valuean object built from (name, value) pairs
formats/src/json.rs#
Source: lib/formats/src/json.rs
Strict, bounded UTF-8 JSON (RFC 8259): settings and project files, manifests, protocols,
the agent interface's control channels. New shared code (agent_core::json until 0.3.0).
struct Number(String)Exact JSON number token; construction validates the JSON number grammar.
impl Number
fn parse(text: &str) -> Option<Self>Parse one complete JSON number without rounding it through floating point.fn as_str(&self) -> &strOriginal validated JSON representation.fn as_i64(&self) -> Option<i64>Read an exactly integral JSON number without precision loss, including exponents.fn as_u64(&self) -> Option<u64>Read an exactly integral, nonnegative JSON number without precision loss.enum ValueOwned JSON data. Objects retain member order and parsed objects have unique keys.Null-- JSON null.Bool(bool)-- JSON boolean.Number(Number)-- Exact JSON number.String(String)-- Unicode string.Array(Vec<Value>)-- Ordered values.Object(Vec<(String, Value)>)-- Ordered name/value members.
impl Value
fn string(value: impl Into<String>) -> SelfMake a JSON string.fn u64(value: u64) -> SelfMake an unsigned number without converting to floating point.fn i64(value: i64) -> SelfMake a signed number without converting to floating point.fn object<const N: usize>(fields: [(&str, Value); N]) -> SelfMake an object, with later duplicate names replacing earlier values.fn insert(&mut self, key: &str, value: Value) -> boolInsert or replace an object member; false when this value is not an object.fn get(&self, key: &str) -> Option<&Value>Look up an object member.fn as_object(&self) -> Option<&[(String, Value)]>Borrow an object member list.fn as_array(&self) -> Option<&[Value]>Borrow an array.fn as_str(&self) -> Option<&str>Borrow a string.fn as_bool(&self) -> Option<bool>Read a boolean.fn as_u64(&self) -> Option<u64>Read an unsigned integer token.fn as_i64(&self) -> Option<i64>Read a signed integer token.struct LimitsBounds applied before and during decoding or encoding.bytes: usize-- Maximum encoded byte count.depth: usize-- Maximum nested arrays/objects; the root value starts at depth zero.values: usize-- Maximum total values, including the root.string_bytes: usize-- Maximum decoded bytes in any string, including member names.members: usize-- Maximum members/elements in any container.
struct ErrorParse or serialization failure with the byte offset where it was found.offset: usize-- Zero-based byte offset (zero for serialization limits).kind: &'static str-- Stable machine-readable failure category.
fn parse(bytes: &[u8]) -> Result<Value, Error>Parse a complete UTF-8 JSON value using default limits.fn parse_with_limits(bytes: &[u8], limits: Limits) -> Result<Value, Error>Parse a complete UTF-8 JSON value. Duplicate object keys and lone surrogates are errors.fn stringify(value: &Value) -> Result<String, Error>Encode JSON without literal newlines, enforcing the default bounds.fn stringify_with_limits(value: &Value, limits: Limits) -> Result<String, Error>Encode bounded JSON. Invalid duplicate keys in manually built objects are rejected.fn stringify_pretty(value: &Value, limits: Limits, indent: usize) -> Result<String, Error>Encode bounded JSON for people to read: every array element and object member on its own line, indented byindentspaces per level, "name": value; empty containers stay "[]" / "{}". The output ends without a newline.
formats/src/multibyte.rs#
Source: lib/formats/src/multibyte.rs
multibyte -- the multi-byte encodings of the WHATWG Encoding Standard for formats::encoding: Shift_JIS,
EUC-JP, ISO-2022-JP, GBK, gb18030, Big5 and EUC-KR. The encoders here, the decoders in decode.rs, both as
the standard writes them step by step; the indexes are generated (cjk.rs, cjk.bin).
A pointer is a character's place in an index (row × columns + column); the decoders compute it from the
bytes and look the code point up, the encoders search the pointers sorted by code point (*_ORDER) and
compute the bytes from it.
enum MultiByteA multi-byte encoding of the WHATWG Encoding Standard: the legacy encodings of Chinese, Japanese and Korean text that browsers, mail and old files still use. Each is the standard's: the Windows variants where the web uses them (Shift_JIS is Windows' code page 932, EUC-KR its 949, GBK its 936).ShiftJis-- Shift_JIS: Japanese as Windows writes it (code page 932, windows-31j: JIS X 0208 with the NEC and IBM extensions, half-width katakana, the user-defined rows as the Private Use Area)EucJp-- EUC-JP: Japanese on Unix (JIS X 0208, JIS X 0212 after 0x8F, half-width katakana after 0x8E)Iso2022Jp-- ISO-2022-JP: Japanese in mail and news, 7 bits with escape sequences (ASCII, JIS X 0201 Roman and katakana, JIS X 0208)Gbk-- GBK: simplified Chinese (code page 936; also what the labels gb2312 and chinese name). It reads gb18030; it writes only its two-byte characters and the euro sign as 0x80.Gb18030-- gb18030: simplified Chinese with all of Unicode but U+E5E5, which it does not write (GB18030-2022; code page 54936)Big5-- Big5: traditional Chinese with the Hong Kong Supplementary Character Set (HKSCS-2008; code page 950)EucKr-- EUC-KR: Korean as Windows writes it (code page 949, the Unified Hangul Code: all 11 172 syllables)
impl MultiByte
const ALL: &'static [MultiByte] = &[MultiByte::ShiftJis, MultiByte::EucJp, MultiByte::Iso20 ...every multi-byte encoding, in declaration orderconst fn name(self) -> &'static strits name in the WHATWG Encoding Standard ("Shift_JIS", "EUC-JP", "ISO-2022-JP", "GBK", "gb18030", "Big5", "EUC-KR")const fn code_page(self) -> u16its Windows code page number: 932, 20932, 50220, 936, 54936, 950, 949const fn from_code_page(cp: u16) -> Option<MultiByte>the encoding of a Windows code page number: 932, 936, 949, 950, 20932 and 51932 (EUC-JP), 50220 and 50221 (ISO-2022-JP), 51949 (EUC-KR), 54936. None for the others: Johab (1361) is none of the standard's, and 50222 writes half-width katakana between SO and SI, which the standard's ISO-2022-JP does not read.fn from_label(name: &str) -> Option<MultiByte>the encoding a WHATWG label names ("shift_jis", "sjis", "windows-31j", "gb2312", "big5-hkscs", "ks_c_5601-1987" ...;encoding::label), multi-byte encodings onlyfn decode(self, bytes: &[u8]) -> StringThe text of these bytes, as the standard decodes them: malformed or unassigned sequences become U+FFFD, ASCII bytes after a broken lead byte are kept. For input in pieces:Decoder.fn encode(self, text: &str) -> Result<Vec<u8>, Error>The bytes of a text; Unmappable: the first character this encoding does not have (ISO-2022-JP ends in ASCII, with ESC ( B where needed).fn encode_html(self, text: &str) -> Vec<u8>The bytes of a text, a character this encoding does not have as a decimal character reference ("😀"), as browsers submit forms (the standard's "html" error mode).
formats/src/xml/mod.rs#
Source: lib/formats/src/xml/mod.rs
xml -- XML for JFLib, one reader in two kinds, and a bounded tree on top. New native functionality;
no DTD, no I/O, no XInclude, nothing is ever fetched.
Reader (reader.rs) the strict pull reader: well-formed XML 1.0 with namespaces; events,
positions, the raw text of an element (skip); DOCTYPE refused
Lenient (lenient.rs) the forgiving reader of files from editors (SVG, fontconfig, theme parts):
tokens, nothing is an error, a DOCTYPE's internal entities with a budget
parse(text) -> Node a tree of the strict subset for interchange formats: element-only or
text-only nodes, names expanded to their namespaces; comments, processing
instructions, CDATA and mixed content refused (Unsupported); bounded
(Limits: bytes, elements, nesting; the names it keeps)
escape(text), valid_char(c) for writers
Every reader of the library is one of these two (img_svg, diagram_io, diagram_core's theme parts,
text's fontconfig files): one place to fuzz, one set of limits per caller.
struct NameExpanded XML name (prefixes are not identities).ns: Stringlocal: String
struct NodeElement-only or text-only node; mixed content is rejected by this subset reader.name: Nameattrs: Vec<(Name, String)>text: Stringchildren: Vec<Node>
impl Node
fn is(&self, ns: &str, local: &str) -> boolTest an expanded name.fn attr(&self, ns: &str, local: &str) -> Option<&str>Attribute lookup; the default namespace never applies to unprefixed attributes.enum ErrorSyntax error, resource limit, or an intentionally unsupported XML construct.Syntax-- not well-formed (or, for the tree, a name it cannot keep)Limit-- a limit of the tree: bytes, elements, nesting, attributes, the names it keepsUnsupported-- a construct the reader does not take: a DOCTYPE or other declaration, an encoding other than UTF-8 and UTF-16, XML other than 1.0; for the tree also comments, processing instructions, CDATA and mixed contentDepth-- (Reader) more open elements than its depthAttributes-- (Reader) more attributes on one element than allowed, or more than 64 namespace bindings in scope
struct LimitsWhat one parse may take: the text's bytes, its elements, their nesting. The default (4 MiB, 30000 elements, 48 levels) isparse's; a reader whose own model bounds its documents otherwise names what that model can expand to (parse_with).bytes: usizenodes: usizedepth: usize
fn valid_char(c: char) -> boolXML 1.0 character validity (also used before emitting document text).fn escape(s: &str) -> Result<String, Error>Escape text/attribute content, including CR so it survives XML newline normalization.fn parse(s: &str) -> Result<Node, Error>Parse a bounded XML subset into a tree. DTDs, processing instructions, comments, CDATA and mixed content are explicitly rejected (Unsupported). No resources are ever resolved or fetched.fn parse_with(s: &str, lim: Limits) -> Result<Node, Error>parsewithin other limits than the default ones. The tree is built from the strict Reader without recursion; a limit of the reader (nesting, attributes, bindings) is Limit here.
formats/src/xml/lenient.rs#
Source: lib/formats/src/xml/lenient.rs
lenient -- the forgiving reader of formats::xml: what a browser or an editor would still show
Lenient::new(text) / with_limits(text, attrs, entities, expand)
l.next() -> Token Start { name, attrs (raw values), empty }, End { name }, Text (raw), CData, Eof
l.decode(raw, &mut out) a raw text or attribute value with its references replaced
l.truncated() the input ended inside a tag, or the entities' budget was spent
For files from editors, which are often sloppy (SVG, fontconfig, theme parts): nothing is an error.
Tokens: a start tag (its name as written, at most `attrs` attributes: a repeated one counts, the first
stays; a value in ' or ", unquoted to the next blank or '>', none for a bare name; a stray quote, '=' or
'/' is skipped; '<' ends a broken tag), an end tag (its name; the rest up to '>' is skipped), text up to
the next '<' (a lone '<' that starts no tag is text), CDATA as written. Skipped: the XML declaration and
processing instructions, comments, every `<!...>` declaration; a DOCTYPE's internal subset gives the
entities: its `<!ENTITY name "value">` declarations (general ones; parameter and external entities are
skipped; the first declaration of a name stays; at most `entities`, values of at most 64 KiB, with
character references and the five predefined entities replaced, other references kept as written so no
entity grows exponentially). An unterminated construct ends the document there.
References (decode): the five predefined entities, character references (decimal, x or X; a number that
is no character, or 0, gives U+FFFD), the DOCTYPE's entities while `expand` bytes of their values have
not been used up (beyond: the reference is dropped and truncated() set); an unknown entity stays as
written, and so does an '&' that has no ';' within 63 bytes before the next '&'. Nesting, a second
root, mismatched end tags and limits on elements are the caller's: it builds the tree it needs.
/// the default limit of attributes per start tag
ATTRS: usize = 512
/// the default limit of entity declarations in a DOCTYPE
ENTITIES: usize = 256
/// the default budget of bytes that entity references may produce in all
EXPAND: usize = 32 << 20
enum Token<'a>what the lenient reader found nextStart { name: &'a str, attrs: Vec<(&'a str, &'a str)>, empty: bool }-- a start tag: its name as written and its attributes with their raw values ("" for none)End { name: &'a str }-- an end tagText(&'a str)-- character data as written (decode replaces the references)CData(&'a str)-- a CDATA section's content as writtenEof-- the end of the text
struct Lenient<'a>the forgiving reader (see the top of this file)
impl<'a> Lenient<'a>
fn new(s: &'a str) -> Selfa reader ofswith the default limits (ATTRS, ENTITIES, EXPAND)fn with_limits(s: &'a str, attrs: usize, entities: usize, expand: usize) -> Selfa reader with at mostattrsattributes per start tag,entitiesentity declarations andexpandbytes of entity values in allfn truncated(&self) -> boolwhether the input ended inside a tag or the entities' budget was spentfn pos(&self) -> usizethe offset the reader is atfn decode(&mut self, raw: &str, out: &mut String)a raw text or attribute value (from a token) with its references replaced, appended tooutfn next(&mut self) -> Token<'a>the next token (Eof at the end, and from then on)
formats/src/xml/reader.rs#
Source: lib/formats/src/xml/reader.rs
reader -- the strict pull reader of formats::xml: well-formed XML 1.0 with namespaces, without a DTD
Reader::new(text, depth, attrs) at most `depth` open elements and `attrs` attributes per element
r.next() -> Event Start, End, Text, CData, Comment, Pi, Eof; an empty element <a/> gives
Start (empty: true) and then End
r.skip(at) -> &str the rest of the element whose start tag began at `at`, as written
r.pos() / r.src()
Read: elements, attributes in ' or ", the five predefined entities and character references, CDATA,
comments and processing instructions (as events), the XML declaration (version 1.0; encoding UTF-8 or
UTF-16, the text is decoded already; standalone; in this order, values as written), a leading U+FEFF, and
namespaces: every name comes with the URI its prefix is bound to (Namespaces in XML 1.0; xmlns attributes
are in NS_XMLNS). Refused: a DOCTYPE and every other declaration (Unsupported: no entities, nothing
external), an undefined entity, a character XML does not allow, mismatched or unclosed tags, text or a
second element outside the root, an unbound prefix, a name that is no QName, a duplicate attribute (also
two prefixes of one namespace), more nesting than `depth` (Depth), more attributes on one element than
`attrs` or more than 64 namespace bindings in scope (Attributes). Line ends are normalised as XML says:
CR LF and CR become LF in text; in attribute values a literal tab, line end or CR becomes a space
(character references stay). Nothing recurses: the stack is the reader's own Vec, bounded by `depth`.
Text is borrowed from the input unless a reference or a CR had to be replaced.
/// the namespace of the xml prefix (xml:lang, xml:space)
NS_XML: &str = "http://www.w3.org/XML/1998/namespace"
/// the namespace of namespace declarations (xmlns, xmlns:p)
NS_XMLNS: &str = "http://www.w3.org/2000/xmlns/"
struct Attr<'a>one attribute of a start tagqname: &'a str-- the name as written (with its prefix)local: &'a str-- the name without prefix (for a declaration: the prefix it binds, "" for xmlns)ns: Cow<'a, str>-- the namespace URI ("" for an unprefixed attribute; NS_XMLNS for a declaration)value: Cow<'a, str>-- the value with references replaced and white space normalised
struct Start<'a>a start tagqname: &'a str-- the name as written (with its prefix)local: &'a str-- the name without prefixns: Cow<'a, str>-- the namespace URI ("" for none)attrs: Vec<Attr<'a>>-- the attributes in their order, namespace declarations includedempty: bool-- <a/>: an End follows right awayat: usize-- the offset of '<'end: usize-- the offset after '>'
impl Start<'_>
fn is(&self, ns: &str, local: &str) -> boolwhether this is the elementlocalof the namespacensfn attr(&self, ns: &str, local: &str) -> Option<&str>the value of the attributelocalof the namespacens("" for an unprefixed one)enum Event<'a>what the reader found nextStart(Start<'a>)-- a start tagEnd { end: usize }-- an end tag: the offset after its '>' (the start tag's end for an empty element)Text(Cow<'a, str>)-- character data with references replacedCData(Cow<'a, str>)-- a CDATA section's content (line ends normalised)Comment(&'a str)-- a comment's contentPi { target: &'a str, data: &'a str }-- a processing instructionEof-- the end of a well-formed document
struct ReadErroran error and the byte offset it was found aterror: Errorat: usize
struct Reader<'a>the strict pull reader (see the top of this file)
impl<'a> Reader<'a>
fn new(s: &'a str, depth: usize, attrs: usize) -> Selfa reader ofswith at mostdepthopen elements andattrsattributes per element; a leading U+FEFF is skippedfn pos(&self) -> usizethe offset the reader is atfn src(&self) -> &'a strthe source textfn depth(&self) -> usizethe elements open nowfn next(&mut self) -> Result<Event<'a>, ReadError>the next event; after an error the reader is not meant to go onfn skip(&mut self, at: usize) -> Result<&'a str, ReadError>the rest of the element whose start tag began atat(just returned by next), as the file wrote it