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
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
// Copyright 2016 Andrew Baumhauer <andy@baumhauer.us>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Represent and parse IEEE EUI-48 Media Access Control addresses
//! The IEEE claims trademarks on the names EUI-48 and EUI-64, in which EUI is an
//! abbreviation for Extended Unique Identifier.

#![doc(
    html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
    html_favicon_url = "https://www.rust-lang.org/favicon.ico",
    html_root_url = "https://doc.rust-lang.org/eui48/"
)]

extern crate regex;
#[cfg(feature = "rustc-serialize")]
extern crate rustc_serialize;
#[cfg(feature = "serde")]
extern crate serde;
#[cfg(feature = "serde_json")]
extern crate serde_json;

use std::default::Default;
use std::error::Error;
use std::fmt;
use std::str::FromStr;

use regex::Regex;
#[cfg(feature = "rustc-serialize")]
use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
#[cfg(feature = "serde")]
use serde::{de, Deserialize, Deserializer, Serialize, Serializer};

/// A 48-bit (6 byte) buffer containing the EUI address
pub const EUI48LEN: usize = 6;
pub type Eui48 = [u8; EUI48LEN];

/// A 64-bit (8 byte) buffer containing the EUI address
pub const EUI64LEN: usize = 8;
pub type Eui64 = [u8; EUI64LEN];

/// A MAC address (EUI-48)
#[repr(C)]
#[derive(Copy, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub struct MacAddress {
    /// The 48-bit number stored in 6 bytes
    eui: Eui48,
}

#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
/// Format to display MacAddress
pub enum MacAddressFormat {
    /// Use - notaion
    Canonical,
    /// Use : notation
    HexString,
    /// Use . notation
    DotNotation,
    /// Use 0x notation
    Hexadecimal,
}

#[derive(PartialEq, Eq, Copy, Clone, Debug, Ord, PartialOrd, Hash)]
/// Parsing errors
pub enum ParseError {
    /// Length is incorrect (should be 11 to 17)
    InvalidLength(usize),
    /// The input string is invalid, usize bytes were found, and we put up to 6 bytes into Eui48
    InvalidByteCount(usize, Eui48),
}

impl MacAddress {
    /// Create a new MacAddress from `[u8; 6]`.
    pub const fn new(eui: Eui48) -> MacAddress {
        MacAddress { eui }
    }

    /// Create a new MacAddress from a byte slice.
    ///
    /// Returns an error (without any description) if the slice doesn't have the proper length.
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, ParseError> {
        if bytes.len() != EUI48LEN {
            return Err(ParseError::InvalidLength(bytes.len()));
        }
        let mut input: [u8; EUI48LEN] = Default::default();
        input[..EUI48LEN].clone_from_slice(&bytes[..EUI48LEN]);
        Ok(Self::new(input))
    }

    /// Returns empty EUI-48 address
    pub fn nil() -> MacAddress {
        MacAddress { eui: [0; EUI48LEN] }
    }

    /// Returns 'ff:ff:ff:ff:ff:ff', a MAC broadcast address
    pub fn broadcast() -> MacAddress {
        MacAddress {
            eui: [0xFF; EUI48LEN],
        }
    }

    /// Returns true if the address is '00:00:00:00:00:00'
    pub fn is_nil(&self) -> bool {
        self.eui.iter().all(|&b| b == 0)
    }

    /// Returns true if the address is 'ff:ff:ff:ff:ff:ff'
    pub fn is_broadcast(&self) -> bool {
        self.eui.iter().all(|&b| b == 0xFF)
    }

    /// Returns true if bit 1 of Y is 0 in address 'xY:xx:xx:xx:xx:xx'
    pub fn is_unicast(&self) -> bool {
        self.eui[0] & 1 == 0
    }

    /// Returns true if bit 1 of Y is 1 in address 'xY:xx:xx:xx:xx:xx'
    pub fn is_multicast(&self) -> bool {
        self.eui[0] & 1 == 1
    }

    /// Returns true if bit 2 of Y is 0 in address 'xY:xx:xx:xx:xx:xx'
    pub fn is_universal(&self) -> bool {
        self.eui[0] & 1 << 1 == 0
    }

    /// Returns true if bit 2 of Y is 1 in address 'xY:xx:xx:xx:xx:xx'
    pub fn is_local(&self) -> bool {
        self.eui[0] & 1 << 1 == 2
    }

    /// Returns a String representation in the format '00-00-00-00-00-00'
    pub fn to_canonical(&self) -> String {
        format!(
            "{:02x}-{:02x}-{:02x}-{:02x}-{:02x}-{:02x}",
            self.eui[0], self.eui[1], self.eui[2], self.eui[3], self.eui[4], self.eui[5]
        )
    }

    /// Returns a String representation in the format '00:00:00:00:00:00'
    pub fn to_hex_string(&self) -> String {
        format!(
            "{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}",
            self.eui[0], self.eui[1], self.eui[2], self.eui[3], self.eui[4], self.eui[5]
        )
    }

    /// Returns a String representation in the format '0000.0000.0000'
    pub fn to_dot_string(&self) -> String {
        format!(
            "{:02x}{:02x}.{:02x}{:02x}.{:02x}{:02x}",
            self.eui[0], self.eui[1], self.eui[2], self.eui[3], self.eui[4], self.eui[5]
        )
    }

    /// Returns a String representation in the format '0x000000000000'
    pub fn to_hexadecimal(&self) -> String {
        format!(
            "0x{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}",
            self.eui[0], self.eui[1], self.eui[2], self.eui[3], self.eui[4], self.eui[5]
        )
    }

    /// Returns a String representation in the EUI-64 interface ID format '0000:00ff:fe00:0000'
    pub fn to_interfaceid(&self) -> String {
        format!(
            "{:02x}{:02x}:{:02x}ff:fe{:02x}:{:02x}{:02x}",
            (self.eui[0] ^ 0x02),
            self.eui[1],
            self.eui[2],
            self.eui[3],
            self.eui[4],
            self.eui[5]
        )
    }

    /// Returns a String representation in the IPv6 link local format 'fe80::0000:00ff:fe00:0000'
    pub fn to_link_local(&self) -> String {
        format!(
            "fe80::{:02x}{:02x}:{:02x}ff:fe{:02x}:{:02x}{:02x}",
            (self.eui[0] ^ 0x02),
            self.eui[1],
            self.eui[2],
            self.eui[3],
            self.eui[4],
            self.eui[5]
        )
    }

    /// Returns a String in the format selected by fmt
    pub fn to_string(&self, fmt: MacAddressFormat) -> String {
        match fmt {
            MacAddressFormat::Canonical => self.to_canonical(),
            MacAddressFormat::HexString => self.to_hex_string(),
            MacAddressFormat::DotNotation => self.to_dot_string(),
            MacAddressFormat::Hexadecimal => self.to_hexadecimal(),
        }
    }

    /// Parses a String representation from any format supported
    pub fn parse_str(s: &str) -> Result<MacAddress, ParseError> {
        let re = Regex::new("(0x)?([0-9a-fA-F]{1,2})[:.-]?").unwrap();
        let mut eui: Eui48 = [0; EUI48LEN];

        match s.len() {
            11..=17 => {}
            _ => {
                return Err(ParseError::InvalidLength(s.len()));
            }
        }

        let mut i = 0;
        for caps in re.captures_iter(s) {
            // Fill the array and keep counting for InvalidByteCount
            if i < EUI48LEN {
                let matched_byte = caps.get(2).unwrap().as_str();
                eui[i] = u8::from_str_radix(matched_byte, 16).unwrap();
            }
            i += 1;
        }

        if i != EUI48LEN {
            return Err(ParseError::InvalidByteCount(i, eui));
        }

        Ok(MacAddress::new(eui))
    }

    /// Return the internal structure as a slice of bytes
    pub fn as_bytes(&self) -> &[u8] {
        &self.eui
    }

    /// Returns an array in Eui48. Works as an inverse function of new()
    pub fn to_array(&self) -> Eui48 {
        self.eui
    }

    /// Returns Display MacAddressFormat, determined at compile time.
    pub fn get_display_format() -> MacAddressFormat {
        if cfg!(feature = "disp_hexstring") {
            MacAddressFormat::HexString
        } else {
            MacAddressFormat::Canonical
        }
    }
}

impl FromStr for MacAddress {
    type Err = ParseError;
    /// Create a MacAddress from String
    fn from_str(us: &str) -> Result<MacAddress, ParseError> {
        MacAddress::parse_str(us)
    }
}

impl Default for MacAddress {
    /// Create a Default MacAddress (00-00-00-00-00-00)
    fn default() -> MacAddress {
        MacAddress::nil()
    }
}

impl fmt::Debug for MacAddress {
    /// Debug format for MacAddress is HexString notation
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "MacAddress(\"{}\")",
            self.to_string(MacAddressFormat::HexString)
        )
    }
}

impl fmt::Display for MacAddress {
    /// Display format is canonical format (00-00-00-00-00-00) by default
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let disp_fmt = MacAddress::get_display_format();
        write!(f, "{}", self.to_string(disp_fmt))
    }
}

impl fmt::Display for ParseError {
    /// Human readable error strings for ParseError enum
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            ParseError::InvalidLength(found) => write!(
                f,
                "Invalid length; expecting 11 to 17 chars, found {}",
                found
            ),
            ParseError::InvalidByteCount(found, eui) => write!(
                f,
                "Invalid byte count; Matched `{}` bytes ({:?})",
                found,
                &eui[..found]
            ),
        }
    }
}

impl Error for ParseError {
    /// Human readable description for ParseError enum
    fn description(&self) -> &str {
        "MacAddress parse error"
    }
}

#[cfg(feature = "rustc-serialize")]
impl Encodable for MacAddress {
    /// Encode a MacAddress using the default format
    fn encode<E: Encoder>(&self, e: &mut E) -> Result<(), E::Error> {
        let disp_fmt = MacAddress::get_display_format();
        e.emit_str(&self.to_string(disp_fmt))
    }
}

#[cfg(feature = "rustc-serialize")]
impl Decodable for MacAddress {
    /// Decode a MacAddress from a string in canonical form
    fn decode<D: Decoder>(d: &mut D) -> Result<MacAddress, D::Error> {
        let string = d.read_str()?;
        string.parse().map_err(|err| d.error(&format!("{}", err)))
    }
}

#[cfg(all(feature = "serde", not(feature = "serde_bytes")))]
impl Serialize for MacAddress {
    /// Serialize a MacAddress in the default format using the serde crate
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let disp_fmt = MacAddress::get_display_format();
        serializer.serialize_str(&self.to_string(disp_fmt))
    }
}

#[cfg(feature = "serde_bytes")]
impl Serialize for MacAddress {
    /// Serialize a MacAddress as raw bytes using the serde crate
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_bytes(self.as_bytes())
    }
}

#[cfg(all(feature = "serde", not(feature = "serde_bytes")))]
impl<'de> Deserialize<'de> for MacAddress {
    /// Deserialize a MacAddress from canonical form using the serde crate
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        struct MacAddressVisitor;
        impl<'de> de::Visitor<'de> for MacAddressVisitor {
            type Value = MacAddress;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                write!(formatter, "a string representation of a MAC address")
            }

            fn visit_str<E: de::Error>(self, value: &str) -> Result<Self::Value, E> {
                value.parse().map_err(|err| E::custom(&format!("{}", err)))
            }
        }
        deserializer.deserialize_str(MacAddressVisitor)
    }
}

#[cfg(feature = "serde_bytes")]
impl<'de> Deserialize<'de> for MacAddress {
    /// Deserialize a MacAddress from raw bytes using the serde crate
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        struct MacAddressVisitor;
        impl<'de> de::Visitor<'de> for MacAddressVisitor {
            type Value = MacAddress;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                write!(formatter, "6-element byte array")
            }

            fn visit_bytes<E: de::Error>(self, value: &[u8]) -> Result<Self::Value, E> {
                MacAddress::from_bytes(value).map_err(|_| E::invalid_length(value.len(), &self))
            }
        }
        deserializer.deserialize_bytes(MacAddressVisitor)
    }
}

// ************** TESTS BEGIN HERE ***************
#[cfg(test)]
mod tests {
    use super::{Eui48, MacAddress, MacAddressFormat, ParseError};

    #[test]
    fn test_new() {
        let eui: Eui48 = [0x12, 0x34, 0x56, 0xAB, 0xCD, 0xEF];
        let mac = MacAddress::new(eui);

        assert!(mac.eui[0..5] == eui[0..5]);
    }

    #[test]
    fn test_from_bytes() {
        assert_eq!(
            "12:34:56:ab:cd:ef",
            MacAddress::from_bytes(&[0x12, 0x34, 0x56, 0xAB, 0xCD, 0xEF])
                .unwrap()
                .to_hex_string()
        );
        assert!(MacAddress::from_bytes(&[0x12, 0x34, 0x56, 0xAB, 0xCD]).is_err());
    }

    #[test]
    fn test_nil() {
        let nil = MacAddress::nil();
        let not_nil = MacAddress::broadcast();
        assert_eq!("00:00:00:00:00:00", nil.to_hex_string());
        assert!(nil.is_nil());
        assert!(!not_nil.is_nil());
    }

    #[test]
    fn test_default() {
        let default = MacAddress::default();
        assert!(default.is_nil());
    }

    #[test]
    fn test_broadcast() {
        let broadcast = MacAddress::broadcast();
        let not_broadcast = MacAddress::nil();
        assert_eq!("ff:ff:ff:ff:ff:ff", broadcast.to_hex_string());
        assert!(broadcast.is_broadcast());
        assert!(!not_broadcast.is_broadcast());
    }

    #[test]
    fn test_is_nil() {
        let nil = MacAddress::nil();
        let not_nil = MacAddress::parse_str("01:00:5E:AB:CD:EF").unwrap();
        assert!(nil.is_nil());
        assert!(!not_nil.is_nil());
    }

    #[test]
    fn test_is_broadcast() {
        let broadcast = MacAddress::broadcast();
        let not_broadcast = MacAddress::parse_str("01:00:5E:AB:CD:EF").unwrap();
        assert!(broadcast.is_broadcast());
        assert!(!not_broadcast.is_broadcast());
    }

    #[test]
    fn test_is_unicast() {
        let mac_u = MacAddress::parse_str("FE:00:5E:AB:CD:EF").unwrap();
        let mac_m = MacAddress::parse_str("01:00:5E:AB:CD:EF").unwrap();
        assert!(mac_u.is_unicast());
        assert!(!mac_m.is_unicast());
        assert_eq!("fe:00:5e:ab:cd:ef", mac_u.to_hex_string()); // Catch modifying first octet
        let mac = MacAddress::parse_str("FF:00:5E:AB:CD:EF").unwrap();
        assert!(!mac.is_unicast());
        assert_eq!("ff:00:5e:ab:cd:ef", mac.to_hex_string()); // Catch modifying first octet
        assert!(MacAddress::nil().is_unicast());
        assert!(!MacAddress::broadcast().is_unicast());
    }

    #[test]
    fn test_is_multicast() {
        let mac_u = MacAddress::parse_str("FE:00:5E:AB:CD:EF").unwrap();
        let mac_m = MacAddress::parse_str("01:00:5E:AB:CD:EF").unwrap();
        assert!(!mac_u.is_multicast());
        assert!(mac_m.is_multicast());
        assert!(!MacAddress::nil().is_multicast());
        assert_eq!("01:00:5e:ab:cd:ef", mac_m.to_hex_string()); // Catch modifying first octet
        let mac = MacAddress::parse_str("F0:00:5E:AB:CD:EF").unwrap();
        assert!(!mac.is_multicast());
        assert_eq!("f0:00:5e:ab:cd:ef", mac.to_hex_string()); // Catch modifying first octet
        assert!(MacAddress::broadcast().is_multicast());
    }

    #[test]
    fn test_is_universal() {
        let universal = MacAddress::parse_str("11:24:56:AB:CD:EF").unwrap();
        let not_universal = MacAddress::parse_str("12:24:56:AB:CD:EF").unwrap();
        assert!(universal.is_universal());
        assert!(!not_universal.is_universal());
        assert_eq!("11:24:56:ab:cd:ef", universal.to_hex_string()); // Catch modifying first octet
    }

    #[test]
    fn test_is_local() {
        let local = MacAddress::parse_str("06:34:56:AB:CD:EF").unwrap();
        let not_local = MacAddress::parse_str("00:34:56:AB:CD:EF").unwrap();
        assert!(local.is_local());
        assert!(!not_local.is_local());
        assert_eq!("06:34:56:ab:cd:ef", local.to_hex_string()); // Catch modifying first octet
    }

    #[test]
    fn test_to_canonical() {
        let eui: Eui48 = [0x12, 0x34, 0x56, 0xAB, 0xCD, 0xEF];
        let mac = MacAddress::new(eui);
        assert_eq!("12-34-56-ab-cd-ef", mac.to_canonical());
    }

    #[test]
    fn test_to_hex_string() {
        let eui: Eui48 = [0x12, 0x34, 0x56, 0xAB, 0xCD, 0xEF];
        let mac = MacAddress::new(eui);
        assert_eq!("12:34:56:ab:cd:ef", mac.to_hex_string());
    }

    #[test]
    fn test_to_dot_string() {
        let eui: Eui48 = [0x12, 0x34, 0x56, 0xAB, 0xCD, 0xEF];
        let mac = MacAddress::new(eui);
        assert_eq!("1234.56ab.cdef", mac.to_dot_string());
    }

    #[test]
    fn test_to_hexadecimal() {
        let eui: Eui48 = [0x12, 0x34, 0x56, 0xAB, 0xCD, 0xEF];
        let mac = MacAddress::new(eui);
        assert_eq!("0x123456abcdef", mac.to_hexadecimal());
    }

    #[test]
    fn test_to_interfaceid() {
        let eui: Eui48 = [0x12, 0x34, 0x56, 0xAB, 0xCD, 0xEF];
        let mac = MacAddress::new(eui);
        assert_eq!("1034:56ff:feab:cdef", mac.to_interfaceid());
    }

    #[test]
    fn test_to_link_local() {
        let eui: Eui48 = [0x12, 0x34, 0x56, 0xAB, 0xCD, 0xEF];
        let mac = MacAddress::new(eui);
        assert_eq!("fe80::1034:56ff:feab:cdef", mac.to_link_local());
    }

    #[test]
    fn test_to_string() {
        let eui: Eui48 = [0x12, 0x34, 0x56, 0xAB, 0xCD, 0xEF];
        let mac = MacAddress::new(eui);
        assert_eq!(
            "0x123456abcdef",
            mac.to_string(MacAddressFormat::Hexadecimal)
        );
        assert_eq!(
            "1234.56ab.cdef",
            mac.to_string(MacAddressFormat::DotNotation)
        );
        assert_eq!(
            "12:34:56:ab:cd:ef",
            mac.to_string(MacAddressFormat::HexString)
        );
        assert_eq!(
            "12-34-56-ab-cd-ef",
            mac.to_string(MacAddressFormat::Canonical)
        );
    }

    #[test]
    fn test_parse_str() {
        use super::ParseError::*;

        assert_eq!(
            "0x123456abcdef",
            MacAddress::parse_str("0x123456ABCDEF")
                .unwrap()
                .to_hexadecimal()
        );
        assert_eq!(
            "1234.56ab.cdef",
            MacAddress::parse_str("1234.56AB.CDEF")
                .unwrap()
                .to_dot_string()
        );
        assert_eq!(
            "12:34:56:ab:cd:ef",
            MacAddress::parse_str("12:34:56:AB:CD:EF")
                .unwrap()
                .to_hex_string()
        );
        assert_eq!(
            "12-34-56-ab-cd-ef",
            MacAddress::parse_str("12-34-56-AB-CD-EF")
                .unwrap()
                .to_canonical()
        );
        assert_eq!(
            "12-34-56-78-90-0a",
            MacAddress::parse_str("0x1234567890A")
                .unwrap()
                .to_canonical()
        );
        assert_eq!(
            "12-34-56-ab-cd-ef",
            MacAddress::parse_str("123456ABCDEF")
                .unwrap()
                .to_canonical()
        );
        assert_eq!(
            "00-00-00-00-00-00",
            MacAddress::parse_str("!0x00000000000")
                .unwrap()
                .to_canonical()
        );
        assert_eq!(
            "00-00-00-00-00-00",
            MacAddress::parse_str("0x00000000000!")
                .unwrap()
                .to_canonical()
        );
        // Test error parsing
        assert_eq!(MacAddress::parse_str(""), Err(InvalidLength(0)));
        assert_eq!(MacAddress::parse_str("0"), Err(InvalidLength(1)));
        assert_eq!(
            MacAddress::parse_str("1234567890ABCD"),
            Err(InvalidByteCount(7, [0x12, 0x34, 0x56, 0x78, 0x90, 0xAB]))
        );
        assert_eq!(
            MacAddress::parse_str("1234567890ABCDEF"),
            Err(InvalidByteCount(8, [0x12, 0x34, 0x56, 0x78, 0x90, 0xAB]))
        );
        assert_eq!(
            MacAddress::parse_str("01234567890ABCDEF"),
            Err(InvalidByteCount(9, [0x01, 0x23, 0x45, 0x67, 0x89, 0x0A]))
        );
        assert_eq!(
            MacAddress::parse_str("0x1234567890ABCDE"),
            Err(InvalidByteCount(8, [0x12, 0x34, 0x56, 0x78, 0x90, 0xAB]))
        );
        assert_eq!(
            MacAddress::parse_str("0x00:01:02:03:"),
            Err(InvalidByteCount(4, [0, 1, 2, 3, 0, 0]))
        );
        assert_eq!(
            MacAddress::parse_str("0x00:01:02:03:04:"),
            Err(InvalidByteCount(5, [0, 1, 2, 3, 4, 0]))
        );
        assert_eq!(
            MacAddress::parse_str("::::::::::::::"),
            Err(InvalidByteCount(0, [0, 0, 0, 0, 0, 0]))
        );
        assert_eq!(
            MacAddress::parse_str(":::::::::::::::::"),
            Err(InvalidByteCount(0, [0, 0, 0, 0, 0, 0]))
        );
        assert_eq!(
            MacAddress::parse_str("0x0x0x0x0x0x0x"),
            Err(InvalidByteCount(4, [0, 0, 0, 0, 0, 0]))
        );
    }

    #[test]
    fn test_as_bytes() {
        let mac = MacAddress::broadcast();
        let bytes = mac.as_bytes();

        assert!(bytes.len() == 6);
        assert!(bytes.iter().all(|&b| b == 0xFF));
    }

    #[test]
    fn test_compare() {
        let m1 = MacAddress::nil();
        let m2 = MacAddress::broadcast();
        assert_eq!(m1, m1);
        assert_eq!(m2, m2);
        assert_ne!(m1, m2);
        assert_ne!(m2, m1);
    }

    #[test]
    fn test_clone() {
        let m1 = MacAddress::parse_str("12:34:56:AB:CD:EF").unwrap();
        let m2 = m1;
        assert_eq!(m1, m1);
        assert_eq!(m2, m2);
        assert_eq!(m1, m2);
        assert_eq!(m2, m1);
    }

    #[test]
    fn test_serialize() {
        use rustc_serialize::json;

        let mac = MacAddress::parse_str("12:34:56:AB:CD:EF").unwrap();
        // Format returned is base on compile time of feature(disp_hexstring)
        if cfg!(feature = "disp_hexstring") {
            assert_eq!("\"12:34:56:ab:cd:ef\"", json::encode(&mac).unwrap());
        } else {
            assert_eq!("\"12-34-56-ab-cd-ef\"", json::encode(&mac).unwrap());
        }
    }

    #[test]
    fn test_deserialize() {
        use rustc_serialize::json;

        let mac = MacAddress::parse_str("12:34:56:AB:CD:EF").unwrap();

        if cfg!(feature = "disp_hexstring") {
            let d = "\"12:34:56:AB:CD:EF\"";
            assert_eq!(mac, json::decode(&d).unwrap());
        } else {
            let d = "\"12-34-56-AB-CD-EF\"";
            assert_eq!(mac, json::decode(&d).unwrap());
        }
    }

    #[test]
    fn test_serialize_roundtrip() {
        use rustc_serialize::json;

        let m1 = MacAddress::parse_str("12:34:56:AB:CD:EF").unwrap();
        let s = json::encode(&m1).unwrap();
        let m2 = json::decode(&s).unwrap();
        assert_eq!(m1, m2);
    }

    #[test]
    fn test_fmt_debug() {
        let mac = MacAddress::parse_str("12:34:56:AB:CD:EF").unwrap();
        assert_eq!(
            "MacAddress(\"12:34:56:ab:cd:ef\")".to_owned(),
            format!("{:?}", mac)
        );
    }

    #[test]
    fn test_fmt() {
        let mac = MacAddress::parse_str("0x123456ABCDEF").unwrap();
        match MacAddress::get_display_format() {
            MacAddressFormat::HexString => {
                assert_eq!("12:34:56:ab:cd:ef".to_owned(), format!("{}", mac))
            }
            _ => assert_eq!("12-34-56-ab-cd-ef".to_owned(), format!("{}", mac)),
        };
    }

    #[test]
    fn test_fmt_parse_errors() {
        assert_eq!(
            "Err(InvalidByteCount(7, [18, 52, 86, 171, 205, 239]))".to_owned(),
            format!("{:?}", MacAddress::parse_str("123456ABCDEF1"))
        );
        assert_eq!(
            "Err(InvalidLength(19))",
            format!("{:?}", MacAddress::parse_str("12##45#67#89#AB#C#D"))
        );
    }

    #[test]
    #[cfg(feature = "serde_json")]
    fn test_serde_json_serialize() {
        use serde_json;
        let serialized =
            serde_json::to_string(&MacAddress::parse_str("12:34:56:AB:CD:EF").unwrap()).unwrap();
        if cfg!(feature = "disp_hexstring") {
            assert_eq!("\"12:34:56:ab:cd:ef\"", serialized);
        } else {
            assert_eq!("\"12-34-56-ab-cd-ef\"", serialized);
        }
    }

    #[test]
    #[cfg(feature = "serde_json")]
    fn test_serde_json_deserialize() {
        use serde_json;
        let mac = MacAddress::parse_str("12:34:56:AB:CD:EF").unwrap();
        let deserialized: MacAddress = serde_json::from_str("\"12-34-56-AB-CD-EF\"").unwrap();
        assert_eq!(deserialized, mac);
    }

    #[test]
    #[should_panic(expected = "Invalid length; expecting 11 to 17 chars, found 2")]
    #[cfg(feature = "serde_json")]
    fn test_serde_json_deserialize_panic() {
        let _should_panic: MacAddress = serde_json::from_str("\"12\"").unwrap();
    }

    #[test]
    #[cfg(feature = "serde_bytes")]
    fn test_serde_bytes_serialization_roundtrip() {
        use bincode;
        let mac = MacAddress::parse_str("12:34:56:AB:CD:EF").unwrap();
        let mut buffer = Vec::new();
        bincode::serialize_into(&mut buffer, &mac).unwrap();
        let deserialized: MacAddress = bincode::deserialize_from(&*buffer).unwrap();
        assert_eq!(deserialized, mac);
    }

    #[test]
    fn test_macaddressformat_derive() {
        assert_eq!(MacAddressFormat::HexString, MacAddressFormat::HexString);
        assert_ne!(MacAddressFormat::HexString, MacAddressFormat::Canonical);
    }

    #[test]
    fn test_parseerror_fmt() {
        assert_eq!(
            "Invalid length; expecting 11 to 17 chars, found 2".to_owned(),
            format!("{}", ParseError::InvalidLength(2))
        );
        assert_eq!(
            "Invalid length; expecting 11 to 17 chars, found 2".to_owned(),
            ParseError::InvalidLength(2).to_string()
        );
    }

    #[test]
    fn test_to_array() {
        let eui: Eui48 = [0x12, 0x34, 0x56, 0xAB, 0xCD, 0xEF];
        let mac = MacAddress::new(eui);
        assert_eq!(eui, MacAddress::new(eui).to_array());
        assert_eq!(mac, MacAddress::new(mac.to_array()));
    }
}