]> git.ipfire.org Git - location/libloc.git/commitdiff
network: Move a couple of helper functions into headers
authorMichael Tremer <michael.tremer@ipfire.org>
Sat, 5 Mar 2022 16:00:43 +0000 (16:00 +0000)
committerMichael Tremer <michael.tremer@ipfire.org>
Sat, 5 Mar 2022 16:00:43 +0000 (16:00 +0000)
Signed-off-by: Michael Tremer <michael.tremer@ipfire.org>
src/libloc/private.h
src/network.c

index de4b9aec64015e4a5dd1c329b3b034f8342ed8d1..675e14b774ff081d87b6a2f113f34b77ec25186a 100644 (file)
@@ -78,6 +78,44 @@ static inline void in6_addr_set_bit(struct in6_addr* address, unsigned int i, un
        address->s6_addr[i / 8] ^= (-val ^ address->s6_addr[i / 8]) & (1 << (7 - (i % 8)));
 }
 
+static inline struct in6_addr loc_prefix_to_bitmask(const unsigned int prefix) {
+       struct in6_addr bitmask;
+
+       for (unsigned int i = 0; i < 16; i++)
+               bitmask.s6_addr[i] = 0;
+
+       for (int i = prefix, j = 0; i > 0; i -= 8, j++) {
+               if (i >= 8)
+                       bitmask.s6_addr[j] = 0xff;
+               else
+                       bitmask.s6_addr[j] = 0xff << (8 - i);
+       }
+
+       return bitmask;
+}
+
+static inline struct in6_addr loc_address_and(
+               const struct in6_addr* address, const struct in6_addr* bitmask) {
+       struct in6_addr a;
+
+       // Perform bitwise AND
+       for (unsigned int i = 0; i < 4; i++)
+               a.s6_addr32[i] = address->s6_addr32[i] & bitmask->s6_addr32[i];
+
+       return a;
+}
+
+static inline struct in6_addr loc_address_or(
+               const struct in6_addr* address, const struct in6_addr* bitmask) {
+       struct in6_addr a;
+
+       // Perform bitwise OR
+       for (unsigned int i = 0; i < 4; i++)
+               a.s6_addr32[i] = address->s6_addr32[i] | ~bitmask->s6_addr32[i];
+
+       return a;
+}
+
 static inline void hexdump(struct loc_ctx* ctx, const void* addr, size_t len) {
        char buffer_hex[16 * 3 + 6];
        char buffer_ascii[17];
index 4b2b279c76e357daf36295b7fbb2c799491739c7..67dbe3395b56b347dcbc0464a263ec07e558ecf5 100644 (file)
@@ -141,11 +141,11 @@ LOC_EXPORT int loc_network_new(struct loc_ctx* ctx, struct loc_network** network
        n->prefix = prefix;
 
        // Convert the prefix into a bitmask
-       struct in6_addr bitmask = prefix_to_bitmask(n->prefix);
+       struct in6_addr bitmask = loc_prefix_to_bitmask(n->prefix);
 
        // Store the first and last address in the network
-       n->first_address = make_first_address(address, &bitmask);
-       n->last_address = make_last_address(&n->first_address, &bitmask);
+       n->first_address = loc_address_and(address, &bitmask);
+       n->last_address  = loc_address_or(&n->first_address, &bitmask);
 
        // Set family
        n->family = loc_address_family(&n->first_address);