Files
ec3/src/misc.c

105 lines
1.7 KiB
C
Raw Normal View History

#include "misc.h"
#include <blue/core/endian.h>
#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static enum ec3_status identifier_from_int_string(
const char *s,
uint64_t *out,
int base)
{
/* skip leading '0x' */
s += 2;
char *ep = NULL;
uint64_t v = strtoull(s, &ep, base);
if (!ep || *ep != '\0') {
return EC3_ERR_INVALID_VALUE;
}
*out = v;
return EC3_SUCCESS;
}
static bool is_base10_string(const char *s)
{
for (unsigned int i = 0; s[i]; i++) {
if (!isdigit(s[i])) {
return false;
}
}
return true;
}
enum ec3_status ec3_identifier_from_string(const char *s, uint64_t *out)
{
if (s[0] == '0' && s[1] == 'x') {
return identifier_from_int_string(s, out, 16);
}
if (is_base10_string(s)) {
return identifier_from_int_string(s, out, 10);
}
b_i64 v = {0};
for (unsigned int i = 0; s[i]; i++) {
if (i > sizeof *out) {
return EC3_ERR_INVALID_VALUE;
}
v.i_bytes[i] = s[i];
}
*out = b_i64_btoh(v);
return EC3_SUCCESS;
}
enum ec3_status ec3_identifier_to_string(uint64_t id, char *out, size_t max)
{
if (id == 0) {
snprintf(out, max, "%016llx", id);
return EC3_SUCCESS;
}
bool is_ascii = true;
bool zero_only = false;
b_i64 v = b_i64_htob(id);
for (unsigned int i = 0; i < sizeof v; i++) {
int c = v.i_bytes[i];
if (c != 0 && zero_only) {
is_ascii = false;
}
if (c == 0) {
zero_only = true;
continue;
}
if (c < 32 || c > 126) {
is_ascii = false;
}
}
if (is_ascii) {
char str[9];
memcpy(str, v.i_bytes, sizeof v);
str[8] = 0;
strncpy(out, str, max - 1);
out[max - 1] = 0;
} else {
snprintf(out, max, "%016llx", id);
}
return EC3_SUCCESS;
}