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)) = (bytes.get(index + 1), bytes.get(index + 2)) else {
122 return Err(invalid_percent_escape(index));
123 };
124 let high = percent_hex_value(high_byte).ok_or_else(|| invalid_percent_escape(index))?;
125 let low = percent_hex_value(low_byte).ok_or_else(|| invalid_percent_escape(index))?;
126 output.push((high << 4) | low);
127 index += 3;
128 }
129 b'+' if plus_as_space => {
130 output.push(b' ');
131 index += 1;
132 }
133 byte => {
134 output.push(byte);
135 index += 1;
136 }
137 }
138 }
139 Ok(output)
140}
141
142fn invalid_percent_escape(index: usize) -> CodecError {
150 CodecError::InvalidEscape {
151 index,
152 escape: "%".to_owned(),
153 reason: "expected two hexadecimal digits".to_owned(),
154 }
155}
156
157fn is_unreserved(byte: u8) -> bool {
165 matches!(
166 byte,
167 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~'
168 )
169}
170
171fn percent_hex_value(byte: u8) -> Option<u8> {
179 match byte {
180 b'0'..=b'9' => Some(byte - b'0'),
181 b'a'..=b'f' => Some(byte - b'a' + 10),
182 b'A'..=b'F' => Some(byte - b'A' + 10),
183 _ => None,
184 }
185}
186
187fn percent_hex_digit(value: u8) -> char {
195 match value & 0x0f {
196 0x0 => '0',
197 0x1 => '1',
198 0x2 => '2',
199 0x3 => '3',
200 0x4 => '4',
201 0x5 => '5',
202 0x6 => '6',
203 0x7 => '7',
204 0x8 => '8',
205 0x9 => '9',
206 0x0a => 'A',
207 0x0b => 'B',
208 0x0c => 'C',
209 0x0d => 'D',
210 0x0e => 'E',
211 _ => 'F',
212 }
213}