1 | use alloc::vec::Vec; |
2 | |
3 | #[cfg (feature = "std" )] |
4 | use std::io::{self, Write}; |
5 | |
6 | #[inline ] |
7 | pub(crate) fn write_hex_to_vec(e: u8, output: &mut Vec<u8>) { |
8 | output.reserve(6); |
9 | |
10 | let length = output.len(); |
11 | |
12 | unsafe { |
13 | output.set_len(length + 6); |
14 | } |
15 | |
16 | let output = &mut output[length..]; |
17 | |
18 | output[0] = b'&' ; |
19 | output[1] = b'#' ; |
20 | output[2] = b'x' ; |
21 | output[5] = b';' ; |
22 | |
23 | let he = e >> 4; |
24 | let le = e & 0xF; |
25 | |
26 | output[3] = if he >= 10 { |
27 | b'A' - 10 + he |
28 | } else { |
29 | b'0' + he |
30 | }; |
31 | |
32 | output[4] = if le >= 10 { |
33 | b'A' - 10 + le |
34 | } else { |
35 | b'0' + le |
36 | }; |
37 | } |
38 | |
39 | #[cfg (feature = "std" )] |
40 | #[inline ] |
41 | pub(crate) fn write_hex_to_writer<W: Write>(e: u8, output: &mut W) -> Result<(), io::Error> { |
42 | output.write_fmt(args:format_args!("&#x {e:02X};" )) |
43 | } |
44 | |
45 | #[inline ] |
46 | pub(crate) fn write_html_entity_to_vec(e: u8, output: &mut Vec<u8>) { |
47 | match e { |
48 | b'&' => output.extend_from_slice(b"&" ), |
49 | b'<' => output.extend_from_slice(b"<" ), |
50 | b'>' => output.extend_from_slice(b">" ), |
51 | b'"' => output.extend_from_slice(b""" ), |
52 | _ => write_hex_to_vec(e, output), |
53 | } |
54 | } |
55 | |
56 | #[cfg (feature = "std" )] |
57 | #[inline ] |
58 | pub(crate) fn write_html_entity_to_writer<W: Write>( |
59 | e: u8, |
60 | output: &mut W, |
61 | ) -> Result<(), io::Error> { |
62 | match e { |
63 | b'&' => output.write_all(buf:b"&" ), |
64 | b'<' => output.write_all(buf:b"<" ), |
65 | b'>' => output.write_all(buf:b">" ), |
66 | b'"' => output.write_all(buf:b""" ), |
67 | _ => write_hex_to_writer(e, output), |
68 | } |
69 | } |
70 | |
71 | #[inline ] |
72 | pub(crate) fn write_char_to_vec(c: char, output: &mut Vec<u8>) { |
73 | let width: usize = c.len_utf8(); |
74 | |
75 | output.reserve(additional:width); |
76 | |
77 | let current_length: usize = output.len(); |
78 | |
79 | unsafe { |
80 | output.set_len(new_len:current_length + width); |
81 | } |
82 | |
83 | c.encode_utf8(&mut output[current_length..]); |
84 | } |
85 | |
86 | #[cfg (feature = "std" )] |
87 | #[inline ] |
88 | pub(crate) fn write_char_to_writer<W: Write>(c: char, output: &mut W) -> Result<(), io::Error> { |
89 | let mut buffer: [u8; 4] = [0u8; 4]; |
90 | let length: usize = c.encode_utf8(&mut buffer).len(); |
91 | |
92 | output.write_all(&buffer[..length]) |
93 | } |
94 | |