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#[derive(Debug, Clone, PartialEq, Eq)]
17pub struct StringLit<B: Buffer> {
18 raw: B,
20
21 value: Option<String>,
24
25 num_hashes: Option<u8>,
28
29 start_suffix: usize,
31}
32
33impl<B: Buffer> StringLit<B> {
34 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 pub fn value(&self) -> &str {
49 self.value
50 .as_deref()
51 .unwrap_or(&self.raw[self.inner_range()])
52 }
53
54 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 pub fn suffix(&self) -> &str {
68 &(*self.raw)[self.start_suffix..]
69 }
70
71 pub fn is_raw_string(&self) -> bool {
74 self.num_hashes.is_some()
75 }
76
77 pub fn raw_input(&self) -> &str {
79 &self.raw
80 }
81
82 pub fn into_raw_input(self) -> B {
84 self.raw
85 }
86
87 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 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#[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;