openthread/ot/types/
network_name.rs

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
// Copyright 2021 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::prelude_internal::*;

use core::cmp::Ordering;
use core::fmt::{Debug, Formatter};

/// Network Name.
/// Functional equivalent of [`otsys::otNetworkName`](crate::otsys::otNetworkName).
#[derive(Default, Copy, Clone)]
#[repr(transparent)]
pub struct NetworkName(pub otNetworkName);

impl_ot_castable!(NetworkName, otNetworkName);

impl Debug for NetworkName {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        match self.try_as_str() {
            Ok(s) => s.fmt(f),
            Err(_) => write!(f, "[{:?}]", hex::encode(self.as_slice())),
        }
    }
}

impl PartialEq for NetworkName {
    fn eq(&self, other: &Self) -> bool {
        self.as_slice() == other.as_slice()
    }
}

impl Eq for NetworkName {}

impl PartialOrd for NetworkName {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for NetworkName {
    fn cmp(&self, other: &Self) -> Ordering {
        self.as_slice().cmp(other.as_slice())
    }
}

impl NetworkName {
    /// Tries to create a network name instance from the given byte slice.
    pub fn try_from_slice(slice: &[u8]) -> Result<Self, ot::WrongSize> {
        let len = slice.len();
        if len > OT_NETWORK_NAME_MAX_SIZE as usize {
            return Err(ot::WrongSize);
        }

        sa::assert_eq_size!(u8, ::std::os::raw::c_char);
        let slice = zerocopy::Ref::into_ref(
            zerocopy::Ref::<_, [::std::os::raw::c_char]>::from_bytes(slice).unwrap(),
        );

        let mut ret = NetworkName::default();
        ret.0.m8[0..len].clone_from_slice(slice);

        Ok(ret)
    }

    /// Returns length of the network name in bytes. 0-16.
    #[allow(clippy::len_without_is_empty)]
    pub fn len(&self) -> usize {
        self.0.m8.iter().position(|&x| x == 0).unwrap_or(OT_NETWORK_NAME_MAX_SIZE as usize)
    }

    /// Returns the network name as a byte slice with no trailing zeros.
    pub fn as_slice(&self) -> &[u8] {
        use zerocopy::IntoBytes as _;

        sa::assert_eq_size!(u8, ::std::os::raw::c_char);
        self.0.m8[0..self.len()].as_bytes()
    }

    /// Creates a `Vec<u8>` from the raw bytes of this network name.
    pub fn to_vec(&self) -> Vec<u8> {
        self.as_slice().to_vec()
    }

    /// Tries to return a representation of this network name as a string slice.
    pub fn try_as_str(&self) -> Result<&str, std::str::Utf8Error> {
        std::str::from_utf8(self.as_slice())
    }

    /// Returns as a c-string pointer
    pub fn as_c_str(&self) -> *const ::std::os::raw::c_char {
        self.0.m8.as_ptr()
    }
}

impl<'a> TryFrom<&'a str> for NetworkName {
    type Error = ot::WrongSize;

    fn try_from(value: &'a str) -> Result<Self, Self::Error> {
        NetworkName::try_from_slice(value.as_bytes())
    }
}

impl<'a> TryFrom<&'a [u8]> for NetworkName {
    type Error = ot::WrongSize;

    fn try_from(value: &'a [u8]) -> Result<Self, Self::Error> {
        NetworkName::try_from_slice(value)
    }
}

impl TryFrom<Vec<u8>> for NetworkName {
    type Error = ot::WrongSize;

    fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
        NetworkName::try_from_slice(&value)
    }
}

impl From<&NetworkName> for otNetworkName {
    fn from(x: &NetworkName) -> Self {
        *x.as_ot_ref()
    }
}