Skip to main content

polytrack_codes/tools/
mod.rs

1#![allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
2#[cfg(test)]
3mod tests;
4
5pub mod prelude {
6    pub use super::{Track, read::*, write::*};
7}
8
9use std::io::Read as _;
10
11use flate2::{Compression, FlushCompress, read::ZlibDecoder};
12
13const ENCODE_VALUES: [char; 62] = [
14    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
15    'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
16    'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4',
17    '5', '6', '7', '8', '9',
18];
19
20const DECODE_VALUES: [i32; 123] = [
21    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
22    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
23    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,
24    9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26,
25    27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50,
26    51,
27];
28
29#[must_use]
30/// Encode the given byte buffer into base62 encoded text according to Polytrack's base62 implementation.
31/// Returns [`None`] if something failed in the process.
32pub fn encode(input: &[u8]) -> Option<String> {
33    let mut bit_pos = 0;
34    let mut res = String::new();
35
36    while bit_pos < 8 * input.len() {
37        let mut char_value = encode_chars(input, bit_pos)?;
38        // if char_num ends with 11110, shorten it to 5 bits
39        // (getting rid of value 62 and 63, which are too big for base62)
40        if (char_value & 0b11110) == 0b11110 {
41            char_value &= 0b11111;
42            bit_pos += 5;
43        } else {
44            bit_pos += 6;
45        }
46        res.push(*ENCODE_VALUES.get(char_value)?);
47    }
48
49    Some(res)
50}
51
52#[must_use]
53/// Decode the given string as base62 text according to Polytrack's base62 implementation.
54/// Returns [`None`] if any character isn't valid for base62 encoded text.
55pub fn decode(input: &str) -> Option<Vec<u8>> {
56    let mut out_pos = 0;
57    let mut bytes_out: Vec<u8> = Vec::new();
58
59    for (i, ch) in input.chars().enumerate() {
60        let char_code = ch as usize;
61        let char_value = *DECODE_VALUES.get(char_code)?;
62        if char_value == -1 {
63            return None;
64        }
65        // 5 if char_value is 30 or 31, 6 otherwise (see encode for explanation)
66        let value_len = if (char_value & 0b11110) == 0b11110 {
67            5
68        } else {
69            6
70        };
71        decode_chars(
72            &mut bytes_out,
73            out_pos,
74            value_len,
75            char_value,
76            i == input.len() - 1,
77        );
78        out_pos += value_len;
79    }
80
81    Some(bytes_out)
82}
83
84fn encode_chars(bytes: &[u8], bit_index: usize) -> Option<usize> {
85    if bit_index >= 8 * bytes.len() {
86        return None;
87    }
88
89    let byte_index = bit_index / 8;
90    let current_byte = *bytes.get(byte_index)? as usize;
91    let offset = bit_index - 8 * byte_index;
92    if offset <= 2 || byte_index >= bytes.len() - 1 {
93        // move mask into right position, get only offset bits of current_byte, move back
94        Some((current_byte & (63 << offset)) >> offset)
95    } else {
96        let next_byte = *bytes.get(byte_index + 1)? as usize;
97        // same concept as above, move mask into right position,
98        // get correct bits of current and next byte, move back, combine the two
99        Some(
100            ((current_byte & (63 << offset)) >> offset)
101                | ((next_byte & (63 >> (8 - offset))) << (8 - offset)),
102        )
103    }
104}
105
106fn decode_chars(
107    bytes: &mut Vec<u8>,
108    bit_index: usize,
109    value_len: usize,
110    char_value: i32,
111    is_last: bool,
112) {
113    let byte_index = bit_index / 8;
114    while byte_index >= bytes.len() {
115        bytes.push(0);
116    }
117
118    // offset in current byte
119    let offset = bit_index - 8 * byte_index;
120
121    // writes value into byte (only part that fits)
122    bytes[byte_index] |= ((char_value << offset) & 0xFF) as u8;
123
124    // in case of value going into next byte add that part
125    if offset > 8 - value_len && !is_last {
126        let byte_index_next = byte_index + 1;
127        if byte_index_next >= bytes.len() {
128            bytes.push(0);
129        }
130
131        // write rest of value into next byte
132        bytes[byte_index_next] |= (char_value >> (8 - offset)) as u8;
133    }
134}
135
136#[must_use]
137pub fn decompress(data: &[u8]) -> Option<Vec<u8>> {
138    let mut decoder = ZlibDecoder::new(data);
139    let mut decompressed_data = Vec::new();
140    decoder.read_to_end(&mut decompressed_data).ok()?;
141    Some(decompressed_data)
142}
143
144#[must_use]
145pub fn compress_first(data: &[u8]) -> Option<Vec<u8>> {
146    deflate_with_window(data, 9)
147}
148
149#[must_use]
150pub fn compress_final(data: &[u8]) -> Option<Vec<u8>> {
151    deflate_with_window(data, 15)
152}
153
154fn deflate_with_window(input: &[u8], window_bits: u8) -> Option<Vec<u8>> {
155    let mut compressor =
156        flate2::Compress::new_with_window_bits(Compression::best(), true, window_bits);
157    let mut output = Vec::new();
158    let mut buffer = [0u8; 65536];
159    let mut input_offset = 0;
160    loop {
161        let before_in = compressor.total_in();
162        let before_out = compressor.total_out();
163        let flush = if input_offset >= input.len() {
164            FlushCompress::Finish
165        } else {
166            FlushCompress::None
167        };
168        let status = compressor
169            .compress(&input[input_offset..], &mut buffer, flush)
170            .ok()?;
171        let consumed = (compressor.total_in() - before_in) as usize;
172        let produced = (compressor.total_out() - before_out) as usize;
173        input_offset += consumed;
174        output.extend_from_slice(&buffer[..produced]);
175        if status == flate2::Status::StreamEnd {
176            break;
177        }
178    }
179    Some(output)
180}
181
182#[must_use]
183pub fn hash_vec(track_data: Vec<u8>) -> String {
184    sha256::digest(track_data)
185}
186
187#[derive(Debug, PartialEq, Eq, Clone)]
188pub struct Track {
189    pub name: String,
190    pub author: Option<String>,
191    pub last_modified: Option<u32>,
192    pub track_data: Vec<u8>,
193}
194
195pub(crate) mod read {
196    #[inline]
197    pub fn read_u8(buf: &[u8], offset: &mut usize) -> Option<u8> {
198        let res = buf.get(*offset).copied();
199        *offset += 1;
200        res
201    }
202    #[inline]
203    pub fn read_u16(buf: &[u8], offset: &mut usize) -> Option<u16> {
204        let res = Some(u16::from(*buf.get(*offset)?) | (u16::from(*buf.get(*offset + 1)?) << 8));
205        *offset += 2;
206        res
207    }
208    #[inline]
209    pub fn read_i24(buf: &[u8], offset: &mut usize) -> Option<i32> {
210        let res = Some(
211            i32::from(*buf.get(*offset)?)
212                | (i32::from(*buf.get(*offset + 1)?) << 8)
213                | (i32::from(*buf.get(*offset + 2)?) << 16),
214        );
215        *offset += 3;
216        res
217    }
218    #[inline]
219    pub fn read_u32(buf: &[u8], offset: &mut usize) -> Option<u32> {
220        let res = Some(
221            u32::from(*buf.get(*offset)?)
222                | (u32::from(*buf.get(*offset + 1)?) << 8)
223                | (u32::from(*buf.get(*offset + 2)?) << 16)
224                | (u32::from(*buf.get(*offset + 3)?) << 24),
225        );
226        *offset += 4;
227        res
228    }
229}
230
231pub(crate) mod write {
232    #[inline]
233    pub fn write_u8(data: &mut Vec<u8>, value: u32) {
234        data.push((value & 0xFF) as u8);
235    }
236    #[inline]
237    pub fn write_u16(data: &mut Vec<u8>, value: u32) {
238        data.push((value & 0xFF) as u8);
239        data.push((value >> 8 & 0xFF) as u8);
240    }
241    #[inline]
242    pub fn write_u24(data: &mut Vec<u8>, value: u32) {
243        data.push((value & 0xFF) as u8);
244        data.push((value >> 8 & 0xFF) as u8);
245        data.push((value >> 16 & 0xFF) as u8);
246    }
247    #[inline]
248    pub fn write_u32(data: &mut Vec<u8>, value: u32) {
249        data.push((value & 0xFF) as u8);
250        data.push((value >> 8 & 0xFF) as u8);
251        data.push((value >> 16 & 0xFF) as u8);
252        data.push((value >> 24 & 0xFF) as u8);
253    }
254}