/*
 * GTK VNC Widget, test utils
 *
 * Copyright (C) 2024  Red Hat, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.0 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA
 */

#include <config.h>

#include "testutils.h"

static guchar hex_to_val(guchar c)
{
    if (c >= '0' && c <= '9')
        return c - '0';
    else if (c >= 'a' && c <= 'f')
        return 10 + (c - 'a');
    else
        abort();
}

GBytes *bytes_from_hex(const gchar *hex)
{
    size_t size = strlen(hex) / 2;
    gchar *data = g_new0(char, size);
    size_t i;

    for (i = 0; i < size; i++) {
        data[i] = (hex_to_val(hex[i*2]) << 4) | hex_to_val(hex[(i*2)+1]);
    }

    return g_bytes_new_take(data, size);
}


char *bytes_to_hex(GBytes *val)
{
    static const char hex[] = "0123456789abcdef";
    gsize len;
    const char *data = g_bytes_get_data(val, &len);
    GString *str = g_string_sized_new((len*2)+1);
    gsize i;

    for (i = 0; i < len; i++) {
        str->str[i*2] = hex[(data[i] >> 4) & 0xf];
        str->str[(i*2)+1] = hex[data[i] & 0xf];
    }
    str->str[len*2] = '\0';

    return g_string_free_and_steal(str);
}

void test_assert_cmpbytes(const guint8 *want, size_t wantlen,
                          const guint8 *got, size_t gotlen)
{
    GBytes *gotb, *wantb;
    char *gotstr, *wantstr;
    gotb = g_bytes_new(got, gotlen);
    wantb = g_bytes_new(want, wantlen);

    gotstr = bytes_to_hex(gotb);
    wantstr = bytes_to_hex(wantb);

    g_assert_cmpstr(gotstr, ==, wantstr);

    g_free(wantstr);
    g_free(gotstr);
    g_bytes_unref(gotb);
    g_bytes_unref(wantb);
}
