AK: Create MACAddress from string

Previously there was no way to create a MACAddress by passing a direct
address as a string. This will allow programs like the arp utility to
create a MACAddress instance by user-passed addresses.
This commit is contained in:
brapru 2021-07-24 20:15:14 -04:00 committed by Andreas Kling
parent 8313d35749
commit 7e40c17460
Notes: sideshowbarker 2024-07-18 08:21:27 +09:00
2 changed files with 62 additions and 0 deletions

View File

@ -57,6 +57,28 @@ public:
return String::formatted("{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}", m_data[0], m_data[1], m_data[2], m_data[3], m_data[4], m_data[5]);
}
static Optional<MACAddress> from_string(const StringView& string)
{
if (string.is_null())
return {};
const auto parts = string.split_view(":");
if (parts.size() != 6)
return {};
auto a = AK::StringUtils::convert_to_uint_from_hex(parts[0]).value_or(256);
auto b = AK::StringUtils::convert_to_uint_from_hex(parts[1]).value_or(256);
auto c = AK::StringUtils::convert_to_uint_from_hex(parts[2]).value_or(256);
auto d = AK::StringUtils::convert_to_uint_from_hex(parts[3]).value_or(256);
auto e = AK::StringUtils::convert_to_uint_from_hex(parts[4]).value_or(256);
auto f = AK::StringUtils::convert_to_uint_from_hex(parts[5]).value_or(256);
if (a > 255 || b > 255 || c > 255 || d > 255 || e > 255 || f > 255)
return {};
return MACAddress(a, b, c, d, e, f);
}
constexpr bool is_zero() const
{
return all_of(m_data.begin(), m_data.end(), [](const auto octet) { return octet == 0; });

View File

@ -82,3 +82,43 @@ TEST_CASE(should_string_format)
MACAddress sut(1, 2, 3, 4, 5, 6);
EXPECT_EQ("01:02:03:04:05:06", sut.to_string());
}
TEST_CASE(should_make_mac_address_from_string_numbers)
{
const auto sut = MACAddress::from_string("01:02:03:04:05:06");
EXPECT(sut.has_value());
EXPECT_EQ(1, sut.value()[0]);
EXPECT_EQ(2, sut.value()[1]);
EXPECT_EQ(3, sut.value()[2]);
EXPECT_EQ(4, sut.value()[3]);
EXPECT_EQ(5, sut.value()[4]);
EXPECT_EQ(6, sut.value()[5]);
}
TEST_CASE(should_make_mac_address_from_string_letters)
{
const auto sut = MACAddress::from_string("de:ad:be:ee:ee:ef");
EXPECT(sut.has_value());
EXPECT_EQ(u8 { 0xDE }, sut.value()[0]);
EXPECT_EQ(u8 { 0xAD }, sut.value()[1]);
EXPECT_EQ(u8 { 0xBE }, sut.value()[2]);
EXPECT_EQ(u8 { 0xEE }, sut.value()[3]);
EXPECT_EQ(u8 { 0xEE }, sut.value()[4]);
EXPECT_EQ(u8 { 0xEF }, sut.value()[5]);
}
TEST_CASE(should_make_empty_optional_from_bad_string)
{
const auto sut = MACAddress::from_string("bad string");
EXPECT(!sut.has_value());
}
TEST_CASE(should_make_empty_optional_from_out_of_range_values)
{
const auto sut = MACAddress::from_string("de:ad:be:ee:ee:fz");
EXPECT(!sut.has_value());
}