blob: 26be353a53224212905c29eb690c3b97141781f8 [file] [log] [blame]
David K. Bainbridge8bc905c2016-05-31 14:07:10 -07001package main
2
3type Storage interface {
4 Init(start string, count uint) error
5 Get(mac string) (string, error)
6 GetAll() map[string]string
7 Put(mac, ip string) error
8 Remove(mac string) (string, error)
9 Dequeue() (string, error)
10 Enqueue(ip string) error
11}
12
13type MemoryStorage struct {
14 allocated map[string]IPv4
15 available []IPv4
16 readIdx, writeIdx, size uint
17}
18
19func (s *MemoryStorage) Init(start string, count uint) error {
20 ip, err := ParseIP(start)
21 if err != nil {
22 return err
23 }
24 s.readIdx = 0
25 s.writeIdx = 0
26 s.size = count
27 s.allocated = make(map[string]IPv4)
28 s.available = make([]IPv4, count)
29 for i := uint(0); i < count; i += 1 {
30 s.available[i] = ip
31 ip, err = ip.Next()
32 if err != nil {
33 return err
34 }
35 }
36 return nil
37}
38
39func (s *MemoryStorage) Get(mac string) (string, error) {
40 ip, ok := s.allocated[mac]
41 if !ok {
42 return "", nil
43 }
44 return ip.String(), nil
45}
46
47func (s *MemoryStorage) GetAll() map[string]string {
48 all := make(map[string]string)
49 for k, v := range s.allocated {
50 all[k] = v.String()
51 }
52 return all
53}
54
55func (s *MemoryStorage) Put(mac, ip string) error {
56 data, err := ParseIP(ip)
57 if err != nil {
58 return err
59 }
60 s.allocated[mac] = data
61 return nil
62}
63
64func (s *MemoryStorage) Remove(mac string) (string, error) {
65 ip, ok := s.allocated[mac]
66 if !ok {
67 return "", nil
68 }
69 delete(s.allocated, mac)
70 return ip.String(), nil
71}
72
73func (s *MemoryStorage) Dequeue() (string, error) {
74 ip := s.available[s.readIdx]
75 s.readIdx = (s.readIdx + 1) % s.size
76 return ip.String(), nil
77}
78
79func (s *MemoryStorage) Enqueue(ip string) error {
80 data, err := ParseIP(ip)
81 if err != nil {
82 return err
83 }
84 s.available[s.writeIdx] = data
85 s.writeIdx = (s.writeIdx + 1) % s.size
86 return nil
87}