1
0
mirror of https://gitlab.com/80486DX2-66/gists synced 2025-05-31 08:31:41 +05:30

C: categorize files, update .gitignore

This commit is contained in:
2024-02-20 19:36:12 +03:00
parent 73257b0c55
commit eb34ee33b3
12 changed files with 36 additions and 36 deletions

View File

@ -0,0 +1,188 @@
/*
* clock-malfunction-imitation.c
*
* Author: Intel A80486DX2-66
* License: Creative Commons Zero 1.0 Universal
*/
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#define EXIT_IN 2U
#define SECOND_PRECISION 1L
#define TIME_BEFORE_ACCIDENT 2UL
#define TEST_LABEL(s) { \
printf("Test: %s\n", s); \
fflush(stdout); \
}
#define CLOCK_FUN_BEGIN \
static unsigned ticks_before_accident = TIME_BEFORE_ACCIDENT; \
time_t y;
#define CLOCK_FUN_END \
if (x != NULL) { \
*x = y; \
} \
return y;
time_t clock_change_time(time_t* x);
time_t clock_exponential_growth(time_t* x);
time_t clock_hang(time_t* x);
time_t clock_overflow(time_t* x);
time_t clock_reverse(time_t* x);
void time_flow_test(time_t (*time_function)(time_t*));
time_t clock_change_time(time_t* x) {
CLOCK_FUN_BEGIN
time(&y);
if (ticks_before_accident == 0) {
y = 0;
size_t max = sizeof(time(NULL)) / sizeof(int);
printf("max of clock_change_time = %zu\n", max);
size_t intmax_plus_1 = (size_t) INT_MAX + 1;
for (size_t i = 0; i < max; i++)
y |= (rand() & INT_MAX) * intmax_plus_1;
} else
ticks_before_accident--;
CLOCK_FUN_END
}
time_t clock_exponential_growth(time_t* x) {
CLOCK_FUN_BEGIN
static time_t counter = 1;
time(&y);
if (ticks_before_accident == 0) {
y += counter++;
counter *= counter;
} else {
ticks_before_accident--;
}
CLOCK_FUN_END
}
time_t clock_hang(time_t* x) {
CLOCK_FUN_BEGIN
static time_t last_time;
if (ticks_before_accident == 0)
y = last_time;
else {
time(&y);
last_time = y;
ticks_before_accident--;
}
CLOCK_FUN_END
}
time_t clock_overflow(time_t* x) {
CLOCK_FUN_BEGIN
time(&y);
if (ticks_before_accident == 0)
y = LONG_MAX - y;
else
ticks_before_accident--;
CLOCK_FUN_END
}
time_t clock_reverse(time_t* x) {
CLOCK_FUN_BEGIN
static time_t counter = 1, old_time;
if (ticks_before_accident == 0) {
y = old_time - counter++;
} else {
time(&y);
old_time = y;
ticks_before_accident--;
}
CLOCK_FUN_END
}
void time_flow_test(time_t (*time_function)(time_t*)) {
time_t current_time, previous_time;
double time_diff;
// Get the current time
time(&current_time);
previous_time = current_time;
bool first_time_passed = false;
unsigned i = 0;
for (;;) {
// Get the current time
time_function(&current_time);
// Calculate the time difference in seconds
time_diff = difftime(current_time, previous_time);
if (!first_time_passed) {
time_diff = (double) SECOND_PRECISION;
first_time_passed = true;
}
printf("time difference: %f", time_diff);
fflush(stdout);
// Check if the time difference exceeds a threshold (e.g., 1 second)
if (time_diff != (double) SECOND_PRECISION) {
printf(" -> Abnormal time flow detected!");
fflush(stdout);
if (++i >= EXIT_IN) {
printf("\nAborting\n");
fflush(stdout);
break;
}
}
printf("\n");
fflush(stdout);
// Update the previous time
previous_time = current_time;
usleep(SECOND_PRECISION * 1000000L);
first_time_passed = true;
}
printf("\n");
fflush(stdout);
}
int main(void) {
TEST_LABEL("clock_change_time")
time_flow_test(&clock_change_time);
TEST_LABEL("clock_exponential_growth")
time_flow_test(&clock_exponential_growth);
TEST_LABEL("clock_hang")
time_flow_test(&clock_hang);
TEST_LABEL("clock_overflow")
time_flow_test(&clock_overflow);
TEST_LABEL("clock_reverse")
time_flow_test(&clock_reverse);
return 0;
}

View File

@ -0,0 +1,536 @@
/*
* This was an experiment to learn about how libc turn floating point strings
* into actual values.
*
* Expects the floating point string to be in stdin.
*
* The new added code:
* Author: Intel A80486DX2-66
* License: Creative Commons Zero 1.0 Universal
* The original code is from musl libc: version 1.2.4, src/internal/floatscan.c
*/
#include <stdint.h>
#include <stdio.h>
#include <math.h>
#include <float.h>
#include <limits.h>
#include <errno.h>
#include <ctype.h>
/* wrapping code --- beginning */
#define shgetc(f) fgetc(f)
#define shlim(...)
#define shunget(...)
#define FLOAT_TYPE 0
#define DOUBLE_TYPE 1
#define LONG_DOUBLE_TYPE 2
/* wrapping code --- end */
/* the original musl libc code --- beginning */
#if LDBL_MANT_DIG == 53 && LDBL_MAX_EXP == 1024
#define LD_B1B_DIG 2
#define LD_B1B_MAX 9007199, 254740991
#define KMAX 128
#elif LDBL_MANT_DIG == 64 && LDBL_MAX_EXP == 16384
#define LD_B1B_DIG 3
#define LD_B1B_MAX 18, 446744073, 709551615
#define KMAX 2048
#elif LDBL_MANT_DIG == 113 && LDBL_MAX_EXP == 16384
#define LD_B1B_DIG 4
#define LD_B1B_MAX 10384593, 717069655, 257060992, 658440191
#define KMAX 2048
#else
#error Unsupported long double representation
#endif
#define MASK (KMAX-1)
static long long scanexp(FILE *f, int pok)
{
int c;
int x;
long long y;
int neg = 0;
c = shgetc(f);
if (c=='+' || c=='-') {
neg = (c=='-');
c = shgetc(f);
if (c-'0'>=10U && pok) shunget(f);
}
if (c-'0'>=10U) {
shunget(f);
return LLONG_MIN;
}
for (x=0; c-'0'<10U && x<INT_MAX/10; c = shgetc(f))
x = 10*x + c-'0';
for (y=x; c-'0'<10U && y<LLONG_MAX/100; c = shgetc(f))
y = 10*y + c-'0';
for (; c-'0'<10U; c = shgetc(f));
shunget(f);
return neg ? -y : y;
}
static long double decfloat(FILE *f, int c, int bits, int emin, int sign, int pok)
{
uint32_t x[KMAX];
static const uint32_t th[] = { LD_B1B_MAX };
int i, j, k, a, z;
long long lrp=0, dc=0;
long long e10=0;
int lnz = 0;
int gotdig = 0, gotrad = 0;
int rp;
int e2;
int emax = -emin-bits+3;
int denormal = 0;
long double y;
long double frac=0;
long double bias=0;
static const int p10s[] = { 10, 100, 1000, 10000,
100000, 1000000, 10000000, 100000000 };
j=0;
k=0;
/* Don't let leading zeros consume buffer space */
for (; c=='0'; c = shgetc(f)) gotdig=1;
if (c=='.') {
gotrad = 1;
for (c = shgetc(f); c=='0'; c = shgetc(f)) gotdig=1, lrp--;
}
x[0] = 0;
for (; c-'0'<10U || c=='.'; c = shgetc(f)) {
if (c == '.') {
if (gotrad) break;
gotrad = 1;
lrp = dc;
} else if (k < KMAX-3) {
dc++;
if (c!='0') lnz = dc;
if (j) x[k] = x[k]*10 + c-'0';
else x[k] = c-'0';
if (++j==9) {
k++;
j=0;
}
gotdig=1;
} else {
dc++;
if (c!='0') {
lnz = (KMAX-4)*9;
x[KMAX-4] |= 1;
}
}
}
if (!gotrad) lrp=dc;
if (gotdig && (c|32)=='e') {
e10 = scanexp(f, pok);
if (e10 == LLONG_MIN) {
if (pok) {
shunget(f);
} else {
shlim(f, 0);
return 0;
}
e10 = 0;
}
lrp += e10;
} else if (c>=0) {
shunget(f);
}
if (!gotdig) {
errno = EINVAL;
shlim(f, 0);
return 0;
}
/* Handle zero specially to avoid nasty special cases later */
if (!x[0]) return sign * 0.0;
/* Optimize small integers (w/no exponent) and over/under-flow */
if (lrp==dc && dc<10 && (bits>30 || x[0]>>bits==0))
return sign * (long double)x[0];
if (lrp > -emin/2) {
errno = ERANGE;
return sign * LDBL_MAX * LDBL_MAX;
}
if (lrp < emin-2*LDBL_MANT_DIG) {
errno = ERANGE;
return sign * LDBL_MIN * LDBL_MIN;
}
/* Align incomplete final B1B digit */
if (j) {
for (; j<9; j++) x[k]*=10;
k++;
j=0;
}
a = 0;
z = k;
e2 = 0;
rp = lrp;
/* Optimize small to mid-size integers (even in exp. notation) */
if (lnz<9 && lnz<=rp && rp < 18) {
if (rp == 9) return sign * (long double)x[0];
if (rp < 9) return sign * (long double)x[0] / p10s[8-rp];
int bitlim = bits-3*(int)(rp-9);
if (bitlim>30 || x[0]>>bitlim==0)
return sign * (long double)x[0] * p10s[rp-10];
}
/* Drop trailing zeros */
for (; !x[z-1]; z--);
/* Align radix point to B1B digit boundary */
if (rp % 9) {
int rpm9 = rp>=0 ? rp%9 : rp%9+9;
int p10 = p10s[8-rpm9];
uint32_t carry = 0;
for (k=a; k!=z; k++) {
uint32_t tmp = x[k] % p10;
x[k] = x[k]/p10 + carry;
carry = 1000000000/p10 * tmp;
if (k==a && !x[k]) {
a = (a+1 & MASK);
rp -= 9;
}
}
if (carry) x[z++] = carry;
rp += 9-rpm9;
}
/* Upscale until desired number of bits are left of radix point */
while (rp < 9*LD_B1B_DIG || (rp == 9*LD_B1B_DIG && x[a]<th[0])) {
uint32_t carry = 0;
e2 -= 29;
for (k=(z-1 & MASK); ; k=(k-1 & MASK)) {
uint64_t tmp = ((uint64_t)x[k] << 29) + carry;
if (tmp > 1000000000) {
carry = tmp / 1000000000;
x[k] = tmp % 1000000000;
} else {
carry = 0;
x[k] = tmp;
}
if (k==(z-1 & MASK) && k!=a && !x[k]) z = k;
if (k==a) break;
}
if (carry) {
rp += 9;
a = (a-1 & MASK);
if (a == z) {
z = (z-1 & MASK);
x[z-1 & MASK] |= x[z];
}
x[a] = carry;
}
}
/* Downscale until exactly number of bits are left of radix point */
for (;;) {
uint32_t carry = 0;
int sh = 1;
for (i=0; i<LD_B1B_DIG; i++) {
k = (a+i & MASK);
if (k == z || x[k] < th[i]) {
i=LD_B1B_DIG;
break;
}
if (x[a+i & MASK] > th[i]) break;
}
if (i==LD_B1B_DIG && rp==9*LD_B1B_DIG) break;
/* FIXME: find a way to compute optimal sh */
if (rp > 9+9*LD_B1B_DIG) sh = 9;
e2 += sh;
for (k=a; k!=z; k=(k+1 & MASK)) {
uint32_t tmp = x[k] & (1<<sh)-1;
x[k] = (x[k]>>sh) + carry;
carry = (1000000000>>sh) * tmp;
if (k==a && !x[k]) {
a = (a+1 & MASK);
i--;
rp -= 9;
}
}
if (carry) {
if ((z+1 & MASK) != a) {
x[z] = carry;
z = (z+1 & MASK);
} else x[z-1 & MASK] |= 1;
}
}
/* Assemble desired bits into floating point variable */
for (y=i=0; i<LD_B1B_DIG; i++) {
if ((a+i & MASK)==z) x[(z=(z+1 & MASK))-1] = 0;
y = 1000000000.0L * y + x[a+i & MASK];
}
y *= sign;
/* Limit precision for denormal results */
if (bits > LDBL_MANT_DIG+e2-emin) {
bits = LDBL_MANT_DIG+e2-emin;
if (bits<0) bits=0;
denormal = 1;
}
/* Calculate bias term to force rounding, move out lower bits */
if (bits < LDBL_MANT_DIG) {
bias = copysignl(scalbn(1, 2*LDBL_MANT_DIG-bits-1), y);
frac = fmodl(y, scalbn(1, LDBL_MANT_DIG-bits));
y -= frac;
y += bias;
}
/* Process tail of decimal input so it can affect rounding */
if ((a+i & MASK) != z) {
uint32_t t = x[a+i & MASK];
if (t < 500000000 && (t || (a+i+1 & MASK) != z))
frac += 0.25*sign;
else if (t > 500000000)
frac += 0.75*sign;
else if (t == 500000000) {
if ((a+i+1 & MASK) == z)
frac += 0.5*sign;
else
frac += 0.75*sign;
}
if (LDBL_MANT_DIG-bits >= 2 && !fmodl(frac, 1))
frac++;
}
y += frac;
y -= bias;
if ((e2+LDBL_MANT_DIG & INT_MAX) > emax-5) {
if (fabsl(y) >= 2/LDBL_EPSILON) {
if (denormal && bits==LDBL_MANT_DIG+e2-emin)
denormal = 0;
y *= 0.5;
e2++;
}
if (e2+LDBL_MANT_DIG>emax || (denormal && frac))
errno = ERANGE;
}
return scalbnl(y, e2);
}
static long double hexfloat(FILE *f, int bits, int emin, int sign, int pok)
{
uint32_t x = 0;
long double y = 0;
long double scale = 1;
long double bias = 0;
int gottail = 0, gotrad = 0, gotdig = 0;
long long rp = 0;
long long dc = 0;
long long e2 = 0;
int d;
int c;
c = shgetc(f);
/* Skip leading zeros */
for (; c=='0'; c = shgetc(f)) gotdig = 1;
if (c=='.') {
gotrad = 1;
c = shgetc(f);
/* Count zeros after the radix point before significand */
for (rp=0; c=='0'; c = shgetc(f), rp--) gotdig = 1;
}
for (; c-'0'<10U || (c|32)-'a'<6U || c=='.'; c = shgetc(f)) {
if (c=='.') {
if (gotrad) break;
rp = dc;
gotrad = 1;
} else {
gotdig = 1;
if (c > '9') d = (c|32)+10-'a';
else d = c-'0';
if (dc<8) {
x = x*16 + d;
} else if (dc < LDBL_MANT_DIG/4+1) {
y += d*(scale/=16);
} else if (d && !gottail) {
y += 0.5*scale;
gottail = 1;
}
dc++;
}
}
if (!gotdig) {
shunget(f);
if (pok) {
shunget(f);
if (gotrad) shunget(f);
} else {
shlim(f, 0);
}
return sign * 0.0;
}
if (!gotrad) rp = dc;
while (dc<8) x *= 16, dc++;
if ((c|32)=='p') {
e2 = scanexp(f, pok);
if (e2 == LLONG_MIN) {
if (pok) {
shunget(f);
} else {
shlim(f, 0);
return 0;
}
e2 = 0;
}
} else {
shunget(f);
}
e2 += 4*rp - 32;
if (!x) return sign * 0.0;
if (e2 > -emin) {
errno = ERANGE;
return sign * LDBL_MAX * LDBL_MAX;
}
if (e2 < emin-2*LDBL_MANT_DIG) {
errno = ERANGE;
return sign * LDBL_MIN * LDBL_MIN;
}
while (x < 0x80000000) {
if (y>=0.5) {
x += x + 1;
y += y - 1;
} else {
x += x;
y += y;
}
e2--;
}
if (bits > 32+e2-emin) {
bits = 32+e2-emin;
if (bits<0) bits=0;
}
if (bits < LDBL_MANT_DIG)
bias = copysignl(scalbn(1, 32+LDBL_MANT_DIG-bits-1), sign);
if (bits<32 && y && !(x&1)) x++, y=0;
y = bias + sign*(long double)x + sign*y;
y -= bias;
if (!y) errno = ERANGE;
return scalbnl(y, e2);
}
long double __floatscan(FILE *f, int prec, int pok)
{
int sign = 1;
size_t i;
int bits;
int emin;
int c;
switch (prec) {
case 0:
bits = FLT_MANT_DIG;
emin = FLT_MIN_EXP-bits;
break;
case 1:
bits = DBL_MANT_DIG;
emin = DBL_MIN_EXP-bits;
break;
case 2:
bits = LDBL_MANT_DIG;
emin = LDBL_MIN_EXP-bits;
break;
default:
return 0;
}
while (isspace((c=shgetc(f))));
if (c=='+' || c=='-') {
sign -= 2*(c=='-');
c = shgetc(f);
}
for (i=0; i<8 && (c|32)=="infinity"[i]; i++)
if (i<7) c = shgetc(f);
if (i==3 || i==8 || (i>3 && pok)) {
if (i!=8) {
shunget(f);
if (pok) for (; i>3; i--) shunget(f);
}
return sign * INFINITY;
}
if (!i) for (i=0; i<3 && (c|32)=="nan"[i]; i++)
if (i<2) c = shgetc(f);
if (i==3) {
if (shgetc(f) != '(') {
shunget(f);
return NAN;
}
for (i=1; ; i++) {
c = shgetc(f);
if (c-'0'<10U || c-'A'<26U || c-'a'<26U || c=='_')
continue;
if (c==')') return NAN;
shunget(f);
if (!pok) {
errno = EINVAL;
shlim(f, 0);
return 0;
}
while (i--) shunget(f);
return NAN;
}
return NAN;
}
if (i) {
shunget(f);
errno = EINVAL;
shlim(f, 0);
return 0;
}
if (c=='0') {
c = shgetc(f);
if ((c|32) == 'x')
return hexfloat(f, bits, emin, sign, pok);
shunget(f);
c = '0';
}
return decfloat(f, c, bits, emin, sign, pok);
}
/* the original musl libc code --- end */
/* test code --- beginning */
int main(void) {
printf("LD_B1B_DIG = %d\n", LD_B1B_DIG);
printf("%La\n", __floatscan(stdin, LONG_DOUBLE_TYPE, 1));
return 0;
}
/* test code --- end */

View File

@ -0,0 +1,396 @@
/*
* reverse-ramdisk.c
*
* C programming idea: Handling temporary files like memory allocations
* (allocating -> creating empty file, using -> locking for R/W,
* freeing -> deleting).
*
* 20% AI, 80% human (the code is tested and reviewed)
*
* Warning: The current result is quick and dirty. Not for educational or
* production purposes.
*
* GCC/Clang/TCC: Compile with -DTEST to set macro TEST as defined, with
* -DDEBUG to enable debug mode
*
* To-Do: Test: Fix the bug with invalid next size to reallocate
* To-Do: Test: Automate the test verification
*
* Author: Intel A80486DX2-66
* License: Creative Commons Zero 1.0 Universal
*/
#include <errno.h>
#include <inttypes.h>
#include <math.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#if _POSIX_VERSION >= 200112L
# include <fcntl.h>
# include <unistd.h>
# define IS_POSIX 1
#else
# define IS_POSIX 0
#endif
#ifdef DEBUG
# define LINE_FAIL(x) printf("failed on line %d\n", __LINE__ + x)
#else
# define LINE_FAIL(x)
#endif
#if defined(DEBUG) || defined(TEST)
# define DBG_PRINT(...) do { \
printf(__VA_ARGS__); \
fflush(stdout); \
} while (0)
#else
# define DBG_PRINT(...)
#endif
#define RETREAT(s) do { \
perror(s); \
exit(EXIT_FAILURE); \
} while (0)
typedef struct {
bool locked;
int ID;
char* file_path;
#if IS_POSIX
int file;
#else
FILE* file;
#endif
} TempFile;
TempFile* temp_files = NULL;
size_t num_temp_files = 0;
int tf_alloc(size_t n, size_t type_size);
int tf_free(int ID);
int tf_write(int ID, size_t offset, void* src, size_t data_size);
int tf_read(int ID, size_t offset, void* dest, size_t data_size);
int tf_alloc(size_t n, size_t type_size) {
DBG_PRINT("tf_alloc(%zu, %zu)\n", n, type_size);
// Create an empty file
size_t len_digit;
if (num_temp_files == 0)
len_digit = 1;
else
len_digit = (size_t) floor(log10((double) num_temp_files)) + 1;
size_t file_path_len = len_digit + strlen("tf_.tmp");
char* file_path = malloc((file_path_len + 1) * sizeof(char));
if (file_path == NULL) {
LINE_FAIL(-2);
return -1;
}
int res = snprintf(file_path, file_path_len + 1, "tf_%" PRIuMAX ".tmp",
(uintmax_t) num_temp_files);
if ((size_t) res != file_path_len) {
LINE_FAIL(-2);
return -1;
}
#if IS_POSIX
int file = open(file_path, O_RDWR | O_CREAT);
if (file == -1) {
#else
FILE* file = fopen(file_path, "w+b");
if (file == NULL) {
#endif
LINE_FAIL(-2);
return -1;
}
// Allocate memory for the TempFile struct
TempFile* temp_file = malloc(sizeof(TempFile));
if (temp_file == NULL) {
LINE_FAIL(-2);
return -1;
}
// Assign the ID, file path, file handler
temp_file->locked = false;
temp_file->ID = num_temp_files;
temp_file->file_path = strdup(file_path);
temp_file->file = file;
// Allocate/reallocate memory for the temp_files structure
if (temp_files == NULL)
temp_files = malloc(sizeof(TempFile));
else
temp_files = realloc(temp_files, num_temp_files * sizeof(TempFile));
if (temp_files == NULL) {
LINE_FAIL(-2);
return -1;
}
// Add the temp file to the array
temp_files[num_temp_files++] = *temp_file;
return temp_file->ID;
}
int tf_free(int ID) {
DBG_PRINT("tf_free(%d)\n", ID);
size_t index = (size_t) ID;
if (temp_files[index].locked) {
errno = EBUSY;
return -1;
}
temp_files[index].locked = true;
#if IS_POSIX
close(temp_files[index].file);
#else
fclose(temp_files[index].file);
#endif
// Delete the file
if (remove(temp_files[index].file_path) != 0) {
LINE_FAIL(-1);
return -1;
}
free(temp_files[index].file_path);
// Shift the remaining temp files in the array
for (size_t i = index; i < num_temp_files - 1; i++)
temp_files[i] = temp_files[i + 1];
// Reallocate memory for the temp_files array
if (--num_temp_files > 0) {
DBG_PRINT("num_temp_files = %zu\n", num_temp_files);
if ((temp_files = realloc(temp_files, num_temp_files
* sizeof(TempFile))) == NULL) {
LINE_FAIL(-2);
return -1;
}
}
temp_files[index].locked = false;
return 0;
}
int tf_write(int ID, size_t offset, void* src, size_t data_size) {
DBG_PRINT("tf_write(%d, %zu, %p, %zu)\n", ID, offset, src, data_size);
size_t index = (size_t) ID;
if (temp_files[index].locked) {
errno = EBUSY;
return -1;
}
temp_files[index].locked = true;
#if IS_POSIX
// Check file handler for -1
int file = temp_files[index].file;
if (file == -1)
#else
// Check file handler for NULL
FILE* file = temp_files[index].file;
if (file == NULL)
#endif
return -1;
// Set the position
#if IS_POSIX
if (lseek(file, offset, SEEK_SET) == -1) {
#else
if (fseek(file, offset, SEEK_SET) == -1) {
#endif
LINE_FAIL(-1);
return -1;
}
// Write the data to the file
#if IS_POSIX
ssize_t
#else
size_t
#endif
bytes_written =
#if IS_POSIX
write(file, src, data_size);
#else
fwrite(src, 1, data_size, file);
#endif
if (
#if IS_POSIX
(size_t)
#endif
bytes_written != data_size) {
errno = EIO;
return -1;
}
#if IS_POSIX
if (fsync(file) == -1) {
LINE_FAIL(-1);
return -1;
}
#else
fflush(file);
#endif
temp_files[index].locked = false;
return 0;
}
int tf_read(int ID, size_t offset, void* dest, size_t data_size) {
DBG_PRINT("tf_read(%d, %zu, %p, %zu)\n", ID, offset, dest, data_size);
size_t index = (size_t) ID;
if (temp_files[index].locked) {
errno = EBUSY;
return -1;
}
temp_files[index].locked = true;
#if IS_POSIX
int file = temp_files[index].file;
if (file == -1)
#else
FILE* file = temp_files[index].file;
if (file == NULL)
#endif
return -1;
// Read the data from the file
void* src = malloc(data_size);
if (src == NULL) {
#if IS_POSIX
close(file);
#else
fclose(file);
#endif
LINE_FAIL(-7);
return -1;
}
memset(src, 0, data_size); // clear destination
// Set the position
#if IS_POSIX
if (lseek(file, offset, SEEK_SET) == -1) {
#else
if (fseek(file, offset, SEEK_SET) == -1) {
#endif
LINE_FAIL(-1);
return -1;
}
// read bytes
#if IS_POSIX
ssize_t bytes_read = read(file, src, data_size);
#else
size_t bytes_read = fread(src, 1, data_size, file);
#endif
memcpy(dest, src, data_size);
free(src); // Free the allocated memory
if (
#if IS_POSIX
(size_t)
#endif
bytes_read != data_size) {
errno = EIO;
return -1;
}
#ifdef DEBUG
printf("Read: ID = %d, src = %p, size = %zu -> '",
ID, dest, data_size);
for (size_t i = 0; i < data_size; i++)
printf("0x%02" PRIX8 "%c", *((uint8_t*)((uint8_t*)dest + i)),
i == (data_size - 1) ? '\'' : ' ');
printf("\n");
fflush(stdout);
#endif
temp_files[index].locked = false;
return 0;
}
#ifdef TEST
int main(void) {
DBG_PRINT("started\n");
#define ARRAY_1_LEN 4
#define ARRAY_2_LEN 16
int ID_1 = tf_alloc(ARRAY_1_LEN, sizeof(int));
int ID_2 = tf_alloc(ARRAY_2_LEN, sizeof(uint16_t));
if (ID_1 == -1 || ID_2 == -1)
RETREAT("tf_alloc");
DBG_PRINT("allocated memory\n");
int test_data_1[ARRAY_1_LEN] = {123, 456, 789, -123};
DBG_PRINT("initialized array 1\n");
uint16_t test_data_2[ARRAY_2_LEN];
for (size_t i = 0; i < ARRAY_2_LEN; i++)
test_data_2[i] = 1 << i;
DBG_PRINT("initialized array 2\n");
for (size_t i = 0; i < ARRAY_1_LEN; i++)
if (tf_write(ID_1, i * sizeof(int), &test_data_1[i], sizeof(int)) == -1)
RETREAT("tf_write");
DBG_PRINT("wrote array 1\n");
for (size_t i = 0; i < ARRAY_2_LEN; i++)
if (tf_write(ID_2, i * sizeof(uint16_t), &test_data_2[i],
sizeof(uint16_t)) == -1)
RETREAT("tf_write");
DBG_PRINT("wrote array 2\n");
// round-trip
test_data_1[0] = 111;
test_data_1[1] = 222;
test_data_1[2] = 333;
test_data_1[3] = 444;
DBG_PRINT("filled array 1 with garbage\n");
for (size_t i = 0; i < 16; i++)
test_data_2[i] ^= 1;
DBG_PRINT("filled array 2 with garbage\n");
for (size_t i = 0; i < ARRAY_1_LEN; i++)
if (tf_read(ID_1, i * sizeof(int), &test_data_1[i], sizeof(int)) == -1)
RETREAT("tf_read");
DBG_PRINT("restored array 1\n");
for (size_t i = 0; i < ARRAY_2_LEN; i++)
if (tf_read(ID_2, i * sizeof(uint16_t), &test_data_2[i],
sizeof(uint16_t)) == -1)
RETREAT("tf_read");
DBG_PRINT("restored array 2\n");
DBG_PRINT("Values (1): ");
for (size_t i = 0; i < ARRAY_1_LEN; i++)
DBG_PRINT("%d%c", test_data_1[i], i == (ARRAY_1_LEN - 1) ? '\n' : ' ');
DBG_PRINT("Values (2): ");
for (size_t i = 0; i < ARRAY_2_LEN; i++)
DBG_PRINT("%d%c", test_data_2[i], i == (ARRAY_2_LEN - 1) ? '\n' : ' ');
tf_free(ID_1);
tf_free(ID_2);
DBG_PRINT("freed both files\n");
return 0;
}
#endif