From dc5d2d68ca0be3c82a65975d297fa69b5c3b3a13 Mon Sep 17 00:00:00 2001 From: Syndamia Date: Fri, 12 Jun 2026 12:13:59 +0300 Subject: feat: Use a macro for round-up division --- BigInt.c | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/BigInt.c b/BigInt.c index e9f6565..ec4f4ee 100644 --- a/BigInt.c +++ b/BigInt.c @@ -5,6 +5,8 @@ #include #include +#define DIVIDE_UP(x, y) (1 + ((x) - 1) / (y)) + typedef uint_fast32_t UWord; #define UWORD_MAX UINT_FAST32_MAX #define UWORD_BIT (sizeof(UWord) * CHAR_BIT) @@ -80,17 +82,18 @@ B_newstr(MemoryManager *mm, const char* str) { usize len = strlen(str); - UWord *num = B_newbytes(mm, len / 2); + UWord *num = B_start(mm, DIVIDE_UP(len * CHAR_BIT / 2, UWORD_BIT)); if (NULL == num) return NULL; - UWord *bcd = B_newbytes(mm, len / 2); + struct BigIntMeta *numm = B_metadata(num); + + UWord *bcd = B_start(mm, numm->words); if (NULL == bcd) { mm->free(*mm, (void**)&num); return NULL; } - struct BigIntMeta *numm = B_metadata(num); struct BigIntMeta *bcdm = B_metadata(bcd); // char string to BCD @@ -123,7 +126,7 @@ BigInt B_newbytes(MemoryManager *mm, usize bytes) { if (0 == bytes) return B_start(mm, 1); - return B_start(mm, 1 + (bytes - 1) / sizeof(UWord)); + return B_start(mm, DIVIDE_UP(bytes, sizeof(UWord))); } BigInt @@ -407,7 +410,7 @@ B_lshift(BigInt *intx, usize shift) { if (xm->resizeable) { UWord width = B_bitwidth(*intx); if (width + shift > xm->words * UWORD_BIT) { - RETURN_NOTOK(B_resize(intx, (width + shift - 1) / UWORD_BIT + 1)); + RETURN_NOTOK(B_resize(intx, DIVIDE_UP(width + shift, UWORD_BIT))); xm = B_metadata(*intx); } } @@ -504,7 +507,7 @@ B_tostr(MemoryManager *mm, const BigInt intx) { // for number of bytes, results in the following formula value. // Do note, a side effect is that we'll use more memory than needed and // show unnecessary leading 0s. Later in the code we'll discard these zeroes. - usize bcd_bytes = 1 + (n - 1) / 6; + usize bcd_bytes = DIVIDE_UP(n, 6); u8 *bcd; if (R_Ok != mm->alloc(*mm, (void**)&bcd, sizeof(u8) * bcd_bytes)) -- cgit v1.2.3