aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/clickhouse/src/Common/parseAddress.cpp
blob: 339c015ca9c9f2dc61e5a0d9fa253522cc5bc407 (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
#include <Common/parseAddress.h>
#include <Common/Exception.h>
#include <IO/ReadHelpers.h>
#include <base/find_symbols.h>


namespace DB
{

namespace ErrorCodes
{
    extern const int BAD_ARGUMENTS;
}

std::pair<std::string, UInt16> parseAddress(const std::string & str, UInt16 default_port)
{
    if (str.empty())
        throw Exception(ErrorCodes::BAD_ARGUMENTS, "Empty address passed to function parseAddress");

    const char * begin = str.data();
    const char * end = begin + str.size();
    const char * port = end; // NOLINT

    if (begin[0] == '[')
    {
        const char * closing_square_bracket = find_first_symbols<']'>(begin + 1, end);
        if (closing_square_bracket >= end)
            throw Exception(ErrorCodes::BAD_ARGUMENTS, "Illegal address passed to function parseAddress: "
                            "the address begins with opening square bracket, but no closing square bracket found");

        port = closing_square_bracket + 1;
    }
    else
        port = find_first_symbols<':'>(begin, end);

    if (port != end)
    {
        if (*port != ':')
            throw Exception(ErrorCodes::BAD_ARGUMENTS,
                "Illegal port prefix passed to function parseAddress: {}", port);

        ++port;

        UInt16 port_number;
        ReadBufferFromMemory port_buf(port, end - port);
        if (!tryReadText(port_number, port_buf) || !port_buf.eof())
        {
            throw Exception(ErrorCodes::BAD_ARGUMENTS,
                "Illegal port passed to function parseAddress: {}", port);
        }
        return { std::string(begin, port - 1), port_number };
    }
    else if (default_port)
    {
        return { str, default_port };
    }
    else
        throw Exception(ErrorCodes::BAD_ARGUMENTS,
                        "The address passed to function parseAddress doesn't contain port number and no 'default_port' was passed");
}

}