litrs/string/
mod.rs

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