Documentation
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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
use std::io::{self, Read, Write};
use std::str::FromStr;
pub mod prelude;

#[derive(Debug, Eq, PartialEq)]
pub struct Tag(u16);

pub trait Serialize {
    /// Serializes the value to the stream.
    ///
    /// # Errors
    ///
    /// Returns an error if writing to the stream fails.
    fn serialize<W: Write>(&self, stream: &mut W) -> io::Result<()>;
}

pub trait Deserialize: Sized {
    /// Deserializes a value from the stream.
    ///
    /// # Errors
    ///
    /// Returns an error if reading from the stream fails or if the data is invalid.
    fn deserialize<R: Read>(stream: &mut R) -> io::Result<Self>;
}

fn read_u8<R: Read>(stream: &mut R) -> io::Result<u8> {
    let mut buf = [0u8; 1];
    stream.read_exact(&mut buf)?;
    Ok(buf[0])
}

fn read_u16_be<R: Read>(stream: &mut R) -> io::Result<u16> {
    let mut buf = [0u8; 2];
    stream.read_exact(&mut buf)?;
    Ok(u16::from_be_bytes(buf))
}

fn read_u32_be<R: Read>(stream: &mut R) -> io::Result<u32> {
    let mut buf = [0u8; 4];
    stream.read_exact(&mut buf)?;
    Ok(u32::from_be_bytes(buf))
}

#[allow(unused)]
fn read_u64_be<R: Read>(stream: &mut R) -> io::Result<u64> {
    let mut buf = [0u8; 8];
    stream.read_exact(&mut buf)?;
    Ok(u64::from_be_bytes(buf))
}

#[must_use]
pub const fn is_valid_tag_char(c: u8) -> bool {
    c.is_ascii_lowercase() || c.is_ascii_uppercase() || c.is_ascii_digit() || c == b'_'
}

impl Tag {
    /// Creates a Tag from a 2-character string.
    ///
    /// # Errors
    ///
    /// Returns an error if the string is not exactly 2 characters or contains invalid characters.
    pub fn with_str(s: &str) -> io::Result<Self> {
        if s.len() != 2 {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "Tag must be exactly 2 characters long.",
            ));
        }

        let bytes = s.as_bytes();

        if !is_valid_tag_char(bytes[0]) || !is_valid_tag_char(bytes[1]) {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "Invalid characters in tag.",
            ));
        }

        Ok(Self(u16::from_be_bytes([bytes[0], bytes[1]])))
    }

    /// Creates a Tag from a u16 value.
    ///
    /// # Errors
    ///
    /// Returns an error if the bytes represent invalid tag characters.
    pub fn new(v: u16) -> io::Result<Self> {
        let [first, second] = v.to_be_bytes();

        if !is_valid_tag_char(first) || !is_valid_tag_char(second) {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "Invalid characters in tag.",
            ));
        }
        Ok(Self(v))
    }

    #[must_use]
    pub const fn inner(&self) -> u16 {
        self.0
    }
}

impl FromStr for Tag {
    type Err = io::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::with_str(s)
    }
}

impl TryFrom<&str> for Tag {
    type Error = io::Error;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Self::with_str(value)
    }
}

#[derive(Debug, Eq, PartialEq)]
pub struct TagHeader {
    pub name: Tag,
}

impl TagHeader {
    #[must_use]
    pub const fn new(name: Tag) -> Self {
        Self { name }
    }
}

impl Serialize for TagHeader {
    fn serialize<W: Write>(&self, stream: &mut W) -> io::Result<()> {
        stream.write_all(&self.name.0.to_be_bytes())
    }
}

impl Deserialize for TagHeader {
    fn deserialize<R: Read>(stream: &mut R) -> io::Result<Self> {
        Ok(Self {
            name: Tag::new(read_u16_be(stream)?)?,
        })
    }
}

// Function to decode the size from a compact format
fn decode_size<R: Read>(stream: &mut R) -> io::Result<u32> {
    let mut size = 0u32;
    let mut shift = 0;

    loop {
        let octet = read_u8(stream)?;

        size |= u32::from(octet & 0x7F) << shift;
        shift += 7;

        if shift > 28 {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "Size exceeds u32 maximum value",
            ));
        }

        if octet & 0x80 == 0 {
            break;
        }
    }

    Ok(size)
}

// Function to encode the size in a compact format
fn encode_size(size: u32) -> Vec<u8> {
    let mut encoded = Vec::new();
    let mut current = size;

    loop {
        let octet = (current & 0x7F) as u8;
        current >>= 7;

        if current > 0 {
            encoded.push(octet | 0x80);
        } else {
            encoded.push(octet);
            break;
        }
    }

    encoded
}

#[derive(Debug, Eq, PartialEq)]
pub struct ChunkHeader {
    pub tag: TagHeader,
    pub size: u32,
}

impl ChunkHeader {
    #[must_use]
    pub const fn new(tag: Tag, size: u32) -> Self {
        Self {
            tag: TagHeader::new(tag),
            size,
        }
    }
}

impl Serialize for ChunkHeader {
    fn serialize<W: Write>(&self, stream: &mut W) -> io::Result<()> {
        self.tag.serialize(stream)?;
        stream.write_all(encode_size(self.size).as_slice())
    }
}

impl Deserialize for ChunkHeader {
    fn deserialize<R: Read>(stream: &mut R) -> io::Result<Self> {
        Ok(Self {
            tag: TagHeader::deserialize(stream)?,
            size: decode_size(stream)?,
        })
    }
}

#[derive(Debug, Eq, PartialEq, Default)]
pub struct RaffHeader {
    pub major: u8,
    pub minor: u8,
}

pub const RAFF_TEXT: u32 = 0x5241_4646;
pub const RAFF_ICON: u32 = 0xF09F_A68A;
pub const RAFF_MAJOR: u8 = 0x00;
pub const RAFF_MINOR: u8 = 0x02;

#[derive(Debug, Eq, PartialEq, Clone)]
pub struct RaffApplicationHeader {
    pub identifier: [u8; 16],
    pub app_major: u8,
    pub app_minor: u8,
}

impl RaffApplicationHeader {
    #[must_use]
    pub const fn new(identifier: [u8; 16], app_major: u8, app_minor: u8) -> Self {
        Self {
            identifier,
            app_major,
            app_minor,
        }
    }

    /// Create an application header from a UTF-8 string (up to 16 bytes, zero-padded)
    /// Example: `with_str("Game.SaveFile`", 1, 0) for "Game.SaveFile v1.0"
    /// Supports UTF-8, so you can use "Game🎮.Save"
    ///
    /// # Errors
    ///
    /// Returns an error if the identifier exceeds 16 bytes when UTF-8 encoded.
    pub fn with_str(id: &str, app_major: u8, app_minor: u8) -> io::Result<Self> {
        let id_bytes = id.as_bytes();

        if id_bytes.len() > 16 {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "Identifier must be at most 16 bytes when UTF-8 encoded.",
            ));
        }

        let mut identifier = [0u8; 16];
        identifier[..id_bytes.len()].copy_from_slice(id_bytes);

        Ok(Self::new(identifier, app_major, app_minor))
    }

    /// Get the identifier as a string (trimming trailing zeros)
    #[must_use]
    pub fn as_string(&self) -> String {
        let end = self.identifier.iter().position(|&b| b == 0).unwrap_or(16);
        String::from_utf8_lossy(&self.identifier[..end]).to_string()
    }
}

impl RaffHeader {
    #[must_use]
    pub const fn new() -> Self {
        Self {
            major: RAFF_MAJOR,
            minor: RAFF_MINOR,
        }
    }

    #[must_use]
    pub const fn with_version(major: u8, minor: u8) -> Self {
        Self { major, minor }
    }
}

#[must_use]
pub fn to_version(data: u8) -> u8 {
    if !(48..=57).contains(&data) {
        return 0;
    }
    data - 48
}

#[must_use]
pub const fn from_version(data: u8) -> u8 {
    if data > 9 {
        return 0;
    }
    data + 48
}

impl Deserialize for RaffHeader {
    fn deserialize<R: Read>(stream: &mut R) -> io::Result<Self> {
        let icon = read_u32_be(stream)?;
        if icon != RAFF_ICON {
            // fox
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "Invalid icon",
            ));
        }

        let raff_text = read_u32_be(stream)?;
        if raff_text != RAFF_TEXT {
            // "RAFF"
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "Invalid RAFF text",
            ));
        }

        let mut version_buf = [0u8; 4]; // e.g. "0.1\n"
        stream.read_exact(&mut version_buf)?;

        if version_buf[1] != b'.' || version_buf[3] != b'\n' {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "Invalid version",
            ));
        }

        let sub_char = read_u8(stream)?;
        if sub_char != 0x1A {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "Missing SUB character",
            ));
        }

        Ok(Self {
            major: to_version(version_buf[0]),
            minor: to_version(version_buf[2]),
        })
    }
}

impl Serialize for RaffHeader {
    fn serialize<W: Write>(&self, stream: &mut W) -> io::Result<()> {
        stream.write_all(&RAFF_ICON.to_be_bytes())?;
        stream.write_all(&RAFF_TEXT.to_be_bytes())?;
        stream.write_all(&[from_version(self.major)])?;
        stream.write_all(b".")?;
        stream.write_all(&[from_version(self.minor)])?;
        stream.write_all(&[0x0A])?;
        stream.write_all(&[0x1A])?; // SUBSTITUTE character to stop cat from displaying binary content (https://en.wikipedia.org/wiki/Substitute_character)
        Ok(())
    }
}

impl Serialize for RaffApplicationHeader {
    fn serialize<W: Write>(&self, stream: &mut W) -> io::Result<()> {
        stream.write_all(&self.identifier)?;
        stream.write_all(&[self.app_major])?;
        stream.write_all(&[self.app_minor])?;
        Ok(())
    }
}

impl Deserialize for RaffApplicationHeader {
    fn deserialize<R: Read>(stream: &mut R) -> io::Result<Self> {
        let mut identifier = [0u8; 16];
        stream.read_exact(&mut identifier)?;
        let app_major = read_u8(stream)?;
        let app_minor = read_u8(stream)?;
        Ok(Self::new(identifier, app_major, app_minor))
    }
}

/// Writes a chunk to the stream.
///
/// # Errors
///
/// Returns an error if writing to the stream fails or if the data length exceeds `u32::MAX`.
pub fn write_chunk<W: Write>(stream: &mut W, tag: Tag, data: &[u8]) -> io::Result<()> {
    let size = u32::try_from(data.len())
        .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "Data length exceeds u32::MAX"))?;
    let header = ChunkHeader::new(tag, size);
    header.serialize(stream)?;
    stream.write_all(data)
}

/// Reads the RAFF header and application header from the stream.
///
/// # Errors
///
/// Returns an error if the stream cannot be read, if the RAFF format is invalid,
/// or if the version is not supported.
pub fn read_raff_header<R: Read>(
    stream: &mut R,
) -> io::Result<(RaffHeader, RaffApplicationHeader)> {
    let header = RaffHeader::deserialize(stream)?;
    if header.major != RAFF_MAJOR || header.minor != RAFF_MINOR {
        return Err(std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            "Invalid RAFF header",
        ));
    }
    let app_header = RaffApplicationHeader::deserialize(stream)?;
    Ok((header, app_header))
}

/// Writes the RAFF header and application header to the stream.
///
/// # Errors
///
/// Returns an error if writing to the stream fails.
pub fn write_raff_header<W: Write>(
    stream: &mut W,
    app_header: &RaffApplicationHeader,
) -> io::Result<()> {
    let header = RaffHeader::new();
    header.serialize(stream)?;
    app_header.serialize(stream)
}

/// Writes the RAFF header with an application identifier string.
///
/// # Errors
///
/// Returns an error if the identifier is invalid or if writing to the stream fails.
pub fn write_raff_header_with_app<W: Write>(
    stream: &mut W,
    identifier: &str,
    major: u8,
    minor: u8,
) -> io::Result<()> {
    let app_header = RaffApplicationHeader::with_str(identifier, major, minor)?;
    write_raff_header(stream, &app_header)
}

/// Reads a chunk header from the stream.
///
/// # Errors
///
/// Returns an error if the stream cannot be read or if the chunk format is invalid.
pub fn read_chunk_header<R: Read>(stream: &mut R) -> io::Result<ChunkHeader> {
    ChunkHeader::deserialize(stream)
}

/// Writes an application header to the stream.
///
/// # Errors
///
/// Returns an error if writing to the stream fails.
pub fn write_app_header<W: Write>(
    stream: &mut W,
    app_header: &RaffApplicationHeader,
) -> io::Result<()> {
    app_header.serialize(stream)
}

/// Reads an application header from the stream.
///
/// # Errors
///
/// Returns an error if the stream cannot be read or if the format is invalid.
pub fn read_app_header<R: Read>(stream: &mut R) -> io::Result<RaffApplicationHeader> {
    RaffApplicationHeader::deserialize(stream)
}