bstack 0.1.7

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
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
/* Expose POSIX + BSD extensions on non-Windows platforms.
 * _DARWIN_C_SOURCE is defined unconditionally on non-Windows: on real macOS
 * it overrides _POSIX_C_SOURCE restrictions to keep fdatasync/flock visible;
 * on Linux/glibc it is ignored.  This also handles clang cross-compilation
 * that falls back to macOS SDK headers when no Linux sysroot is available.
 * On Windows (_WIN32) these macros are skipped and Win32 APIs are used
 * instead. */
#ifndef _WIN32
#  define _DARWIN_C_SOURCE
#  define _DEFAULT_SOURCE
#  define _POSIX_C_SOURCE 200809L
#  define _XOPEN_SOURCE 700
#endif

#include "bstack.h"

#include <errno.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>

#ifdef _WIN32
#  define WIN32_LEAN_AND_MEAN
#  include <windows.h>
#else
#  include <fcntl.h>
#  include <pthread.h>
#  include <sys/file.h>
#  include <sys/stat.h>
#  include <unistd.h>
#endif

/* -------------------------------------------------------------------------
 * Constants
 * ---------------------------------------------------------------------- */

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

/* -------------------------------------------------------------------------
 * Platform file handle type
 * ---------------------------------------------------------------------- */

#ifdef _WIN32
typedef HANDLE bstack_fd_t;
#else
typedef int    bstack_fd_t;
#endif

/* -------------------------------------------------------------------------
 * Internal struct
 * ---------------------------------------------------------------------- */

struct bstack {
    bstack_fd_t fd;
#ifdef _WIN32
    SRWLOCK          lock;
#else
    pthread_rwlock_t lock;
#endif
};

/* =========================================================================
 * Platform layer — Windows
 * ====================================================================== */

#ifdef _WIN32

/* Map the most recent Windows error to an errno value. */
static void win_set_errno(void)
{
    switch (GetLastError()) {
        case ERROR_ACCESS_DENIED:
        case ERROR_SHARING_VIOLATION:   errno = EACCES;      break;
        case ERROR_FILE_NOT_FOUND:
        case ERROR_PATH_NOT_FOUND:      errno = ENOENT;      break;
        case ERROR_NOT_ENOUGH_MEMORY:
        case ERROR_OUTOFMEMORY:         errno = ENOMEM;      break;
        case ERROR_LOCK_VIOLATION:      errno = EWOULDBLOCK; break;
        case ERROR_INVALID_HANDLE:      errno = EBADF;       break;
        default:                        errno = EIO;         break;
    }
}

static int plat_durable_sync(bstack_fd_t h)
{
    if (!FlushFileBuffers(h)) { win_set_errno(); return -1; }
    return 0;
}

static int plat_file_size(bstack_fd_t h, uint64_t *out)
{
    LARGE_INTEGER li;
    if (!GetFileSizeEx(h, &li)) { win_set_errno(); return -1; }
    *out = (uint64_t)li.QuadPart;
    return 0;
}

/*
 * Positional write via OVERLAPPED — does not advance the file pointer.
 * The file is extended automatically if offset + count exceeds its size.
 */
static int plat_pwrite(bstack_fd_t h, const void *buf, size_t count,
                       uint64_t offset)
{
    if (count == 0) return 0;
    if (count > (size_t)MAXDWORD) { errno = EINVAL; return -1; }
    OVERLAPPED ov;
    memset(&ov, 0, sizeof ov);
    ov.Offset     = (DWORD)(offset & 0xFFFFFFFFU);
    ov.OffsetHigh = (DWORD)(offset >> 32);
    DWORD nw = 0;
    if (!WriteFile(h, buf, (DWORD)count, &nw, &ov)) { win_set_errno(); return -1; }
    if (nw != (DWORD)count) { errno = EIO; return -1; }
    return 0;
}

/* Positional read via OVERLAPPED — does not advance the file pointer. */
static int plat_pread(bstack_fd_t h, void *buf, size_t count,
                      uint64_t offset)
{
    if (count == 0) return 0;
    if (count > (size_t)MAXDWORD) { errno = EINVAL; return -1; }
    OVERLAPPED ov;
    memset(&ov, 0, sizeof ov);
    ov.Offset     = (DWORD)(offset & 0xFFFFFFFFU);
    ov.OffsetHigh = (DWORD)(offset >> 32);
    DWORD nr = 0;
    if (!ReadFile(h, buf, (DWORD)count, &nr, &ov)) { win_set_errno(); return -1; }
    if (nr != (DWORD)count) { errno = EIO; return -1; }
    return 0;
}

/* Truncate (or extend) the file to exactly `size` bytes. */
static int plat_ftruncate(bstack_fd_t h, uint64_t size)
{
    LARGE_INTEGER li;
    li.QuadPart = (LONGLONG)size;
    if (!SetFilePointerEx(h, li, NULL, FILE_BEGIN)) { win_set_errno(); return -1; }
    if (!SetEndOfFile(h)) { win_set_errno(); return -1; }
    return 0;
}

/* =========================================================================
 * Platform layer — Unix
 * ====================================================================== */

#else /* !_WIN32 */

static int plat_durable_sync(bstack_fd_t fd)
{
#  ifdef __APPLE__
    if (fcntl(fd, F_FULLFSYNC) == 0)
        return 0;
    /* Device does not support F_FULLFSYNC — fall back to fdatasync. */
#  endif
    return fdatasync(fd);
}

static int plat_file_size(bstack_fd_t fd, uint64_t *out)
{
    struct stat st;
    if (fstat(fd, &st) != 0) return -1;
    *out = (uint64_t)st.st_size;
    return 0;
}

static int plat_pwrite(bstack_fd_t fd, const void *buf, size_t count,
                       uint64_t offset)
{
    if (count == 0) return 0;
    ssize_t r = pwrite(fd, buf, count, (off_t)offset);
    if (r < 0) return -1;
    if ((size_t)r != count) { errno = EIO; return -1; }
    return 0;
}

static int plat_pread(bstack_fd_t fd, void *buf, size_t count,
                      uint64_t offset)
{
    if (count == 0) return 0;
    ssize_t r = pread(fd, buf, count, (off_t)offset);
    if (r < 0) return -1;
    if ((size_t)r != count) { errno = EIO; return -1; }
    return 0;
}

static int plat_ftruncate(bstack_fd_t fd, uint64_t size)
{
    return ftruncate(fd, (off_t)size);
}

#endif /* _WIN32 */

/* -------------------------------------------------------------------------
 * Close helper (releases advisory lock on both platforms)
 * ---------------------------------------------------------------------- */

static void close_fd(bstack_fd_t fd)
{
#ifdef _WIN32
    CloseHandle(fd);
#else
    close(fd);
#endif
}

/* -------------------------------------------------------------------------
 * Lock / unlock macros (reader–writer lock, cross-platform)
 * ---------------------------------------------------------------------- */

#ifdef _WIN32
#  define BS_RDLOCK(bs)    AcquireSRWLockShared(&(bs)->lock)
#  define BS_WRLOCK(bs)    AcquireSRWLockExclusive(&(bs)->lock)
#  define BS_RDUNLOCK(bs)  ReleaseSRWLockShared(&(bs)->lock)
#  define BS_WRUNLOCK(bs)  ReleaseSRWLockExclusive(&(bs)->lock)
#else
#  define BS_RDLOCK(bs)    pthread_rwlock_rdlock(&(bs)->lock)
#  define BS_WRLOCK(bs)    pthread_rwlock_wrlock(&(bs)->lock)
#  define BS_RDUNLOCK(bs)  pthread_rwlock_unlock(&(bs)->lock)
#  define BS_WRUNLOCK(bs)  pthread_rwlock_unlock(&(bs)->lock)
#endif

/* -------------------------------------------------------------------------
 * Little-endian helpers (positional — no cursor side-effects)
 * ---------------------------------------------------------------------- */

static int write_le64(bstack_fd_t fd, uint64_t file_offset, uint64_t val)
{
    uint8_t buf[8];
    for (int i = 0; i < 8; i++)
        buf[i] = (uint8_t)(val >> (8 * i));
    return plat_pwrite(fd, buf, 8, file_offset);
}

/* -------------------------------------------------------------------------
 * Header helpers
 * ---------------------------------------------------------------------- */

static int write_committed_len(bstack_fd_t fd, uint64_t len)
{
    return write_le64(fd, 8, len);
}

static int init_header(bstack_fd_t fd)
{
    uint8_t hdr[16];
    memcpy(hdr, MAGIC, 8);
    memset(hdr + 8, 0, 8);
    return plat_pwrite(fd, hdr, 16, 0);
}

/* Validates magic prefix and returns committed payload length via *out_clen.
 * Sets errno = EINVAL on bad magic or short header read. */
static int read_header(bstack_fd_t fd, uint64_t *out_clen)
{
    uint8_t hdr[16];
    if (plat_pread(fd, hdr, 16, 0) != 0) {
        errno = EINVAL;
        return -1;
    }
    if (memcmp(hdr, MAGIC_PREFIX, 6) != 0) {
        errno = EINVAL;
        return -1;
    }
    uint64_t clen = 0;
    for (int i = 0; i < 8; i++)
        clen |= (uint64_t)hdr[8 + i] << (8 * i);
    *out_clen = clen;
    return 0;
}

/* -------------------------------------------------------------------------
 * File size helper
 * ---------------------------------------------------------------------- */

static int file_size(bstack_fd_t fd, uint64_t *out)
{
    return plat_file_size(fd, out);
}

#ifdef __cplusplus
extern "C" {
#endif

/* -------------------------------------------------------------------------
 * bstack_open
 * ---------------------------------------------------------------------- */

bstack_t *bstack_open(const char *path)
{
#ifdef _WIN32
    HANDLE fd = CreateFileA(path,
                            GENERIC_READ | GENERIC_WRITE,
                            FILE_SHARE_READ | FILE_SHARE_WRITE,
                            NULL,
                            OPEN_ALWAYS,
                            FILE_ATTRIBUTE_NORMAL,
                            NULL);
    if (fd == INVALID_HANDLE_VALUE) {
        win_set_errno();
        return NULL;
    }
    /* Exclusive non-blocking advisory lock over the entire file. */
    {
        OVERLAPPED ov_lock;
        memset(&ov_lock, 0, sizeof ov_lock);
        if (!LockFileEx(fd,
                        LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY,
                        0, MAXDWORD, MAXDWORD, &ov_lock)) {
            DWORD err = GetLastError();
            CloseHandle(fd);
            errno = (err == ERROR_LOCK_VIOLATION) ? EWOULDBLOCK : EIO;
            return NULL;
        }
    }
#else
    int fd = open(path, O_RDWR | O_CREAT, 0666);
    if (fd < 0)
        return NULL;

    /* Exclusive non-blocking advisory lock. */
    if (flock(fd, LOCK_EX | LOCK_NB) != 0) {
        int saved = errno;
        close(fd);
        errno = saved;
        return NULL;
    }
#endif

    uint64_t raw_size;
    if (file_size(fd, &raw_size) != 0) {
        int saved = errno;
        close_fd(fd);
        errno = saved;
        return NULL;
    }

    if (raw_size == 0) {
        /* New file — write header and sync. */
        if (init_header(fd) != 0 || plat_durable_sync(fd) != 0) {
            int saved = errno;
            close_fd(fd);
            errno = saved;
            return NULL;
        }
    } else if (raw_size < HEADER_SIZE) {
        close_fd(fd);
        errno = EINVAL;
        return NULL;
    } else {
        /* Existing file — validate header and crash-recover if needed. */
        uint64_t clen;
        if (read_header(fd, &clen) != 0) {
            int saved = errno;
            close_fd(fd);
            errno = saved;
            return NULL;
        }

        uint64_t actual = raw_size - HEADER_SIZE;
        if (actual != clen) {
            uint64_t correct = (clen < actual) ? clen : actual;
            if (plat_ftruncate(fd, HEADER_SIZE + correct) != 0 ||
                write_committed_len(fd, correct) != 0 ||
                plat_durable_sync(fd) != 0)
            {
                int saved = errno;
                close_fd(fd);
                errno = saved;
                return NULL;
            }
        }
    }

    bstack_t *bs = malloc(sizeof(bstack_t));
    if (!bs) {
        close_fd(fd);
        return NULL;
    }
    bs->fd = fd;
#ifdef _WIN32
    InitializeSRWLock(&bs->lock);
#else
    if (pthread_rwlock_init(&bs->lock, NULL) != 0) {
        free(bs);
        close(fd);
        errno = ENOMEM;
        return NULL;
    }
#endif
    return bs;
}

/* -------------------------------------------------------------------------
 * bstack_close
 * ---------------------------------------------------------------------- */

void bstack_close(bstack_t *bs)
{
    if (!bs)
        return;
#ifndef _WIN32
    pthread_rwlock_destroy(&bs->lock);
#endif
    close_fd(bs->fd); /* also releases the advisory lock */
    free(bs);
}

/* -------------------------------------------------------------------------
 * bstack_push
 * ---------------------------------------------------------------------- */

int bstack_push(bstack_t *bs, const uint8_t *data, size_t len,
                uint64_t *out_offset)
{
    BS_WRLOCK(bs);

    uint64_t raw_size;
    if (file_size(bs->fd, &raw_size) != 0)
        goto fail_unlock;

    uint64_t logical_offset = raw_size - HEADER_SIZE;

    if (len == 0) {
        BS_WRUNLOCK(bs);
        if (out_offset)
            *out_offset = logical_offset;
        return 0;
    }

    /* Write payload at end of file. */
    if (plat_pwrite(bs->fd, data, len, raw_size) != 0) {
        /* Best-effort rollback: truncate any partial write. */
        plat_ftruncate(bs->fd, raw_size);
        goto fail_unlock;
    }

    uint64_t new_len = logical_offset + (uint64_t)len;
    if (write_committed_len(bs->fd, new_len) != 0 ||
        plat_durable_sync(bs->fd) != 0)
    {
        /* Rollback: remove written data and reset committed length. */
        plat_ftruncate(bs->fd, raw_size);
        write_committed_len(bs->fd, logical_offset);
        goto fail_unlock;
    }

    BS_WRUNLOCK(bs);
    if (out_offset)
        *out_offset = logical_offset;
    return 0;

fail_unlock:
    {
        int saved = errno;
        BS_WRUNLOCK(bs);
        errno = saved;
    }
    return -1;
}

/* -------------------------------------------------------------------------
 * bstack_extend
 * ---------------------------------------------------------------------- */

int bstack_extend(bstack_t *bs, size_t n, uint64_t *out_offset)
{
    BS_WRLOCK(bs);

    uint64_t raw_size;
    if (file_size(bs->fd, &raw_size) != 0)
        goto fail_unlock;

    uint64_t logical_offset = raw_size - HEADER_SIZE;

    if (n == 0) {
        BS_WRUNLOCK(bs);
        if (out_offset)
            *out_offset = logical_offset;
        return 0;
    }

    /* Extend the file; the OS will zero-fill the new space. */
    uint64_t new_raw_size = raw_size + (uint64_t)n;
    if (plat_ftruncate(bs->fd, new_raw_size) != 0)
        goto fail_unlock;

    uint64_t new_len = logical_offset + (uint64_t)n;
    if (write_committed_len(bs->fd, new_len) != 0 ||
        plat_durable_sync(bs->fd) != 0)
    {
        /* Rollback: truncate and reset committed length. */
        plat_ftruncate(bs->fd, raw_size);
        write_committed_len(bs->fd, logical_offset);
        goto fail_unlock;
    }

    BS_WRUNLOCK(bs);
    if (out_offset)
        *out_offset = logical_offset;
    return 0;

fail_unlock:
    {
        int saved = errno;
        BS_WRUNLOCK(bs);
        errno = saved;
    }
    return -1;
}

/* -------------------------------------------------------------------------
 * bstack_pop
 * ---------------------------------------------------------------------- */

int bstack_pop(bstack_t *bs, size_t n,
               uint8_t *buf, size_t *written_out)
{
    BS_WRLOCK(bs);

    uint64_t raw_size;
    if (file_size(bs->fd, &raw_size) != 0)
        goto fail_unlock;

    uint64_t data_size = raw_size - HEADER_SIZE;
    if ((uint64_t)n > data_size) {
        BS_WRUNLOCK(bs);
        errno = EINVAL;
        return -1;
    }

    uint64_t new_len = data_size - (uint64_t)n;
    uint64_t read_offset = HEADER_SIZE + new_len;

    /* Read the bytes to be removed before truncating. */
    if (n > 0) {
        if (plat_pread(bs->fd, buf, n, read_offset) != 0)
            goto fail_unlock;
    }

    if (plat_ftruncate(bs->fd, HEADER_SIZE + new_len) != 0 ||
        write_committed_len(bs->fd, new_len) != 0 ||
        plat_durable_sync(bs->fd) != 0)
        goto fail_unlock;

    BS_WRUNLOCK(bs);
    if (written_out)
        *written_out = n;
    return 0;

fail_unlock:
    {
        int saved = errno;
        BS_WRUNLOCK(bs);
        errno = saved;
    }
    return -1;
}

/* -------------------------------------------------------------------------
 * bstack_peek
 * ---------------------------------------------------------------------- */

int bstack_peek(bstack_t *bs, uint64_t offset,
                uint8_t *buf, size_t *written_out)
{
    BS_RDLOCK(bs);

    uint64_t raw_size;
    if (file_size(bs->fd, &raw_size) != 0)
        goto fail_unlock;

    uint64_t data_size = raw_size - HEADER_SIZE;
    if (offset > data_size) {
        BS_RDUNLOCK(bs);
        errno = EINVAL;
        return -1;
    }

    size_t to_read = (size_t)(data_size - offset);
    if (to_read > 0) {
        if (plat_pread(bs->fd, buf, to_read, HEADER_SIZE + offset) != 0)
            goto fail_unlock;
    }

    BS_RDUNLOCK(bs);
    if (written_out)
        *written_out = to_read;
    return 0;

fail_unlock:
    {
        int saved = errno;
        BS_RDUNLOCK(bs);
        errno = saved;
    }
    return -1;
}

/* -------------------------------------------------------------------------
 * bstack_get
 * ---------------------------------------------------------------------- */

int bstack_get(bstack_t *bs, uint64_t start, uint64_t end,
               uint8_t *buf)
{
    if (end < start) {
        errno = EINVAL;
        return -1;
    }

    BS_RDLOCK(bs);

    uint64_t raw_size;
    if (file_size(bs->fd, &raw_size) != 0)
        goto fail_unlock;

    uint64_t data_size = raw_size - HEADER_SIZE;
    if (end > data_size) {
        BS_RDUNLOCK(bs);
        errno = EINVAL;
        return -1;
    }

    size_t to_read = (size_t)(end - start);
    if (to_read > 0) {
        if (plat_pread(bs->fd, buf, to_read, HEADER_SIZE + start) != 0)
            goto fail_unlock;
    }

    BS_RDUNLOCK(bs);
    return 0;

fail_unlock:
    {
        int saved = errno;
        BS_RDUNLOCK(bs);
        errno = saved;
    }
    return -1;
}

/* -------------------------------------------------------------------------
 * bstack_discard
 * ---------------------------------------------------------------------- */

int bstack_discard(bstack_t *bs, size_t n)
{
    if (n == 0)
        return 0;

    BS_WRLOCK(bs);

    uint64_t raw_size;
    if (file_size(bs->fd, &raw_size) != 0)
        goto fail_unlock;

    uint64_t data_size = raw_size - HEADER_SIZE;
    if ((uint64_t)n > data_size) {
        BS_WRUNLOCK(bs);
        errno = EINVAL;
        return -1;
    }

    uint64_t new_len = data_size - (uint64_t)n;

    if (plat_ftruncate(bs->fd, HEADER_SIZE + new_len) != 0 ||
        write_committed_len(bs->fd, new_len) != 0 ||
        plat_durable_sync(bs->fd) != 0)
        goto fail_unlock;

    BS_WRUNLOCK(bs);
    return 0;

fail_unlock:
    {
        int saved = errno;
        BS_WRUNLOCK(bs);
        errno = saved;
    }
    return -1;
}

/* -------------------------------------------------------------------------
 * bstack_len
 * ---------------------------------------------------------------------- */

int bstack_len(bstack_t *bs, uint64_t *out_len)
{
    BS_RDLOCK(bs);

    uint64_t raw_size;
    if (file_size(bs->fd, &raw_size) != 0) {
        int saved = errno;
        BS_RDUNLOCK(bs);
        errno = saved;
        return -1;
    }

    BS_RDUNLOCK(bs);
    *out_len = raw_size - HEADER_SIZE;
    return 0;
}

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

#ifdef BSTACK_FEATURE_SET
int bstack_set(bstack_t *bs, uint64_t offset,
               const uint8_t *data, size_t len)
{
    if (len == 0)
        return 0;

    /* Guard against offset + len wrapping around. */
    if ((uint64_t)len > UINT64_MAX - offset) {
        errno = EINVAL;
        return -1;
    }
    uint64_t end = offset + (uint64_t)len;

    BS_WRLOCK(bs);

    uint64_t raw_size;
    if (file_size(bs->fd, &raw_size) != 0)
        goto fail_unlock;

    uint64_t data_size = raw_size - HEADER_SIZE;
    if (end > data_size) {
        BS_WRUNLOCK(bs);
        errno = EINVAL;
        return -1;
    }

    if (plat_pwrite(bs->fd, data, len, HEADER_SIZE + offset) != 0)
        goto fail_unlock;

    if (plat_durable_sync(bs->fd) != 0)
        goto fail_unlock;

    BS_WRUNLOCK(bs);
    return 0;

fail_unlock:
    {
        int saved = errno;
        BS_WRUNLOCK(bs);
        errno = saved;
    }
    return -1;
}

int bstack_zero(bstack_t *bs, uint64_t offset, size_t n)
{
    if (n == 0)
        return 0;

    /* Guard against offset + n wrapping around. */
    if ((uint64_t)n > UINT64_MAX - offset) {
        errno = EINVAL;
        return -1;
    }
    uint64_t end = offset + (uint64_t)n;

    BS_WRLOCK(bs);

    uint64_t raw_size;
    if (file_size(bs->fd, &raw_size) != 0)
        goto fail_unlock;

    uint64_t data_size = raw_size - HEADER_SIZE;
    if (end > data_size) {
        BS_WRUNLOCK(bs);
        errno = EINVAL;
        return -1;
    }

    /* Allocate a buffer of zeros and write it. */
    uint8_t *zeros = calloc(n, 1);
    if (!zeros) {
        BS_WRUNLOCK(bs);
        errno = ENOMEM;
        return -1;
    }

    if (plat_pwrite(bs->fd, zeros, n, HEADER_SIZE + offset) != 0) {
        free(zeros);
        goto fail_unlock;
    }

    free(zeros);

    if (plat_durable_sync(bs->fd) != 0)
        goto fail_unlock;

    BS_WRUNLOCK(bs);
    return 0;

fail_unlock:
    {
        int saved = errno;
        BS_WRUNLOCK(bs);
        errno = saved;
    }
    return -1;
}

#endif /* BSTACK_FEATURE_SET */

/* -------------------------------------------------------------------------
 * Atomic compound operations  (only compiled with -DBSTACK_FEATURE_ATOMIC)
 * ---------------------------------------------------------------------- */

#ifdef BSTACK_FEATURE_ATOMIC

/* Shared body for atrunc and splice (after the removed bytes are read).
 * Caller already holds the write lock.  raw_size / data_size / tail_offset /
 * final_data_len are pre-computed by the caller. */
static int atomic_write_tail(bstack_fd_t fd,
                              uint64_t raw_size,
                              uint64_t tail_offset,
                              uint64_t final_data_len,
                              const uint8_t *buf, size_t buf_len,
                              size_t n)
{
    if (buf_len > n) {
        /* Net extension: extend first so crashes roll back cleanly, then
         * write buf over the old tail + the new space, sync, commit clen. */
        if (plat_ftruncate(fd, HEADER_SIZE + final_data_len) != 0)
            return -1;
        if (buf_len > 0 &&
            plat_pwrite(fd, buf, buf_len, tail_offset) != 0) {
            plat_ftruncate(fd, raw_size); /* best-effort rollback */
            return -1;
        }
        if (plat_durable_sync(fd) != 0) {
            plat_ftruncate(fd, raw_size); /* best-effort rollback */
            return -1;
        }
        return write_committed_len(fd, final_data_len);
    } else {
        /* Net truncation or same size: write buf into old tail, truncate,
         * sync, commit clen.  A crash after truncate is committed by
         * recovery (file_size - 16 < clen → clen = file_size - 16). */
        if (buf_len > 0 &&
            plat_pwrite(fd, buf, buf_len, tail_offset) != 0)
            return -1;
        if (plat_ftruncate(fd, HEADER_SIZE + final_data_len) != 0)
            return -1;
        if (plat_durable_sync(fd) != 0)
            return -1;
        return write_committed_len(fd, final_data_len);
    }
}

int bstack_atrunc(bstack_t *bs, size_t n,
                  const uint8_t *buf, size_t buf_len)
{
    if (n == 0 && buf_len == 0)
        return 0;

    BS_WRLOCK(bs);

    uint64_t raw_size;
    if (file_size(bs->fd, &raw_size) != 0)
        goto fail_unlock;

    uint64_t data_size = raw_size - HEADER_SIZE;
    if ((uint64_t)n > data_size) {
        BS_WRUNLOCK(bs);
        errno = EINVAL;
        return -1;
    }

    uint64_t tail_offset    = HEADER_SIZE + data_size - (uint64_t)n;
    uint64_t final_data_len = data_size  - (uint64_t)n + (uint64_t)buf_len;

    if (atomic_write_tail(bs->fd, raw_size, tail_offset,
                          final_data_len, buf, buf_len, n) != 0)
        goto fail_unlock;

    BS_WRUNLOCK(bs);
    return 0;

fail_unlock:
    { int s = errno; BS_WRUNLOCK(bs); errno = s; }
    return -1;
}

int bstack_splice(bstack_t *bs,
                  uint8_t *removed, size_t n,
                  const uint8_t *new_buf, size_t new_len)
{
    if (n == 0 && new_len == 0)
        return 0;

    BS_WRLOCK(bs);

    uint64_t raw_size;
    if (file_size(bs->fd, &raw_size) != 0)
        goto fail_unlock;

    uint64_t data_size = raw_size - HEADER_SIZE;
    if ((uint64_t)n > data_size) {
        BS_WRUNLOCK(bs);
        errno = EINVAL;
        return -1;
    }

    uint64_t tail_offset    = HEADER_SIZE + data_size - (uint64_t)n;
    uint64_t final_data_len = data_size  - (uint64_t)n + (uint64_t)new_len;

    /* Read removed bytes before any mutation. */
    if (n > 0 && removed != NULL) {
        if (plat_pread(bs->fd, removed, n, tail_offset) != 0)
            goto fail_unlock;
    }

    if (atomic_write_tail(bs->fd, raw_size, tail_offset,
                          final_data_len, new_buf, new_len, n) != 0)
        goto fail_unlock;

    BS_WRUNLOCK(bs);
    return 0;

fail_unlock:
    { int s = errno; BS_WRUNLOCK(bs); errno = s; }
    return -1;
}

int bstack_try_extend(bstack_t *bs, uint64_t s,
                      const uint8_t *buf, size_t buf_len, int *ok)
{
    BS_WRLOCK(bs);

    uint64_t raw_size;
    if (file_size(bs->fd, &raw_size) != 0)
        goto fail_unlock;

    uint64_t data_size = raw_size - HEADER_SIZE;
    if (data_size != s) {
        BS_WRUNLOCK(bs);
        if (ok) *ok = 0;
        return 0;
    }
    if (buf_len == 0) {
        BS_WRUNLOCK(bs);
        if (ok) *ok = 1;
        return 0;
    }

    /* Same sequence as bstack_push. */
    if (plat_pwrite(bs->fd, buf, buf_len, raw_size) != 0) {
        plat_ftruncate(bs->fd, raw_size);
        goto fail_unlock;
    }
    uint64_t new_len = data_size + (uint64_t)buf_len;
    if (write_committed_len(bs->fd, new_len) != 0 ||
        plat_durable_sync(bs->fd) != 0) {
        plat_ftruncate(bs->fd, raw_size);
        write_committed_len(bs->fd, data_size);
        goto fail_unlock;
    }

    BS_WRUNLOCK(bs);
    if (ok) *ok = 1;
    return 0;

fail_unlock:
    { int s = errno; BS_WRUNLOCK(bs); errno = s; }
    return -1;
}

int bstack_try_discard(bstack_t *bs, uint64_t s, size_t n, int *ok)
{
    if (n == 0) {
        /* Read-only path: just check the size. */
        BS_RDLOCK(bs);
        uint64_t raw_size;
        if (file_size(bs->fd, &raw_size) != 0) {
            int saved = errno;
            BS_RDUNLOCK(bs);
            errno = saved;
            return -1;
        }
        BS_RDUNLOCK(bs);
        if (ok) *ok = ((raw_size - HEADER_SIZE) == s) ? 1 : 0;
        return 0;
    }

    BS_WRLOCK(bs);

    uint64_t raw_size;
    if (file_size(bs->fd, &raw_size) != 0)
        goto fail_unlock;

    uint64_t data_size = raw_size - HEADER_SIZE;
    if (data_size != s) {
        BS_WRUNLOCK(bs);
        if (ok) *ok = 0;
        return 0;
    }
    if ((uint64_t)n > data_size) {
        BS_WRUNLOCK(bs);
        errno = EINVAL;
        return -1;
    }

    uint64_t new_len = data_size - (uint64_t)n;
    if (plat_ftruncate(bs->fd, HEADER_SIZE + new_len) != 0 ||
        write_committed_len(bs->fd, new_len) != 0 ||
        plat_durable_sync(bs->fd) != 0)
        goto fail_unlock;

    BS_WRUNLOCK(bs);
    if (ok) *ok = 1;
    return 0;

fail_unlock:
    { int s = errno; BS_WRUNLOCK(bs); errno = s; }
    return -1;
}

int bstack_replace(bstack_t *bs, size_t n,
                   int (*cb)(const uint8_t *old, size_t old_len,
                              uint8_t **new_buf, size_t *new_len,
                              void *ctx),
                   void *ctx)
{
    BS_WRLOCK(bs);

    uint64_t raw_size;
    if (file_size(bs->fd, &raw_size) != 0)
        goto fail_unlock;

    uint64_t data_size = raw_size - HEADER_SIZE;
    if ((uint64_t)n > data_size) {
        BS_WRUNLOCK(bs);
        errno = EINVAL;
        return -1;
    }

    uint64_t tail_offset = HEADER_SIZE + data_size - (uint64_t)n;

    /* Read old tail bytes (NULL when n == 0 — callback must check old_len). */
    uint8_t *old_tail = NULL;
    if (n > 0) {
        old_tail = (uint8_t *)malloc(n);
        if (old_tail == NULL)
            goto fail_unlock;
        if (plat_pread(bs->fd, old_tail, n, tail_offset) != 0) {
            free(old_tail);
            goto fail_unlock;
        }
    }

    /* Invoke callback to produce new tail. */
    uint8_t *new_buf = NULL;
    size_t   new_len = 0;
    int cb_ret = cb(old_tail, n, &new_buf, &new_len, ctx);
    free(old_tail);

    if (cb_ret != 0)
        goto fail_unlock;

    /* Skip all I/O when both sides are empty. */
    if (n == 0 && new_len == 0) {
        BS_WRUNLOCK(bs);
        return 0;
    }

    uint64_t final_data_len = data_size - (uint64_t)n + (uint64_t)new_len;

    if (atomic_write_tail(bs->fd, raw_size, tail_offset,
                          final_data_len, new_buf, new_len, n) != 0) {
        free(new_buf);
        goto fail_unlock;
    }
    free(new_buf);

    BS_WRUNLOCK(bs);
    return 0;

fail_unlock:
    { int s = errno; BS_WRUNLOCK(bs); errno = s; }
    return -1;
}

#endif /* BSTACK_FEATURE_ATOMIC */

/* -------------------------------------------------------------------------
 * swap / cas  (require both BSTACK_FEATURE_ATOMIC and BSTACK_FEATURE_SET)
 * ---------------------------------------------------------------------- */

#if defined(BSTACK_FEATURE_ATOMIC) && defined(BSTACK_FEATURE_SET)

int bstack_swap(bstack_t *bs, uint64_t offset,
                uint8_t *old_buf, const uint8_t *new_buf, size_t len)
{
    if (len == 0)
        return 0;
    if ((uint64_t)len > UINT64_MAX - offset) {
        errno = EINVAL;
        return -1;
    }
    uint64_t end = offset + (uint64_t)len;

    BS_WRLOCK(bs);

    uint64_t raw_size;
    if (file_size(bs->fd, &raw_size) != 0)
        goto fail_unlock;

    uint64_t data_size = raw_size - HEADER_SIZE;
    if (end > data_size) {
        BS_WRUNLOCK(bs);
        errno = EINVAL;
        return -1;
    }

    if (plat_pread(bs->fd,  old_buf, len, HEADER_SIZE + offset) != 0)
        goto fail_unlock;
    if (plat_pwrite(bs->fd, new_buf, len, HEADER_SIZE + offset) != 0)
        goto fail_unlock;
    if (plat_durable_sync(bs->fd) != 0)
        goto fail_unlock;

    BS_WRUNLOCK(bs);
    return 0;

fail_unlock:
    { int s = errno; BS_WRUNLOCK(bs); errno = s; }
    return -1;
}

int bstack_cas(bstack_t *bs, uint64_t offset,
               const uint8_t *old_buf, const uint8_t *new_buf,
               size_t len, int *ok)
{
    if (len == 0) {
        if (ok) *ok = 1;
        return 0;
    }
    if ((uint64_t)len > UINT64_MAX - offset) {
        errno = EINVAL;
        return -1;
    }
    uint64_t end = offset + (uint64_t)len;

    BS_WRLOCK(bs);

    uint64_t raw_size;
    if (file_size(bs->fd, &raw_size) != 0)
        goto fail_unlock;

    uint64_t data_size = raw_size - HEADER_SIZE;
    if (end > data_size) {
        BS_WRUNLOCK(bs);
        errno = EINVAL;
        return -1;
    }

    /* Compare in fixed-size stack chunks — no heap allocation. */
    uint8_t chunk[256];
    size_t  remaining = len;
    uint64_t file_off = HEADER_SIZE + offset;
    const uint8_t *cmp = old_buf;
    while (remaining > 0) {
        size_t batch = remaining < sizeof chunk ? remaining : sizeof chunk;
        if (plat_pread(bs->fd, chunk, batch, file_off) != 0)
            goto fail_unlock;
        if (memcmp(chunk, cmp, batch) != 0) {
            BS_WRUNLOCK(bs);
            if (ok) *ok = 0;
            return 0;
        }
        cmp       += batch;
        file_off  += batch;
        remaining -= batch;
    }

    /* All bytes matched — write new_buf and sync. */
    if (plat_pwrite(bs->fd, new_buf, len, HEADER_SIZE + offset) != 0)
        goto fail_unlock;
    if (plat_durable_sync(bs->fd) != 0)
        goto fail_unlock;

    BS_WRUNLOCK(bs);
    if (ok) *ok = 1;
    return 0;

fail_unlock:
    { int s = errno; BS_WRUNLOCK(bs); errno = s; }
    return -1;
}

int bstack_process(bstack_t *bs, uint64_t start, uint64_t end,
                   int (*cb)(uint8_t *buf, size_t len, void *ctx),
                   void *ctx)
{
    if (end < start) {
        errno = EINVAL;
        return -1;
    }
    uint64_t n = end - start;

    BS_WRLOCK(bs);

    uint64_t raw_size;
    if (file_size(bs->fd, &raw_size) != 0)
        goto fail_unlock;

    uint64_t data_size = raw_size - HEADER_SIZE;
    if (end > data_size) {
        BS_WRUNLOCK(bs);
        errno = EINVAL;
        return -1;
    }

    uint8_t *buf = NULL;
    if (n > 0) {
        buf = (uint8_t *)malloc((size_t)n);
        if (buf == NULL)
            goto fail_unlock;
        if (plat_pread(bs->fd, buf, (size_t)n, HEADER_SIZE + start) != 0) {
            free(buf);
            goto fail_unlock;
        }
    }

    if (cb(buf, (size_t)n, ctx) != 0) {
        free(buf);
        goto fail_unlock;
    }

    if (n > 0) {
        if (plat_pwrite(bs->fd, buf, (size_t)n, HEADER_SIZE + start) != 0) {
            free(buf);
            goto fail_unlock;
        }
        if (plat_durable_sync(bs->fd) != 0) {
            free(buf);
            goto fail_unlock;
        }
        free(buf);
    }

    BS_WRUNLOCK(bs);
    return 0;

fail_unlock:
    { int s = errno; BS_WRUNLOCK(bs); errno = s; }
    return -1;
}

#endif /* BSTACK_FEATURE_ATOMIC && BSTACK_FEATURE_SET */

#ifdef __cplusplus
}
#endif