Skip to content

Commit c3b73a5

Browse files
committed
Add constructor for Seg6Header
As the structure Seg6Header is tagged with `non_exhaustive`, there is currently no way for an external library to create a Seg6Header structure. By defining a constructor function `new` for Seg6Header, this patch should allow to create Seg6Header instances. In addition, this constructor checks if the segment list is valid, i.e. if at least one segment is present, preventing an underflow exception in `emit_value`. Signed-off-by: Aperence <anthony.doeraene@hotmail.com>
1 parent 420d181 commit c3b73a5

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

src/route/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,6 @@ pub use self::{
3636
next_hops::{RouteNextHop, RouteNextHopBuffer, RouteNextHopFlags},
3737
preference::RoutePreference,
3838
realm::RouteRealm,
39-
seg6::{RouteSeg6IpTunnel, Seg6Header, Seg6Mode},
39+
seg6::{RouteSeg6IpTunnel, Seg6Error, Seg6Header, Seg6Mode},
4040
via::{RouteVia, RouteViaBuffer},
4141
};

src/route/seg6.rs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,22 @@ buffer!(Seg6SegmentBuffer(SEG6_SEGMENT_LEN) {
103103
rest: (slice, SEG6_SEGMENT_LEN..)
104104
});
105105

106+
#[derive(Debug)]
107+
#[non_exhaustive]
108+
pub enum Seg6Error {
109+
InvalidSegmentList,
110+
}
111+
112+
impl std::fmt::Display for Seg6Error {
113+
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
114+
match self{
115+
Seg6Error::InvalidSegmentList => write!(f, "Invalid segment list. A segment list should contain at least one segment."),
116+
}
117+
}
118+
}
119+
120+
impl std::error::Error for Seg6Error {}
121+
106122
/// Netlink attributes for `RTA_ENCAP` with `RTA_ENCAP_TYPE` set to
107123
/// `LWTUNNEL_ENCAP_SEG6`.
108124
#[derive(Debug, PartialEq, Eq, Clone)]
@@ -115,6 +131,17 @@ pub struct Seg6Header {
115131
}
116132

117133
impl Seg6Header {
134+
pub fn new(
135+
mode: Seg6Mode,
136+
segments: Vec<Ipv6Addr>,
137+
) -> Result<Seg6Header, Seg6Error> {
138+
if !segments.is_empty() {
139+
Ok(Seg6Header { mode, segments })
140+
} else {
141+
Err(Seg6Error::InvalidSegmentList)
142+
}
143+
}
144+
118145
fn push_segments(buf: &mut [u8], mut segments: Vec<Ipv6Addr>) {
119146
if let Some(segment) = segments.pop() {
120147
let mut segment_buffer = Seg6SegmentBuffer::new(buf);

0 commit comments

Comments
 (0)