damus

nostr ios client
git clone git://jb55.com/damus
Log | Files | Refs | README | LICENSE

hex.h (2110B)


      1 /* CC0 (Public domain) - see LICENSE file for details */
      2 #ifndef CCAN_HEX_H
      3 #define CCAN_HEX_H
      4 #include "config.h"
      5 #include <stdbool.h>
      6 #include <stdlib.h>
      7 
      8 /**
      9  * hex_decode - Unpack a hex string.
     10  * @str: the hexadecimal string
     11  * @slen: the length of @str
     12  * @buf: the buffer to write the data into
     13  * @bufsize: the length of
     14  *
     15  * Returns false if there are any characters which aren't 0-9, a-f or A-F,
     16  * of the string wasn't the right length for @bufsize.
     17  *
     18  * Example:
     19  *    unsigned char data[20];
     20  *
     21  *    if (!hex_decode(argv[1], strlen(argv[1]), data, 20))
     22  *        printf("String is malformed!\n");
     23  */
     24 bool hex_decode(const char *str, size_t slen, void *buf, size_t bufsize);
     25 
     26 /**
     27  * hex_encode - Create a nul-terminated hex string
     28  * @buf: the buffer to read the data from
     29  * @bufsize: the length of buf
     30  * @dest: the string to fill
     31  * @destsize: the max size of the string
     32  *
     33  * Returns true if the string, including terminator, fit in @destsize;
     34  *
     35  * Example:
     36  *    unsigned char buf[] = { 0x1F, 0x2F };
     37  *    char str[5];
     38  *
     39  *    if (!hex_encode(buf, sizeof(buf), str, sizeof(str)))
     40  *        abort();
     41  */
     42 bool hex_encode(const void *buf, size_t bufsize, char *dest, size_t destsize);
     43 
     44 /**
     45  * hex_str_size - Calculate how big a nul-terminated hex string is
     46  * @bytes: bytes of data to represent
     47  *
     48  * Example:
     49  *    unsigned char buf[] = { 0x1F, 0x2F };
     50  *    char str[hex_str_size(sizeof(buf))];
     51  *
     52  *    hex_encode(buf, sizeof(buf), str, sizeof(str));
     53  */
     54 static inline size_t hex_str_size(size_t bytes)
     55 {
     56     return 2 * bytes + 1;
     57 }
     58 
     59 /**
     60  * hex_data_size - Calculate how many bytes of data in a hex string
     61  * @strlen: the length of the string (with or without NUL)
     62  *
     63  * Example:
     64  *    const char str[] = "1F2F";
     65  *    unsigned char buf[hex_data_size(sizeof(str))];
     66  *
     67  *    hex_decode(str, strlen(str), buf, sizeof(buf));
     68  */
     69 static inline size_t hex_data_size(size_t strlen)
     70 {
     71     return strlen / 2;
     72 }
     73 
     74 static inline char hexchar(unsigned int val)
     75 {
     76     if (val < 10)
     77         return '0' + val;
     78     if (val < 16)
     79         return 'a' + val - 10;
     80     abort();
     81 }
     82 
     83 
     84 #endif /* CCAN_HEX_H */