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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
use crate::Error;
use crate::SymbolValue;
use crate::TypedValueHandle;
use crate::Value;
use crate::ValueArena;
use crate::ValueHandle;
use crate::MAJOR_VERSION;
use crate::MINOR_VERSION;
use crate::VALUE_KIND_ARRAY;
use crate::VALUE_KIND_FALSE;
use crate::VALUE_KIND_FIXNUM;
use crate::VALUE_KIND_HASH;
use crate::VALUE_KIND_HASH_DEFAULT;
use crate::VALUE_KIND_INSTANCE_VARIABLES;
use crate::VALUE_KIND_NIL;
use crate::VALUE_KIND_OBJECT;
use crate::VALUE_KIND_OBJECT_LINK;
use crate::VALUE_KIND_STRING;
use crate::VALUE_KIND_SYMBOL;
use crate::VALUE_KIND_SYMBOL_LINK;
use crate::VALUE_KIND_TRUE;
use crate::VALUE_KIND_USER_DEFINED;
use indexmap::IndexSet;
use std::io::Write;

/// A dumper for ruby data
pub struct Dumper<'a, W> {
    writer: W,
    arena: &'a ValueArena,

    symbol_links: IndexSet<TypedValueHandle<SymbolValue>>,
    object_links: IndexSet<ValueHandle>,
}

impl<'a, W> Dumper<'a, W> {
    /// Create a new [`Dumper`] from a writer and entry arena.
    fn new(writer: W, arena: &'a ValueArena) -> Self {
        Self {
            writer,
            arena,
            symbol_links: IndexSet::new(),
            object_links: IndexSet::new(),
        }
    }
}

impl<'a, W> Dumper<'a, W>
where
    W: Write,
{
    /// Write the header
    fn write_header(&mut self) -> Result<(), Error> {
        self.writer.write_all(&[MAJOR_VERSION, MINOR_VERSION])?;
        Ok(())
    }

    /// Write a byte
    fn write_byte(&mut self, byte: u8) -> Result<(), Error> {
        self.writer.write_all(std::slice::from_ref(&byte))?;
        Ok(())
    }

    /// Write a byte string.
    ///
    /// This is a fixnum, followed by that many bytes.
    fn write_byte_string(&mut self, value: &[u8]) -> Result<(), Error> {
        let len =
            i32::try_from(value.len()).map_err(|error| Error::USizeInvalidFixnum { error })?;

        self.write_fixnum(len)?;
        self.writer.write_all(value)?;

        Ok(())
    }

    /// Write a Fixnum
    fn write_fixnum(&mut self, mut value: i32) -> Result<(), Error> {
        if value == 0 {
            self.writer.write_all(&[0])?;
            return Ok(());
        }

        if value > 0 && value < 123 {
            let value = u8::try_from(value).unwrap();
            self.writer.write_all(&[value + 5])?;
            return Ok(());
        }

        if value < 0 && value > -124 {
            let value = u8::try_from((value - 5) & 0xFF).unwrap();
            self.writer.write_all(&[value])?;
            return Ok(());
        }

        let mut buffer = [0; std::mem::size_of::<i32>() + 1];
        let mut buffer_size = 0;
        for i in 1..(std::mem::size_of::<i32>() + 1) {
            buffer[i] = u8::try_from(value & 0xFF).unwrap();
            buffer_size = i + 1;

            value >>= 8;
            if value == 0 {
                buffer[0] = u8::try_from(i).unwrap();
                break;
            }
            if value == -1 {
                buffer[0] = (-i8::try_from(i).unwrap()) as u8;
                break;
            }
        }
        self.writer.write_all(&buffer[..buffer_size])?;

        Ok(())
    }

    /// Try to write a value object reference, if possible.
    /// If not successful, this entry is recorded and will be used for future resolutions.
    ///
    /// # Returns
    /// Returns true if successful.
    fn try_write_value_object_link(&mut self, handle: ValueHandle) -> Result<bool, Error> {
        let (index, inserted) = self.object_links.insert_full(handle);
        if !inserted {
            self.write_value_object_link(index)?;
            return Ok(true);
        }

        Ok(false)
    }

    /// Write a value that is either a symbol or a symbol link.
    fn write_value_symbol_like(
        &mut self,
        handle: TypedValueHandle<SymbolValue>,
        value: &SymbolValue,
    ) -> Result<(), Error> {
        match self.symbol_links.get_index_of(&handle) {
            Some(index) => {
                let index =
                    i32::try_from(index).map_err(|error| Error::USizeInvalidFixnum { error })?;

                self.write_byte(VALUE_KIND_SYMBOL_LINK)?;
                self.write_fixnum(index)?;
            }
            None => {
                self.symbol_links.insert(handle);

                self.write_byte(VALUE_KIND_SYMBOL)?;
                self.write_byte_string(value.value())?;
            }
        }

        Ok(())
    }

    /// Write an object link, as a value.
    fn write_value_object_link(&mut self, index: usize) -> Result<(), Error> {
        let index = i32::try_from(index).map_err(|error| Error::USizeInvalidFixnum { error })?;

        self.write_byte(VALUE_KIND_OBJECT_LINK)?;
        self.write_fixnum(index)?;

        Ok(())
    }

    /// Write instance variables
    fn write_instance_variables(
        &mut self,
        instance_variables: &[(TypedValueHandle<SymbolValue>, ValueHandle)],
    ) -> Result<(), Error> {
        let num_vars = i32::try_from(instance_variables.len())
            .map_err(|error| Error::USizeInvalidFixnum { error })?;
        self.write_fixnum(num_vars)?;

        for (name, value) in instance_variables.iter() {
            self.write_value((*name).into())?;
            self.write_value(*value)?;
        }

        Ok(())
    }

    /// Write a value
    fn write_value(&mut self, handle: ValueHandle) -> Result<(), Error> {
        let value = self
            .arena
            .get(handle)
            .ok_or(Error::InvalidValueHandle { handle })?;

        match value {
            Value::Nil(_) => self.write_byte(VALUE_KIND_NIL)?,
            Value::Bool(value) => {
                if value.value() {
                    self.write_byte(VALUE_KIND_TRUE)?
                } else {
                    self.write_byte(VALUE_KIND_FALSE)?
                }
            }
            Value::Fixnum(value) => {
                self.write_byte(VALUE_KIND_FIXNUM)?;
                self.write_fixnum(value.value())?;
            }
            Value::Symbol(value) => {
                let handle = TypedValueHandle::new_unchecked(handle);
                self.write_value_symbol_like(handle, value)?;
            }
            Value::Array(value) => {
                if self.try_write_value_object_link(handle)? {
                    return Ok(());
                }

                let len = i32::try_from(value.len())
                    .map_err(|error| Error::USizeInvalidFixnum { error })?;

                self.write_byte(VALUE_KIND_ARRAY)?;
                self.write_fixnum(len)?;
                for value in value.value().iter() {
                    self.write_value(*value)?;
                }
            }
            Value::Hash(value) => {
                if self.try_write_value_object_link(handle)? {
                    return Ok(());
                }

                let default_value = value.default_value();
                let value = value.value();

                if default_value.is_some() {
                    self.write_byte(VALUE_KIND_HASH_DEFAULT)?;
                } else {
                    self.write_byte(VALUE_KIND_HASH)?;
                }

                let num_vars = i32::try_from(value.len())
                    .map_err(|error| Error::USizeInvalidFixnum { error })?;
                self.write_fixnum(num_vars)?;

                for (key, value) in value.iter() {
                    self.write_value(*key)?;
                    self.write_value(*value)?;
                }

                if let Some(default_value) = default_value {
                    self.write_value(default_value)?;
                }
            }
            Value::Object(value) => {
                if self.try_write_value_object_link(handle)? {
                    return Ok(());
                }

                self.write_byte(VALUE_KIND_OBJECT)?;
                self.write_value(value.name().into())?;
                self.write_instance_variables(value.instance_variables())?;
            }
            Value::String(value) => {
                if self.try_write_value_object_link(handle)? {
                    return Ok(());
                }

                match value.instance_variables() {
                    Some(instance_variables) => {
                        self.write_byte(VALUE_KIND_INSTANCE_VARIABLES)?;

                        self.write_byte(VALUE_KIND_STRING)?;
                        self.write_byte_string(value.value())?;

                        self.write_instance_variables(instance_variables)?;
                    }
                    None => {
                        self.write_byte(VALUE_KIND_STRING)?;
                        self.write_byte_string(value.value())?;
                    }
                }
            }
            Value::UserDefined(value) => {
                if self.try_write_value_object_link(handle)? {
                    return Ok(());
                }

                match value.instance_variables() {
                    Some(instance_variables) => {
                        self.write_byte(VALUE_KIND_INSTANCE_VARIABLES)?;

                        self.write_byte(VALUE_KIND_USER_DEFINED)?;
                        self.write_value(value.name().into())?;
                        self.write_byte_string(value.value())?;

                        self.write_instance_variables(instance_variables)?;
                    }
                    None => {
                        self.write_byte(VALUE_KIND_USER_DEFINED)?;
                        self.write_value(value.name().into())?;
                        self.write_byte_string(value.value())?;
                    }
                }
            }
        }

        Ok(())
    }

    /// Dump the root node to the writer.
    fn dump(&mut self) -> Result<(), Error> {
        self.write_header()?;
        self.write_value(self.arena.root())?;

        Ok(())
    }
}

/// Dump to a writer.
pub fn dump<W>(writer: W, value_arena: &ValueArena) -> Result<(), Error>
where
    W: Write,
{
    let mut dumper = Dumper::new(writer, value_arena);
    dumper.dump()?;
    Ok(())
}