tosca 0.1.1

A library that acts as an interface between a device and its controller.
Documentation
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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
use hashbrown::DefaultHashBuilder;

use indexmap::set::{IndexSet, IntoIter, Iter};

use serde::{Deserialize, Serialize};

use crate::macros::set;

/// All [`Hazard`]s.
pub const ALL_HAZARDS: &[Hazard] = &[
    Hazard::AirPoisoning,
    Hazard::Asphyxia,
    Hazard::AudioVideoDisplay,
    Hazard::AudioVideoRecordAndStore,
    Hazard::ElectricEnergyConsumption,
    Hazard::Explosion,
    Hazard::FireHazard,
    Hazard::GasConsumption,
    Hazard::LogEnergyConsumption,
    Hazard::LogUsageTime,
    Hazard::PaySubscriptionFee,
    Hazard::PowerOutage,
    Hazard::PowerSurge,
    Hazard::RecordIssuedCommands,
    Hazard::RecordUserPreferences,
    Hazard::SpendMoney,
    Hazard::SpoiledFood,
    Hazard::TakeDeviceScreenshots,
    Hazard::TakePictures,
    Hazard::UnauthorisedPhysicalAccess,
    Hazard::VideoDisplay,
    Hazard::VideoRecordAndStore,
    Hazard::WaterConsumption,
    Hazard::WaterFlooding,
];

/// All possible hazards for a device route.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Serialize)]
#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
pub enum Hazard {
    /// The execution may release toxic gases.
    AirPoisoning,
    /// The execution may cause oxygen deficiency by gaseous substances.
    Asphyxia,
    /// The execution authorises an application to display a video
    /// with audio coming from a device.
    AudioVideoDisplay,
    /// The execution authorises an application to record and save a video with
    /// audio coming from a device on persistent storage.
    AudioVideoRecordAndStore,
    /// The execution enables a device which consumes electricity.
    ElectricEnergyConsumption,
    /// The execution may cause an explosion.
    Explosion,
    /// The execution may cause fire.
    FireHazard,
    /// The execution enables a device which consumes gas.
    GasConsumption,
    /// The execution authorises an application to get and save information
    /// about a device's energy impact.
    LogEnergyConsumption,
    /// The execution authorises an application to get and save information
    /// about a device's duration of use.
    LogUsageTime,
    /// The execution authorises an application to use payment information and
    /// make a periodic payment.
    PaySubscriptionFee,
    /// The execution may cause an interruption in the supply of electricity.
    PowerOutage,
    /// The execution may lead to exposure to high voltages.
    PowerSurge,
    /// The execution authorises an application to get and save user inputs.
    RecordIssuedCommands,
    /// The execution authorises an application to get and save information
    /// about user's preferences.
    RecordUserPreferences,
    /// The execution authorises an application to use payment information and
    /// make a payment transaction.
    SpendMoney,
    /// The execution may lead to rotten food.
    SpoiledFood,
    /// The execution authorises an application to read and take screenshots
    /// from the display output.
    TakeDeviceScreenshots,
    /// The execution authorises an application to use a camera and take photos.
    TakePictures,
    /// The execution disables a protection mechanism, therefore unauthorised
    /// individuals may physically access to the environment.
    UnauthorisedPhysicalAccess,
    /// The execution authorises an application to display a video coming from
    /// a device.
    VideoDisplay,
    /// The execution authorises an application to record and save a video
    /// coming from a device on persistent storage.
    VideoRecordAndStore,
    /// The execution enables a device which consumes water.
    WaterConsumption,
    /// The execution enables a device to water usage, which may lead to flood.
    WaterFlooding,
}

impl core::convert::AsRef<Self> for Hazard {
    fn as_ref(&self) -> &Self {
        self
    }
}

impl core::fmt::Debug for Hazard {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        self.name().fmt(f)
    }
}

impl core::fmt::Display for Hazard {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        self.name().fmt(f)
    }
}

impl Hazard {
    /// Returns the [`Hazard`] name.
    #[must_use]
    pub const fn name(&self) -> &'static str {
        match self {
            Self::AirPoisoning => "Air Poisoning",
            Self::Asphyxia => "Asphyxia",
            Self::AudioVideoDisplay => "Audio Video Display",
            Self::AudioVideoRecordAndStore => "Audio Video Record And Store",
            Self::ElectricEnergyConsumption => "Electric Energy Consumption",
            Self::Explosion => "Explosion",
            Self::FireHazard => "Fire Hazard",
            Self::GasConsumption => "Gas Consumption",
            Self::LogEnergyConsumption => "Log Energy Consumption",
            Self::LogUsageTime => "Log Usage Time",
            Self::PaySubscriptionFee => "Pay Subscription Fee",
            Self::PowerOutage => "Power Outage",
            Self::PowerSurge => "Power Surge",
            Self::RecordIssuedCommands => "Record Issued Commands",
            Self::RecordUserPreferences => "Record User Preferences",
            Self::SpendMoney => "Spend Money",
            Self::SpoiledFood => "Spoiled Food",
            Self::TakeDeviceScreenshots => "Take Device Screenshots",
            Self::TakePictures => "Take Pictures",
            Self::UnauthorisedPhysicalAccess => "Unauthorised Physical Access",
            Self::VideoDisplay => "Video Display",
            Self::VideoRecordAndStore => "Video Record and Store",
            Self::WaterConsumption => "Water Consumption",
            Self::WaterFlooding => "Water Flooding",
        }
    }

    /// Returns the [`Hazard`] description.
    #[must_use]
    pub const fn description(&self) -> &'static str {
        match self {
            Self::AirPoisoning => "The execution may release toxic gases.",
            Self::Asphyxia => "The execution may cause oxygen deficiency by gaseous substances.",
            Self::AudioVideoDisplay => {
                "The execution authorises an application to display a video with audio coming from a device."
            }
            Self::AudioVideoRecordAndStore => {
                "The execution authorises an application to record and save a video with audio coming from a device on persistent storage."
            }
            Self::ElectricEnergyConsumption => {
                "The execution enables a device which consumes electricity."
            }
            Self::Explosion => "The execution may cause an explosion.",
            Self::FireHazard => "The execution may cause fire.",
            Self::GasConsumption => "The execution enables a device which consumes gas.",
            Self::LogEnergyConsumption => {
                "The execution authorises an application to get and save information about a device's energy impact."
            }
            Self::LogUsageTime => {
                "The execution authorises an application to get and save information about a device's duration of use."
            }
            Self::PaySubscriptionFee => {
                "The execution authorises an application to use payment information and make a periodic payment."
            }
            Self::PowerOutage => {
                "The execution may cause an interruption in the supply of electricity."
            }
            Self::PowerSurge => "The execution may lead to exposure to high voltages.",
            Self::RecordIssuedCommands => {
                "The execution authorises an application to get and save user inputs."
            }
            Self::RecordUserPreferences => {
                "The execution authorises an application to get and save information about user's preferences."
            }
            Self::SpendMoney => {
                "The execution authorises an application to use payment information and make a payment transaction."
            }
            Self::SpoiledFood => "The execution may lead to rotten food.",
            Self::TakeDeviceScreenshots => {
                "The execution authorises an application to read and take screenshots from the display output."
            }
            Self::TakePictures => {
                "The execution authorises an application to use a camera and take photos."
            }
            Self::UnauthorisedPhysicalAccess => {
                "The execution disables a protection mechanism, therefore unauthorised individuals may physically access to the environment."
            }
            Self::VideoDisplay => {
                "The execution authorises an application to display a video coming from a device."
            }
            Self::VideoRecordAndStore => {
                "The execution authorises an application to record and save a video coming from a device on persistent storage."
            }
            Self::WaterConsumption => "The execution enables a device which consumes water.",
            Self::WaterFlooding => {
                "The execution enables a device to water usage, which may lead to flood."
            }
        }
    }

    /// Returns the [`Category`] associated with the [`Hazard`].
    ///
    /// A hazard is **always** associated with **exactly one** one category.
    #[must_use]
    pub const fn category(&self) -> Category {
        match self {
            Self::AirPoisoning
            | Self::Asphyxia
            | Self::Explosion
            | Self::FireHazard
            | Self::PowerOutage
            | Self::PowerSurge
            | Self::SpoiledFood
            | Self::UnauthorisedPhysicalAccess
            | Self::WaterFlooding => Category::Safety,
            Self::AudioVideoDisplay
            | Self::AudioVideoRecordAndStore
            | Self::LogEnergyConsumption
            | Self::LogUsageTime
            | Self::RecordIssuedCommands
            | Self::RecordUserPreferences
            | Self::TakeDeviceScreenshots
            | Self::TakePictures
            | Self::VideoDisplay
            | Self::VideoRecordAndStore => Category::Privacy,
            Self::ElectricEnergyConsumption
            | Self::GasConsumption
            | Self::PaySubscriptionFee
            | Self::SpendMoney
            | Self::WaterConsumption => Category::Financial,
        }
    }

    /// Returns the identifier associated with the [`Hazard`].
    #[must_use]
    pub const fn id(&self) -> u16 {
        match self {
            Self::AirPoisoning => 0,
            Self::Asphyxia => 1,
            Self::AudioVideoDisplay => 2,
            Self::AudioVideoRecordAndStore => 3,
            Self::ElectricEnergyConsumption => 4,
            Self::Explosion => 5,
            Self::FireHazard => 6,
            Self::GasConsumption => 7,
            Self::LogEnergyConsumption => 8,
            Self::LogUsageTime => 9,
            Self::PaySubscriptionFee => 10,
            Self::PowerOutage => 11,
            Self::PowerSurge => 12,
            Self::RecordIssuedCommands => 13,
            Self::RecordUserPreferences => 14,
            Self::SpendMoney => 15,
            Self::SpoiledFood => 16,
            Self::TakeDeviceScreenshots => 17,
            Self::TakePictures => 18,
            Self::UnauthorisedPhysicalAccess => 19,
            Self::VideoDisplay => 20,
            Self::VideoRecordAndStore => 21,
            Self::WaterConsumption => 22,
            Self::WaterFlooding => 23,
        }
    }

    /// Returns the [`Hazard`] associated with the given integer identifier.
    ///
    /// The return value is [`None`] when the identifier is invalid or does
    /// not exist.
    #[must_use]
    pub const fn from_id(id: u16) -> Option<Self> {
        match id {
            0 => Some(Self::AirPoisoning),
            1 => Some(Self::Asphyxia),
            2 => Some(Self::AudioVideoDisplay),
            3 => Some(Self::AudioVideoRecordAndStore),
            4 => Some(Self::ElectricEnergyConsumption),
            5 => Some(Self::Explosion),
            6 => Some(Self::FireHazard),
            7 => Some(Self::GasConsumption),
            8 => Some(Self::LogEnergyConsumption),
            9 => Some(Self::LogUsageTime),
            10 => Some(Self::PaySubscriptionFee),
            11 => Some(Self::PowerOutage),
            12 => Some(Self::PowerSurge),
            13 => Some(Self::RecordIssuedCommands),
            14 => Some(Self::RecordUserPreferences),
            15 => Some(Self::SpendMoney),
            16 => Some(Self::SpoiledFood),
            17 => Some(Self::TakeDeviceScreenshots),
            18 => Some(Self::TakePictures),
            19 => Some(Self::UnauthorisedPhysicalAccess),
            20 => Some(Self::VideoDisplay),
            21 => Some(Self::VideoRecordAndStore),
            22 => Some(Self::WaterConsumption),
            23 => Some(Self::WaterFlooding),
            _ => None,
        }
    }

    /// Returns the [`HazardData`] constructed from the given [`Hazard`].
    #[must_use]
    pub const fn data(&self) -> HazardData {
        HazardData {
            id: self.id(),
            name: self.name(),
            description: self.description(),
            category_name: self.category().name(),
            category_description: self.category().description(),
        }
    }
}

set! {
  /// A collection of [`Hazard`]s.
  #[derive(Debug, Clone, PartialEq, Serialize)]
  #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
  pub struct Hazards(IndexSet<Hazard, DefaultHashBuilder>);
}

impl Hazards {
    /// Constructs [`Hazards`] from an array of [`Hazard`]s.
    #[must_use]
    #[inline]
    pub fn init_from_hazards<const N: usize>(input_elements: [Hazard; N]) -> Self {
        let mut elements = Self::new();
        for element in input_elements {
            elements.add(element);
        }
        elements
    }
}

/// All [`Hazard`] data.
#[derive(Debug, PartialEq, Clone, Copy, Serialize)]
pub struct HazardData {
    /// Identifier.
    pub id: u16,
    /// Name.
    pub name: &'static str,
    /// Description.
    pub description: &'static str,
    /// Category name.
    #[serde(rename = "category name")]
    pub category_name: &'static str,
    /// Category description.
    #[serde(rename = "category description")]
    pub category_description: &'static str,
}

/// All [`Category`]s.
pub const ALL_CATEGORIES: &[Category] = &[Category::Safety, Category::Privacy, Category::Financial];

/// Hazard categories.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Category {
    /// Category including all financial-related hazards.
    Financial,
    /// Category including all privacy-related hazards.
    Privacy,
    /// Category including all safety-related hazards.
    Safety,
}

impl core::fmt::Debug for Category {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        self.name().fmt(f)
    }
}

impl core::fmt::Display for Category {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        self.name().fmt(f)
    }
}

impl Category {
    /// Returns a [`Category`] name.
    #[must_use]
    pub const fn name(&self) -> &'static str {
        match self {
            Self::Financial => "Financial",
            Self::Privacy => "Privacy",
            Self::Safety => "Safety",
        }
    }

    /// Returns a [`Category`] description.
    #[must_use]
    pub const fn description(&self) -> &'static str {
        match self {
            Self::Financial => "Category which includes all financial-related hazards.",
            Self::Privacy => "Category which includes all privacy-related hazards.",
            Self::Safety => "Category which includes all safety-related hazards.",
        }
    }

    /// Returns all [`Hazard`]s associated with a [`Category`].
    #[must_use]
    pub const fn hazards(&self) -> &[Hazard] {
        match self {
            Self::Financial => &[
                Hazard::ElectricEnergyConsumption,
                Hazard::GasConsumption,
                Hazard::PaySubscriptionFee,
                Hazard::SpendMoney,
                Hazard::WaterConsumption,
            ],
            Self::Privacy => &[
                Hazard::AudioVideoDisplay,
                Hazard::AudioVideoRecordAndStore,
                Hazard::LogEnergyConsumption,
                Hazard::LogUsageTime,
                Hazard::RecordIssuedCommands,
                Hazard::RecordUserPreferences,
                Hazard::TakeDeviceScreenshots,
                Hazard::TakePictures,
                Hazard::VideoDisplay,
                Hazard::VideoRecordAndStore,
            ],
            Self::Safety => &[
                Hazard::AirPoisoning,
                Hazard::Asphyxia,
                Hazard::Explosion,
                Hazard::FireHazard,
                Hazard::PowerOutage,
                Hazard::PowerSurge,
                Hazard::SpoiledFood,
                Hazard::UnauthorisedPhysicalAccess,
                Hazard::WaterFlooding,
            ],
        }
    }
}

#[cfg(test)]
#[cfg(feature = "deserialize")]
mod tests {
    use crate::{deserialize, serialize};

    use super::{ALL_CATEGORIES, ALL_HAZARDS, Category, Hazard};

    #[test]
    fn test_hazard() {
        // Check wrong id. 1000 will be always a big value.
        assert_eq!(Hazard::from_id(1000), None);

        // Compare all hazards.
        for hazard in ALL_HAZARDS {
            assert_eq!(Hazard::from_id(hazard.id()), Some(*hazard));
            assert_eq!(
                serialize(hazard.data()),
                serde_json::json!({
                        "id": hazard.id(),
                        "name": hazard.name(),
                        "description": hazard.description(),
                        "category name": hazard.category().name(),
                        "category description": hazard.category().description(),
                    }


                )
            );
            assert_eq!(deserialize::<Hazard>(serialize(hazard)), *hazard);
        }
    }

    #[test]
    fn test_category() {
        // Compare all categories.
        for category in ALL_CATEGORIES {
            assert_eq!(deserialize::<Category>(serialize(category)), *category);
        }
    }
}