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 & 30) == 30 {
41            char_value &= 31;
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 & 30) == 30 { 5 } else { 6 };
67        decode_chars(
68            &mut bytes_out,
69            out_pos,
70            value_len,
71            char_value,
72            i == input.len() - 1,
73        );
74        out_pos += value_len;
75    }
76
77    Some(bytes_out)
78}
79
80fn encode_chars(bytes: &[u8], bit_index: usize) -> Option<usize> {
81    if bit_index >= 8 * bytes.len() {
82        return None;
83    }
84
85    let byte_index = bit_index / 8;
86    let current_byte = *bytes.get(byte_index)? as usize;
87    let offset = bit_index - 8 * byte_index;
88    if offset <= 2 || byte_index >= bytes.len() - 1 {
89        // move mask into right position, get only offset bits of current_byte, move back
90        Some((current_byte & (63 << offset)) >> offset)
91    } else {
92        let next_byte = *bytes.get(byte_index + 1)? as usize;
93        // same concept as above, move mask into right position,
94        // get correct bits of current and next byte, move back, combine the two
95        Some(
96            ((current_byte & (63 << offset)) >> offset)
97                | ((next_byte & (63 >> (8 - offset))) << (8 - offset)),
98        )
99    }
100}
101
102fn decode_chars(
103    bytes: &mut Vec<u8>,
104    bit_index: usize,
105    value_len: usize,
106    char_value: i32,
107    is_last: bool,
108) {
109    let byte_index = bit_index / 8;
110    while byte_index >= bytes.len() {
111        bytes.push(0);
112    }
113
114    // offset in current byte
115    let offset = bit_index - 8 * byte_index;
116
117    // writes value into byte (only part that fits)
118    bytes[byte_index] |= ((char_value << offset) & 0xFF) as u8;
119
120    // in case of value going into next byte add that part
121    if offset > 8 - value_len && !is_last {
122        let byte_index_next = byte_index + 1;
123        if byte_index_next >= bytes.len() {
124            bytes.push(0);
125        }
126
127        // write rest of value into next byte
128        bytes[byte_index_next] |= (char_value >> (8 - offset)) as u8;
129    }
130}
131
132#[must_use]
133pub fn decompress(data: &[u8]) -> Option<Vec<u8>> {
134    let mut decoder = ZlibDecoder::new(data);
135    let mut decompressed_data = Vec::new();
136    decoder.read_to_end(&mut decompressed_data).ok()?;
137    Some(decompressed_data)
138}
139
140#[must_use]
141pub fn compress_first(data: &[u8]) -> Option<Vec<u8>> {
142    let mut compressor = flate2::Compress::new_with_window_bits(Compression::best(), true, 9);
143    let mut compressed_data = Vec::new();
144    let mut buffer = [0u8; 4096];
145    compressor
146        .compress(data, &mut buffer, FlushCompress::Finish)
147        .ok()?;
148    compressed_data.extend_from_slice(&buffer[..compressor.total_out() as usize]);
149    Some(compressed_data)
150}
151
152#[must_use]
153pub fn compress_final(data: &[u8]) -> Option<Vec<u8>> {
154    let mut compressor = flate2::Compress::new_with_window_bits(Compression::best(), true, 15);
155    let mut compressed_data = Vec::new();
156    let mut buffer = [0u8; 4096];
157    compressor
158        .compress(data, &mut buffer, FlushCompress::Finish)
159        .ok()?;
160    compressed_data.extend_from_slice(&buffer[..compressor.total_out() as usize]);
161    Some(compressed_data)
162}
163
164#[must_use]
165pub fn hash_vec(track_data: Vec<u8>) -> String {
166    sha256::digest(track_data)
167}
168
169#[derive(Debug, PartialEq, Eq, Clone)]
170pub struct Track {
171    pub name: String,
172    pub author: Option<String>,
173    pub last_modified: Option<u32>,
174    pub track_data: Vec<u8>,
175}
176
177pub(crate) mod read {
178    #[inline]
179    pub fn read_u8(buf: &[u8], offset: &mut usize) -> Option<u8> {
180        let res = buf.get(*offset).copied();
181        *offset += 1;
182        res
183    }
184    #[inline]
185    pub fn read_u16(buf: &[u8], offset: &mut usize) -> Option<u16> {
186        let res = Some(u16::from(*buf.get(*offset)?) | (u16::from(*buf.get(*offset + 1)?) << 8));
187        *offset += 2;
188        res
189    }
190    #[inline]
191    pub fn read_i24(buf: &[u8], offset: &mut usize) -> Option<i32> {
192        let res = Some(
193            i32::from(*buf.get(*offset)?)
194                | (i32::from(*buf.get(*offset + 1)?) << 8)
195                | (i32::from(*buf.get(*offset + 2)?) << 16),
196        );
197        *offset += 3;
198        res
199    }
200    #[inline]
201    pub fn read_u32(buf: &[u8], offset: &mut usize) -> Option<u32> {
202        let res = Some(
203            u32::from(*buf.get(*offset)?)
204                | (u32::from(*buf.get(*offset + 1)?) << 8)
205                | (u32::from(*buf.get(*offset + 2)?) << 16)
206                | (u32::from(*buf.get(*offset + 3)?) << 24),
207        );
208        *offset += 4;
209        res
210    }
211}
212
213pub(crate) mod write {
214    #[inline]
215    pub fn write_u8(data: &mut Vec<u8>, value: u32) {
216        data.push((value & 0xFF) as u8);
217    }
218    #[inline]
219    pub fn write_u16(data: &mut Vec<u8>, value: u32) {
220        data.push((value & 0xFF) as u8);
221        data.push((value >> 8 & 0xFF) as u8);
222    }
223    #[inline]
224    pub fn write_u24(data: &mut Vec<u8>, value: u32) {
225        data.push((value & 0xFF) as u8);
226        data.push((value >> 8 & 0xFF) as u8);
227        data.push((value >> 16 & 0xFF) as u8);
228    }
229    #[inline]
230    pub fn write_u32(data: &mut Vec<u8>, value: u32) {
231        data.push((value & 0xFF) as u8);
232        data.push((value >> 8 & 0xFF) as u8);
233        data.push((value >> 16 & 0xFF) as u8);
234        data.push((value >> 24 & 0xFF) as u8);
235    }
236}