1use std::{fmt, ops::Range};
23use crate::{
4 Buffer, ParseError,
5 err::{perr, ParseErrorKind::*},
6 escape::{scan_raw_string, unescape_string},
7};
8910/// 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)]
16pub struct ByteStringLit<B: Buffer> {
17/// The raw input.
18raw: B,
1920/// The string value (with all escaped unescaped), or `None` if there were
21 /// no escapes. In the latter case, `input` is the string value.
22value: Option<Vec<u8>>,
2324/// The number of hash signs in case of a raw string literal, or `None` if
25 /// it's not a raw string literal.
26num_hashes: Option<u32>,
2728/// Start index of the suffix or `raw.len()` if there is no suffix.
29start_suffix: usize,
30}
3132impl<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.
35pub fn parse(input: B) -> Result<Self, ParseError> {
36if input.is_empty() {
37return Err(perr(None, Empty));
38 }
39if !input.starts_with(r#"b""#) && !input.starts_with("br") {
40return Err(perr(None, InvalidByteStringLiteralStart));
41 }
4243let (value, num_hashes, start_suffix) = parse_impl(&input)?;
44Ok(Self { raw: input, value, num_hashes, start_suffix })
45 }
4647/// Returns the string value this literal represents (where all escapes have
48 /// been turned into their respective values).
49pub fn value(&self) -> &[u8] {
50self.value.as_deref().unwrap_or(&self.raw.as_bytes()[self.inner_range()])
51 }
5253/// 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`.
57pub fn into_value(self) -> B::ByteCow {
58let inner_range = self.inner_range();
59let Self { raw, value, .. } = self;
60 value.map(B::ByteCow::from).unwrap_or_else(|| raw.cut(inner_range).into_byte_cow())
61 }
6263/// The optional suffix. Returns `""` if the suffix is empty/does not exist.
64pub fn suffix(&self) -> &str {
65&(*self.raw)[self.start_suffix..]
66 }
6768/// Returns whether this literal is a raw string literal (starting with
69 /// `r`).
70pub fn is_raw_byte_string(&self) -> bool {
71self.num_hashes.is_some()
72 }
7374/// Returns the raw input that was passed to `parse`.
75pub fn raw_input(&self) -> &str {
76&self.raw
77 }
7879/// Returns the raw input that was passed to `parse`, potentially owned.
80pub fn into_raw_input(self) -> B {
81self.raw
82 }
8384/// The range within `self.raw` that excludes the quotes and potential `r#`.
85fn inner_range(&self) -> Range<usize> {
86match self.num_hashes {
87None => 2..self.start_suffix - 1,
88Some(n) => 2 + n as usize + 1..self.start_suffix - n as usize - 1,
89 }
90 }
91}
9293impl ByteStringLit<&str> {
94/// Makes a copy of the underlying buffer and returns the owned version of
95 /// `Self`.
96pub 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}
105106impl<B: Buffer> fmt::Display for ByteStringLit<B> {
107fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
108 f.pad(&self.raw)
109 }
110}
111112113/// Precondition: input has to start with either `b"` or `br`.
114#[inline(never)]
115fn parse_impl(input: &str) -> Result<(Option<Vec<u8>>, Option<u32>, usize), ParseError> {
116if input.starts_with("br") {
117 scan_raw_string::<u8>(&input, 2)
118 .map(|(v, num, start_suffix)| (v.map(String::into_bytes), Some(num), start_suffix))
119 } else {
120 unescape_string::<u8>(&input, 2)
121 .map(|(v, start_suffix)| (v.map(String::into_bytes), None, start_suffix))
122 }
123}
124125#[cfg(test)]
126mod tests;