File: util.py

package info (click to toggle)
python-aiomeasures 0.5.14-6
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 672 kB
  • sloc: python: 5,173; makefile: 159
file content (61 lines) | stat: -rw-r--r-- 1,467 bytes parent folder | download | duplicates (3)
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
__all__ = ['parse_addr']


class Address(tuple):
    """Defines what is a net address.
    """
    def __new__(cls, proto, host, port):
        return super().__new__(cls, (host, port))

    def __init__(self, proto, host, port):
        self.proto = proto
        self.host = host
        self.port = port

    def __hash__(self):
        return id((self.proto, self.host, self.port))

    def __eq__(self, other):
        return other == (self.proto, self.host, self.port)

    def __str__(self):
        return '%s://%s:%s' % (self.proto, self.host, self.port)


def parse_addr(addr, *, proto=None, host=None):
    """Parses an address;

    Returns:
        Address: the parsed address
    """
    port = None

    if isinstance(addr, Address):
        return addr

    elif isinstance(addr, str):
        if addr.startswith('udp://'):
            proto, addr = 'udp', addr[6:]
        elif addr.startswith('tcp://'):
            proto, addr = 'tcp', addr[6:]
        elif addr.startswith('unix://'):
            proto, addr = 'unix', addr[7:]
        a, _, b = addr.partition(':')
        host = a or host
        port = b or port

    elif isinstance(addr, (tuple, list)):
        # list is not good
        a, b = addr
        host = a or host
        port = b or port

    elif isinstance(addr, int):
        port = addr

    else:
        raise ValueError('bad value')

    if port is not None:
        port = int(port)
    return Address(proto, host, port)