1use std::{fmt, ops::Range};
23use crate::{
4 Buffer, ParseError,
5 err::{perr, ParseErrorKind::*},
6 escape::{scan_raw_string, unescape_string},
7 parse::first_byte_or_empty,
8};
91011/// 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.
19raw: B,
2021/// The string value (with all escaped unescaped), or `None` if there were
22 /// no escapes. In the latter case, `input` is the string value.
23value: Option<String>,
2425/// The number of hash signs in case of a raw string literal, or `None` if
26 /// it's not a raw string literal.
27num_hashes: Option<u32>,
28}
2930impl<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.
33pub fn parse(input: B) -> Result<Self, ParseError> {
34match first_byte_or_empty(&input)? {
35b'r' | b'"' => Self::parse_impl(input),
36_ => Err(perr(0, InvalidStringLiteralStart)),
37 }
38 }
3940/// Returns the string value this literal represents (where all escapes have
41 /// been turned into their respective values).
42pub fn value(&self) -> &str {
43self.value.as_deref().unwrap_or(&self.raw[self.inner_range()])
44 }
4546/// 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`.
50pub fn into_value(self) -> B::Cow {
51let inner_range = self.inner_range();
52let Self { raw, value, .. } = self;
53 value.map(B::Cow::from).unwrap_or_else(|| raw.cut(inner_range).into_cow())
54 }
5556/// Returns whether this literal is a raw string literal (starting with
57 /// `r`).
58pub fn is_raw_string(&self) -> bool {
59self.num_hashes.is_some()
60 }
6162/// The range within `self.raw` that excludes the quotes and potential `r#`.
63fn inner_range(&self) -> Range<usize> {
64match self.num_hashes {
65None => 1..self.raw.len() - 1,
66Some(n) => 1 + n as usize + 1..self.raw.len() - n as usize - 1,
67 }
68 }
6970/// Precondition: input has to start with either `"` or `r`.
71pub(crate) fn parse_impl(input: B) -> Result<Self, ParseError> {
72if input.starts_with('r') {
73let (value, num_hashes) = scan_raw_string::<char>(&input, 1)?;
74Ok(Self {
75 raw: input,
76 value,
77 num_hashes: Some(num_hashes),
78 })
79 } else {
80let value = unescape_string::<char>(&input, 1)?;
81Ok(Self {
82 raw: input,
83 value,
84 num_hashes: None,
85 })
86 }
87 }
88}
8990impl StringLit<&str> {
91/// Makes a copy of the underlying buffer and returns the owned version of
92 /// `Self`.
93pub 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}
101102impl<B: Buffer> fmt::Display for StringLit<B> {
103fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
104 f.pad(&self.raw)
105 }
106}
107108109#[cfg(test)]
110mod tests;