Skip to main content

mux_media/types/
file_number.rs

1use std::ffi::OsStr;
2
3/// Extracts an ascii-digit number from file names.
4///
5/// Defines number:
6/// - by default: as first ascii-digit subsequence.
7/// - after [`FileNumber::update`]: as first different ascii-digit subsequence between two names
8/// OR by default (if not different ascii-digit subsequence).
9///
10/// # Limits
11/// Correct works with standard path length only (255 ascii-digits max). In other cases,
12/// processes first 255 ascii-digits only.
13#[derive(Clone)]
14pub struct FileNumber {
15    // ranges stores input (start, end) values, not digits_buf
16    ranges: [(u16, u16); Self::MAX_NUMBER_NUMBERS],
17    ranges_idx: u16,
18
19    // ascii digit bytes only
20    digits_buf: [u8; Self::MAX_ASCII_DIGITS],
21}
22
23impl FileNumber {
24    /// Max digits count in most filesystems is 255 ascii bytes.
25    const MAX_ASCII_DIGITS: usize = u8::MAX as usize;
26
27    /// Max file name in most filesystems is 255 ascii bytes. Minimum digit range is 2 bytes
28    /// (digit + sep). Therefore MAX_NUMBER_NUMBERS is 128.
29    const MAX_NUMBER_NUMBERS: usize = 128;
30
31    /// Returns the number string if present; otherwise, returns an empty string.
32    pub fn as_str(&self) -> &str {
33        // SAFETY: ascii digit bytes only
34        unsafe { str::from_utf8_unchecked(self.as_bytes()) }
35    }
36
37    /// Gets `usize` number if parsable.
38    pub fn get_usize(&self) -> Option<usize> {
39        self.as_str().parse::<usize>().ok()
40    }
41
42    /// Constructs a new [`FileNumber`] from a byte slice.
43    ///
44    /// Sets number as first ascii-digit subsequence (if present); otherwise, as empty string.
45    pub fn from_bytes<B>(bytes: &B) -> FileNumber
46    where
47        B: AsRef<[u8]> + ?Sized,
48    {
49        FileNumber::from(bytes.as_ref())
50    }
51
52    /// Updates the number from `new` bytes.
53    ///
54    /// # Cases
55    /// - New bytes contain correct and different number at the old address:
56    /// copies only this number bytes.
57    ///
58    /// - New bytes contain correct and different number at the any other old address:
59    /// copies this number bytes and updates index number.
60    ///
61    /// - Otherwise, its eq constructs new [`FileNumber`].
62    pub fn update<B>(&mut self, new: &B)
63    where
64        B: AsRef<[u8]> + ?Sized,
65    {
66        let new_bytes = new.as_ref();
67
68        let is_updated_only_number_and_idx = |current: &mut FileNumber, ranges_idx| -> bool {
69            let (start, end) = current.ranges[ranges_idx];
70            let end = end as usize;
71
72            if end <= new_bytes.len() {
73                let maybe_new_number = &new_bytes[start as usize..end];
74                let mut i = 0;
75
76                for (old, n) in current
77                    .as_bytes_idx(ranges_idx)
78                    .iter()
79                    .zip(maybe_new_number.iter())
80                {
81                    if n != old {
82                        let remainder = &maybe_new_number[i..];
83
84                        return if remainder.iter().all(|b| b.is_ascii_digit()) {
85                            current.ranges_idx = ranges_idx as u16;
86                            current.as_mut_bytes_idx(ranges_idx)[i..].copy_from_slice(remainder);
87                            true
88                        } else {
89                            false
90                        };
91                    }
92                    i += 1;
93                }
94            }
95
96            false
97        };
98
99        let ranges_idx = self.ranges_idx as usize;
100
101        if is_updated_only_number_and_idx(self, ranges_idx) {
102            return;
103        }
104
105        for idx in 0..self.ranges.len() {
106            if idx == ranges_idx {
107                continue;
108            }
109            if self.ranges[idx].1 == 0 {
110                break;
111            }
112
113            if is_updated_only_number_and_idx(self, idx) {
114                return;
115            }
116        }
117
118        *self = FileNumber::from(new_bytes);
119    }
120
121    fn as_bytes(&self) -> &[u8] {
122        self.as_bytes_idx(self.ranges_idx as usize)
123    }
124
125    fn as_bytes_idx(&self, idx: usize) -> &[u8] {
126        let (start, end) = self.digit_start_end_idx(idx);
127        &self.digits_buf[start..end]
128    }
129
130    fn as_mut_bytes_idx(&mut self, idx: usize) -> &mut [u8] {
131        let (start, end) = self.digit_start_end_idx(idx);
132        &mut self.digits_buf[start..end]
133    }
134
135    fn digit_start_end_idx(&self, idx: usize) -> (usize, usize) {
136        let mut start = 0;
137        let mut end = 0;
138
139        for (r_start, r_end) in self.ranges.iter().take(idx + 1) {
140            start = end;
141            end += (r_end - r_start) as usize;
142        }
143
144        (start, end)
145    }
146}
147
148impl From<&OsStr> for FileNumber {
149    fn from(value: &OsStr) -> Self {
150        value.as_encoded_bytes().into()
151    }
152}
153
154impl From<&[u8]> for FileNumber {
155    fn from(bytes: &[u8]) -> Self {
156        let mut ranges = [(0u16, 0u16); Self::MAX_NUMBER_NUMBERS];
157        let mut i_ranges = 0;
158        let mut count_digits = 0;
159
160        let mut start = None;
161
162        for (i, byte) in bytes.into_iter().enumerate() {
163            match (byte.is_ascii_digit(), start) {
164                (true, None) => start = Some(i),
165                (false, Some(st)) => {
166                    if i > u16::MAX as usize {
167                        break;
168                    }
169
170                    count_digits += i - st;
171                    if count_digits > Self::MAX_ASCII_DIGITS {
172                        break;
173                    }
174
175                    ranges[i_ranges] = (st as u16, i as u16);
176                    i_ranges += 1;
177                    start = None;
178                }
179                _ => continue,
180            }
181        }
182
183        let mut digits_buf = [0u8; Self::MAX_ASCII_DIGITS];
184        let mut i = 0;
185
186        ranges
187            .iter()
188            .take_while(|(_, end)| *end > 0)
189            .for_each(|&(start, end)| {
190                let (start, end) = (start as usize, end as usize);
191                let len = end - start;
192                let next_i = i + len;
193
194                digits_buf[i..next_i].copy_from_slice(&bytes[start..end]);
195                i = next_i;
196            });
197
198        FileNumber {
199            digits_buf,
200            ranges,
201            ranges_idx: 0,
202        }
203    }
204}