allcing/example.c

81 lines
1.4 KiB
C

// No copyright
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
// ----
#define ACG_NO_READ_FUNCTIONS
#include "allcing.h"
static inline bool acg_stream_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;
}
uint8_t frag = 0U;
if (s->cursor_bits%8U > 0U) {
frag = s->buffer[s->cursor_bits/8U];
}
memset(s->buffer, 0U, s->size_bytes);
s->buffer[0] = frag;
s->cursor_bits %= 8U;
if (0U != fflush(*fp)) {
return false;
}
return true;
}
#undef ACG_FLUSH
#define ACG_FLUSH(s) acg_stream_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);
}