Skip to main content

cynic_parser/common/
string_literal.rs

1use std::{borrow::Cow, fmt};
2
3use crate::common::trim_block_string_whitespace;
4
5#[derive(Clone, Copy, Debug)]
6pub struct StringLiteral<'a>(StringLiteralInner<'a>);
7
8impl<'a> StringLiteral<'a> {
9    pub(crate) fn new_string(inner: &'a str) -> Self {
10        Self(StringLiteralInner::String(inner))
11    }
12
13    pub(crate) fn new_block(inner: &'a str) -> Self {
14        Self(StringLiteralInner::BlockString(inner))
15    }
16}
17
18#[derive(Clone, Copy, Debug)]
19enum StringLiteralInner<'a> {
20    String(&'a str),
21    BlockString(&'a str),
22}
23
24#[derive(Clone, Copy, Debug)]
25pub enum StringLiteralKind {
26    String,
27    Block,
28}
29
30impl<'a> StringLiteral<'a> {
31    pub fn to_cow(&self) -> Cow<'a, str> {
32        match self.0 {
33            StringLiteralInner::String(string) => Cow::Borrowed(string),
34            StringLiteralInner::BlockString(string) => {
35                // This is more intense - we need to unquote the string
36                //
37                // TODO: Look into recording what work needs done at parse time
38                Cow::Owned(trim_block_string_whitespace(string))
39            }
40        }
41    }
42
43    pub fn raw_untrimmed_str(&self) -> &'a str {
44        match self.0 {
45            StringLiteralInner::String(string) => string,
46            StringLiteralInner::BlockString(string) => string,
47        }
48    }
49
50    pub fn kind(&self) -> StringLiteralKind {
51        match self.0 {
52            StringLiteralInner::String(_) => StringLiteralKind::String,
53            StringLiteralInner::BlockString(_) => StringLiteralKind::Block,
54        }
55    }
56}
57
58impl fmt::Display for StringLiteral<'_> {
59    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60        f.write_str(self.to_cow().as_ref())
61    }
62}