libsood

Zig library for Roon Core discovery message, with C-compatible API and WebAssembly.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
  49. 49
  50. 50
  51. 51
  52. 52
  53. 53
  54. 54
  55. 55
// Copyright 2025 Shota FUJI
//
// Licensed under the Zero-Clause BSD License or the Apache License, Version 2.0, at your option.
// You may not use, copy, modify, or distribute this file except according to those terms. You can
// find a copy of the Zero-Clause BSD License at LICENSES/0BSD.txt, and a copy of the Apache License,
// Version 2.0 at LICENSES/Apache-2.0.txt. You may also obtain a copy of the Apache License, Version
// 2.0 at <https://www.apache.org/licenses/LICENSE-2.0>
//
// SPDX-License-Identifier: 0BSD OR Apache-2.0

//! This module contains cross-platform, pure Zig functions for computing a broadcast address in
//! IPv4 subnet.

const std = @import("std");

/// Helper function to get a broadcast address for a subnet.
/// If your platform have this functionality, use that instead.
pub inline fn getBroadcastAddressU32(ipv4_addr: u32, netmask: u32) u32 {
    return ipv4_addr | (~netmask);
}

test getBroadcastAddressU32 {
    // Addresses are borrowed from here: <https://en.wikipedia.org/wiki/Broadcast_address>
    try std.testing.expectEqual(
        0xac1fffff,
        getBroadcastAddressU32(0xac100000, 0xfff00000),
    );
}

/// Helper function to get a broadcast address for a subnet.
/// This variant operates on an array.
/// If your platform have this functionality, use that instead.
pub inline fn getBroadcastAddress(ipv4_addr: *const [4]u8, netmask: *const [4]u8) [4]u8 {
    var result: [4]u8 = undefined;

    std.mem.writeInt(u32, &result, getBroadcastAddressU32(
        std.mem.readInt(u32, ipv4_addr, .big),
        std.mem.readInt(u32, netmask, .big),
    ), .big);

    return result;
}

test getBroadcastAddress {
    try std.testing.expectEqualDeep(
        &[4]u8{ 192, 168, 1, 255 },
        &getBroadcastAddress(&.{ 192, 168, 1, 1 }, &.{ 255, 255, 255, 0 }),
    );

    // Addresses are borrowed from here: <https://en.wikipedia.org/wiki/Broadcast_address>
    try std.testing.expectEqualDeep(
        &[4]u8{ 172, 31, 255, 255 },
        &getBroadcastAddress(&.{ 172, 16, 0, 0 }, &.{ 255, 240, 0, 0 }),
    );
}