Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_core/src/string.rs

1.6 KiB, 8 runs

created by r1870400018:120, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1use crate::{
2 prelude::*,
3 byte::B32,
4};
5
6use std::fmt;
7
8/// Tests whether a static string is contained in the given slice.
9pub fn contains_str(target: &'static str, list: &[&'static str]) -> bool {
10 for &s in list {
11 if s == target {
12 return true;
13 }
14 }
15 false
16}
17
18/// Inspect the Unicode value of the first characters of the given string.
19pub fn inspect(s: &str, n: usize) {
20 for (i, c) in s.chars().enumerate() {
21 println!("Character {}: '{}' (U+{:04X})", i, c, c as u32);
22 if i >= n {
23 break;
24 }
25 }
26}
27
28pub trait ToHexString: std::fmt::LowerHex + Copy + Sized {
29 fn to_hex_string(&self) -> String {
30 to_hex_string(*self)
31 }
32}
33
34fn to_hex_string<T: std::fmt::LowerHex>(v: T) -> String {
35 let max_digits = std::mem::size_of::<T>() * 2;
36 format!("{:0width$x}", v, width = max_digits)
37}
38
39impl ToHexString for B32 {
40 fn to_hex_string(&self) -> String {
41 format!("{:x}", self)
42 }
43}
44
45impl fmt::LowerHex for B32 {
46 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47 for byt in &self.0 {
48 ok!(write!(f, "{:02x}", byt));
49 }
50 Ok(())
51 }
52}
53
54impl ToHexString for usize {
55 fn to_hex_string(&self) -> String {
56 format!("{:x}", self)
57 }
58}
59
60pub fn parse_hex_char(c: char) -> Outcome<u8> {
61 match c {
62 '0'..='9' => Ok(c as u8 - b'0'),
63 'a'..='f' => Ok(c as u8 - b'a' + 10),
64 'A'..='F' => Ok(c as u8 - b'A' + 10),
65 _ => Err(err!(
66 "'{}' is not a valid hexadecimal digit.", c;
67 Invalid, Input, String, Decode)),
68 }
69}