Skip to main content

zr/
string.rs

1// Copyright 2026 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5/// Parse a decimal integer from a string slice at compile time.
6///
7/// Returns a `Some(usize)` value on success, or `None` on failure.
8pub const fn parse_usize(s: &str) -> Option<usize> {
9    let bytes = s.as_bytes();
10    if bytes.is_empty() {
11        return None;
12    }
13    let mut val: usize = 0;
14    let mut i = 0;
15    while i < bytes.len() {
16        let b = bytes[i];
17        if b < b'0' || b > b'9' {
18            return None;
19        }
20        let digit = (b - b'0') as usize;
21        match val.checked_mul(10) {
22            Some(v) => match v.checked_add(digit) {
23                Some(final_val) => val = final_val,
24                None => return None,
25            },
26            None => return None,
27        }
28        i += 1;
29    }
30    Some(val)
31}
32
33/// Copy a string slice into a fixed-size byte array at compile time, leaving space for a null
34/// terminator.
35pub const fn to_array<const N: usize>(s: &str) -> [u8; N] {
36    assert!(N > 0, "N must be non-zero");
37    let bytes = s.as_bytes();
38    let mut arr = [0; N];
39    let mut i = 0;
40    while i < bytes.len() && i < N - 1 {
41        arr[i] = bytes[i];
42        i += 1;
43    }
44    arr
45}