| 1 | use std::{fmt, ops::Range}; |
| 2 | |
| 3 | use crate::{ |
| 4 | Buffer, ParseError, |
| 5 | err::{perr, ParseErrorKind::*}, |
| 6 | escape::{scan_raw_string, unescape_string}, |
| 7 | }; |
| 8 | |
| 9 | |
| 10 | /// A byte string or raw byte string literal, e.g. `b"hello"` or `br#"abc"def"#`. |
| 11 | /// |
| 12 | /// See [the reference][ref] for more information. |
| 13 | /// |
| 14 | /// [ref]: https://doc.rust-lang.org/reference/tokens.html#byte-string-literals |
| 15 | #[derive (Debug, Clone, PartialEq, Eq)] |
| 16 | pub struct ByteStringLit<B: Buffer> { |
| 17 | /// The raw input. |
| 18 | raw: B, |
| 19 | |
| 20 | /// The string value (with all escaped unescaped), or `None` if there were |
| 21 | /// no escapes. In the latter case, `input` is the string value. |
| 22 | value: Option<Vec<u8>>, |
| 23 | |
| 24 | /// The number of hash signs in case of a raw string literal, or `None` if |
| 25 | /// it's not a raw string literal. |
| 26 | num_hashes: Option<u32>, |
| 27 | |
| 28 | /// Start index of the suffix or `raw.len()` if there is no suffix. |
| 29 | start_suffix: usize, |
| 30 | } |
| 31 | |
| 32 | impl<B: Buffer> ByteStringLit<B> { |
| 33 | /// Parses the input as a (raw) byte string literal. Returns an error if the |
| 34 | /// input is invalid or represents a different kind of literal. |
| 35 | pub fn parse(input: B) -> Result<Self, ParseError> { |
| 36 | if input.is_empty() { |
| 37 | return Err(perr(None, Empty)); |
| 38 | } |
| 39 | if !input.starts_with(r#"b""# ) && !input.starts_with("br" ) { |
| 40 | return Err(perr(None, InvalidByteStringLiteralStart)); |
| 41 | } |
| 42 | |
| 43 | let (value, num_hashes, start_suffix) = parse_impl(&input)?; |
| 44 | Ok(Self { raw: input, value, num_hashes, start_suffix }) |
| 45 | } |
| 46 | |
| 47 | /// Returns the string value this literal represents (where all escapes have |
| 48 | /// been turned into their respective values). |
| 49 | pub fn value(&self) -> &[u8] { |
| 50 | self.value.as_deref().unwrap_or(&self.raw.as_bytes()[self.inner_range()]) |
| 51 | } |
| 52 | |
| 53 | /// Like `value` but returns a potentially owned version of the value. |
| 54 | /// |
| 55 | /// The return value is either `Cow<'static, [u8]>` if `B = String`, or |
| 56 | /// `Cow<'a, [u8]>` if `B = &'a str`. |
| 57 | pub fn into_value(self) -> B::ByteCow { |
| 58 | let inner_range = self.inner_range(); |
| 59 | let Self { raw, value, .. } = self; |
| 60 | value.map(B::ByteCow::from).unwrap_or_else(|| raw.cut(inner_range).into_byte_cow()) |
| 61 | } |
| 62 | |
| 63 | /// The optional suffix. Returns `""` if the suffix is empty/does not exist. |
| 64 | pub fn suffix(&self) -> &str { |
| 65 | &(*self.raw)[self.start_suffix..] |
| 66 | } |
| 67 | |
| 68 | /// Returns whether this literal is a raw string literal (starting with |
| 69 | /// `r`). |
| 70 | pub fn is_raw_byte_string(&self) -> bool { |
| 71 | self.num_hashes.is_some() |
| 72 | } |
| 73 | |
| 74 | /// Returns the raw input that was passed to `parse`. |
| 75 | pub fn raw_input(&self) -> &str { |
| 76 | &self.raw |
| 77 | } |
| 78 | |
| 79 | /// Returns the raw input that was passed to `parse`, potentially owned. |
| 80 | pub fn into_raw_input(self) -> B { |
| 81 | self.raw |
| 82 | } |
| 83 | |
| 84 | /// The range within `self.raw` that excludes the quotes and potential `r#`. |
| 85 | fn inner_range(&self) -> Range<usize> { |
| 86 | match self.num_hashes { |
| 87 | None => 2..self.start_suffix - 1, |
| 88 | Some(n) => 2 + n as usize + 1..self.start_suffix - n as usize - 1, |
| 89 | } |
| 90 | } |
| 91 | } |
| 92 | |
| 93 | impl ByteStringLit<&str> { |
| 94 | /// Makes a copy of the underlying buffer and returns the owned version of |
| 95 | /// `Self`. |
| 96 | pub fn into_owned(self) -> ByteStringLit<String> { |
| 97 | ByteStringLit { |
| 98 | raw: self.raw.to_owned(), |
| 99 | value: self.value, |
| 100 | num_hashes: self.num_hashes, |
| 101 | start_suffix: self.start_suffix, |
| 102 | } |
| 103 | } |
| 104 | } |
| 105 | |
| 106 | impl<B: Buffer> fmt::Display for ByteStringLit<B> { |
| 107 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 108 | f.pad(&self.raw) |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | |
| 113 | /// Precondition: input has to start with either `b"` or `br`. |
| 114 | #[inline (never)] |
| 115 | fn parse_impl(input: &str) -> Result<(Option<Vec<u8>>, Option<u32>, usize), ParseError> { |
| 116 | if input.starts_with("br" ) { |
| 117 | scan_raw_string::<u8>(&input, 2) |
| 118 | .map(|(v: Option, num: u32, start_suffix: usize)| (v.map(String::into_bytes), Some(num), start_suffix)) |
| 119 | } else { |
| 120 | unescape_string::<u8>(&input, 2) |
| 121 | .map(|(v: Option, start_suffix: usize)| (v.map(String::into_bytes), None, start_suffix)) |
| 122 | } |
| 123 | } |
| 124 | |
| 125 | #[cfg (test)] |
| 126 | mod tests; |
| 127 | |