summaryrefslogtreecommitdiff
path: root/rfc1982_serial_number.py
blob: bb9988c8df6992a1352d3eeea4c095bcf5a10c8d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#!/usr/bin/env python3

"""Implementation of RFC 1982 Serial Number Arithmetic.

Run as a program, this takes start and finish serial values and tells
you what intermediate steps (if any) are needed to make the specified
change.

Used as a module, this implements the Serial class and an iterator
which returns the intermediate steps (if any) needed between two
Serial values.
"""

class Serial:
    """Implementation of RFC 1982 Serial Number Arithmetic.

    Per the RFC, only two operations are defined on Serial objects:
    addition and comparision, both within a restricted range specified
    by the RFC.

    The default modulus is 2**32, you can change this by subclassing
    the Serial class and overriding the class's modulus variable.  The
    modulus must be a power of two.

    See RFC 1982 for discussion of the ways in which Serial numbers do
    not work like normal integers.  In particular, note that there's a
    corner case in which one can have a pair of Serial numbers I1 and
    I2 where I1 is neither equal to, less than, nor greater than I2.
    This is deliberate and is not a bug in the code.  See the RFC.

    """

    modulus = 2 ** 32

    def __init__(self, val):
        self._val = int(val)
        if self._val < 0 or self._val >= self.modulus:
            raise ValueError

    def __add__(self, val):
        val = int(val)
        if val < 0 or val > (self.modulus - 1) >> 1:
            raise ValueError
        return type(self)((self._val + val) & (self.modulus - 1))

    def __le__(self, other):
        return (self.modulus - int(self) + int(other)) & (self.modulus >> 1) == 0

    def __ge__(self, other):
        return (self.modulus + int(self) - int(other)) & (self.modulus >> 1) == 0

    def __eq__(self, other):
        return int(self) == int(other)

    def __ne__(self, other):
        return int(self) != int(other)

    def __lt__(self, other):
        return self != other and self <= other

    def __gt__(self, other):
        return self != other and self >= other

    def __int__(self):
        return self._val

    def __str__(self):
        return f"{int(self):{len(str(self.modulus))}d}"

def find_intermediate(start, finish):
    """
    Find the sequence of intermediate values (if any) needed to step
    from start to finish
    """

    while not (start < finish): # sic: serial numbers are not (quite) integers
        start += ((Serial.modulus >> 1) - 1)
        yield start

def main():
    from argparse import ArgumentParser

    ap = ArgumentParser(description = __doc__)
    ap.add_argument("start", type = Serial)
    ap.add_argument("finish", type = Serial)
    args = ap.parse_args()

    print(f"Start at {args.start!s}")

    if args.start < args.finish:
        print("No step needed")
    else:
        for wrap in find_intermediate(args.start, args.finish):
            print(f"Step via {wrap!s}")

    print(f"End at   {args.finish!s}")

if __name__ == "__main__":
    main()