Changeset 3e6bca8 in mainline for uspace/lib/inet/src/eth_addr.c


Ignore:
Timestamp:
2021-08-08T17:30:29Z (3 years ago)
Author:
Jiri Svoboda <jiri@…>
Branches:
master, serial, ticket/834-toolchain-update, topic/msim-upgrade, topic/simplify-dev-export
Children:
a7f7b9c3
Parents:
b4edc96
Message:

Represent Ethernet address as a number instead of an array

Carefully document the design since this breaks the principle of least
surprise. Also add unit tests.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • uspace/lib/inet/src/eth_addr.c

    rb4edc96 r3e6bca8  
    3737#include <inet/eth_addr.h>
    3838#include <mem.h>
     39#include <stdio.h>
    3940
    40 const eth_addr_t eth_addr_broadcast = {
    41         0xff, 0xff, 0xff, 0xff, 0xff, 0xff
    42 };
     41const eth_addr_t eth_addr_broadcast =
     42    ETH_ADDR_INITIALIZER(0xff, 0xff, 0xff, 0xff, 0xff, 0xff);
    4343
    4444void eth_addr_encode(eth_addr_t *addr, void *buf)
    4545{
    4646        uint8_t *bp = (uint8_t *)buf;
     47        uint64_t a;
     48        int i;
    4749
    48         memcpy(bp, &addr->b[0], ETH_ADDR_SIZE);
     50        a = addr->a;
     51
     52        for (i = 0; i < ETH_ADDR_SIZE; i++)
     53                bp[i] = (a >> (40 - 8 * i)) & 0xff;
    4954}
    5055
     
    5257{
    5358        const uint8_t *bp = (uint8_t *)buf;
     59        uint64_t a;
     60        int i;
    5461
    55         memcpy(&addr->b[0], bp, ETH_ADDR_SIZE);
     62        a = 0;
     63        for (i = 0; i < ETH_ADDR_SIZE; i++)
     64                a |= (uint64_t)bp[i] << (40 - 8 * i);
     65
     66        addr->a = a;
    5667}
    5768
     
    6273int eth_addr_compare(const eth_addr_t *a, const eth_addr_t *b)
    6374{
    64         return memcmp(a->b, b->b, ETH_ADDR_SIZE) == 0;
     75        if (a->a < b->a)
     76                return -1;
     77        else if (a->a == b->a)
     78                return 0;
     79        else
     80                return 1;
     81}
     82
     83void eth_addr_format(eth_addr_t *addr, eth_addr_str_t *saddr)
     84{
     85        int i;
     86
     87        snprintf(saddr->str, 3, "%02x",
     88            (unsigned)((addr->a >> 40) & 0xff));
     89        for (i = 1; i < ETH_ADDR_SIZE; i++) {
     90                snprintf(saddr->str + 2 + 3 * (i - 1), 4, ":%02x",
     91                    (unsigned)((addr->a >> (40 - i * 8)) & 0xff));
     92        }
    6593}
    6694
Note: See TracChangeset for help on using the changeset viewer.