12 "github.com/edsrzf/mmap-go"
15 // The packed format is an 8 byte integer of the number of ranges. Then 20
16 // bytes per range, consisting of 4 byte packed IP being the lower bound IP of
17 // the range, then 4 bytes of the upper, inclusive bound, 8 bytes for the
18 // offset of the description from the end of the packed ranges, and 4 bytes
19 // for the length of the description. After these packed ranges, are the
20 // concatenated descriptions.
23 packedRangesOffset = 8
27 func (ipl *IPList) WritePacked(w io.Writer) (err error) {
28 descOffsets := make(map[string]int64, len(ipl.ranges))
29 descs := make([]string, 0, len(ipl.ranges))
31 // This is a little monadic, no?
32 write := func(b []byte, expectedLen int) {
46 binary.LittleEndian.PutUint64(b[:], uint64(len(ipl.ranges)))
48 for _, r := range ipl.ranges {
49 write(r.First.To16(), 16)
50 write(r.Last.To16(), 16)
51 descOff, ok := descOffsets[r.Description]
54 descOffsets[r.Description] = descOff
55 descs = append(descs, r.Description)
56 nextOffset += int64(len(r.Description))
58 binary.LittleEndian.PutUint64(b[:], uint64(descOff))
60 binary.LittleEndian.PutUint32(b[:], uint32(len(r.Description)))
63 for _, d := range descs {
64 write([]byte(d), len(d))
69 func NewFromPacked(b []byte) PackedIPList {
70 ret := PackedIPList(b)
71 minLen := packedRangesOffset + ret.len()*packedRangeLen
73 panic(fmt.Sprintf("packed len %d < %d", len(b), minLen))
78 type PackedIPList []byte
80 var _ Ranger = PackedIPList{}
82 func (pil PackedIPList) len() int {
83 return int(binary.LittleEndian.Uint64(pil[:8]))
86 func (pil PackedIPList) NumRanges() int {
90 func (pil PackedIPList) getFirst(i int) net.IP {
91 off := packedRangesOffset + packedRangeLen*i
92 return net.IP(pil[off : off+16])
95 func (pil PackedIPList) getRange(i int) (ret Range) {
96 rOff := packedRangesOffset + packedRangeLen*i
97 last := pil[rOff+16 : rOff+32]
98 descOff := int(binary.LittleEndian.Uint64(pil[rOff+32:]))
99 descLen := int(binary.LittleEndian.Uint32(pil[rOff+40:]))
100 descOff += packedRangesOffset + packedRangeLen*pil.len()
104 string(pil[descOff : descOff+descLen]),
109 func (pil PackedIPList) Lookup(ip net.IP) (r Range, ok bool) {
114 return lookup(pil.getFirst, pil.getRange, pil.len(), ip16)
117 type closerFunc func() error
119 func (me closerFunc) Close() error {
123 func MMapPackedFile(filename string) (
130 f, err := os.Open(filename)
135 mm, err := mmap.Map(f, mmap.RDONLY, 0)
142 }{NewFromPacked(mm), closerFunc(mm.Unmap)}