k-sone / critbitgo

crit-bit for golang and its applications (sorted map, IP routing table)
MIT License
45 stars 14 forks source link

Add Net.WalkPrefix API #10

Closed fujita closed 5 years ago

fujita commented 5 years ago

For interating routes that have a given prefix.

Signed-off-by: FUJITA Tomonori fujita.tomonori@gmail.com

k-sone commented 5 years ago

Thank you for sending a pull request.

I wrote a sample code and ran it.

package main

import (
        "fmt"
        "net"

        "github.com/k-sone/critbitgo"
)

func testWalkPrefix(trie *critbitgo.Net, n string) {
        f := func(n *net.IPNet, _ interface{}) bool {
                fmt.Println(n)
                return true
        }

        fmt.Printf("Case of %s\n", n)
        _, s, _ := net.ParseCIDR(n)
        trie.WalkPrefix(s, f)
}

func main() {
        trie := critbitgo.NewNet()
        trie.AddCIDR("192.168.0.0/24", nil)
        trie.AddCIDR("192.168.1.0/24", nil)
        trie.AddCIDR("192.168.2.0/24", nil)

        testWalkPrefix(trie, "192.168.0.0/24")
        testWalkPrefix(trie, "192.168.0.0/23")
}

And I got the output.

Case of 192.168.0.0/24
192.168.0.0/24
Case of 192.168.0.0/23
192.168.0.0/24
192.168.1.0/24
192.168.2.0/24

I think the last line is unnecessary, Is this your expected results?

fujita commented 5 years ago

Oops, I messed up. Fixed the handling of prefix length, non multiple of 8. Thanks for the quick response!

k-sone commented 5 years ago

Thanks!