|
| 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