Skip to main content

anyxml_encoding/
us_ascii.rs

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