1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
// Copyright 2024 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use crate::sys::ZX_MAX_NAME_LEN;
use crate::Status;
use bstr::BStr;
use zerocopy::{AsBytes, FromBytes, FromZeros, NoCell};

/// A wrapper around zircon name fields.
///
/// This type is ABI-compatible with the syscall interface but offers convenient ways to print and
/// create UTF-8 strings.
///
/// Can be created from regular strings or byte slices.
#[derive(
    AsBytes,
    Copy,
    Clone,
    Default,
    Eq,
    FromBytes,
    FromZeros,
    Hash,
    NoCell,
    PartialEq,
    PartialOrd,
    Ord,
)]
#[repr(transparent)]
pub struct Name([u8; ZX_MAX_NAME_LEN]);

impl Name {
    /// Create a new name value.
    ///
    /// Returns an error if the string is too long to fit or contains null bytes.
    #[inline]
    pub const fn new(s: &str) -> Result<Self, Status> {
        Self::from_bytes(s.as_bytes())
    }

    /// Create a new name value, truncating the input string to fit and stripping null bytes if
    /// necessary.
    #[inline]
    pub const fn new_lossy(s: &str) -> Self {
        Self::from_bytes_lossy(s.as_bytes())
    }

    /// Create a new name value from raw bytes.
    ///
    /// Returns an error if the slice is longer than `ZX_MAX_LEN_NAME - 1` or contains null bytes.
    #[inline]
    pub const fn from_bytes(b: &[u8]) -> Result<Self, Status> {
        if b.len() >= ZX_MAX_NAME_LEN {
            return Err(Status::INVALID_ARGS);
        }

        let mut inner = [0u8; ZX_MAX_NAME_LEN];
        let mut i = 0;
        while i < b.len() {
            if b[i] == 0 {
                return Err(Status::INVALID_ARGS);
            }
            inner[i] = b[i];
            i += 1;
        }

        Ok(Self(inner))
    }

    /// Create a new name value from raw bytes, truncating the input to fit if necessary. Strips
    /// null bytes.
    #[inline]
    pub const fn from_bytes_lossy(b: &[u8]) -> Self {
        let to_copy = if b.len() <= ZX_MAX_NAME_LEN - 1 { b.len() } else { ZX_MAX_NAME_LEN - 1 };

        let mut inner = [0u8; ZX_MAX_NAME_LEN];
        let mut source_idx = 0;
        let mut dest_idx = 0;
        while source_idx < to_copy {
            if b[source_idx] != 0 {
                inner[dest_idx] = b[source_idx];
                dest_idx += 1;
            }
            source_idx += 1;
        }

        Self(inner)
    }

    pub(crate) fn from_raw(mut inner: [u8; ZX_MAX_NAME_LEN]) -> Self {
        // Set the last byte to null just in case this is being constructed from an invalid array.
        inner[ZX_MAX_NAME_LEN - 1] = 0;
        Self(inner)
    }

    fn before_nulls(&self) -> &[u8] {
        self.0.splitn(ZX_MAX_NAME_LEN - 1, |b| *b == 0).next().unwrap_or(&[])
    }

    /// Returns the length of the name before a terminating null byte.
    #[inline]
    pub fn len(&self) -> usize {
        self.before_nulls().len()
    }

    /// Returns whether the name has any non-null bytes.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.before_nulls().is_empty()
    }

    /// Return the non-null portion of the name as a BStr.
    #[inline]
    pub fn as_bstr(&self) -> &BStr {
        BStr::new(self.before_nulls())
    }
}

impl std::fmt::Debug for Name {
    #[inline]
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        std::fmt::Debug::fmt(self.as_bstr(), f)
    }
}

impl std::fmt::Display for Name {
    #[inline]
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        std::fmt::Display::fmt(self.as_bstr(), f)
    }
}

impl PartialEq<str> for Name {
    #[inline]
    fn eq(&self, other: &str) -> bool {
        self.before_nulls() == other.as_bytes()
    }
}

impl PartialEq<&str> for Name {
    #[inline]
    fn eq(&self, other: &&str) -> bool {
        self.eq(*other)
    }
}

impl PartialEq<Name> for str {
    #[inline]
    fn eq(&self, other: &Name) -> bool {
        self.as_bytes() == other.before_nulls()
    }
}

impl PartialEq<Name> for &str {
    #[inline]
    fn eq(&self, other: &Name) -> bool {
        (*self).eq(other)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn empty_name() {
        assert_eq!(Name::new("").unwrap(), "");
        assert_eq!(Name::new_lossy(""), "");
    }

    #[test]
    fn short_name() {
        assert_eq!(Name::new("v").unwrap(), "v");
        assert_eq!(Name::new_lossy("v"), "v");
    }

    #[test]
    fn max_len_name() {
        let max_len_name = "a_great_maximum_length_vmo_name";
        assert_eq!(max_len_name.len(), ZX_MAX_NAME_LEN - 1);
        assert_eq!(Name::new(max_len_name).unwrap(), max_len_name);
        assert_eq!(Name::new_lossy(max_len_name), max_len_name);
    }

    #[test]
    fn too_long_name() {
        let too_long_name = "bad_really_too_too_long_vmo_name";
        assert_eq!(too_long_name.len(), ZX_MAX_NAME_LEN);
        assert_eq!(Name::new(too_long_name), Err(Status::INVALID_ARGS));
        assert_eq!(Name::new_lossy(too_long_name), "bad_really_too_too_long_vmo_nam");
    }

    #[test]
    fn interior_null_handling() {
        assert_eq!(Name::new("lol\0lol"), Err(Status::INVALID_ARGS));
        assert_eq!(Name::new_lossy("lol\0lol"), "lollol");
    }
}