Debian Codegraph @

third_party/rust/xml-rs/src/reader/parser/inside_reference.rs

raw
1 use std::char;
2
3 use common::{is_name_start_char, is_name_char, is_whitespace_str};
4
5 use reader::lexer::Token;
6
7 use super::{Result, PullParser, State};
8
9 impl PullParser {
10 pub fn inside_reference(&mut self, t: Token, prev_st: State) -> Option<Result> {
11 match t {
12 Token::Character(c) if !self.data.ref_data.is_empty() && is_name_char(c) ||
13 self.data.ref_data.is_empty() && (is_name_start_char(c) || c == '#') => {
14 self.data.ref_data.push(c);
15 None
16 }
17
18 Token::ReferenceEnd => {
19 // TODO: check for unicode correctness
20 let name = self.data.take_ref_data();
21 let name_len = name.len(); // compute once
22 let c = match &name[..] {
23 "lt" => Ok('<'.to_string()),
24 "gt" => Ok('>'.to_string()),
25 "amp" => Ok('&'.to_string()),
26 "apos" => Ok('\''.to_string()),
27 "quot" => Ok('"'.to_string()),
28 "" => Err(self_error!(self; "Encountered empty entity")),
29 _ if name_len > 2 && name.starts_with("#x") => {
30 let num_str = &name[2..name_len];
31 if num_str == "0" {
32 Err(self_error!(self; "Null character entity is not allowed"))
33 } else {
34 if self.config.replace_unknown_entity_references {
35 match u32::from_str_radix(num_str, 16).ok().map(|i| char::from_u32(i).unwrap_or('\u{fffd}')) {
36 Some(c) => Ok(c.to_string()),
37 None => Err(self_error!(self; "Invalid hexadecimal character number in an entity: {}", name))
38 }
39 } else {
40 match u32::from_str_radix(num_str, 16).ok().and_then(char::from_u32) {
41 Some(c) => Ok(c.to_string()),
42 None => Err(self_error!(self; "Invalid hexadecimal character number in an entity: {}", name))
43 }
44 }
45 }
46 }
47 _ if name_len > 1 && name.starts_with('#') => {
48 let num_str = &name[1..name_len];
49 if num_str == "0" {
50 Err(self_error!(self; "Null character entity is not allowed"))
51 } else {
52 if self.config.replace_unknown_entity_references {
53 match u32::from_str_radix(num_str, 10).ok().map(|i| char::from_u32(i).unwrap_or('\u{fffd}')) {
54 Some(c) => Ok(c.to_string()),
55 None => Err(self_error!(self; "Invalid decimal character number in an entity: {}", name))
56 }
57 }
58 else {
59 match u32::from_str_radix(num_str, 10).ok().and_then(char::from_u32) {
60 Some(c) => Ok(c.to_string()),
61 None => Err(self_error!(self; "Invalid decimal character number in an entity: {}", name))
62 }
63 }
64 }
65 },
66 _ => {
67 if let Some(v) = self.config.extra_entities.get(&name) {
68 Ok(v.clone())
69 } else {
70 Err(self_error!(self; "Unexpected entity: {}", name))
71 }
72 }
73 };
74 match c {
75 Ok(c) => {
76 self.buf.push_str(&c);
77 if prev_st == State::OutsideTag && !is_whitespace_str(&c) {
78 self.inside_whitespace = false;
79 }
80 self.into_state_continue(prev_st)
81 }
82 Err(e) => Some(e)
83 }
84 }
85
86 _ => Some(self_error!(self; "Unexpected token inside an entity: {}", t))
87 }
88 }
89 }