warcraft3_stats_observer/
string_utils.rs1use std::borrow::Cow;
2use std::fmt::{Debug, Display};
3
4#[repr(C)]
14#[derive(Clone, Copy, PartialEq, Eq, Hash)]
15pub struct PaddedString<const SIZE: usize> {
16 array: [u8; SIZE],
17}
18
19impl<const SIZE: usize> PaddedString<SIZE> {
20 pub fn as_bytes(&self) -> &[u8] {
24 &self.array[..self.len()]
25 }
26
27 pub fn to_string_lossy(&self) -> Cow<'_, str> {
31 String::from_utf8_lossy(self.as_bytes())
32 }
33
34 pub fn len(&self) -> usize {
37 self.array.iter().position(|&b| b == 0).unwrap_or(SIZE)
38 }
39
40 pub fn is_empty(&self) -> bool {
42 self.array.first() == Some(&0)
43 }
44}
45
46impl<const SIZE: usize> Display for PaddedString<SIZE> {
47 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
48 write!(f, "{}", self.to_string_lossy())
49 }
50}
51
52impl<const SIZE: usize> Debug for PaddedString<SIZE> {
53 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54 Debug::fmt(&self.to_string_lossy(), f)
55 }
56}
57
58impl<const SIZE: usize> AsRef<[u8]> for PaddedString<SIZE> {
59 fn as_ref(&self) -> &[u8] {
60 self.as_bytes()
61 }
62}