David K. Bainbridge | 8bc905c | 2016-05-31 14:07:10 -0700 | [diff] [blame^] | 1 | package main |
| 2 | |
| 3 | type 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 | |
| 13 | type MemoryStorage struct { |
| 14 | allocated map[string]IPv4 |
| 15 | available []IPv4 |
| 16 | readIdx, writeIdx, size uint |
| 17 | } |
| 18 | |
| 19 | func (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 | |
| 39 | func (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 | |
| 47 | func (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 | |
| 55 | func (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 | |
| 64 | func (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 | |
| 73 | func (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 | |
| 79 | func (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 | } |