qubit_codec/
percent_codec.rs1use crate::{
13 CodecError,
14 CodecResult,
15 Decoder,
16 Encoder,
17};
18
19#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
21pub struct PercentCodec;
22
23impl PercentCodec {
24 pub fn new() -> Self {
29 Self
30 }
31
32 pub fn encode(&self, text: &str) -> String {
40 percent_encode_bytes(text.as_bytes(), false)
41 }
42
43 pub fn decode(&self, text: &str) -> CodecResult<String> {
55 String::from_utf8(percent_decode_bytes(text, false)?).map_err(CodecError::from)
56 }
57}
58
59impl Encoder<str> for PercentCodec {
60 type Error = CodecError;
61 type Output = String;
62
63 fn encode(&self, input: &str) -> Result<Self::Output, Self::Error> {
65 Ok(PercentCodec::encode(self, input))
66 }
67}
68
69impl Decoder<str> for PercentCodec {
70 type Error = CodecError;
71 type Output = String;
72
73 fn decode(&self, input: &str) -> Result<Self::Output, Self::Error> {
75 PercentCodec::decode(self, input)
76 }
77}
78
79pub(crate) fn percent_encode_bytes(bytes: &[u8], space_as_plus: bool) -> String {
88 let mut output = String::with_capacity(bytes.len());
89 for byte in bytes {
90 if *byte == b' ' && space_as_plus {
91 output.push('+');
92 } else if is_unreserved(*byte) {
93 output.push(*byte as char);
94 } else {
95 output.push('%');
96 output.push(percent_hex_digit(byte >> 4));
97 output.push(percent_hex_digit(byte & 0x0f));
98 }
99 }
100 output
101}
102
103pub(crate) fn percent_decode_bytes(text: &str, plus_as_space: bool) -> CodecResult<Vec<u8>> {
115 let bytes = text.as_bytes();
116 let mut output = Vec::with_capacity(bytes.len());
117 let mut index = 0;
118 while let Some(&byte) = bytes.get(index) {
119 match byte {
120 b'%' => {
121 let (Some(&high_byte), Some(&low_byte)) =
122 (bytes.get(index + 1), bytes.get(index + 2))
123 else {
124 return Err(CodecError::InvalidPercentEscape { index });
125 };
126 let high = percent_hex_value(high_byte)
127 .ok_or(CodecError::InvalidPercentEscape { index })?;
128 let low = percent_hex_value(low_byte)
129 .ok_or(CodecError::InvalidPercentEscape { index })?;
130 output.push((high << 4) | low);
131 index += 3;
132 }
133 b'+' if plus_as_space => {
134 output.push(b' ');
135 index += 1;
136 }
137 byte => {
138 output.push(byte);
139 index += 1;
140 }
141 }
142 }
143 Ok(output)
144}
145
146fn is_unreserved(byte: u8) -> bool {
154 matches!(
155 byte,
156 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~'
157 )
158}
159
160fn percent_hex_value(byte: u8) -> Option<u8> {
168 match byte {
169 b'0'..=b'9' => Some(byte - b'0'),
170 b'a'..=b'f' => Some(byte - b'a' + 10),
171 b'A'..=b'F' => Some(byte - b'A' + 10),
172 _ => None,
173 }
174}
175
176fn percent_hex_digit(value: u8) -> char {
184 match value & 0x0f {
185 0x0 => '0',
186 0x1 => '1',
187 0x2 => '2',
188 0x3 => '3',
189 0x4 => '4',
190 0x5 => '5',
191 0x6 => '6',
192 0x7 => '7',
193 0x8 => '8',
194 0x9 => '9',
195 0x0a => 'A',
196 0x0b => 'B',
197 0x0c => 'C',
198 0x0d => 'D',
199 0x0e => 'E',
200 _ => 'F',
201 }
202}