litrs/string/
mod.rs

1use std::{fmt, ops::Range};
2
3use crate::{
4    Buffer, ParseError,
5    err::{perr, ParseErrorKind::*},
6    escape::{scan_raw_string, unescape_string},
7    parse::first_byte_or_empty,
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 escaped unescaped), or `None` if there were
22    /// no escapes. In the latter case, `input` is the string value.
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<u32>,
28}
29
30impl<B: Buffer> StringLit<B> {
31    /// Parses the input as a (raw) string literal. Returns an error if the
32    /// input is invalid or represents a different kind of literal.
33    pub fn parse(input: B) -> Result<Self, ParseError> {
34        match first_byte_or_empty(&input)? {
35            b'r' | b'"' => Self::parse_impl(input),
36            _ => Err(perr(0, InvalidStringLiteralStart)),
37        }
38    }
39
40    /// Returns the string value this literal represents (where all escapes have
41    /// been turned into their respective values).
42    pub fn value(&self) -> &str {
43        self.value.as_deref().unwrap_or(&self.raw[self.inner_range()])
44    }
45
46    /// Like `value` but returns a potentially owned version of the value.
47    ///
48    /// The return value is either `Cow<'static, str>` if `B = String`, or
49    /// `Cow<'a, str>` if `B = &'a str`.
50    pub fn into_value(self) -> B::Cow {
51        let inner_range = self.inner_range();
52        let Self { raw, value, .. } = self;
53        value.map(B::Cow::from).unwrap_or_else(|| raw.cut(inner_range).into_cow())
54    }
55
56    /// Returns whether this literal is a raw string literal (starting with
57    /// `r`).
58    pub fn is_raw_string(&self) -> bool {
59        self.num_hashes.is_some()
60    }
61
62    /// The range within `self.raw` that excludes the quotes and potential `r#`.
63    fn inner_range(&self) -> Range<usize> {
64        match self.num_hashes {
65            None => 1..self.raw.len() - 1,
66            Some(n) => 1 + n as usize + 1..self.raw.len() - n as usize - 1,
67        }
68    }
69
70    /// Precondition: input has to start with either `"` or `r`.
71    pub(crate) fn parse_impl(input: B) -> Result<Self, ParseError> {
72        if input.starts_with('r') {
73            let (value, num_hashes) = scan_raw_string::<char>(&input, 1)?;
74            Ok(Self {
75                raw: input,
76                value,
77                num_hashes: Some(num_hashes),
78            })
79        } else {
80            let value = unescape_string::<char>(&input, 1)?;
81            Ok(Self {
82                raw: input,
83                value,
84                num_hashes: None,
85            })
86        }
87    }
88}
89
90impl StringLit<&str> {
91    /// Makes a copy of the underlying buffer and returns the owned version of
92    /// `Self`.
93    pub fn into_owned(self) -> StringLit<String> {
94        StringLit {
95            raw: self.raw.to_owned(),
96            value: self.value,
97            num_hashes: self.num_hashes,
98        }
99    }
100}
101
102impl<B: Buffer> fmt::Display for StringLit<B> {
103    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
104        f.pad(&self.raw)
105    }
106}
107
108
109#[cfg(test)]
110mod tests;