Skip to main content

php_std/
string.rs

1//! Byte-string functions of `ext/standard/string.c` and `ext/ctype`, plus
2//! `crypt()`, `password_hash()` / `password_verify()` and `hash()`.
3//!
4//! PHP strings are byte strings: every function here takes and returns
5//! `&[u8]` / `Vec<u8>`, never assumes UTF-8 and handles invalid UTF-8 like
6//! any other byte. Case mapping (`strtolower`, `ucfirst`, `stripos`, ...) is
7//! ASCII-only, as in PHP 8.2 and later.
8//!
9//! Callers holding a `&str` pass `s.as_bytes()`. For valid UTF-8 arguments
10//! these keep the result valid UTF-8, so `String::from_utf8` (or
11//! `std::str::from_utf8`) on it cannot fail: the case functions, `trim`
12//! family with an ASCII character list (such as [`TRIM_CHARACTERS`]),
13//! `str_replace`/`strtr_array` with UTF-8 strings, `explode`. Functions that
14//! work on single bytes or byte positions (`substr`, `strtr` with non-ASCII
15//! bytes) may split a character, as in PHP.
16//!
17//! Arguments PHP takes as `int` (offsets, lengths) are `i64`, with PHP's
18//! negative-offset rules. Results that PHP returns as `false` are `None`.
19//! Errors PHP throws are [`Error`], one variant per exception class, with
20//! PHP's message.
21//!
22//! | PHP | Rust |
23//! |---|---|
24//! | `strtolower`, `strtoupper`, `ucfirst`, `lcfirst`, `ucwords` | [`strtolower`], [`strtoupper`], [`ucfirst`], [`lcfirst`], [`ucwords`] |
25//! | `trim`, `ltrim`, `rtrim` | [`trim`], [`ltrim`], [`rtrim`] ([`TRIM_CHARACTERS`] is the default) |
26//! | `substr` | [`substr`] |
27//! | `stripos` | [`stripos`] |
28//! | `str_contains`, `str_starts_with` | [`str_contains`], [`str_starts_with`] |
29//! | `strcmp`, `strcasecmp` | [`strcmp`], [`strcasecmp`] |
30//! | `str_replace` | [`str_replace`], [`str_replace_array`] |
31//! | `strtr` | [`strtr`], [`strtr_array`] |
32//! | `explode` | [`explode`] |
33//! | `addcslashes`, `stripcslashes` | [`addcslashes`], [`stripcslashes`] |
34//! | `strip_tags` (no allowed tags) | [`strip_tags`] |
35//! | `escapeshellarg` | [`escapeshellarg`] |
36//! | `ctype_alnum`, `ctype_digit`, `ctype_xdigit` | [`ctype_alnum`], [`ctype_digit`], [`ctype_xdigit`] ([`Ctype`] for any value) |
37//! | `(string) $value` (`zval_get_string`) | [`to_php_string`] |
38
39use std::borrow::Cow;
40use std::fmt;
41
42use serde_json::Value;
43
44use crate::number;
45
46/// An exception a PHP string, multibyte, encoding or formatting function
47/// throws: one variant per PHP exception class, carrying PHP's message.
48#[derive(Debug, Clone, PartialEq, Eq)]
49pub enum Error {
50    /// `ValueError`: an argument has a value the function rejects.
51    Value(String),
52    /// `TypeError`: an argument combination PHP rejects by type.
53    Type(String),
54    /// `ArgumentCountError`: too few arguments (`sprintf`).
55    ArgumentCount(String),
56    /// `Error`, e.g. converting a `stdClass` to a string.
57    Error(String),
58}
59
60impl Error {
61    /// The PHP exception class this error corresponds to.
62    pub fn php_class(&self) -> &'static str {
63        match self {
64            Error::Value(_) => "ValueError",
65            Error::Type(_) => "TypeError",
66            Error::ArgumentCount(_) => "ArgumentCountError",
67            Error::Error(_) => "Error",
68        }
69    }
70
71    /// PHP's exception message.
72    pub fn message(&self) -> &str {
73        match self {
74            Error::Value(m) | Error::Type(m) | Error::ArgumentCount(m) | Error::Error(m) => m,
75        }
76    }
77
78    /// `zend_argument_value_error()`: `"<function>(): Argument #<n> ($<name>) <what>"`.
79    pub(crate) fn argument(function: &str, n: u32, name: &str, what: &str) -> Self {
80        Error::Value(format!("{function}(): Argument #{n} (${name}) {what}"))
81    }
82}
83
84impl fmt::Display for Error {
85    /// Writes the message.
86    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87        f.write_str(self.message())
88    }
89}
90
91impl std::error::Error for Error {}
92
93// ---------------------------------------------------------------------------
94// Case (ASCII only since PHP 8.2)
95// ---------------------------------------------------------------------------
96
97/// PHP `strtolower`: ASCII `A-Z` to `a-z`; every other byte unchanged.
98/// Borrows when nothing changes. Valid UTF-8 stays valid UTF-8.
99pub fn strtolower(s: &[u8]) -> Cow<'_, [u8]> {
100    match s.iter().position(u8::is_ascii_uppercase) {
101        None => Cow::Borrowed(s),
102        Some(_) => Cow::Owned(s.to_ascii_lowercase()),
103    }
104}
105
106/// PHP `strtoupper`: ASCII `a-z` to `A-Z`; every other byte unchanged.
107/// Borrows when nothing changes. Valid UTF-8 stays valid UTF-8.
108pub fn strtoupper(s: &[u8]) -> Cow<'_, [u8]> {
109    match s.iter().position(u8::is_ascii_lowercase) {
110        None => Cow::Borrowed(s),
111        Some(_) => Cow::Owned(s.to_ascii_uppercase()),
112    }
113}
114
115/// PHP `strip_tags($s)` (no allowed tags): drops HTML and PHP tags,
116/// comments and NUL bytes; a `<` followed by whitespace is kept as text.
117pub fn strip_tags(s: &[u8]) -> Vec<u8> {
118    crate::filter::sanitize::strip_tags(s, false)
119}
120
121/// PHP `ucfirst`: uppercases the first byte if it is an ASCII letter.
122pub fn ucfirst(s: &[u8]) -> Cow<'_, [u8]> {
123    match s.first() {
124        Some(c) if c.is_ascii_lowercase() => {
125            let mut out = s.to_vec();
126            out[0] = c.to_ascii_uppercase();
127            Cow::Owned(out)
128        }
129        _ => Cow::Borrowed(s),
130    }
131}
132
133/// PHP `lcfirst`: lowercases the first byte if it is an ASCII letter.
134pub fn lcfirst(s: &[u8]) -> Cow<'_, [u8]> {
135    match s.first() {
136        Some(c) if c.is_ascii_uppercase() => {
137            let mut out = s.to_vec();
138            out[0] = c.to_ascii_lowercase();
139            Cow::Owned(out)
140        }
141        _ => Cow::Borrowed(s),
142    }
143}
144
145/// The default `$separators` of `ucwords`: `" \t\r\n\f\v"`.
146pub const UCWORDS_SEPARATORS: &[u8] = b" \t\r\n\x0c\x0b";
147
148/// PHP `ucwords($string, $separators)`: uppercases (ASCII) the first byte
149/// and every byte that follows one of `separators`. `separators` accepts
150/// `a..z` ranges like [`trim`]. Pass [`UCWORDS_SEPARATORS`] for PHP's default.
151///
152/// As in PHP, the separator test looks at the previous byte *after* it was
153/// uppercased, so `ucwords("aab", "A")` is `"AAB"`.
154pub fn ucwords<'a>(s: &'a [u8], separators: &[u8]) -> Cow<'a, [u8]> {
155    if s.is_empty() {
156        return Cow::Borrowed(s);
157    }
158    let mask = charmask(separators);
159    let mut out = s.to_vec();
160    out[0] = out[0].to_ascii_uppercase();
161    for i in 1..out.len() {
162        if mask[out[i - 1] as usize] {
163            out[i] = out[i].to_ascii_uppercase();
164        }
165    }
166    if out == s { Cow::Borrowed(s) } else { Cow::Owned(out) }
167}
168
169// ---------------------------------------------------------------------------
170// Character masks and trimming
171// ---------------------------------------------------------------------------
172
173/// `php_charmask`: the set of bytes a `trim`/`ucwords`/`addcslashes`
174/// character list names. `a..z` adds an inclusive range; a malformed range
175/// (PHP warns) adds what PHP adds: for `"a.."` that is `a` and the last `.`.
176pub fn charmask(chars: &[u8]) -> [bool; 256] {
177    let mut mask = [false; 256];
178    let len = chars.len();
179    let mut i = 0;
180    while i < len {
181        let c = chars[i];
182        if i + 3 < len && chars[i + 1] == b'.' && chars[i + 2] == b'.' && chars[i + 3] >= c {
183            for b in c..=chars[i + 3] {
184                mask[b as usize] = true;
185            }
186            i += 4;
187        } else if i + 1 < len && chars[i] == b'.' && chars[i + 1] == b'.' {
188            // An invalid range: PHP warns and skips this '.' only.
189            i += 1;
190        } else {
191            mask[c as usize] = true;
192            i += 1;
193        }
194    }
195    mask
196}
197
198/// The default character list of `trim`, `ltrim` and `rtrim`: `" \n\r\t\v\0"`.
199pub const TRIM_CHARACTERS: &[u8] = b" \n\r\t\x0b\0";
200
201fn trim_mode<'a>(s: &'a [u8], characters: &[u8], left: bool, right: bool) -> &'a [u8] {
202    let mask = charmask(characters);
203    let mut start = 0;
204    let mut end = s.len();
205    if left {
206        while start < end && mask[s[start] as usize] {
207            start += 1;
208        }
209    }
210    if right {
211        while end > start && mask[s[end - 1] as usize] {
212            end -= 1;
213        }
214    }
215    &s[start..end]
216}
217
218/// PHP `trim($string, $characters)`: strips the bytes of `characters` (with
219/// `a..z` ranges, see [`charmask`]) from both ends. Pass [`TRIM_CHARACTERS`]
220/// for PHP's default.
221pub fn trim<'a>(s: &'a [u8], characters: &[u8]) -> &'a [u8] {
222    trim_mode(s, characters, true, true)
223}
224
225/// PHP `ltrim($string, $characters)`: like [`trim`], start only.
226pub fn ltrim<'a>(s: &'a [u8], characters: &[u8]) -> &'a [u8] {
227    trim_mode(s, characters, true, false)
228}
229
230/// PHP `rtrim($string, $characters)` (alias `chop`): like [`trim`], end only.
231pub fn rtrim<'a>(s: &'a [u8], characters: &[u8]) -> &'a [u8] {
232    trim_mode(s, characters, false, true)
233}
234
235// ---------------------------------------------------------------------------
236// Substrings and searching
237// ---------------------------------------------------------------------------
238
239/// PHP `substr($string, $offset, $length)`: a negative `offset` counts from
240/// the end; a negative `length` stops that many bytes before the end;
241/// `None` takes the rest. Out-of-range values clamp; never fails.
242pub fn substr(s: &[u8], offset: i64, length: Option<i64>) -> &[u8] {
243    let len = s.len() as u64;
244    let from = if offset < 0 {
245        len.saturating_sub(offset.unsigned_abs())
246    } else if offset as u64 > len {
247        return &[];
248    } else {
249        offset as u64
250    };
251    let rest = len - from;
252    let take = match length {
253        None => rest,
254        Some(l) if l < 0 => rest.saturating_sub(l.unsigned_abs()),
255        Some(l) => (l as u64).min(rest),
256    };
257    &s[from as usize..(from + take) as usize]
258}
259
260/// `php_memnstr`: first occurrence of `needle` in `haystack` (an empty needle
261/// matches at 0).
262pub(crate) fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
263    if needle.is_empty() {
264        return Some(0);
265    }
266    if needle.len() > haystack.len() {
267        return None;
268    }
269    if needle.len() == 1 {
270        return haystack.iter().position(|&b| b == needle[0]);
271    }
272    let first = needle[0];
273    let last_start = haystack.len() - needle.len();
274    let mut i = 0;
275    while i <= last_start {
276        i += haystack[i..=last_start].iter().position(|&b| b == first)?;
277        if &haystack[i..i + needle.len()] == needle {
278            return Some(i);
279        }
280        i += 1;
281    }
282    None
283}
284
285/// `zend_memnrstr`: last occurrence of `needle` that ends at or before the
286/// end of `haystack` (an empty needle matches at the end).
287pub(crate) fn rfind(haystack: &[u8], needle: &[u8]) -> Option<usize> {
288    if needle.is_empty() {
289        return Some(haystack.len());
290    }
291    if needle.len() > haystack.len() {
292        return None;
293    }
294    (0..=haystack.len() - needle.len()).rev().find(|&i| &haystack[i..i + needle.len()] == needle)
295}
296
297/// Case-insensitive (ASCII) [`find`].
298fn find_ci(haystack: &[u8], needle: &[u8]) -> Option<usize> {
299    if needle.is_empty() {
300        return Some(0);
301    }
302    if needle.len() > haystack.len() {
303        return None;
304    }
305    (0..=haystack.len() - needle.len()).find(|&i| haystack[i..i + needle.len()].eq_ignore_ascii_case(needle))
306}
307
308fn offset_error(function: &str) -> Error {
309    Error::argument(function, 3, "offset", "must be contained in argument #1 ($haystack)")
310}
311
312/// The start position for `stripos`: a negative offset counts from
313/// the end; anything outside `0..=len` is PHP's `ValueError`.
314fn forward_start(function: &str, haystack: &[u8], offset: i64) -> Result<usize, Error> {
315    let len = haystack.len() as i64;
316    let start = if offset < 0 { offset.saturating_add(len) } else { offset };
317    if start < 0 || start > len {
318        return Err(offset_error(function));
319    }
320    Ok(start as usize)
321}
322
323/// PHP `stripos($haystack, $needle, $offset)`: byte position of the first
324/// ASCII case-insensitive occurrence at or after `offset` (negative: from
325/// the end), `None` for `false`. An empty needle matches at the offset.
326pub fn stripos(haystack: &[u8], needle: &[u8], offset: i64) -> Result<Option<usize>, Error> {
327    let start = forward_start("stripos", haystack, offset)?;
328    Ok(find_ci(&haystack[start..], needle).map(|p| p + start))
329}
330
331/// PHP `str_contains`.
332pub fn str_contains(haystack: &[u8], needle: &[u8]) -> bool {
333    find(haystack, needle).is_some()
334}
335
336/// PHP `str_starts_with`.
337pub fn str_starts_with(haystack: &[u8], needle: &[u8]) -> bool {
338    haystack.starts_with(needle)
339}
340
341// ---------------------------------------------------------------------------
342// Comparison
343// ---------------------------------------------------------------------------
344
345/// `zend_binary_strcmp`: the difference of the first differing bytes, else
346/// -1/0/1 by length.
347fn compare_bytes(a: &[u8], b: &[u8], fold: bool) -> i64 {
348    for (&x, &y) in a.iter().zip(b) {
349        let (x, y) = if fold { (x.to_ascii_lowercase(), y.to_ascii_lowercase()) } else { (x, y) };
350        if x != y {
351            return x as i64 - y as i64;
352        }
353    }
354    (a.len() as i64 - b.len() as i64).signum()
355}
356
357/// PHP `strcmp`: the byte difference at the first mismatch (`"a"` vs `"c"`
358/// is `-2`), else `-1`, `0` or `1` by length.
359pub fn strcmp(a: &[u8], b: &[u8]) -> i64 {
360    compare_bytes(a, b, false)
361}
362
363/// PHP `strcasecmp`: [`strcmp`] on ASCII-lowercased bytes.
364pub fn strcasecmp(a: &[u8], b: &[u8]) -> i64 {
365    compare_bytes(a, b, true)
366}
367
368// ---------------------------------------------------------------------------
369// Replacement
370// ---------------------------------------------------------------------------
371
372/// Replaces every non-overlapping occurrence (left to right) and counts them.
373fn replace_all<'a>(subject: Cow<'a, [u8]>, search: &[u8], replace: &[u8], fold: bool) -> (Cow<'a, [u8]>, usize) {
374    if search.is_empty() || search.len() > subject.len() {
375        return (subject, 0);
376    }
377    let lowered;
378    let (hay, needle): (&[u8], Cow<'_, [u8]>) = if fold {
379        lowered = subject.to_ascii_lowercase();
380        (&lowered, Cow::Owned(search.to_ascii_lowercase()))
381    } else {
382        (&subject, Cow::Borrowed(search))
383    };
384    let mut out: Option<Vec<u8>> = None;
385    let mut count = 0;
386    let mut p = 0;
387    while let Some(i) = find(&hay[p..], &needle) {
388        let o = out.get_or_insert_with(|| Vec::with_capacity(subject.len()));
389        o.extend_from_slice(&subject[p..p + i]);
390        o.extend_from_slice(replace);
391        count += 1;
392        p += i + needle.len();
393    }
394    match out {
395        None => (subject, 0),
396        Some(mut o) => {
397            o.extend_from_slice(&subject[p..]);
398            (Cow::Owned(o), count)
399        }
400    }
401}
402
403/// PHP `str_replace($search, $replace, $subject, $count)` with string
404/// arguments: replaces every occurrence of `search` (left to right, not
405/// overlapping) and returns the result with `$count`. An empty `search`
406/// changes nothing. Valid UTF-8 arguments give valid UTF-8.
407pub fn str_replace<'a>(search: &[u8], replace: &[u8], subject: &'a [u8]) -> (Cow<'a, [u8]>, usize) {
408    replace_all(Cow::Borrowed(subject), search, replace, false)
409}
410
411/// The `$replace` of an array-`$search` `str_replace`.
412#[derive(Debug, Clone, Copy)]
413pub enum Replace<'a> {
414    /// A string: every search string is replaced by it.
415    All(&'a [u8]),
416    /// An array: the n-th search string is replaced by the n-th element (in
417    /// iteration order), or by `""` once the array runs out.
418    Each(&'a [&'a [u8]]),
419}
420
421/// PHP `str_replace` / `str_ireplace` with an array `$search`: applies each
422/// search/replacement pair in turn to the result of the previous one, skipping
423/// empty search strings, and returns the total count. The array forms of
424/// `$subject` apply this to each element (keys kept, counts summed); a string
425/// `$search` with an array `$replace` is a `TypeError` in PHP and cannot be
426/// expressed here.
427pub fn str_replace_array<'a>(
428    search: &[&[u8]],
429    replace: Replace<'_>,
430    subject: &'a [u8],
431    case_insensitive: bool,
432) -> (Cow<'a, [u8]>, usize) {
433    let mut out = Cow::Borrowed(subject);
434    let mut total = 0;
435    for (i, s) in search.iter().enumerate() {
436        let r: &[u8] = match replace {
437            Replace::All(r) => r,
438            Replace::Each(list) => list.get(i).copied().unwrap_or(b""),
439        };
440        if s.is_empty() {
441            continue;
442        }
443        let (next, n) = replace_all(out, s, r, case_insensitive);
444        out = next;
445        total += n;
446    }
447    (out, total)
448}
449
450/// PHP `strtr($string, $from, $to)`: translates each byte of `from` to the
451/// byte at the same position of `to`, ignoring the extra bytes of the longer
452/// one. When a byte appears twice in `from`, the last one wins.
453pub fn strtr<'a>(s: &'a [u8], from: &[u8], to: &[u8]) -> Cow<'a, [u8]> {
454    let n = from.len().min(to.len());
455    if s.is_empty() || n == 0 {
456        return Cow::Borrowed(s);
457    }
458    let mut table: [u8; 256] = std::array::from_fn(|i| i as u8);
459    for i in 0..n {
460        table[from[i] as usize] = to[i];
461    }
462    if s.iter().all(|&b| table[b as usize] == b) {
463        return Cow::Borrowed(s);
464    }
465    Cow::Owned(s.iter().map(|&b| table[b as usize]).collect())
466}
467
468/// Up to this many pairs, [`strtr_array`] compares keys in place instead of
469/// building a hash map.
470const STRTR_SMALL: usize = 8;
471
472/// [`strtr_array`] for a few pairs, without allocating a table: the pairs
473/// (the last of a repeated key) on the stack, and at each position the
474/// longest key that starts there.
475fn strtr_small<'a>(s: &'a [u8], pairs: &[(&[u8], &[u8])]) -> Cow<'a, [u8]> {
476    let mut table: [(&[u8], &[u8]); STRTR_SMALL] = [(&[], &[]); STRTR_SMALL];
477    let mut n = 0;
478    for &(k, v) in pairs {
479        if k.is_empty() || k.len() > s.len() {
480            continue;
481        }
482        match table[..n].iter_mut().find(|e| e.0 == k) {
483            Some(slot) => slot.1 = v,
484            None => {
485                table[n] = (k, v);
486                n += 1;
487            }
488        }
489    }
490    let table = &table[..n];
491    let Some(minlen) = table.iter().map(|e| e.0.len()).min() else { return Cow::Borrowed(s) };
492    let mut out: Option<Vec<u8>> = None;
493    let (mut pos, mut old) = (0, 0);
494    while pos + minlen <= s.len() {
495        let rest = &s[pos..];
496        let best = table.iter().filter(|e| rest.starts_with(e.0)).max_by_key(|e| e.0.len());
497        match best {
498            Some(&(k, v)) => {
499                let o = out.get_or_insert_with(|| Vec::with_capacity(s.len() + v.len()));
500                o.extend_from_slice(&s[old..pos]);
501                o.extend_from_slice(v);
502                pos += k.len();
503                old = pos;
504            }
505            None => pos += 1,
506        }
507    }
508    match out {
509        None => Cow::Borrowed(s),
510        Some(mut o) => {
511            o.extend_from_slice(&s[old..]);
512            Cow::Owned(o)
513        }
514    }
515}
516
517/// PHP `strtr($string, $replace_pairs)`: at each position replaces the
518/// longest key that matches, then continues after it; replaced text is never
519/// rescanned. Empty keys are ignored (PHP warns). `pairs` is the array in
520/// order, keys as PHP strings (integer keys as their decimal form); when a
521/// key repeats, the last pair wins, as in a PHP array.
522pub fn strtr_array<'a>(s: &'a [u8], pairs: &[(&[u8], &[u8])]) -> Cow<'a, [u8]> {
523    if s.is_empty() || pairs.is_empty() {
524        return Cow::Borrowed(s);
525    }
526    if pairs.len() <= STRTR_SMALL {
527        return strtr_small(s, pairs);
528    }
529    let mut map: std::collections::HashMap<&[u8], &[u8]> = std::collections::HashMap::with_capacity(pairs.len());
530    let (mut minlen, mut maxlen) = (usize::MAX, 0);
531    for (k, v) in pairs {
532        map.insert(k, v);
533    }
534    for k in map.keys() {
535        if k.is_empty() || k.len() > s.len() {
536            continue;
537        }
538        minlen = minlen.min(k.len());
539        maxlen = maxlen.max(k.len());
540    }
541    if minlen > maxlen {
542        return Cow::Borrowed(s);
543    }
544    let mut out: Option<Vec<u8>> = None;
545    let (mut pos, mut old) = (0, 0);
546    while pos + minlen <= s.len() {
547        let mut len = maxlen.min(s.len() - pos);
548        let mut matched = false;
549        while len >= minlen {
550            if let Some(v) = map.get(&s[pos..pos + len]) {
551                let o = out.get_or_insert_with(|| Vec::with_capacity(s.len()));
552                o.extend_from_slice(&s[old..pos]);
553                o.extend_from_slice(v);
554                old = pos + len;
555                pos = old;
556                matched = true;
557                break;
558            }
559            len -= 1;
560        }
561        if !matched {
562            pos += 1;
563        }
564    }
565    match out {
566        None => Cow::Borrowed(s),
567        Some(mut o) => {
568            o.extend_from_slice(&s[old..]);
569            Cow::Owned(o)
570        }
571    }
572}
573
574// ---------------------------------------------------------------------------
575// Splitting and joining
576// ---------------------------------------------------------------------------
577
578/// `explode`'s default `$limit` (`PHP_INT_MAX`): no limit.
579pub const NO_LIMIT: i64 = i64::MAX;
580
581/// PHP `explode($separator, $string, $limit)`: the pieces between occurrences
582/// of `separator`. A positive `limit` returns at most that many pieces (the
583/// last holds the rest); a negative one drops that many pieces from the end;
584/// `0` is `1`. An empty string gives `[""]` (or `[]` for a negative limit).
585pub fn explode<'a>(separator: &[u8], s: &'a [u8], limit: i64) -> Result<Vec<&'a [u8]>, Error> {
586    if separator.is_empty() {
587        return Err(Error::argument("explode", 1, "separator", "must not be empty"));
588    }
589    if s.is_empty() {
590        return Ok(if limit >= 0 { vec![s] } else { Vec::new() });
591    }
592    if limit > 1 {
593        let mut out = Vec::new();
594        let mut p = 0;
595        let mut remaining = limit;
596        while let Some(i) = find(&s[p..], separator) {
597            out.push(&s[p..p + i]);
598            p += i + separator.len();
599            remaining -= 1;
600            if remaining <= 1 {
601                break;
602            }
603        }
604        out.push(&s[p..]);
605        Ok(out)
606    } else if limit < 0 {
607        let mut pieces = Vec::new();
608        let mut p = 0;
609        while let Some(i) = find(&s[p..], separator) {
610            pieces.push(&s[p..p + i]);
611            p += i + separator.len();
612        }
613        if pieces.is_empty() {
614            return Ok(Vec::new());
615        }
616        pieces.push(&s[p..]);
617        let keep = (pieces.len() as i64).saturating_add(limit).max(0) as usize;
618        pieces.truncate(keep);
619        Ok(pieces)
620    } else {
621        Ok(vec![s])
622    }
623}
624
625/// PHP's string conversion of a value as string functions perform it
626/// (`zval_get_string`): `null` and `false` are `""`, `true` is `"1"`,
627/// integers in decimal, floats at the `precision` setting ([`number::to_string`]),
628/// arrays `"Array"` (PHP also warns). A `stdClass` (an empty JSON object)
629/// has no string form: PHP's `Error`.
630pub fn to_php_string(value: &Value) -> Result<Cow<'_, str>, Error> {
631    Ok(match value {
632        Value::Null | Value::Bool(false) => Cow::Borrowed(""),
633        Value::Bool(true) => Cow::Borrowed("1"),
634        Value::Number(n) => Cow::Owned(match crate::value::json_number(n) {
635            crate::value::Number::Int(i) => i.to_string(),
636            crate::value::Number::Float(f) => number::to_string(f),
637        }),
638        Value::String(s) => Cow::Borrowed(s.as_str()),
639        Value::Array(_) => Cow::Borrowed("Array"),
640        Value::Object(o) if o.is_empty() => {
641            return Err(Error::Error("Object of class stdClass could not be converted to string".into()));
642        }
643        Value::Object(_) => Cow::Borrowed("Array"),
644    })
645}
646
647/// PHP `escapeshellarg($arg)` on Unix: the argument between single quotes,
648/// each `'` written as `'\''`, so a POSIX shell reads it back as one word.
649///
650/// Bytes are read as multibyte characters of the locale PHP runs in
651/// (`C.UTF-8`, PHP's default since 8.0): a valid UTF-8 character is copied
652/// whole, and a byte that does not start one is dropped (`mblen()` fails on
653/// it). A NUL byte raises `ValueError`, as in PHP.
654///
655/// ```
656/// use php_std::string::escapeshellarg;
657///
658/// assert_eq!(escapeshellarg(b"it's").unwrap(), b"'it'\\''s'");
659/// assert_eq!(escapeshellarg(b"caf\xc3\xa9\xff").unwrap(), "'caf\u{e9}'".as_bytes());
660/// assert_eq!(escapeshellarg(b"a\0b").unwrap_err().php_class(), "ValueError");
661/// ```
662pub fn escapeshellarg(arg: &[u8]) -> Result<Vec<u8>, Error> {
663    if arg.contains(&0) {
664        return Err(Error::argument("escapeshellarg", 1, "arg", "must not contain any null bytes"));
665    }
666    let mut out = Vec::with_capacity(arg.len() + 2);
667    out.push(b'\'');
668    for chunk in arg.utf8_chunks() {
669        for &b in chunk.valid().as_bytes() {
670            if b == b'\'' {
671                out.extend_from_slice(b"'\\''");
672            } else {
673                out.push(b);
674            }
675        }
676    }
677    out.push(b'\'');
678    Ok(out)
679}
680
681/// PHP `addcslashes($string, $characters)`: backslash-escapes the bytes of
682/// `characters` (with `a..z` ranges); those outside printable ASCII become
683/// `\n`, `\t`, `\r`, `\a`, `\v`, `\b`, `\f` or a 3-digit octal escape.
684pub fn addcslashes<'a>(s: &'a [u8], characters: &[u8]) -> Cow<'a, [u8]> {
685    if s.is_empty() || characters.is_empty() {
686        return Cow::Borrowed(s);
687    }
688    let mask = charmask(characters);
689    let mut out = Vec::with_capacity(s.len() * 2);
690    for &c in s {
691        if mask[c as usize] {
692            out.push(b'\\');
693            if !(32..=126).contains(&c) {
694                match c {
695                    b'\n' => out.push(b'n'),
696                    b'\t' => out.push(b't'),
697                    b'\r' => out.push(b'r'),
698                    0x07 => out.push(b'a'),
699                    0x0b => out.push(b'v'),
700                    0x08 => out.push(b'b'),
701                    0x0c => out.push(b'f'),
702                    _ => out.extend_from_slice(format!("{c:03o}").as_bytes()),
703                }
704                continue;
705            }
706        }
707        out.push(c);
708    }
709    Cow::Owned(out)
710}
711
712/// PHP `stripcslashes`: decodes C-style escapes (`\n`, `\t`, `\xhh`, `\ooo`,
713/// ...); an unknown escape yields the escaped byte.
714pub fn stripcslashes(s: &[u8]) -> Vec<u8> {
715    let mut out = Vec::with_capacity(s.len());
716    let end = s.len();
717    let mut i = 0;
718    while i < end {
719        if s[i] == b'\\' && i + 1 < end {
720            i += 1;
721            match s[i] {
722                b'n' => out.push(b'\n'),
723                b'r' => out.push(b'\r'),
724                b'a' => out.push(0x07),
725                b't' => out.push(b'\t'),
726                b'v' => out.push(0x0b),
727                b'b' => out.push(0x08),
728                b'f' => out.push(0x0c),
729                b'\\' => out.push(b'\\'),
730                b'x' if i + 1 < end && s[i + 1].is_ascii_hexdigit() => {
731                    let mut v = hex_value(s[i + 1]);
732                    i += 1;
733                    if i + 1 < end && s[i + 1].is_ascii_hexdigit() {
734                        v = v * 16 + hex_value(s[i + 1]);
735                        i += 1;
736                    }
737                    out.push(v);
738                }
739                _ => {
740                    let start = i;
741                    let mut v: u32 = 0;
742                    while i < end && (b'0'..=b'7').contains(&s[i]) && i - start < 3 {
743                        v = v * 8 + (s[i] - b'0') as u32;
744                        i += 1;
745                    }
746                    if i > start {
747                        out.push(v as u8);
748                        i -= 1;
749                    } else {
750                        out.push(s[i]);
751                    }
752                }
753            }
754        } else {
755            out.push(s[i]);
756        }
757        i += 1;
758    }
759    out
760}
761
762pub(crate) fn hex_value(c: u8) -> u8 {
763    match c {
764        b'0'..=b'9' => c - b'0',
765        b'a'..=b'f' => c - b'a' + 10,
766        _ => c - b'A' + 10,
767    }
768}
769
770// ---------------------------------------------------------------------------
771// ctype (C locale)
772// ---------------------------------------------------------------------------
773
774fn ctype(s: &[u8], f: impl Fn(u8) -> bool) -> bool {
775    !s.is_empty() && s.iter().all(|&c| f(c))
776}
777
778/// A `ctype_*` function, for calls with a value that may not be a string.
779#[derive(Debug, Clone, Copy, PartialEq, Eq)]
780pub enum Ctype {
781    /// `ctype_alnum()`: letters and digits.
782    Alnum,
783    /// `ctype_digit()`: decimal digits.
784    Digit,
785    /// `ctype_xdigit()`: hexadecimal digits.
786    Xdigit,
787}
788
789impl Ctype {
790    /// The function on a string (the supported call).
791    pub fn on_bytes(self, s: &[u8]) -> bool {
792        match self {
793            Ctype::Alnum => ctype_alnum(s),
794            Ctype::Digit => ctype_digit(s),
795            Ctype::Xdigit => ctype_xdigit(s),
796        }
797    }
798
799    /// The function on an integer (deprecated in PHP 8.1, still supported):
800    /// -128..=255 is a character code (negatives + 256); a larger integer is
801    /// true, as every class here contains digits (`ext/ctype`'s
802    /// `allow_digits`), and a smaller one false (none contains `-`).
803    pub fn on_int(self, n: i64) -> bool {
804        match n {
805            0..=255 => self.on_bytes(&[n as u8]),
806            -128..=-1 => self.on_bytes(&[(n + 256) as u8]),
807            _ => n > 0,
808        }
809    }
810}
811
812/// PHP `ctype_alnum` on a string: non-empty and all ASCII letters or digits.
813pub fn ctype_alnum(s: &[u8]) -> bool {
814    ctype(s, |c| c.is_ascii_alphanumeric())
815}
816
817/// PHP `ctype_digit` on a string: non-empty and all `0-9`.
818pub fn ctype_digit(s: &[u8]) -> bool {
819    ctype(s, |c| c.is_ascii_digit())
820}
821
822/// PHP `ctype_xdigit` on a string: non-empty and all hexadecimal digits.
823pub fn ctype_xdigit(s: &[u8]) -> bool {
824    ctype(s, |c| c.is_ascii_hexdigit())
825}
826
827// ---------------------------------------------------------------------------
828// crypt(), password_hash(), password_verify()
829// (ext/standard/crypt.c, crypt_blowfish.c, crypt_sha256.c, crypt_sha512.c,
830// php_crypt_r.c, password.c)
831// ---------------------------------------------------------------------------
832
833/// `PHP_MAX_SALT_LEN`: `crypt()` reads at most this much of the salt.
834const PHP_MAX_SALT_LEN: usize = 123;
835/// The `./0-9A-Za-z` alphabet of MD5 and SHA crypt.
836const CRYPT_ITOA64: &[u8; 64] = b"./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
837/// crypt_blowfish's `./A-Za-z0-9` alphabet.
838const BF_ITOA64: &[u8; 64] = b"./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
839
840/// A C string: the bytes before the first NUL.
841fn c_str(s: &[u8]) -> &[u8] {
842    s.iter().position(|b| *b == 0).map_or(s, |n| &s[..n])
843}
844
845/// PHP `crypt($string, $salt)`: the hash, or `*0` (`*1` when the salt starts
846/// with `*0`) where the salt names no supported algorithm or is invalid.
847///
848/// The algorithms are PHP's own: blowfish (`$2a$`, `$2b$`, `$2x$`, `$2y$`),
849/// MD5 (`$1$`), SHA-256 (`$5$`), SHA-512 (`$6$`), and FreeSec's DES
850/// (two salt characters) and extended DES (`_`).
851pub fn crypt(string: &[u8], salt: &[u8]) -> Vec<u8> {
852    let salt = &salt[..salt.len().min(PHP_MAX_SALT_LEN)];
853    match php_crypt(string, salt) {
854        Some(hash) => hash,
855        None if c_str(salt).starts_with(b"*0") => b"*1".to_vec(),
856        None => b"*0".to_vec(),
857    }
858}
859
860/// `php_crypt()`: `crypt()` without the failure strings. Both arguments are
861/// C strings (they end at the first NUL).
862pub fn php_crypt(password: &[u8], salt: &[u8]) -> Option<Vec<u8>> {
863    let (password, salt) = (c_str(password), c_str(salt));
864    let at = |i: usize| salt.get(i).copied().unwrap_or(0);
865    if at(0) == b'*' && (at(1) == b'0' || at(1) == b'1') {
866        return None;
867    }
868    if salt.starts_with(b"$1$") {
869        return Some(md5_crypt(password, salt));
870    }
871    if salt.starts_with(b"$6$") {
872        return sha_crypt::<sha2::Sha512>(password, salt, b"$6$", &SHA512_ORDER, [0, 0, 63], 2, true);
873    }
874    if salt.starts_with(b"$5$") {
875        return sha_crypt::<sha2::Sha256>(password, salt, b"$5$", &SHA256_ORDER, [0, 31, 30], 3, false);
876    }
877    if at(0) == b'$' && at(1) == b'2' && at(2) != 0 && at(3) == b'$' {
878        return blowfish_crypt(password, salt);
879    }
880    let valid = |c: u8| matches!(c, b'.'..=b'9' | b'A'..=b'Z' | b'a'..=b'z');
881    if at(0) == b'_' || (valid(at(0)) && valid(at(1))) {
882        return des_crypt(password, salt);
883    }
884    None
885}
886
887/// `php_md5_crypt_r()`: `$1$` hashes (salt up to 8 characters).
888fn md5_crypt(password: &[u8], salt: &[u8]) -> Vec<u8> {
889    use md5::{Digest, Md5};
890    let sp = salt.strip_prefix(b"$1$").unwrap_or(salt);
891    let sl = sp.iter().take(8).take_while(|b| **b != b'$').count();
892    let sp = &sp[..sl];
893    let mut ctx = Md5::new();
894    ctx.update(password);
895    ctx.update(b"$1$");
896    ctx.update(sp);
897    let mut final_ = Md5::new().chain_update(password).chain_update(sp).chain_update(password).finalize();
898    let mut pl = password.len() as isize;
899    while pl > 0 {
900        ctx.update(&final_[..pl.min(16) as usize]);
901        pl -= 16;
902    }
903    final_.iter_mut().for_each(|b| *b = 0);
904    let mut i = password.len();
905    while i != 0 {
906        if i & 1 != 0 {
907            ctx.update(&final_[..1]);
908        } else {
909            ctx.update(&password[..1]);
910        }
911        i >>= 1;
912    }
913    let mut final_ = ctx.finalize();
914    for i in 0..1000 {
915        let mut ctx1 = Md5::new();
916        if i & 1 != 0 {
917            ctx1.update(password);
918        } else {
919            ctx1.update(final_);
920        }
921        if i % 3 != 0 {
922            ctx1.update(sp);
923        }
924        if i % 7 != 0 {
925            ctx1.update(password);
926        }
927        if i & 1 != 0 {
928            ctx1.update(final_);
929        } else {
930            ctx1.update(password);
931        }
932        final_ = ctx1.finalize();
933    }
934    let mut out = b"$1$".to_vec();
935    out.extend_from_slice(sp);
936    out.push(b'$');
937    let to64 = |out: &mut Vec<u8>, mut v: u32, n: usize| {
938        for _ in 0..n {
939            out.push(CRYPT_ITOA64[(v & 0x3f) as usize]);
940            v >>= 6;
941        }
942    };
943    let f = |i: usize| u32::from(final_[i]);
944    for [a, b, c] in [[0, 6, 12], [1, 7, 13], [2, 8, 14], [3, 9, 15], [4, 10, 5]] {
945        to64(&mut out, (f(a) << 16) | (f(b) << 8) | f(c), 4);
946    }
947    to64(&mut out, f(11), 2);
948    out
949}
950
951/// The byte triples SHA-512 crypt encodes, in order.
952const SHA512_ORDER: [[usize; 3]; 21] = [
953    [0, 21, 42],
954    [22, 43, 1],
955    [44, 2, 23],
956    [3, 24, 45],
957    [25, 46, 4],
958    [47, 5, 26],
959    [6, 27, 48],
960    [28, 49, 7],
961    [50, 8, 29],
962    [9, 30, 51],
963    [31, 52, 10],
964    [53, 11, 32],
965    [12, 33, 54],
966    [34, 55, 13],
967    [56, 14, 35],
968    [15, 36, 57],
969    [37, 58, 16],
970    [59, 17, 38],
971    [18, 39, 60],
972    [40, 61, 19],
973    [62, 20, 41],
974];
975
976/// The byte triples SHA-256 crypt encodes, in order.
977const SHA256_ORDER: [[usize; 3]; 10] = [
978    [0, 10, 20],
979    [21, 1, 11],
980    [12, 22, 2],
981    [3, 13, 23],
982    [24, 4, 14],
983    [15, 25, 5],
984    [6, 16, 26],
985    [27, 7, 17],
986    [18, 28, 8],
987    [9, 19, 29],
988];
989
990/// `strtoul(s, &end, 10)`: the value (saturated) and the bytes consumed,
991/// 0 when there are no digits.
992fn strtoul(s: &[u8]) -> (u64, usize) {
993    let mut i = s.iter().take_while(|b| matches!(b, b' ' | b'\t' | b'\n' | b'\x0b' | b'\x0c' | b'\r')).count();
994    let negative = match s.get(i) {
995        Some(b'-') => {
996            i += 1;
997            true
998        }
999        Some(b'+') => {
1000            i += 1;
1001            false
1002        }
1003        _ => false,
1004    };
1005    let digits = s[i..].iter().take_while(|b| b.is_ascii_digit()).count();
1006    if digits == 0 {
1007        return (0, 0);
1008    }
1009    let mut value: u64 = 0;
1010    let mut overflow = false;
1011    for d in &s[i..i + digits] {
1012        match value.checked_mul(10).and_then(|v| v.checked_add(u64::from(d - b'0'))) {
1013            Some(v) => value = v,
1014            None => overflow = true,
1015        }
1016    }
1017    let value = if overflow {
1018        u64::MAX
1019    } else if negative {
1020        value.wrapping_neg()
1021    } else {
1022        value
1023    };
1024    (value, i + digits)
1025}
1026
1027/// `php_sha256_crypt_r()` / `php_sha512_crypt_r()`.
1028fn sha_crypt<D: sha2::Digest + Clone>(
1029    key: &[u8],
1030    salt: &[u8],
1031    prefix: &[u8],
1032    order: &[[usize; 3]],
1033    last: [usize; 3],
1034    last_chars: usize,
1035    bounded: bool,
1036) -> Option<Vec<u8>> {
1037    let size = <D as sha2::Digest>::output_size();
1038    let mut salt = salt.strip_prefix(prefix).unwrap_or(salt);
1039    let mut rounds = 5000u64;
1040    let mut custom = false;
1041    if let Some(num) = salt.strip_prefix(b"rounds=") {
1042        let (value, used) = strtoul(num);
1043        if num.get(used) == Some(&b'$') {
1044            salt = &num[used + 1..];
1045            if !(1000..=999_999_999).contains(&value) {
1046                return None;
1047            }
1048            rounds = value;
1049            custom = true;
1050        }
1051    }
1052    let salt_len = salt.iter().take_while(|b| **b != b'$').count().min(16);
1053    let salt = &salt[..salt_len];
1054    let key_len = key.len();
1055    // The output must fit PHP_MAX_SALT_LEN with its NUL (only SHA-512 with
1056    // 9-digit rounds and a 16-byte salt does not): PHP computes, then fails.
1057    let rounds_len = if custom { format!("rounds={rounds}$").len() } else { 0 };
1058    let chars = order.len() * 4 + last_chars;
1059    if prefix.len() + rounds_len + salt_len + 1 + chars >= PHP_MAX_SALT_LEN {
1060        return None;
1061    }
1062
1063    let mut ctx = D::new();
1064    ctx.update(key);
1065    ctx.update(salt);
1066    let alt = D::new().chain_update(key).chain_update(salt).chain_update(key).finalize();
1067    let mut cnt = key_len;
1068    while cnt > size {
1069        ctx.update(&alt);
1070        cnt -= size;
1071    }
1072    ctx.update(&alt[..cnt]);
1073    let mut cnt = key_len;
1074    while cnt > 0 {
1075        if cnt & 1 != 0 {
1076            ctx.update(&alt);
1077        } else {
1078            ctx.update(key);
1079        }
1080        cnt >>= 1;
1081    }
1082    let mut alt_result = ctx.finalize();
1083
1084    let mut dp = D::new();
1085    for _ in 0..key_len {
1086        dp.update(key);
1087    }
1088    let temp = dp.finalize();
1089    let p_bytes: Vec<u8> = (0..key_len).map(|i| temp[i % size]).collect();
1090    let mut ds = D::new();
1091    for _ in 0..16 + usize::from(alt_result[0]) {
1092        ds.update(salt);
1093    }
1094    let temp = ds.finalize();
1095    let s_bytes: Vec<u8> = (0..salt_len).map(|i| temp[i % size]).collect();
1096
1097    for cnt in 0..rounds {
1098        let mut ctx = D::new();
1099        if cnt & 1 != 0 {
1100            ctx.update(&p_bytes);
1101        } else {
1102            ctx.update(&alt_result);
1103        }
1104        if cnt % 3 != 0 {
1105            ctx.update(&s_bytes);
1106        }
1107        if cnt % 7 != 0 {
1108            ctx.update(&p_bytes);
1109        }
1110        if cnt & 1 != 0 {
1111            ctx.update(&alt_result);
1112        } else {
1113            ctx.update(&p_bytes);
1114        }
1115        alt_result = ctx.finalize();
1116    }
1117
1118    // The result goes into a PHP_MAX_SALT_LEN buffer, which must keep room for the NUL.
1119    let mut buflen = PHP_MAX_SALT_LEN as isize - prefix.len() as isize;
1120    let mut out = prefix.to_vec();
1121    if custom {
1122        let r = format!("rounds={rounds}$");
1123        buflen -= r.len() as isize;
1124        out.extend_from_slice(r.as_bytes());
1125    }
1126    let n = salt_len.min(buflen.max(0) as usize);
1127    out.extend_from_slice(&salt[..n]);
1128    buflen -= n as isize;
1129    if buflen > 0 {
1130        out.push(b'$');
1131        buflen -= 1;
1132    }
1133    let mut b64 = |out: &mut Vec<u8>, [b2, b1, b0]: [u32; 3], n: usize| {
1134        let mut w = (b2 << 16) | (b1 << 8) | b0;
1135        for _ in 0..n {
1136            if buflen <= 0 {
1137                break;
1138            }
1139            out.push(CRYPT_ITOA64[(w & 0x3f) as usize]);
1140            buflen -= 1;
1141            w >>= 6;
1142        }
1143    };
1144    let r = |i: usize| u32::from(alt_result[i]);
1145    for [a, b, c] in order {
1146        b64(&mut out, [r(*a), r(*b), r(*c)], 4);
1147    }
1148    let [_, b, c] = last;
1149    let triple = if bounded { [0, 0, r(c)] } else { [0, r(b), r(c)] };
1150    b64(&mut out, triple, last_chars);
1151    if buflen <= 0 {
1152        return None;
1153    }
1154    Some(out)
1155}
1156
1157/// crypt_blowfish's `BF_decode` of the 22-character salt (the last
1158/// character's low bits are ignored).
1159fn bf_decode_salt(src: &[u8]) -> Option<[u8; 16]> {
1160    let get = |i: usize| src.get(i).and_then(|c| BF_ITOA64.iter().position(|x| x == c)).map(|p| p as u32);
1161    let mut out = [0u8; 16];
1162    let (mut n, mut i) = (0, 0);
1163    while n < 16 {
1164        let (c1, c2) = (get(i)?, get(i + 1)?);
1165        out[n] = ((c1 << 2) | ((c2 & 0x30) >> 4)) as u8;
1166        n += 1;
1167        if n >= 16 {
1168            break;
1169        }
1170        let c3 = get(i + 2)?;
1171        out[n] = (((c2 & 0x0f) << 4) | ((c3 & 0x3c) >> 2)) as u8;
1172        n += 1;
1173        let c4 = get(i + 3)?;
1174        out[n] = (((c3 & 0x03) << 6) | c4) as u8;
1175        n += 1;
1176        i += 4;
1177    }
1178    Some(out)
1179}
1180
1181/// crypt_blowfish's `BF_encode`.
1182fn bf_encode(src: &[u8]) -> Vec<u8> {
1183    let mut out = Vec::with_capacity(src.len() * 4 / 3 + 2);
1184    let mut i = 0;
1185    while i < src.len() {
1186        let c1 = u32::from(src[i]);
1187        i += 1;
1188        out.push(BF_ITOA64[(c1 >> 2) as usize]);
1189        let mut c1 = (c1 & 0x03) << 4;
1190        if i >= src.len() {
1191            out.push(BF_ITOA64[c1 as usize]);
1192            break;
1193        }
1194        let c2 = u32::from(src[i]);
1195        i += 1;
1196        c1 |= c2 >> 4;
1197        out.push(BF_ITOA64[c1 as usize]);
1198        c1 = (c2 & 0x0f) << 2;
1199        if i >= src.len() {
1200            out.push(BF_ITOA64[c1 as usize]);
1201            break;
1202        }
1203        let c2 = u32::from(src[i]);
1204        i += 1;
1205        c1 |= c2 >> 6;
1206        out.push(BF_ITOA64[c1 as usize]);
1207        out.push(BF_ITOA64[(c2 & 0x3f) as usize]);
1208    }
1209    out
1210}
1211
1212/// `BF_set_key()`: the 18 key words for the expensive loop and for the
1213/// initial salted expansion, serialised (the key with its NUL, cycled over
1214/// 72 bytes). `bug` (`$2x$`) sign-extends 8-bit characters as old
1215/// crypt_blowfish did; `safety` (`$2a$`) flips bit 16 of the initial first
1216/// word when the buggy and the correct schedules coincide despite a sign
1217/// extension, so such keys cannot collide with buggy hashes.
1218fn bf_set_key(key: &[u8], bug: bool, safety: bool) -> ([u8; 72], [u8; 72]) {
1219    let mut expanded = [0u8; 72];
1220    let (mut sign, mut diff) = (0u32, 0u32);
1221    let mut ptr = 0usize;
1222    for word in 0..18 {
1223        let (mut correct, mut buggy) = (0u32, 0u32);
1224        for j in 0..4 {
1225            let c = key.get(ptr).copied().unwrap_or(0);
1226            correct = (correct << 8) | u32::from(c);
1227            buggy = (buggy << 8) | (c as i8 as i32 as u32);
1228            if j != 0 {
1229                sign |= buggy & 0x80;
1230            }
1231            ptr = if c == 0 { 0 } else { ptr + 1 };
1232        }
1233        diff |= correct ^ buggy;
1234        let w = if bug { buggy } else { correct };
1235        expanded[word * 4..word * 4 + 4].copy_from_slice(&w.to_be_bytes());
1236    }
1237    diff |= diff >> 16;
1238    diff &= 0xffff;
1239    diff = diff.wrapping_add(0xffff);
1240    sign <<= 9;
1241    sign &= !diff & if safety { 0x10000 } else { 0 };
1242    let mut initial = expanded;
1243    let first = u32::from_be_bytes([initial[0], initial[1], initial[2], initial[3]]) ^ sign;
1244    initial[..4].copy_from_slice(&first.to_be_bytes());
1245    (expanded, initial)
1246}
1247
1248/// EksBlowfish and the 64-fold encryption of "OrpheanBeholderScryDoubt".
1249fn bf_crypt_raw(cost: u32, salt: &[u8; 16], expanded: &[u8; 72], initial: &[u8; 72]) -> [u8; 24] {
1250    let mut state = blowfish::Blowfish::bc_init_state();
1251    state.salted_expand_key(salt, initial);
1252    for _ in 0..1u64 << cost {
1253        state.bc_expand_key(expanded);
1254        state.bc_expand_key(salt);
1255    }
1256    let mut ctext = [0x4f72_7068, 0x6561_6e42, 0x6568_6f6c, 0x6465_7253, 0x6372_7944, 0x6f75_6274];
1257    let mut output = [0u8; 24];
1258    for i in (0..6).step_by(2) {
1259        for _ in 0..64 {
1260            let [l, r] = state.bc_encrypt([ctext[i], ctext[i + 1]]);
1261            ctext[i] = l;
1262            ctext[i + 1] = r;
1263        }
1264        output[i * 4..i * 4 + 4].copy_from_slice(&ctext[i].to_be_bytes());
1265        output[(i + 1) * 4..(i + 1) * 4 + 4].copy_from_slice(&ctext[i + 1].to_be_bytes());
1266    }
1267    output
1268}
1269
1270/// `php_crypt_blowfish_rn()`: `$2a$`, `$2b$`, `$2x$` and `$2y$` hashes.
1271fn blowfish_crypt(key: &[u8], setting: &[u8]) -> Option<Vec<u8>> {
1272    let at = |i: usize| setting.get(i).copied().unwrap_or(0);
1273    let (bug, safety) = match at(2) {
1274        b'a' => (false, true),
1275        b'b' | b'y' => (false, false),
1276        b'x' => (true, false),
1277        _ => return None,
1278    };
1279    if at(3) != b'$'
1280        || !(b'0'..=b'3').contains(&at(4))
1281        || !at(5).is_ascii_digit()
1282        || (at(4) == b'3' && at(5) > b'1')
1283        || at(6) != b'$'
1284    {
1285        return None;
1286    }
1287    let cost = u32::from(at(4) - b'0') * 10 + u32::from(at(5) - b'0');
1288    if cost < 4 || setting.len() < 29 {
1289        return None;
1290    }
1291    let salt = bf_decode_salt(&setting[7..29])?;
1292    let (expanded, initial) = bf_set_key(key, bug, safety);
1293    let raw = bf_crypt_raw(cost, &salt, &expanded, &initial);
1294    let mut out = setting[..28].to_vec();
1295    let last = BF_ITOA64.iter().position(|c| *c == setting[28])?;
1296    out.push(BF_ITOA64[last & 0x30]);
1297    out.extend_from_slice(&bf_encode(&raw[..23]));
1298    Some(out)
1299}
1300
1301/// `password_hash($password, PASSWORD_BCRYPT, ['cost' => $cost])` with
1302/// `salt` (16 random bytes in PHP).
1303pub fn password_hash_bcrypt(password: &[u8], cost: i64, salt: &[u8; 16]) -> Result<Vec<u8>, Error> {
1304    if !(4..=31).contains(&cost) {
1305        return Err(Error::Value(format!("Invalid bcrypt cost parameter specified: {cost}")));
1306    }
1307    if password.contains(&0) {
1308        return Err(Error::Value("Bcrypt password must not contain null character".into()));
1309    }
1310    let mut setting = format!("$2y${cost:02}$").into_bytes();
1311    setting.extend_from_slice(&bf_encode(salt)[..22]);
1312    blowfish_crypt(password, &setting).ok_or_else(|| Error::Value("Invalid bcrypt cost parameter specified".into()))
1313}
1314
1315/// The cost of allocating Argon2 memory PHP would fail to allocate: beyond
1316/// this (KiB) the port reports an allocation error instead of trying.
1317const ARGON2_MEMORY_LIMIT: u32 = 1 << 22;
1318
1319/// `password_hash($password, PASSWORD_ARGON2ID, $options)` with the
1320/// options' `memory_cost`, `time_cost` and `threads` (already cast to int)
1321/// and `salt` (16 random bytes in PHP).
1322pub fn password_hash_argon2id(
1323    password: &[u8],
1324    memory_cost: i64,
1325    time_cost: i64,
1326    threads: i64,
1327    salt: &[u8; 16],
1328) -> Result<Vec<u8>, Error> {
1329    use crate::argon2::{Algorithm, Params, hash};
1330    if !(8..=0xFFFF_FFFF).contains(&memory_cost) {
1331        return Err(Error::Value("Memory cost is outside of allowed memory range".into()));
1332    }
1333    if !(1..=0xFFFF_FFFF).contains(&time_cost) {
1334        return Err(Error::Value("Time cost is outside of allowed time range".into()));
1335    }
1336    if !(1..=0xFF_FFFF).contains(&threads) {
1337        return Err(Error::Value("Invalid number of threads".into()));
1338    }
1339    let (m, t, p) = (memory_cost as u32, time_cost as u32, threads as u32);
1340    if m < 8 * p {
1341        return Err(Error::Value("Memory cost is too small".into()));
1342    }
1343    let failed = || Error::Value("Memory allocation error".into());
1344    if m > ARGON2_MEMORY_LIMIT {
1345        return Err(failed());
1346    }
1347    let params = Params::new(Algorithm::Argon2id, 0x13, m, t, p).ok_or_else(failed)?;
1348    let mut out = [0u8; 32];
1349    hash(&params, password, salt, &mut out).ok_or_else(failed)?;
1350    let b64 = |b: &[u8]| crate::encoding::base64_encode(b).trim_end_matches('=').to_owned();
1351    Ok(format!("$argon2id$v=19$m={m},t={t},p={p}${}${}", b64(salt), b64(&out)).into_bytes())
1352}
1353
1354/// PHP `password_verify($password, $hash)`.
1355pub fn password_verify(password: &[u8], hash: &[u8]) -> bool {
1356    match password_ident(hash) {
1357        Some(b"argon2i") => argon2_verify(password, hash, crate::argon2::Algorithm::Argon2i, b"argon2i"),
1358        Some(b"argon2id") => argon2_verify(password, hash, crate::argon2::Algorithm::Argon2id, b"argon2id"),
1359        _ => {
1360            // php_password_bcrypt_verify: php_crypt() and a constant-time compare.
1361            let Some(computed) = php_crypt(password, hash) else {
1362                return false;
1363            };
1364            if hash.len() < 13 {
1365                return false;
1366            }
1367            computed.len() == hash.len() && computed.iter().zip(hash).fold(0u8, |acc, (a, b)| acc | (a ^ b)) == 0
1368        }
1369    }
1370}
1371
1372/// `php_password_algo_extract_ident`: between the first byte and the next `$`.
1373fn password_ident(hash: &[u8]) -> Option<&[u8]> {
1374    if hash.len() < 3 {
1375        return None;
1376    }
1377    let rest = &hash[1..];
1378    rest.iter().position(|b| *b == b'$').map(|end| &rest[..end])
1379}
1380
1381/// libargon2's `decode_decimal`: digits without leading zeros.
1382fn argon2_decimal(s: &[u8]) -> Option<(u64, &[u8])> {
1383    let len = s.iter().take_while(|b| b.is_ascii_digit()).count();
1384    if len == 0 || (s[0] == b'0' && len > 1) {
1385        return None;
1386    }
1387    let mut acc: u64 = 0;
1388    for d in &s[..len] {
1389        acc = acc.checked_mul(10)?.checked_add(u64::from(d - b'0'))?;
1390    }
1391    Some((acc, &s[len..]))
1392}
1393
1394fn argon2_u32<'a>(s: &'a [u8], prefix: &[u8]) -> Option<(u32, &'a [u8])> {
1395    let (v, rest) = argon2_decimal(s.strip_prefix(prefix)?)?;
1396    Some((u32::try_from(v).ok()?, rest))
1397}
1398
1399/// libargon2's `from_base64`: standard alphabet, no padding, zero trailing bits.
1400fn argon2_base64(s: &[u8]) -> Option<(Vec<u8>, &[u8])> {
1401    let val = |c: u8| -> Option<u32> {
1402        Some(match c {
1403            b'A'..=b'Z' => u32::from(c - b'A'),
1404            b'a'..=b'z' => u32::from(c - b'a') + 26,
1405            b'0'..=b'9' => u32::from(c - b'0') + 52,
1406            b'+' => 62,
1407            b'/' => 63,
1408            _ => return None,
1409        })
1410    };
1411    let (mut acc, mut bits, mut out, mut i) = (0u32, 0u32, Vec::new(), 0);
1412    while let Some(d) = s.get(i).copied().and_then(val) {
1413        i += 1;
1414        acc = (acc << 6) | d;
1415        bits += 6;
1416        if bits >= 8 {
1417            bits -= 8;
1418            out.push((acc >> bits) as u8);
1419        }
1420        acc &= (1 << bits) - 1;
1421    }
1422    if bits > 4 || acc != 0 {
1423        return None;
1424    }
1425    Some((out, &s[i..]))
1426}
1427
1428/// `argon2_verify()` as PHP's argon2 password algorithms call it.
1429fn argon2_verify(password: &[u8], hash: &[u8], algorithm: crate::argon2::Algorithm, name: &[u8]) -> bool {
1430    use crate::argon2::Params;
1431    let parse = || {
1432        let s = hash.strip_prefix(b"$")?.strip_prefix(name)?;
1433        let (version, s) = match argon2_u32(s, b"$v=") {
1434            Some((v, rest)) => (v, rest),
1435            None if s.starts_with(b"$v=") => return None,
1436            None => (0x10, s),
1437        };
1438        let (m, s) = argon2_u32(s, b"$m=")?;
1439        let (t, s) = argon2_u32(s, b",t=")?;
1440        let (p, s) = argon2_u32(s, b",p=")?;
1441        let (salt, s) = argon2_base64(s.strip_prefix(b"$")?)?;
1442        let (out, s) = argon2_base64(s.strip_prefix(b"$")?)?;
1443        s.is_empty().then_some((version, [m, t, p], salt, out))
1444    };
1445    let Some((version, [m, t, p], salt, expected)) = parse() else {
1446        return false;
1447    };
1448    if expected.len() < 4 || salt.len() < 8 || m > ARGON2_MEMORY_LIMIT {
1449        return false;
1450    }
1451    let Some(params) = Params::new(algorithm, version, m, t, p) else {
1452        return false;
1453    };
1454    let mut out = vec![0u8; expected.len()];
1455    if crate::argon2::hash(&params, password, &salt, &mut out).is_none() {
1456        return false;
1457    }
1458    out.iter().zip(&expected).fold(0u8, |acc, (a, b)| acc | (a ^ b)) == 0
1459}
1460
1461/// FreeSec's DES tables (ext/standard/crypt_freesec.c), built once.
1462struct DesTables {
1463    m_sbox: [[u8; 4096]; 4],
1464    psbox: [[u32; 256]; 4],
1465    ip_maskl: [[u32; 256]; 8],
1466    ip_maskr: [[u32; 256]; 8],
1467    fp_maskl: [[u32; 256]; 8],
1468    fp_maskr: [[u32; 256]; 8],
1469    key_perm_maskl: [[u32; 128]; 8],
1470    key_perm_maskr: [[u32; 128]; 8],
1471    comp_maskl: [[u32; 128]; 8],
1472    comp_maskr: [[u32; 128]; 8],
1473}
1474
1475const DES_IP: [u8; 64] = [
1476    58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32,
1477    24, 16, 8, 57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, 61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47,
1478    39, 31, 23, 15, 7,
1479];
1480const DES_KEY_PERM: [u8; 56] = [
1481    57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36, 63, 55,
1482    47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4,
1483];
1484const DES_KEY_SHIFTS: [u32; 16] = [1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1];
1485const DES_COMP_PERM: [u8; 48] = [
1486    14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, 23, 19, 12, 4, 26, 8, 16, 7, 27, 20, 13, 2, 41, 52, 31, 37, 47, 55, 30,
1487    40, 51, 45, 33, 48, 44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32,
1488];
1489const DES_SBOX: [[u8; 64]; 8] = [
1490    [
1491        14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7, 0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8, 4,
1492        1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0, 15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13,
1493    ],
1494    [
1495        15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10, 3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5, 0,
1496        14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15, 13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9,
1497    ],
1498    [
1499        10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8, 13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1, 13,
1500        6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7, 1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12,
1501    ],
1502    [
1503        7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15, 13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9, 10,
1504        6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4, 3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14,
1505    ],
1506    [
1507        2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9, 14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6, 4,
1508        2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14, 11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3,
1509    ],
1510    [
1511        12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11, 10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8, 9,
1512        14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6, 4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13,
1513    ],
1514    [
1515        4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1, 13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6, 1,
1516        4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2, 6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12,
1517    ],
1518    [
1519        13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7, 1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2, 7,
1520        11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8, 2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11,
1521    ],
1522];
1523const DES_PBOX: [u8; 32] = [
1524    16, 7, 20, 21, 29, 12, 28, 17, 1, 15, 23, 26, 5, 18, 31, 10, 2, 8, 24, 14, 32, 27, 3, 9, 19, 13, 30, 6, 22, 11, 4,
1525    25,
1526];
1527
1528fn bits32(i: usize) -> u32 {
1529    0x8000_0000 >> i
1530}
1531
1532/// `_crypt_extended_init()`.
1533fn des_tables() -> Box<DesTables> {
1534    let bits28 = |i: usize| bits32(i + 4);
1535    let bits24 = |i: usize| bits32(i + 8);
1536    let bits8 = |i: usize| 0x80u32 >> i;
1537    let mut t = Box::new(DesTables {
1538        m_sbox: [[0; 4096]; 4],
1539        psbox: [[0; 256]; 4],
1540        ip_maskl: [[0; 256]; 8],
1541        ip_maskr: [[0; 256]; 8],
1542        fp_maskl: [[0; 256]; 8],
1543        fp_maskr: [[0; 256]; 8],
1544        key_perm_maskl: [[0; 128]; 8],
1545        key_perm_maskr: [[0; 128]; 8],
1546        comp_maskl: [[0; 128]; 8],
1547        comp_maskr: [[0; 128]; 8],
1548    });
1549    let mut u_sbox = [[0u8; 64]; 8];
1550    for (i, row) in u_sbox.iter_mut().enumerate() {
1551        for (j, v) in row.iter_mut().enumerate() {
1552            let b = (j & 0x20) | ((j & 1) << 4) | ((j >> 1) & 0xf);
1553            *v = DES_SBOX[i][b];
1554        }
1555    }
1556    for b in 0..4 {
1557        for i in 0..64 {
1558            for j in 0..64 {
1559                t.m_sbox[b][(i << 6) | j] = (u_sbox[b << 1][i] << 4) | u_sbox[(b << 1) + 1][j];
1560            }
1561        }
1562    }
1563    let mut init_perm = [0u8; 64];
1564    let mut final_perm = [0u8; 64];
1565    let mut inv_key_perm = [255u8; 64];
1566    let mut inv_comp_perm = [255u8; 56];
1567    for i in 0..64 {
1568        final_perm[i] = DES_IP[i] - 1;
1569        init_perm[final_perm[i] as usize] = i as u8;
1570    }
1571    for (i, p) in DES_KEY_PERM.iter().enumerate() {
1572        inv_key_perm[*p as usize - 1] = i as u8;
1573    }
1574    for (i, p) in DES_COMP_PERM.iter().enumerate() {
1575        inv_comp_perm[*p as usize - 1] = i as u8;
1576    }
1577    for k in 0..8 {
1578        for i in 0..256u32 {
1579            let (mut il, mut ir, mut fl, mut fr) = (0, 0, 0, 0);
1580            for j in 0..8 {
1581                let inbit = 8 * k + j;
1582                if i & bits8(j) != 0 {
1583                    let obit = init_perm[inbit] as usize;
1584                    if obit < 32 {
1585                        il |= bits32(obit);
1586                    } else {
1587                        ir |= bits32(obit - 32);
1588                    }
1589                    let obit = final_perm[inbit] as usize;
1590                    if obit < 32 {
1591                        fl |= bits32(obit);
1592                    } else {
1593                        fr |= bits32(obit - 32);
1594                    }
1595                }
1596            }
1597            t.ip_maskl[k][i as usize] = il;
1598            t.ip_maskr[k][i as usize] = ir;
1599            t.fp_maskl[k][i as usize] = fl;
1600            t.fp_maskr[k][i as usize] = fr;
1601        }
1602        for i in 0..128u32 {
1603            let (mut il, mut ir) = (0, 0);
1604            for j in 0..7 {
1605                let inbit = 8 * k + j;
1606                if i & bits8(j + 1) != 0 {
1607                    let obit = inv_key_perm[inbit];
1608                    if obit == 255 {
1609                        continue;
1610                    }
1611                    let obit = obit as usize;
1612                    if obit < 28 {
1613                        il |= bits28(obit);
1614                    } else {
1615                        ir |= bits28(obit - 28);
1616                    }
1617                }
1618            }
1619            t.key_perm_maskl[k][i as usize] = il;
1620            t.key_perm_maskr[k][i as usize] = ir;
1621            let (mut il, mut ir) = (0, 0);
1622            for j in 0..7 {
1623                let inbit = 7 * k + j;
1624                if i & bits8(j + 1) != 0 {
1625                    let obit = inv_comp_perm[inbit];
1626                    if obit == 255 {
1627                        continue;
1628                    }
1629                    let obit = obit as usize;
1630                    if obit < 24 {
1631                        il |= bits24(obit);
1632                    } else {
1633                        ir |= bits24(obit - 24);
1634                    }
1635                }
1636            }
1637            t.comp_maskl[k][i as usize] = il;
1638            t.comp_maskr[k][i as usize] = ir;
1639        }
1640    }
1641    let mut un_pbox = [0u8; 32];
1642    for (i, p) in DES_PBOX.iter().enumerate() {
1643        un_pbox[*p as usize - 1] = i as u8;
1644    }
1645    for b in 0..4 {
1646        for i in 0..256u32 {
1647            let mut p = 0;
1648            for j in 0..8 {
1649                if i & bits8(j) != 0 {
1650                    p |= bits32(un_pbox[8 * b + j] as usize);
1651                }
1652            }
1653            t.psbox[b][i as usize] = p;
1654        }
1655    }
1656    t
1657}
1658
1659static DES: std::sync::LazyLock<Box<DesTables>> = std::sync::LazyLock::new(des_tables);
1660
1661/// A DES key schedule and the salt bits (`struct php_crypt_extended_data`).
1662struct Des {
1663    keys_l: [u32; 16],
1664    keys_r: [u32; 16],
1665    saltbits: u32,
1666}
1667
1668impl Des {
1669    fn new() -> Self {
1670        Des { keys_l: [0; 16], keys_r: [0; 16], saltbits: 0 }
1671    }
1672
1673    /// `setup_salt()`.
1674    fn set_salt(&mut self, salt: u32) {
1675        let mut saltbits = 0;
1676        let (mut saltbit, mut obit) = (1u32, 0x80_0000u32);
1677        for _ in 0..24 {
1678            if salt & saltbit != 0 {
1679                saltbits |= obit;
1680            }
1681            saltbit <<= 1;
1682            obit >>= 1;
1683        }
1684        self.saltbits = saltbits;
1685    }
1686
1687    /// `des_setkey()`.
1688    fn set_key(&mut self, key: &[u8; 8]) {
1689        let t = &**DES;
1690        let raw0 = u32::from_be_bytes([key[0], key[1], key[2], key[3]]);
1691        let raw1 = u32::from_be_bytes([key[4], key[5], key[6], key[7]]);
1692        let perm = |m: &[[u32; 128]; 8]| {
1693            m[0][(raw0 >> 25) as usize]
1694                | m[1][((raw0 >> 17) & 0x7f) as usize]
1695                | m[2][((raw0 >> 9) & 0x7f) as usize]
1696                | m[3][((raw0 >> 1) & 0x7f) as usize]
1697                | m[4][(raw1 >> 25) as usize]
1698                | m[5][((raw1 >> 17) & 0x7f) as usize]
1699                | m[6][((raw1 >> 9) & 0x7f) as usize]
1700                | m[7][((raw1 >> 1) & 0x7f) as usize]
1701        };
1702        let (k0, k1) = (perm(&t.key_perm_maskl), perm(&t.key_perm_maskr));
1703        let mut shifts = 0;
1704        for (round, shift) in DES_KEY_SHIFTS.iter().enumerate() {
1705            shifts += shift;
1706            let t0 = (k0 << shifts) | (k0 >> (28 - shifts));
1707            let t1 = (k1 << shifts) | (k1 >> (28 - shifts));
1708            let comp = |m: &[[u32; 128]; 8]| {
1709                m[0][((t0 >> 21) & 0x7f) as usize]
1710                    | m[1][((t0 >> 14) & 0x7f) as usize]
1711                    | m[2][((t0 >> 7) & 0x7f) as usize]
1712                    | m[3][(t0 & 0x7f) as usize]
1713                    | m[4][((t1 >> 21) & 0x7f) as usize]
1714                    | m[5][((t1 >> 14) & 0x7f) as usize]
1715                    | m[6][((t1 >> 7) & 0x7f) as usize]
1716                    | m[7][(t1 & 0x7f) as usize]
1717            };
1718            self.keys_l[round] = comp(&t.comp_maskl);
1719            self.keys_r[round] = comp(&t.comp_maskr);
1720        }
1721    }
1722
1723    /// `do_des()`, encrypting `count` times.
1724    fn encrypt(&self, l_in: u32, r_in: u32, count: u32) -> (u32, u32) {
1725        let t = &**DES;
1726        let byte = |v: u32, s: u32| ((v >> s) & 0xff) as usize;
1727        let ip = |m: &[[u32; 256]; 8]| {
1728            m[0][byte(l_in, 24)]
1729                | m[1][byte(l_in, 16)]
1730                | m[2][byte(l_in, 8)]
1731                | m[3][byte(l_in, 0)]
1732                | m[4][byte(r_in, 24)]
1733                | m[5][byte(r_in, 16)]
1734                | m[6][byte(r_in, 8)]
1735                | m[7][byte(r_in, 0)]
1736        };
1737        let (mut l, mut r) = (ip(&t.ip_maskl), ip(&t.ip_maskr));
1738        let mut f = 0u32;
1739        for _ in 0..count {
1740            for round in 0..16 {
1741                let mut r48l = ((r & 0x0000_0001) << 23)
1742                    | ((r & 0xf800_0000) >> 9)
1743                    | ((r & 0x1f80_0000) >> 11)
1744                    | ((r & 0x01f8_0000) >> 13)
1745                    | ((r & 0x001f_8000) >> 15);
1746                let mut r48r = ((r & 0x0001_f800) << 7)
1747                    | ((r & 0x0000_1f80) << 5)
1748                    | ((r & 0x0000_01f8) << 3)
1749                    | ((r & 0x0000_001f) << 1)
1750                    | ((r & 0x8000_0000) >> 31);
1751                f = (r48l ^ r48r) & self.saltbits;
1752                r48l ^= f ^ self.keys_l[round];
1753                r48r ^= f ^ self.keys_r[round];
1754                f = t.psbox[0][t.m_sbox[0][(r48l >> 12) as usize] as usize]
1755                    | t.psbox[1][t.m_sbox[1][(r48l & 0xfff) as usize] as usize]
1756                    | t.psbox[2][t.m_sbox[2][(r48r >> 12) as usize] as usize]
1757                    | t.psbox[3][t.m_sbox[3][(r48r & 0xfff) as usize] as usize];
1758                f ^= l;
1759                l = r;
1760                r = f;
1761            }
1762            r = l;
1763            l = f;
1764        }
1765        let fp = |m: &[[u32; 256]; 8]| {
1766            m[0][byte(l, 24)]
1767                | m[1][byte(l, 16)]
1768                | m[2][byte(l, 8)]
1769                | m[3][byte(l, 0)]
1770                | m[4][byte(r, 24)]
1771                | m[5][byte(r, 16)]
1772                | m[6][byte(r, 8)]
1773                | m[7][byte(r, 0)]
1774        };
1775        (fp(&t.fp_maskl), fp(&t.fp_maskr))
1776    }
1777}
1778
1779/// FreeSec's `ascii_to_bin()` (on a signed char).
1780fn des_ascii_to_bin(ch: u8) -> u32 {
1781    let sch = i32::from(ch as i8);
1782    let mut v = sch - i32::from(b'.');
1783    if sch >= i32::from(b'A') {
1784        v = sch - (i32::from(b'A') - 12);
1785        if sch >= i32::from(b'a') {
1786            v = sch - (i32::from(b'a') - 38);
1787        }
1788    }
1789    (v & 0x3f) as u32
1790}
1791
1792/// `_crypt_extended_r()`: traditional DES (two salt characters, the first
1793/// 8 key bytes) and BSDi extended DES (`_`, 4 count and 4 salt characters).
1794fn des_crypt(key: &[u8], setting: &[u8]) -> Option<Vec<u8>> {
1795    let at = |i: usize| setting.get(i).copied().unwrap_or(0);
1796    let mut keybuf = [0u8; 8];
1797    let mut k = 0usize;
1798    for b in keybuf.iter_mut() {
1799        let c = key.get(k).copied().unwrap_or(0);
1800        *b = c << 1;
1801        if c != 0 {
1802            k += 1;
1803        }
1804    }
1805    let mut des = Des::new();
1806    des.set_key(&keybuf);
1807    let (count, salt, mut out) = if at(0) == b'_' {
1808        let field = |range: std::ops::Range<usize>| -> Option<u32> {
1809            let mut v = 0u32;
1810            for (n, i) in range.enumerate() {
1811                let value = des_ascii_to_bin(at(i));
1812                if CRYPT_ITOA64[value as usize] != at(i) {
1813                    return None;
1814                }
1815                v |= value << (n * 6);
1816            }
1817            Some(v)
1818        };
1819        let count = field(1..5)?;
1820        if count == 0 {
1821            return None;
1822        }
1823        let salt = field(5..9)?;
1824        while key.get(k).is_some_and(|c| *c != 0) {
1825            des.set_salt(0);
1826            let (l, r) = des.encrypt(
1827                u32::from_be_bytes([keybuf[0], keybuf[1], keybuf[2], keybuf[3]]),
1828                u32::from_be_bytes([keybuf[4], keybuf[5], keybuf[6], keybuf[7]]),
1829                1,
1830            );
1831            keybuf[..4].copy_from_slice(&l.to_be_bytes());
1832            keybuf[4..].copy_from_slice(&r.to_be_bytes());
1833            for b in keybuf.iter_mut() {
1834                match key.get(k) {
1835                    Some(c) if *c != 0 => {
1836                        *b ^= c << 1;
1837                        k += 1;
1838                    }
1839                    _ => break,
1840                }
1841            }
1842            des.set_key(&keybuf);
1843        }
1844        (count, salt, setting[..9].to_vec())
1845    } else {
1846        let unsafe_char = |c: u8| c == 0 || c == b'\n' || c == b':';
1847        if unsafe_char(at(0)) || unsafe_char(at(1)) {
1848            return None;
1849        }
1850        let salt = (des_ascii_to_bin(at(1)) << 6) | des_ascii_to_bin(at(0));
1851        (25, salt, setting[..2].to_vec())
1852    };
1853    des.set_salt(salt);
1854    let (r0, r1) = des.encrypt(0, 0, count);
1855    let mut push = |v: u32, shifts: &[u32]| {
1856        for s in shifts {
1857            out.push(CRYPT_ITOA64[((v >> s) & 0x3f) as usize]);
1858        }
1859    };
1860    push(r0 >> 8, &[18, 12, 6, 0]);
1861    push((r0 << 16) | ((r1 >> 16) & 0xffff), &[18, 12, 6, 0]);
1862    push(r1 << 2, &[12, 6, 0]);
1863    Some(out)
1864}
1865
1866// ---------------------------------------------------------------------------
1867// hash()
1868// ---------------------------------------------------------------------------
1869
1870mod tables;
1871
1872/// `md5($data)`: the lowercase hex digest, in a buffer rather than a new string.
1873pub fn md5_hex(data: &[u8]) -> [u8; 32] {
1874    use md5::Digest;
1875    const DIGITS: &[u8; 16] = b"0123456789abcdef";
1876    let digest = md5::Md5::digest(data);
1877    let mut out = [0u8; 32];
1878    for (i, byte) in digest.iter().enumerate() {
1879        out[2 * i] = DIGITS[usize::from(byte >> 4)];
1880        out[2 * i + 1] = DIGITS[usize::from(byte & 0x0f)];
1881    }
1882    out
1883}
1884
1885/// `hash($algo, $data)` as lowercase hex, for every algorithm of
1886/// `hash_algos()`; `None` for any other name (PHP's "must be a valid hashing
1887/// algorithm"). The name is case-insensitive.
1888pub fn hash(algo: &[u8], data: &[u8]) -> Option<String> {
1889    use sha2::Digest;
1890    let hex = crate::encoding::bin2hex;
1891    Some(match algo.to_ascii_lowercase().as_slice() {
1892        b"md2" => hex(&md2::Md2::digest(data)),
1893        b"md4" => hex(&md4(data)),
1894        b"md5" => hex(&md5::Md5::digest(data)),
1895        b"sha1" => hex(&sha1::Sha1::digest(data)),
1896        b"sha224" => hex(&sha2::Sha224::digest(data)),
1897        b"sha256" => hex(&sha2::Sha256::digest(data)),
1898        b"sha384" => hex(&sha2::Sha384::digest(data)),
1899        b"sha512/224" => hex(&sha2::Sha512_224::digest(data)),
1900        b"sha512/256" => hex(&sha2::Sha512_256::digest(data)),
1901        b"sha512" => hex(&sha2::Sha512::digest(data)),
1902        b"sha3-224" => hex(&sha3::Sha3_224::digest(data)),
1903        b"sha3-256" => hex(&sha3::Sha3_256::digest(data)),
1904        b"sha3-384" => hex(&sha3::Sha3_384::digest(data)),
1905        b"sha3-512" => hex(&sha3::Sha3_512::digest(data)),
1906        b"ripemd128" => hex(&ripemd::Ripemd128::digest(data)),
1907        b"ripemd160" => hex(&ripemd::Ripemd160::digest(data)),
1908        b"ripemd256" => hex(&ripemd::Ripemd256::digest(data)),
1909        b"ripemd320" => hex(&ripemd::Ripemd320::digest(data)),
1910        b"whirlpool" => hex(&whirlpool::Whirlpool::digest(data)),
1911        b"tiger128,3" => hex(&tiger(data, 0)[..16]),
1912        b"tiger160,3" => hex(&tiger(data, 0)[..20]),
1913        b"tiger192,3" => hex(&tiger(data, 0)),
1914        b"tiger128,4" => hex(&tiger(data, 1)[..16]),
1915        b"tiger160,4" => hex(&tiger(data, 1)[..20]),
1916        b"tiger192,4" => hex(&tiger(data, 1)),
1917        b"snefru" | b"snefru256" => hex(&snefru(data)),
1918        name if name.starts_with(b"haval") => {
1919            let spec = &name[5..];
1920            let (bits, passes) = match spec {
1921                b"128,3" => (128, 3),
1922                b"160,3" => (160, 3),
1923                b"192,3" => (192, 3),
1924                b"224,3" => (224, 3),
1925                b"256,3" => (256, 3),
1926                b"128,4" => (128, 4),
1927                b"160,4" => (160, 4),
1928                b"192,4" => (192, 4),
1929                b"224,4" => (224, 4),
1930                b"256,4" => (256, 4),
1931                b"128,5" => (128, 5),
1932                b"160,5" => (160, 5),
1933                b"192,5" => (192, 5),
1934                b"224,5" => (224, 5),
1935                b"256,5" => (256, 5),
1936                _ => return None,
1937            };
1938            hex(&haval(data, passes, bits))
1939        }
1940        b"gost" => hex(&gost94::Gost94Test::digest(data)),
1941        b"gost-crypto" => hex(&gost94::Gost94CryptoPro::digest(data)),
1942        b"adler32" => {
1943            let (mut a, mut b) = (1u32, 0u32);
1944            for x in data {
1945                a = (a + u32::from(*x)) % 65521;
1946                b = (b + a) % 65521;
1947            }
1948            format!("{:08x}", (b << 16) | a)
1949        }
1950        // bzip2's CRC (most significant bit first), written least significant byte first.
1951        b"crc32" => {
1952            let mut state = !0u32;
1953            for x in data {
1954                let mut c = (state >> 24) ^ u32::from(*x);
1955                c <<= 24;
1956                for _ in 0..8 {
1957                    c = if c & 0x8000_0000 != 0 { (c << 1) ^ 0x04c1_1db7 } else { c << 1 };
1958                }
1959                state = (state << 8) ^ c;
1960            }
1961            hex(&(!state).to_le_bytes())
1962        }
1963        b"crc32b" => format!("{:08x}", crc32_reflected(data, 0xedb8_8320)),
1964        b"crc32c" => format!("{:08x}", crc32_reflected(data, 0x82f6_3b78)),
1965        b"fnv132" | b"fnv1a32" => {
1966            let mut h = 0x811c_9dc5u32;
1967            for x in data {
1968                if algo.eq_ignore_ascii_case(b"fnv132") {
1969                    h = h.wrapping_mul(0x0100_0193) ^ u32::from(*x);
1970                } else {
1971                    h = (h ^ u32::from(*x)).wrapping_mul(0x0100_0193);
1972                }
1973            }
1974            format!("{h:08x}")
1975        }
1976        b"fnv164" | b"fnv1a64" => {
1977            let mut h = 0xcbf2_9ce4_8422_2325u64;
1978            for x in data {
1979                if algo.eq_ignore_ascii_case(b"fnv164") {
1980                    h = h.wrapping_mul(0x0000_0100_0000_01b3) ^ u64::from(*x);
1981                } else {
1982                    h = (h ^ u64::from(*x)).wrapping_mul(0x0000_0100_0000_01b3);
1983                }
1984            }
1985            format!("{h:016x}")
1986        }
1987        b"joaat" => {
1988            let mut h = 0u32;
1989            for x in data {
1990                h = h.wrapping_add(u32::from(*x));
1991                h = h.wrapping_add(h << 10);
1992                h ^= h >> 6;
1993            }
1994            h = h.wrapping_add(h << 3);
1995            h ^= h >> 11;
1996            h = h.wrapping_add(h << 15);
1997            format!("{h:08x}")
1998        }
1999        b"murmur3a" => format!("{:08x}", murmur3_x86_32(data)),
2000        b"murmur3c" => murmur3_x86_128(data).iter().map(|h| format!("{h:08x}")).collect(),
2001        b"murmur3f" => murmur3_x64_128(data).iter().map(|h| format!("{h:016x}")).collect(),
2002        b"xxh32" => format!("{:08x}", xxh32(data)),
2003        b"xxh64" => format!("{:016x}", xxh64(data)),
2004        b"xxh3" => format!("{:016x}", xxhash_rust::xxh3::xxh3_64(data)),
2005        b"xxh128" => format!("{:032x}", xxhash_rust::xxh3::xxh3_128(data)),
2006        _ => return None,
2007    })
2008}
2009
2010/// Tiger with `extra` passes beyond three (`PHP_3TIGER` / `PHP_4TIGER`):
2011/// the state's words little-endian.
2012fn tiger(data: &[u8], extra: usize) -> [u8; 24] {
2013    let mut msg = data.to_vec();
2014    msg.push(0x01);
2015    while msg.len() % 64 != 56 {
2016        msg.push(0);
2017    }
2018    msg.extend_from_slice(&(data.len() as u64).wrapping_mul(8).to_le_bytes());
2019    let mut state = [0x0123_4567_89ab_cdefu64, 0xfedc_ba98_7654_3210, 0xf096_a5b4_c3b2_e187];
2020    for block in msg.chunks(64) {
2021        let mut x = [0u64; 8];
2022        for (i, w) in x.iter_mut().enumerate() {
2023            *w = u64::from_le_bytes(block[i * 8..i * 8 + 8].try_into().unwrap_or_default());
2024        }
2025        tiger_compress(&mut state, &mut x, extra);
2026    }
2027    let mut out = [0u8; 24];
2028    for (i, w) in state.iter().enumerate() {
2029        out[i * 8..i * 8 + 8].copy_from_slice(&w.to_le_bytes());
2030    }
2031    out
2032}
2033
2034fn tiger_round(a: &mut u64, b: &mut u64, c: &mut u64, x: u64, mul: u64) {
2035    let t = &tables::TIGER;
2036    let s = |box_: usize, byte: u64| t[box_ * 256 + (byte & 0xff) as usize];
2037    *c ^= x;
2038    let (lo, hi) = (*c & 0xffff_ffff, *c >> 32);
2039    *a = a.wrapping_sub(s(0, lo) ^ s(1, lo >> 16) ^ s(2, hi) ^ s(3, hi >> 16));
2040    *b = b.wrapping_add(s(3, lo >> 8) ^ s(2, lo >> 24) ^ s(1, hi >> 8) ^ s(0, hi >> 24));
2041    *b = b.wrapping_mul(mul);
2042}
2043
2044fn tiger_pass(a: &mut u64, b: &mut u64, c: &mut u64, x: &[u64; 8], mul: u64) {
2045    tiger_round(a, b, c, x[0], mul);
2046    tiger_round(b, c, a, x[1], mul);
2047    tiger_round(c, a, b, x[2], mul);
2048    tiger_round(a, b, c, x[3], mul);
2049    tiger_round(b, c, a, x[4], mul);
2050    tiger_round(c, a, b, x[5], mul);
2051    tiger_round(a, b, c, x[6], mul);
2052    tiger_round(b, c, a, x[7], mul);
2053}
2054
2055fn tiger_key_schedule(x: &mut [u64; 8]) {
2056    x[0] = x[0].wrapping_sub(x[7] ^ 0xa5a5_a5a5_a5a5_a5a5);
2057    x[1] ^= x[0];
2058    x[2] = x[2].wrapping_add(x[1]);
2059    x[3] = x[3].wrapping_sub(x[2] ^ ((!x[1]) << 19));
2060    x[4] ^= x[3];
2061    x[5] = x[5].wrapping_add(x[4]);
2062    x[6] = x[6].wrapping_sub(x[5] ^ ((!x[4]) >> 23));
2063    x[7] ^= x[6];
2064    x[0] = x[0].wrapping_add(x[7]);
2065    x[1] = x[1].wrapping_sub(x[0] ^ ((!x[7]) << 19));
2066    x[2] ^= x[1];
2067    x[3] = x[3].wrapping_add(x[2]);
2068    x[4] = x[4].wrapping_sub(x[3] ^ ((!x[2]) >> 23));
2069    x[5] ^= x[4];
2070    x[6] = x[6].wrapping_add(x[5]);
2071    x[7] = x[7].wrapping_sub(x[6] ^ 0x0123_4567_89ab_cdef);
2072}
2073
2074fn tiger_compress(state: &mut [u64; 3], x: &mut [u64; 8], extra: usize) {
2075    let [mut a, mut b, mut c] = *state;
2076    let (aa, bb, cc) = (a, b, c);
2077    tiger_pass(&mut a, &mut b, &mut c, x, 5);
2078    tiger_key_schedule(x);
2079    tiger_pass(&mut c, &mut a, &mut b, x, 7);
2080    tiger_key_schedule(x);
2081    tiger_pass(&mut b, &mut c, &mut a, x, 9);
2082    for _ in 0..extra {
2083        tiger_key_schedule(x);
2084        tiger_pass(&mut a, &mut b, &mut c, x, 9);
2085        (a, b, c) = (c, a, b);
2086    }
2087    *state = [a ^ aa, b.wrapping_sub(bb), c.wrapping_add(cc)];
2088}
2089
2090/// Snefru (`PHP_SNEFRU`): 32-byte blocks into the upper half of a sixteen
2091/// word state, the bit count in its last two words, words big-endian.
2092fn snefru(data: &[u8]) -> [u8; 32] {
2093    let mut state = [0u32; 16];
2094    let bits = (data.len() as u64).wrapping_mul(8);
2095    // PHP_SNEFRUUpdate's carry: one when the bit count passes 32 bits.
2096    let count = if bits > 0xffff_ffff { [1, (bits as u32).wrapping_sub(0xffff_ffff)] } else { [0, bits as u32] };
2097    for block in data.chunks(32) {
2098        let mut padded = [0u8; 32];
2099        padded[..block.len()].copy_from_slice(block);
2100        for (j, w) in padded.chunks(4).enumerate() {
2101            state[8 + j] = u32::from_be_bytes([w[0], w[1], w[2], w[3]]);
2102        }
2103        snefru_block(&mut state);
2104        state[8..].fill(0);
2105    }
2106    state[14] = count[0];
2107    state[15] = count[1];
2108    snefru_block(&mut state);
2109    let mut out = [0u8; 32];
2110    for (i, w) in state[..8].iter().enumerate() {
2111        out[i * 4..i * 4 + 4].copy_from_slice(&w.to_be_bytes());
2112    }
2113    out
2114}
2115
2116fn snefru_block(state: &mut [u32; 16]) {
2117    let mut b = *state;
2118    for index in 0..8 {
2119        let boxes = [&tables::SNEFRU[2 * index], &tables::SNEFRU[2 * index + 1]];
2120        for shift in [16, 8, 16, 24] {
2121            for k in 0..16 {
2122                let sbe = boxes[(k / 2) % 2][(b[k] & 0xff) as usize];
2123                b[(k + 15) % 16] ^= sbe;
2124                b[(k + 1) % 16] ^= sbe;
2125            }
2126            for v in b.iter_mut() {
2127                *v = v.rotate_right(shift);
2128            }
2129        }
2130    }
2131    for i in 0..8 {
2132        state[i] ^= b[15 - i];
2133    }
2134}
2135
2136/// HAVAL with `passes` passes and an `output`-bit digest (`PHP_HAVAL`):
2137/// 128-byte blocks of little-endian words, padded to 118 mod 128, then the
2138/// version, passes, length and bit count; shorter digests fold the state.
2139fn haval(data: &[u8], passes: u32, output: u32) -> Vec<u8> {
2140    let count = [((data.len() as u64) << 3) as u32, (data.len() as u64 >> 29) as u32];
2141    let mut msg = data.to_vec();
2142    let index = data.len() % 128;
2143    let pad = if index < 118 { 118 - index } else { 246 - index };
2144    msg.push(1);
2145    msg.resize(msg.len() + pad - 1, 0);
2146    msg.push((1 | ((passes & 7) << 3) | ((output & 3) << 6)) as u8);
2147    msg.push((output >> 2) as u8);
2148    for c in count {
2149        msg.extend_from_slice(&c.to_le_bytes());
2150    }
2151    let mut s = tables::HAVAL_D0;
2152    for block in msg.chunks(128) {
2153        haval_transform(&mut s, block, passes);
2154    }
2155    let rotr = |x: u32, n: u32| x.rotate_right(n);
2156    match output {
2157        128 => {
2158            s[3] = s[3].wrapping_add(
2159                (s[7] & 0xff00_0000) | (s[6] & 0x00ff_0000) | (s[5] & 0x0000_ff00) | (s[4] & 0x0000_00ff),
2160            );
2161            s[2] = s[2].wrapping_add(
2162                (((s[7] & 0x00ff_0000) | (s[6] & 0x0000_ff00) | (s[5] & 0x0000_00ff)) << 8)
2163                    | ((s[4] & 0xff00_0000) >> 24),
2164            );
2165            s[1] = s[1].wrapping_add(
2166                (((s[7] & 0x0000_ff00) | (s[6] & 0x0000_00ff)) << 16)
2167                    | (((s[5] & 0xff00_0000) | (s[4] & 0x00ff_0000)) >> 16),
2168            );
2169            s[0] = s[0].wrapping_add(
2170                ((s[7] & 0x0000_00ff) << 24)
2171                    | (((s[6] & 0xff00_0000) | (s[5] & 0x00ff_0000) | (s[4] & 0x0000_ff00)) >> 8),
2172            );
2173        }
2174        160 => {
2175            s[4] = s[4].wrapping_add(((s[7] & 0xfe00_0000) | (s[6] & 0x01f8_0000) | (s[5] & 0x0007_f000)) >> 12);
2176            s[3] = s[3].wrapping_add(((s[7] & 0x01f8_0000) | (s[6] & 0x0007_f000) | (s[5] & 0x0000_0fc0)) >> 6);
2177            s[2] = s[2].wrapping_add((s[7] & 0x0007_f000) | (s[6] & 0x0000_0fc0) | (s[5] & 0x0000_003f));
2178            s[1] = s[1].wrapping_add(rotr((s[7] & 0x0000_0fc0) | (s[6] & 0x0000_003f) | (s[5] & 0xfe00_0000), 25));
2179            s[0] = s[0].wrapping_add(rotr((s[7] & 0x0000_003f) | (s[6] & 0xfe00_0000) | (s[5] & 0x01f8_0000), 19));
2180        }
2181        192 => {
2182            s[5] = s[5].wrapping_add(((s[7] & 0xfc00_0000) | (s[6] & 0x03e0_0000)) >> 21);
2183            s[4] = s[4].wrapping_add(((s[7] & 0x03e0_0000) | (s[6] & 0x001f_0000)) >> 16);
2184            s[3] = s[3].wrapping_add(((s[7] & 0x001f_0000) | (s[6] & 0x0000_fc00)) >> 10);
2185            s[2] = s[2].wrapping_add(((s[7] & 0x0000_fc00) | (s[6] & 0x0000_03e0)) >> 5);
2186            s[1] = s[1].wrapping_add((s[7] & 0x0000_03e0) | (s[6] & 0x0000_001f));
2187            s[0] = s[0].wrapping_add(rotr((s[7] & 0x0000_001f) | (s[6] & 0xfc00_0000), 26));
2188        }
2189        224 => {
2190            s[6] = s[6].wrapping_add(s[7] & 0x0000_000f);
2191            s[5] = s[5].wrapping_add((s[7] >> 4) & 0x0000_001f);
2192            s[4] = s[4].wrapping_add((s[7] >> 9) & 0x0000_000f);
2193            s[3] = s[3].wrapping_add((s[7] >> 13) & 0x0000_001f);
2194            s[2] = s[2].wrapping_add((s[7] >> 18) & 0x0000_000f);
2195            s[1] = s[1].wrapping_add((s[7] >> 22) & 0x0000_001f);
2196            s[0] = s[0].wrapping_add((s[7] >> 27) & 0x0000_001f);
2197        }
2198        _ => {}
2199    }
2200    s.iter().flat_map(|w| w.to_le_bytes()).take(output as usize / 8).collect()
2201}
2202
2203/// `PHP_{3,4,5}HAVALTransform`: each pass applies its boolean function to a
2204/// permutation of the eight words (`M`), the argument orders below.
2205fn haval_transform(state: &mut [u32; 8], block: &[u8], passes: u32) {
2206    type F = fn(u32, u32, u32, u32, u32, u32, u32) -> u32;
2207    let f1: F = |x6, x5, x4, x3, x2, x1, x0| (x1 & x4) ^ (x2 & x5) ^ (x3 & x6) ^ (x0 & x1) ^ x0;
2208    let f2: F = |x6, x5, x4, x3, x2, x1, x0| {
2209        (x1 & x2 & x3) ^ (x2 & x4 & x5) ^ (x1 & x2) ^ (x1 & x4) ^ (x2 & x6) ^ (x3 & x5) ^ (x4 & x5) ^ (x0 & x2) ^ x0
2210    };
2211    let f3: F = |x6, x5, x4, x3, x2, x1, x0| (x1 & x2 & x3) ^ (x1 & x4) ^ (x2 & x5) ^ (x3 & x6) ^ (x0 & x3) ^ x0;
2212    let f4: F = |x6, x5, x4, x3, x2, x1, x0| {
2213        (x1 & x2 & x3)
2214            ^ (x2 & x4 & x5)
2215            ^ (x3 & x4 & x6)
2216            ^ (x1 & x4)
2217            ^ (x2 & x6)
2218            ^ (x3 & x4)
2219            ^ (x3 & x5)
2220            ^ (x3 & x6)
2221            ^ (x4 & x5)
2222            ^ (x4 & x6)
2223            ^ (x0 & x4)
2224            ^ x0
2225    };
2226    let f5: F = |x6, x5, x4, x3, x2, x1, x0| (x1 & x4) ^ (x2 & x5) ^ (x3 & x6) ^ (x0 & x1 & x2 & x3) ^ (x0 & x5) ^ x0;
2227    let orders: &[[usize; 7]] = match passes {
2228        3 => &[[1, 0, 3, 5, 6, 2, 4], [4, 2, 1, 0, 5, 3, 6], [6, 1, 2, 3, 4, 5, 0]],
2229        4 => &[[2, 6, 1, 4, 5, 3, 0], [3, 5, 2, 0, 1, 6, 4], [1, 4, 3, 6, 0, 2, 5], [6, 4, 0, 5, 2, 1, 3]],
2230        _ => &[
2231            [3, 4, 1, 0, 5, 2, 6],
2232            [6, 2, 1, 0, 3, 4, 5],
2233            [2, 6, 0, 4, 3, 1, 5],
2234            [1, 5, 3, 2, 0, 4, 6],
2235            [2, 5, 0, 6, 4, 3, 1],
2236        ],
2237    };
2238    let functions = [f1, f2, f3, f4, f5];
2239    let words: [Option<(&[usize; 32], &[u32; 32])>; 5] = [
2240        None,
2241        Some((&tables::HAVAL_I2, &tables::HAVAL_K2)),
2242        Some((&tables::HAVAL_I3, &tables::HAVAL_K3)),
2243        Some((&tables::HAVAL_I4, &tables::HAVAL_K4)),
2244        Some((&tables::HAVAL_I5, &tables::HAVAL_K5)),
2245    ];
2246    let x: Vec<u32> = block.chunks(4).map(|w| u32::from_le_bytes([w[0], w[1], w[2], w[3]])).collect();
2247    let mut e = *state;
2248    for (p, order) in orders.iter().enumerate() {
2249        for i in 0..32 {
2250            let m = |k: usize| e[(k + 8 - i % 8) % 8];
2251            let f =
2252                functions[p](m(order[0]), m(order[1]), m(order[2]), m(order[3]), m(order[4]), m(order[5]), m(order[6]));
2253            let word = match words[p] {
2254                None => x[i],
2255                Some((index, k)) => x[index[i]].wrapping_add(k[i]),
2256            };
2257            e[7 - i % 8] = f.rotate_right(7).wrapping_add(m(7).rotate_right(11)).wrapping_add(word);
2258        }
2259    }
2260    for (s, v) in state.iter_mut().zip(e) {
2261        *s = s.wrapping_add(v);
2262    }
2263}
2264
2265fn crc32_reflected(data: &[u8], poly: u32) -> u32 {
2266    let mut state = !0u32;
2267    for x in data {
2268        state ^= u32::from(*x);
2269        for _ in 0..8 {
2270            state = if state & 1 != 0 { (state >> 1) ^ poly } else { state >> 1 };
2271        }
2272    }
2273    !state
2274}
2275
2276/// RFC 1320.
2277fn md4(data: &[u8]) -> [u8; 16] {
2278    let mut msg = data.to_vec();
2279    let bits = (data.len() as u64).wrapping_mul(8);
2280    msg.push(0x80);
2281    while msg.len() % 64 != 56 {
2282        msg.push(0);
2283    }
2284    msg.extend_from_slice(&bits.to_le_bytes());
2285    let mut s = [0x6745_2301u32, 0xefcd_ab89, 0x98ba_dcfe, 0x1032_5476];
2286    for block in msg.chunks(64) {
2287        let x: Vec<u32> = block.chunks(4).map(|w| u32::from_le_bytes([w[0], w[1], w[2], w[3]])).collect();
2288        let [mut a, mut b, mut c, mut d] = s;
2289        let f = |x: u32, y: u32, z: u32| (x & y) | (!x & z);
2290        let g = |x: u32, y: u32, z: u32| (x & y) | (x & z) | (y & z);
2291        let h = |x: u32, y: u32, z: u32| x ^ y ^ z;
2292        for &i in &[0usize, 4, 8, 12] {
2293            a = a.wrapping_add(f(b, c, d)).wrapping_add(x[i]).rotate_left(3);
2294            d = d.wrapping_add(f(a, b, c)).wrapping_add(x[i + 1]).rotate_left(7);
2295            c = c.wrapping_add(f(d, a, b)).wrapping_add(x[i + 2]).rotate_left(11);
2296            b = b.wrapping_add(f(c, d, a)).wrapping_add(x[i + 3]).rotate_left(19);
2297        }
2298        for &i in &[0usize, 1, 2, 3] {
2299            a = a.wrapping_add(g(b, c, d)).wrapping_add(x[i]).wrapping_add(0x5a82_7999).rotate_left(3);
2300            d = d.wrapping_add(g(a, b, c)).wrapping_add(x[i + 4]).wrapping_add(0x5a82_7999).rotate_left(5);
2301            c = c.wrapping_add(g(d, a, b)).wrapping_add(x[i + 8]).wrapping_add(0x5a82_7999).rotate_left(9);
2302            b = b.wrapping_add(g(c, d, a)).wrapping_add(x[i + 12]).wrapping_add(0x5a82_7999).rotate_left(13);
2303        }
2304        for &i in &[0usize, 2, 1, 3] {
2305            a = a.wrapping_add(h(b, c, d)).wrapping_add(x[i]).wrapping_add(0x6ed9_eba1).rotate_left(3);
2306            d = d.wrapping_add(h(a, b, c)).wrapping_add(x[i + 8]).wrapping_add(0x6ed9_eba1).rotate_left(9);
2307            c = c.wrapping_add(h(d, a, b)).wrapping_add(x[i + 4]).wrapping_add(0x6ed9_eba1).rotate_left(11);
2308            b = b.wrapping_add(h(c, d, a)).wrapping_add(x[i + 12]).wrapping_add(0x6ed9_eba1).rotate_left(15);
2309        }
2310        s = [s[0].wrapping_add(a), s[1].wrapping_add(b), s[2].wrapping_add(c), s[3].wrapping_add(d)];
2311    }
2312    let mut out = [0u8; 16];
2313    for (i, w) in s.iter().enumerate() {
2314        out[i * 4..i * 4 + 4].copy_from_slice(&w.to_le_bytes());
2315    }
2316    out
2317}
2318
2319fn fmix32(mut h: u32) -> u32 {
2320    h ^= h >> 16;
2321    h = h.wrapping_mul(0x85eb_ca6b);
2322    h ^= h >> 13;
2323    h = h.wrapping_mul(0xc2b2_ae35);
2324    h ^ (h >> 16)
2325}
2326
2327fn fmix64(mut k: u64) -> u64 {
2328    k ^= k >> 33;
2329    k = k.wrapping_mul(0xff51_afd7_ed55_8ccd);
2330    k ^= k >> 33;
2331    k = k.wrapping_mul(0xc4ce_b9fe_1a85_ec53);
2332    k ^ (k >> 33)
2333}
2334
2335/// The tail bytes of a block, little-endian, as one integer.
2336fn tail(bytes: &[u8]) -> u64 {
2337    bytes.iter().rev().fold(0u64, |acc, b| (acc << 8) | u64::from(*b))
2338}
2339
2340/// MurmurHash3_x86_32, seed 0.
2341fn murmur3_x86_32(data: &[u8]) -> u32 {
2342    let (c1, c2) = (0xcc9e_2d51u32, 0x1b87_3593u32);
2343    let mut h = 0u32;
2344    let blocks = data.chunks_exact(4);
2345    let rest = blocks.remainder();
2346    for b in blocks {
2347        let k = u32::from_le_bytes([b[0], b[1], b[2], b[3]]).wrapping_mul(c1).rotate_left(15).wrapping_mul(c2);
2348        h = (h ^ k).rotate_left(13).wrapping_mul(5).wrapping_add(0xe654_6b64);
2349    }
2350    if !rest.is_empty() {
2351        h ^= (tail(rest) as u32).wrapping_mul(c1).rotate_left(15).wrapping_mul(c2);
2352    }
2353    fmix32(h ^ data.len() as u32)
2354}
2355
2356/// MurmurHash3_x86_128, seed 0.
2357fn murmur3_x86_128(data: &[u8]) -> [u32; 4] {
2358    let c = [0x239b_961bu32, 0xab0e_9789, 0x38b3_4ae5, 0xa1e3_8b93];
2359    let rot = [15u32, 16, 17, 18];
2360    let hrot = [19u32, 17, 15, 13];
2361    let add = [0x561c_cd1bu32, 0x0bca_a747, 0x96cd_1c35, 0x32ac_3b17];
2362    let mut h = [0u32; 4];
2363    let blocks = data.chunks_exact(16);
2364    let rest = blocks.remainder();
2365    for b in blocks {
2366        let k: Vec<u32> = b.chunks(4).map(|w| u32::from_le_bytes([w[0], w[1], w[2], w[3]])).collect();
2367        for i in 0..4 {
2368            let n = (i + 1) % 4;
2369            h[i] ^= k[i].wrapping_mul(c[i]).rotate_left(rot[i]).wrapping_mul(c[n]);
2370            h[i] = h[i].rotate_left(hrot[i]).wrapping_add(h[n]).wrapping_mul(5).wrapping_add(add[i]);
2371        }
2372    }
2373    for i in (0..4).rev() {
2374        let part = rest.get(i * 4..rest.len().min(i * 4 + 4)).unwrap_or_default();
2375        if !part.is_empty() {
2376            let n = (i + 1) % 4;
2377            h[i] ^= (tail(part) as u32).wrapping_mul(c[i]).rotate_left(rot[i]).wrapping_mul(c[n]);
2378        }
2379    }
2380    let len = data.len() as u32;
2381    for x in h.iter_mut() {
2382        *x ^= len;
2383    }
2384    let mix = |h: &mut [u32; 4]| {
2385        h[0] = h[0].wrapping_add(h[1]).wrapping_add(h[2]).wrapping_add(h[3]);
2386        h[1] = h[1].wrapping_add(h[0]);
2387        h[2] = h[2].wrapping_add(h[0]);
2388        h[3] = h[3].wrapping_add(h[0]);
2389    };
2390    mix(&mut h);
2391    for x in h.iter_mut() {
2392        *x = fmix32(*x);
2393    }
2394    mix(&mut h);
2395    h
2396}
2397
2398/// MurmurHash3_x64_128, seed 0.
2399fn murmur3_x64_128(data: &[u8]) -> [u64; 2] {
2400    let (c1, c2) = (0x87c3_7b91_1142_53d5u64, 0x4cf5_ad43_2745_937fu64);
2401    let (mut h1, mut h2) = (0u64, 0u64);
2402    let blocks = data.chunks_exact(16);
2403    let rest = blocks.remainder();
2404    for b in blocks {
2405        let k1 = u64::from_le_bytes(b[0..8].try_into().unwrap_or_default());
2406        let k2 = u64::from_le_bytes(b[8..16].try_into().unwrap_or_default());
2407        h1 ^= k1.wrapping_mul(c1).rotate_left(31).wrapping_mul(c2);
2408        h1 = h1.rotate_left(27).wrapping_add(h2).wrapping_mul(5).wrapping_add(0x52dc_e729);
2409        h2 ^= k2.wrapping_mul(c2).rotate_left(33).wrapping_mul(c1);
2410        h2 = h2.rotate_left(31).wrapping_add(h1).wrapping_mul(5).wrapping_add(0x3849_5ab5);
2411    }
2412    if rest.len() > 8 {
2413        h2 ^= tail(&rest[8..]).wrapping_mul(c2).rotate_left(33).wrapping_mul(c1);
2414    }
2415    if !rest.is_empty() {
2416        h1 ^= tail(&rest[..rest.len().min(8)]).wrapping_mul(c1).rotate_left(31).wrapping_mul(c2);
2417    }
2418    let len = data.len() as u64;
2419    h1 ^= len;
2420    h2 ^= len;
2421    h1 = h1.wrapping_add(h2);
2422    h2 = h2.wrapping_add(h1);
2423    h1 = fmix64(h1);
2424    h2 = fmix64(h2);
2425    h1 = h1.wrapping_add(h2);
2426    h2 = h2.wrapping_add(h1);
2427    [h1, h2]
2428}
2429
2430/// XXH32, seed 0.
2431fn xxh32(data: &[u8]) -> u32 {
2432    const P1: u32 = 0x9e37_79b1;
2433    const P2: u32 = 0x85eb_ca77;
2434    const P3: u32 = 0xc2b2_ae3d;
2435    const P4: u32 = 0x27d4_eb2f;
2436    const P5: u32 = 0x1656_67b1;
2437    let round = |acc: u32, lane: u32| acc.wrapping_add(lane.wrapping_mul(P2)).rotate_left(13).wrapping_mul(P1);
2438    let word = |b: &[u8]| u32::from_le_bytes([b[0], b[1], b[2], b[3]]);
2439    let mut rest = data;
2440    let mut h = if data.len() >= 16 {
2441        let mut v = [P1.wrapping_add(P2), P2, 0, 0u32.wrapping_sub(P1)];
2442        while rest.len() >= 16 {
2443            for (i, lane) in v.iter_mut().enumerate() {
2444                *lane = round(*lane, word(&rest[i * 4..]));
2445            }
2446            rest = &rest[16..];
2447        }
2448        v[0].rotate_left(1)
2449            .wrapping_add(v[1].rotate_left(7))
2450            .wrapping_add(v[2].rotate_left(12))
2451            .wrapping_add(v[3].rotate_left(18))
2452    } else {
2453        P5
2454    };
2455    h = h.wrapping_add(data.len() as u32);
2456    while rest.len() >= 4 {
2457        h = h.wrapping_add(word(rest).wrapping_mul(P3)).rotate_left(17).wrapping_mul(P4);
2458        rest = &rest[4..];
2459    }
2460    for b in rest {
2461        h = h.wrapping_add(u32::from(*b).wrapping_mul(P5)).rotate_left(11).wrapping_mul(P1);
2462    }
2463    h ^= h >> 15;
2464    h = h.wrapping_mul(P2);
2465    h ^= h >> 13;
2466    h = h.wrapping_mul(P3);
2467    h ^ (h >> 16)
2468}
2469
2470/// XXH64, seed 0.
2471fn xxh64(data: &[u8]) -> u64 {
2472    const P1: u64 = 0x9e37_79b1_85eb_ca87;
2473    const P2: u64 = 0xc2b2_ae3d_27d4_eb4f;
2474    const P3: u64 = 0x1656_67b1_9e37_79f9;
2475    const P4: u64 = 0x85eb_ca77_c2b2_ae63;
2476    const P5: u64 = 0x27d4_eb2f_1656_67c5;
2477    let round = |acc: u64, lane: u64| acc.wrapping_add(lane.wrapping_mul(P2)).rotate_left(31).wrapping_mul(P1);
2478    let merge = |acc: u64, v: u64| (acc ^ round(0, v)).wrapping_mul(P1).wrapping_add(P4);
2479    let word = |b: &[u8]| u64::from_le_bytes(b[..8].try_into().unwrap_or_default());
2480    let mut rest = data;
2481    let mut h = if data.len() >= 32 {
2482        let mut v = [P1.wrapping_add(P2), P2, 0, 0u64.wrapping_sub(P1)];
2483        while rest.len() >= 32 {
2484            for (i, lane) in v.iter_mut().enumerate() {
2485                *lane = round(*lane, word(&rest[i * 8..]));
2486            }
2487            rest = &rest[32..];
2488        }
2489        let mut h = v[0]
2490            .rotate_left(1)
2491            .wrapping_add(v[1].rotate_left(7))
2492            .wrapping_add(v[2].rotate_left(12))
2493            .wrapping_add(v[3].rotate_left(18));
2494        for lane in v {
2495            h = merge(h, lane);
2496        }
2497        h
2498    } else {
2499        P5
2500    };
2501    h = h.wrapping_add(data.len() as u64);
2502    while rest.len() >= 8 {
2503        h = (h ^ round(0, word(rest))).rotate_left(27).wrapping_mul(P1).wrapping_add(P4);
2504        rest = &rest[8..];
2505    }
2506    if rest.len() >= 4 {
2507        h = (h ^ u64::from(u32::from_le_bytes([rest[0], rest[1], rest[2], rest[3]])).wrapping_mul(P1))
2508            .rotate_left(23)
2509            .wrapping_mul(P2)
2510            .wrapping_add(P3);
2511        rest = &rest[4..];
2512    }
2513    for b in rest {
2514        h = (h ^ u64::from(*b).wrapping_mul(P5)).rotate_left(11).wrapping_mul(P1);
2515    }
2516    h ^= h >> 33;
2517    h = h.wrapping_mul(P2);
2518    h ^= h >> 29;
2519    h = h.wrapping_mul(P3);
2520    h ^ (h >> 32)
2521}
2522
2523#[cfg(test)]
2524mod tests {
2525    use super::*;
2526
2527    #[test]
2528    fn trims_with_ranges() {
2529        assert_eq!(trim(b"  abc  ", TRIM_CHARACTERS), b"abc");
2530        assert_eq!(trim(b"abcxyz", b"a..c"), b"xyz");
2531        assert_eq!(trim(b"a..", b"a.."), b"");
2532        assert_eq!(rtrim(b"1.500", b"0"), b"1.5");
2533    }
2534
2535    #[test]
2536    fn substr_like_php() {
2537        assert_eq!(substr(b"abcdef", -2, None), b"ef");
2538        assert_eq!(substr(b"abcdef", 1, Some(-1)), b"bcde");
2539        assert_eq!(substr(b"abc", 5, None), b"");
2540        assert_eq!(substr(b"abc", i64::MIN, Some(i64::MIN)), b"");
2541    }
2542
2543    #[test]
2544    fn explode_limits() {
2545        assert_eq!(explode(b",", b"a,b,c", 2).unwrap(), vec![&b"a"[..], b"b,c"]);
2546        assert_eq!(explode(b",", b"a,b,c", -1).unwrap(), vec![&b"a"[..], b"b"]);
2547        assert_eq!(explode(b",", b"abc", -1).unwrap(), Vec::<&[u8]>::new());
2548        assert!(explode(b"", b"a", 1).is_err());
2549    }
2550
2551    #[test]
2552    fn replaces_and_counts() {
2553        assert_eq!(str_replace(b"a", b"bb", b"aXa"), (Cow::Owned(b"bbXbb".to_vec()), 2));
2554        let (r, n) = str_replace_array(&[b"a", b"b"], Replace::All(b"b"), b"ab", false);
2555        assert_eq!((r.as_ref(), n), (&b"bb"[..], 3));
2556    }
2557
2558    #[test]
2559    fn strtr_longest_first() {
2560        let r = strtr_array(b"Hi all", &[(b"Hi", b"Hello"), (b"Hi all", b"Hey"), (b"a", b"A")]);
2561        assert_eq!(r.as_ref(), b"Hey");
2562    }
2563
2564    #[test]
2565    fn compares_like_php() {
2566        assert_eq!(strcmp(b"a", b"c"), -2);
2567        assert_eq!(strcmp(b"ab", b"abcd"), -1);
2568        assert_eq!(strcasecmp(b"HELLO", b"hello"), 0);
2569    }
2570}