polytrack_codes/tools/
mod.rs

1#![allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
2#[cfg(test)]
3mod tests;
4
5use std::io::Read as _;
6
7use flate2::read::ZlibDecoder;
8
9const ENCODE_VALUES: [char; 62] = [
10    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
11    'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
12    'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4',
13    '5', '6', '7', '8', '9',
14];
15
16const DECODE_VALUES: [i32; 123] = [
17    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
18    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
19    52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8,
20    9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26,
21    27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50,
22    51,
23];
24
25#[must_use]
26/// Encode the given byte buffer into base62 encoded text according to Polytrack's base62 implementation.
27/// Returns [`None`] if something failed in the process.
28pub fn encode(input: &[u8]) -> Option<String> {
29    let mut bit_pos = 0;
30    let mut res = String::new();
31
32    while bit_pos < 8 * input.len() {
33        let mut char_value = encode_chars(input, bit_pos)?;
34        // if char_num ends with 11110, shorten it to 5 bits
35        // (getting rid of value 62 and 63, which are too big for base62)
36        if (char_value & 30) == 30 {
37            char_value &= 31;
38            bit_pos += 5;
39        } else {
40            bit_pos += 6;
41        }
42        res.push(*ENCODE_VALUES.get(char_value)?);
43    }
44
45    Some(res)
46}
47
48#[must_use]
49/// Decode the given string as base62 text according to Polytrack's base62 implementation.
50/// Returns [`None`] if any character isn't valid for base62 encoded text.
51pub fn decode(input: &str) -> Option<Vec<u8>> {
52    let mut out_pos = 0;
53    let mut bytes_out: Vec<u8> = Vec::new();
54
55    for (i, ch) in input.chars().enumerate() {
56        let char_code = ch as usize;
57        let char_value = *DECODE_VALUES.get(char_code)?;
58        if char_value == -1 {
59            return None;
60        }
61        // 5 if char_value is 30 or 31, 6 otherwise (see encode for explanation)
62        let value_len = if (char_value & 30) == 30 { 5 } else { 6 };
63        decode_chars(
64            &mut bytes_out,
65            out_pos,
66            value_len,
67            char_value,
68            i == input.len() - 1,
69        );
70        out_pos += value_len;
71    }
72
73    Some(bytes_out)
74}
75
76fn encode_chars(bytes: &[u8], bit_index: usize) -> Option<usize> {
77    if bit_index >= 8 * bytes.len() {
78        return None;
79    }
80
81    let byte_index = bit_index / 8;
82    let current_byte = *bytes.get(byte_index)? as usize;
83    let offset = bit_index - 8 * byte_index;
84    if offset <= 2 || byte_index >= bytes.len() - 1 {
85        // move mask into right position, get only offset bits of current_byte, move back
86        Some((current_byte & (63 << offset)) >> offset)
87    } else {
88        let next_byte = *bytes.get(byte_index + 1)? as usize;
89        // same concept as above, move mask into right position,
90        // get correct bits of current and next byte, move back, combine the two
91        Some(
92            ((current_byte & (63 << offset)) >> offset)
93                | ((next_byte & (63 >> (8 - offset))) << (8 - offset)),
94        )
95    }
96}
97
98fn decode_chars(
99    bytes: &mut Vec<u8>,
100    bit_index: usize,
101    value_len: usize,
102    char_value: i32,
103    is_last: bool,
104) {
105    let byte_index = bit_index / 8;
106    while byte_index >= bytes.len() {
107        bytes.push(0);
108    }
109
110    // offset in current byte
111    let offset = bit_index - 8 * byte_index;
112
113    // writes value into byte (only part that fits)
114    bytes[byte_index] |= ((char_value << offset) & 0xFF) as u8;
115
116    // in case of value going into next byte add that part
117    if offset > 8 - value_len && !is_last {
118        let byte_index_next = byte_index + 1;
119        if byte_index_next >= bytes.len() {
120            bytes.push(0);
121        }
122
123        // write rest of value into next byte
124        bytes[byte_index_next] |= (char_value >> (8 - offset)) as u8;
125    }
126}
127
128#[must_use]
129pub fn decompress(data: &[u8]) -> Option<Vec<u8>> {
130    let mut decoder = ZlibDecoder::new(data);
131    let mut decompressed_data = Vec::new();
132    decoder.read_to_end(&mut decompressed_data).ok()?;
133    Some(decompressed_data)
134}
135
136#[must_use]
137pub fn hash_vec(track_data: Vec<u8>) -> String {
138    sha256::digest(track_data)
139}
140
141#[derive(Debug, PartialEq, Eq)]
142pub struct Track {
143    pub name: String,
144    pub author: Option<String>,
145    pub track_data: Vec<u8>,
146}
147
148pub(crate) mod read {
149    #[inline]
150    pub fn read_u8(buf: &[u8], offset: &mut usize) -> Option<u8> {
151        let res = buf.get(*offset).copied();
152        *offset += 1;
153        res
154    }
155    #[inline]
156    pub fn read_u16(buf: &[u8], offset: &mut usize) -> Option<u16> {
157        let res = Some(u16::from(*buf.get(*offset)?) | (u16::from(*buf.get(*offset + 1)?) << 8));
158        *offset += 2;
159        res
160    }
161    #[inline]
162    pub fn read_i24(buf: &[u8], offset: &mut usize) -> Option<i32> {
163        let res = Some(
164            i32::from(*buf.get(*offset)?)
165                | (i32::from(*buf.get(*offset + 1)?) << 8)
166                | (i32::from(*buf.get(*offset + 2)?) << 16),
167        );
168        *offset += 3;
169        res
170    }
171    #[inline]
172    pub fn read_u32(buf: &[u8], offset: &mut usize) -> Option<u32> {
173        let res = Some(
174            u32::from(*buf.get(*offset)?)
175                | (u32::from(*buf.get(*offset + 1)?) << 8)
176                | (u32::from(*buf.get(*offset + 2)?) << 16)
177                | (u32::from(*buf.get(*offset + 3)?) << 24),
178        );
179        *offset += 4;
180        res
181    }
182}