-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathipv4int.cpp
More file actions
78 lines (64 loc) · 2.37 KB
/
Copy pathipv4int.cpp
File metadata and controls
78 lines (64 loc) · 2.37 KB
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
#include "ipv4int.h"
#include <QRegularExpression>
#include "ipv4.h"
IpV4Int::IpV4Int(const QString &value) : m_text(value) {}
bool IpV4Int::is_valid() const
{
bool ok = false;
const unsigned long val = m_text.toULong(&ok);
return ok && val <= max_value && !m_text.contains(QRegularExpression("\\D")) &&
m_text != "" &&
(!m_text.startsWith('0') || m_text == "0");
}
bool IpV4Int::is_invalid() const
{
bool ok = false;
const unsigned long val = m_text.toULong(&ok);
return ok && !m_text.contains(QRegularExpression("\\D")) &&
(val > max_value || (m_text.startsWith('0') && m_text != "0"));
}
bool IpV4Int::can_insert_first_separtor_to(const int inserted_index) const
{
if (!is_valid())
return false;
static const int octet_max_value_len = QString::number(IpV4::Octet::max_value).length();
static const int max_len_of_text_after_first_dot = (IpV4::norm_octets_count -1) * octet_max_value_len;
const int text_len_after_first_dot = m_text.length() - inserted_index;
const QString text_before_first_dot = m_text.left(inserted_index);
const ulong value_before_first_dot = text_before_first_dot.toULong();
return
text_len_after_first_dot <= max_len_of_text_after_first_dot
&&
value_before_first_dot <= IpV4::Octet::max_value;
}
QString IpV4Int::insert_separators(const int first_separator_index) const
{
if (m_text.count(IpV4::octet_separator) >= IpV4::norm_separators_count)
return m_text;
QString result = m_text;
result.insert(first_separator_index, IpV4::octet_separator);
auto it = result.begin() + first_separator_index +1;
while (result.count(IpV4::octet_separator) < IpV4::norm_separators_count)
{
int octet_val = 0;
while (it != result.end())
{
const int growed_octet_val = (octet_val * 10) + (it->toLatin1() - '0');
if (growed_octet_val > IpV4::Octet::max_value) break;
it++;
octet_val = growed_octet_val;
}
if (it == result.end())
{
result.append(IpV4::octet_separator);
it = result.end();
}
else
{
const auto it_index = std::distance(result.begin(), it);
result.insert(it_index, IpV4::octet_separator);
it = result.begin() + it_index +1;
}
}
return result;
}