-
Notifications
You must be signed in to change notification settings - Fork 21
/
bs_size.c
1280 lines (1112 loc) · 36.8 KB
/
bs_size.c
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <gmp.h>
#include <mpfr.h>
#include <langinfo.h>
#include <stdarg.h>
#include <stdio.h>
#include <inttypes.h>
#include <string.h>
#include <ctype.h>
#include <limits.h>
/* set code unit width to 8 so we can use generic macros like 'pcre2_compile'
* instead of 'pcre2_compile_8'
*/
#define PCRE2_CODE_UNIT_WIDTH 8
#include <pcre2.h>
#include "bs_size.h"
#include "gettext.h"
#define _(String) gettext (String)
#define N_(String) String
#define ERROR_BUFFER_LEN 256
/**
* SECTION: bs_size
* @title: BSSize
* @short_description: a class facilitating work with sizes in bytes
* @include: bs_size.h
*
* #BSSize is a type that facilitates work with sizes in bytes by providing
* functions/methods that are required for parsing users input when entering
* size, showing size in nice human-readable format, storing sizes bigger than
* %UINT64_MAX and doing calculations with sizes without loss of
* precision/information. The class is able to hold negative sizes and do
* operations on/with them, but some of the (division and multiplication)
* operations simply ignore the signs of the operands (check the documentation).
*
* The reason why some functions take or return a float as a string instead of a
* float directly is because a string "0.3" can be translated into 0.3 with
* appropriate precision while 0.3 as float is probably something like
* 0.294343... with unknown precision.
*
*/
/***************
* STATIC DATA *
***************/
static char const * const b_units[BS_BUNIT_UNDEF] = {
/* TRANSLATORS: 'B' for bytes */
N_("B"),
/* TRANSLATORS: abbreviation for kibibyte, 2**10 bytes */
N_("KiB"),
/* TRANSLATORS: abbreviation for mebibyte, 2**20 bytes */
N_("MiB"),
/* TRANSLATORS: abbreviation for gibibyte, 2**30 bytes */
N_("GiB"),
/* TRANSLATORS: abbreviation for tebibyte, 2**40 bytes */
N_("TiB"),
/* TRANSLATORS: abbreviation for pebibyte, 2**50 bytes */
N_("PiB"),
/* TRANSLATORS: abbreviation for exbibyte, 2**60 bytes */
N_("EiB"),
/* TRANSLATORS: abbreviation for zebibyte, 2**70 bytes */
N_("ZiB"),
/* TRANSLATORS: abbreviation for yobibyte, 2**80 bytes */
N_("YiB")
};
static char const * const d_units[BS_DUNIT_UNDEF] = {
/* TRANSLATORS: 'B' for bytes */
N_("B"),
/* TRANSLATORS: abbreviation for kilobyte, 10**3 bytes */
N_("KB"),
/* TRANSLATORS: abbreviation for megabyte, 10**6 bytes */
N_("MB"),
/* TRANSLATORS: abbreviation for gigabyte, 10**9 bytes */
N_("GB"),
/* TRANSLATORS: abbreviation for terabyte, 10**12 bytes */
N_("TB"),
/* TRANSLATORS: abbreviation for petabyte, 10**15 bytes */
N_("PB"),
/* TRANSLATORS: abbreviation for exabyte, 10**18 bytes */
N_("EB"),
/* TRANSLATORS: abbreviation for zettabyte, 10**21 bytes */
N_("ZB"),
/* TRANSLATORS: abbreviation for yottabyte, 10**24 bytes */
N_("YB")
};
/****************************
* STRUCT DEFINITIONS *
****************************/
/**
* BSSize:
*
* The BSSize struct contains only private fields and should not be directly
* accessed.
*/
struct _BSSize {
mpz_t bytes;
};
/********************
* HELPER FUNCTIONS *
********************/
static void bs_size_init (BSSize size) {
/* let's start with 64 bits of space */
mpz_init2 (size->bytes, (mp_bitcnt_t) 64);
}
static char *strdup_printf (const char *fmt, ...) {
int num = 0;
char *ret = NULL;
va_list ap;
va_start (ap, fmt);
num = vasprintf (&ret, fmt, ap);
va_end (ap);
if (num <= 0)
/* make sure we return NULL on error */
ret = NULL;
return ret;
}
/**
* replace_char_with_str: (skip)
*
* Replaces all apperances of @char in @str with @new.
*/
static char *replace_char_with_str (const char *str, char orig, const char *new) {
uint64_t offset = 0;
uint64_t i = 0;
uint64_t j = 0;
char *ret = NULL;
const char *next = NULL;
uint64_t count = 0;
if (!str)
return NULL;
next = str;
for (next=strchr (next, orig); next; count++, next=strchr (++next, orig));
/* allocate space for the string [strlen(str)] with the char replaced by the
string [strlen(new) - 1] $count times and a \0 byte at the end [ + 1] */
ret = malloc (sizeof(char) * (strlen(str) + (strlen(new) - 1) * count + 1));
for (i=0; str[i]; i++) {
if (str[i] == orig)
for (j=0; new[j]; j++) {
ret[i+offset] = new[j];
if (new[j+1])
/* something more to copy over */
offset++;
}
else
ret[i+offset] = str[i];
}
ret[i+offset] = '\0';
return ret;
}
/**
* replace_str_with_str: (skip)
*
* Replaces the first appearance of @orig in @str with @new.
*/
static char *replace_str_with_str (const char *str, const char *orig, const char *new) {
char *pos = NULL;
int str_len = 0;
int orig_len = 0;
int new_len = 0;
char *ret = NULL;
int ret_size = 0;
char *dest = NULL;
pos = strstr (str, orig);
if (!pos)
/* nothing to do, just return a copy */
return strdup (str);
str_len = strlen (str);
orig_len = strlen (orig);
new_len = strlen (new);
ret_size = str_len + new_len - orig_len + 1;
ret = malloc (sizeof(char) * ret_size);
memset (ret, 0, ret_size);
memcpy (ret, str, pos - str);
dest = ret + (pos - str);
memcpy (dest, new, new_len);
dest = dest + new_len;
memcpy (dest, pos + orig_len, str_len - (pos - str) - orig_len);
return ret;
}
/**
* strstrip: (skip)
*
* Strips leading and trailing whitespace from the string (**IN-PLACE**)
*/
static void strstrip(char *str) {
int i = 0;
int begin = 0;
int end = strlen(str) - 1;
while (isspace(str[begin]))
begin++;
while ((end >= begin) && isspace(str[end]))
end--;
for (i=begin; i <= end; i++)
str[i - begin] = str[i];
str[i-begin] = '\0';
}
static bool multiply_size_by_unit (mpfr_t size, char *unit_str) {
BSBunit bunit = BS_BUNIT_UNDEF;
BSDunit dunit = BS_DUNIT_UNDEF;
uint64_t pwr = 0;
mpfr_t dec_mul;
size_t unit_str_len = 0;
unit_str_len = strlen (unit_str);
for (bunit=BS_BUNIT_B; bunit < BS_BUNIT_UNDEF; bunit++)
if (strncasecmp (unit_str, b_units[bunit-BS_BUNIT_B], unit_str_len) == 0) {
pwr = (uint64_t) bunit - BS_BUNIT_B;
mpfr_mul_2exp (size, size, 10 * pwr, MPFR_RNDN);
return true;
}
mpfr_init2 (dec_mul, BS_FLOAT_PREC_BITS);
mpfr_set_ui (dec_mul, 1000, MPFR_RNDN);
for (dunit=BS_DUNIT_B; dunit < BS_DUNIT_UNDEF; dunit++)
if (strncasecmp (unit_str, d_units[dunit-BS_DUNIT_B], unit_str_len) == 0) {
pwr = (uint64_t) (dunit - BS_DUNIT_B);
mpfr_pow_ui (dec_mul, dec_mul, pwr, MPFR_RNDN);
mpfr_mul (size, size, dec_mul, MPFR_RNDN);
mpfr_clear (dec_mul);
return true;
}
/* not found among the binary and decimal units, let's try their translated
verions */
for (bunit=BS_BUNIT_B; bunit < BS_BUNIT_UNDEF; bunit++)
if (strncasecmp (unit_str, _(b_units[bunit-BS_BUNIT_B]), unit_str_len) == 0) {
pwr = (uint64_t) bunit - BS_BUNIT_B;
mpfr_mul_2exp (size, size, 10 * pwr, MPFR_RNDN);
return true;
}
mpfr_init2 (dec_mul, BS_FLOAT_PREC_BITS);
mpfr_set_ui (dec_mul, 1000, MPFR_RNDN);
for (dunit=BS_DUNIT_B; dunit < BS_DUNIT_UNDEF; dunit++)
if (strncasecmp (unit_str, _(d_units[dunit-BS_DUNIT_B]), unit_str_len) == 0) {
pwr = (uint64_t) (dunit - BS_DUNIT_B);
mpfr_pow_ui (dec_mul, dec_mul, pwr, MPFR_RNDN);
mpfr_mul (size, size, dec_mul, MPFR_RNDN);
mpfr_clear (dec_mul);
return true;
}
return false;
}
/**
* set_error: (skip)
*
* Sets @error to @code and @msg (if not %NULL). **TAKES OVER @msg.**
*/
static void set_error (BSError **error, BSErrorCode code, char *msg) {
*error = (BSError *) malloc (sizeof(BSError));
(*error)->code = code;
(*error)->msg = msg;
return;
}
typedef void (*MpzOp) (mpz_t ROP, const mpz_t OP1, unsigned long int OP2);
static void do_64bit_add_sub (MpzOp op, mpz_t rop, const mpz_t op1, uint64_t op2) {
uint64_t i = 0;
uint64_t div = 0;
uint64_t mod = 0;
/* small enough to just work */
if (op2 < (uint64_t) ULONG_MAX) {
op (rop, op1, (unsigned long int) op2);
return;
}
mpz_set (rop, op1);
div = op2 / (uint64_t) ULONG_MAX;
mod = op2 % (uint64_t) ULONG_MAX;
for (i=0; i < div; i++)
op (rop, rop, (unsigned long int) ULONG_MAX);
op (rop, rop, (unsigned long int) mod);
}
static void mul_64bit (mpz_t rop, const mpz_t op1, uint64_t op2) {
uint64_t i = 0;
uint64_t div = 0;
uint64_t mod = 0;
mpz_t aux;
mpz_t res;
/* small enough to just work */
if (op2 < (uint64_t) ULONG_MAX) {
mpz_mul_ui (rop, op1, (unsigned long int) op2);
return;
}
mpz_init2 (aux, (mp_bitcnt_t) 64);
mpz_init2 (res, (mp_bitcnt_t) 64);
mpz_set_ui (res, 0);
div = op2 / (uint64_t) ULONG_MAX;
mod = op2 % (uint64_t) ULONG_MAX;
for (i=0; i < div; i++) {
mpz_mul_ui (aux, op1, (unsigned long int) ULONG_MAX);
mpz_add (res, res, aux);
}
mpz_mul_ui (aux, op1, (unsigned long int) mod);
mpz_add (res, res, aux);
mpz_set (rop, res);
mpz_clear (aux);
mpz_clear (res);
}
/***************
* DESTRUCTORS *
* *************/
/**
* bs_size_free:
*
* Clears @size and frees the allocated resources.
*/
void bs_size_free (BSSize size) {
if (size) {
mpz_clear (size->bytes);
free (size);
}
return;
}
/**
* bs_clear_error:
*
* Clears @error and frees the allocated resources.
*/
void bs_clear_error (BSError **error) {
if (error && *error) {
free ((*error)->msg);
free (*error);
*error = NULL;
}
return;
}
/****************
* CONSTRUCTORS *
****************/
/**
* bs_size_new: (constructor)
*
* Creates a new #BSSize instance initialized to 0.
*
* Returns: a new #BSSize initialized to 0.
*/
BSSize bs_size_new (void) {
BSSize ret = (BSSize) malloc (sizeof(struct _BSSize));
bs_size_init (ret);
return ret;
}
/**
* bs_size_new_from_bytes: (constructor)
* @bytes: number of bytes
* @sgn: sign of the size -- if being -1, the size is initialized to
* -@bytes, other values are ignored
*
* Creates a new #BSSize instance.
*
* Returns: a new #BSSize
*/
BSSize bs_size_new_from_bytes (uint64_t bytes, int sgn) {
char *num_str = NULL;
BSSize ret = bs_size_new ();
int ok = 0;
ok = asprintf (&num_str, "%"PRIu64, bytes);
if (ok == -1)
/* probably cannot allocate memory, there's nothing more we can do */
return ret;
mpz_set_str (ret->bytes, num_str, 10);
free (num_str);
if (sgn == -1)
mpz_neg (ret->bytes, ret->bytes);
return ret;
}
/**
* bs_size_new_from_str: (constructor)
* @size_str: string representing the size as a number and an optional unit
* (e.g. "1 GiB")
*
* Creates a new #BSSize instance.
*
* Returns: a new #BSSize
*/
BSSize bs_size_new_from_str (const char *size_str, BSError **error) {
char const * const pattern = "^\\s* # white space \n" \
"(?P<numeric> # the numeric part consists of three parts, below \n" \
" (-|\\+)? # optional sign character \n" \
" (?P<base>([0-9\\.%s]+)) # base \n" \
" (?P<exp>(e|E)(-|\\+)?[0-9]+)?) # exponent \n" \
"\\s* # white space \n" \
"(?P<rest>[^\\s]*)\\s*$ # unit specification";
char *real_pattern = NULL;
pcre2_code *regex = NULL;
int errorcode = 0;
PCRE2_SIZE erroffset;
int str_len = 0;
pcre2_match_data *match_data = NULL;
int str_count = 0;
char *num_str = NULL;
const char *radix_char = NULL;
char *loc_size_str = NULL;
mpf_t parsed_size;
mpfr_t size;
int status = 0;
char *unit_str = NULL;
BSSize ret = NULL;
PCRE2_UCHAR *substring = NULL;
PCRE2_SIZE substring_len = 0;
PCRE2_UCHAR error_buffer[ERROR_BUFFER_LEN];
radix_char = nl_langinfo (RADIXCHAR);
if (strncmp (radix_char, ".", 1) != 0)
real_pattern = strdup_printf (pattern, radix_char);
else
real_pattern = strdup_printf (pattern, "");
regex = pcre2_compile ((PCRE2_SPTR) real_pattern, PCRE2_ZERO_TERMINATED, PCRE2_EXTENDED, &errorcode, &erroffset, NULL);
free (real_pattern);
if (!regex) {
status = pcre2_get_error_message (errorcode, error_buffer, ERROR_BUFFER_LEN);
switch (status) {
case PCRE2_ERROR_BADDATA:
// unknown/invalid error code
set_error (error, BS_ERROR_INVALID_SPEC,
strdup_printf ("Failed to compile pattern at offset %d: Unknown error.", erroffset));
break;
case PCRE2_ERROR_NOMEMORY:
// error buffer is too short
set_error (error, BS_ERROR_INVALID_SPEC,
strdup_printf ("Failed to compile pattern at offset %d: %s (truncated)", erroffset, error_buffer));
break;
default:
set_error (error, BS_ERROR_INVALID_SPEC,
strdup_printf ("Failed to compile pattern at offset %d: %s", erroffset, error_buffer));
break;
}
return NULL;
}
loc_size_str = replace_char_with_str (size_str, '.', radix_char);
str_len = strlen (loc_size_str);
match_data = pcre2_match_data_create_from_pattern (regex, NULL);
str_count = pcre2_match (regex, (PCRE2_SPTR) loc_size_str, str_len,
0, 0, match_data, NULL);
if (str_count < 0) {
set_error (error, BS_ERROR_INVALID_SPEC, strdup_printf ("Failed to parse size spec: %s", size_str));
pcre2_match_data_free (match_data);
pcre2_code_free (regex);
free (loc_size_str);
return NULL;
}
status = pcre2_substring_get_byname (match_data, (PCRE2_SPTR) "numeric", &substring, &substring_len);
if (status < 0) {
set_error (error, BS_ERROR_INVALID_SPEC, strdup_printf ("Failed to parse size spec: %s", size_str));
pcre2_match_data_free (match_data);
pcre2_code_free (regex);
free (loc_size_str);
return NULL;
}
num_str = strndup ((const char*) substring, substring_len);
/* parse the number using GMP because it knows how to handle localization
much better than MPFR */
mpf_init2 (parsed_size, BS_FLOAT_PREC_BITS);
status = mpf_set_str (parsed_size, *num_str == '+' ? num_str+1 : num_str, 10);
free (num_str);
if (status != 0) {
set_error (error, BS_ERROR_INVALID_SPEC, strdup_printf ("Failed to parse size spec: %s", size_str));
pcre2_match_data_free (match_data);
pcre2_code_free (regex);
free (loc_size_str);
mpf_clear (parsed_size);
return NULL;
}
/* but use MPFR from now on because GMP thinks 0.1*1000 = 99 */
mpfr_init2 (size, BS_FLOAT_PREC_BITS);
mpfr_set_f (size, parsed_size, MPFR_RNDN);
mpf_clear (parsed_size);
status = pcre2_substring_get_byname (match_data, (PCRE2_SPTR) "rest", &substring, &substring_len);
unit_str = strndup ((const char*) substring, substring_len);
if ((status >= 0) && strncmp (unit_str, "", 1) != 0) {
strstrip (unit_str);
if (!multiply_size_by_unit (size, unit_str)) {
set_error (error, BS_ERROR_INVALID_SPEC, strdup_printf ("Failed to recognize unit from the spec: %s", size_str));
free (unit_str);
pcre2_match_data_free (match_data);
pcre2_code_free (regex);
free (loc_size_str);
mpfr_clear (size);
return NULL;
}
}
free (unit_str);
pcre2_match_data_free (match_data);
pcre2_code_free (regex);
ret = bs_size_new ();
mpfr_get_z (ret->bytes, size, MPFR_RNDZ);
free (loc_size_str);
mpfr_clear (size);
return ret;
}
/**
* bs_size_new_from_size: (constructor)
* @size: the size to create a new instance from (a copy of)
*
* Creates a new instance of #BSSize.
*
* Returns: (transfer full): a new #BSSize instance which is copy of @size.
*/
BSSize bs_size_new_from_size (const BSSize size) {
BSSize ret = NULL;
ret = bs_size_new ();
mpz_set (ret->bytes, size->bytes);
return ret;
}
/*****************
* QUERY METHODS *
*****************/
/**
* bs_size_get_bytes:
* @sgn: (allow-none) (out): sign of the @size - -1, 0 or 1 for negative, zero or positive
* size respectively
*
* Get the number of bytes of the @size.
*
* Returns: the @size in a number of bytes
*/
uint64_t bs_size_get_bytes (const BSSize size, int *sgn, BSError **error) {
char *num_str = NULL;
mpz_t max;
uint64_t ret = 0;
int ok = 0;
mpz_init2 (max, (mp_bitcnt_t) 64);
ok = asprintf (&num_str, "%"PRIu64, UINT64_MAX);
if (ok == -1) {
/* we probably cannot allocate memory so we are doomed */
set_error (error, BS_ERROR_FAIL, strdup("Failed to allocate memory"));
mpz_clear (max);
return 0;
}
mpz_set_str (max, num_str, 10);
free (num_str);
if (mpz_cmp (size->bytes, max) > 0) {
set_error (error, BS_ERROR_OVER, strdup("The size is too big, cannot be returned as a 64bit number of bytes"));
return 0;
}
mpz_clear (max);
if (sgn)
*sgn = mpz_sgn (size->bytes);
if (mpz_cmp_ui (size->bytes, UINT64_MAX) <= 0)
return (uint64_t) mpz_get_ui (size->bytes);
else {
num_str = bs_size_get_bytes_str (size);
ret = strtoull (num_str, NULL, 10);
free (num_str);
return ret;
}
}
/**
* bs_size_sgn:
*
* Get the sign of the size.
*
* Returns: -1, 0 or 1 if @size is negative, zero or positive, respectively
*/
int bs_size_sgn (const BSSize size) {
return mpz_sgn (size->bytes);
}
/**
* bs_size_get_bytes_str:
*
* Get the number of bytes in @size as a string. This way, the caller doesn't
* have to care about the limitations of some particular integer type.
*
* Returns: (transfer full): the string representing the @size as a number of bytes.
*/
char* bs_size_get_bytes_str (const BSSize size) {
return mpz_get_str (NULL, 10, size->bytes);
}
/**
* bs_size_convert_to:
* @unit: the unit to convert @size to
*
* Get the @size converted to @unit as a string representing a floating-point
* number.
*
* Returns: (transfer full): a string representing the floating-point number
* that equals to @size converted to @unit
*/
char* bs_size_convert_to (const BSSize size, BSUnit unit, BSError **error) {
BSBunit b_unit = BS_BUNIT_B;
BSDunit d_unit = BS_DUNIT_B;
mpf_t divisor;
mpf_t result;
bool found_match = false;
char *ret = NULL;
mpf_init2 (divisor, BS_FLOAT_PREC_BITS);
for (b_unit = BS_BUNIT_B; !found_match && b_unit != BS_BUNIT_UNDEF; b_unit++) {
if (unit.bunit == b_unit) {
found_match = true;
mpf_set_ui (divisor, 1);
mpf_mul_2exp (divisor, divisor, 10 * (b_unit - BS_BUNIT_B));
}
}
for (d_unit = BS_DUNIT_B; !found_match && d_unit != BS_DUNIT_UNDEF; d_unit++) {
if (unit.dunit == d_unit) {
found_match = true;
mpf_set_ui (divisor, 1000);
mpf_pow_ui (divisor, divisor, (d_unit - BS_DUNIT_B));
}
}
if (!found_match) {
set_error (error, BS_ERROR_INVALID_SPEC, "Invalid unit spec given");
mpf_clear (divisor);
return NULL;
}
mpf_init2 (result, BS_FLOAT_PREC_BITS);
mpf_set_z (result, size->bytes);
mpf_div (result, result, divisor);
gmp_asprintf (&ret, "%.*Fg", BS_FLOAT_PREC_BITS/3, result);
mpf_clears (divisor, result, NULL);
return ret;
}
/**
* bs_size_human_readable:
* @min_unit: the smallest unit the returned representation should use
* @max_places: maximum number of decimal places the representation should use
* @xlate: whether to try to translate the representation or not
*
* Get a human-readable representation of @size.
*
* Returns: (transfer full): a string which is human-readable representation of
* @size according to the restrictions given by the
* other parameters
*/
char* bs_size_human_readable (const BSSize size, BSBunit min_unit, int max_places, bool xlate) {
mpf_t cur_val;
char *num_str = NULL;
char *ret = NULL;
int len = 0;
char *zero = NULL;
char *radix_char = NULL;
int sign = 0;
char *loc_num_str = NULL;
bool at_radix = false;
mpf_init2 (cur_val, BS_FLOAT_PREC_BITS);
mpf_set_z (cur_val, size->bytes);
if (min_unit == BS_BUNIT_UNDEF)
min_unit = BS_BUNIT_B;
sign = mpf_sgn (cur_val);
mpf_abs (cur_val, cur_val);
mpf_div_2exp (cur_val, cur_val, 10 * (min_unit - BS_BUNIT_B));
while ((mpf_cmp_ui (cur_val, 1024) > 0) && min_unit != BS_BUNIT_YiB) {
mpf_div_2exp (cur_val, cur_val, 10);
min_unit++;
}
if (sign == -1)
mpf_neg (cur_val, cur_val);
len = gmp_asprintf (&num_str, "%.*Ff", max_places >= 0 ? max_places : BS_FLOAT_PREC_BITS,
cur_val);
mpf_clear (cur_val);
/* should use the proper radix char according to @xlate */
radix_char = nl_langinfo (RADIXCHAR);
if (!xlate) {
loc_num_str = replace_str_with_str (num_str, radix_char, ".");
free (num_str);
radix_char = ".";
} else
loc_num_str = num_str;
/* remove trailing zeros and the radix char */
/* if max_places == 0, there can't be anything trailing */
if (max_places != 0) {
zero = loc_num_str + (len - 1);
while ((zero != loc_num_str) && ((*zero == '0') || (*zero == *radix_char)) && !at_radix) {
at_radix = *zero == *radix_char;
zero--;
}
zero[1] = '\0';
}
ret = strdup_printf ("%s %s", loc_num_str, xlate ? _(b_units[min_unit - BS_BUNIT_B]) : b_units[min_unit - BS_BUNIT_B]);
free (loc_num_str);
return ret;
}
/***************
* ARITHMETIC *
***************/
/**
* bs_size_add:
*
* Add two sizes.
*
* Returns: (transfer full): a new instance of #BSSize which is a sum of @size1 and @size2
*/
BSSize bs_size_add (const BSSize size1, const BSSize size2) {
BSSize ret = bs_size_new ();
mpz_add (ret->bytes, size1->bytes, size2->bytes);
return ret;
}
/**
* bs_size_grow:
*
* Grows @size1 by @size2. IOW, adds @size2 to @size1 in-place (modifying
* @size1).
*
* Basically an in-place variant of bs_size_add().
*
* Returns: (transfer none): @size1 modified by adding @size2 to it
*/
BSSize bs_size_grow (BSSize size1, const BSSize size2) {
mpz_add (size1->bytes, size1->bytes, size2->bytes);
return size1;
}
/**
* bs_size_add_bytes:
*
* Add @bytes to the @size. To add a negative number of bytes use
* bs_size_sub_bytes().
*
* Returns: (transfer full): a new instance of #BSSize which is a sum of @size and @bytes
*/
BSSize bs_size_add_bytes (const BSSize size, uint64_t bytes) {
BSSize ret = bs_size_new ();
do_64bit_add_sub (mpz_add_ui, ret->bytes, size->bytes, bytes);
return ret;
}
/**
* bs_size_grow_bytes:
*
* Grows @size by @bytes. IOW, adds @bytes to @size in-place (modifying @size).
*
* Basically an in-place variant of bs_size_add_bytes().
*
* Returns: (transfer none): @size modified by adding @bytes to it
*/
BSSize bs_size_grow_bytes (BSSize size, const uint64_t bytes) {
do_64bit_add_sub (mpz_add_ui, size->bytes, size->bytes, bytes);
return size;
}
/**
* bs_size_sub:
*
* Subtract @size2 from @size1.
*
* Returns: (transfer full): a new instance of #BSSize which is equals to @size1 - @size2
*/
BSSize bs_size_sub (const BSSize size1, const BSSize size2) {
BSSize ret = bs_size_new ();
mpz_sub (ret->bytes, size1->bytes, size2->bytes);
return ret;
}
/**
* bs_size_shrink:
*
* Shrinks @size1 by @size2. IOW, subtracts @size2 from @size1 in-place
* (modifying @size1).
*
* Basically an in-place variant of bs_size_sub().
*
* Returns: (transfer none): @size1 modified by subtracting @size2 from it
*/
BSSize bs_size_shrink (BSSize size1, const BSSize size2) {
mpz_sub (size1->bytes, size1->bytes, size2->bytes);
return size1;
}
/**
* bs_size_sub_bytes:
*
* Subtract @bytes from the @size. To subtract a negative number of bytes use
* bs_size_add_bytes().
*
* Returns: (transfer full): a new instance of #BSSize which equals to @size - @bytes
*/
BSSize bs_size_sub_bytes (const BSSize size, uint64_t bytes) {
BSSize ret = bs_size_new ();
do_64bit_add_sub (mpz_sub_ui, ret->bytes, size->bytes, bytes);
return ret;
}
/**
* bs_size_shrink_bytes:
*
* Shrinks @size by @bytes. IOW, subtracts @bytes from @size in-place
* (modifying @size). To shrink by a negative number of bytes use
* bs_size_grow_bytes().
*
* Basically an in-place variant of bs_size_sub_bytes().
*
* Returns: (transfer none): @size modified by subtracting @bytes from it
*/
BSSize bs_size_shrink_bytes (BSSize size, uint64_t bytes) {
do_64bit_add_sub (mpz_sub_ui, size->bytes, size->bytes, bytes);
return size;
}
/**
* bs_size_mul_int:
*
* Multiply @size by @times.
*
* Returns: (transfer full): a new instance of #BSSize which equals to @size * @times
*/
BSSize bs_size_mul_int (const BSSize size, uint64_t times) {
BSSize ret = bs_size_new ();
mul_64bit (ret->bytes, size->bytes, times);
return ret;
}
/**
* bs_size_grow_mul_int:
*
* Grow @size @times times. IOW, multiply @size by @times in-place.
*
* Basically an in-place variant of bs_size_mul_int().
*
* Returns: (transfer none): @size modified by growing it @times times
*/
BSSize bs_size_grow_mul_int (BSSize size, uint64_t times) {
mul_64bit (size->bytes, size->bytes, times);
return size;
}
/**
* bs_size_mul_float_str:
*
* Multiply @size by the floating-point number @float_str represents.
*
* Returns: (transfer full): a new #BSSize instance which equals to
* @size * @times_str
*
*/
BSSize bs_size_mul_float_str (const BSSize size, const char *float_str, BSError **error) {
mpf_t op1, op2;
int status = 0;
BSSize ret = NULL;
const char *radix_char = NULL;
char *loc_float_str = NULL;
radix_char = nl_langinfo (RADIXCHAR);
mpf_init2 (op1, BS_FLOAT_PREC_BITS);
mpf_init2 (op2, BS_FLOAT_PREC_BITS);
mpf_set_z (op1, size->bytes);
loc_float_str = replace_char_with_str (float_str, '.', radix_char);
status = mpf_set_str (op2, loc_float_str, 10);
if (status != 0) {
set_error (error, BS_ERROR_INVALID_SPEC, strdup_printf ("'%s' is not a valid floating point number string", loc_float_str));
free (loc_float_str);
mpf_clears (op1, op2, NULL);
return NULL;
}
free (loc_float_str);
mpf_mul (op1, op1, op2);
ret = bs_size_new ();
mpz_set_f (ret->bytes, op1);
mpf_clears (op1, op2, NULL);
return ret;
}
/**
* bs_size_grow_mul_float_str:
*
* Grow @size by the floating-point number @float_str represents times. IOW,
* multiply @size by @float_str in-place.
*
* Basically an in-place variant of bs_size_grow_mul_float_str().
*
* Returns: (transfer none): @size modified by growing it @float_str times.
*/
BSSize bs_size_grow_mul_float_str (BSSize size, const char *float_str, BSError **error) {
mpf_t op1, op2;
int status = 0;
const char *radix_char = NULL;
char *loc_float_str = NULL;
radix_char = nl_langinfo (RADIXCHAR);
mpf_init2 (op1, BS_FLOAT_PREC_BITS);
mpf_init2 (op2, BS_FLOAT_PREC_BITS);
mpf_set_z (op1, size->bytes);
loc_float_str = replace_char_with_str (float_str, '.', radix_char);
status = mpf_set_str (op2, loc_float_str, 10);
if (status != 0) {
set_error (error, BS_ERROR_INVALID_SPEC, strdup_printf ("'%s' is not a valid floating point number string", loc_float_str));
free (loc_float_str);
mpf_clears (op1, op2, NULL);
return NULL;
}
free (loc_float_str);
mpf_mul (op1, op1, op2);
mpz_set_f (size->bytes, op1);
mpf_clears (op1, op2, NULL);
return size;
}
/**
* bs_size_div:
* @sgn: (allow-none) (out): sign of the result
*
* Divide @size1 by @size2. Gives the answer to the question "How many times
* does @size2 fit in @size1?".
*