1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
use crate::ast;
use crate::{
Parse, ParseError, Parser, Resolve, ResolveError, ResolveErrorKind, ResolveOwned, Spanned,
Storage, ToTokens,
};
use runestick::{Source, Span};
use std::borrow::Cow;
#[derive(Debug, Clone, PartialEq, Eq, ToTokens, Spanned)]
pub struct LitByteStr {
pub token: ast::Token,
#[rune(skip)]
pub source: ast::StrSource,
}
impl LitByteStr {
fn parse_escaped(&self, span: Span, source: &str) -> Result<Vec<u8>, ResolveError> {
let mut buffer = Vec::with_capacity(source.len());
let start = span.start.into_usize();
let mut it = source
.char_indices()
.map(|(n, c)| (start + n, c))
.peekable();
while let Some((start, c)) = it.next() {
buffer.extend(match c {
'\\' => {
match ast::utils::parse_byte_escape(&mut it, ast::utils::WithLineCont(true)) {
Ok(c) => c,
Err(kind) => {
let end = it
.next()
.map(|n| n.0)
.unwrap_or_else(|| span.end.into_usize());
return Err(ResolveError::new(Span::new(start, end), kind));
}
}
}
c => Some(c as u8),
});
}
Ok(buffer)
}
}
impl Parse for LitByteStr {
fn parse(parser: &mut Parser<'_>) -> Result<Self, ParseError> {
let token = parser.next()?;
match token.kind {
K![bytestr(source)] => Ok(Self { token, source }),
_ => Err(ParseError::expected(&token, "literal byte string")),
}
}
}
impl<'a> Resolve<'a> for LitByteStr {
type Output = Cow<'a, [u8]>;
fn resolve(
&self,
storage: &Storage,
source: &'a Source,
) -> Result<Cow<'a, [u8]>, ResolveError> {
let span = self.token.span();
let text = match self.source {
ast::StrSource::Text(text) => text,
ast::StrSource::Synthetic(id) => {
let bytes = storage.get_byte_string(id).ok_or_else(|| {
ResolveError::new(
span,
ResolveErrorKind::BadSyntheticId {
kind: "byte string",
id,
},
)
})?;
return Ok(Cow::Owned(bytes));
}
};
let span = span.trim_start(2).trim_end(1);
let string = source
.source(span)
.ok_or_else(|| ResolveError::new(span, ResolveErrorKind::BadSlice))?;
Ok(if text.escaped {
Cow::Owned(self.parse_escaped(span, string)?)
} else {
Cow::Borrowed(string.as_bytes())
})
}
}
impl ResolveOwned for LitByteStr {
type Owned = Vec<u8>;
fn resolve_owned(
&self,
storage: &Storage,
source: &Source,
) -> Result<Self::Owned, ResolveError> {
Ok(self.resolve(storage, source)?.into_owned())
}
}