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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
use crate::{FileSystem, SourceMap, SourceMapBuilder, SpanWithSource};

/// A trait for defining behavior of adding content to a buffer. As well as register markers for source maps
pub trait ToString {
    /// Append character
    fn push(&mut self, chr: char);

    /// Append a new line character
    fn push_new_line(&mut self);

    /// Use [ToString::push_str_contains_new_line] if `string` could contain new lines
    fn push_str(&mut self, string: &str);

    /// Used to push strings that may contain new lines
    fn push_str_contains_new_line(&mut self, string: &str);

    /// Adds a mapping of the from a original position in the source to the position in the current buffer
    fn add_mapping(&mut self, source_span: &SpanWithSource);

    /// Some implementors might not ToString the whole input. This signals for users to end early as further usage
    /// of this trait has no effect
    fn halt(&self) -> bool {
        false
    }
}

// TODO clarify calls
impl ToString for String {
    fn push(&mut self, chr: char) {
        self.push(chr);
    }

    fn push_new_line(&mut self) {
        self.push('\n');
    }

    fn push_str(&mut self, string: &str) {
        self.push_str(string)
    }

    fn push_str_contains_new_line(&mut self, string: &str) {
        self.push_str(string)
    }

    fn add_mapping(&mut self, _source_span: &SpanWithSource) {}
}

/// Building a source along with its source map
#[derive(Default)]
pub struct StringWithSourceMap(String, SourceMapBuilder);

impl StringWithSourceMap {
    pub fn new() -> Self {
        Self::default()
    }

    /// Returns source and the source map
    pub fn build(self, filesystem: &impl FileSystem) -> (String, SourceMap) {
        (self.0, self.1.build(filesystem))
    }

    #[cfg(feature = "inline-source-map")]
    /// Build the output and append the source map in base 64
    pub fn build_with_inline_source_map(self, filesystem: &impl FileSystem) -> String {
        use base64::Engine;

        let Self(mut source, source_map) = self;
        let built_source_map = source_map.build(filesystem);
        // Inline URL:
        source.push_str("\n//# sourceMappingURL=data:application/json;base64,");
        source.push_str(
            &base64::prelude::BASE64_STANDARD.encode(built_source_map.to_json(filesystem)),
        );
        source
    }
}

// TODO use ToString for self.0
impl ToString for StringWithSourceMap {
    fn push(&mut self, chr: char) {
        self.1.add_to_column(chr.len_utf16());
        self.0.push(chr);
    }

    fn push_new_line(&mut self) {
        self.1.add_new_line();
        self.0.push('\n');
    }

    fn push_str(&mut self, slice: &str) {
        self.1.add_to_column(slice.chars().count());
        self.0.push_str(slice);
    }

    fn push_str_contains_new_line(&mut self, slice: &str) {
        for chr in slice.chars() {
            if chr == '\n' {
                self.1.add_new_line()
            }
        }
        self.0.push_str(slice);
    }

    fn add_mapping(&mut self, source_span: &SpanWithSource) {
        self.1.add_mapping(source_span);
    }
}

/// Used for getting **byte count** of the result when built into string without building the string
#[derive(Default)]
pub struct Counter(usize);

impl Counter {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn get_count(self) -> usize {
        self.0
    }
}

impl ToString for Counter {
    fn push(&mut self, chr: char) {
        self.0 += chr.len_utf8();
    }

    fn push_new_line(&mut self) {
        self.push('\n');
    }

    fn push_str(&mut self, string: &str) {
        self.0 += string.chars().count();
    }

    fn push_str_contains_new_line(&mut self, string: &str) {
        self.0 += string.chars().count();
    }

    fn add_mapping(&mut self, _source_span: &SpanWithSource) {}
}

/// Counts text until a limit. Used for telling whether the text is greater than some threshold
pub struct MaxCounter {
    acc: usize,
    max: usize,
}

impl MaxCounter {
    pub fn new(max: usize) -> Self {
        Self { acc: 0, max }
    }

    /// TODO temp to see overshoot
    pub fn get_acc(&self) -> usize {
        self.acc
    }
}

impl ToString for MaxCounter {
    fn push(&mut self, chr: char) {
        self.acc += chr.len_utf8();
    }

    fn push_new_line(&mut self) {
        self.push('\n');
    }

    fn push_str(&mut self, string: &str) {
        self.acc += string.len();
    }

    fn push_str_contains_new_line(&mut self, string: &str) {
        self.acc += string.len();
    }

    fn add_mapping(&mut self, _source_span: &SpanWithSource) {}

    fn halt(&self) -> bool {
        self.acc > self.max
    }
}

#[cfg(test)]
mod to_string_tests {
    use super::*;

    fn serializer<T: ToString>(t: &mut T) {
        t.push_str("Hello");
        t.push(' ');
        t.push_str("World");
    }

    #[test]
    fn string_concatenation() {
        let mut s = String::new();
        serializer(&mut s);
        assert_eq!(&s, "Hello World");
    }

    #[test]
    fn counting() {
        let mut s = Counter::new();
        serializer(&mut s);
        assert_eq!(s.get_count(), "Hello World".chars().count());
    }

    #[test]
    fn max_counter() {
        let mut s = MaxCounter::new(14);
        serializer(&mut s);
        assert!(!s.halt());
        serializer(&mut s);
        assert!(s.halt());
    }
}