zx/
name.rs

1// Copyright 2024 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
5use crate::sys::ZX_MAX_NAME_LEN;
6use crate::Status;
7use bstr::BStr;
8use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};
9
10/// A wrapper around zircon name fields.
11///
12/// This type is ABI-compatible with the syscall interface but offers convenient ways to print and
13/// create UTF-8 strings.
14///
15/// Can be created from regular strings or byte slices.
16#[derive(
17    IntoBytes,
18    Copy,
19    Clone,
20    Default,
21    Eq,
22    KnownLayout,
23    FromBytes,
24    Hash,
25    Immutable,
26    PartialEq,
27    PartialOrd,
28    Ord,
29)]
30#[repr(transparent)]
31pub struct Name([u8; ZX_MAX_NAME_LEN]);
32
33impl Name {
34    /// Create a new name value.
35    ///
36    /// Returns an error if the string is too long to fit or contains null bytes.
37    #[inline]
38    pub const fn new(s: &str) -> Result<Self, Status> {
39        Self::from_bytes(s.as_bytes())
40    }
41
42    /// Create a new name value, truncating the input string to fit and stripping null bytes if
43    /// necessary.
44    #[inline]
45    pub const fn new_lossy(s: &str) -> Self {
46        Self::from_bytes_lossy(s.as_bytes())
47    }
48
49    /// Create a new name value from raw bytes.
50    ///
51    /// Returns an error if the slice is longer than `ZX_MAX_LEN_NAME - 1` or contains null bytes.
52    #[inline]
53    pub const fn from_bytes(b: &[u8]) -> Result<Self, Status> {
54        if b.len() >= ZX_MAX_NAME_LEN {
55            return Err(Status::INVALID_ARGS);
56        }
57
58        let mut inner = [0u8; ZX_MAX_NAME_LEN];
59        let mut i = 0;
60        while i < b.len() {
61            if b[i] == 0 {
62                return Err(Status::INVALID_ARGS);
63            }
64            inner[i] = b[i];
65            i += 1;
66        }
67
68        Ok(Self(inner))
69    }
70
71    /// Create a new name value from raw bytes, truncating the input to fit if necessary. Strips
72    /// null bytes.
73    #[inline]
74    pub const fn from_bytes_lossy(b: &[u8]) -> Self {
75        let to_copy = if b.len() <= ZX_MAX_NAME_LEN - 1 { b.len() } else { ZX_MAX_NAME_LEN - 1 };
76
77        let mut inner = [0u8; ZX_MAX_NAME_LEN];
78        let mut source_idx = 0;
79        let mut dest_idx = 0;
80        while source_idx < to_copy {
81            if b[source_idx] != 0 {
82                inner[dest_idx] = b[source_idx];
83                dest_idx += 1;
84            }
85            source_idx += 1;
86        }
87
88        Self(inner)
89    }
90
91    fn before_nulls(&self) -> &[u8] {
92        self.0.splitn(ZX_MAX_NAME_LEN - 1, |b| *b == 0).next().unwrap_or(&[])
93    }
94
95    /// Returns the length of the name before a terminating null byte.
96    #[inline]
97    pub fn len(&self) -> usize {
98        self.before_nulls().len()
99    }
100
101    /// Returns whether the name has any non-null bytes.
102    #[inline]
103    pub fn is_empty(&self) -> bool {
104        self.before_nulls().is_empty()
105    }
106
107    /// Return the non-null portion of the name as a BStr.
108    #[inline]
109    pub fn as_bstr(&self) -> &BStr {
110        BStr::new(self.before_nulls())
111    }
112}
113
114impl std::fmt::Debug for Name {
115    #[inline]
116    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
117        std::fmt::Debug::fmt(self.as_bstr(), f)
118    }
119}
120
121impl std::fmt::Display for Name {
122    #[inline]
123    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
124        std::fmt::Display::fmt(self.as_bstr(), f)
125    }
126}
127
128impl PartialEq<str> for Name {
129    #[inline]
130    fn eq(&self, other: &str) -> bool {
131        self.before_nulls() == other.as_bytes()
132    }
133}
134
135impl PartialEq<&str> for Name {
136    #[inline]
137    fn eq(&self, other: &&str) -> bool {
138        self.eq(*other)
139    }
140}
141
142impl PartialEq<Name> for str {
143    #[inline]
144    fn eq(&self, other: &Name) -> bool {
145        self.as_bytes() == other.before_nulls()
146    }
147}
148
149impl PartialEq<Name> for &str {
150    #[inline]
151    fn eq(&self, other: &Name) -> bool {
152        (*self).eq(other)
153    }
154}
155
156#[cfg(test)]
157mod tests {
158    use super::*;
159
160    #[test]
161    fn empty_name() {
162        assert_eq!(Name::new("").unwrap(), "");
163        assert_eq!(Name::new_lossy(""), "");
164    }
165
166    #[test]
167    fn short_name() {
168        assert_eq!(Name::new("v").unwrap(), "v");
169        assert_eq!(Name::new_lossy("v"), "v");
170    }
171
172    #[test]
173    fn max_len_name() {
174        let max_len_name = "a_great_maximum_length_vmo_name";
175        assert_eq!(max_len_name.len(), ZX_MAX_NAME_LEN - 1);
176        assert_eq!(Name::new(max_len_name).unwrap(), max_len_name);
177        assert_eq!(Name::new_lossy(max_len_name), max_len_name);
178    }
179
180    #[test]
181    fn too_long_name() {
182        let too_long_name = "bad_really_too_too_long_vmo_name";
183        assert_eq!(too_long_name.len(), ZX_MAX_NAME_LEN);
184        assert_eq!(Name::new(too_long_name), Err(Status::INVALID_ARGS));
185        assert_eq!(Name::new_lossy(too_long_name), "bad_really_too_too_long_vmo_nam");
186    }
187
188    #[test]
189    fn interior_null_handling() {
190        assert_eq!(Name::new("lol\0lol"), Err(Status::INVALID_ARGS));
191        assert_eq!(Name::new_lossy("lol\0lol"), "lollol");
192    }
193}