Create print module

This commit is contained in:
2025-08-10 16:38:59 +01:00
parent d5173243ba
commit d90f91cda0
5 changed files with 97 additions and 0 deletions

View File

@@ -6,6 +6,7 @@ add_library(imp
memory_stream.c memory_stream.c
parse.c parse.c
prim.c prim.c
print.c
store.c store.c
token.c token.c
) )

8
lib/include/print.h Normal file
View File

@@ -0,0 +1,8 @@
#ifndef PRINT_H
#define PRINT_H
#include "am.h"
size_t print(am_t *am, char *buffer, size_t buffer_size);
#endif

26
lib/print.c Normal file
View File

@@ -0,0 +1,26 @@
#include "print.h"
#include <assert.h>
size_t print(am_t *am, char *buffer, size_t buffer_size)
{
assert(am->val->is_atom);
assert(am->val->atom.type == ATOM_TYPE_INTEGER);
int64_t value = am->val->atom.integer;
int divisor = 10;
while (divisor <= value)
divisor *= 10;
size_t i = 0;
do {
divisor /= 10;
const int digit = value / divisor;
value = value % divisor;
assert(i < buffer_size);
buffer[i++] = '0' + (char)digit;
} while (divisor > 1);
return i;
}

View File

@@ -15,6 +15,7 @@ add_test_suites(
expr_tests.c expr_tests.c
parse_tests.c parse_tests.c
prim_tests.c prim_tests.c
print_tests.c
store_tests.c store_tests.c
token_tests.c token_tests.c
) )

61
tests/print_tests.c Normal file
View File

@@ -0,0 +1,61 @@
#include "print.h"
#include "unity.h"
#include <string.h>
#define BUFFER_SIZE 256U
static am_t am;
static char buffer[BUFFER_SIZE];
void setUp(void)
{
memset(buffer, 0, BUFFER_SIZE);
am_init(&am);
}
void tearDown(void)
{
}
static void test_integer_5(void)
{
am.val = expr_integer(&am, 5);
const size_t len = print(&am, buffer, BUFFER_SIZE);
TEST_ASSERT_EQUAL(1, len);
TEST_ASSERT_EQUAL_MEMORY("5", buffer, 1);
}
static void test_integer_1234(void)
{
am.val = expr_integer(&am, 1234);
const size_t len = print(&am, buffer, BUFFER_SIZE);
TEST_ASSERT_EQUAL(4, len);
TEST_ASSERT_EQUAL_MEMORY("1234", buffer, 4);
}
static void test_integer_0(void)
{
am.val = expr_integer(&am, 0);
const size_t len = print(&am, buffer, BUFFER_SIZE);
TEST_ASSERT_EQUAL(1, len);
TEST_ASSERT_EQUAL_MEMORY("0", buffer, 1);
}
static void test_integer_10(void)
{
am.val = expr_integer(&am, 10);
const size_t len = print(&am, buffer, BUFFER_SIZE);
TEST_ASSERT_EQUAL(2, len);
TEST_ASSERT_EQUAL_MEMORY("10", buffer, 2);
}
int main(void)
{
UNITY_BEGIN();
RUN_TEST(test_integer_5);
RUN_TEST(test_integer_1234);
RUN_TEST(test_integer_0);
RUN_TEST(test_integer_10);
return UNITY_END();
}