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
//! # Parsing functions

use std::convert::TryInto;

use crate::{
    common::{parser::parse_crc_node, FileMeta, FileMetaPair},
    md5::MD5Sum,
};

use super::file::*;
use nom::{
    bytes::complete::{tag, take},
    combinator::{map, map_res},
    multi::length_count,
    number::complete::le_u32,
    sequence::tuple,
    IResult,
};

/// Parse the magic bytes
pub fn parse_pk_magic(input: &[u8]) -> IResult<&[u8], ()> {
    let (rest, _) = tag("ndpk")(input)?;
    Ok((rest, ()))
}

/// Parse the trailer
pub fn parse_pk_trailer(input: &[u8]) -> IResult<&[u8], PKTrailer> {
    map(tuple((le_u32, le_u32)), |(a, b)| PKTrailer {
        file_list_base_addr: a,
        num_compressed: b,
    })(input)
}

fn parse_hash(i: &[u8]) -> IResult<&[u8], MD5Sum> {
    map_res(take(32usize), MD5Sum::from_hex_bytes)(i)
}

fn parse_compressed(i: &[u8]) -> IResult<&[u8], u32> {
    let (i, byte_slice) = take(4usize)(i)?;
    // This cannot fail
    let bytes: [u8; 4] = byte_slice.try_into().unwrap();
    Ok((i, u32::from_le_bytes(bytes)))
}

fn parse_file_meta(input: &[u8]) -> IResult<&[u8], FileMeta> {
    let (input, size) = le_u32(input)?;
    let (input, hash) = parse_hash(input)?;
    let (input, _padding) = take(4usize)(input)?;
    Ok((input, FileMeta { size, hash }))
}

fn parse_file_meta_pair(input: &[u8]) -> IResult<&[u8], FileMetaPair> {
    let (input, raw) = parse_file_meta(input)?;
    let (input, compressed) = parse_file_meta(input)?;
    Ok((input, FileMetaPair { raw, compressed }))
}

/// Parse a file list entry
pub fn parse_pk_entry_data(input: &[u8]) -> IResult<&[u8], PKEntryData> {
    let (input, meta) = parse_file_meta_pair(input)?;
    let (input, file_data_addr) = le_u32(input)?;
    let (input, is_compressed) = parse_compressed(input)?;
    Ok((
        input,
        PKEntryData {
            meta,
            file_data_addr,
            is_compressed,
        },
    ))
}

/// Parse a file list entry
pub fn parse_pk_entry(input: &[u8]) -> IResult<&[u8], PKEntry> {
    parse_crc_node(parse_pk_entry_data)(input)
}

/// Parse the file list
pub fn parse_pk_entry_list(input: &[u8]) -> IResult<&[u8], Vec<PKEntry>> {
    length_count(le_u32, parse_pk_entry)(input)
}

#[cfg(test)]
mod tests {
    use crate::crc::CRC;

    use super::*;

    const EMPTY: &[u8] = &[];

    #[test]
    fn test_magic() {
        assert_eq!(parse_pk_magic(b"ndpk"), Ok((EMPTY, ())));
    }

    #[test]
    fn test_trailer() {
        assert_eq!(
            parse_pk_trailer(&[0x20, 0x10, 0, 0, 0, 0, 0, 0]),
            Ok((
                EMPTY,
                PKTrailer {
                    file_list_base_addr: 0x1020,
                    num_compressed: 0,
                }
            ))
        )
    }

    const ARR: [u8; 16] = [
        0x33, 0x7e, 0x24, 0xd7, 0x26, 0xfd, 0x72, 0x8f, //
        0x92, 0x95, 0x7a, 0x2c, 0x90, 0x8d, 0xde, 0xe6,
    ];

    const ARR2: [u8; 16] = [
        0x44, 0x7e, 0x24, 0xd7, 0x26, 0xfd, 0x72, 0x8f, //
        0x92, 0x95, 0x7a, 0x2c, 0x90, 0x8d, 0xde, 0xe6,
    ];

    #[test]
    fn test_parse_hash() {
        assert_eq!(
            parse_hash(b"337e24d726fd728f92957a2c908ddee6"),
            Ok((EMPTY, MD5Sum(ARR)))
        );
    }

    #[test]
    fn test_entry() {
        let mut data = Vec::new();
        data.extend_from_slice(&u32::to_le_bytes(1234)); // CRC
        data.extend_from_slice(&i32::to_le_bytes(100)); // left
        data.extend_from_slice(&i32::to_le_bytes(200)); // right

        data.extend_from_slice(&u32::to_le_bytes(4444)); // file size
        data.extend_from_slice(b"337e24d726fd728f92957a2c908ddee6");
        data.extend_from_slice(&[0, 0, 0, 0]);

        data.extend_from_slice(&u32::to_le_bytes(8888)); // file size
        data.extend_from_slice(b"447e24d726fd728f92957a2c908ddee6");
        data.extend_from_slice(&[0, 0, 0, 0]);

        data.extend_from_slice(&u32::to_le_bytes(5678)); // file offset
        data.extend_from_slice(&[1, 0, 0, 0]); // compressed

        assert_eq!(
            parse_pk_entry(&data),
            Ok((
                EMPTY,
                PKEntry {
                    crc: CRC::from_raw(1234),
                    left: 100,
                    right: 200,
                    data: PKEntryData {
                        meta: FileMetaPair {
                            raw: FileMeta {
                                size: 4444,
                                hash: MD5Sum(ARR)
                            },
                            compressed: FileMeta {
                                size: 8888,
                                hash: MD5Sum(ARR2)
                            }
                        },
                        file_data_addr: 5678,
                        is_compressed: 1,
                    }
                }
            ))
        );
    }
}