openthread/ot/types/
operational_dataset.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
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
// 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 std::ops::Deref;

/// Functional equivalent of [`otsys::otOperationalDataset`](crate::otsys::otOperationalDataset).
#[derive(Default, Clone)]
#[repr(transparent)]
pub struct OperationalDataset(pub otOperationalDataset);

impl_ot_castable!(OperationalDataset, otOperationalDataset);

impl OperationalDataset {
    /// Returns an empty operational dataset.
    pub fn empty() -> OperationalDataset {
        Self::default()
    }

    /// Returns true if this dataset is considered "complete"
    pub fn is_complete(&self) -> bool {
        self.get_active_timestamp().is_some()
            && self.get_network_name().is_some()
            && self.get_network_key().is_some()
            && self.get_extended_pan_id().is_some()
            && self.get_mesh_local_prefix().is_some()
            && self.get_pan_id().is_some()
            && self.get_channel().is_some()
            && self.get_pskc().is_some()
            && self.get_security_policy().is_some()
            && self.get_channel_mask().is_some()
    }

    /// Clears all of the fields in this dataset.
    pub fn clear(&mut self) {
        *self = Self::empty();
    }

    // TODO: Not clear what the OpenThread API is to accomplish this.
    // pub fn to_tlvs(&self) -> OperationalDatasetTlvs {
    //     todo!()
    // }
}

impl std::fmt::Debug for OperationalDataset {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut ds = f.debug_struct("OperationalDataset");

        if let Some(x) = self.get_network_name() {
            ds.field("network_name", &x);
        }
        if let Some(x) = self.get_extended_pan_id() {
            ds.field("xpanid", &x);
        }
        if let Some(x) = self.get_network_key() {
            ds.field("network_key", &x);
        }
        if let Some(x) = self.get_mesh_local_prefix() {
            ds.field("mesh_local_prefix", &x);
        }
        if let Some(x) = self.get_pan_id() {
            ds.field("panid", &x);
        }
        if let Some(x) = self.get_channel() {
            ds.field("channel", &x);
        }
        if let Some(x) = self.get_channel_mask() {
            ds.field("channel_mask", &x);
        }
        if let Some(x) = self.get_pskc() {
            ds.field("pskc", &x);
        }
        if let Some(x) = self.get_security_policy() {
            ds.field("security_policy", &x);
        }
        if let Some(x) = self.get_delay() {
            ds.field("delay", &x);
        }
        if let Some(x) = self.get_active_timestamp() {
            ds.field("active_timestamp", &x);
        }
        if let Some(x) = self.get_pending_timestamp() {
            ds.field("pending_timestamp", &x);
        }
        ds.finish()
    }
}

impl OperationalDataset {
    /// Returns the channel index, if present.
    pub fn get_channel(&self) -> Option<ChannelIndex> {
        self.0.mComponents.mIsChannelPresent.then(|| self.0.mChannel.try_into().unwrap())
    }

    /// Returns the channel mask, if present.
    pub fn get_channel_mask(&self) -> Option<ChannelMask> {
        self.0.mComponents.mIsChannelMaskPresent.then(|| self.0.mChannelMask.into())
    }

    /// Returns the delay, if present.
    pub fn get_delay(&self) -> Option<u32> {
        self.0.mComponents.mIsDelayPresent.then_some(self.0.mDelay)
    }

    /// Returns the extended PAN-ID, if present.
    pub fn get_extended_pan_id(&self) -> Option<&ExtendedPanId> {
        self.0
            .mComponents
            .mIsExtendedPanIdPresent
            .then(|| ExtendedPanId::ref_from_ot_ref(&self.0.mExtendedPanId))
    }

    /// Returns the network key, if present.
    pub fn get_network_key(&self) -> Option<&NetworkKey> {
        self.0
            .mComponents
            .mIsNetworkKeyPresent
            .then(|| NetworkKey::ref_from_ot_ref(&self.0.mNetworkKey))
    }

    /// Returns the network key, if present.
    pub fn get_pskc(&self) -> Option<&Pskc> {
        self.0.mComponents.mIsPskcPresent.then(|| Pskc::ref_from_ot_ref(&self.0.mPskc))
    }

    /// Returns the network name, if present.
    pub fn get_network_name(&self) -> Option<&NetworkName> {
        self.0
            .mComponents
            .mIsNetworkNamePresent
            .then(|| NetworkName::ref_from_ot_ref(&self.0.mNetworkName))
    }

    /// Returns the PAN-ID, if present.
    pub fn get_pan_id(&self) -> Option<PanId> {
        self.0.mComponents.mIsPanIdPresent.then_some(self.0.mPanId)
    }

    /// Returns the active timestamp, if present.
    pub fn get_active_timestamp(&self) -> Option<Timestamp> {
        self.0.mComponents.mIsActiveTimestampPresent.then(|| self.0.mActiveTimestamp.into())
    }

    /// Returns the pending timestamp, if present.
    pub fn get_pending_timestamp(&self) -> Option<Timestamp> {
        self.0.mComponents.mIsPendingTimestampPresent.then(|| self.0.mPendingTimestamp.into())
    }

    /// Returns the security policy, if present.
    pub fn get_security_policy(&self) -> Option<&SecurityPolicy> {
        self.0
            .mComponents
            .mIsSecurityPolicyPresent
            .then(|| SecurityPolicy::ref_from_ot_ref(&self.0.mSecurityPolicy))
    }

    /// Returns the mesh-local prefix, if present.
    pub fn get_mesh_local_prefix(&self) -> Option<&MeshLocalPrefix> {
        self.0
            .mComponents
            .mIsMeshLocalPrefixPresent
            .then_some(&self.0.mMeshLocalPrefix)
            .map(Into::into)
    }
}

impl OperationalDataset {
    /// Sets or clears the channel index.
    pub fn set_channel(&mut self, opt: Option<ChannelIndex>) {
        if let Some(x) = opt {
            self.0.mChannel = x.into();
            self.0.mComponents.mIsChannelPresent = true;
        } else {
            self.0.mComponents.mIsChannelPresent = false;
        }
    }

    /// Sets or clears the channel mask.
    pub fn set_channel_mask(&mut self, opt: Option<ChannelMask>) {
        if let Some(x) = opt {
            self.0.mChannelMask = x.into();
            self.0.mComponents.mIsChannelMaskPresent = true;
        } else {
            self.0.mComponents.mIsChannelMaskPresent = false;
        }
    }

    /// Sets or clears the delay.
    pub fn set_delay(&mut self, opt: Option<u32>) {
        if let Some(x) = opt {
            self.0.mDelay = x;
            self.0.mComponents.mIsDelayPresent = true;
        } else {
            self.0.mComponents.mIsDelayPresent = false;
        }
    }

    /// Sets or clears the extended PAN-ID.
    pub fn set_extended_pan_id(&mut self, opt: Option<&ExtendedPanId>) {
        if let Some(x) = opt {
            self.0.mExtendedPanId = *x.as_ot_ref();
            self.0.mComponents.mIsExtendedPanIdPresent = true;
        } else {
            self.0.mComponents.mIsExtendedPanIdPresent = false;
        }
    }

    /// Sets or clears the network key.
    pub fn set_network_key(&mut self, opt: Option<&NetworkKey>) {
        if let Some(x) = opt {
            self.0.mNetworkKey = *x.as_ot_ref();
            self.0.mComponents.mIsNetworkKeyPresent = true;
        } else {
            self.0.mComponents.mIsNetworkKeyPresent = false;
        }
    }

    /// Sets or clears the network name.
    pub fn set_network_name(&mut self, opt: Option<&NetworkName>) {
        if let Some(x) = opt {
            self.0.mNetworkName = *x.as_ot_ref();
            self.0.mComponents.mIsNetworkNamePresent = true;
        } else {
            self.0.mComponents.mIsNetworkNamePresent = false;
        }
    }

    /// Sets or clears the PAN-ID.
    pub fn set_pan_id(&mut self, opt: Option<PanId>) {
        if let Some(x) = opt {
            self.0.mPanId = x;
            self.0.mComponents.mIsPanIdPresent = true;
        } else {
            self.0.mComponents.mIsPanIdPresent = false;
        }
    }

    /// Sets or clears the active timestamp
    pub fn set_active_timestamp(&mut self, opt: Option<Timestamp>) {
        if let Some(x) = opt {
            self.0.mActiveTimestamp = x.into();
            self.0.mComponents.mIsActiveTimestampPresent = true;
        } else {
            self.0.mComponents.mIsActiveTimestampPresent = false;
        }
    }

    /// Sets or clears the pending timestamp.
    pub fn set_pending_timestamp(&mut self, opt: Option<Timestamp>) {
        if let Some(x) = opt {
            self.0.mPendingTimestamp = x.into();
            self.0.mComponents.mIsPendingTimestampPresent = true;
        } else {
            self.0.mComponents.mIsPendingTimestampPresent = false;
        }
    }

    /// Sets or clears the security policy.
    pub fn set_security_policy(&mut self, opt: Option<SecurityPolicy>) {
        if let Some(x) = opt {
            self.0.mSecurityPolicy = *x.as_ot_ref();
            self.0.mComponents.mIsSecurityPolicyPresent = true;
        } else {
            self.0.mComponents.mIsSecurityPolicyPresent = false;
        }
    }

    /// Sets or clears the mesh-local prefix.
    pub fn set_mesh_local_prefix(&mut self, opt: Option<&MeshLocalPrefix>) {
        if let Some(x) = opt {
            self.0.mMeshLocalPrefix = *x.as_ot_ref();
            self.0.mComponents.mIsMeshLocalPrefixPresent = true;
        } else {
            self.0.mComponents.mIsMeshLocalPrefixPresent = false;
        }
    }
}

/// Functional equivalent of [`otsys::otOperationalDatasetTlvs`](crate::otsys::otOperationalDatasetTlvs).
#[derive(Debug, Default, Clone)]
#[repr(transparent)]
pub struct OperationalDatasetTlvs(pub otOperationalDatasetTlvs);

impl_ot_castable!(OperationalDatasetTlvs, otOperationalDatasetTlvs);

impl OperationalDatasetTlvs {
    /// Tries to parse the TLVs into a dataset
    /// Functional equivalent to `otDatasetParseTlvs`
    pub fn try_to_dataset(&self) -> Result<OperationalDataset> {
        let mut ret = OperationalDataset::default();
        Error::from(unsafe { otDatasetParseTlvs(self.as_ot_ptr(), ret.as_ot_mut_ptr()) })
            .into_result()?;
        Ok(ret)
    }

    /// Tries to create a `OperationalDatasetTlvs` instance from the given byte slice.
    pub fn try_from_slice(slice: &[u8]) -> Result<Self, ot::WrongSize> {
        let mut ret = Self::default();
        let len = slice.len();

        if len > OT_OPERATIONAL_DATASET_MAX_LENGTH as usize {
            return Err(ot::WrongSize);
        }

        ret.0.mLength = len.try_into().unwrap();

        ret.0.mTlvs[0..len].clone_from_slice(slice);

        Ok(ret)
    }

    /// Returns length of the TLVs in bytes. 0-16.
    #[allow(clippy::len_without_is_empty)]
    pub fn len(&self) -> usize {
        self.0.mLength as usize
    }

    /// Returns the TLVs as a byte slice with no trailing zeros.
    pub fn as_slice(&self) -> &[u8] {
        &self.0.mTlvs[0..self.len()]
    }

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

impl Deref for OperationalDatasetTlvs {
    type Target = [u8];

    fn deref(&self) -> &Self::Target {
        self.as_slice()
    }
}

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

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

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

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

impl From<OperationalDatasetTlvs> for Vec<u8> {
    fn from(value: OperationalDatasetTlvs) -> Self {
        value.to_vec()
    }
}

impl TryFrom<OperationalDatasetTlvs> for OperationalDataset {
    type Error = ot::Error;

    fn try_from(value: OperationalDatasetTlvs) -> Result<Self, Self::Error> {
        value.try_to_dataset()
    }
}

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

    #[test]
    fn test_operational_dataset() {
        let dataset_bytes = hex::decode("0e08000062cc8de70000000300001635060004001fffe0020830b02192978a444f0708fd70a9fb17d60000030d4e4553542d50414e2d3043454401020ced0410f73d3809ffd94b329fdab33ba781ba910c0402a0f778").unwrap();

        let dataset_tlvs = OperationalDatasetTlvs::try_from_slice(&dataset_bytes).unwrap();

        let dataset = dataset_tlvs.try_to_dataset().unwrap();

        println!("dataset = {dataset:#?}");
    }
}