Coverage Report

Created: 2023-03-26 07:33

/src/gnutls/lib/extras/hex.c
Line
Count
Source (jump to first uncovered line)
1
/* CC0 license (public domain) - see LICENSE file for details */
2
#include <config.h>
3
#include <hex.h>
4
#include <stdio.h>
5
#include <stdlib.h>
6
7
static bool char_to_hex(unsigned char *val, char c)
8
0
{
9
0
  if (c >= '0' && c <= '9') {
10
0
    *val = c - '0';
11
0
    return true;
12
0
  }
13
0
  if (c >= 'a' && c <= 'f') {
14
0
    *val = c - 'a' + 10;
15
0
    return true;
16
0
  }
17
0
  if (c >= 'A' && c <= 'F') {
18
0
    *val = c - 'A' + 10;
19
0
    return true;
20
0
  }
21
0
  return false;
22
0
}
23
24
bool hex_decode(const char *str, size_t slen, void *buf, size_t bufsize)
25
0
{
26
0
  unsigned char v1, v2;
27
0
  unsigned char *p = buf;
28
29
0
  while (slen > 1) {
30
0
    if (!char_to_hex(&v1, str[0]) || !char_to_hex(&v2, str[1]))
31
0
      return false;
32
0
    if (!bufsize)
33
0
      return false;
34
0
    *(p++) = (v1 << 4) | v2;
35
0
    str += 2;
36
0
    slen -= 2;
37
0
    bufsize--;
38
0
  }
39
0
  return slen == 0 && bufsize == 0;
40
0
}
41
42
static const char HEX_CHARS[] = "0123456789abcdef";
43
44
bool hex_encode(const void *buf, size_t bufsize, char *dest, size_t destsize)
45
0
{
46
0
  size_t used = 0;
47
48
0
  if (destsize < 1)
49
0
    return false;
50
51
0
  while (used < bufsize) {
52
0
    unsigned int c = ((const unsigned char *)buf)[used];
53
0
    if (destsize < 3)
54
0
      return false;
55
0
    *(dest++) = HEX_CHARS[(c >> 4) & 0xF];
56
0
    *(dest++) = HEX_CHARS[c & 0xF];
57
0
    used++;
58
0
    destsize -= 2;
59
0
  }
60
0
  *dest = '\0';
61
62
0
  return used + 1;
63
0
}