/*
 *      dnsutl - utilities to make DNS easier to configure
 *      Copyright (C) 1999, 2006, 2007 Peter Miller
 *
 *      This program is free software; you can redistribute it and/or modify
 *      it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation; either version 3 of the License, or
 *      (at your option) any later version.
 *
 *      This program is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *      GNU General Public License for more details.
 *
 *      You should have received a copy of the GNU General Public License
 *      along with this program. If not, see
 *      <http://www.gnu.org/licenses/>.
 */

#include <ac/ctype.h>
#include <ac/string.h>

#include <mac.h>
#include <str.h>


static int
hex(int c)
{
    static char     digit[] = "0123456789ABCDEFabcdef";
    static int      value[] =
    {
        0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
        10, 11, 12, 13, 14, 15,
        10, 11, 12, 13, 14, 15,
    };
    char            *cp;

    cp = strchr(digit, c);
    if (!cp)
    {
        /* should not happen */
        return 0;
    }
    return value[cp - digit];
}


string_ty *
mac_cannonicalize(string_ty * s)
{
    size_t          nbytes;
    unsigned char   buffer[6 + 1];      /* must be more than 6 */
    const char      *cp;

    cp = s->str_text;
    nbytes = 0;
    while (nbytes < SIZEOF(buffer))
    {
        if (!isxdigit((unsigned char)cp[0]))
            return 0;
        if (isxdigit((unsigned char)cp[1]))
        {
            buffer[nbytes++] = (hex(cp[0]) << 4) | hex(cp[1]);
            cp += 2;
        }
        else
            buffer[nbytes++] = hex(*cp++);
        if (*cp != ':')
            break;
        ++cp;
    }
    if (*cp != 0 || nbytes != 6)
        return 0;
    return
        str_format
        (
            "%x:%x:%x:%x:%x:%x",
            buffer[0],
            buffer[1],
            buffer[2],
            buffer[3],
            buffer[4],
            buffer[5]
        );
}


syntax highlighted by Code2HTML, v. 0.9.1