anyxml_encoding/
us_ascii.rs1use crate::{DecodeError, Decoder, EncodeError, Encoder};
2
3pub const US_ASCII_NAME: &str = "US-ASCII";
5
6pub struct USASCIIEncoder;
8impl Encoder for USASCIIEncoder {
9 fn name(&self) -> &'static str {
10 US_ASCII_NAME
11 }
12
13 fn encode(
14 &mut self,
15 src: &str,
16 dst: &mut [u8],
17 finish: bool,
18 ) -> Result<(usize, usize), EncodeError> {
19 if src.is_empty() {
20 return if finish {
21 Ok((0, 0))
22 } else {
23 Err(EncodeError::InputIsEmpty)
24 };
25 }
26
27 if dst.is_empty() {
28 return Err(EncodeError::OutputTooShort);
29 }
30
31 let (mut read, mut write) = (0, 0);
32 for c in src.chars() {
33 let b = c as u32;
34 read += c.len_utf8();
35 if b >= 128 {
36 return Err(EncodeError::Unmappable { read, write, c });
37 }
38 dst[write] = b as u8;
39 write += 1;
40 if write == dst.len() {
41 break;
42 }
43 }
44 Ok((read, write))
45 }
46}
47
48pub struct USASCIIDecoder;
50impl Decoder for USASCIIDecoder {
51 fn name(&self) -> &'static str {
52 US_ASCII_NAME
53 }
54
55 fn decode(
56 &mut self,
57 src: &[u8],
58 dst: &mut String,
59 finish: bool,
60 ) -> Result<(usize, usize), DecodeError> {
61 if src.is_empty() {
62 return if finish {
63 Ok((0, 0))
64 } else {
65 Err(DecodeError::InputIsEmpty)
66 };
67 }
68 let len = dst.capacity() - dst.len();
69 if len == 0 {
70 return Err(DecodeError::OutputTooShort);
71 }
72
73 let (mut read, mut write) = (0, 0);
74 for &b in src {
75 read += 1;
76 if b >= 128 {
77 return Err(DecodeError::Malformed {
78 read,
79 write,
80 length: 1,
81 offset: 0,
82 });
83 }
84 let c = b as char;
85 dst.push(c);
86 write += 1;
87 if write == len {
88 break;
89 }
90 }
91 Ok((read, write))
92 }
93}