1
0
Fork 0
mirror of https://github.com/tailix/libkernaux.git synced 2024-10-30 11:54:01 -04:00
libkernaux/src/units.c

141 lines
2.8 KiB
C
Raw Normal View History

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
2021-12-15 05:45:40 -05:00
#include <kernaux/itoa.h>
#include <kernaux/libc.h>
2021-12-14 15:44:09 -05:00
#include <kernaux/units.h>
#define TMP_BUFFER_SIZE (64)
bool kernaux_units_human_raw(
const size_t value,
const enum KernAux_Unit unit,
char *const buffer,
const size_t buffer_size
) {
char tmp_buffer[TMP_BUFFER_SIZE];
char *tmp = tmp_buffer;
kernaux_itoa(value, tmp, 10);
while (*tmp != '\0') ++tmp;
*(tmp++) = ' ';
switch (unit) {
case KERNAUX_UNIT_BIT:
*(tmp++) = 'b';
*(tmp++) = 'i';
*(tmp++) = 't';
break;
case KERNAUX_UNIT_BYTE:
*(tmp++) = 'B';
*(tmp++) = 'y';
*(tmp++) = 't';
*(tmp++) = 'e';
break;
}
*(tmp++) = '\0';
2021-12-15 05:45:40 -05:00
const size_t tmp_size = strlen(tmp_buffer) + 1;
if (tmp_size > buffer_size) return false;
2021-12-15 05:45:40 -05:00
strcpy(buffer, tmp_buffer);
return true;
}
bool kernaux_units_human_dec(
const size_t value,
const enum KernAux_Unit unit,
const enum KernAux_UnitPrefixDec prefix,
char *const buffer,
const size_t buffer_size
) {
char tmp_buffer[TMP_BUFFER_SIZE];
char *tmp = tmp_buffer;
kernaux_itoa(value, tmp, 10);
while (*tmp != '\0') ++tmp;
*(tmp++) = ' ';
switch (prefix) {
case KERNAUX_UNITPFX_KILO:
*(tmp++) = 'k';
break;
case KERNAUX_UNITPFX_MEGA:
*(tmp++) = 'M';
break;
case KERNAUX_UNITPFX_GIGA:
*(tmp++) = 'G';
break;
}
switch (unit) {
case KERNAUX_UNIT_BIT:
*(tmp++) = 'b';
*(tmp++) = 'i';
*(tmp++) = 't';
break;
case KERNAUX_UNIT_BYTE:
*(tmp++) = 'B';
break;
}
*(tmp++) = '\0';
2021-12-15 05:45:40 -05:00
const size_t tmp_size = strlen(tmp_buffer) + 1;
if (tmp_size > buffer_size) return false;
2021-12-15 05:45:40 -05:00
strcpy(buffer, tmp_buffer);
return true;
}
bool kernaux_units_human_bin(
const size_t value,
const enum KernAux_Unit unit,
const enum KernAux_UnitPrefixBin prefix,
char *const buffer,
const size_t buffer_size
) {
char tmp_buffer[TMP_BUFFER_SIZE];
char *tmp = tmp_buffer;
kernaux_itoa(value, tmp, 10);
while (*tmp != '\0') ++tmp;
*(tmp++) = ' ';
switch (prefix) {
case KERNAUX_UNITPFX_KIBI:
*(tmp++) = 'K';
*(tmp++) = 'i';
break;
case KERNAUX_UNITPFX_MEBI:
*(tmp++) = 'M';
*(tmp++) = 'i';
break;
case KERNAUX_UNITPFX_GIBI:
*(tmp++) = 'G';
*(tmp++) = 'i';
break;
}
switch (unit) {
case KERNAUX_UNIT_BIT:
*(tmp++) = 'b';
*(tmp++) = 'i';
*(tmp++) = 't';
break;
case KERNAUX_UNIT_BYTE:
*(tmp++) = 'B';
break;
}
*(tmp++) = '\0';
2021-12-15 05:45:40 -05:00
const size_t tmp_size = strlen(tmp_buffer) + 1;
if (tmp_size > buffer_size) return false;
2021-12-15 05:45:40 -05:00
strcpy(buffer, tmp_buffer);
return true;
}