| 43 | } |
| 44 | |
| 45 | pub fn parse_bytes(s: &str) -> Result<Vec<u8>, ParseSequenceError> { |
| 46 | let mut chars = s.chars().enumerate(); |
| 47 | let mut res: Vec<u8> = Vec::with_capacity(s.len()); |
| 48 | |
| 49 | while let Some((idx, c)) = chars.next() { |
| 50 | if c == '\\' { |
| 51 | match chars.next() { |
| 52 | None => { |
| 53 | return Err(ParseSequenceError::InvalidEscape { |
| 54 | escape: format!("{c}"), |
| 55 | index: idx, |
| 56 | string: String::from(s), |
| 57 | }); |
| 58 | } |
| 59 | Some((idx, c2)) => { |
| 60 | let byte: u8 = match c2 { |
| 61 | 'x' => { |
| 62 | let hex: String = [ |
| 63 | chars |
| 64 | .next() |
| 65 | .ok_or_else(|| ParseSequenceError::InvalidEscape { |
| 66 | escape: "\\x".to_string(), |
| 67 | index: idx, |
| 68 | string: s.to_string(), |
| 69 | })? |
| 70 | .1, |
| 71 | chars |
| 72 | .next() |
| 73 | .ok_or_else(|| ParseSequenceError::InvalidEscape { |
| 74 | escape: "\\x".to_string(), |
| 75 | index: idx, |
| 76 | string: s.to_string(), |
| 77 | })? |
| 78 | .1, |
| 79 | ] |
| 80 | .iter() |
| 81 | .collect(); |
| 82 | u8::from_str_radix(&hex, 16).map_err(|_| { |
| 83 | ParseSequenceError::InvalidEscape { |
| 84 | escape: hex, |
| 85 | index: idx, |
| 86 | string: s.to_string(), |
| 87 | } |
| 88 | })? |
| 89 | } |
| 90 | n if ('0'..='3').contains(&n) => { |
| 91 | let octal: String = [ |
| 92 | n, |
| 93 | chars |
| 94 | .next() |
| 95 | .ok_or_else(|| ParseSequenceError::InvalidEscape { |
| 96 | escape: format!("\\{n}"), |
| 97 | index: idx, |
| 98 | string: s.to_string(), |
| 99 | })? |
| 100 | .1, |
| 101 | chars |
| 102 | .next() |