bstack 0.1.2

A persistent, fsync-durable binary stack backed by a single file
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
/* Mirror of the Rust bstack test suite, adapted for the C API. */

#define _DARWIN_C_SOURCE
#define _DEFAULT_SOURCE
#define _POSIX_C_SOURCE 200809L
#define _XOPEN_SOURCE 700

#include "bstack.h"

#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>

/* =========================================================================
 * Harness
 * ====================================================================== */

static int g_total  = 0;
static int g_passed = 0;

/* Returns -1 immediately from the enclosing test function on failure. */
#define CHECK(cond)                                                  \
    do {                                                             \
        if (!(cond)) {                                               \
            fprintf(stderr, "  FAIL %s:%d  %s\n",                   \
                    __func__, __LINE__, #cond);                      \
            return -1;                                               \
        }                                                            \
    } while (0)

typedef int (*test_fn)(void);

static void run(const char *name, test_fn fn)
{
    g_total++;
    int r = fn();
    if (r == 0) {
        printf("PASS  %s\n", name);
        g_passed++;
    } else {
        printf("FAIL  %s\n", name);
    }
}

#define T(fn) run(#fn, fn)

/* Create a unique temp path and remove any pre-existing file at it so
 * bstack_open starts with a fresh empty file. */
static void make_tmp(char *buf, size_t n)
{
    snprintf(buf, n, "/tmp/bstack_test_XXXXXX");
    int fd = mkstemp(buf);
    if (fd >= 0) { close(fd); unlink(buf); }
}

/* Read 8-byte little-endian value from absolute file offset (raw fd). */
static uint64_t raw_read_le64(int fd, off_t offset)
{
    uint8_t b[8];
    if (pread(fd, b, 8, offset) != 8) return (uint64_t)-1;
    uint64_t v = 0;
    for (int i = 0; i < 8; i++) v |= (uint64_t)b[i] << (8 * i);
    return v;
}

/* =========================================================================
 * Functional tests
 * ====================================================================== */

static int test_push_returns_correct_offsets(void)
{
    char tmp[64]; make_tmp(tmp, sizeof tmp);
    bstack_t *bs = bstack_open(tmp);
    CHECK(bs != NULL);

    uint64_t off0, off1, off2;
    CHECK(bstack_push(bs, (uint8_t *)"hello", 5, &off0) == 0);
    CHECK(bstack_push(bs, (uint8_t *)"world", 5, &off1) == 0);
    CHECK(bstack_push(bs, (uint8_t *)"!",     1, &off2) == 0);

    CHECK(off0 == 0);
    CHECK(off1 == 5);
    CHECK(off2 == 10);

    uint64_t len;
    CHECK(bstack_len(bs, &len) == 0);
    CHECK(len == 11);

    bstack_close(bs); unlink(tmp);
    return 0;
}

static int test_pop_returns_correct_bytes_and_shrinks(void)
{
    char tmp[64]; make_tmp(tmp, sizeof tmp);
    bstack_t *bs = bstack_open(tmp);
    CHECK(bs != NULL);

    CHECK(bstack_push(bs, (uint8_t *)"hello", 5, NULL) == 0);
    CHECK(bstack_push(bs, (uint8_t *)"world", 5, NULL) == 0);

    uint8_t buf[5]; size_t written;
    CHECK(bstack_pop(bs, 5, buf, &written) == 0);
    CHECK(written == 5);
    CHECK(memcmp(buf, "world", 5) == 0);

    uint64_t len;
    CHECK(bstack_len(bs, &len) == 0);
    CHECK(len == 5);

    bstack_close(bs); unlink(tmp);
    return 0;
}

static int test_pop_across_push_boundary(void)
{
    char tmp[64]; make_tmp(tmp, sizeof tmp);
    bstack_t *bs = bstack_open(tmp);
    CHECK(bs != NULL);

    CHECK(bstack_push(bs, (uint8_t *)"hello", 5, NULL) == 0);
    CHECK(bstack_push(bs, (uint8_t *)"world", 5, NULL) == 0);

    uint8_t buf[7]; size_t written;
    CHECK(bstack_pop(bs, 7, buf, &written) == 0);
    CHECK(written == 7);
    CHECK(memcmp(buf, "loworld", 7) == 0);    /* last 7 of "helloworld" */

    uint64_t len;
    CHECK(bstack_len(bs, &len) == 0);
    CHECK(len == 3);

    bstack_close(bs); unlink(tmp);
    return 0;
}

static int test_pop_on_empty_file_returns_error(void)
{
    char tmp[64]; make_tmp(tmp, sizeof tmp);
    bstack_t *bs = bstack_open(tmp);
    CHECK(bs != NULL);

    uint8_t buf[1];
    int r = bstack_pop(bs, 1, buf, NULL);
    CHECK(r == -1);
    CHECK(errno == EINVAL);

    /* File must still be empty after the failed pop. */
    uint64_t len;
    CHECK(bstack_len(bs, &len) == 0);
    CHECK(len == 0);

    bstack_close(bs); unlink(tmp);
    return 0;
}

static int test_pop_n_exceeds_size_returns_error(void)
{
    char tmp[64]; make_tmp(tmp, sizeof tmp);
    bstack_t *bs = bstack_open(tmp);
    CHECK(bs != NULL);

    CHECK(bstack_push(bs, (uint8_t *)"abc", 3, NULL) == 0);

    uint8_t buf[4];
    int r = bstack_pop(bs, 4, buf, NULL);
    CHECK(r == -1);
    CHECK(errno == EINVAL);

    /* File must be unchanged. */
    uint64_t len;
    CHECK(bstack_len(bs, &len) == 0);
    CHECK(len == 3);

    bstack_close(bs); unlink(tmp);
    return 0;
}

static int test_peek_reads_from_offset_to_end(void)
{
    char tmp[64]; make_tmp(tmp, sizeof tmp);
    bstack_t *bs = bstack_open(tmp);
    CHECK(bs != NULL);

    CHECK(bstack_push(bs, (uint8_t *)"hello", 5, NULL) == 0);
    CHECK(bstack_push(bs, (uint8_t *)"world", 5, NULL) == 0);

    uint8_t buf[10]; size_t w;

    CHECK(bstack_peek(bs, 0, buf, &w) == 0);
    CHECK(w == 10);
    CHECK(memcmp(buf, "helloworld", 10) == 0);

    CHECK(bstack_peek(bs, 5, buf, &w) == 0);
    CHECK(w == 5);
    CHECK(memcmp(buf, "world", 5) == 0);

    bstack_close(bs); unlink(tmp);
    return 0;
}

static int test_peek_offset_exceeds_size_returns_error(void)
{
    char tmp[64]; make_tmp(tmp, sizeof tmp);
    bstack_t *bs = bstack_open(tmp);
    CHECK(bs != NULL);

    CHECK(bstack_push(bs, (uint8_t *)"hi", 2, NULL) == 0);

    uint8_t buf[4];
    int r = bstack_peek(bs, 3, buf, NULL);
    CHECK(r == -1);
    CHECK(errno == EINVAL);

    bstack_close(bs); unlink(tmp);
    return 0;
}

static int test_get_reads_half_open_range(void)
{
    char tmp[64]; make_tmp(tmp, sizeof tmp);
    bstack_t *bs = bstack_open(tmp);
    CHECK(bs != NULL);

    CHECK(bstack_push(bs, (uint8_t *)"hello", 5, NULL) == 0);
    CHECK(bstack_push(bs, (uint8_t *)"world", 5, NULL) == 0);

    uint8_t buf[5];
    CHECK(bstack_get(bs, 3, 8, buf) == 0);
    CHECK(memcmp(buf, "lowor", 5) == 0);

    bstack_close(bs); unlink(tmp);
    return 0;
}

/* =========================================================================
 * Range validation
 * ====================================================================== */

static int test_get_end_exceeds_size_returns_error(void)
{
    char tmp[64]; make_tmp(tmp, sizeof tmp);
    bstack_t *bs = bstack_open(tmp);
    CHECK(bs != NULL);

    CHECK(bstack_push(bs, (uint8_t *)"abc", 3, NULL) == 0);

    uint8_t buf[4];
    int r = bstack_get(bs, 0, 4, buf);
    CHECK(r == -1);
    CHECK(errno == EINVAL);

    bstack_close(bs); unlink(tmp);
    return 0;
}

static int test_get_end_less_than_start_returns_error(void)
{
    char tmp[64]; make_tmp(tmp, sizeof tmp);
    bstack_t *bs = bstack_open(tmp);
    CHECK(bs != NULL);

    CHECK(bstack_push(bs, (uint8_t *)"abc", 3, NULL) == 0);

    uint8_t buf[1];
    int r = bstack_get(bs, 2, 1, buf);
    CHECK(r == -1);
    CHECK(errno == EINVAL);

    bstack_close(bs); unlink(tmp);
    return 0;
}

static int test_get_does_not_modify_file(void)
{
    char tmp[64]; make_tmp(tmp, sizeof tmp);
    bstack_t *bs = bstack_open(tmp);
    CHECK(bs != NULL);

    CHECK(bstack_push(bs, (uint8_t *)"hello", 5, NULL) == 0);

    uint8_t buf[3];
    CHECK(bstack_get(bs, 1, 4, buf) == 0);

    /* Next push must start at offset 5, not somewhere corrupted. */
    uint64_t off;
    CHECK(bstack_push(bs, (uint8_t *)"!", 1, &off) == 0);
    CHECK(off == 5);

    uint64_t len;
    CHECK(bstack_len(bs, &len) == 0);
    CHECK(len == 6);

    bstack_close(bs); unlink(tmp);
    return 0;
}

/* =========================================================================
 * Persistence
 * ====================================================================== */

static int test_reopen_reads_back_correct_data(void)
{
    char tmp[64]; make_tmp(tmp, sizeof tmp);

    {
        bstack_t *bs = bstack_open(tmp);
        CHECK(bs != NULL);
        CHECK(bstack_push(bs, (uint8_t *)"persist", 7, NULL) == 0);
        bstack_close(bs);
    }

    {
        bstack_t *bs = bstack_open(tmp);
        CHECK(bs != NULL);

        uint64_t len;
        CHECK(bstack_len(bs, &len) == 0);
        CHECK(len == 7);

        uint8_t buf[7]; size_t w;
        CHECK(bstack_peek(bs, 0, buf, &w) == 0);
        CHECK(w == 7);
        CHECK(memcmp(buf, "persist", 7) == 0);

        bstack_close(bs);
    }

    unlink(tmp);
    return 0;
}

static int test_reopen_and_continue_pushing(void)
{
    char tmp[64]; make_tmp(tmp, sizeof tmp);

    {
        bstack_t *bs = bstack_open(tmp);
        CHECK(bs != NULL);
        CHECK(bstack_push(bs, (uint8_t *)"hello", 5, NULL) == 0);
        bstack_close(bs);
    }

    {
        bstack_t *bs = bstack_open(tmp);
        CHECK(bs != NULL);

        uint64_t off;
        CHECK(bstack_push(bs, (uint8_t *)"world", 5, &off) == 0);
        CHECK(off == 5);

        uint8_t buf[10]; size_t w;
        CHECK(bstack_peek(bs, 0, buf, &w) == 0);
        CHECK(w == 10);
        CHECK(memcmp(buf, "helloworld", 10) == 0);

        bstack_close(bs);
    }

    unlink(tmp);
    return 0;
}

static int test_reopen_after_pop_sees_truncated_file(void)
{
    char tmp[64]; make_tmp(tmp, sizeof tmp);

    {
        bstack_t *bs = bstack_open(tmp);
        CHECK(bs != NULL);
        CHECK(bstack_push(bs, (uint8_t *)"helloworld", 10, NULL) == 0);
        uint8_t buf[5];
        CHECK(bstack_pop(bs, 5, buf, NULL) == 0);
        bstack_close(bs);
    }

    {
        bstack_t *bs = bstack_open(tmp);
        CHECK(bs != NULL);

        uint64_t len;
        CHECK(bstack_len(bs, &len) == 0);
        CHECK(len == 5);

        bstack_close(bs);
    }

    unlink(tmp);
    return 0;
}

/* =========================================================================
 * Boundary / zero-value handling
 * ====================================================================== */

static int test_push_empty_slice(void)
{
    char tmp[64]; make_tmp(tmp, sizeof tmp);
    bstack_t *bs = bstack_open(tmp);
    CHECK(bs != NULL);

    CHECK(bstack_push(bs, (uint8_t *)"abc", 3, NULL) == 0);

    uint64_t off;
    CHECK(bstack_push(bs, (uint8_t *)"", 0, &off) == 0);
    CHECK(off == 3);  /* returns current end, not a new slot */

    uint64_t len;
    CHECK(bstack_len(bs, &len) == 0);
    CHECK(len == 3);

    bstack_close(bs); unlink(tmp);
    return 0;
}

static int test_pop_zero_bytes(void)
{
    char tmp[64]; make_tmp(tmp, sizeof tmp);
    bstack_t *bs = bstack_open(tmp);
    CHECK(bs != NULL);

    CHECK(bstack_push(bs, (uint8_t *)"abc", 3, NULL) == 0);

    uint8_t buf[1]; size_t w = 99;
    CHECK(bstack_pop(bs, 0, buf, &w) == 0);
    CHECK(w == 0);

    uint64_t len;
    CHECK(bstack_len(bs, &len) == 0);
    CHECK(len == 3);

    bstack_close(bs); unlink(tmp);
    return 0;
}

static int test_peek_at_end_offset_on_empty_file(void)
{
    char tmp[64]; make_tmp(tmp, sizeof tmp);
    bstack_t *bs = bstack_open(tmp);
    CHECK(bs != NULL);

    uint8_t buf[1]; size_t w = 99;
    CHECK(bstack_peek(bs, 0, buf, &w) == 0);
    CHECK(w == 0);

    bstack_close(bs); unlink(tmp);
    return 0;
}

static int test_get_zero_range_on_empty_file(void)
{
    char tmp[64]; make_tmp(tmp, sizeof tmp);
    bstack_t *bs = bstack_open(tmp);
    CHECK(bs != NULL);

    uint8_t buf[1];
    CHECK(bstack_get(bs, 0, 0, buf) == 0);

    bstack_close(bs); unlink(tmp);
    return 0;
}

static int test_drain_to_zero_then_push_starts_at_offset_zero(void)
{
    char tmp[64]; make_tmp(tmp, sizeof tmp);
    bstack_t *bs = bstack_open(tmp);
    CHECK(bs != NULL);

    CHECK(bstack_push(bs, (uint8_t *)"hello", 5, NULL) == 0);
    uint8_t buf[5];
    CHECK(bstack_pop(bs, 5, buf, NULL) == 0);

    uint64_t len;
    CHECK(bstack_len(bs, &len) == 0);
    CHECK(len == 0);

    uint64_t off;
    CHECK(bstack_push(bs, (uint8_t *)"new", 3, &off) == 0);
    CHECK(off == 0);

    bstack_close(bs); unlink(tmp);
    return 0;
}

/* =========================================================================
 * Data integrity
 * ====================================================================== */

static int test_peek_does_not_modify_file(void)
{
    char tmp[64]; make_tmp(tmp, sizeof tmp);
    bstack_t *bs = bstack_open(tmp);
    CHECK(bs != NULL);

    CHECK(bstack_push(bs, (uint8_t *)"hello", 5, NULL) == 0);
    uint8_t buf[5];
    CHECK(bstack_peek(bs, 0, buf, NULL) == 0);
    CHECK(bstack_peek(bs, 0, buf, NULL) == 0);

    /* Push must still go to offset 5. */
    uint64_t off;
    CHECK(bstack_push(bs, (uint8_t *)"!", 1, &off) == 0);
    CHECK(off == 5);

    bstack_close(bs); unlink(tmp);
    return 0;
}

static int test_binary_roundtrip_all_byte_values(void)
{
    char tmp[64]; make_tmp(tmp, sizeof tmp);
    bstack_t *bs = bstack_open(tmp);
    CHECK(bs != NULL);

    uint8_t all[256];
    for (int i = 0; i < 256; i++) all[i] = (uint8_t)i;

    CHECK(bstack_push(bs, all, 256, NULL) == 0);

    uint8_t out[256]; size_t w;
    CHECK(bstack_pop(bs, 256, out, &w) == 0);
    CHECK(w == 256);
    CHECK(memcmp(out, all, 256) == 0);

    bstack_close(bs); unlink(tmp);
    return 0;
}

static int test_large_payload_roundtrip(void)
{
    char tmp[64]; make_tmp(tmp, sizeof tmp);
    bstack_t *bs = bstack_open(tmp);
    CHECK(bs != NULL);

    const size_t MiB = 1024 * 1024;
    uint8_t *big = malloc(MiB);
    CHECK(big != NULL);
    for (size_t i = 0; i < MiB; i++) big[i] = (uint8_t)(i & 0xFF);

    CHECK(bstack_push(bs, big, MiB, NULL) == 0);

    uint8_t *out = malloc(MiB);
    CHECK(out != NULL);
    CHECK(bstack_get(bs, 0, MiB, out) == 0);
    CHECK(memcmp(out, big, MiB) == 0);

    free(big); free(out);
    bstack_close(bs); unlink(tmp);
    return 0;
}

/* =========================================================================
 * Header / magic
 * ====================================================================== */

static const uint8_t MAGIC[8]        = {'B','S','T','K', 0, 1, 1, 0};
static const uint8_t MAGIC_PREFIX[6] = {'B','S','T','K', 0, 1};

static int test_new_file_has_valid_header(void)
{
    char tmp[64]; make_tmp(tmp, sizeof tmp);
    bstack_t *bs = bstack_open(tmp);
    CHECK(bs != NULL);
    bstack_close(bs);

    int fd = open(tmp, O_RDONLY);
    CHECK(fd >= 0);

    struct stat st; fstat(fd, &st);
    CHECK(st.st_size == 16);

    uint8_t hdr[16];
    CHECK(pread(fd, hdr, 16, 0) == 16);
    CHECK(memcmp(hdr,     MAGIC,        8) == 0);
    CHECK(memcmp(hdr + 8, "\0\0\0\0\0\0\0\0", 8) == 0);

    close(fd); unlink(tmp);
    return 0;
}

static int test_header_clen_matches_after_pushes(void)
{
    char tmp[64]; make_tmp(tmp, sizeof tmp);
    bstack_t *bs = bstack_open(tmp);
    CHECK(bs != NULL);

    CHECK(bstack_push(bs, (uint8_t *)"hello", 5, NULL) == 0);
    CHECK(bstack_push(bs, (uint8_t *)"world", 5, NULL) == 0);
    bstack_close(bs);

    int fd = open(tmp, O_RDONLY);
    CHECK(fd >= 0);
    CHECK(raw_read_le64(fd, 8) == 10);
    close(fd); unlink(tmp);
    return 0;
}

static int test_header_clen_matches_after_pop(void)
{
    char tmp[64]; make_tmp(tmp, sizeof tmp);
    bstack_t *bs = bstack_open(tmp);
    CHECK(bs != NULL);

    CHECK(bstack_push(bs, (uint8_t *)"helloworld", 10, NULL) == 0);
    uint8_t buf[4];
    CHECK(bstack_pop(bs, 4, buf, NULL) == 0);
    bstack_close(bs);

    int fd = open(tmp, O_RDONLY);
    CHECK(fd >= 0);
    CHECK(raw_read_le64(fd, 8) == 6);
    close(fd); unlink(tmp);
    return 0;
}

static int test_open_rejects_bad_magic(void)
{
    char tmp[64]; make_tmp(tmp, sizeof tmp);

    int fd = open(tmp, O_WRONLY | O_CREAT | O_TRUNC, 0666);
    CHECK(fd >= 0);
    uint8_t garbage[16];
    memcpy(garbage, "GARBAGE!", 8);
    memset(garbage + 8, 0, 8);
    CHECK(write(fd, garbage, 16) == 16);
    close(fd);

    bstack_t *bs = bstack_open(tmp);
    CHECK(bs == NULL);
    CHECK(errno == EINVAL);

    unlink(tmp);
    return 0;
}

static int test_open_rejects_truncated_header(void)
{
    char tmp[64]; make_tmp(tmp, sizeof tmp);

    int fd = open(tmp, O_WRONLY | O_CREAT | O_TRUNC, 0666);
    CHECK(fd >= 0);
    /* Write only 6 bytes — valid prefix but far too short to be a header. */
    CHECK(write(fd, MAGIC_PREFIX, 6) == 6);
    close(fd);

    bstack_t *bs = bstack_open(tmp);
    CHECK(bs == NULL);
    CHECK(errno == EINVAL);

    unlink(tmp);
    return 0;
}

/* =========================================================================
 * Crash recovery
 * ====================================================================== */

static int test_recovery_truncates_partial_push(void)
{
    char tmp[64]; make_tmp(tmp, sizeof tmp);

    /* Commit "hello" (clen == 5, file == 16+5 == 21 bytes). */
    {
        bstack_t *bs = bstack_open(tmp);
        CHECK(bs != NULL);
        CHECK(bstack_push(bs, (uint8_t *)"hello", 5, NULL) == 0);
        bstack_close(bs);
    }

    /* Simulate a push that wrote 3 extra bytes but crashed before updating
     * the committed-length field in the header. */
    {
        int fd = open(tmp, O_WRONLY);
        CHECK(fd >= 0);
        CHECK(ftruncate(fd, 16 + 5 + 3) == 0);
        /* clen at offset 8 still says 5 — do NOT update it. */
        close(fd);
    }

    /* Reopen: recovery must truncate back to 16+5. */
    {
        bstack_t *bs = bstack_open(tmp);
        CHECK(bs != NULL);

        uint64_t len;
        CHECK(bstack_len(bs, &len) == 0);
        CHECK(len == 5);

        uint8_t buf[5]; size_t w;
        CHECK(bstack_pop(bs, 5, buf, &w) == 0);
        CHECK(memcmp(buf, "hello", 5) == 0);

        bstack_close(bs);
    }

    unlink(tmp);
    return 0;
}

static int test_recovery_repairs_header_after_partial_pop(void)
{
    char tmp[64]; make_tmp(tmp, sizeof tmp);

    /* Commit "helloworld" (clen == 10, file == 26 bytes). */
    {
        bstack_t *bs = bstack_open(tmp);
        CHECK(bs != NULL);
        CHECK(bstack_push(bs, (uint8_t *)"helloworld", 10, NULL) == 0);
        bstack_close(bs);
    }

    /* Simulate a pop that truncated the file to 16+5 but crashed before
     * writing the new committed length to the header. */
    {
        int fd = open(tmp, O_WRONLY);
        CHECK(fd >= 0);
        CHECK(ftruncate(fd, 16 + 5) == 0);
        /* clen at offset 8 still says 10 — do NOT update it. */
        close(fd);
    }

    /* Reopen: recovery must set clen = actual == 5. */
    {
        bstack_t *bs = bstack_open(tmp);
        CHECK(bs != NULL);

        uint64_t len;
        CHECK(bstack_len(bs, &len) == 0);
        CHECK(len == 5);

        uint8_t buf[5]; size_t w;
        CHECK(bstack_pop(bs, 5, buf, &w) == 0);
        CHECK(memcmp(buf, "hello", 5) == 0);

        bstack_close(bs);
    }

    unlink(tmp);
    return 0;
}

/* =========================================================================
 * Concurrency
 * ====================================================================== */

/* --- concurrent reads -------------------------------------------------- */

#define READ_THREADS 32
#define READ_ITERS   50

typedef struct {
    bstack_t      *bs;
    const uint8_t *expected; /* 64 bytes */
    int            ok;
} reader_arg_t;

static void *concurrent_reader(void *raw)
{
    reader_arg_t *a = raw;
    a->ok = 1;
    uint8_t buf[64];

    for (int i = 0; i < READ_ITERS; i++) {
        size_t w;
        if (bstack_peek(a->bs, 0, buf, &w) != 0 || w != 64 ||
            memcmp(buf, a->expected, 64) != 0) {
            a->ok = 0; return NULL;
        }
        if (bstack_get(a->bs, 8, 16, buf) != 0 ||
            memcmp(buf, a->expected + 8, 8) != 0) {
            a->ok = 0; return NULL;
        }
    }
    return NULL;
}

static int test_concurrent_reads_do_not_serialise(void)
{
    char tmp[64]; make_tmp(tmp, sizeof tmp);
    bstack_t *bs = bstack_open(tmp);
    CHECK(bs != NULL);

    uint8_t expected[64];
    for (int i = 0; i < 8; i++) {
        uint8_t rec[8];
        for (int j = 0; j < 8; j++) rec[j] = (uint8_t)(i * 8 + j);
        memcpy(expected + i * 8, rec, 8);
        CHECK(bstack_push(bs, rec, 8, NULL) == 0);
    }

    pthread_t threads[READ_THREADS];
    reader_arg_t args[READ_THREADS];
    for (int i = 0; i < READ_THREADS; i++) {
        args[i] = (reader_arg_t){ .bs = bs, .expected = expected, .ok = 1 };
        pthread_create(&threads[i], NULL, concurrent_reader, &args[i]);
    }
    for (int i = 0; i < READ_THREADS; i++) pthread_join(threads[i], NULL);
    for (int i = 0; i < READ_THREADS; i++) CHECK(args[i].ok);

    bstack_close(bs); unlink(tmp);
    return 0;
}

/* --- concurrent pushes ------------------------------------------------- */

#define PUSH_THREADS 8
#define PUSH_COUNT   100
#define RECORD_SIZE  16

typedef struct {
    bstack_t *bs;
    int       id;
    uint64_t  offsets[PUSH_COUNT];
} push_arg_t;

static void *push_worker(void *raw)
{
    push_arg_t *a = raw;
    for (int i = 0; i < PUSH_COUNT; i++) {
        uint8_t rec[RECORD_SIZE];
        memset(rec, 0, RECORD_SIZE);
        rec[0] = (uint8_t)a->id;
        rec[1] = (uint8_t)i;
        if (bstack_push(a->bs, rec, RECORD_SIZE, &a->offsets[i]) != 0)
            a->offsets[i] = (uint64_t)-1;
    }
    return NULL;
}

static int test_concurrent_pushes_non_overlapping(void)
{
    char tmp[64]; make_tmp(tmp, sizeof tmp);
    bstack_t *bs = bstack_open(tmp);
    CHECK(bs != NULL);

    pthread_t  threads[PUSH_THREADS];
    push_arg_t args[PUSH_THREADS];
    for (int i = 0; i < PUSH_THREADS; i++) {
        args[i].bs = bs;
        args[i].id = i;
        pthread_create(&threads[i], NULL, push_worker, &args[i]);
    }
    for (int i = 0; i < PUSH_THREADS; i++) pthread_join(threads[i], NULL);

    /* Total length must be exact. */
    uint64_t len;
    CHECK(bstack_len(bs, &len) == 0);
    CHECK(len == (uint64_t)(PUSH_THREADS * PUSH_COUNT * RECORD_SIZE));

    /* Every offset must be a valid record boundary and unique. */
    for (int i = 0; i < PUSH_THREADS; i++) {
        for (int j = 0; j < PUSH_COUNT; j++) {
            uint64_t off = args[i].offsets[j];
            CHECK(off != (uint64_t)-1);
            CHECK(off % RECORD_SIZE == 0);
            /* Uniqueness: compare against all later (i,j) pairs. */
            for (int k = i; k < PUSH_THREADS; k++) {
                int sl = (k == i) ? j + 1 : 0;
                for (int l = sl; l < PUSH_COUNT; l++)
                    CHECK(off != args[k].offsets[l]);
            }
        }
    }

    /* Data integrity: each record must contain the right thread/index. */
    for (int i = 0; i < PUSH_THREADS; i++) {
        for (int j = 0; j < PUSH_COUNT; j++) {
            uint64_t off = args[i].offsets[j];
            uint8_t rec[RECORD_SIZE];
            CHECK(bstack_get(bs, off, off + RECORD_SIZE, rec) == 0);
            CHECK(rec[0] == (uint8_t)args[i].id);
            CHECK(rec[1] == (uint8_t)j);
        }
    }

    bstack_close(bs); unlink(tmp);
    return 0;
}

/* --- concurrent len is a multiple of item size ------------------------- */

#define LEN_PUSH_THREADS 4
#define LEN_PUSH_COUNT   200
#define LEN_ITEM_SIZE    8
#define LEN_READ_COUNT   2000

typedef struct {
    bstack_t *bs;
    int       ok;
} len_reader_arg_t;

static void *len_reader(void *raw)
{
    len_reader_arg_t *a = raw;
    a->ok = 1;
    for (int i = 0; i < LEN_READ_COUNT; i++) {
        uint64_t l;
        if (bstack_len(a->bs, &l) != 0 || l % LEN_ITEM_SIZE != 0) {
            a->ok = 0; return NULL;
        }
    }
    return NULL;
}

static void *len_pusher(void *raw)
{
    bstack_t *bs = raw;
    uint8_t item[LEN_ITEM_SIZE];
    memset(item, 0xAB, LEN_ITEM_SIZE);
    for (int i = 0; i < LEN_PUSH_COUNT; i++)
        bstack_push(bs, item, LEN_ITEM_SIZE, NULL);
    return NULL;
}

static int test_concurrent_len_is_multiple_of_item_size(void)
{
    char tmp[64]; make_tmp(tmp, sizeof tmp);
    bstack_t *bs = bstack_open(tmp);
    CHECK(bs != NULL);

    pthread_t push_threads[LEN_PUSH_THREADS];
    pthread_t reader;
    len_reader_arg_t rarg = { .bs = bs, .ok = 1 };

    pthread_create(&reader, NULL, len_reader, &rarg);
    for (int i = 0; i < LEN_PUSH_THREADS; i++)
        pthread_create(&push_threads[i], NULL, len_pusher, bs);

    for (int i = 0; i < LEN_PUSH_THREADS; i++)
        pthread_join(push_threads[i], NULL);
    pthread_join(reader, NULL);

    CHECK(rarg.ok);

    uint64_t final_len;
    CHECK(bstack_len(bs, &final_len) == 0);
    CHECK(final_len == (uint64_t)(LEN_PUSH_THREADS * LEN_PUSH_COUNT * LEN_ITEM_SIZE));

    bstack_close(bs); unlink(tmp);
    return 0;
}

/* =========================================================================
 * Interleaved push / pop
 * ====================================================================== */

static int test_interleaved_push_pop_correct_state(void)
{
    char tmp[64]; make_tmp(tmp, sizeof tmp);
    bstack_t *bs = bstack_open(tmp);
    CHECK(bs != NULL);

    uint64_t off0, off1, off2;
    CHECK(bstack_push(bs, (uint8_t *)"AAAA", 4, &off0) == 0);  CHECK(off0 == 0);
    CHECK(bstack_push(bs, (uint8_t *)"BBBB", 4, &off1) == 0);  CHECK(off1 == 4);

    uint8_t pop1[4]; size_t w;
    CHECK(bstack_pop(bs, 4, pop1, &w) == 0);
    CHECK(w == 4);
    CHECK(memcmp(pop1, "BBBB", 4) == 0);

    CHECK(bstack_push(bs, (uint8_t *)"CCCC", 4, &off2) == 0);  CHECK(off2 == 4);

    uint8_t pop2[8];
    CHECK(bstack_pop(bs, 8, pop2, &w) == 0);
    CHECK(w == 8);
    CHECK(memcmp(pop2, "AAAACCCC", 8) == 0);

    uint64_t len;
    CHECK(bstack_len(bs, &len) == 0);
    CHECK(len == 0);

    bstack_close(bs); unlink(tmp);
    return 0;
}

/* =========================================================================
 * bstack_set  (compiled only with -DBSTACK_FEATURE_SET)
 * ====================================================================== */

#ifdef BSTACK_FEATURE_SET

static int test_set_overwrites_middle_bytes(void)
{
    char tmp[64]; make_tmp(tmp, sizeof tmp);
    bstack_t *bs = bstack_open(tmp);
    CHECK(bs != NULL);

    CHECK(bstack_push(bs, (uint8_t *)"helloworld", 10, NULL) == 0);
    CHECK(bstack_set(bs, 5, (uint8_t *)"WORLD", 5) == 0);

    uint8_t buf[10]; size_t w;
    CHECK(bstack_peek(bs, 0, buf, &w) == 0);
    CHECK(w == 10);
    CHECK(memcmp(buf, "helloWORLD", 10) == 0);

    bstack_close(bs); unlink(tmp);
    return 0;
}

static int test_set_at_start(void)
{
    char tmp[64]; make_tmp(tmp, sizeof tmp);
    bstack_t *bs = bstack_open(tmp);
    CHECK(bs != NULL);

    CHECK(bstack_push(bs, (uint8_t *)"abcde", 5, NULL) == 0);
    CHECK(bstack_set(bs, 0, (uint8_t *)"XY", 2) == 0);

    uint8_t buf[5]; size_t w;
    CHECK(bstack_peek(bs, 0, buf, &w) == 0);
    CHECK(memcmp(buf, "XYcde", 5) == 0);

    bstack_close(bs); unlink(tmp);
    return 0;
}

static int test_set_at_exact_end_boundary(void)
{
    char tmp[64]; make_tmp(tmp, sizeof tmp);
    bstack_t *bs = bstack_open(tmp);
    CHECK(bs != NULL);

    CHECK(bstack_push(bs, (uint8_t *)"abcde", 5, NULL) == 0);
    /* Write 2 bytes ending exactly at the last byte. */
    CHECK(bstack_set(bs, 3, (uint8_t *)"ZZ", 2) == 0);

    uint8_t buf[5]; size_t w;
    CHECK(bstack_peek(bs, 0, buf, &w) == 0);
    CHECK(memcmp(buf, "abcZZ", 5) == 0);

    bstack_close(bs); unlink(tmp);
    return 0;
}

static int test_set_empty_slice_is_noop(void)
{
    char tmp[64]; make_tmp(tmp, sizeof tmp);
    bstack_t *bs = bstack_open(tmp);
    CHECK(bs != NULL);

    CHECK(bstack_push(bs, (uint8_t *)"hello", 5, NULL) == 0);
    CHECK(bstack_set(bs, 0, (uint8_t *)"", 0) == 0);

    uint8_t buf[5]; size_t w;
    CHECK(bstack_peek(bs, 0, buf, &w) == 0);
    CHECK(memcmp(buf, "hello", 5) == 0);

    bstack_close(bs); unlink(tmp);
    return 0;
}

static int test_set_does_not_change_file_size(void)
{
    char tmp[64]; make_tmp(tmp, sizeof tmp);
    bstack_t *bs = bstack_open(tmp);
    CHECK(bs != NULL);

    CHECK(bstack_push(bs, (uint8_t *)"hello", 5, NULL) == 0);
    CHECK(bstack_set(bs, 1, (uint8_t *)"ELL", 3) == 0);

    uint64_t len;
    CHECK(bstack_len(bs, &len) == 0);
    CHECK(len == 5);

    bstack_close(bs); unlink(tmp);
    return 0;
}

static int test_set_rejects_write_past_end(void)
{
    char tmp[64]; make_tmp(tmp, sizeof tmp);
    bstack_t *bs = bstack_open(tmp);
    CHECK(bs != NULL);

    CHECK(bstack_push(bs, (uint8_t *)"hello", 5, NULL) == 0);

    int r = bstack_set(bs, 3, (uint8_t *)"XXX", 3); /* 3+3=6 > 5 */
    CHECK(r == -1);
    CHECK(errno == EINVAL);

    bstack_close(bs); unlink(tmp);
    return 0;
}

static int test_set_persists_across_reopen(void)
{
    char tmp[64]; make_tmp(tmp, sizeof tmp);

    {
        bstack_t *bs = bstack_open(tmp);
        CHECK(bs != NULL);
        CHECK(bstack_push(bs, (uint8_t *)"hello", 5, NULL) == 0);
        CHECK(bstack_set(bs, 0, (uint8_t *)"HELLO", 5) == 0);
        bstack_close(bs);
    }

    {
        bstack_t *bs = bstack_open(tmp);
        CHECK(bs != NULL);
        uint8_t buf[5]; size_t w;
        CHECK(bstack_peek(bs, 0, buf, &w) == 0);
        CHECK(memcmp(buf, "HELLO", 5) == 0);
        bstack_close(bs);
    }

    unlink(tmp);
    return 0;
}

#endif /* BSTACK_FEATURE_SET */

/* =========================================================================
 * main
 * ====================================================================== */

int main(void)
{
    /* Functional */
    T(test_push_returns_correct_offsets);
    T(test_pop_returns_correct_bytes_and_shrinks);
    T(test_pop_across_push_boundary);
    T(test_pop_on_empty_file_returns_error);
    T(test_pop_n_exceeds_size_returns_error);
    T(test_peek_reads_from_offset_to_end);
    T(test_peek_offset_exceeds_size_returns_error);
    T(test_get_reads_half_open_range);

    /* Range validation */
    T(test_get_end_exceeds_size_returns_error);
    T(test_get_end_less_than_start_returns_error);
    T(test_get_does_not_modify_file);

    /* Persistence */
    T(test_reopen_reads_back_correct_data);
    T(test_reopen_and_continue_pushing);
    T(test_reopen_after_pop_sees_truncated_file);

    /* Boundary / zero */
    T(test_push_empty_slice);
    T(test_pop_zero_bytes);
    T(test_peek_at_end_offset_on_empty_file);
    T(test_get_zero_range_on_empty_file);
    T(test_drain_to_zero_then_push_starts_at_offset_zero);

    /* Data integrity */
    T(test_peek_does_not_modify_file);
    T(test_binary_roundtrip_all_byte_values);
    T(test_large_payload_roundtrip);

    /* Header / magic */
    T(test_new_file_has_valid_header);
    T(test_header_clen_matches_after_pushes);
    T(test_header_clen_matches_after_pop);
    T(test_open_rejects_bad_magic);
    T(test_open_rejects_truncated_header);

    /* Crash recovery */
    T(test_recovery_truncates_partial_push);
    T(test_recovery_repairs_header_after_partial_pop);

    /* Concurrency */
    T(test_concurrent_reads_do_not_serialise);
    T(test_concurrent_pushes_non_overlapping);
    T(test_concurrent_len_is_multiple_of_item_size);

    /* Interleaved */
    T(test_interleaved_push_pop_correct_state);

#ifdef BSTACK_FEATURE_SET
    /* bstack_set */
    T(test_set_overwrites_middle_bytes);
    T(test_set_at_start);
    T(test_set_at_exact_end_boundary);
    T(test_set_empty_slice_is_noop);
    T(test_set_does_not_change_file_size);
    T(test_set_rejects_write_past_end);
    T(test_set_persists_across_reopen);
#endif

    printf("\n%d/%d passed\n", g_passed, g_total);
    return (g_passed == g_total) ? 0 : 1;
}