Skip to content

Commit dafde3f

Browse files
author
Conrad Lukawski
committed
Handle CIDR ingestion and create IpList struct/impl for allocation
1 parent b922335 commit dafde3f

3 files changed

Lines changed: 84 additions & 0 deletions

File tree

Cargo.lock

Lines changed: 23 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ parking_lot = "0.10"
1717
slog = "2.5"
1818
slog-term = "2.5"
1919
json = "0.12"
20+
cidr = "0.1.1"
2021

2122
[target.'cfg(not(target_arch="arm"))'.dependencies]
2223
ring = "0.16"

src/device/ip_list.rs

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
extern crate cidr;
2+
3+
use cidr::{Cidr, Ipv4Cidr};
4+
use std::cell::{Cell, RefCell};
5+
use std::collections::HashMap;
6+
use std::net::Ipv4Addr;
7+
use std::vec::Vec;
8+
9+
struct IpList {
10+
pub list: RefCell<Vec<[u8; 5]>>,
11+
pub allocated: Cell<HashMap<[u8; 5], bool>>,
12+
index: Cell<usize>,
13+
}
14+
15+
impl IpList {
16+
pub fn new(cidr: [u8; 5]) -> Result<IpList, Error> {
17+
let subnet: u8 = cidr[4];
18+
// It can also be created from string representations.
19+
let net = Ipv4Cidr::new(Ipv4Addr::new(cidr[0], cidr[1], cidr[2], cidr[3]), subnet)
20+
.expect("Expected valid ip range");
21+
22+
let mut ip_list: Vec<[u8; 5]> = Vec::new();
23+
for ip in net.iter() {
24+
let octets = ip.octets();
25+
if octets[3] == 255 || octets[3] == 0 {
26+
continue;
27+
}
28+
let full_ip: [u8; 5] = [octets[0], octets[1], octets[2], octets[3], subnet];
29+
ip_list.push(full_ip);
30+
}
31+
}
32+
33+
pub fn get_ip(&mut self) -> Option<[u8; 5]> {
34+
let mut current = self.index.get();
35+
let list = self.list.get_mut();
36+
let mut ip_avail = false;
37+
let allocated = self.allocated.get_mut();
38+
let mut counter: usize = 0;
39+
40+
while !ip_avail {
41+
current = self.index.get();
42+
if counter == list.len() {
43+
return None;
44+
}
45+
46+
self.index.set(current + 1);
47+
let ip = list[self.index.get()];
48+
ip_avail = !allocated.contains_key(&ip);
49+
counter += 1;
50+
}
51+
52+
return Some(list[self.index.get()]);
53+
}
54+
55+
pub fn allocate_ip(&mut self, ip: [u8; 5]) {
56+
let allocated = self.allocated.get_mut();
57+
58+
allocated.insert(ip, true);
59+
}
60+
}

0 commit comments

Comments
 (0)