jsommers / pytricia

A library for fast IP address lookup in Python.
GNU Lesser General Public License v3.0
216 stars 22 forks source link

Add prefix raw int support #33

Closed j0k2r closed 1 year ago

j0k2r commented 4 years ago

This PR add the raw long prefix representation for pytricia input/output.

The idea is to choose the prefix representation to work with for input/output on pytricia initialization and prevent unnecessary conversions.

pyt = pytricia.PyTricia(32, socket.AF_INET, RAW_OUTPUT)

The RAW_OUTPUT is an integer that represent:

The ideal would be to use a Python namedtuple and initialize pytricia with something like:

pyt = pytricia.PyTricia(32, socket.AF_INET, pytricia.RAW_BYTES)

but I dont know how to do that with the c-api.

Usage example:

# Initialize pytricia (working with raw integer)
pyt = pytricia.PyTricia(32, socket.AF_INET, 2)

pyt.insert((167837696, 16), 'b')   # 10.1.0.0/16
pyt.insert((167772160, 8), 'a')  # 10.0.0.0/8
pyt.insert((167772416, 24), 'c')  #10.0.1.0/24

# Iterate and print key tuple
for prefix, prefix_len in pyt:
    print((prefix, prefix_len))

PS: I kept the retro-compatibility with the commit #4ba88f6, that use RAW_OUTPUT as a boolean.