add an example program

This commit is contained in:
falsycat 2024-02-12 23:14:07 +09:00
parent d75ef72583
commit f0ae9692fc
2 changed files with 75 additions and 0 deletions

View File

@ -43,3 +43,9 @@ if (BUILD_TESTING)
target_link_libraries(allcing_test PRIVATE allcing) target_link_libraries(allcing_test PRIVATE allcing)
add_test(NAME allcing_test COMMAND $<TARGET_FILE:allcing_test>) add_test(NAME allcing_test COMMAND $<TARGET_FILE:allcing_test>)
endif() endif()
# ---- example binary
add_executable(allcing_example EXCLUDE_FROM_ALL)
target_sources(allcing_example PRIVATE example.c)
target_link_libraries(allcing_example PRIVATE allcing)

69
example.c Normal file
View File

@ -0,0 +1,69 @@
// No copyright
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
// ----
#include "allcing.h"
static inline bool acg_flush(struct acg_stream* s) {
assert(NULL != s);
if (s->cursor_bits < 8U) {
return false;
}
FILE** fp = (void*) &s->udata;
if (NULL == *fp) {
*fp = fopen("log.acg", "wb");
if (NULL == *fp) {
abort();
}
}
if (1U != fwrite(s->buffer, s->cursor_bits/8U, 1U, *fp)) {
return false;
}
if (0U != fflush(*fp)) {
return false;
}
return true;
}
#undef ACG_LOC_FULL
#define ACG_LOC_FULL ACG_LOC_SHORT
#undef ACG_FLUSH
#define ACG_FLUSH(s) acg_flush((s))
struct acg_stream logstream = {
.buffer = (uint8_t[1024U]) {0U},
.size_bytes = 1024U,
};
// ----
int collatz(int n) {
ACG_BEGIN(&logstream);
ACG_BLOB(&logstream, sizeof(n), &n);
if (n == 1U) {
ACG_CHECK(&logstream);
ACG_BLOB_LITERAL(&logstream, "it's finished!");
} else if (n%2U) {
ACG_CHECK(&logstream);
n = collatz(3U*n + 1U);
} else {
ACG_CHECK(&logstream);
n = collatz(n / 2U);
}
ACG_END(&logstream);
ACG_BLOB(&logstream, sizeof(n), &n);
return n;
}
int main(int, char**) {
ACG_BEGIN(&logstream);
collatz(100);
ACG_END(&logstream);
}