Skip to main content

bgpkit_parser/models/bgp/
community.rs

1use crate::models::Asn;
2use num_enum::{FromPrimitive, IntoPrimitive};
3use std::fmt::{Display, Formatter};
4use std::net::{Ipv4Addr, Ipv6Addr};
5
6#[derive(Debug, PartialEq, Copy, Clone, Eq)]
7#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
8#[cfg_attr(feature = "serde", serde(untagged))]
9pub enum MetaCommunity {
10    Plain(Community),
11    Extended(ExtendedCommunity),
12    Ipv6Extended(Ipv6AddrExtCommunity),
13    Large(LargeCommunity),
14}
15
16#[derive(Debug, PartialEq, Copy, Clone, Eq)]
17#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
18#[cfg_attr(feature = "ts-rs", derive(ts_rs::TS), ts(export))]
19pub enum Community {
20    NoExport,
21    NoAdvertise,
22    NoExportSubConfed,
23    Custom(Asn, u16),
24}
25
26/// Large community structure as defined in [RFC8092](https://datatracker.ietf.org/doc/html/rfc8092)
27///
28/// ## Display
29///
30/// Large community is displayed as `GLOBAL_ADMINISTRATOR:LOCAL_DATA_1:LOCAL_DATA_2`
31#[derive(Debug, PartialEq, Clone, Copy, Eq)]
32#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
33#[cfg_attr(feature = "ts-rs", derive(ts_rs::TS), ts(export))]
34pub struct LargeCommunity {
35    pub global_admin: u32,
36    pub local_data: [u32; 2],
37}
38
39impl LargeCommunity {
40    pub fn new(global_admin: u32, local_data: [u32; 2]) -> LargeCommunity {
41        LargeCommunity {
42            global_admin,
43            local_data,
44        }
45    }
46}
47
48/// Type definitions of extended communities
49#[derive(Debug, FromPrimitive, IntoPrimitive, PartialEq, Eq, Hash, Copy, Clone)]
50#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
51#[cfg_attr(feature = "ts-rs", derive(ts_rs::TS), ts(export))]
52#[repr(u8)]
53pub enum ExtendedCommunityType {
54    // transitive types
55    TransitiveTwoOctetAs = 0x00,
56    TransitiveIpv4Addr = 0x01,
57    TransitiveFourOctetAs = 0x02,
58    TransitiveOpaque = 0x03,
59    /// EVPN extended community - RFC 7432 §7
60    Evpn = 0x06,
61
62    // non-transitive types
63    NonTransitiveTwoOctetAs = 0x40,
64    NonTransitiveIpv4Addr = 0x41,
65    NonTransitiveFourOctetAs = 0x42,
66    NonTransitiveOpaque = 0x43,
67    // the rest are either draft or experimental
68    #[num_enum(catch_all)]
69    Unknown(u8),
70}
71
72impl ExtendedCommunityType {
73    /// Map a wire type octet to a variant.
74    ///
75    /// [`From<u8>`] cannot be used in a constant context, and
76    /// [`ExtendedCommunity::community_type`] is `const`, so the mapping is
77    /// spelled out here. Keep it in step with the enum.
78    pub const fn from_byte(byte: u8) -> Self {
79        use ExtendedCommunityType::*;
80        match byte {
81            0x00 => TransitiveTwoOctetAs,
82            0x01 => TransitiveIpv4Addr,
83            0x02 => TransitiveFourOctetAs,
84            0x03 => TransitiveOpaque,
85            0x06 => Evpn,
86            0x40 => NonTransitiveTwoOctetAs,
87            0x41 => NonTransitiveIpv4Addr,
88            0x42 => NonTransitiveFourOctetAs,
89            0x43 => NonTransitiveOpaque,
90            other => Unknown(other),
91        }
92    }
93}
94
95/// Extended Communities.
96///
97/// ## Overview  
98///
99/// It is a 8-octet data that has flexible definition based on the types:
100/// <https://datatracker.ietf.org/doc/html/rfc4360>
101///
102/// For more up-to-date definitions, see [IANA' website](https://www.iana.org/assignments/bgp-extended-communities/bgp-extended-communities.xhtml).
103///
104/// ```text
105///    Each Extended Community is encoded as an 8-octet quantity, as
106///    follows:
107///
108///       - Type Field  : 1 or 2 octets
109///       - Value Field : Remaining octets
110///
111///        0                   1                   2                   3
112///        0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
113///       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
114///       |  Type high    |  Type low(*)  |                               |
115///       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+          Value                |
116///       |                                                               |
117///       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
118///
119///       (*) Present for Extended types only, used for the Value field
120///           otherwise.
121/// ```
122#[derive(Debug, PartialEq, Clone, Copy, Eq)]
123#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
124#[cfg_attr(feature = "ts-rs", derive(ts_rs::TS), ts(export))]
125pub enum ExtendedCommunity {
126    TransitiveTwoOctetAs(TwoOctetAsExtCommunity),
127    TransitiveIpv4Addr(Ipv4AddrExtCommunity),
128    TransitiveFourOctetAs(FourOctetAsExtCommunity),
129    TransitiveOpaque(OpaqueExtCommunity),
130    NonTransitiveTwoOctetAs(TwoOctetAsExtCommunity),
131    NonTransitiveIpv4Addr(Ipv4AddrExtCommunity),
132    NonTransitiveFourOctetAs(FourOctetAsExtCommunity),
133    NonTransitiveOpaque(OpaqueExtCommunity),
134    /// Flow-Spec Traffic Rate - RFC 8955
135    FlowSpecTrafficRate(FlowSpecTrafficRate),
136    /// Flow-Spec Traffic Action - RFC 8955  
137    FlowSpecTrafficAction(FlowSpecTrafficAction),
138    /// Flow-Spec Redirect - RFC 8955
139    FlowSpecRedirect(TwoOctetAsExtCommunity),
140    /// Flow-Spec Traffic Marking - RFC 8955
141    FlowSpecTrafficMarking(FlowSpecTrafficMarking),
142    /// BGP Link Bandwidth - RFC 10005
143    LinkBandwidth(LinkBandwidth),
144    /// MAC Mobility - RFC 7432 §7.7
145    MacMobility(MacMobility),
146    Raw([u8; 8]),
147}
148
149impl ExtendedCommunity {
150    pub const fn community_type(&self) -> ExtendedCommunityType {
151        use ExtendedCommunityType::*;
152        match self {
153            ExtendedCommunity::TransitiveTwoOctetAs(_) => TransitiveTwoOctetAs,
154            ExtendedCommunity::TransitiveIpv4Addr(_) => TransitiveIpv4Addr,
155            ExtendedCommunity::TransitiveFourOctetAs(_) => TransitiveFourOctetAs,
156            ExtendedCommunity::TransitiveOpaque(_) => TransitiveOpaque,
157            ExtendedCommunity::NonTransitiveTwoOctetAs(_) => NonTransitiveTwoOctetAs,
158            ExtendedCommunity::NonTransitiveIpv4Addr(_) => NonTransitiveIpv4Addr,
159            ExtendedCommunity::NonTransitiveFourOctetAs(_) => NonTransitiveFourOctetAs,
160            ExtendedCommunity::NonTransitiveOpaque(_) => NonTransitiveOpaque,
161            ExtendedCommunity::FlowSpecTrafficRate(_) => NonTransitiveTwoOctetAs,
162            ExtendedCommunity::FlowSpecTrafficAction(_) => NonTransitiveTwoOctetAs,
163            ExtendedCommunity::FlowSpecRedirect(_) => NonTransitiveTwoOctetAs,
164            ExtendedCommunity::FlowSpecTrafficMarking(_) => NonTransitiveTwoOctetAs,
165            ExtendedCommunity::LinkBandwidth(link_bandwidth) => {
166                if link_bandwidth.transitive {
167                    TransitiveTwoOctetAs
168                } else {
169                    NonTransitiveTwoOctetAs
170                }
171            }
172            ExtendedCommunity::MacMobility(_) => Evpn,
173            ExtendedCommunity::Raw(buffer) => ExtendedCommunityType::from_byte(buffer[0]),
174        }
175    }
176}
177
178#[derive(Debug, PartialEq, Clone, Copy, Eq)]
179#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
180#[cfg_attr(feature = "ts-rs", derive(ts_rs::TS), ts(export))]
181pub struct Ipv6AddrExtCommunity {
182    pub community_type: ExtendedCommunityType,
183    pub subtype: u8,
184    // 16 octets
185    pub global_admin: Ipv6Addr,
186    // 2 octets
187    pub local_admin: [u8; 2],
188}
189
190/// MAC Mobility Extended Community - RFC 7432 §7.7
191///
192/// Carried with a MAC/IP Advertisement (route type 2). The sequence number is
193/// how a fabric orders competing advertisements for the same MAC: the highest
194/// value wins, and a PE that sees a locally learned MAC it previously knew as
195/// remote re-advertises it with the sequence number incremented.
196///
197/// ```text
198///  0                   1                   2                   3
199///  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
200/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
201/// |  Type = 0x06  | Sub-Type = 0x00|     Flags   |   Reserved    |
202/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
203/// |                      Sequence Number                          |
204/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
205/// ```
206#[derive(Debug, PartialEq, Clone, Copy, Eq)]
207#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
208#[cfg_attr(feature = "ts-rs", derive(ts_rs::TS), ts(export))]
209pub struct MacMobility {
210    /// Sticky/static flag (bit 0 of the flags octet): the MAC is considered
211    /// immobile and does not take part in sequence-number comparison.
212    pub sticky: bool,
213    /// Sequence number, 32 bits big-endian.
214    pub sequence: u32,
215}
216
217/// Two-Octet AS Specific Extended Community
218///
219/// <https://datatracker.ietf.org/doc/html/rfc4360#section-3.1>
220#[derive(Debug, PartialEq, Clone, Copy, Eq)]
221#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
222#[cfg_attr(feature = "ts-rs", derive(ts_rs::TS), ts(export))]
223pub struct TwoOctetAsExtCommunity {
224    pub subtype: u8,
225    // 2 octet
226    pub global_admin: Asn,
227    // 4 octet
228    pub local_admin: [u8; 4],
229}
230
231/// Four-Octet AS Specific Extended Community
232///
233/// <https://datatracker.ietf.org/doc/html/rfc5668#section-2>
234#[derive(Debug, PartialEq, Clone, Copy, Eq)]
235#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
236#[cfg_attr(feature = "ts-rs", derive(ts_rs::TS), ts(export))]
237pub struct FourOctetAsExtCommunity {
238    pub subtype: u8,
239    // 4 octet
240    pub global_admin: Asn,
241    // 2 octet
242    pub local_admin: [u8; 2],
243}
244
245/// IPv4 Address Specific Extended Community
246///
247/// <https://datatracker.ietf.org/doc/html/rfc4360#section-3.2>
248#[derive(Debug, PartialEq, Clone, Copy, Eq)]
249#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
250#[cfg_attr(feature = "ts-rs", derive(ts_rs::TS), ts(export))]
251pub struct Ipv4AddrExtCommunity {
252    pub subtype: u8,
253    // 4 octet
254    pub global_admin: Ipv4Addr,
255    // 2 octet
256    pub local_admin: [u8; 2],
257}
258
259/// Opaque Extended Community
260///
261/// <https://datatracker.ietf.org/doc/html/rfc4360#section-3.3>
262#[derive(Debug, PartialEq, Clone, Copy, Eq)]
263#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
264#[cfg_attr(feature = "ts-rs", derive(ts_rs::TS), ts(export))]
265pub struct OpaqueExtCommunity {
266    pub subtype: u8,
267    // 6 octet
268    pub value: [u8; 6],
269}
270
271/// BGP Link Bandwidth Extended Community
272///
273/// RFC 10005 - subtype 0x04
274#[derive(Debug, Clone, Copy)]
275#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
276#[cfg_attr(feature = "ts-rs", derive(ts_rs::TS), ts(export))]
277pub struct LinkBandwidth {
278    /// Global Administrator value (2 octets)
279    pub global_admin: u16,
280    /// Bandwidth in bytes per second (IEEE 754 single-precision float)
281    pub bandwidth: f32,
282    /// Whether the community uses type 0x00 rather than non-transitive type 0x40
283    pub transitive: bool,
284}
285
286impl PartialEq for LinkBandwidth {
287    fn eq(&self, other: &Self) -> bool {
288        self.global_admin == other.global_admin
289            && self.bandwidth.to_bits() == other.bandwidth.to_bits()
290            && self.transitive == other.transitive
291    }
292}
293
294impl Eq for LinkBandwidth {}
295
296/// Flow-Spec Traffic Rate Extended Community
297///
298/// RFC 8955 - subtype 0x06
299#[derive(Debug, Clone, Copy)]
300#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
301#[cfg_attr(feature = "ts-rs", derive(ts_rs::TS), ts(export))]
302pub struct FlowSpecTrafficRate {
303    /// AS Number (2 octets)
304    pub as_number: u16,
305    /// Rate in bytes per second (IEEE 754 single precision float)
306    pub rate_bytes_per_sec: f32,
307}
308
309impl PartialEq for FlowSpecTrafficRate {
310    fn eq(&self, other: &Self) -> bool {
311        self.as_number == other.as_number
312            && self.rate_bytes_per_sec.to_bits() == other.rate_bytes_per_sec.to_bits()
313    }
314}
315
316impl Eq for FlowSpecTrafficRate {}
317
318/// Flow-Spec Traffic Action Extended Community
319///
320/// RFC 8955 - subtype 0x07  
321#[derive(Debug, PartialEq, Clone, Copy, Eq)]
322#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
323#[cfg_attr(feature = "ts-rs", derive(ts_rs::TS), ts(export))]
324pub struct FlowSpecTrafficAction {
325    /// AS Number (2 octets)
326    pub as_number: u16,
327    /// Terminal action - stop processing additional flow-specs
328    pub terminal: bool,
329    /// Sample action - enable traffic sampling
330    pub sample: bool,
331}
332
333/// Flow-Spec Traffic Marking Extended Community
334///
335/// RFC 8955 - subtype 0x09
336#[derive(Debug, PartialEq, Clone, Copy, Eq)]
337#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
338#[cfg_attr(feature = "ts-rs", derive(ts_rs::TS), ts(export))]
339pub struct FlowSpecTrafficMarking {
340    /// AS Number (2 octets)
341    pub as_number: u16,
342    /// DSCP value (6 bits)
343    pub dscp: u8,
344}
345
346impl FlowSpecTrafficRate {
347    /// Create a new traffic rate community
348    pub fn new(as_number: u16, rate_bytes_per_sec: f32) -> Self {
349        Self {
350            as_number,
351            rate_bytes_per_sec,
352        }
353    }
354
355    /// Create a "discard all traffic" rate (rate = 0.0)
356    pub fn discard(as_number: u16) -> Self {
357        Self {
358            as_number,
359            rate_bytes_per_sec: 0.0,
360        }
361    }
362}
363
364impl FlowSpecTrafficAction {
365    /// Create a new traffic action community
366    pub fn new(as_number: u16, terminal: bool, sample: bool) -> Self {
367        Self {
368            as_number,
369            terminal,
370            sample,
371        }
372    }
373}
374
375impl FlowSpecTrafficMarking {
376    /// Create a new traffic marking community
377    pub fn new(as_number: u16, dscp: u8) -> Self {
378        Self {
379            as_number,
380            dscp: dscp & 0x3F,
381        } // Mask to 6 bits
382    }
383}
384
385/////////////
386// DISPLAY //
387/////////////
388
389struct ToHexString<'a>(&'a [u8]);
390
391impl Display for ToHexString<'_> {
392    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
393        for byte in self.0 {
394            write!(f, "{byte:02X}")?;
395        }
396        Ok(())
397    }
398}
399
400impl Display for Community {
401    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
402        match self {
403            Community::NoExport => write!(f, "no-export"),
404            Community::NoAdvertise => write!(f, "no-advertise"),
405            Community::NoExportSubConfed => write!(f, "no-export-sub-confed"),
406            Community::Custom(asn, value) => write!(f, "{asn}:{value}"),
407        }
408    }
409}
410
411impl Display for LargeCommunity {
412    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
413        write!(
414            f,
415            "{}:{}:{}",
416            self.global_admin, self.local_data[0], self.local_data[1]
417        )
418    }
419}
420
421impl Display for ExtendedCommunity {
422    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
423        let ec_type = u8::from(self.community_type());
424        match self {
425            ExtendedCommunity::TransitiveTwoOctetAs(ec)
426            | ExtendedCommunity::NonTransitiveTwoOctetAs(ec) => {
427                write!(
428                    f,
429                    "{}:{}:{}:{}",
430                    ec_type,
431                    ec.subtype,
432                    ec.global_admin,
433                    ToHexString(&ec.local_admin)
434                )
435            }
436            ExtendedCommunity::TransitiveIpv4Addr(ec)
437            | ExtendedCommunity::NonTransitiveIpv4Addr(ec) => {
438                write!(
439                    f,
440                    "{}:{}:{}:{}",
441                    ec_type,
442                    ec.subtype,
443                    ec.global_admin,
444                    ToHexString(&ec.local_admin)
445                )
446            }
447            ExtendedCommunity::TransitiveFourOctetAs(ec)
448            | ExtendedCommunity::NonTransitiveFourOctetAs(ec) => {
449                write!(
450                    f,
451                    "{}:{}:{}:{}",
452                    ec_type,
453                    ec.subtype,
454                    ec.global_admin,
455                    ToHexString(&ec.local_admin)
456                )
457            }
458            ExtendedCommunity::TransitiveOpaque(ec)
459            | ExtendedCommunity::NonTransitiveOpaque(ec) => {
460                write!(f, "{}:{}:{}", ec_type, ec.subtype, ToHexString(&ec.value))
461            }
462            ExtendedCommunity::FlowSpecTrafficRate(rate) => {
463                write!(
464                    f,
465                    "rate:{} bytes/sec (AS {})",
466                    rate.rate_bytes_per_sec, rate.as_number
467                )
468            }
469            ExtendedCommunity::FlowSpecTrafficAction(action) => {
470                let mut flags = Vec::new();
471                if action.terminal {
472                    flags.push("terminal");
473                }
474                if action.sample {
475                    flags.push("sample");
476                }
477                write!(f, "action:{} (AS {})", flags.join(","), action.as_number)
478            }
479            ExtendedCommunity::FlowSpecRedirect(redirect) => {
480                write!(
481                    f,
482                    "redirect:AS{}:{}",
483                    redirect.global_admin,
484                    ToHexString(&redirect.local_admin)
485                )
486            }
487            ExtendedCommunity::FlowSpecTrafficMarking(marking) => {
488                write!(f, "mark:DSCP{} (AS {})", marking.dscp, marking.as_number)
489            }
490            ExtendedCommunity::LinkBandwidth(link_bandwidth) => {
491                write!(
492                    f,
493                    "{}:{}:{}:{}",
494                    ec_type, 0x04, link_bandwidth.global_admin, link_bandwidth.bandwidth
495                )
496            }
497            ExtendedCommunity::MacMobility(mobility) => {
498                write!(
499                    f,
500                    "{}:{}:{}:{}",
501                    ec_type,
502                    0x00,
503                    u8::from(mobility.sticky),
504                    mobility.sequence
505                )
506            }
507            ExtendedCommunity::Raw(ec) => {
508                write!(f, "{}", ToHexString(ec))
509            }
510        }
511    }
512}
513
514impl Display for Ipv6AddrExtCommunity {
515    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
516        write!(
517            f,
518            "{}:{}:{}:{}",
519            u8::from(self.community_type),
520            self.subtype,
521            self.global_admin,
522            ToHexString(&self.local_admin)
523        )
524    }
525}
526
527impl Display for MetaCommunity {
528    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
529        match self {
530            MetaCommunity::Plain(c) => write!(f, "{c}"),
531            MetaCommunity::Extended(c) => write!(f, "{c}"),
532            MetaCommunity::Large(c) => write!(f, "{c}"),
533            MetaCommunity::Ipv6Extended(c) => write!(f, "{c}"),
534        }
535    }
536}
537
538#[cfg(test)]
539mod tests {
540    use super::*;
541
542    #[test]
543    fn test_large_community_new() {
544        let global_admin = 56;
545        let local_data = [3, 4];
546        let large_comm = LargeCommunity::new(global_admin, local_data);
547        assert_eq!(large_comm.global_admin, global_admin);
548        assert_eq!(large_comm.local_data, local_data);
549    }
550
551    #[test]
552    fn test_extended_community_community_type() {
553        let two_octet_as_ext_comm = TwoOctetAsExtCommunity {
554            subtype: 0,
555            global_admin: Asn::new_32bit(0),
556            local_admin: [0; 4],
557        };
558        let extended_community = ExtendedCommunity::TransitiveTwoOctetAs(two_octet_as_ext_comm);
559        assert_eq!(
560            extended_community.community_type(),
561            ExtendedCommunityType::TransitiveTwoOctetAs
562        );
563    }
564
565    #[test]
566    fn test_display_community() {
567        assert_eq!(format!("{}", Community::NoExport), "no-export");
568        assert_eq!(format!("{}", Community::NoAdvertise), "no-advertise");
569        assert_eq!(
570            format!("{}", Community::NoExportSubConfed),
571            "no-export-sub-confed"
572        );
573        assert_eq!(
574            format!("{}", Community::Custom(Asn::new_32bit(64512), 100)),
575            "64512:100"
576        );
577    }
578
579    #[test]
580    fn test_display_large_community() {
581        let large_community = LargeCommunity::new(1, [2, 3]);
582        assert_eq!(format!("{large_community}"), "1:2:3");
583    }
584
585    #[test]
586    fn test_display_extended_community() {
587        let two_octet_as_ext_comm = TwoOctetAsExtCommunity {
588            subtype: 0,
589            global_admin: Asn::new_32bit(0),
590            local_admin: [0; 4],
591        };
592        let extended_community = ExtendedCommunity::TransitiveTwoOctetAs(two_octet_as_ext_comm);
593        assert_eq!(format!("{extended_community}"), "0:0:0:00000000");
594
595        let two_octet_as_ext_comm = TwoOctetAsExtCommunity {
596            subtype: 0,
597            global_admin: Asn::new_32bit(0),
598            local_admin: [0; 4],
599        };
600        let extended_community = ExtendedCommunity::NonTransitiveTwoOctetAs(two_octet_as_ext_comm);
601        assert_eq!(format!("{extended_community}"), "64:0:0:00000000");
602
603        let ipv4_ext_comm = Ipv4AddrExtCommunity {
604            subtype: 1,
605            global_admin: "192.168.1.1".parse().unwrap(),
606            local_admin: [5, 6],
607        };
608        let extended_community = ExtendedCommunity::TransitiveIpv4Addr(ipv4_ext_comm);
609        assert_eq!(format!("{extended_community}"), "1:1:192.168.1.1:0506");
610
611        let ipv4_ext_comm = Ipv4AddrExtCommunity {
612            subtype: 1,
613            global_admin: "192.168.1.1".parse().unwrap(),
614            local_admin: [5, 6],
615        };
616        let extended_community = ExtendedCommunity::NonTransitiveIpv4Addr(ipv4_ext_comm);
617        assert_eq!(format!("{extended_community}"), "65:1:192.168.1.1:0506");
618
619        let four_octet_as_ext_comm = FourOctetAsExtCommunity {
620            subtype: 2,
621            global_admin: Asn::new_32bit(64512),
622            local_admin: [7, 8],
623        };
624        let extended_community = ExtendedCommunity::TransitiveFourOctetAs(four_octet_as_ext_comm);
625        assert_eq!(format!("{extended_community}"), "2:2:64512:0708");
626
627        let four_octet_as_ext_comm = FourOctetAsExtCommunity {
628            subtype: 2,
629            global_admin: Asn::new_32bit(64512),
630            local_admin: [7, 8],
631        };
632        let extended_community =
633            ExtendedCommunity::NonTransitiveFourOctetAs(four_octet_as_ext_comm);
634        assert_eq!(format!("{extended_community}"), "66:2:64512:0708");
635
636        let opaque_ext_comm = OpaqueExtCommunity {
637            subtype: 3,
638            value: [9, 10, 11, 12, 13, 14],
639        };
640        let extended_community = ExtendedCommunity::TransitiveOpaque(opaque_ext_comm);
641        assert_eq!(format!("{extended_community}"), "3:3:090A0B0C0D0E");
642
643        let opaque_ext_comm = OpaqueExtCommunity {
644            subtype: 3,
645            value: [9, 10, 11, 12, 13, 14],
646        };
647        let extended_community = ExtendedCommunity::NonTransitiveOpaque(opaque_ext_comm);
648        assert_eq!(format!("{extended_community}"), "67:3:090A0B0C0D0E");
649
650        let link_bandwidth = ExtendedCommunity::LinkBandwidth(LinkBandwidth {
651            global_admin: 1,
652            bandwidth: 1000.0,
653            transitive: true,
654        });
655        assert_eq!(format!("{link_bandwidth}"), "0:4:1:1000");
656
657        let link_bandwidth = ExtendedCommunity::LinkBandwidth(LinkBandwidth {
658            global_admin: 1,
659            bandwidth: 1000.0,
660            transitive: false,
661        });
662        assert_eq!(format!("{link_bandwidth}"), "64:4:1:1000");
663
664        let raw_ext_comm = [0, 1, 2, 3, 4, 5, 6, 7];
665        let extended_community = ExtendedCommunity::Raw(raw_ext_comm);
666        assert_eq!(format!("{extended_community}"), "0001020304050607");
667    }
668
669    #[test]
670    fn test_display_ipv6_addr_ext_community() {
671        let ipv6_addr_ext_comm = Ipv6AddrExtCommunity {
672            community_type: ExtendedCommunityType::TransitiveTwoOctetAs,
673            subtype: 0,
674            global_admin: "2001:db8::8a2e:370:7334".parse().unwrap(),
675            local_admin: [0, 1],
676        };
677        assert_eq!(
678            format!("{ipv6_addr_ext_comm}"),
679            "0:0:2001:db8::8a2e:370:7334:0001"
680        );
681    }
682
683    #[test]
684    fn test_display_meta_community() {
685        let large_community = LargeCommunity::new(1, [2, 3]);
686        let meta_community = MetaCommunity::Large(large_community);
687        assert_eq!(format!("{meta_community}"), "1:2:3");
688    }
689
690    #[test]
691    fn test_to_hex_string() {
692        // Test empty array
693        assert_eq!(format!("{}", ToHexString(&[])), "");
694
695        // Test single byte
696        assert_eq!(format!("{}", ToHexString(&[0x0A])), "0A");
697
698        // Test multiple bytes
699        assert_eq!(format!("{}", ToHexString(&[0x0A, 0x0B, 0x0C])), "0A0B0C");
700
701        // Test zero byte
702        assert_eq!(format!("{}", ToHexString(&[0x00])), "00");
703
704        // Test byte with value > 0x0F (needs two hex digits)
705        assert_eq!(format!("{}", ToHexString(&[0x10])), "10");
706
707        // Test mixed bytes
708        assert_eq!(
709            format!("{}", ToHexString(&[0x00, 0x0F, 0x10, 0xFF])),
710            "000F10FF"
711        );
712    }
713
714    #[test]
715    #[cfg(feature = "serde")]
716    fn test_serde() {
717        let meta_community = MetaCommunity::Large(LargeCommunity::new(1, [2, 3]));
718        let serialized = serde_json::to_string(&meta_community).unwrap();
719        let deserialized: MetaCommunity = serde_json::from_str(&serialized).unwrap();
720        assert_eq!(meta_community, deserialized);
721
722        let meta_community = MetaCommunity::Extended(ExtendedCommunity::TransitiveTwoOctetAs(
723            TwoOctetAsExtCommunity {
724                subtype: 0,
725                global_admin: Asn::new_32bit(0),
726                local_admin: [0; 4],
727            },
728        ));
729        let serialized = serde_json::to_string(&meta_community).unwrap();
730        let deserialized: MetaCommunity = serde_json::from_str(&serialized).unwrap();
731        assert_eq!(meta_community, deserialized);
732
733        let meta_community = MetaCommunity::Plain(Community::NoExport);
734        let serialized = serde_json::to_string(&meta_community).unwrap();
735        let deserialized: MetaCommunity = serde_json::from_str(&serialized).unwrap();
736        assert_eq!(meta_community, deserialized);
737
738        let meta_community = MetaCommunity::Ipv6Extended(Ipv6AddrExtCommunity {
739            community_type: ExtendedCommunityType::TransitiveTwoOctetAs,
740            subtype: 0,
741            global_admin: "2001:db8::8a2e:370:7334".parse().unwrap(),
742            local_admin: [0, 1],
743        });
744        let serialized = serde_json::to_string(&meta_community).unwrap();
745        let deserialized: MetaCommunity = serde_json::from_str(&serialized).unwrap();
746        assert_eq!(meta_community, deserialized);
747    }
748
749    #[test]
750    fn test_flowspec_traffic_rate() {
751        let rate = FlowSpecTrafficRate::new(64512, 1000.0);
752        assert_eq!(rate.as_number, 64512);
753        assert_eq!(rate.rate_bytes_per_sec, 1000.0);
754
755        let discard = FlowSpecTrafficRate::discard(64512);
756        assert_eq!(discard.rate_bytes_per_sec, 0.0);
757    }
758
759    #[test]
760    fn test_flowspec_traffic_action() {
761        let action = FlowSpecTrafficAction::new(64512, true, false);
762        assert_eq!(action.as_number, 64512);
763        assert!(action.terminal);
764        assert!(!action.sample);
765    }
766
767    #[test]
768    fn test_flowspec_traffic_marking() {
769        let marking = FlowSpecTrafficMarking::new(64512, 46); // EF DSCP
770        assert_eq!(marking.as_number, 64512);
771        assert_eq!(marking.dscp, 46);
772
773        // Test DSCP masking
774        let masked = FlowSpecTrafficMarking::new(64512, 255);
775        assert_eq!(masked.dscp, 63); // Should be masked to 6 bits
776    }
777
778    #[test]
779    fn test_flowspec_community_display() {
780        let rate = ExtendedCommunity::FlowSpecTrafficRate(FlowSpecTrafficRate::new(64512, 1000.0));
781        assert_eq!(format!("{}", rate), "rate:1000 bytes/sec (AS 64512)");
782
783        let action =
784            ExtendedCommunity::FlowSpecTrafficAction(FlowSpecTrafficAction::new(64512, true, true));
785        assert_eq!(format!("{}", action), "action:terminal,sample (AS 64512)");
786
787        let marking =
788            ExtendedCommunity::FlowSpecTrafficMarking(FlowSpecTrafficMarking::new(64512, 46));
789        assert_eq!(format!("{}", marking), "mark:DSCP46 (AS 64512)");
790    }
791}