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>,
27}
2829impl<B: Buffer> ByteStringLit<B> {
30/// Parses the input as a (raw) byte string literal. Returns an error if the
31 /// input is invalid or represents a different kind of literal.
32pub fn parse(input: B) -> Result<Self, ParseError> {
33if input.is_empty() {
34return Err(perr(None, Empty));
35 }
36if !input.starts_with(r#"b""#) && !input.starts_with("br") {
37return Err(perr(None, InvalidByteStringLiteralStart));
38 }
3940Self::parse_impl(input)
41 }
4243/// Returns the string value this literal represents (where all escapes have
44 /// been turned into their respective values).
45pub fn value(&self) -> &[u8] {
46self.value.as_deref().unwrap_or(&self.raw.as_bytes()[self.inner_range()])
47 }
4849/// Like `value` but returns a potentially owned version of the value.
50 ///
51 /// The return value is either `Cow<'static, [u8]>` if `B = String`, or
52 /// `Cow<'a, [u8]>` if `B = &'a str`.
53pub fn into_value(self) -> B::ByteCow {
54let inner_range = self.inner_range();
55let Self { raw, value, .. } = self;
56 value.map(B::ByteCow::from).unwrap_or_else(|| raw.cut(inner_range).into_byte_cow())
57 }
5859/// Returns whether this literal is a raw string literal (starting with
60 /// `r`).
61pub fn is_raw_byte_string(&self) -> bool {
62self.num_hashes.is_some()
63 }
6465/// The range within `self.raw` that excludes the quotes and potential `r#`.
66fn inner_range(&self) -> Range<usize> {
67match self.num_hashes {
68None => 2..self.raw.len() - 1,
69Some(n) => 2 + n as usize + 1..self.raw.len() - n as usize - 1,
70 }
71 }
7273/// Precondition: input has to start with either `b"` or `br`.
74pub(crate) fn parse_impl(input: B) -> Result<Self, ParseError> {
75if input.starts_with(r"br") {
76let (value, num_hashes) = scan_raw_string::<u8>(&input, 2)?;
77Ok(Self {
78 raw: input,
79 value: value.map(|s| s.into_bytes()),
80 num_hashes: Some(num_hashes),
81 })
82 } else {
83let value = unescape_string::<u8>(&input, 2)?.map(|s| s.into_bytes());
84Ok(Self {
85 raw: input,
86 value,
87 num_hashes: None,
88 })
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 }
102 }
103}
104105impl<B: Buffer> fmt::Display for ByteStringLit<B> {
106fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
107 f.pad(&self.raw)
108 }
109}
110111112#[cfg(test)]
113mod tests;