Serenity Operating System
1/*
2 * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright notice, this
9 * list of conditions and the following disclaimer.
10 *
11 * 2. Redistributions in binary form must reproduce the above copyright notice,
12 * this list of conditions and the following disclaimer in the documentation
13 * and/or other materials provided with the distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
16 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
18 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
19 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
21 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
22 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
23 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 */
26
27#pragma once
28
29#include <AK/Assertions.h>
30#include <AK/String.h>
31#include <AK/Types.h>
32#include <LibBareMetal/StdLib.h>
33
34class [[gnu::packed]] MACAddress
35{
36public:
37 MACAddress() {}
38 MACAddress(const u8 data[6])
39 {
40 memcpy(m_data, data, 6);
41 }
42 MACAddress(u8 a, u8 b, u8 c, u8 d, u8 e, u8 f)
43 {
44 m_data[0] = a;
45 m_data[1] = b;
46 m_data[2] = c;
47 m_data[3] = d;
48 m_data[4] = e;
49 m_data[5] = f;
50 }
51 ~MACAddress() {}
52
53 u8 operator[](int i) const
54 {
55 ASSERT(i >= 0 && i < 6);
56 return m_data[i];
57 }
58
59 bool operator==(const MACAddress& other) const
60 {
61 return !memcmp(m_data, other.m_data, sizeof(m_data));
62 }
63
64 String to_string() const
65 {
66 return String::format("%02x:%02x:%02x:%02x:%02x:%02x", m_data[0], m_data[1], m_data[2], m_data[3], m_data[4], m_data[5]);
67 }
68
69 bool is_zero() const
70 {
71 return m_data[0] == 0 && m_data[1] == 0 && m_data[2] == 0 && m_data[3] == 0 && m_data[4] == 0 && m_data[5] == 0;
72 }
73
74private:
75 u8 m_data[6];
76};
77
78static_assert(sizeof(MACAddress) == 6);
79
80namespace AK {
81
82template<>
83struct Traits<MACAddress> : public GenericTraits<MACAddress> {
84 static unsigned hash(const MACAddress& address) { return string_hash((const char*)&address, sizeof(address)); }
85};
86
87}