Last active
February 5, 2024 16:20
-
-
Save mbernson/22cf86368602122d8c8c0a3af46f5572 to your computer and use it in GitHub Desktop.
MACAddress value type in Swift, for storing a MAC address
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// MACAddress.swift | |
// | |
// | |
// Created by Mathijs on 23/01/2024. | |
// | |
import Foundation | |
/// Model for a standard MAC (Media Access Control) address, which consists of 6 bytes | |
/// and can be represented as 6 hexadecimals separated by a colon. For example: `00:0C:6E:D2:11:E6`. | |
struct MACAddress: RawRepresentable, CustomStringConvertible, Hashable { | |
let rawValue: Data | |
init?(rawValue: Data) { | |
guard rawValue.count == 6 else { return nil } | |
self.rawValue = rawValue | |
} | |
init?(string: String) { | |
let components = string.split(separator: ":").map { String($0) } | |
guard components.count == 6 else { return nil } | |
var bytes = Data() | |
for component in components { | |
guard let byte = UInt8(component, radix: 16) else { return nil } | |
bytes.append(byte) | |
} | |
self.init(rawValue: bytes) | |
} | |
var description: String { | |
return rawValue.map { String(format: "%02X", $0) }.joined(separator: ":") | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// MACAddressTests.swift | |
// | |
// | |
// Created by Mathijs Bernson on 23/01/2024. | |
// | |
import XCTest | |
@testable import HeartEye | |
final class MACAddressTests: XCTestCase { | |
func testValidMACAddress() { | |
XCTAssertNotNil(MACAddress(string: "00:0C:6E:D2:11:E6")) | |
XCTAssertNotNil(MACAddress(string: "FF:FF:FF:FF:FF:FF")) | |
} | |
func testInvalidMACAddress() { | |
XCTAssertNil(MACAddress(string: "")) | |
XCTAssertNil(MACAddress(string: "00:0C:6E:D2:11:E6:FF"), "Too many bytes") | |
XCTAssertNil(MACAddress(string: "00:0C:6E:D2:11"), "Too few bytes") | |
XCTAssertNil(MACAddress(rawValue: Data([0x00, 0x1A, 0x2B, 0x3C, 0x4D, 0x5E, 0xFF])), "Too many bytes") | |
XCTAssertNil(MACAddress(rawValue: Data([0x00, 0x1A, 0x2B, 0x3C, 0x4D])), "Too few bytes") | |
} | |
func testByteOrdering() throws { | |
let macAddress = try XCTUnwrap(MACAddress(rawValue: Data([0x00, 0x1A, 0x2B, 0x3C, 0x4D, 0x5E]))) | |
let macAddressFromString = try XCTUnwrap(MACAddress(string: "00:1A:2B:3C:4D:5E")) | |
XCTAssertEqual(macAddress, macAddressFromString) | |
XCTAssertEqual(macAddress.description, "00:1A:2B:3C:4D:5E") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment