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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
use crate::{device, error};
use core::{cmp, fmt};
use pci_ids::FromId;

#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct Classes {
    class: Class,
    subclass: Subclass,
}

/// A code describing a PCI device's device class.
///
/// This type represents a class code that exists in the PCI class database.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct Class(&'static pci_ids::Class);

/// A code describing a PCI device's subclass within its [`Class`].
///
/// This type represents a subclass code that exists in the PCI class database.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct Subclass(&'static pci_ids::Subclass);

#[derive(Debug, Copy, Clone)]
#[repr(C)]
pub struct RawClasses {
    pub(crate) subclass: u8,
    pub(crate) class: u8,
}

// === impl Classes ===

impl Classes {
    #[inline]
    #[must_use]
    pub fn class(&self) -> Class {
        self.class
    }

    #[inline]
    #[must_use]
    pub fn subclass(&self) -> Subclass {
        self.subclass
    }

    #[inline]
    #[must_use]
    pub fn class_id(&self) -> u8 {
        self.class.0.id()
    }

    #[inline]
    #[must_use]
    pub fn subclass_id(&self) -> u8 {
        self.subclass.0.id()
    }
}

impl fmt::Display for Classes {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let Self { class, subclass } = self;
        write!(f, "{}: {}", class.name(), subclass.name())
    }
}

// === impl Class ===

impl Class {
    pub fn from_id(id: u8) -> Result<Self, error::UnexpectedValue<u8>> {
        let inner =
            pci_ids::Class::from_id(id).ok_or_else(|| error::unexpected(id).named("PCI class"))?;
        Ok(Self(inner))
    }

    pub fn subclass(self, id: u8) -> Result<Subclass, error::UnexpectedValue<u8>> {
        let inner = pci_ids::Subclass::from_cid_sid(self.id(), id)
            .ok_or_else(|| error::unexpected(id).named("PCI subclass"))?;
        Ok(Subclass(inner))
    }

    #[inline]
    #[must_use]
    pub fn name(self) -> &'static str {
        self.0.name()
    }

    #[inline]
    #[must_use]
    pub fn id(self) -> u8 {
        self.0.id()
    }
}

impl PartialOrd for Class {
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Class {
    #[inline]
    fn cmp(&self, other: &Self) -> cmp::Ordering {
        self.id().cmp(&other.id())
    }
}

// === impl Subclass ===

impl Subclass {
    #[inline]
    #[must_use]
    pub fn name(self) -> &'static str {
        self.0.name()
    }

    #[inline]
    #[must_use]
    pub fn id(self) -> u8 {
        self.0.id()
    }

    #[inline]
    #[must_use]
    pub fn class(self) -> Class {
        Class(self.0.class())
    }

    /// Resolves a register-level programming interface code ("prog IF") for
    /// this subclass.
    ///
    /// Note that this is an O(_N_) operation.
    #[must_use]
    pub fn prog_if(self, code: u8) -> device::ProgIf {
        self.0
            .prog_ifs()
            .find(|prog_if| prog_if.id() == code)
            .map(device::ProgIf::Known)
            .unwrap_or(device::ProgIf::Unknown(code))
    }
}

impl PartialOrd for Subclass {
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Subclass {
    #[inline]
    fn cmp(&self, other: &Self) -> cmp::Ordering {
        self.0
            .class()
            .id()
            .cmp(&other.class().id())
            .then_with(|| self.id().cmp(&other.id()))
    }
}

// === impl RawClasses ===

impl RawClasses {
    pub fn resolve(&self) -> Result<Classes, error::UnexpectedValue<Self>> {
        let class = self
            .resolve_class()
            .map_err(|_| error::unexpected(*self).named("PCI device class"))?;
        let subclass = self
            .resolve_subclass()
            .map_err(|_| error::unexpected(*self).named("PCI device subclass"))?;
        Ok(crate::Classes { class, subclass })
    }

    pub fn resolve_class(&self) -> Result<Class, error::UnexpectedValue<u8>> {
        pci_ids::Class::from_id(self.class)
            .ok_or_else(|| error::unexpected(self.class).named("PCI device class"))
            .map(Class)
    }

    pub fn resolve_subclass(&self) -> Result<Subclass, error::UnexpectedValue<u8>> {
        pci_ids::Subclass::from_cid_sid(self.class, self.subclass)
            .ok_or_else(|| error::unexpected(self.subclass).named("PCI device subclass"))
            .map(Subclass)
    }
}

impl fmt::LowerHex for RawClasses {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let Self { class, subclass } = self;
        // should the formatted ID be prefaced with a leading `0x`?
        let leading = if f.alternate() { "0x" } else { "" };
        write!(f, "{leading}{class:x}:{subclass:x}")
    }
}

// macro_rules! replace_tt {
//     ($old:tt $new:tt) => {
//         $new
//     };
// }

// macro_rules! class_enum {
//     (
//         $(#[$m:meta])*
//         $v:vis enum $name:ident<NoProgIf> {
//             $(
//                 $(#[$($mm:tt)*])*
//                 $variant:ident = $value:expr
//             ),+
//             $(,)?
//         }
//     ) => {
//         class_enum! {
//             $(#[$m])*
//             $v enum $name {
//                 $(
//                     $(#[$($mm)*])*
//                     $variant = $value
//                 ),+
//             }
//         }

//         impl TryFrom<(u8, u8)> for $name {
//             type Error = error::UnexpectedValue<u8>;
//             fn try_from((u, rest): (u8, u8)) -> Result<Self, Self::Error> {
//                 if rest != 0 {
//                     return Err(error::unexpected(rest));
//                 }

//                 Self::try_from(u)
//             }
//         }
//     };

//     (
//         $(#[$m:meta])*
//         $v:vis enum $name:ident<$kind:ident, $rest:ty> {
//             $(
//                 $(#[$($mm:tt)*])*
//                 $variant:ident $(($next:ty))? = $value:expr
//             ),+
//             $(,)?
//         }
//     ) => {
//         $(#[$m])*
//         #[derive(Copy, Clone, Debug, PartialEq, Eq, Ord, PartialOrd)]
//         $v enum $name {
//             $(
//                 $(#[$($mm)*])*
//                 $variant $( ($next) )?
//             ),+
//         }

//         impl TryFrom<(u8, $rest)> for $name {
//             type Error = error::UnexpectedValue<u8>;
//             fn try_from((u, rest): (u8, $rest)) -> Result<Self, Self::Error> {
//                 match $kind::try_from(u)? {
//                     $(
//                         $kind::$variant => Ok($name::$variant $((<$next>::try_from(rest)?) )?)
//                     ),+
//                 }
//             }
//         }

//         impl fmt::Display for $name {
//             fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
//                 match self {
//                     $(
//                         $name::$variant $((replace_tt!($next next)))? => {
//                             fmt::Display::fmt(&$kind::$variant, f)?;
//                             $(next_display_helper(f, replace_tt!($next next))?;)?
//                         }
//                     ),*
//                 }
//                 Ok(())
//             }
//         }

//         class_enum!{
//             enum $kind {
//                 $(
//                     $(#[$($mm)*])*
//                     $variant = $value
//                 ),+
//             }
//         }
//     };

//     (
//         $(#[$m:meta])*
//         $v:vis enum $name:ident {
//             $(
//                 #[doc = $doc:expr]
//                 $(#[$mm:meta])*
//                 $variant:ident = $value:expr
//             ),+
//             $(,)?
//         }
//     ) => {
//         $(#[$m])*
//         #[derive(Copy, Clone, Debug, PartialEq, Eq, Ord, PartialOrd)]
//         #[repr(u8)]
//         $v enum $name {
//             $(
//                 #[doc = $doc]
//                 $(#[$mm])*
//                 $variant = $value
//             ),+
//         }

//         impl TryFrom<u8> for $name {
//             type Error = error::UnexpectedValue<u8>;
//             fn try_from(num: u8) -> Result<Self, Self::Error> {
//                 match num {
//                     $(
//                         $value => Ok($name::$variant),
//                     )+
//                     num => Err(error::unexpected(num)),
//                 }
//             }
//         }

//         impl fmt::Display for $name {
//             fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
//                 match self {
//                     $(
//                         $name::$variant => f.write_str($doc.trim())
//                     ),*
//                 }
//             }
//         }
//     };
// }

// fn next_display_helper(f: &mut fmt::Formatter, next: &impl fmt::Display) -> fmt::Result {
//     // Precision of `0` means we're done, no precision implies infinite precision.
//     match f.precision() {
//         Some(0) => Ok(()),
//         Some(precision) => write!(f, ": {:.*}", precision - 1, next),
//         None => write!(f, ": {}", next),
//     }
// }

// class_enum! {
//     pub enum Class<ClassValue, (u8, u8)> {
//         /// Unclassified
//         Unclassified(Unclassified) = 0x00,
//         /// Mass Storage
//         MassStorage(MassStorage) = 0x01,
//         /// Network
//         Network(Network) = 0x02,
//         /// Display
//         Display(Display) = 0x03,
//         /// Multimedia
//         Multimedia(Multimedia) = 0x04,
//         /// Memory Controller
//         Memory = 0x05,
//         /// Bridge Device
//         Bridge = 0x06,
//         /// Simple Communication Controller
//         SimpleComm = 0x07,
//         /// Base System Peripheral
//         BaseSystemPeripheral = 0x08,
//         /// Input Device Controller
//         Input = 0x09,
//         /// Docking Station
//         DockingStation = 0x0A,
//         /// Processor
//         Processor = 0x0B,
//         /// Serial Bus Controller
//         SerialBus = 0x0C,
//         /// Wireless Controller
//         Wireless = 0x0D,
//         /// Intelligent Controller
//         Intelligent = 0x0E,
//         /// Satellite Communication Controller
//         SatelliteComm = 0x0F,
//         /// Encryption Controller
//         Encryption = 0x10,
//         /// Signal Processing Controller
//         SignalProcessing = 0x11,
//         /// Processing Accelerator
//         ProcessingAccelerator = 0x12,
//         /// Non-Essential Instrumentation
//         NonEssentialInstrumentation = 0x13
//     }
// }

// class_enum! {
//     pub enum Unclassified<NoProgIf> {
//         /// Non-VGA-Compatible Device
//         NonVga = 0x00,
//         /// VGA-Compatible Device
//         Vga = 0x01
//     }
// }

// class_enum! {
//     pub enum MassStorage<MassStorageKind, u8> {
//         /// SCSI Bus Controller
//         ScsiBus = 0x00,
//         /// IDE Controller
//         Ide(iface::Ide) = 0x01,
//         /// Floppy Disk Controller
//         Floppy = 0x02,
//         /// IPI Bus Controller
//         IpiBus = 0x03,
//         /// RAID Controller
//         Raid = 0x04,
//         /// ATA Controller
//         Ata(iface::Ata) = 0x05,
//         /// Serial ATA Controller
//         Sata(iface::Sata) = 0x06,
//         /// Serial Attached SCSI
//         SerialAttachedScsi(iface::SerialAttachedScsi) = 0x07,
//         /// Non-Volatile Memory Controller
//         NonVolatileMem(iface::Nvm) = 0x08,
//         /// Other
//         Other = 0x80
//     }
// }

// class_enum! {
//     pub enum Network<NoProgIf> {
//         /// Ethernet Controller
//         Ethernet = 0x00,
//         /// Token Ring Controller
//         TokenRing = 0x01,
//         /// FDDI Controller
//         Fddi = 0x02,
//         /// ATM Controller
//         Atm = 0x03,
//         /// ISDN Controller
//         Isdn = 0x04,
//         /// WorldFlip Controller
//         WorldFip = 0x05,
//         /// PICMG 2.14 Multi Computing
//         Picmig2_14 = 0x06,
//         /// Infiniband Controller
//         Infiniband = 0x07,
//         /// Fabric Controller
//         Fabric = 0x08,
//         /// Other
//         Other = 0x80,
//     }
// }

// class_enum! {
//     pub enum Display<DisplayValue, u8> {
//         /// VGA Compatible
//         VgaCompatible(iface::VgaCompatible) = 0x00,
//         /// XGA Controller
//         Xga = 0x01,
//         /// 3D Controller (Not VGA-Compatible)
//         ThreeD = 0x02,
//         /// Other
//         Other = 0x80,
//     }
// }

// class_enum! {
//     pub enum Multimedia<NoProgIf> {
//         /// Multimedia Video Controller
//         MultimediaVideo = 0x00,
//         /// Multimedia Audio Controller
//         MultimediaAudio = 0x01,
//         /// Computer Telephony Device
//         ComputerTelephony = 0x02,
//         /// Audio Device
//         Audio = 0x03,
//         /// Other
//         Other = 0x80,
//     }
// }

// class_enum! {
//     pub enum Memory<NoProgIf> {
//         /// RAM Controller
//         Ram = 0x00,
//         /// Flash Controller
//         Flash = 0x01,
//         /// Other
//         Other = 0x80,
//     }
// }

// impl TryFrom<(RawClasses, u8)> for Class {
//     type Error = error::UnexpectedValue<u8>;
//     fn try_from(
//         (RawClasses { class, subclass }, prog_if): (RawClasses, u8),
//     ) -> Result<Self, Self::Error> {
//         Self::try_from((class, (subclass, prog_if)))
//     }
// }

// pub mod iface {
//     use super::*;

//     #[derive(Debug, Eq, PartialEq, Copy, Clone, Ord, PartialOrd)]
//     #[repr(transparent)]
//     pub struct Ide(u8);

//     impl Ide {
//         const PCI_NATIVE: u8 = 0b0101;
//         const SWITCHABLE: u8 = 0b1010;
//         const BUS_MASTERING: u8 = 0x8;

//         pub fn supports_bus_mastering(&self) -> bool {
//             self.0 & Self::BUS_MASTERING == Self::BUS_MASTERING
//         }

//         pub fn is_switchable(&self) -> bool {
//             self.0 & Self::SWITCHABLE == Self::SWITCHABLE
//         }

//         pub fn is_isa_native(&self) -> bool {
//             !self.is_pci_native()
//         }

//         pub fn is_pci_native(&self) -> bool {
//             self.0 & Self::PCI_NATIVE == Self::PCI_NATIVE
//         }
//     }

//     impl TryFrom<u8> for Ide {
//         type Error = error::UnexpectedValue<u8>;
//         fn try_from(u: u8) -> Result<Self, Self::Error> {
//             if u > 0x8f {
//                 return Err(error::unexpected(u));
//             }
//             Ok(Self(u))
//         }
//     }

//     impl fmt::Display for Ide {
//         fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
//             let mode = match (self.is_pci_native(), self.is_switchable()) {
//                 (false, false) => "ISA compatibility mode-only",
//                 (false, true) => {
//                     "ISA compatibility mode, supports both channels switched to PCI native mode"
//                 }
//                 (true, false) => "PCI native mode-only",
//                 (true, true) => {
//                     "PCI native mode, supports both channels switched to ISA compatibility mode"
//                 }
//             };

//             if self.supports_bus_mastering() {
//                 write!(f, "{}, supports bus mastering", mode)?;
//             } else {
//                 write!(f, "{}", mode)?;
//             }
//             Ok(())
//         }
//     }

//     class_enum! {
//         pub enum Ata {
//             /// Single DMA
//             SingleDma = 0x20,
//             /// Chained DMA
//             ChainedDma = 0x30,
//         }
//     }

//     class_enum! {
//         pub enum Sata {
//             /// Vendor Specific Interface
//             VendorSpecific = 0x00,
//             /// AHCI 1.0
//             Achi1 = 0x01,
//             /// Serial Storage Bus
//             SerialStorageBus = 0x02,
//         }
//     }

//     class_enum! {
//         pub enum SerialAttachedScsi {
//             /// SAS
//             Sas = 0x00,
//             /// Serial Storage Bus
//             SerialStorageBus = 0x02,
//         }
//     }

//     class_enum! {
//         pub enum Nvm {
//             /// NVMHCI
//             Nvmhci = 0x01,
//             /// NVM Express
//             NvmExpress = 0x02,
//         }
//     }

//     class_enum! {
//         pub enum VgaCompatible {
//             /// VGA Controller
//             VgaController = 0x00,
//             /// 8514-Compatible Controller
//             Compat8514 = 0x01,
//         }
//     }
// }

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

//     #[test]
//     fn test_parsing() {
//         let mass_storage_sata_achi = (
//             RawClasses {
//                 class: 0x01,
//                 subclass: 0x06,
//             },
//             0x01,
//         );
//         let class = Class::try_from(mass_storage_sata_achi);
//         assert_eq!(
//             class,
//             Ok(Class::MassStorage(MassStorage::Sata(iface::Sata::Achi1))),
//         );
//     }

//     #[test]
//     fn test_display() {
//         assert_eq!(
//             Class::MassStorage(MassStorage::Sata(iface::Sata::Achi1)).to_string(),
//             "Mass Storage: Serial ATA Controller: AHCI 1.0"
//         );

//         let ide_iface = iface::Ide::try_from(0x8F).unwrap();
//         assert_eq!(
//             Class::MassStorage(MassStorage::Ide(ide_iface)).to_string(),
//             "Mass Storage: IDE Controller: PCI native mode, supports both channels switched to ISA compatibility mode, supports bus mastering"
//         );
//         assert_eq!(
//             format!("{:.1}", Class::MassStorage(MassStorage::Ide(ide_iface))),
//             "Mass Storage: IDE Controller"
//         );
//     }
// }