aboutsummaryrefslogtreecommitdiff
path: root/cstring/src/cstring.c
blob: 832cb85da007d0bbe0c9167e71cf9319c495e9bf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#include <cstring.h>

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>

string string_new(const char* cstr) {
  const size_t length = strlen(cstr);
  const size_t size   = length + 1;

  char* data = calloc(size, sizeof(char));
  ASSERT(data);
  if (length > 0) {
    memcpy(data, cstr, length);
  }

  return (string){
      .data   = data,
      .length = length,
  };
}

void string_del(string* str) {
  if (str->data) {
    free((void*)str->data);
    str->data   = 0;
    str->length = 0;
  }
}

string string_concat(string left, string right) {
  const size_t length = left.length + right.length;
  const size_t size   = length + 1;

  char* data = calloc(size, sizeof(char));
  ASSERT(data);
  if (length > 0) {
    memcpy(data, left.data, left.length);
    memcpy(data + left.length, right.data, right.length);
  }

  return (string){
      .data   = data,
      .length = length,
  };
}

string string_from_size(size_t size) {
  const size_t length = snprintf(NULL, 0, "%zu", size) + 1;
  char*        data   = calloc(length, sizeof(char));
  ASSERT(data);
  snprintf(data, length, "%zu", size);
  return (string){
      .data   = data,
      .length = length,
  };
}

string string_format_size(size_t size) {
  const size_t multiples[] = {1073741824, 1048576, 1024, 1};
  const char*  units[]     = {"G", "M", "K", "B"};

  size_t integer    = 0;
  size_t fractional = 0;

  int i;
  for (i = 0; i < 4; ++i) {
    const size_t m = multiples[i];
    if (size >= m) {
      integer    = size / m;
      fractional = size % m;
      break;
    }
  }

  double      s;
  const char* unit;
  const char* format;
  if (i == 4) { // 0
    s      = (double)size;
    unit   = "";
    format = "%f%s";
  } else if (i == 3) { // Bytes
    s      = (double)integer + (double)fractional / (double)multiples[i];
    unit   = units[i];
    format = "%.0f%s";
  } else { // KB, MB, GB
    assert(i >= 0);
    assert(i < 3);
    s      = (double)integer + (double)fractional / (double)multiples[i];
    unit   = units[i];
    format = "%.2f%s";
  }

  const size_t length = snprintf(NULL, 0, format, s, unit) + 1;
  char*        data   = calloc(length, sizeof(char));
  ASSERT(data);
  snprintf(data, length, format, s, unit);
  return (string){
      .data   = data,
      .length = length,
  };
}