ewf-image 0.2.0

Pure-Rust library for reading and writing EWF/E01 forensic disk images.
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
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
use std::borrow::Cow;
use std::collections::BTreeMap;
use std::fs::{self, File};
use std::io::{Read, Seek, SeekFrom, Write};
use std::ops::Range;
use std::path::{Component, Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};

use bzip2::Compression as Bzip2Compression;
use bzip2::write::BzEncoder;
use flate2::Compression as ZlibCompression;
use flate2::write::ZlibEncoder;
use md5::{Digest, Md5};
use sha1::Sha1;
use tempfile::NamedTempFile;

use crate::codepage::encode_header_text;
use crate::date_time::{
    format_ewf1_header_date_value, format_ewf1_header2_date_value, format_xheader_date_value,
};
use crate::decode::{ChunkEncoding, decode_chunk, validate_encoded_size};
use crate::format::{ewf1, ewf2};
use crate::image::Image;
use crate::types::{
    AcquisitionError, CompressionLevel, CompressionMethod, CompressionValues, DataChunk,
    DataChunkEncoding, EncodedDataChunk, EwfMetadata, Format, FormatProfile, HeaderCodepage,
    HeaderDateFormat, ImageInfo, MediaFlags, MediaType, MemoryExtent, SectorRange,
    SingleFileAttribute, SingleFileEntry, SingleFileEntryType, SingleFileExtent,
    SingleFilePermission, SingleFilePermissionGroup, SingleFileSource, SingleFileSubject,
    SingleFilesAuxTables, SingleFilesInfo, StoredHashes,
};
use crate::{EwfError, Result};

const VOLUME_DATA_SIZE: usize = 1052;
const EWF1_LTREE_HEADER_SIZE: usize = 48;
const EWF2_DEVICE_INFORMATION_SECTION: u32 = 0x01;
const EWF2_CASE_DATA_SECTION: u32 = 0x02;
const EWF2_SECTOR_DATA_SECTION: u32 = 0x03;
const EWF2_SECTOR_TABLE_SECTION: u32 = 0x04;
const EWF2_ERROR_TABLE_SECTION: u32 = 0x05;
const EWF2_SESSION_TABLE_SECTION: u32 = 0x06;
const EWF2_INCREMENT_DATA_SECTION: u32 = 0x07;
const EWF2_MD5_HASH_SECTION: u32 = 0x08;
const EWF2_SHA1_HASH_SECTION: u32 = 0x09;
const EWF2_RESTART_DATA_SECTION: u32 = 0x0a;
const EWF2_MEMORY_EXTENTS_TABLE_SECTION: u32 = 0x0c;
const EWF2_NEXT_SECTION: u32 = 0x0d;
const EWF2_FINAL_INFORMATION_SECTION: u32 = 0x0e;
const EWF2_DONE_SECTION: u32 = 0x0f;
const EWF2_ANALYTICAL_DATA_SECTION: u32 = 0x10;
const EWF2_SINGLE_FILES_DATA_SECTION: u32 = 0x20;
const EWF2_SINGLE_FILES_TABLE_SECTION: u32 = 0x21;
const EWF2_SINGLE_FILES_MD5_HASH_TABLE_SECTION: u32 = 0x22;
const EWF2_SINGLE_FILES_UNKNOWN_TABLE_SECTION: u32 = 0x23;
const EWF2_TABLE_HEADER_V2_SIZE: usize = 32;
const EWF2_TABLE_FOOTER_SIZE: usize = 16;
// EWF1 table entries hold 31-bit offsets relative to the table base offset, so
// each sectors/table group can address at most 2 GiB of chunk payload. Large
// non-segmented images are written as multiple groups per segment, matching
// EnCase 6 and FTK Imager output.
const EWF1_TABLE_GROUP_MAX_PAYLOAD: u64 = 0x7fff_ffff;
const EWF1_TABLE_GROUP_MAX_ENTRIES: usize = 16_375;
const SIGNED_SECTOR_RANGE_MAX: u64 = i64::MAX as u64;
const EWF2_EXTENDED_ATTRIBUTES_HEADER: &[u8; 37] = &[
    0x00, 0x00, 0x00, 0x00, 0x01, 0x0b, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x41, 0x00, 0x74,
    0x00, 0x74, 0x00, 0x72, 0x00, 0x69, 0x00, 0x62, 0x00, 0x75, 0x00, 0x74, 0x00, 0x65, 0x00, 0x73,
    0x00, 0x00, 0x00, 0x00, 0x00,
];

const SINGLE_FILE_ENTRY_TYPES: &[&str] = &[
    "id", "p", "n", "ls", "lo", "po", "du", "src", "sub", "pm", "cid", "opr", "be", "ha", "sha",
    "snh", "cr", "wr", "ac", "mo", "dl", "ea",
];
const SINGLE_FILE_SOURCE_TYPES: &[&str] = &[
    "id", "n", "ev", "loc", "gu", "pgu", "dt", "mfr", "mo", "se", "do", "ip", "ma", "tb", "lo",
    "po", "aq", "ah", "sh",
];
const SINGLE_FILE_SUBJECT_TYPES: &[&str] = &["id", "n"];
const SINGLE_FILE_PERMISSION_TYPES: &[&str] = &["n", "pr", "s", "nta", "nti"];

#[derive(Debug, Clone, PartialEq, Eq)]
/// Configuration used to create an [`EwfWriter`].
pub struct WriteOptions {
    /// Output EWF format.
    pub format: WriteFormat,
    /// Number of sectors represented by each chunk.
    pub sectors_per_chunk: u32,
    /// Bytes in each logical sector.
    pub bytes_per_sector: u32,
    /// Segment set identifier written to output metadata.
    pub set_identifier: Option<[u8; 16]>,
    /// Compression method for newly encoded chunks.
    pub compression: WriteCompression,
    /// Compression level and flags for newly encoded chunks.
    pub compression_values: WriteCompressionValues,
    /// Stored hash values to write.
    pub hashes: WriteHashes,
    /// Maximum output segment size in bytes.
    pub maximum_segment_size: Option<u64>,
    /// First path of the mirrored secondary output segment set.
    pub secondary_segment_filename: Option<PathBuf>,
    /// Declared logical media size in bytes.
    pub media_size: Option<u64>,
    /// Case and acquisition metadata to write.
    pub metadata: EwfMetadata,
    /// Codepage used to encode EWF1 header values.
    pub header_codepage: HeaderCodepage,
    /// Date format used for EWF1 header date values.
    pub header_values_date_format: HeaderDateFormat,
    /// Acquisition error ranges to write.
    pub acquisition_errors: Vec<AcquisitionError>,
    /// Checksum error ranges to write.
    pub checksum_errors: Vec<SectorRange>,
    /// Session sector ranges to write.
    pub sessions: Vec<SectorRange>,
    /// Track sector ranges to write.
    pub tracks: Vec<SectorRange>,
    /// Media type and acquisition flags to write.
    pub media_profile: WriteMediaProfile,
    /// Memory acquisition extents to write.
    pub memory_extents: Vec<MemoryExtent>,
    /// Logical single-file catalog to write.
    pub single_files: Option<SingleFilesInfo>,
    /// Preserved EWF2 single-file auxiliary table data.
    pub ewf2_single_files_tables: SingleFilesAuxTables,
    /// Raw EWF2 increment data sections to write.
    pub ewf2_increment_data: Vec<Vec<u8>>,
    /// Raw EWF2 final information section to write.
    pub ewf2_final_information: Option<Vec<u8>>,
    /// EWF2 restart data text to write.
    pub ewf2_restart_data: Option<String>,
    /// EWF2 analytical data text to write.
    pub ewf2_analytical_data: Option<String>,
}

impl Default for WriteOptions {
    fn default() -> Self {
        Self {
            format: WriteFormat::Ewf1Physical,
            sectors_per_chunk: 64,
            bytes_per_sector: 512,
            set_identifier: None,
            compression: WriteCompression::None,
            compression_values: WriteCompressionValues::default(),
            hashes: WriteHashes::default(),
            maximum_segment_size: None,
            secondary_segment_filename: None,
            media_size: None,
            metadata: EwfMetadata::default(),
            header_codepage: HeaderCodepage::Ascii,
            header_values_date_format: HeaderDateFormat::Ctime,
            acquisition_errors: Vec::new(),
            checksum_errors: Vec::new(),
            sessions: Vec::new(),
            tracks: Vec::new(),
            media_profile: WriteMediaProfile::default(),
            memory_extents: Vec::new(),
            single_files: None,
            ewf2_single_files_tables: SingleFilesAuxTables::default(),
            ewf2_increment_data: Vec::new(),
            ewf2_final_information: None,
            ewf2_restart_data: None,
            ewf2_analytical_data: None,
        }
    }
}

impl WriteOptions {
    /// Copies media geometry and flags from an opened image.
    ///
    /// # Errors
    ///
    /// Returns an error if the source image contains media values that cannot be
    /// represented by writer options.
    pub fn copy_media_values_from_image(&mut self, image: &Image) -> Result<()> {
        self.copy_media_values_from_info(image.info())
    }

    /// Copies media geometry and flags from parsed image metadata.
    ///
    /// # Errors
    ///
    /// Returns an error if the source metadata contains media values that cannot
    /// be represented by writer options.
    pub fn copy_media_values_from_info(&mut self, info: &ImageInfo) -> Result<()> {
        let mut candidate = self.clone();
        candidate.format = write_format_from_image_info(info);
        candidate.sectors_per_chunk =
            required_media_u32(info.media.sectors_per_chunk, "sectors per chunk")?;
        candidate.bytes_per_sector =
            required_media_u32(info.media.bytes_per_sector, "bytes per sector")?;
        candidate.set_identifier = info.media.set_identifier;
        candidate.media_size = Some(info.logical_size);
        candidate.media_profile = WriteMediaProfile {
            media_type: info.media.media_type,
            error_granularity: info.media.error_granularity,
            fastbloc: info.media.media_flags.fastbloc,
            tableau: info.media.media_flags.tableau,
        };
        let has_explicit_compression_values =
            info.media.compression_values != CompressionValues::default();
        candidate.compression_values = if has_explicit_compression_values {
            write_compression_values_from_media_values(info.media.compression_values)?
        } else {
            WriteCompressionValues::default()
        };
        if let Some(compression_method) = info.media.compression_method {
            candidate.compression = write_compression_from_media_method(compression_method)?;
        } else if has_explicit_compression_values
            && candidate.compression_values.level != WriteCompressionLevel::None
        {
            candidate.compression = WriteCompression::Zlib;
        } else {
            candidate.compression = WriteCompression::None;
        }
        validate_options(&candidate)?;
        *self = candidate;
        Ok(())
    }

    /// Copies header values from an opened image.
    pub fn copy_header_values_from_image(&mut self, image: &Image) {
        self.copy_header_values_from_info(image.info());
    }

    /// Copies header values from parsed image metadata.
    pub fn copy_header_values_from_info(&mut self, info: &ImageInfo) {
        self.copy_header_values_from_metadata(&info.metadata);
    }

    /// Copies header values from metadata.
    pub fn copy_header_values_from_metadata(&mut self, metadata: &EwfMetadata) {
        self.metadata.copy_header_values_from(metadata);
    }

    /// Copies stored hash values from an opened image.
    pub fn copy_hash_values_from_image(&mut self, image: &Image) {
        self.copy_hash_values_from_info(image.info());
    }

    /// Copies stored hash values from parsed image metadata.
    pub fn copy_hash_values_from_info(&mut self, info: &ImageInfo) {
        self.copy_hash_values_from_stored_hashes(&info.stored_hashes);
    }

    /// Copies stored hash values from a hash collection.
    pub fn copy_hash_values_from_stored_hashes(&mut self, hashes: &StoredHashes) {
        self.hashes.copy_hash_values_from_stored_hashes(hashes);
    }
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
/// Output EWF format selected for writing.
pub enum WriteFormat {
    /// EWF1 physical `.E01` output.
    #[default]
    Ewf1Physical,
    /// EWF1 logical `.L01` output.
    Ewf1Logical,
    /// EWF1 SMART `.S01` output.
    Ewf1Smart,
    /// EWF2 physical `.Ex01` output.
    Ewf2Physical,
    /// EWF2 logical `.Lx01` output.
    Ewf2Logical,
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
/// Hash values configured for writer output.
pub struct WriteHashes {
    /// MD5 hash bytes.
    pub md5: Option<[u8; 16]>,
    /// SHA1 hash bytes.
    pub sha1: Option<[u8; 20]>,
    /// Hash strings keyed by hash identifier.
    pub hash_values: BTreeMap<String, String>,
}

impl WriteHashes {
    /// Copies stored hash values from an image hash collection.
    pub fn copy_hash_values_from_stored_hashes(&mut self, hashes: &StoredHashes) {
        self.md5 = hashes.md5;
        self.sha1 = hashes.sha1;
        self.hash_values = hashes.hash_values.clone();
    }

    /// Returns a hash string by identifier.
    pub fn hash_value(&self, identifier: &str) -> Option<&str> {
        self.hash_values.get(identifier).map(String::as_str)
    }

    /// Sets a hash string by identifier and returns the previous value.
    ///
    /// `MD5` and `SHA1` values are also parsed into typed byte arrays.
    ///
    /// # Errors
    ///
    /// Returns an error if an `MD5` or `SHA1` value is not valid hexadecimal of
    /// the required length.
    pub fn set_hash_value(
        &mut self,
        identifier: impl Into<String>,
        value: impl Into<String>,
    ) -> Result<Option<String>> {
        let identifier = identifier.into();
        let value = value.into();
        if identifier.eq_ignore_ascii_case("MD5") {
            self.md5 = Some(parse_writer_hash_value("MD5", &value)?);
        } else if identifier.eq_ignore_ascii_case("SHA1") {
            self.sha1 = Some(parse_writer_hash_value("SHA1", &value)?);
        }
        Ok(self.hash_values.insert(identifier, value))
    }

    /// Returns the number of configured hash strings.
    pub fn number_of_hash_values(&self) -> usize {
        self.hash_values.len()
    }

    /// Returns a hash identifier by enumeration index.
    pub fn hash_value_identifier(&self, index: usize) -> Option<&str> {
        self.hash_values.keys().nth(index).map(String::as_str)
    }
}

fn parse_writer_hash_value<const N: usize>(label: &str, value: &str) -> Result<[u8; N]> {
    if value.len() != N * 2 {
        return Err(EwfError::Unsupported(format!("invalid {label} hash value")));
    }

    let mut bytes = [0; N];
    for (index, pair) in value.as_bytes().chunks_exact(2).enumerate() {
        let high = writer_hash_nibble(pair[0])
            .ok_or_else(|| EwfError::Unsupported(format!("invalid {label} hash value")))?;
        let low = writer_hash_nibble(pair[1])
            .ok_or_else(|| EwfError::Unsupported(format!("invalid {label} hash value")))?;
        bytes[index] = (high << 4) | low;
    }
    Ok(bytes)
}

fn writer_hash_nibble(value: u8) -> Option<u8> {
    match value {
        b'0'..=b'9' => Some(value - b'0'),
        b'a'..=b'f' => Some(value - b'a' + 10),
        b'A'..=b'F' => Some(value - b'A' + 10),
        _ => None,
    }
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
/// Media type and acquisition flags configured for writer output.
pub struct WriteMediaProfile {
    /// Media type to write.
    pub media_type: Option<MediaType>,
    /// Error granularity in sectors.
    pub error_granularity: Option<u64>,
    /// `FastBloc` acquisition flag.
    pub fastbloc: bool,
    /// Tableau acquisition flag.
    pub tableau: bool,
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
/// Compression method for writer output.
pub enum WriteCompression {
    /// Store chunks without compression.
    #[default]
    None,
    /// Compress chunks with zlib.
    Zlib,
    /// Compress chunks with `BZip2`.
    Bzip2,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// Compression settings for writer output.
pub struct WriteCompressionValues {
    /// Compression level.
    pub level: WriteCompressionLevel,
    /// Whether empty-block compression flags should be written.
    pub empty_block: bool,
}

impl Default for WriteCompressionValues {
    fn default() -> Self {
        Self {
            level: WriteCompressionLevel::Default,
            empty_block: true,
        }
    }
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
/// Compression level for writer output.
pub enum WriteCompressionLevel {
    /// Use the compressor default level.
    #[default]
    Default,
    /// Do not compress.
    None,
    /// Prefer faster compression.
    Fast,
    /// Prefer stronger compression.
    Best,
}

#[derive(Debug, Clone, PartialEq, Eq)]
/// Result returned after finalizing writer output.
pub struct WriteResult {
    /// Output segment paths or labels.
    pub segment_paths: Vec<PathBuf>,
    /// Mirrored secondary output segment paths.
    pub secondary_segment_paths: Vec<PathBuf>,
    /// Logical media size written in bytes.
    pub logical_size: u64,
    /// Logical chunk size written in bytes.
    pub chunk_size: u64,
    /// Number of logical chunks written.
    pub chunk_count: u64,
}

/// Incremental EWF writer.
///
/// The writer buffers media data until [`EwfWriter::finish`] or another finish
/// method is called. Geometry and format options must be configured before
/// media data is written.
pub struct EwfWriter {
    path: PathBuf,
    options: WriteOptions,
    chunk_size: u64,
    chunk_capacity: usize,
    raw: RawSpool,
    encoded_chunks: BTreeMap<u64, RememberedEncodedChunk>,
    current_offset: u64,
    logical_input_size: u64,
    abort_signaled: AtomicBool,
}

struct PreparedWrite {
    path: PathBuf,
    options: WriteOptions,
    chunks: Vec<ChunkDescriptor>,
    spool: ChunkSpool,
    logical_size: u64,
    chunk_size: u64,
    chunk_count: u64,
    chunk_count_u32: u32,
    sector_count: u64,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum TerminalSection {
    Done,
    Next,
}

impl TerminalSection {
    fn ewf1_type(self) -> &'static [u8; 4] {
        match self {
            Self::Done => b"done",
            Self::Next => b"next",
        }
    }

    fn ewf2_type(self) -> u32 {
        match self {
            Self::Done => EWF2_DONE_SECTION,
            Self::Next => EWF2_NEXT_SECTION,
        }
    }
}

impl std::fmt::Debug for EwfWriter {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("EwfWriter")
            .field("path", &self.path)
            .field("options", &self.options)
            .field("chunk_size", &self.chunk_size)
            .field("chunk_capacity", &self.chunk_capacity)
            .field("raw", &"<temporary>")
            .field("raw_spooled_bytes", &self.raw.len())
            .field("encoded_chunks", &self.encoded_chunks.len())
            .field("current_offset", &self.current_offset)
            .field("logical_input_size", &self.logical_input_size)
            .field(
                "abort_signaled",
                &self.abort_signaled.load(Ordering::Relaxed),
            )
            .finish()
    }
}

impl EwfWriter {
    /// Creates a new writer for a file-backed EWF segment set.
    ///
    /// # Errors
    ///
    /// Returns an error if options are invalid, the secondary segment filename
    /// conflicts with the primary filename, or temporary spool creation fails.
    pub fn create(path: impl AsRef<Path>, mut options: WriteOptions) -> Result<Self> {
        let path = path.as_ref().to_path_buf();
        options.maximum_segment_size = normalize_maximum_segment_size(options.maximum_segment_size);
        options.media_size = normalize_media_size(options.media_size);
        validate_options(&options)?;
        validate_secondary_segment_filename(&path, options.secondary_segment_filename.as_deref())?;
        let (chunk_size, chunk_capacity) =
            writer_chunk_geometry(options.sectors_per_chunk, options.bytes_per_sector)?;

        Ok(Self {
            path,
            options,
            chunk_size,
            chunk_capacity,
            raw: RawSpool::new()?,
            encoded_chunks: BTreeMap::new(),
            current_offset: 0,
            logical_input_size: 0,
            abort_signaled: AtomicBool::new(false),
        })
    }

    /// Creates a writer initialized from an existing image and copies its media.
    ///
    /// # Errors
    ///
    /// Returns an error if the source image cannot be represented by the writer,
    /// media copying fails, or writer creation fails.
    pub fn create_from_image(path: impl AsRef<Path>, image: &Image) -> Result<Self> {
        let options = rewrite_options_from_image_info(image.info())?;
        let mut writer = Self::create(path, options)?;
        copy_image_media_to_writer(image, &mut writer)?;
        Ok(writer)
    }

    /// Opens an existing image and prepares a writer that can append or rewrite it.
    ///
    /// # Errors
    ///
    /// Returns an error if the existing image cannot be opened, copied, or
    /// represented by writer options.
    pub fn resume<P: AsRef<Path>>(path: P) -> Result<Self> {
        let path = path.as_ref().to_path_buf();
        let image = Image::open(&path)?;
        let mut writer = Self::create_from_image(&path, &image)?;
        writer.options.media_size = None;
        Ok(writer)
    }

    /// Returns the first output segment filename.
    pub fn filename(&self) -> &Path {
        self.path.as_path()
    }

    /// Returns the first output segment filename.
    pub fn segment_filename(&self) -> &Path {
        self.path.as_path()
    }

    /// Sets the first output segment filename.
    pub fn set_segment_filename(&mut self, path: impl AsRef<Path>) {
        self.path = path.as_ref().to_path_buf();
    }

    /// Returns the first mirrored secondary output segment filename.
    pub fn secondary_segment_filename(&self) -> Option<&Path> {
        self.options.secondary_segment_filename.as_deref()
    }

    /// Sets the first mirrored secondary output segment filename.
    ///
    /// # Errors
    ///
    /// Returns an error if the secondary filename conflicts with the primary
    /// output filename.
    pub fn set_secondary_segment_filename(&mut self, path: impl AsRef<Path>) -> Result<()> {
        let path = path.as_ref().to_path_buf();
        validate_secondary_segment_filename(&self.path, Some(&path))?;
        self.options.secondary_segment_filename = Some(path);
        Ok(())
    }

    /// Clears mirrored secondary output.
    pub fn clear_secondary_segment_filename(&mut self) {
        self.options.secondary_segment_filename = None;
    }

    /// Writes all bytes at the current writer position.
    ///
    /// # Errors
    ///
    /// Returns an error if the writer has been aborted or writing would exceed
    /// configured limits.
    pub fn write_all(&mut self, data: &[u8]) -> Result<()> {
        self.ensure_not_aborted()?;
        self.write_to_current(data)?;
        Ok(())
    }

    /// Writes bytes at the current writer position and returns the byte count.
    ///
    /// # Errors
    ///
    /// Returns an error if the writer has been aborted or writing would exceed
    /// configured limits.
    pub fn write_buffer(&mut self, data: &[u8]) -> Result<usize> {
        self.ensure_not_aborted()?;
        self.write_to_current(data)
    }

    /// Writes bytes at an absolute logical byte offset.
    ///
    /// # Errors
    ///
    /// Returns an error if the writer has been aborted or writing would exceed
    /// configured limits.
    pub fn write_at(&mut self, data: &[u8], offset: u64) -> Result<usize> {
        self.ensure_not_aborted()?;
        self.current_offset = offset;
        self.write_to_current(data)
    }

    /// Alias for [`EwfWriter::write_at`].
    ///
    /// # Errors
    ///
    /// Returns the same errors as [`EwfWriter::write_at`].
    pub fn write_buffer_at_offset(&mut self, data: &[u8], offset: u64) -> Result<usize> {
        self.write_at(data, offset)
    }

    /// Writes a decoded data chunk at the current writer position.
    ///
    /// # Errors
    ///
    /// Returns an error if the chunk metadata is inconsistent, the writer has
    /// been aborted, or writing would exceed configured limits.
    pub fn write_data_chunk(&mut self, chunk: &DataChunk) -> Result<usize> {
        self.ensure_not_aborted()?;
        validate_write_data_chunk(chunk)?;
        self.write_to_current(&chunk.data)
    }

    /// Decodes and writes an encoded data chunk at the current writer position.
    ///
    /// # Errors
    ///
    /// Returns an error if the encoded chunk cannot be decoded, the writer has
    /// been aborted, or writing would exceed configured limits.
    pub fn write_encoded_data_chunk(&mut self, chunk: &EncodedDataChunk) -> Result<usize> {
        self.ensure_not_aborted()?;
        let data = decode_write_encoded_data_chunk(chunk)?;
        let offset = self.current_offset;
        let written = self.write_to_current(&data)?;
        self.remember_encoded_data_chunk_at(chunk, offset, data.len());
        Ok(written)
    }

    /// Writes a decoded data chunk at an absolute logical byte offset.
    ///
    /// # Errors
    ///
    /// Returns the same errors as [`EwfWriter::write_data_chunk`] and
    /// [`EwfWriter::write_at`].
    pub fn write_data_chunk_at(&mut self, chunk: &DataChunk, offset: u64) -> Result<usize> {
        self.ensure_not_aborted()?;
        validate_write_data_chunk(chunk)?;
        self.write_at(&chunk.data, offset)
    }

    /// Decodes and writes an encoded data chunk at an absolute logical byte offset.
    ///
    /// # Errors
    ///
    /// Returns the same errors as [`EwfWriter::write_encoded_data_chunk`] and
    /// [`EwfWriter::write_at`].
    pub fn write_encoded_data_chunk_at(
        &mut self,
        chunk: &EncodedDataChunk,
        offset: u64,
    ) -> Result<usize> {
        self.ensure_not_aborted()?;
        let data = decode_write_encoded_data_chunk(chunk)?;
        self.current_offset = offset;
        let written = self.write_to_current(&data)?;
        self.remember_encoded_data_chunk_at(chunk, offset, data.len());
        Ok(written)
    }

    /// Returns the configured output format.
    pub fn format(&self) -> WriteFormat {
        self.options.format
    }

    /// Sets the output format before media data is written.
    ///
    /// # Errors
    ///
    /// Returns an error if media data has already been written or the new option
    /// combination is unsupported.
    pub fn set_format(&mut self, format: WriteFormat) -> Result<()> {
        self.ensure_configuration_mutable("format")?;
        let mut options = self.options.clone();
        options.format = format;
        validate_options(&options)?;
        self.options = options;
        Ok(())
    }

    /// Returns the current logical byte write position.
    pub fn position(&self) -> u64 {
        self.current_offset
    }

    /// Returns the current logical chunk size in bytes.
    pub fn chunk_size(&self) -> u64 {
        self.chunk_size
    }

    /// Returns the configured sectors per chunk.
    pub fn sectors_per_chunk(&self) -> u32 {
        self.options.sectors_per_chunk
    }

    /// Sets sectors per chunk before media data is written.
    ///
    /// # Errors
    ///
    /// Returns an error if media data has already been written or the resulting
    /// chunk geometry is invalid.
    pub fn set_sectors_per_chunk(&mut self, sectors_per_chunk: u32) -> Result<()> {
        self.ensure_configuration_mutable("sectors per chunk")?;
        let (chunk_size, chunk_capacity) =
            writer_chunk_geometry(sectors_per_chunk, self.options.bytes_per_sector)?;
        self.options.sectors_per_chunk = sectors_per_chunk;
        self.chunk_size = chunk_size;
        self.chunk_capacity = chunk_capacity;
        self.encoded_chunks.clear();
        Ok(())
    }

    /// Returns the configured bytes per sector.
    pub fn bytes_per_sector(&self) -> u32 {
        self.options.bytes_per_sector
    }

    /// Sets bytes per sector before media data is written.
    ///
    /// # Errors
    ///
    /// Returns an error if media data has already been written or the resulting
    /// chunk geometry is invalid.
    pub fn set_bytes_per_sector(&mut self, bytes_per_sector: u32) -> Result<()> {
        self.ensure_configuration_mutable("bytes per sector")?;
        let (chunk_size, chunk_capacity) =
            writer_chunk_geometry(self.options.sectors_per_chunk, bytes_per_sector)?;
        self.options.bytes_per_sector = bytes_per_sector;
        self.chunk_size = chunk_size;
        self.chunk_capacity = chunk_capacity;
        self.encoded_chunks.clear();
        Ok(())
    }

    /// Returns the logical size that would be written after sector padding.
    ///
    /// # Errors
    ///
    /// Returns an error if configured sizes overflow or are inconsistent.
    pub fn logical_size(&self) -> Result<u64> {
        padded_logical_size(
            target_media_input_size(self.logical_input_size, self.options.media_size)?,
            self.options.bytes_per_sector,
        )
    }

    /// Alias for [`EwfWriter::logical_size`].
    ///
    /// # Errors
    ///
    /// Returns the same errors as [`EwfWriter::logical_size`].
    pub fn media_size(&self) -> Result<u64> {
        self.logical_size()
    }

    /// Returns the logical sector count that would be written.
    ///
    /// # Errors
    ///
    /// Returns an error if the logical size cannot be computed.
    pub fn number_of_sectors(&self) -> Result<u64> {
        Ok(self.media_size()? / u64::from(self.options.bytes_per_sector))
    }

    /// Returns the configured maximum segment size in bytes.
    pub fn maximum_segment_size(&self) -> Option<u64> {
        self.options.maximum_segment_size
    }

    /// Sets the maximum segment size before media data is written.
    ///
    /// # Errors
    ///
    /// Returns an error if media data has already been written or the value is
    /// invalid for the current output format.
    pub fn set_maximum_segment_size(&mut self, maximum_segment_size: Option<u64>) -> Result<()> {
        self.ensure_configuration_mutable("maximum segment size")?;
        let mut options = self.options.clone();
        options.maximum_segment_size = normalize_maximum_segment_size(maximum_segment_size);
        validate_options(&options)?;
        self.options = options;
        Ok(())
    }

    /// Sets the declared logical media size before media data is written.
    ///
    /// # Errors
    ///
    /// Returns an error if media data has already been written or the requested
    /// size is smaller than data already written.
    pub fn set_media_size(&mut self, media_size: u64) -> Result<()> {
        self.ensure_configuration_mutable("media size")?;
        let media_size = normalize_media_size(Some(media_size));
        if media_size.is_some_and(|media_size| self.logical_input_size > media_size) {
            return Err(EwfError::Unsupported(
                "writer configured media size is smaller than written data".into(),
            ));
        }
        self.options.media_size = media_size;
        Ok(())
    }

    /// Returns the number of logical chunks that would be written.
    ///
    /// # Errors
    ///
    /// Returns an error if the logical size cannot be computed.
    pub fn number_of_chunks_written(&self) -> Result<u64> {
        Ok(self.logical_size()?.div_ceil(self.chunk_size))
    }

    /// Returns the configured segment set identifier.
    pub fn segment_file_set_identifier(&self) -> Option<[u8; 16]> {
        self.options.set_identifier
    }

    /// Signals future writer operations to abort with [`EwfError::Aborted`].
    pub fn signal_abort(&self) {
        self.abort_signaled.store(true, Ordering::Relaxed);
    }

    /// Sets the segment set identifier before media data is written.
    ///
    /// # Errors
    ///
    /// Returns an error if media data has already been written.
    pub fn set_segment_file_set_identifier(&mut self, set_identifier: [u8; 16]) -> Result<()> {
        self.ensure_configuration_mutable("set identifier")?;
        self.options.set_identifier = Some(set_identifier);
        Ok(())
    }

    /// Returns the configured compression method.
    pub fn compression_method(&self) -> WriteCompression {
        self.options.compression
    }

    /// Sets the compression method before media data is written.
    ///
    /// # Errors
    ///
    /// Returns an error if media data has already been written or `BZip2` is
    /// selected for an EWF1 output format.
    pub fn set_compression_method(&mut self, compression: WriteCompression) -> Result<()> {
        self.ensure_configuration_mutable("compression method")?;
        if matches!(compression, WriteCompression::Bzip2) && !is_ewf2_format(self.options.format) {
            return Err(EwfError::Unsupported(
                "BZip2 writer compression is only supported for EWF2".into(),
            ));
        }
        self.options.compression = compression;
        Ok(())
    }

    /// Returns the configured compression values.
    pub fn compression_values(&self) -> WriteCompressionValues {
        self.options.compression_values
    }

    /// Sets compression values before media data is written.
    ///
    /// # Errors
    ///
    /// Returns an error if media data has already been written.
    pub fn set_compression_values(
        &mut self,
        compression_values: WriteCompressionValues,
    ) -> Result<()> {
        self.ensure_configuration_mutable("compression values")?;
        self.options.compression_values = compression_values;
        Ok(())
    }

    /// Returns the configured media type.
    pub fn media_type(&self) -> Option<MediaType> {
        self.options.media_profile.media_type
    }

    /// Sets the media type before media data is written.
    ///
    /// # Errors
    ///
    /// Returns an error if media data has already been written.
    pub fn set_media_type(&mut self, media_type: Option<MediaType>) -> Result<()> {
        self.ensure_configuration_mutable("media type")?;
        self.options.media_profile.media_type = media_type;
        Ok(())
    }

    /// Returns the configured error granularity in sectors.
    pub fn error_granularity(&self) -> Option<u64> {
        self.options.media_profile.error_granularity
    }

    /// Sets error granularity before media data is written.
    ///
    /// # Errors
    ///
    /// Returns an error if media data has already been written.
    pub fn set_error_granularity(&mut self, error_granularity: Option<u64>) -> Result<()> {
        self.ensure_configuration_mutable("error granularity")?;
        self.options.media_profile.error_granularity = error_granularity;
        Ok(())
    }

    /// Returns media flags derived from format and media profile options.
    pub fn media_flags(&self) -> MediaFlags {
        writer_media_flags(self.options.format, self.options.media_profile)
    }

    /// Sets writable media flags before media data is written.
    ///
    /// The physical flag is controlled by [`WriteFormat`] and cannot be changed
    /// independently.
    ///
    /// # Errors
    ///
    /// Returns an error if media data has already been written or if the
    /// physical flag conflicts with the output format.
    pub fn set_media_flags(&mut self, media_flags: MediaFlags) -> Result<()> {
        self.ensure_configuration_mutable("media flags")?;
        if media_flags.physical != write_format_is_physical(self.options.format) {
            return Err(EwfError::Unsupported(
                "writer physical media flag is controlled by image format".into(),
            ));
        }
        self.options.media_profile.fastbloc = media_flags.fastbloc;
        self.options.media_profile.tableau = media_flags.tableau;
        Ok(())
    }

    /// Copies media geometry and flags from an opened image.
    ///
    /// # Errors
    ///
    /// Returns an error if the source values cannot be represented or conflict
    /// with media data already written.
    pub fn copy_media_values_from_image(&mut self, image: &Image) -> Result<()> {
        self.copy_media_values_from_info(image.info())
    }

    /// Copies media geometry and flags from parsed image metadata.
    ///
    /// # Errors
    ///
    /// Returns an error if the source values cannot be represented or conflict
    /// with media data already written.
    pub fn copy_media_values_from_info(&mut self, info: &ImageInfo) -> Result<()> {
        let mut options = self.options.clone();
        options.copy_media_values_from_info(info)?;
        if options
            .media_size
            .is_some_and(|media_size| self.logical_input_size > media_size)
        {
            return Err(EwfError::Unsupported(
                "writer configured media size is smaller than written data".into(),
            ));
        }
        let (chunk_size, chunk_capacity) =
            writer_chunk_geometry(options.sectors_per_chunk, options.bytes_per_sector)?;
        self.options = options;
        self.chunk_size = chunk_size;
        self.chunk_capacity = chunk_capacity;
        Ok(())
    }

    /// Returns a configured header value by EWF identifier.
    pub fn header_value(&self, identifier: &str) -> Option<std::borrow::Cow<'_, str>> {
        self.options
            .metadata
            .header_value_with_date_format(identifier, self.options.header_values_date_format)
    }

    /// Returns the configured header codepage.
    pub fn header_codepage(&self) -> HeaderCodepage {
        self.options.header_codepage
    }

    /// Sets the header codepage.
    pub fn set_header_codepage(&mut self, header_codepage: HeaderCodepage) {
        self.options.header_codepage = header_codepage;
    }

    /// Returns the configured header date format.
    pub fn header_values_date_format(&self) -> HeaderDateFormat {
        self.options.header_values_date_format
    }

    /// Sets the header date format.
    pub fn set_header_values_date_format(&mut self, date_format: HeaderDateFormat) {
        self.options.header_values_date_format = date_format;
    }

    /// Copies header values from an opened image.
    pub fn copy_header_values_from_image(&mut self, image: &Image) {
        self.copy_header_values_from_info(image.info());
    }

    /// Copies header values from parsed image metadata.
    pub fn copy_header_values_from_info(&mut self, info: &ImageInfo) {
        self.copy_header_values_from_metadata(&info.metadata);
    }

    /// Copies header values from metadata.
    pub fn copy_header_values_from_metadata(&mut self, metadata: &EwfMetadata) {
        self.options.copy_header_values_from_metadata(metadata);
    }

    /// Copies stored hash values from an opened image.
    pub fn copy_hash_values_from_image(&mut self, image: &Image) {
        self.copy_hash_values_from_info(image.info());
    }

    /// Copies stored hash values from parsed image metadata.
    pub fn copy_hash_values_from_info(&mut self, info: &ImageInfo) {
        self.copy_hash_values_from_stored_hashes(&info.stored_hashes);
    }

    /// Copies stored hash values from a hash collection.
    pub fn copy_hash_values_from_stored_hashes(&mut self, hashes: &StoredHashes) {
        self.options.copy_hash_values_from_stored_hashes(hashes);
    }

    /// Sets a header value by EWF identifier and returns the previous value.
    pub fn set_header_value(
        &mut self,
        identifier: &str,
        value: impl Into<String>,
    ) -> Option<String> {
        self.options.metadata.set_header_value(identifier, value)
    }

    /// Returns the number of configured header values.
    pub fn number_of_header_values(&self) -> usize {
        self.options.metadata.number_of_header_values()
    }

    /// Returns a configured header value identifier by enumeration index.
    pub fn header_value_identifier(&self, index: usize) -> Option<&str> {
        self.options.metadata.header_value_identifier(index)
    }

    /// Returns a configured hash string by identifier.
    pub fn hash_value(&self, identifier: &str) -> Option<&str> {
        self.options.hashes.hash_value(identifier)
    }

    /// Sets a configured hash string by identifier and returns the previous value.
    ///
    /// # Errors
    ///
    /// Returns an error if an `MD5` or `SHA1` value is not valid hexadecimal of
    /// the required length.
    pub fn set_hash_value(
        &mut self,
        identifier: impl Into<String>,
        value: impl Into<String>,
    ) -> Result<Option<String>> {
        self.options.hashes.set_hash_value(identifier, value)
    }

    /// Returns the number of configured hash strings.
    pub fn number_of_hash_values(&self) -> usize {
        self.options.hashes.number_of_hash_values()
    }

    /// Returns a configured hash identifier by enumeration index.
    pub fn hash_value_identifier(&self, index: usize) -> Option<&str> {
        self.options.hashes.hash_value_identifier(index)
    }

    /// Returns the configured MD5 hash bytes.
    pub fn md5_hash(&self) -> Option<[u8; 16]> {
        self.options.hashes.md5
    }

    /// Sets the configured MD5 hash bytes.
    ///
    /// # Errors
    ///
    /// Returns an error if an MD5 hash is already configured.
    pub fn set_md5_hash(&mut self, md5: [u8; 16]) -> Result<()> {
        if self.options.hashes.md5.is_some() {
            return Err(EwfError::Unsupported("MD5 hash cannot be changed".into()));
        }
        self.options.hashes.md5 = Some(md5);
        self.options
            .hashes
            .hash_values
            .entry("MD5".to_string())
            .or_insert_with(|| hex_string(&md5));
        Ok(())
    }

    /// Returns the configured SHA1 hash bytes.
    pub fn sha1_hash(&self) -> Option<[u8; 20]> {
        self.options.hashes.sha1
    }

    /// Sets the configured SHA1 hash bytes.
    ///
    /// # Errors
    ///
    /// Returns an error if a SHA1 hash is already configured.
    pub fn set_sha1_hash(&mut self, sha1: [u8; 20]) -> Result<()> {
        if self.options.hashes.sha1.is_some() {
            return Err(EwfError::Unsupported("SHA1 hash cannot be changed".into()));
        }
        self.options.hashes.sha1 = Some(sha1);
        self.options
            .hashes
            .hash_values
            .entry("SHA1".to_string())
            .or_insert_with(|| hex_string(&sha1));
        Ok(())
    }

    /// Returns configured acquisition error ranges.
    pub fn acquisition_errors(&self) -> &[AcquisitionError] {
        &self.options.acquisition_errors
    }

    /// Returns the number of configured acquisition error ranges.
    pub fn number_of_acquisition_errors(&self) -> usize {
        self.options.acquisition_errors.len()
    }

    /// Returns a configured acquisition error range by index.
    pub fn acquisition_error(&self, index: usize) -> Option<&AcquisitionError> {
        self.options.acquisition_errors.get(index)
    }

    /// Appends an acquisition error range.
    ///
    /// # Errors
    ///
    /// This method currently validates no additional constraints and returns
    /// `Ok(())` after appending.
    pub fn append_acquisition_error(&mut self, first_sector: u64, sector_count: u64) -> Result<()> {
        self.options.acquisition_errors.push(AcquisitionError {
            first_sector,
            sector_count,
        });
        Ok(())
    }

    /// Returns configured checksum error ranges.
    pub fn checksum_errors(&self) -> &[SectorRange] {
        &self.options.checksum_errors
    }

    /// Returns the number of configured checksum error ranges.
    pub fn number_of_checksum_errors(&self) -> usize {
        self.options.checksum_errors.len()
    }

    /// Returns a configured checksum error range by index.
    pub fn checksum_error(&self, index: usize) -> Option<&SectorRange> {
        self.options.checksum_errors.get(index)
    }

    /// Appends a checksum error range.
    ///
    /// # Errors
    ///
    /// This method currently validates no additional constraints and returns
    /// `Ok(())` after appending.
    pub fn append_checksum_error(&mut self, first_sector: u64, sector_count: u64) -> Result<()> {
        self.options.checksum_errors.push(SectorRange {
            first_sector,
            sector_count,
        });
        Ok(())
    }

    /// Returns configured session sector ranges.
    pub fn sessions(&self) -> &[SectorRange] {
        &self.options.sessions
    }

    /// Returns the number of configured session sector ranges.
    pub fn number_of_sessions(&self) -> usize {
        self.options.sessions.len()
    }

    /// Returns a configured session sector range by index.
    pub fn session(&self, index: usize) -> Option<&SectorRange> {
        self.options.sessions.get(index)
    }

    /// Appends a session sector range.
    ///
    /// # Errors
    ///
    /// Returns an error if the range values exceed the signed 64-bit range
    /// required by EWF metadata.
    pub fn append_session(&mut self, first_sector: u64, sector_count: u64) -> Result<()> {
        validate_signed_sector_range_value("session", "start sector", first_sector)?;
        validate_signed_sector_range_value("session", "sector count", sector_count)?;
        self.options.sessions.push(SectorRange {
            first_sector,
            sector_count,
        });
        Ok(())
    }

    /// Returns configured track sector ranges.
    pub fn tracks(&self) -> &[SectorRange] {
        &self.options.tracks
    }

    /// Returns the number of configured track sector ranges.
    pub fn number_of_tracks(&self) -> usize {
        self.options.tracks.len()
    }

    /// Returns a configured track sector range by index.
    pub fn track(&self, index: usize) -> Option<&SectorRange> {
        self.options.tracks.get(index)
    }

    /// Appends a track sector range.
    ///
    /// # Errors
    ///
    /// Returns an error if the range values exceed the signed 64-bit range
    /// required by EWF metadata.
    pub fn append_track(&mut self, first_sector: u64, sector_count: u64) -> Result<()> {
        validate_signed_sector_range_value("track", "start sector", first_sector)?;
        validate_signed_sector_range_value("track", "sector count", sector_count)?;
        self.options.tracks.push(SectorRange {
            first_sector,
            sector_count,
        });
        Ok(())
    }

    /// Returns the current logical byte write position.
    pub fn offset(&self) -> u64 {
        self.current_offset
    }

    /// Seeks the writer position and returns the new position.
    ///
    /// # Errors
    ///
    /// Returns an error if the seek would move before the start of the media or
    /// beyond representable bounds.
    pub fn seek_offset(&mut self, position: SeekFrom) -> Result<u64> {
        self.seek_position(position)
    }

    /// Seeks the writer position and returns the new position.
    ///
    /// # Errors
    ///
    /// Returns an error if the seek would move before the start of the media or
    /// beyond representable bounds.
    pub fn seek_position(&mut self, position: SeekFrom) -> Result<u64> {
        let end_size = target_media_input_size(self.logical_input_size, self.options.media_size)?;
        let next = checked_writer_seek(self.current_offset, end_size, position)?;
        self.current_offset = next;
        Ok(next)
    }

    /// Finalizes a complete image and writes a terminal `done` marker.
    ///
    /// # Errors
    ///
    /// Returns an error if output cannot be prepared, encoded, written, flushed,
    /// or mirrored.
    pub fn finish(self) -> Result<WriteResult> {
        self.finish_with_terminal_section(TerminalSection::Done)
    }

    /// Finalizes an incomplete image with a continuation marker.
    ///
    /// # Errors
    ///
    /// Returns an error if output cannot be prepared, encoded, written, flushed,
    /// or mirrored.
    pub fn finish_incomplete(self) -> Result<WriteResult> {
        self.finish_with_terminal_section(TerminalSection::Next)
    }

    fn finish_with_terminal_section(self, terminal: TerminalSection) -> Result<WriteResult> {
        let PreparedWrite {
            path,
            options,
            chunks,
            mut spool,
            logical_size,
            chunk_size,
            chunk_count,
            chunk_count_u32,
            sector_count,
        } = self.prepare_write()?;

        if is_ewf2_format(options.format) {
            let groups = segment_groups(
                &chunks,
                options.maximum_segment_size,
                &options,
                sector_count,
                u64::from(chunk_count_u32),
            )?;
            let group_count = groups.len();
            let mut segment_paths = Vec::with_capacity(group_count);
            let mut first_chunk = 0_u64;
            for (index, group) in groups.into_iter().enumerate() {
                let group_chunks = &chunks[group];
                let segment_number = u32::try_from(index + 1).map_err(|_| {
                    EwfError::Unsupported("EWF2 writer segment count exceeds u32".into())
                })?;
                let terminal_section_type = if index + 1 == group_count {
                    terminal.ewf2_type()
                } else {
                    EWF2_NEXT_SECTION
                };
                let segment_path = ewf2_segment_path(&path, index + 1)?;
                let mut file = File::create(&segment_path)?;
                write_ewf2_segment(
                    &mut file,
                    &mut spool,
                    group_chunks,
                    &options,
                    Ewf2SegmentWriteContext {
                        segment_number,
                        first_chunk,
                        total_chunk_count: chunk_count_u32,
                        sector_count,
                        terminal_section_type,
                    },
                )?;
                file.flush()?;
                first_chunk = first_chunk
                    .checked_add(u64::try_from(group_chunks.len()).expect("usize fits u64"))
                    .ok_or_else(|| {
                        EwfError::Malformed("writer EWF2 first chunk overflow".into())
                    })?;
                segment_paths.push(segment_path);
            }
            remove_stale_segment_files(&path, group_count, true)?;
            let secondary_segment_paths = mirror_secondary_segment_files(
                &path,
                options.secondary_segment_filename.as_deref(),
                &segment_paths,
                group_count,
                true,
            )?;

            return Ok(WriteResult {
                segment_paths,
                secondary_segment_paths,
                logical_size,
                chunk_size,
                chunk_count,
            });
        }

        let groups = segment_groups(
            &chunks,
            options.maximum_segment_size,
            &options,
            sector_count,
            u64::from(chunk_count_u32),
        )?;
        let group_count = groups.len();
        let mut segment_paths = Vec::with_capacity(group_count);
        for (index, group) in groups.into_iter().enumerate() {
            let group_chunks = &chunks[group];
            let segment_number = u16::try_from(index + 1).map_err(|_| {
                EwfError::Unsupported("EWF1 writer segment count exceeds u16".into())
            })?;
            let is_last = index + 1 == group_count;
            let segment_terminal = if is_last {
                terminal
            } else {
                TerminalSection::Done
            };
            let sections = Ewf1SegmentSections::for_segment(
                index == 0,
                is_last && terminal == TerminalSection::Done,
            );
            let segment_path = segment_path(&path, index + 1)?;
            let mut file = File::create(&segment_path)?;
            write_ewf1_segment(
                &mut file,
                &mut spool,
                group_chunks,
                &options,
                Ewf1SegmentWriteContext {
                    segment_number,
                    chunk_count: chunk_count_u32,
                    sector_count,
                    sections,
                    terminal_section: segment_terminal,
                },
            )?;
            file.flush()?;
            segment_paths.push(segment_path);
        }
        remove_stale_segment_files(&path, group_count, false)?;
        let secondary_segment_paths = mirror_secondary_segment_files(
            &path,
            options.secondary_segment_filename.as_deref(),
            &segment_paths,
            group_count,
            false,
        )?;

        Ok(WriteResult {
            segment_paths,
            secondary_segment_paths,
            logical_size,
            chunk_size,
            chunk_count,
        })
    }

    /// Alias for [`EwfWriter::finish`].
    ///
    /// # Errors
    ///
    /// Returns the same errors as [`EwfWriter::finish`].
    pub fn write_finalize(self) -> Result<WriteResult> {
        self.finish()
    }

    /// Finalizes the image to one supplied writer.
    ///
    /// # Errors
    ///
    /// Returns an error if the image requires multiple output segments, if
    /// secondary output is configured, or if output preparation/writing fails.
    pub fn finish_to_writer<W: Write>(self, writer: &mut W) -> Result<WriteResult> {
        let path = self.path.clone();
        self.finish_to_segment_writers([(path, writer)])
    }

    /// Finalizes the image to explicitly supplied segment writers.
    ///
    /// The number of supplied writers must match the number of output segments
    /// implied by the current writer configuration.
    ///
    /// # Errors
    ///
    /// Returns an error if secondary output is configured, if the writer count
    /// does not match the computed segment count, or if output
    /// preparation/writing fails.
    pub fn finish_to_segment_writers<P, W, I>(self, segment_writers: I) -> Result<WriteResult>
    where
        P: Into<PathBuf>,
        W: Write,
        I: IntoIterator<Item = (P, W)>,
    {
        let PreparedWrite {
            path: _,
            options,
            chunks,
            mut spool,
            logical_size,
            chunk_size,
            chunk_count,
            chunk_count_u32,
            sector_count,
        } = self.prepare_write()?;
        if options.secondary_segment_filename.is_some() {
            return Err(EwfError::Unsupported(
                "secondary segment output requires file-backed finish".into(),
            ));
        }

        let segment_writers: Vec<_> = segment_writers
            .into_iter()
            .map(|(path, writer)| (path.into(), writer))
            .collect();
        let groups = segment_groups(
            &chunks,
            options.maximum_segment_size,
            &options,
            sector_count,
            u64::from(chunk_count_u32),
        )?;
        if segment_writers.len() != groups.len() {
            return Err(EwfError::Unsupported(
                "finish_to_segment_writers requires exactly one writer per output segment".into(),
            ));
        }
        let group_count = groups.len();
        let mut segment_paths = Vec::with_capacity(group_count);

        if is_ewf2_format(options.format) {
            let mut first_chunk = 0_u64;
            for (index, ((segment_path, mut writer), group)) in
                segment_writers.into_iter().zip(groups).enumerate()
            {
                let group_chunks = &chunks[group];
                let segment_number = u32::try_from(index + 1).map_err(|_| {
                    EwfError::Unsupported("EWF2 writer segment count exceeds u32".into())
                })?;
                let terminal_section_type = if index + 1 == group_count {
                    EWF2_DONE_SECTION
                } else {
                    EWF2_NEXT_SECTION
                };
                write_ewf2_segment(
                    &mut writer,
                    &mut spool,
                    group_chunks,
                    &options,
                    Ewf2SegmentWriteContext {
                        segment_number,
                        first_chunk,
                        total_chunk_count: chunk_count_u32,
                        sector_count,
                        terminal_section_type,
                    },
                )?;
                writer.flush()?;
                first_chunk = first_chunk
                    .checked_add(u64::try_from(group_chunks.len()).expect("usize fits u64"))
                    .ok_or_else(|| {
                        EwfError::Malformed("writer EWF2 first chunk overflow".into())
                    })?;
                segment_paths.push(segment_path);
            }
        } else {
            for (index, ((segment_path, mut writer), group)) in
                segment_writers.into_iter().zip(groups).enumerate()
            {
                let group_chunks = &chunks[group];
                let segment_number = u16::try_from(index + 1).map_err(|_| {
                    EwfError::Unsupported("EWF1 writer segment count exceeds u16".into())
                })?;
                let sections =
                    Ewf1SegmentSections::for_segment(index == 0, index + 1 == group_count);
                write_ewf1_segment(
                    &mut writer,
                    &mut spool,
                    group_chunks,
                    &options,
                    Ewf1SegmentWriteContext {
                        segment_number,
                        chunk_count: chunk_count_u32,
                        sector_count,
                        sections,
                        terminal_section: TerminalSection::Done,
                    },
                )?;
                writer.flush()?;
                segment_paths.push(segment_path);
            }
        }

        Ok(WriteResult {
            segment_paths,
            secondary_segment_paths: Vec::new(),
            logical_size,
            chunk_size,
            chunk_count,
        })
    }

    fn write_to_current(&mut self, data: &[u8]) -> Result<usize> {
        self.ensure_not_aborted()?;
        let data_len = u64::try_from(data.len())
            .map_err(|_| EwfError::Malformed("writer data length does not fit u64".into()))?;
        let end_offset = self
            .current_offset
            .checked_add(data_len)
            .ok_or_else(|| EwfError::Malformed("writer logical input size overflow".into()))?;
        if self
            .options
            .media_size
            .is_some_and(|media_size| end_offset > media_size)
        {
            return Err(EwfError::Unsupported(
                "writer write exceeds configured media size".into(),
            ));
        }
        self.forget_encoded_chunks_in_range(self.current_offset, end_offset);
        self.raw.write_at(self.current_offset, data)?;
        self.current_offset = end_offset;
        self.logical_input_size = self.logical_input_size.max(end_offset);
        Ok(data.len())
    }

    fn prepare_write(self) -> Result<PreparedWrite> {
        self.ensure_not_aborted()?;
        let logical_size = self.logical_size()?;
        let sector_count = logical_size / u64::from(self.options.bytes_per_sector);

        let EwfWriter {
            path,
            mut options,
            chunk_size,
            chunk_capacity,
            mut raw,
            encoded_chunks,
            ..
        } = self;

        let EncodedSpool {
            chunks,
            spool,
            computed_md5,
            computed_sha1,
        } = encode_raw_spool(
            &mut raw,
            encoded_chunks,
            logical_size,
            chunk_capacity,
            chunk_size,
            &options,
        )?;

        options.hashes = effective_write_hashes(&options.hashes, computed_md5, computed_sha1);
        validate_session_ranges("sessions", &options.sessions, sector_count)?;
        validate_session_ranges("tracks", &options.tracks, sector_count)?;
        let chunk_count = u64::try_from(chunks.len())
            .map_err(|_| EwfError::Malformed("writer chunk count does not fit u64".into()))?;
        let chunk_count_u32 = u32::try_from(chunk_count)
            .map_err(|_| EwfError::Unsupported("writer chunk count exceeds u32".into()))?;

        Ok(PreparedWrite {
            path,
            options,
            chunks,
            spool,
            logical_size,
            chunk_size,
            chunk_count,
            chunk_count_u32,
            sector_count,
        })
    }

    fn ensure_not_aborted(&self) -> Result<()> {
        if self.abort_signaled.load(Ordering::Relaxed) {
            return Err(EwfError::Aborted);
        }
        Ok(())
    }

    fn ensure_configuration_mutable(&self, label: &str) -> Result<()> {
        if self.logical_input_size == 0 {
            return Ok(());
        }
        Err(EwfError::Unsupported(format!(
            "writer {label} cannot be changed after media data has been written"
        )))
    }

    fn remember_encoded_data_chunk_at(
        &mut self,
        chunk: &EncodedDataChunk,
        offset: u64,
        decoded_len: usize,
    ) {
        let Some(encoded) = remembered_encoded_data_chunk(
            chunk,
            &self.options,
            self.chunk_size,
            offset,
            decoded_len,
        ) else {
            return;
        };
        self.encoded_chunks
            .insert(offset / self.chunk_size, encoded);
    }

    fn forget_encoded_chunks_in_range(&mut self, start_offset: u64, end_offset: u64) {
        if start_offset >= end_offset || self.encoded_chunks.is_empty() {
            return;
        }

        let first_chunk = start_offset / self.chunk_size;
        let last_chunk = (end_offset - 1) / self.chunk_size;
        let keys: Vec<_> = self
            .encoded_chunks
            .range(first_chunk..=last_chunk)
            .map(|(chunk_index, _)| *chunk_index)
            .collect();
        for chunk_index in keys {
            self.encoded_chunks.remove(&chunk_index);
        }
    }
}

fn target_media_input_size(written_size: u64, configured_media_size: Option<u64>) -> Result<u64> {
    match configured_media_size {
        Some(media_size) if written_size > media_size => Err(EwfError::Unsupported(
            "writer configured media size is smaller than written data".into(),
        )),
        Some(media_size) => Ok(media_size),
        None => Ok(written_size),
    }
}

fn padded_logical_size(logical_input_size: u64, bytes_per_sector: u32) -> Result<u64> {
    let bytes_per_sector = u64::from(bytes_per_sector);
    let sector_count = logical_input_size.div_ceil(bytes_per_sector);
    sector_count
        .checked_mul(bytes_per_sector)
        .ok_or_else(|| EwfError::Malformed("writer logical size overflow".into()))
}

fn required_media_u32(value: Option<u64>, label: &str) -> Result<u32> {
    let value = value.ok_or_else(|| {
        EwfError::Unsupported(format!("cannot copy media values without {label}"))
    })?;
    u32::try_from(value)
        .map_err(|_| EwfError::Unsupported(format!("copied {label} does not fit u32")))
}

fn write_format_from_image_info(info: &ImageInfo) -> WriteFormat {
    match info.format {
        Format::Ewf2 if image_info_is_physical(info) => WriteFormat::Ewf2Physical,
        Format::Ewf2 => WriteFormat::Ewf2Logical,
        Format::Ewf1 if info.format_profile == FormatProfile::Smart => WriteFormat::Ewf1Smart,
        Format::Ewf1 if image_info_is_physical(info) => WriteFormat::Ewf1Physical,
        Format::Ewf1 => WriteFormat::Ewf1Logical,
    }
}

fn image_info_is_physical(info: &ImageInfo) -> bool {
    !matches!(info.media.media_type, Some(MediaType::SingleFiles))
        && info.media.media_flags.physical
}

fn write_compression_from_media_method(method: CompressionMethod) -> Result<WriteCompression> {
    match method {
        CompressionMethod::None => Ok(WriteCompression::None),
        CompressionMethod::Zlib => Ok(WriteCompression::Zlib),
        CompressionMethod::Bzip2 => Ok(WriteCompression::Bzip2),
        CompressionMethod::Unknown(value) => Err(EwfError::Unsupported(format!(
            "cannot copy unknown compression method {value}"
        ))),
    }
}

fn write_compression_values_from_media_values(
    values: CompressionValues,
) -> Result<WriteCompressionValues> {
    if values.flags.pattern_fill {
        return Err(EwfError::Unsupported(
            "cannot copy pattern fill compression flag".into(),
        ));
    }
    if values.flags.unknown_bits != 0 {
        return Err(EwfError::Unsupported(format!(
            "cannot copy unknown compression flags 0x{:02x}",
            values.flags.unknown_bits
        )));
    }

    Ok(WriteCompressionValues {
        level: write_compression_level_from_media_level(values.level)?,
        empty_block: values.flags.empty_block,
    })
}

fn write_compression_level_from_media_level(
    level: CompressionLevel,
) -> Result<WriteCompressionLevel> {
    match level {
        CompressionLevel::Default => Ok(WriteCompressionLevel::Default),
        CompressionLevel::None => Ok(WriteCompressionLevel::None),
        CompressionLevel::Fast => Ok(WriteCompressionLevel::Fast),
        CompressionLevel::Best => Ok(WriteCompressionLevel::Best),
        CompressionLevel::Unknown(value) => Err(EwfError::Unsupported(format!(
            "cannot copy unknown compression level {value}"
        ))),
    }
}

fn rewrite_options_from_image_info(info: &ImageInfo) -> Result<WriteOptions> {
    let mut options = WriteOptions::default();
    options.copy_media_values_from_info(info)?;
    options.copy_header_values_from_info(info);
    options.header_codepage = info.header_codepage;
    options.header_values_date_format = info.header_values_date_format;
    options
        .acquisition_errors
        .clone_from(&info.acquisition_errors);
    options.sessions.clone_from(&info.sessions);
    options.tracks.clone_from(&info.tracks);
    options.memory_extents.clone_from(&info.memory_extents);
    options.single_files.clone_from(&info.single_files);
    options.ewf2_single_files_tables = info.ewf2_single_files_tables.clone();
    options
        .ewf2_increment_data
        .clone_from(&info.ewf2_increment_data);
    options
        .ewf2_final_information
        .clone_from(&info.ewf2_final_information);
    options
        .ewf2_restart_data
        .clone_from(&info.ewf2_restart_data);
    options
        .ewf2_analytical_data
        .clone_from(&info.ewf2_analytical_data);
    validate_options(&options)?;
    Ok(options)
}

fn copy_image_media_to_writer(image: &Image, writer: &mut EwfWriter) -> Result<()> {
    if let Some(chunk_count) = image.number_of_chunks() {
        for chunk_index in 0..chunk_count {
            let chunk = image.read_encoded_data_chunk(chunk_index)?;
            writer.write_encoded_data_chunk(&chunk)?;
        }
        return Ok(());
    }

    copy_image_media_bytes_to_writer(image, writer)
}

fn copy_image_media_bytes_to_writer(image: &Image, writer: &mut EwfWriter) -> Result<()> {
    let media_size = image.media_size();
    let buffer_size = writer.chunk_capacity.clamp(1, 1024 * 1024);
    let mut buffer = vec![0; buffer_size];
    let mut offset = 0_u64;

    while offset < media_size {
        let remaining = media_size - offset;
        let take = usize::try_from(remaining.min(buffer.len() as u64))
            .expect("source image copy is bounded by buffer length");
        let read = image.read_at(&mut buffer[..take], offset)?;
        if read != take {
            return Err(EwfError::Malformed(format!(
                "source image read returned {read} bytes, expected {take}"
            )));
        }
        writer.write_all(&buffer[..take])?;
        offset = offset
            .checked_add(u64::try_from(take).expect("usize fits u64"))
            .ok_or_else(|| EwfError::Malformed("source image copy offset overflow".into()))?;
    }

    Ok(())
}

impl std::io::Write for EwfWriter {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        self.write_all(buf).map_err(std::io::Error::other)?;
        Ok(buf.len())
    }

    fn flush(&mut self) -> std::io::Result<()> {
        Ok(())
    }
}

impl std::io::Seek for EwfWriter {
    fn seek(&mut self, pos: SeekFrom) -> std::io::Result<u64> {
        self.seek_position(pos).map_err(std::io::Error::other)
    }

    fn stream_position(&mut self) -> std::io::Result<u64> {
        Ok(self.current_offset)
    }
}

struct WriteHashState {
    md5: Md5,
    sha1: Sha1,
}

impl WriteHashState {
    fn new() -> Self {
        Self {
            md5: Md5::new(),
            sha1: Sha1::new(),
        }
    }

    fn update(&mut self, data: &[u8]) {
        self.md5.update(data);
        self.sha1.update(data);
    }

    fn finalize(self) -> ([u8; 16], [u8; 20]) {
        (self.md5.finalize().into(), self.sha1.finalize().into())
    }
}

fn validate_options(options: &WriteOptions) -> Result<()> {
    if options.sectors_per_chunk == 0 {
        return Err(EwfError::Malformed(
            "writer sectors_per_chunk is zero".into(),
        ));
    }
    if options.bytes_per_sector == 0 {
        return Err(EwfError::Malformed(
            "writer bytes_per_sector is zero".into(),
        ));
    }
    if matches!(options.compression, WriteCompression::Bzip2) && !is_ewf2_format(options.format) {
        return Err(EwfError::Unsupported(
            "BZip2 writer compression is only supported for EWF2".into(),
        ));
    }
    if matches!(options.compression, WriteCompression::Bzip2)
        && options.compression_values.level == WriteCompressionLevel::None
    {
        return Err(EwfError::Unsupported(
            "BZip2 writer compression does not support none compression level".into(),
        ));
    }
    if options.single_files.is_some()
        && !matches!(
            options.format,
            WriteFormat::Ewf1Logical | WriteFormat::Ewf2Logical
        )
    {
        return Err(EwfError::Unsupported(
            "single files catalog writing is only supported for logical images".into(),
        ));
    }
    if !options.ewf2_single_files_tables.is_empty() && options.format != WriteFormat::Ewf2Logical {
        return Err(EwfError::Unsupported(
            "single files auxiliary table writing is only supported for EWF2 logical images".into(),
        ));
    }
    if !options.memory_extents.is_empty() && !is_ewf2_format(options.format) {
        return Err(EwfError::Unsupported(
            "memory extents writing is only supported for EWF2 images".into(),
        ));
    }
    if (!options.ewf2_increment_data.is_empty() || options.ewf2_final_information.is_some())
        && !is_ewf2_format(options.format)
    {
        return Err(EwfError::Unsupported(
            "opaque EWF2 section writing is only supported for EWF2 images".into(),
        ));
    }
    if (options.ewf2_restart_data.is_some() || options.ewf2_analytical_data.is_some())
        && !is_ewf2_format(options.format)
    {
        return Err(EwfError::Unsupported(
            "EWF2 application data writing is only supported for EWF2 images".into(),
        ));
    }
    Ok(())
}

fn normalize_maximum_segment_size(maximum_segment_size: Option<u64>) -> Option<u64> {
    maximum_segment_size.filter(|size| *size != 0)
}

fn normalize_media_size(media_size: Option<u64>) -> Option<u64> {
    media_size.filter(|size| *size != 0)
}

fn writer_chunk_geometry(sectors_per_chunk: u32, bytes_per_sector: u32) -> Result<(u64, usize)> {
    if sectors_per_chunk == 0 {
        return Err(EwfError::Malformed(
            "writer sectors_per_chunk is zero".into(),
        ));
    }
    if bytes_per_sector == 0 {
        return Err(EwfError::Malformed(
            "writer bytes_per_sector is zero".into(),
        ));
    }

    let chunk_size = u64::from(sectors_per_chunk)
        .checked_mul(u64::from(bytes_per_sector))
        .ok_or_else(|| EwfError::Malformed("writer chunk size overflow".into()))?;
    let chunk_capacity = usize::try_from(chunk_size)
        .map_err(|_| EwfError::Unsupported("writer chunk size does not fit usize".into()))?;
    Ok((chunk_size, chunk_capacity))
}

fn validate_write_data_chunk(chunk: &DataChunk) -> Result<()> {
    if chunk.corrupted {
        return Err(EwfError::Malformed(
            "writer cannot write corrupted data chunk".into(),
        ));
    }
    if chunk.data.len() != chunk.logical_size {
        return Err(EwfError::Malformed(
            "writer data chunk payload length does not match logical size".into(),
        ));
    }

    Ok(())
}

fn decode_write_encoded_data_chunk(chunk: &EncodedDataChunk) -> Result<Vec<u8>> {
    validate_write_encoded_data_chunk(chunk)?;
    decode_chunk(
        &chunk.data,
        encoded_data_chunk_encoding(chunk.encoding),
        chunk.logical_size,
    )
}

fn validate_write_encoded_data_chunk(chunk: &EncodedDataChunk) -> Result<()> {
    let encoded_size = usize::try_from(chunk.encoded_size)
        .map_err(|_| EwfError::Malformed("writer encoded chunk size does not fit usize".into()))?;
    if chunk.data.len() != encoded_size {
        return Err(EwfError::Malformed(
            "writer encoded data chunk payload length does not match encoded size".into(),
        ));
    }

    Ok(())
}

fn encoded_data_chunk_encoding(encoding: DataChunkEncoding) -> ChunkEncoding {
    match encoding {
        DataChunkEncoding::Raw => ChunkEncoding::Raw,
        DataChunkEncoding::Zlib => ChunkEncoding::Zlib,
        DataChunkEncoding::Bzip2 => ChunkEncoding::Bzip2,
        DataChunkEncoding::PatternFill(pattern) => ChunkEncoding::PatternFill(pattern),
    }
}

fn remembered_encoded_data_chunk(
    chunk: &EncodedDataChunk,
    options: &WriteOptions,
    target_chunk_size: u64,
    offset: u64,
    decoded_len: usize,
) -> Option<RememberedEncodedChunk> {
    if !offset.is_multiple_of(target_chunk_size) || decoded_len != chunk.logical_size {
        return None;
    }
    if u64::try_from(decoded_len).ok()? > target_chunk_size {
        return None;
    }
    if !encoded_data_chunk_encoding_compatible(chunk.encoding, options) {
        return None;
    }
    if validate_encoded_size(
        chunk.encoded_size,
        target_chunk_size,
        encoded_data_chunk_encoding(chunk.encoding),
    )
    .is_err()
    {
        return None;
    }

    let encoded = match chunk.encoding {
        DataChunkEncoding::Raw => {
            if chunk.has_checksum && !raw_encoded_data_chunk_checksum_is_valid(chunk) {
                return None;
            }
            EncodedChunk {
                bytes: chunk.data.clone(),
                compressed: false,
                has_checksum: chunk.has_checksum,
                pattern_fill: None,
            }
        }
        DataChunkEncoding::Zlib | DataChunkEncoding::Bzip2 => EncodedChunk {
            bytes: chunk.data.clone(),
            compressed: true,
            has_checksum: false,
            pattern_fill: None,
        },
        DataChunkEncoding::PatternFill(pattern) => EncodedChunk {
            bytes: Vec::new(),
            compressed: true,
            has_checksum: false,
            pattern_fill: Some(pattern),
        },
    };

    Some(RememberedEncodedChunk {
        logical_size: decoded_len,
        encoding: chunk.encoding,
        encoded,
    })
}

fn encoded_data_chunk_encoding_compatible(
    encoding: DataChunkEncoding,
    options: &WriteOptions,
) -> bool {
    match encoding {
        DataChunkEncoding::Raw => true,
        DataChunkEncoding::Zlib => options.compression != WriteCompression::Bzip2,
        DataChunkEncoding::Bzip2 => {
            is_ewf2_format(options.format) && options.compression == WriteCompression::Bzip2
        }
        DataChunkEncoding::PatternFill(_) => is_ewf2_format(options.format),
    }
}

fn raw_encoded_data_chunk_checksum_is_valid(chunk: &EncodedDataChunk) -> bool {
    let Some(checksum_offset) = chunk.logical_size.checked_add(4) else {
        return false;
    };
    if chunk.data.len() != checksum_offset {
        return false;
    }
    let expected = adler32(&chunk.data[..chunk.logical_size]).to_le_bytes();
    chunk.data[chunk.logical_size..] == expected
}

fn validate_session_ranges(
    label: &str,
    ranges: &[SectorRange],
    media_sector_count: u64,
) -> Result<()> {
    validate_sector_ranges(label, ranges, media_sector_count)?;
    if ranges.is_empty() {
        return Ok(());
    }

    let mut expected_start = 0_u64;
    for range in ranges {
        if range.first_sector != expected_start {
            return Err(EwfError::Unsupported(format!(
                "writer {label} must cover the media contiguously from sector 0"
            )));
        }
        expected_start = range
            .first_sector
            .checked_add(range.sector_count)
            .ok_or_else(|| EwfError::Malformed(format!("writer {label} range overflow")))?;
    }
    if expected_start != media_sector_count {
        return Err(EwfError::Unsupported(format!(
            "writer {label} must end at the media sector count"
        )));
    }

    Ok(())
}

fn validate_sector_ranges(
    label: &str,
    ranges: &[SectorRange],
    media_sector_count: u64,
) -> Result<()> {
    let mut previous_end = 0_u64;
    for range in ranges {
        if range.sector_count == 0 {
            return Err(EwfError::Unsupported(format!(
                "writer {label} cannot contain zero-length ranges"
            )));
        }
        if range.first_sector < previous_end {
            return Err(EwfError::Unsupported(format!(
                "writer {label} ranges must be sorted and non-overlapping"
            )));
        }
        let end = range
            .first_sector
            .checked_add(range.sector_count)
            .ok_or_else(|| EwfError::Malformed(format!("writer {label} range overflow")))?;
        if end > media_sector_count {
            return Err(EwfError::Unsupported(format!(
                "writer {label} range exceeds the media sector count"
            )));
        }
        previous_end = end;
    }

    Ok(())
}

fn validate_signed_sector_range_value(label: &str, field: &str, value: u64) -> Result<()> {
    if value > SIGNED_SECTOR_RANGE_MAX {
        return Err(EwfError::Unsupported(format!(
            "writer {label} {field} exceeds signed 64-bit range"
        )));
    }
    Ok(())
}

fn write_ewf1_segment<W: Write>(
    writer: &mut W,
    spool: &mut ChunkSpool,
    chunks: &[ChunkDescriptor],
    options: &WriteOptions,
    context: Ewf1SegmentWriteContext,
) -> Result<()> {
    u32::try_from(chunks.len())
        .map_err(|_| EwfError::Unsupported("EWF1 writer segment chunk count exceeds u32".into()))?;
    let header = if context.sections.contains(Ewf1SegmentSections::HEADER) {
        header_payload(
            &options.metadata,
            options.header_codepage,
            options.compression_values.level,
        )?
    } else {
        None
    };
    let header2 = if context.sections.contains(Ewf1SegmentSections::HEADER) {
        header2_payload(&options.metadata, options.compression_values.level)?
    } else {
        None
    };
    let xheader = if context.sections.contains(Ewf1SegmentSections::HEADER) {
        xheader_payload(&options.metadata, options.compression_values.level)?
    } else {
        None
    };
    let digest = context
        .sections
        .contains(Ewf1SegmentSections::DIGEST)
        .then(|| digest_payload(&options.hashes))
        .flatten();
    let xhash = if context.sections.contains(Ewf1SegmentSections::DIGEST) {
        xhash_payload(&options.hashes, options.compression_values.level)?
    } else {
        None
    };
    let error2 = if context.sections.contains(Ewf1SegmentSections::ERRORS) {
        ewf1_error2_payload(&options.acquisition_errors)?
    } else {
        None
    };
    let session = if context.sections.contains(Ewf1SegmentSections::SESSIONS) {
        ewf1_session_payload(&options.sessions, &options.tracks)?
    } else {
        None
    };
    let ltree = if context.sections.contains(Ewf1SegmentSections::DIGEST)
        && options.format == WriteFormat::Ewf1Logical
    {
        options
            .single_files
            .as_ref()
            .map(ewf1_ltree_payload)
            .transpose()?
    } else {
        None
    };
    let header_desc_offset = ewf1::FILE_HEADER_SIZE as u64;
    let volume_data_size = volume_data_size(options.format);
    let header2_desc_offset = if let Some(header) = &header {
        header_desc_offset
            .checked_add(ewf1::SECTION_DESCRIPTOR_SIZE as u64)
            .and_then(|value| value.checked_add(u64::try_from(header.len()).ok()?))
            .ok_or_else(|| EwfError::Malformed("writer volume descriptor offset overflow".into()))?
    } else {
        header_desc_offset
    };
    let xheader_desc_offset = if let Some(header2) = &header2 {
        header2_desc_offset
            .checked_add(ewf1::SECTION_DESCRIPTOR_SIZE as u64)
            .and_then(|value| value.checked_add(u64::try_from(header2.len()).ok()?))
            .ok_or_else(|| EwfError::Malformed("writer volume descriptor offset overflow".into()))?
    } else {
        header2_desc_offset
    };
    let volume_desc_offset = if let Some(xheader) = &xheader {
        xheader_desc_offset
            .checked_add(ewf1::SECTION_DESCRIPTOR_SIZE as u64)
            .and_then(|value| value.checked_add(u64::try_from(xheader.len()).ok()?))
            .ok_or_else(|| EwfError::Malformed("writer volume descriptor offset overflow".into()))?
    } else {
        xheader_desc_offset
    };
    let volume_data_offset = volume_desc_offset + ewf1::SECTION_DESCRIPTOR_SIZE as u64;
    let session_desc_offset = volume_data_offset + volume_data_size;
    let sectors_desc_offset = if let Some(session) = &session {
        session_desc_offset
            .checked_add(ewf1::SECTION_DESCRIPTOR_SIZE as u64)
            .and_then(|value| value.checked_add(u64::try_from(session.len()).ok()?))
            .ok_or_else(|| {
                EwfError::Malformed("writer sectors descriptor offset overflow".into())
            })?
    } else {
        session_desc_offset
    };
    let table_footer_bytes = if matches!(options.format, WriteFormat::Ewf1Smart) {
        0
    } else {
        4
    };
    let writes_table2 = matches!(
        options.format,
        WriteFormat::Ewf1Physical | WriteFormat::Ewf1Logical
    );
    let group_layouts = ewf1_table_group_layouts(
        chunks,
        sectors_desc_offset,
        table_footer_bytes,
        writes_table2,
    )?;
    let post_table_desc_offset = group_layouts
        .last()
        .map_or(sectors_desc_offset, |layout| layout.end_offset);
    let ltree_desc_offset = post_table_desc_offset;
    let error2_desc_offset = if let Some(ltree) = &ltree {
        ltree_desc_offset
            .checked_add(ewf1::SECTION_DESCRIPTOR_SIZE as u64)
            .and_then(|value| value.checked_add(u64::try_from(ltree.len()).ok()?))
            .ok_or_else(|| EwfError::Malformed("writer error2 descriptor offset overflow".into()))?
    } else {
        post_table_desc_offset
    };
    let digest_desc_offset = if let Some(error2) = &error2 {
        error2_desc_offset
            .checked_add(ewf1::SECTION_DESCRIPTOR_SIZE as u64)
            .and_then(|value| value.checked_add(u64::try_from(error2.len()).ok()?))
            .ok_or_else(|| EwfError::Malformed("writer digest descriptor offset overflow".into()))?
    } else {
        error2_desc_offset
    };
    let xhash_desc_offset = if let Some(digest) = &digest {
        digest_desc_offset
            .checked_add(ewf1::SECTION_DESCRIPTOR_SIZE as u64)
            .and_then(|value| value.checked_add(u64::try_from(digest.len()).ok()?))
            .ok_or_else(|| EwfError::Malformed("writer xhash descriptor offset overflow".into()))?
    } else {
        digest_desc_offset
    };
    let done_desc_offset = if let Some(xhash) = &xhash {
        xhash_desc_offset
            .checked_add(ewf1::SECTION_DESCRIPTOR_SIZE as u64)
            .and_then(|value| value.checked_add(u64::try_from(xhash.len()).ok()?))
            .ok_or_else(|| EwfError::Malformed("writer done descriptor offset overflow".into()))?
    } else {
        xhash_desc_offset
    };
    let after_tables_desc_offset = if ltree.is_some() {
        ltree_desc_offset
    } else if error2.is_some() {
        error2_desc_offset
    } else if digest.is_some() {
        digest_desc_offset
    } else if xhash.is_some() {
        xhash_desc_offset
    } else {
        done_desc_offset
    };
    let after_ltree_desc_offset = if error2.is_some() {
        error2_desc_offset
    } else if digest.is_some() {
        digest_desc_offset
    } else if xhash.is_some() {
        xhash_desc_offset
    } else {
        done_desc_offset
    };
    let after_error2_desc_offset = if digest.is_some() {
        digest_desc_offset
    } else if xhash.is_some() {
        xhash_desc_offset
    } else {
        done_desc_offset
    };
    let after_digest_desc_offset = if xhash.is_some() {
        xhash_desc_offset
    } else {
        done_desc_offset
    };

    writer.write_all(ewf1_signature(options.format))?;
    writer.write_all(&[1])?;
    writer.write_all(&context.segment_number.to_le_bytes())?;
    writer.write_all(&0_u16.to_le_bytes())?;

    if let Some(header) = &header {
        writer.write_all(&section_desc(
            b"header",
            if header2.is_some() {
                header2_desc_offset
            } else if xheader.is_some() {
                xheader_desc_offset
            } else {
                volume_desc_offset
            },
            ewf1::SECTION_DESCRIPTOR_SIZE as u64
                + u64::try_from(header.len()).expect("usize fits u64"),
        ))?;
        writer.write_all(header)?;
    }

    if let Some(header2) = &header2 {
        writer.write_all(&section_desc(
            b"header2",
            if xheader.is_some() {
                xheader_desc_offset
            } else {
                volume_desc_offset
            },
            ewf1::SECTION_DESCRIPTOR_SIZE as u64
                + u64::try_from(header2.len()).expect("usize fits u64"),
        ))?;
        writer.write_all(header2)?;
    }

    if let Some(xheader) = &xheader {
        writer.write_all(&section_desc(
            b"xheader",
            volume_desc_offset,
            ewf1::SECTION_DESCRIPTOR_SIZE as u64
                + u64::try_from(xheader.len()).expect("usize fits u64"),
        ))?;
        writer.write_all(xheader)?;
    }

    writer.write_all(&section_desc(
        b"volume",
        if session.is_some() {
            session_desc_offset
        } else {
            sectors_desc_offset
        },
        ewf1::SECTION_DESCRIPTOR_SIZE as u64 + volume_data_size,
    ))?;
    writer.write_all(&volume_data(
        options,
        context.chunk_count,
        context.sector_count,
    )?)?;

    if let Some(session) = session {
        writer.write_all(&section_desc(
            b"session",
            sectors_desc_offset,
            ewf1::SECTION_DESCRIPTOR_SIZE as u64
                + u64::try_from(session.len()).expect("usize fits u64"),
        ))?;
        writer.write_all(&session)?;
    }

    for (group_index, layout) in group_layouts.iter().enumerate() {
        let group_chunks = &chunks[layout.first_chunk..layout.end_chunk];
        let group_chunk_count = u32::try_from(group_chunks.len()).map_err(|_| {
            EwfError::Unsupported("EWF1 writer table group chunk count exceeds u32".into())
        })?;
        let next_group_desc_offset = group_layouts
            .get(group_index + 1)
            .map_or(after_tables_desc_offset, |next| next.sectors_desc_offset);

        writer.write_all(&section_desc(
            b"sectors",
            layout.table_desc_offset,
            ewf1::SECTION_DESCRIPTOR_SIZE as u64 + layout.payload_size,
        ))?;
        for chunk in group_chunks {
            spool.copy_chunk_to(chunk, writer)?;
        }

        writer.write_all(&section_desc(
            b"table",
            layout.table2_desc_offset.unwrap_or(next_group_desc_offset),
            ewf1::SECTION_DESCRIPTOR_SIZE as u64 + layout.table_data_size,
        ))?;
        let table_capacity = usize::try_from(layout.table_data_size)
            .map_err(|_| EwfError::Malformed("writer table data size does not fit usize".into()))?;
        let mut table_data = Vec::with_capacity(table_capacity);
        append_ewf1_table_data(
            &mut table_data,
            group_chunk_count,
            layout.sectors_data_offset,
            group_chunks,
            table_footer_bytes != 0,
        )?;
        writer.write_all(&table_data)?;

        if layout.table2_desc_offset.is_some() {
            writer.write_all(&section_desc(
                b"table2",
                next_group_desc_offset,
                ewf1::SECTION_DESCRIPTOR_SIZE as u64 + layout.table_data_size,
            ))?;
            let mut table2_data = Vec::with_capacity(table_capacity);
            append_ewf1_table_data(
                &mut table2_data,
                group_chunk_count,
                layout.sectors_data_offset,
                group_chunks,
                true,
            )?;
            writer.write_all(&table2_data)?;
        }
    }

    if let Some(ltree) = &ltree {
        writer.write_all(&section_desc(
            b"ltree",
            after_ltree_desc_offset,
            ewf1::SECTION_DESCRIPTOR_SIZE as u64
                + u64::try_from(ltree.len()).expect("usize fits u64"),
        ))?;
        writer.write_all(ltree)?;
    }

    if let Some(error2) = error2 {
        writer.write_all(&section_desc(
            b"error2",
            after_error2_desc_offset,
            ewf1::SECTION_DESCRIPTOR_SIZE as u64
                + u64::try_from(error2.len()).expect("usize fits u64"),
        ))?;
        writer.write_all(&error2)?;
    }
    if let Some(digest) = digest {
        writer.write_all(&section_desc(
            b"digest",
            after_digest_desc_offset,
            ewf1::SECTION_DESCRIPTOR_SIZE as u64
                + u64::try_from(digest.len()).expect("usize fits u64"),
        ))?;
        writer.write_all(&digest)?;
    }
    if let Some(xhash) = xhash {
        writer.write_all(&section_desc(
            b"xhash",
            done_desc_offset,
            ewf1::SECTION_DESCRIPTOR_SIZE as u64
                + u64::try_from(xhash.len()).expect("usize fits u64"),
        ))?;
        writer.write_all(&xhash)?;
    }
    writer.write_all(&section_desc(
        context.terminal_section.ewf1_type(),
        done_desc_offset,
        ewf1::SECTION_DESCRIPTOR_SIZE as u64,
    ))?;

    Ok(())
}

#[derive(Debug, Clone, Copy)]
struct Ewf1SegmentWriteContext {
    segment_number: u16,
    chunk_count: u32,
    sector_count: u64,
    sections: Ewf1SegmentSections,
    terminal_section: TerminalSection,
}

#[derive(Debug, Clone, Copy)]
struct Ewf1SegmentSections {
    bits: u8,
}

impl Ewf1SegmentSections {
    const HEADER: u8 = 1 << 0;
    const DIGEST: u8 = 1 << 1;
    const ERRORS: u8 = 1 << 2;
    const SESSIONS: u8 = 1 << 3;

    fn for_segment(is_first: bool, is_last: bool) -> Self {
        let mut bits = 0;
        if is_first {
            bits |= Self::HEADER | Self::ERRORS | Self::SESSIONS;
        }
        if is_last {
            bits |= Self::DIGEST;
        }
        Self { bits }
    }

    fn contains(self, flag: u8) -> bool {
        self.bits & flag != 0
    }
}

fn ewf1_signature(format: WriteFormat) -> &'static [u8; 8] {
    match format {
        WriteFormat::Ewf1Physical | WriteFormat::Ewf1Smart => &ewf1::EVF_SIGNATURE,
        WriteFormat::Ewf1Logical => &ewf1::LVF_SIGNATURE,
        WriteFormat::Ewf2Physical | WriteFormat::Ewf2Logical => {
            unreachable!("EWF2 formats are not EWF1")
        }
    }
}

fn is_ewf2_format(format: WriteFormat) -> bool {
    matches!(format, WriteFormat::Ewf2Physical | WriteFormat::Ewf2Logical)
}

fn write_format_is_physical(format: WriteFormat) -> bool {
    matches!(
        format,
        WriteFormat::Ewf1Physical | WriteFormat::Ewf1Smart | WriteFormat::Ewf2Physical
    )
}

fn writer_media_flags(format: WriteFormat, profile: WriteMediaProfile) -> MediaFlags {
    MediaFlags {
        physical: write_format_is_physical(format),
        fastbloc: profile.fastbloc,
        tableau: profile.tableau,
    }
}

#[derive(Debug, Clone, Copy)]
struct Ewf2SegmentWriteContext {
    segment_number: u32,
    first_chunk: u64,
    total_chunk_count: u32,
    sector_count: u64,
    terminal_section_type: u32,
}

#[derive(Debug, Clone, Copy)]
struct Ewf2SectionPlan {
    data_offset: u64,
    previous_desc_offset: u64,
}

fn plan_ewf2_section(
    current_offset: &mut u64,
    previous_desc_offset: &mut u64,
    data_size: u64,
    label: &str,
) -> Result<Ewf2SectionPlan> {
    let data_offset = *current_offset;
    let desc_offset = checked_add(data_offset, data_size, label)?;
    let section = Ewf2SectionPlan {
        data_offset,
        previous_desc_offset: *previous_desc_offset,
    };
    *current_offset = checked_add(
        desc_offset,
        ewf2::SECTION_DESCRIPTOR_SIZE as u64,
        "EWF2 next section",
    )?;
    *previous_desc_offset = desc_offset;
    Ok(section)
}

fn write_ewf2_section<W: Write>(
    writer: &mut W,
    section_type: u32,
    payload: &[u8],
    section: Ewf2SectionPlan,
) -> Result<()> {
    writer.write_all(payload)?;
    writer.write_all(&ewf2_section_desc(
        section_type,
        u64::try_from(payload.len()).expect("usize fits u64"),
        section.previous_desc_offset,
    ))?;
    Ok(())
}

fn write_ewf2_segment<W: Write>(
    writer: &mut W,
    spool: &mut ChunkSpool,
    chunks: &[ChunkDescriptor],
    options: &WriteOptions,
    context: Ewf2SegmentWriteContext,
) -> Result<()> {
    let local_chunk_count = u32::try_from(chunks.len())
        .map_err(|_| EwfError::Unsupported("EWF2 writer segment chunk count exceeds u32".into()))?;
    let device_information_payload = ewf2_device_information_payload(
        options,
        context.sector_count,
        u64::from(context.total_chunk_count),
    );
    let device_information =
        ewf2_device_information_section_payload(&device_information_payload, options)?;
    let case_data_payload = ewf2_case_data_payload(options, u64::from(context.total_chunk_count));
    let case_data = ewf2_metadata_section_payload(
        &case_data_payload,
        options.compression,
        options.compression_values.level,
    )?;
    let error_table = if context.segment_number == 1 {
        ewf2_error_table_payload(&options.acquisition_errors)?
    } else {
        None
    };
    let session_table = if context.segment_number == 1 {
        ewf2_session_table_payload(&options.sessions, &options.tracks)?
    } else {
        None
    };
    let memory_extents_table = if context.segment_number == 1 {
        ewf2_memory_extents_table_payload(&options.memory_extents)
    } else {
        None
    };
    let increment_data: &[Vec<u8>] = if context.segment_number == 1 {
        &options.ewf2_increment_data
    } else {
        &[]
    };
    let single_files_data = if context.segment_number == 1 {
        options
            .single_files
            .as_ref()
            .map(ewf2_single_files_data_payload)
            .transpose()?
    } else {
        None
    };
    let single_files_table_0x21 = if context.segment_number == 1 {
        ewf2_single_files_aux_u64_table_payload(
            &options.ewf2_single_files_tables.table_0x21_entries,
        )
    } else {
        None
    };
    let single_files_md5_hash_table = if context.segment_number == 1 {
        ewf2_single_files_md5_hash_table_payload(&options.ewf2_single_files_tables.md5_hashes)
    } else {
        None
    };
    let single_files_table_0x23 = if context.segment_number == 1 {
        ewf2_single_files_aux_u64_table_payload(
            &options.ewf2_single_files_tables.table_0x23_entries,
        )
    } else {
        None
    };
    let writes_hash_sections = context.terminal_section_type == EWF2_DONE_SECTION;
    let md5_hash = writes_hash_sections
        .then(|| options.hashes.md5.map(ewf2_hash_payload))
        .flatten();
    let sha1_hash = writes_hash_sections
        .then(|| options.hashes.sha1.map(ewf2_hash_payload))
        .flatten();
    let final_information = if writes_hash_sections {
        options.ewf2_final_information.as_deref()
    } else {
        None
    };
    let analytical_data = if writes_hash_sections {
        options
            .ewf2_analytical_data
            .as_deref()
            .map(|data| {
                ewf2_string_section_payload(
                    data,
                    options.compression,
                    options.compression_values.level,
                )
            })
            .transpose()?
    } else {
        None
    };
    let restart_data = if writes_hash_sections {
        options
            .ewf2_restart_data
            .as_deref()
            .map(|data| {
                ewf2_string_section_payload(
                    data,
                    options.compression,
                    options.compression_values.level,
                )
            })
            .transpose()?
    } else {
        None
    };
    let table_entry_bytes = u64::from(local_chunk_count)
        .checked_mul(ewf2::TABLE_ENTRY_SIZE as u64)
        .ok_or_else(|| EwfError::Malformed("writer EWF2 table entry size overflow".into()))?;
    let table_data_size = (EWF2_TABLE_HEADER_V2_SIZE as u64)
        .checked_add(table_entry_bytes)
        .and_then(|value| value.checked_add(EWF2_TABLE_FOOTER_SIZE as u64))
        .ok_or_else(|| EwfError::Malformed("writer EWF2 table size overflow".into()))?;
    let chunk_payload_size = chunks.iter().try_fold(0_u64, |total, chunk| {
        total
            .checked_add(chunk.data_size)
            .ok_or_else(|| EwfError::Malformed("writer EWF2 chunk payload size overflow".into()))
    })?;

    let mut current_offset = ewf2::FILE_HEADER_SIZE as u64;
    let mut previous_desc_offset = 0_u64;

    let device_section = plan_ewf2_section(
        &mut current_offset,
        &mut previous_desc_offset,
        u64::try_from(device_information.len()).expect("usize fits u64"),
        "EWF2 device information",
    )?;
    let case_section = plan_ewf2_section(
        &mut current_offset,
        &mut previous_desc_offset,
        u64::try_from(case_data.len()).expect("usize fits u64"),
        "EWF2 case data",
    )?;
    let error_section = error_table
        .as_ref()
        .map(|payload| {
            plan_ewf2_section(
                &mut current_offset,
                &mut previous_desc_offset,
                u64::try_from(payload.len()).expect("usize fits u64"),
                "EWF2 error table",
            )
        })
        .transpose()?;
    let session_section = session_table
        .as_ref()
        .map(|payload| {
            plan_ewf2_section(
                &mut current_offset,
                &mut previous_desc_offset,
                u64::try_from(payload.len()).expect("usize fits u64"),
                "EWF2 session table",
            )
        })
        .transpose()?;
    let memory_extents_section = memory_extents_table
        .as_ref()
        .map(|payload| {
            plan_ewf2_section(
                &mut current_offset,
                &mut previous_desc_offset,
                u64::try_from(payload.len()).expect("usize fits u64"),
                "EWF2 memory extents table",
            )
        })
        .transpose()?;

    let mut increment_sections = Vec::with_capacity(increment_data.len());
    for payload in increment_data {
        increment_sections.push(plan_ewf2_section(
            &mut current_offset,
            &mut previous_desc_offset,
            u64::try_from(payload.len()).expect("usize fits u64"),
            "EWF2 increment data",
        )?);
    }

    let single_files_section = single_files_data
        .as_ref()
        .map(|payload| {
            plan_ewf2_section(
                &mut current_offset,
                &mut previous_desc_offset,
                u64::try_from(payload.len()).expect("usize fits u64"),
                "EWF2 single files data",
            )
        })
        .transpose()?;
    let single_files_table_0x21_section = single_files_table_0x21
        .as_ref()
        .map(|payload| {
            plan_ewf2_section(
                &mut current_offset,
                &mut previous_desc_offset,
                u64::try_from(payload.len()).expect("usize fits u64"),
                "EWF2 single files 0x21 table",
            )
        })
        .transpose()?;
    let single_files_md5_hash_table_section = single_files_md5_hash_table
        .as_ref()
        .map(|payload| {
            plan_ewf2_section(
                &mut current_offset,
                &mut previous_desc_offset,
                u64::try_from(payload.len()).expect("usize fits u64"),
                "EWF2 single files MD5 hash table",
            )
        })
        .transpose()?;
    let single_files_table_0x23_section = single_files_table_0x23
        .as_ref()
        .map(|payload| {
            plan_ewf2_section(
                &mut current_offset,
                &mut previous_desc_offset,
                u64::try_from(payload.len()).expect("usize fits u64"),
                "EWF2 single files 0x23 table",
            )
        })
        .transpose()?;

    let sectors_section = plan_ewf2_section(
        &mut current_offset,
        &mut previous_desc_offset,
        chunk_payload_size,
        "EWF2 sector data",
    )?;
    let table_section = plan_ewf2_section(
        &mut current_offset,
        &mut previous_desc_offset,
        table_data_size,
        "EWF2 sector table",
    )?;
    let md5_section = md5_hash
        .as_ref()
        .map(|payload| {
            plan_ewf2_section(
                &mut current_offset,
                &mut previous_desc_offset,
                u64::try_from(payload.len()).expect("usize fits u64"),
                "EWF2 MD5 hash",
            )
        })
        .transpose()?;
    let sha1_section = sha1_hash
        .as_ref()
        .map(|payload| {
            plan_ewf2_section(
                &mut current_offset,
                &mut previous_desc_offset,
                u64::try_from(payload.len()).expect("usize fits u64"),
                "EWF2 SHA1 hash",
            )
        })
        .transpose()?;
    let final_information_section = final_information
        .map(|payload| {
            plan_ewf2_section(
                &mut current_offset,
                &mut previous_desc_offset,
                u64::try_from(payload.len()).expect("usize fits u64"),
                "EWF2 final information",
            )
        })
        .transpose()?;
    let analytical_section = analytical_data
        .as_ref()
        .map(|payload| {
            plan_ewf2_section(
                &mut current_offset,
                &mut previous_desc_offset,
                u64::try_from(payload.len()).expect("usize fits u64"),
                "EWF2 analytical data",
            )
        })
        .transpose()?;
    let restart_section = restart_data
        .as_ref()
        .map(|payload| {
            plan_ewf2_section(
                &mut current_offset,
                &mut previous_desc_offset,
                u64::try_from(payload.len()).expect("usize fits u64"),
                "EWF2 restart data",
            )
        })
        .transpose()?;
    let terminal_section = plan_ewf2_section(
        &mut current_offset,
        &mut previous_desc_offset,
        0,
        "EWF2 terminal",
    )?;

    writer.write_all(ewf2_signature(options.format))?;
    writer.write_all(&[2, 1])?;
    writer.write_all(&ewf2_compression_method(options.compression).to_le_bytes())?;
    writer.write_all(&context.segment_number.to_le_bytes())?;
    writer.write_all(&options.set_identifier.unwrap_or([0; 16]))?;

    write_ewf2_section(
        writer,
        EWF2_DEVICE_INFORMATION_SECTION,
        &device_information,
        device_section,
    )?;

    write_ewf2_section(writer, EWF2_CASE_DATA_SECTION, &case_data, case_section)?;

    if let (Some(error_table), Some(section)) = (&error_table, error_section) {
        write_ewf2_section(writer, EWF2_ERROR_TABLE_SECTION, error_table, section)?;
    }

    if let (Some(session_table), Some(section)) = (&session_table, session_section) {
        write_ewf2_section(writer, EWF2_SESSION_TABLE_SECTION, session_table, section)?;
    }

    if let (Some(memory_extents_table), Some(section)) =
        (&memory_extents_table, memory_extents_section)
    {
        write_ewf2_section(
            writer,
            EWF2_MEMORY_EXTENTS_TABLE_SECTION,
            memory_extents_table,
            section,
        )?;
    }

    for (payload, section) in increment_data.iter().zip(&increment_sections) {
        write_ewf2_section(writer, EWF2_INCREMENT_DATA_SECTION, payload, *section)?;
    }

    if let (Some(single_files_data), Some(section)) = (&single_files_data, single_files_section) {
        write_ewf2_section(
            writer,
            EWF2_SINGLE_FILES_DATA_SECTION,
            single_files_data,
            section,
        )?;
    }

    if let (Some(single_files_table_0x21), Some(section)) =
        (&single_files_table_0x21, single_files_table_0x21_section)
    {
        write_ewf2_section(
            writer,
            EWF2_SINGLE_FILES_TABLE_SECTION,
            single_files_table_0x21,
            section,
        )?;
    }

    if let (Some(single_files_md5_hash_table), Some(section)) = (
        &single_files_md5_hash_table,
        single_files_md5_hash_table_section,
    ) {
        write_ewf2_section(
            writer,
            EWF2_SINGLE_FILES_MD5_HASH_TABLE_SECTION,
            single_files_md5_hash_table,
            section,
        )?;
    }

    if let (Some(single_files_table_0x23), Some(section)) =
        (&single_files_table_0x23, single_files_table_0x23_section)
    {
        write_ewf2_section(
            writer,
            EWF2_SINGLE_FILES_UNKNOWN_TABLE_SECTION,
            single_files_table_0x23,
            section,
        )?;
    }

    for chunk in chunks {
        spool.copy_chunk_to(chunk, writer)?;
    }
    writer.write_all(&ewf2_section_desc(
        EWF2_SECTOR_DATA_SECTION,
        chunk_payload_size,
        sectors_section.previous_desc_offset,
    ))?;

    let table_capacity = usize::try_from(table_data_size)
        .map_err(|_| EwfError::Malformed("writer EWF2 table size does not fit usize".into()))?;
    let mut table_data = Vec::with_capacity(table_capacity);
    table_data.extend_from_slice(&ewf2_table_header(context.first_chunk, local_chunk_count));
    let table_entries_start = table_data.len();
    let mut chunk_offset = sectors_section.data_offset;
    for chunk in chunks {
        let chunk_size = u32::try_from(chunk.data_size)
            .map_err(|_| EwfError::Unsupported("EWF2 writer chunk data size exceeds u32".into()))?;
        table_data.extend_from_slice(&ewf2_table_entry(
            chunk.pattern_fill.unwrap_or(chunk_offset),
            chunk_size,
            chunk.compressed,
            chunk.has_checksum,
            chunk.pattern_fill.is_some(),
        ));
        chunk_offset = checked_add(chunk_offset, chunk.data_size, "EWF2 chunk data offset")?;
    }
    let entries_checksum = adler32(&table_data[table_entries_start..]);
    table_data.extend_from_slice(&entries_checksum.to_le_bytes());
    table_data.extend_from_slice(&[0; EWF2_TABLE_FOOTER_SIZE - 4]);
    write_ewf2_section(
        writer,
        EWF2_SECTOR_TABLE_SECTION,
        &table_data,
        table_section,
    )?;

    if let (Some(md5_hash), Some(section)) = (&md5_hash, md5_section) {
        write_ewf2_section(writer, EWF2_MD5_HASH_SECTION, md5_hash, section)?;
    }
    if let (Some(sha1_hash), Some(section)) = (&sha1_hash, sha1_section) {
        write_ewf2_section(writer, EWF2_SHA1_HASH_SECTION, sha1_hash, section)?;
    }
    if let (Some(final_information), Some(section)) = (final_information, final_information_section)
    {
        write_ewf2_section(
            writer,
            EWF2_FINAL_INFORMATION_SECTION,
            final_information,
            section,
        )?;
    }
    if let (Some(analytical_data), Some(section)) = (&analytical_data, analytical_section) {
        write_ewf2_section(
            writer,
            EWF2_ANALYTICAL_DATA_SECTION,
            analytical_data,
            section,
        )?;
    }
    if let (Some(restart_data), Some(section)) = (&restart_data, restart_section) {
        write_ewf2_section(writer, EWF2_RESTART_DATA_SECTION, restart_data, section)?;
    }
    writer.write_all(&ewf2_section_desc(
        context.terminal_section_type,
        0,
        terminal_section.previous_desc_offset,
    ))?;

    Ok(())
}

fn ewf2_signature(format: WriteFormat) -> &'static [u8; 8] {
    match format {
        WriteFormat::Ewf2Physical => &ewf2::EX01_SIGNATURE,
        WriteFormat::Ewf2Logical => &ewf2::LEF2_SIGNATURE,
        WriteFormat::Ewf1Physical | WriteFormat::Ewf1Logical | WriteFormat::Ewf1Smart => {
            unreachable!("EWF1 formats are not EWF2")
        }
    }
}

fn ewf2_compression_method(compression: WriteCompression) -> u16 {
    match compression {
        // Common EWF readers reject EWF2 segment headers that use COMPRESSION_NONE.
        // Raw chunks are still represented by table flags; the header method must
        // name a supported compression family for the segment.
        WriteCompression::None | WriteCompression::Zlib => 1,
        WriteCompression::Bzip2 => 2,
    }
}

fn zlib_compression(level: WriteCompressionLevel) -> ZlibCompression {
    match level {
        WriteCompressionLevel::Default => ZlibCompression::default(),
        WriteCompressionLevel::None => ZlibCompression::none(),
        WriteCompressionLevel::Fast => ZlibCompression::fast(),
        WriteCompressionLevel::Best => ZlibCompression::best(),
    }
}

fn empty_block_zlib_compression(level: WriteCompressionLevel) -> ZlibCompression {
    match level {
        WriteCompressionLevel::None => ZlibCompression::default(),
        level => zlib_compression(level),
    }
}

fn bzip2_compression(level: WriteCompressionLevel) -> Result<Bzip2Compression> {
    match level {
        WriteCompressionLevel::Default => Ok(Bzip2Compression::default()),
        WriteCompressionLevel::None => Err(EwfError::Unsupported(
            "BZip2 writer compression does not support none compression level".into(),
        )),
        WriteCompressionLevel::Fast => Ok(Bzip2Compression::fast()),
        WriteCompressionLevel::Best => Ok(Bzip2Compression::best()),
    }
}

fn ewf2_metadata_section_payload(
    payload: &[u8],
    compression: WriteCompression,
    compression_level: WriteCompressionLevel,
) -> Result<Vec<u8>> {
    match compression {
        WriteCompression::None | WriteCompression::Zlib => {
            let mut encoder = ZlibEncoder::new(Vec::new(), zlib_compression(compression_level));
            encoder.write_all(payload)?;
            Ok(encoder.finish()?)
        }
        WriteCompression::Bzip2 => {
            let mut encoder = BzEncoder::new(Vec::new(), bzip2_compression(compression_level)?);
            encoder.write_all(payload)?;
            Ok(encoder.finish()?)
        }
    }
}

fn ewf2_device_information_section_payload(
    payload: &[u8],
    options: &WriteOptions,
) -> Result<Vec<u8>> {
    let compression = if matches!(options.compression, WriteCompression::Bzip2) {
        WriteCompression::Zlib
    } else {
        options.compression
    };
    ewf2_metadata_section_payload(payload, compression, options.compression_values.level)
}

fn ewf2_device_information_payload(
    options: &WriteOptions,
    sector_count: u64,
    chunk_count: u64,
) -> Vec<u8> {
    let physical = u8::from(options.format == WriteFormat::Ewf2Physical);
    let mut names = vec![
        "sn", "md", "lb", "ts", "hs", "dc", "dt", "pid", "rs", "ls", "bp", "ph", "sc", "tb",
    ];
    let media_type = options
        .media_profile
        .media_type
        .or(Some(MediaType::Removable))
        .map(ewf2_media_type_value)
        .map(|value| value.to_string())
        .unwrap_or_default();
    let mut values = vec![
        ewf2_device_header_value(&options.metadata, "serial_number", &["sn"]),
        ewf2_device_header_value(&options.metadata, "model", &["md"]),
        ewf2_device_header_value(&options.metadata, "device_label", &["lb", "l"]),
        sector_count.to_string(),
        String::new(),
        String::new(),
        media_type,
        ewf2_device_header_value(&options.metadata, "process_identifier", &["pid"]),
        String::new(),
        String::new(),
        options.bytes_per_sector.to_string(),
        physical.to_string(),
        options.sectors_per_chunk.to_string(),
        chunk_count.to_string(),
    ];
    if let Some(error_granularity) = options.media_profile.error_granularity {
        names.push("gr");
        values.push(error_granularity.to_string());
    }
    let write_blocker_flags =
        u64::from(options.media_profile.fastbloc) | (u64::from(options.media_profile.tableau) << 1);
    if write_blocker_flags != 0 {
        names.push("wb");
        values.push(write_blocker_flags.to_string());
    }

    let text = format!("1\nmain\n{}\n{}\n\n", names.join("\t"), values.join("\t"));
    utf16le_with_bom(&text)
}

fn ewf2_device_header_value(metadata: &EwfMetadata, identifier: &str, aliases: &[&str]) -> String {
    metadata
        .header_value(identifier)
        .or_else(|| {
            aliases
                .iter()
                .find_map(|alias| metadata.header_values.get(*alias).map(String::as_str))
        })
        .map(sanitize_header_value)
        .unwrap_or_default()
}

fn ewf2_media_type_value(media_type: MediaType) -> char {
    match media_type {
        MediaType::Removable => 'r',
        MediaType::Fixed => 'f',
        MediaType::Optical => 'c',
        MediaType::SingleFiles => 'l',
        MediaType::Memory => 'm',
        MediaType::Unknown(value) => char::from(value),
    }
}

fn ewf2_case_data_payload(options: &WriteOptions, chunk_count: u64) -> Vec<u8> {
    let metadata = &options.metadata;
    let write_blocker_flags =
        u64::from(options.media_profile.fastbloc) | (u64::from(options.media_profile.tableau) << 1);
    let compression_method = ewf2_case_data_header_value(metadata, "compression_method", &["cp"]);
    let error_granularity = options.media_profile.error_granularity.map_or_else(
        || {
            ewf2_case_data_header_value(metadata, "error_granularity", &["gr"])
                .unwrap_or_else(|| "0".to_string())
        },
        |value| value.to_string(),
    );
    let write_blocker = if write_blocker_flags != 0 {
        write_blocker_flags.to_string()
    } else {
        ewf2_case_data_header_value(metadata, "write_blocker", &["wb"]).unwrap_or_default()
    };
    let fields = [
        (
            "nm",
            ewf2_case_data_header_value(metadata, "description", &["nm", "de"]).unwrap_or_default(),
        ),
        (
            "cn",
            ewf2_case_data_header_value(metadata, "case_number", &["cn"]).unwrap_or_default(),
        ),
        (
            "en",
            ewf2_case_data_header_value(metadata, "evidence_number", &["en"]).unwrap_or_default(),
        ),
        (
            "ex",
            ewf2_case_data_header_value(metadata, "examiner_name", &["ex"]).unwrap_or_default(),
        ),
        (
            "nt",
            ewf2_case_data_header_value(metadata, "notes", &["nt"]).unwrap_or_default(),
        ),
        (
            "av",
            ewf2_case_data_header_value(metadata, "acquiry_software_version", &["av"])
                .unwrap_or_default(),
        ),
        (
            "os",
            ewf2_case_data_header_value(metadata, "acquiry_operating_system", &["os", "ov"])
                .unwrap_or_default(),
        ),
        (
            "tt",
            ewf2_case_data_header_value(metadata, "system_date", &["tt", "sd"]).unwrap_or_default(),
        ),
        (
            "at",
            ewf2_case_data_header_value(metadata, "acquiry_date", &["at", "ad"])
                .unwrap_or_default(),
        ),
        ("tb", chunk_count.to_string()),
        ("cp", compression_method.unwrap_or_default()),
        ("sb", options.sectors_per_chunk.to_string()),
        ("gr", error_granularity),
        ("wb", write_blocker),
    ];
    let mut names = fields
        .iter()
        .map(|(name, _)| (*name).to_string())
        .collect::<Vec<_>>();
    let mut values = fields
        .into_iter()
        .map(|(_, value)| value)
        .collect::<Vec<_>>();
    if let Some(acquisition_software) = metadata.acquisition_software.as_deref() {
        names.push("acquiry_software".to_string());
        values.push(sanitize_header_value(acquisition_software));
    }
    if let Some(password) = metadata.password.as_deref() {
        names.push("password".to_string());
        values.push(sanitize_header_value(password));
    }
    for (name, value) in &metadata.header_values {
        let tag = ewf2_case_data_tag(name);
        if names.iter().any(|existing| existing == tag) {
            continue;
        }
        names.push(tag.to_string());
        values.push(sanitize_header_value(value));
    }

    let text = format!("1\nmain\n{}\n{}\n\n", names.join("\t"), values.join("\t"));
    utf16le_with_bom(&text)
}

fn ewf2_case_data_header_value(
    metadata: &EwfMetadata,
    identifier: &str,
    aliases: &[&str],
) -> Option<String> {
    metadata
        .header_value(identifier)
        .or_else(|| {
            aliases
                .iter()
                .find_map(|alias| metadata.header_values.get(*alias).map(String::as_str))
        })
        .map(sanitize_header_value)
}

fn ewf2_case_data_tag(identifier: &str) -> &str {
    match identifier {
        "acquiry_date" | "ad" => "at",
        "acquiry_operating_system" | "ov" => "os",
        "acquiry_software_version" => "av",
        "case_number" => "cn",
        "compression_method" => "cp",
        "description" | "de" => "nm",
        "evidence_number" => "en",
        "examiner_name" => "ex",
        "error_granularity" => "gr",
        "notes" => "nt",
        "number_of_chunks" => "tb",
        "sectors_per_chunk" => "sb",
        "system_date" | "sd" => "tt",
        "write_blocker" => "wb",
        _ => identifier,
    }
}

fn ewf2_memory_extents_table_payload(extents: &[MemoryExtent]) -> Option<Vec<u8>> {
    if extents.is_empty() {
        return None;
    }

    let mut payload = Vec::with_capacity(extents.len() * 16);
    for extent in extents {
        payload.extend_from_slice(&extent.start_page.to_le_bytes());
        payload.extend_from_slice(&extent.page_count.to_le_bytes());
    }
    Some(payload)
}

fn ewf2_single_files_aux_u64_table_payload(entries: &[u64]) -> Option<Vec<u8>> {
    if entries.is_empty() {
        return None;
    }

    let mut entry_data = Vec::with_capacity(entries.len() * 8);
    for entry in entries {
        entry_data.extend_from_slice(&entry.to_le_bytes());
    }
    Some(ewf2_single_files_aux_table_payload(
        entries.len(),
        &entry_data,
    ))
}

fn ewf2_single_files_md5_hash_table_payload(hashes: &[[u8; 16]]) -> Option<Vec<u8>> {
    if hashes.is_empty() {
        return None;
    }

    let mut entry_data = Vec::with_capacity(hashes.len() * 16);
    for hash in hashes {
        entry_data.extend_from_slice(hash);
    }
    Some(ewf2_single_files_aux_table_payload(
        hashes.len(),
        &entry_data,
    ))
}

fn ewf2_single_files_aux_table_payload(entry_count: usize, entry_data: &[u8]) -> Vec<u8> {
    let mut payload = Vec::with_capacity(32 + entry_data.len() + 16);
    let entry_count = u32::try_from(entry_count).expect("entry count fits u32");
    payload.extend_from_slice(&entry_count.to_le_bytes());
    payload.extend_from_slice(&[0; 12]);
    let header_checksum = adler32(&payload);
    payload.extend_from_slice(&header_checksum.to_le_bytes());
    payload.extend_from_slice(&[0; 12]);
    payload.extend_from_slice(entry_data);
    let entries_checksum = adler32(entry_data);
    payload.extend_from_slice(&entries_checksum.to_le_bytes());
    payload.extend_from_slice(&[0; 12]);
    payload
}

fn ewf2_string_section_payload(
    text: &str,
    compression: WriteCompression,
    compression_level: WriteCompressionLevel,
) -> Result<Vec<u8>> {
    ewf2_metadata_section_payload(&utf16le_with_bom(text), compression, compression_level)
}

fn ewf1_ltree_payload(info: &SingleFilesInfo) -> Result<Vec<u8>> {
    let single_files_data = ewf2_single_files_data_payload(info)?;
    let mut payload = Vec::with_capacity(EWF1_LTREE_HEADER_SIZE + single_files_data.len());
    let mut hasher = Md5::new();
    hasher.update(&single_files_data);
    payload.extend_from_slice(&hasher.finalize());
    payload.extend_from_slice(
        &u64::try_from(single_files_data.len())
            .expect("usize fits u64")
            .to_le_bytes(),
    );
    payload.extend_from_slice(&0_u32.to_le_bytes());
    payload.extend_from_slice(&[0; 20]);
    let checksum = adler32(&payload[..EWF1_LTREE_HEADER_SIZE]);
    payload[24..28].copy_from_slice(&checksum.to_le_bytes());
    payload.extend_from_slice(&single_files_data);
    Ok(payload)
}

fn ewf2_single_files_data_payload(info: &SingleFilesInfo) -> Result<Vec<u8>> {
    let source_ids = SingleFileSourceIds::new(&info.sources)?;
    let mut lines = Vec::new();
    lines.push("5".to_owned());
    append_single_file_record_category(&mut lines, info)?;
    append_single_file_permission_category(&mut lines, &info.permission_groups);
    append_single_file_source_category(&mut lines, &info.sources)?;
    append_single_file_subject_category(&mut lines, &info.subjects);
    append_single_file_entry_category(&mut lines, &info.root, &source_ids)?;
    Ok(utf16le_with_bom(&lines.join("\n")))
}

struct SingleFileSourceIds {
    remapped: BTreeMap<i32, i32>,
}

impl SingleFileSourceIds {
    fn new(sources: &[SingleFileSource]) -> Result<Self> {
        let mut remapped = BTreeMap::new();
        let children = sources.get(1..).unwrap_or(&[]);
        for (index, source) in children.iter().enumerate() {
            if let Some(identifier) = source.identifier {
                remapped
                    .entry(identifier)
                    .or_insert(source_child_identifier(index)?);
            }
        }
        Ok(Self { remapped })
    }

    fn entry_identifier(&self, identifier: Option<i32>) -> Option<i32> {
        match identifier {
            Some(identifier) if identifier > 0 => {
                self.remapped.get(&identifier).copied().or(Some(identifier))
            }
            _ => identifier,
        }
    }
}

fn source_child_identifier(index: usize) -> Result<i32> {
    let identifier = index
        .checked_add(1)
        .ok_or_else(|| EwfError::Malformed("single files source identifier overflow".into()))?;
    i32::try_from(identifier).map_err(|_| {
        EwfError::Unsupported("single files source count exceeds supported identifier range".into())
    })
}

fn append_single_file_record_category(
    lines: &mut Vec<String>,
    info: &SingleFilesInfo,
) -> Result<()> {
    lines.push("rec".to_owned());
    lines.push("tb".to_owned());
    lines.push(single_files_record_data_size(info)?.to_string());
    lines.push(String::new());
    Ok(())
}

fn single_files_record_data_size(info: &SingleFilesInfo) -> Result<u64> {
    Ok(info.data_size.max(single_file_entry_data_size(&info.root)?))
}

fn single_file_entry_data_size(entry: &SingleFileEntry) -> Result<u64> {
    let mut data_size = entry.size.unwrap_or(0);
    for extent in &entry.extents {
        if extent.sparse {
            continue;
        }
        let extent_end = extent
            .data_offset
            .checked_add(extent.data_size)
            .ok_or_else(|| EwfError::Malformed("single files extent end overflow".into()))?;
        data_size = data_size.max(extent_end);
    }
    for child in &entry.children {
        data_size = data_size.max(single_file_entry_data_size(child)?);
    }
    Ok(data_size)
}

fn append_single_file_entry_category(
    lines: &mut Vec<String>,
    root: &SingleFileEntry,
    source_ids: &SingleFileSourceIds,
) -> Result<()> {
    let include_guid = single_file_entry_tree_has_guid(root);
    let entry_types = single_file_entry_types(include_guid);
    lines.push("entry".to_owned());
    lines.push("0\t1".to_owned());
    lines.push(entry_types.join("\t"));
    append_single_file_entry(lines, root, source_ids, include_guid)?;
    lines.push(String::new());
    Ok(())
}

fn single_file_entry_types(include_guid: bool) -> Vec<&'static str> {
    let mut entry_types = SINGLE_FILE_ENTRY_TYPES.to_vec();
    if include_guid {
        entry_types.push("mid");
    }
    entry_types
}

fn single_file_entry_tree_has_guid(entry: &SingleFileEntry) -> bool {
    entry.guid.is_some() || entry.children.iter().any(single_file_entry_tree_has_guid)
}

fn append_single_file_entry(
    lines: &mut Vec<String>,
    entry: &SingleFileEntry,
    source_ids: &SingleFileSourceIds,
    include_guid: bool,
) -> Result<()> {
    lines.push(format!("26\t{}", entry.children.len()));
    lines.push(single_file_entry_row(entry, source_ids, include_guid)?);
    for child in &entry.children {
        append_single_file_entry(lines, child, source_ids, include_guid)?;
    }
    Ok(())
}

fn single_file_entry_row(
    entry: &SingleFileEntry,
    source_ids: &SingleFileSourceIds,
    include_guid: bool,
) -> Result<String> {
    let mut values = vec![
        optional_display(entry.identifier),
        single_file_entry_type_value(entry.file_entry_type),
        optional_text(entry.name.as_deref()),
        optional_display(entry.size),
        optional_display(entry.logical_offset),
        optional_display(entry.physical_offset),
        optional_display(entry.duplicate_data_offset),
        optional_display(source_ids.entry_identifier(entry.source_identifier)),
        optional_display(entry.subject_identifier),
        optional_display(entry.permission_group_index),
        optional_display(entry.record_type),
        optional_display(entry.flags),
        single_file_extents_value(&entry.extents),
        optional_text(entry.md5.as_deref()),
        optional_text(entry.sha1.as_deref()),
        single_file_short_name_value(entry.short_name.as_deref()),
        optional_display(entry.creation_time),
        optional_display(entry.modification_time),
        optional_display(entry.access_time),
        optional_display(entry.entry_modification_time),
        optional_display(entry.deletion_time),
        single_file_attributes_value(&entry.attributes)?,
    ];
    if include_guid {
        values.push(optional_text(entry.guid.as_deref()));
    }
    Ok(values.join("\t"))
}

fn append_single_file_source_category(
    lines: &mut Vec<String>,
    sources: &[SingleFileSource],
) -> Result<()> {
    let default_root = SingleFileSource {
        identifier: Some(0),
        ..SingleFileSource::default()
    };
    let (root, children) = sources.split_first().unwrap_or((&default_root, &[]));
    lines.push("srce".to_owned());
    lines.push(format!("{}\t1", children.len()));
    lines.push(SINGLE_FILE_SOURCE_TYPES.join("\t"));
    lines.push(format!("0\t{}", children.len()));
    lines.push(single_file_source_row(root, Some(0)));
    for (index, source) in children.iter().enumerate() {
        lines.push("0\t0".to_owned());
        lines.push(single_file_source_row(
            source,
            Some(source_child_identifier(index)?),
        ));
    }
    lines.push(String::new());
    Ok(())
}

fn single_file_source_row(source: &SingleFileSource, identifier: Option<i32>) -> String {
    vec![
        optional_display(identifier.or(source.identifier)),
        optional_text(source.name.as_deref()),
        optional_text(source.evidence_number.as_deref()),
        optional_text(source.location.as_deref()),
        optional_text(source.device_guid.as_deref()),
        optional_text(source.primary_device_guid.as_deref()),
        source
            .drive_type
            .map(|value| value.to_string())
            .unwrap_or_default(),
        optional_text(source.manufacturer.as_deref()),
        optional_text(source.model.as_deref()),
        optional_text(source.serial_number.as_deref()),
        optional_text(source.domain.as_deref()),
        optional_text(source.ip_address.as_deref()),
        optional_text(source.mac_address.as_deref()),
        optional_display(source.size),
        optional_display(source.logical_offset),
        optional_display(source.physical_offset),
        optional_display(source.acquisition_time),
        optional_text(source.md5.as_deref()),
        optional_text(source.sha1.as_deref()),
    ]
    .join("\t")
}

fn append_single_file_subject_category(lines: &mut Vec<String>, subjects: &[SingleFileSubject]) {
    let default_root = SingleFileSubject {
        identifier: Some(0),
        ..SingleFileSubject::default()
    };
    let (root, children) = subjects.split_first().unwrap_or((&default_root, &[]));
    lines.push("sub".to_owned());
    lines.push(format!("{}\t1", children.len()));
    lines.push(SINGLE_FILE_SUBJECT_TYPES.join("\t"));
    lines.push(format!("0\t{}", children.len()));
    lines.push(single_file_subject_row(root));
    for subject in children {
        lines.push("0\t0".to_owned());
        lines.push(single_file_subject_row(subject));
    }
    lines.push(String::new());
}

fn single_file_subject_row(subject: &SingleFileSubject) -> String {
    [
        optional_display(subject.identifier),
        optional_text(subject.name.as_deref()),
    ]
    .join("\t")
}

fn append_single_file_permission_category(
    lines: &mut Vec<String>,
    groups: &[SingleFilePermissionGroup],
) {
    lines.push("perm".to_owned());
    lines.push(format!("{}\t1", groups.len()));
    lines.push(SINGLE_FILE_PERMISSION_TYPES.join("\t"));
    lines.push(format!("0\t{}", groups.len()));
    lines.push(single_file_permission_root_row());
    for group in groups {
        lines.push(format!("0\t{}", group.permissions.len()));
        lines.push(single_file_permission_group_row(group));
        for permission in &group.permissions {
            lines.push("0\t0".to_owned());
            lines.push(single_file_permission_row(permission));
        }
    }
    lines.push(String::new());
}

fn single_file_permission_root_row() -> String {
    single_file_permission_row(&SingleFilePermission {
        property_type: Some(10),
        ..SingleFilePermission::default()
    })
}

fn single_file_permission_group_row(group: &SingleFilePermissionGroup) -> String {
    [
        optional_text(group.name.as_deref()),
        optional_display(group.property_type.or(Some(10))),
        optional_text(group.identifier.as_deref()),
        optional_display(group.access_mask),
        optional_display(group.ace_flags),
    ]
    .join("\t")
}

fn single_file_permission_row(permission: &SingleFilePermission) -> String {
    [
        optional_text(permission.name.as_deref()),
        optional_display(permission.property_type),
        optional_text(permission.identifier.as_deref()),
        optional_display(permission.access_mask),
        optional_display(permission.ace_flags),
    ]
    .join("\t")
}

fn single_file_entry_type_value(value: Option<SingleFileEntryType>) -> String {
    match value {
        Some(SingleFileEntryType::File) => "f".to_owned(),
        Some(SingleFileEntryType::Directory) => "d".to_owned(),
        Some(SingleFileEntryType::Unknown) => "u".to_owned(),
        None => String::new(),
    }
}

fn single_file_extents_value(extents: &[SingleFileExtent]) -> String {
    if extents.is_empty() {
        return String::new();
    }

    let mut parts = Vec::with_capacity(1 + extents.len() * 3);
    parts.push(format!("{:x}", extents.len()));
    for extent in extents {
        if extent.sparse {
            parts.push("S".to_owned());
        }
        parts.push(format!("{:x}", extent.data_offset));
        parts.push(format!("{:x}", extent.data_size));
    }
    parts.join(" ")
}

fn single_file_attributes_value(attributes: &[SingleFileAttribute]) -> Result<String> {
    if attributes.is_empty() {
        return Ok(String::new());
    }

    let mut data = EWF2_EXTENDED_ATTRIBUTES_HEADER.to_vec();
    for attribute in attributes {
        let name = optional_utf16le_null_terminated(attribute.name.as_deref());
        let value = optional_utf16le_null_terminated(attribute.value.as_deref());
        let name_units = u32::try_from(name.len() / 2).map_err(|_| {
            EwfError::Unsupported("single file attribute name length exceeds u32".into())
        })?;
        let value_units = u32::try_from(value.len() / 2).map_err(|_| {
            EwfError::Unsupported("single file attribute value length exceeds u32".into())
        })?;

        data.extend_from_slice(&[0; 4]);
        data.push(0);
        data.extend_from_slice(&name_units.to_le_bytes());
        data.extend_from_slice(&value_units.to_le_bytes());
        data.extend_from_slice(&name);
        data.extend_from_slice(&value);
    }
    Ok(hex_bytes(&data))
}

fn optional_utf16le_null_terminated(value: Option<&str>) -> Vec<u8> {
    let Some(value) = value else {
        return Vec::new();
    };

    let mut bytes = utf16le(&optional_text(Some(value)));
    bytes.extend_from_slice(&0_u16.to_le_bytes());
    bytes
}

fn optional_text(value: Option<&str>) -> String {
    value.map(sanitize_header_value).unwrap_or_default()
}

fn single_file_short_name_value(value: Option<&str>) -> String {
    let value = optional_text(value);
    if value.is_empty() {
        String::new()
    } else {
        format!("{} {value}", value.len() + 1)
    }
}

fn optional_display<T: std::fmt::Display>(value: Option<T>) -> String {
    value.map(|value| value.to_string()).unwrap_or_default()
}

fn hex_bytes(bytes: &[u8]) -> String {
    const HEX: &[u8; 16] = b"0123456789abcdef";
    let mut out = String::with_capacity(bytes.len() * 2);
    for byte in bytes {
        out.push(char::from(HEX[(byte >> 4) as usize]));
        out.push(char::from(HEX[(byte & 0x0f) as usize]));
    }
    out
}

fn ewf2_hash_payload<const N: usize>(hash: [u8; N]) -> [u8; 32] {
    let mut payload = [0; 32];
    payload[..N].copy_from_slice(&hash);
    let checksum = adler32(&payload[..N]);
    payload[N..N + 4].copy_from_slice(&checksum.to_le_bytes());
    payload
}

fn ewf1_error2_payload(errors: &[AcquisitionError]) -> Result<Option<Vec<u8>>> {
    if errors.is_empty() {
        return Ok(None);
    }

    let entry_count = u32::try_from(errors.len()).map_err(|_| {
        EwfError::Unsupported("EWF1 writer acquisition error count exceeds u32".into())
    })?;
    let mut payload = Vec::with_capacity(520 + errors.len() * 8 + 4);
    payload.resize(520, 0);
    payload[0..4].copy_from_slice(&entry_count.to_le_bytes());
    let header_checksum = adler32(&payload[..516]);
    payload[516..520].copy_from_slice(&header_checksum.to_le_bytes());
    let entries_start = payload.len();
    for error in errors {
        let first_sector = u32::try_from(error.first_sector).map_err(|_| {
            EwfError::Unsupported("EWF1 writer acquisition error first sector exceeds u32".into())
        })?;
        let sector_count = u32::try_from(error.sector_count).map_err(|_| {
            EwfError::Unsupported("EWF1 writer acquisition error sector count exceeds u32".into())
        })?;
        payload.extend_from_slice(&first_sector.to_le_bytes());
        payload.extend_from_slice(&sector_count.to_le_bytes());
    }
    let entries_checksum = adler32(&payload[entries_start..]);
    payload.extend_from_slice(&entries_checksum.to_le_bytes());
    Ok(Some(payload))
}

fn ewf2_error_table_payload(errors: &[AcquisitionError]) -> Result<Option<Vec<u8>>> {
    if errors.is_empty() {
        return Ok(None);
    }

    let entry_count = u32::try_from(errors.len()).map_err(|_| {
        EwfError::Unsupported("EWF2 writer acquisition error count exceeds u32".into())
    })?;
    let mut payload = vec![0; 32];
    payload[0..4].copy_from_slice(&entry_count.to_le_bytes());
    let header_checksum = adler32(&payload[..16]);
    payload[16..20].copy_from_slice(&header_checksum.to_le_bytes());
    let entries_start = payload.len();
    for error in errors {
        let sector_count = u32::try_from(error.sector_count).map_err(|_| {
            EwfError::Unsupported("EWF2 writer acquisition error sector count exceeds u32".into())
        })?;
        payload.extend_from_slice(&error.first_sector.to_le_bytes());
        payload.extend_from_slice(&sector_count.to_le_bytes());
        payload.extend_from_slice(&[0; 4]);
    }
    let entries_checksum = adler32(&payload[entries_start..]);
    payload.extend_from_slice(&entries_checksum.to_le_bytes());
    payload.extend_from_slice(&[0; 12]);
    Ok(Some(payload))
}

fn ewf1_session_payload(
    sessions: &[SectorRange],
    tracks: &[SectorRange],
) -> Result<Option<Vec<u8>>> {
    session_payload(1, sessions, tracks)
}

fn ewf2_session_table_payload(
    sessions: &[SectorRange],
    tracks: &[SectorRange],
) -> Result<Option<Vec<u8>>> {
    session_payload(2, sessions, tracks)
}

fn session_payload(
    format_version: u8,
    sessions: &[SectorRange],
    tracks: &[SectorRange],
) -> Result<Option<Vec<u8>>> {
    const AUDIO_TRACK_FLAG: u32 = 0x01;

    if sessions.is_empty() && tracks.is_empty() {
        return Ok(None);
    }

    let mut entries = Vec::with_capacity(sessions.len() + tracks.len());
    entries.extend(sessions.iter().map(|range| (range.first_sector, 0)));
    entries.extend(
        tracks
            .iter()
            .map(|range| (range.first_sector, AUDIO_TRACK_FLAG)),
    );
    entries.sort_by_key(|(start_sector, flags)| (*start_sector, *flags & AUDIO_TRACK_FLAG));

    let entry_count = u32::try_from(entries.len())
        .map_err(|_| EwfError::Unsupported("writer session entry count exceeds u32".into()))?;
    let (header_size, checksum_offset, checksum_data_size, footer_size) = match format_version {
        1 => (36_usize, 32_usize, 32_usize, 4_usize),
        2 => (32_usize, 16_usize, 16_usize, 16_usize),
        _ => unreachable!("writer only emits EWF1 or EWF2 sessions"),
    };
    let mut payload = vec![0; header_size];
    payload[0..4].copy_from_slice(&entry_count.to_le_bytes());
    let header_checksum = adler32(&payload[..checksum_data_size]);
    payload[checksum_offset..checksum_offset + 4].copy_from_slice(&header_checksum.to_le_bytes());

    let entries_start = payload.len();
    for (start_sector, flags) in entries {
        if format_version == 1 {
            let start_sector = u32::try_from(start_sector).map_err(|_| {
                EwfError::Unsupported("EWF1 writer session start sector exceeds u32".into())
            })?;
            payload.extend_from_slice(&flags.to_le_bytes());
            payload.extend_from_slice(&start_sector.to_le_bytes());
            payload.extend_from_slice(&[0; 24]);
        } else {
            payload.extend_from_slice(&start_sector.to_le_bytes());
            payload.extend_from_slice(&flags.to_le_bytes());
            payload.extend_from_slice(&[0; 20]);
        }
    }
    let entries_checksum = adler32(&payload[entries_start..]);
    payload.extend_from_slice(&entries_checksum.to_le_bytes());
    if footer_size > 4 {
        payload.extend_from_slice(&vec![0; footer_size - 4]);
    }

    Ok(Some(payload))
}

fn adler32(data: &[u8]) -> u32 {
    const MOD_ADLER: u32 = 65_521;
    let mut a = 1_u32;
    let mut b = 0_u32;
    for byte in data {
        a = (a + u32::from(*byte)) % MOD_ADLER;
        b = (b + a) % MOD_ADLER;
    }
    (b << 16) | a
}

fn utf16le(text: &str) -> Vec<u8> {
    let mut bytes = Vec::with_capacity(text.len() * 2);
    for unit in text.encode_utf16() {
        bytes.extend_from_slice(&unit.to_le_bytes());
    }
    bytes
}

fn utf16le_with_bom(text: &str) -> Vec<u8> {
    let mut bytes = Vec::with_capacity(2 + text.len() * 2);
    bytes.extend_from_slice(&0xfeff_u16.to_le_bytes());
    bytes.extend_from_slice(&utf16le(text));
    bytes
}

fn ewf2_table_header(first_chunk: u64, chunk_count: u32) -> [u8; EWF2_TABLE_HEADER_V2_SIZE] {
    let mut table = [0; EWF2_TABLE_HEADER_V2_SIZE];
    table[0..8].copy_from_slice(&first_chunk.to_le_bytes());
    table[8..12].copy_from_slice(&chunk_count.to_le_bytes());
    let checksum = adler32(&table[..16]);
    table[16..20].copy_from_slice(&checksum.to_le_bytes());
    table
}

fn ewf2_table_entry(
    chunk_offset: u64,
    chunk_size: u32,
    compressed: bool,
    has_checksum: bool,
    pattern_fill: bool,
) -> [u8; ewf2::TABLE_ENTRY_SIZE] {
    let mut entry = [0; ewf2::TABLE_ENTRY_SIZE];
    entry[0..8].copy_from_slice(&chunk_offset.to_le_bytes());
    entry[8..12].copy_from_slice(&chunk_size.to_le_bytes());
    let mut flags = 0_u32;
    if compressed {
        flags |= ewf2::CHUNK_FLAG_COMPRESSED;
    }
    if has_checksum {
        flags |= ewf2::CHUNK_FLAG_HAS_CHECKSUM;
    }
    if pattern_fill {
        flags |= ewf2::CHUNK_FLAG_PATTERN_FILL;
    }
    entry[12..16].copy_from_slice(&flags.to_le_bytes());
    entry
}

fn ewf2_section_desc(
    section_type: u32,
    data_size: u64,
    previous_offset: u64,
) -> [u8; ewf2::SECTION_DESCRIPTOR_SIZE] {
    let mut desc = [0; ewf2::SECTION_DESCRIPTOR_SIZE];
    desc[0..4].copy_from_slice(&section_type.to_le_bytes());
    desc[8..16].copy_from_slice(&previous_offset.to_le_bytes());
    desc[16..24].copy_from_slice(&data_size.to_le_bytes());
    desc[24..28].copy_from_slice(&(ewf2::SECTION_DESCRIPTOR_SIZE as u32).to_le_bytes());
    let checksum = adler32(&desc[..ewf2::SECTION_DESCRIPTOR_SIZE - 4]);
    desc[ewf2::SECTION_DESCRIPTOR_SIZE - 4..].copy_from_slice(&checksum.to_le_bytes());
    desc
}

fn checked_add(left: u64, right: u64, label: &str) -> Result<u64> {
    left.checked_add(right)
        .ok_or_else(|| EwfError::Malformed(format!("writer {label} offset overflow")))
}

fn effective_write_hashes(
    requested: &WriteHashes,
    computed_md5: [u8; 16],
    computed_sha1: [u8; 20],
) -> WriteHashes {
    let mut hashes = requested.clone();
    hashes.md5 = hashes.md5.or(Some(computed_md5));
    hashes.sha1 = hashes.sha1.or(Some(computed_sha1));
    hashes
}

fn checked_writer_seek(
    current_offset: u64,
    logical_input_size: u64,
    position: SeekFrom,
) -> Result<u64> {
    let next = match position {
        SeekFrom::Start(offset) => return Ok(offset),
        SeekFrom::Current(offset) => i128::from(current_offset) + i128::from(offset),
        SeekFrom::End(offset) => i128::from(logical_input_size) + i128::from(offset),
    };
    if next < 0 {
        return Err(EwfError::Malformed(
            "writer seek before start of media".into(),
        ));
    }
    u64::try_from(next)
        .map_err(|_| EwfError::Malformed("writer seek offset does not fit u64".into()))
}

fn encode_raw_spool(
    raw: &mut RawSpool,
    mut encoded_chunks: BTreeMap<u64, RememberedEncodedChunk>,
    logical_size: u64,
    chunk_capacity: usize,
    chunk_size: u64,
    options: &WriteOptions,
) -> Result<EncodedSpool> {
    let mut chunks = Vec::new();
    let mut encoded_spool = ChunkSpool::new()?;
    let mut hash_state = WriteHashState::new();
    let mut offset = 0_u64;
    let is_ewf2 = is_ewf2_format(options.format);

    while offset < logical_size {
        let take = usize::try_from((logical_size - offset).min(chunk_capacity as u64))
            .expect("chunk read is bounded by chunk capacity");
        let mut chunk = vec![0; take];
        raw.read_at_filling_zeroes(offset, &mut chunk)?;
        hash_state.update(&chunk);
        let chunk_index = offset / chunk_size;
        let encoded = if let Some(remembered) = encoded_chunks.remove(&chunk_index) {
            if remembered.logical_size == take
                && encoded_data_chunk_encoding_compatible(remembered.encoding, options)
            {
                remembered.encoded
            } else {
                encode_chunk(
                    chunk,
                    options.compression,
                    options.compression_values,
                    chunk_size,
                    is_ewf2,
                    !is_ewf2 && options.compression_values.empty_block,
                )?
            }
        } else {
            encode_chunk(
                chunk,
                options.compression,
                options.compression_values,
                chunk_size,
                is_ewf2,
                !is_ewf2 && options.compression_values.empty_block,
            )?
        };
        let descriptor = encoded_spool.append(encoded)?;
        chunks.push(descriptor);
        offset = offset
            .checked_add(u64::try_from(take).expect("usize fits u64"))
            .ok_or_else(|| EwfError::Malformed("writer raw spool encode offset overflow".into()))?;
    }

    let (computed_md5, computed_sha1) = hash_state.finalize();
    Ok(EncodedSpool {
        chunks,
        spool: encoded_spool,
        computed_md5,
        computed_sha1,
    })
}

struct EncodedSpool {
    chunks: Vec<ChunkDescriptor>,
    spool: ChunkSpool,
    computed_md5: [u8; 16],
    computed_sha1: [u8; 20],
}

struct RememberedEncodedChunk {
    logical_size: usize,
    encoding: DataChunkEncoding,
    encoded: EncodedChunk,
}

#[derive(Debug, Clone, Copy)]
struct ChunkDescriptor {
    data_offset: u64,
    data_size: u64,
    compressed: bool,
    has_checksum: bool,
    pattern_fill: Option<u64>,
}

struct RawSpool {
    file: NamedTempFile,
    len: u64,
}

impl RawSpool {
    fn new() -> Result<Self> {
        Ok(Self {
            file: NamedTempFile::new()?,
            len: 0,
        })
    }

    fn len(&self) -> u64 {
        self.len
    }

    fn write_at(&mut self, offset: u64, data: &[u8]) -> Result<()> {
        if data.is_empty() {
            return Ok(());
        }

        let data_len = u64::try_from(data.len())
            .map_err(|_| EwfError::Malformed("writer data length does not fit u64".into()))?;
        let end_offset = offset
            .checked_add(data_len)
            .ok_or_else(|| EwfError::Malformed("writer raw spool size overflow".into()))?;
        let file = self.file.as_file_mut();
        file.seek(SeekFrom::Start(offset))?;
        file.write_all(data)?;
        self.len = self.len.max(end_offset);
        Ok(())
    }

    fn read_at_filling_zeroes(&mut self, offset: u64, buffer: &mut [u8]) -> Result<()> {
        buffer.fill(0);
        if buffer.is_empty() || offset >= self.len {
            return Ok(());
        }

        let available = self.len - offset;
        let take = usize::try_from(available.min(buffer.len() as u64))
            .expect("raw spool read is bounded by buffer length");
        let file = self.file.as_file_mut();
        file.seek(SeekFrom::Start(offset))?;
        file.read_exact(&mut buffer[..take])?;
        Ok(())
    }
}

struct ChunkSpool {
    file: NamedTempFile,
    len: u64,
}

impl ChunkSpool {
    fn new() -> Result<Self> {
        Ok(Self {
            file: NamedTempFile::new()?,
            len: 0,
        })
    }

    fn append(&mut self, encoded: EncodedChunk) -> Result<ChunkDescriptor> {
        let EncodedChunk {
            bytes,
            compressed,
            has_checksum,
            pattern_fill,
        } = encoded;
        let data_offset = self.len;
        let data_size = u64::try_from(bytes.len()).map_err(|_| {
            EwfError::Malformed("writer encoded chunk size does not fit u64".into())
        })?;
        if data_size > 0 {
            let file = self.file.as_file_mut();
            file.seek(SeekFrom::Start(data_offset))?;
            file.write_all(&bytes)?;
        }
        self.len = self.len.checked_add(data_size).ok_or_else(|| {
            EwfError::Malformed("writer encoded chunk spool size overflow".into())
        })?;

        Ok(ChunkDescriptor {
            data_offset,
            data_size,
            compressed,
            has_checksum,
            pattern_fill,
        })
    }

    fn copy_chunk_to<W: Write>(
        &mut self,
        descriptor: &ChunkDescriptor,
        writer: &mut W,
    ) -> Result<()> {
        if descriptor.data_size == 0 {
            return Ok(());
        }

        let mut remaining = descriptor.data_size;
        let mut buffer = [0; 8192];
        let file = self.file.as_file_mut();
        file.seek(SeekFrom::Start(descriptor.data_offset))?;
        while remaining > 0 {
            let take = usize::try_from(remaining.min(buffer.len() as u64))
                .expect("copy chunk is bounded by buffer length");
            file.read_exact(&mut buffer[..take])?;
            writer.write_all(&buffer[..take])?;
            remaining -= u64::try_from(take).expect("usize fits u64");
        }

        Ok(())
    }
}

struct EncodedChunk {
    bytes: Vec<u8>,
    compressed: bool,
    has_checksum: bool,
    pattern_fill: Option<u64>,
}

fn encode_chunk(
    chunk: Vec<u8>,
    compression: WriteCompression,
    compression_values: WriteCompressionValues,
    chunk_size: u64,
    allow_pattern_fill: bool,
    allow_empty_block_compression: bool,
) -> Result<EncodedChunk> {
    if allow_pattern_fill && let Some(pattern) = repeated_ewf2_pattern(&chunk) {
        return Ok(EncodedChunk {
            bytes: Vec::new(),
            compressed: true,
            has_checksum: false,
            pattern_fill: Some(pattern),
        });
    }

    if allow_empty_block_compression && is_full_zero_chunk(&chunk, chunk_size) {
        let mut encoder = ZlibEncoder::new(
            Vec::new(),
            empty_block_zlib_compression(compression_values.level),
        );
        encoder.write_all(&chunk)?;
        return Ok(EncodedChunk {
            bytes: encoder.finish()?,
            compressed: true,
            has_checksum: false,
            pattern_fill: None,
        });
    }

    match compression {
        WriteCompression::None => {
            let checksum = adler32(&chunk);
            let mut bytes = chunk;
            bytes.extend_from_slice(&checksum.to_le_bytes());
            Ok(EncodedChunk {
                bytes,
                compressed: false,
                has_checksum: true,
                pattern_fill: None,
            })
        }
        WriteCompression::Zlib => {
            let mut encoder =
                ZlibEncoder::new(Vec::new(), zlib_compression(compression_values.level));
            encoder.write_all(&chunk)?;
            Ok(EncodedChunk {
                bytes: encoder.finish()?,
                compressed: true,
                has_checksum: false,
                pattern_fill: None,
            })
        }
        WriteCompression::Bzip2 => {
            let mut encoder =
                BzEncoder::new(Vec::new(), bzip2_compression(compression_values.level)?);
            encoder.write_all(&chunk)?;
            Ok(EncodedChunk {
                bytes: encoder.finish()?,
                compressed: true,
                has_checksum: false,
                pattern_fill: None,
            })
        }
    }
}

fn is_full_zero_chunk(chunk: &[u8], chunk_size: u64) -> bool {
    u64::try_from(chunk.len()).ok() == Some(chunk_size) && chunk.iter().all(|byte| *byte == 0)
}

fn repeated_ewf2_pattern(chunk: &[u8]) -> Option<u64> {
    if chunk.is_empty() {
        return None;
    }

    let mut pattern = [0; 8];
    let seed_size = chunk.len().min(pattern.len());
    pattern[..seed_size].copy_from_slice(&chunk[..seed_size]);
    chunk
        .iter()
        .enumerate()
        .all(|(index, byte)| *byte == pattern[index % pattern.len()])
        .then(|| u64::from_le_bytes(pattern))
}

fn segment_groups(
    chunks: &[ChunkDescriptor],
    maximum_segment_size: Option<u64>,
    options: &WriteOptions,
    sector_count: u64,
    total_chunk_count: u64,
) -> Result<Vec<Range<usize>>> {
    let Some(maximum_segment_size) = maximum_segment_size else {
        return Ok(std::iter::once(0..chunks.len()).collect());
    };

    let mut groups = Vec::new();
    let mut current_start = 0_usize;
    let mut payload_size = 0_u64;
    let is_ewf2 = is_ewf2_format(options.format);
    let mut ewf1_table_group_state = Ewf1TableGroupState::default();
    for (chunk_index, chunk) in chunks.iter().enumerate() {
        let chunk_size = chunk.data_size;
        let proposed_payload_size = payload_size
            .checked_add(chunk_size)
            .ok_or_else(|| EwfError::Malformed("writer segment payload size overflow".into()))?;
        let proposed_ewf1_table_group_state = if is_ewf2 {
            ewf1_table_group_state
        } else {
            ewf1_table_group_state.add_chunk(
                chunk_size,
                EWF1_TABLE_GROUP_MAX_ENTRIES,
                EWF1_TABLE_GROUP_MAX_PAYLOAD,
            )?
        };
        let proposed_size = estimated_segment_size(
            chunk_index - current_start + 1,
            proposed_payload_size,
            proposed_ewf1_table_group_state.group_count.max(1),
            options,
            sector_count,
            total_chunk_count,
        )?;
        if chunk_index > current_start && proposed_size > maximum_segment_size {
            groups.push(current_start..chunk_index);
            current_start = chunk_index;
            payload_size = 0;
            ewf1_table_group_state = if is_ewf2 {
                Ewf1TableGroupState::default()
            } else {
                Ewf1TableGroupState::default().add_chunk(
                    chunk_size,
                    EWF1_TABLE_GROUP_MAX_ENTRIES,
                    EWF1_TABLE_GROUP_MAX_PAYLOAD,
                )?
            };
        } else {
            ewf1_table_group_state = proposed_ewf1_table_group_state;
        }

        payload_size = payload_size
            .checked_add(chunk_size)
            .ok_or_else(|| EwfError::Malformed("writer segment payload size overflow".into()))?;
    }

    groups.push(current_start..chunks.len());
    Ok(groups)
}

fn estimated_segment_size(
    chunk_count: usize,
    chunk_payload_size: u64,
    ewf1_table_group_count: u64,
    options: &WriteOptions,
    sector_count: u64,
    total_chunk_count: u64,
) -> Result<u64> {
    if is_ewf2_format(options.format) {
        return estimated_ewf2_segment_size(
            chunk_count,
            chunk_payload_size,
            options,
            sector_count,
            total_chunk_count,
        );
    }
    estimated_ewf1_segment_size(
        chunk_count,
        chunk_payload_size,
        ewf1_table_group_count,
        options,
    )
}

fn estimated_ewf1_segment_size(
    chunk_count: usize,
    chunk_payload_size: u64,
    table_group_count: u64,
    options: &WriteOptions,
) -> Result<u64> {
    let table_entry_bytes = u64::try_from(chunk_count)
        .map_err(|_| EwfError::Malformed("writer segment chunk count does not fit u64".into()))?
        .checked_mul(4)
        .ok_or_else(|| EwfError::Malformed("writer table entry size overflow".into()))?;
    let table_footer_bytes = if matches!(options.format, WriteFormat::Ewf1Smart) {
        0
    } else {
        4
    };
    let table_group_overhead = (ewf1::SECTION_DESCRIPTOR_SIZE as u64)
        .checked_add(24)
        .and_then(|value| value.checked_add(table_footer_bytes))
        .ok_or_else(|| EwfError::Malformed("writer table group overhead overflow".into()))?;
    let table_sections_size = table_group_count
        .checked_mul(table_group_overhead)
        .and_then(|value| value.checked_add(table_entry_bytes))
        .ok_or_else(|| EwfError::Malformed("writer table sections size overflow".into()))?;
    let sectors_sections_size = table_group_count
        .checked_mul(ewf1::SECTION_DESCRIPTOR_SIZE as u64)
        .and_then(|value| value.checked_add(chunk_payload_size))
        .ok_or_else(|| EwfError::Malformed("writer sectors sections size overflow".into()))?;
    let writes_table2 = matches!(
        options.format,
        WriteFormat::Ewf1Physical | WriteFormat::Ewf1Logical
    );

    let header_size = header_payload(
        &options.metadata,
        options.header_codepage,
        options.compression_values.level,
    )?
    .map(|payload| estimated_ewf1_section_size(payload.len() as u64))
    .transpose()?
    .unwrap_or(0);
    let header2_size = header2_payload(&options.metadata, options.compression_values.level)?
        .map(|payload| estimated_ewf1_section_size(payload.len() as u64))
        .transpose()?
        .unwrap_or(0);
    let xheader_size = xheader_payload(&options.metadata, options.compression_values.level)?
        .map(|payload| estimated_ewf1_section_size(payload.len() as u64))
        .transpose()?
        .unwrap_or(0);
    let session_size = ewf1_session_payload(&options.sessions, &options.tracks)?
        .map(|payload| estimated_ewf1_section_size(payload.len() as u64))
        .transpose()?
        .unwrap_or(0);
    let ltree_size = if matches!(options.format, WriteFormat::Ewf1Logical) {
        options
            .single_files
            .as_ref()
            .map(ewf1_ltree_payload)
            .transpose()?
            .as_ref()
            .map(|payload| estimated_ewf1_section_size(payload.len() as u64))
            .transpose()?
            .unwrap_or(0)
    } else {
        0
    };
    let error2_size = ewf1_error2_payload(&options.acquisition_errors)?
        .map(|payload| estimated_ewf1_section_size(payload.len() as u64))
        .transpose()?
        .unwrap_or(0);
    let digest_size = digest_payload(&options.hashes)
        .map(|payload| estimated_ewf1_section_size(payload.len() as u64))
        .transpose()?
        .unwrap_or(0);
    let xhash_size = xhash_payload(&options.hashes, options.compression_values.level)?
        .map(|payload| estimated_ewf1_section_size(payload.len() as u64))
        .transpose()?
        .unwrap_or(0);

    checked_sum(
        [
            ewf1::FILE_HEADER_SIZE as u64,
            header_size,
            header2_size,
            xheader_size,
            estimated_ewf1_section_size(volume_data_size(options.format))?,
            session_size,
            table_sections_size,
            if writes_table2 {
                table_sections_size
            } else {
                0
            },
            ltree_size,
            sectors_sections_size,
            error2_size,
            digest_size,
            xhash_size,
            ewf1::SECTION_DESCRIPTOR_SIZE as u64,
        ],
        "estimated EWF1 segment size",
    )
}

fn estimated_ewf2_segment_size(
    chunk_count: usize,
    chunk_payload_size: u64,
    options: &WriteOptions,
    sector_count: u64,
    total_chunk_count: u64,
) -> Result<u64> {
    let device_information_payload =
        ewf2_device_information_payload(options, sector_count, total_chunk_count);
    let device_information =
        ewf2_device_information_section_payload(&device_information_payload, options)?;
    let case_data_payload = ewf2_case_data_payload(options, total_chunk_count);
    let case_data = ewf2_metadata_section_payload(
        &case_data_payload,
        options.compression,
        options.compression_values.level,
    )?;
    let error_table = ewf2_error_table_payload(&options.acquisition_errors)?;
    let session_table = ewf2_session_table_payload(&options.sessions, &options.tracks)?;
    let memory_extents_table = ewf2_memory_extents_table_payload(&options.memory_extents);
    let single_files_table_0x21 = ewf2_single_files_aux_u64_table_payload(
        &options.ewf2_single_files_tables.table_0x21_entries,
    );
    let single_files_md5_hash_table =
        ewf2_single_files_md5_hash_table_payload(&options.ewf2_single_files_tables.md5_hashes);
    let single_files_table_0x23 = ewf2_single_files_aux_u64_table_payload(
        &options.ewf2_single_files_tables.table_0x23_entries,
    );
    let increment_data_size =
        options
            .ewf2_increment_data
            .iter()
            .try_fold(0_u64, |total, payload| -> Result<u64> {
                let section_size = estimated_ewf2_section_size(
                    u64::try_from(payload.len()).expect("usize fits u64"),
                )?;
                total.checked_add(section_size).ok_or_else(|| {
                    EwfError::Malformed("writer estimated EWF2 increment data size overflow".into())
                })
            })?;
    let md5_hash = options.hashes.md5.map(ewf2_hash_payload);
    let sha1_hash = options.hashes.sha1.map(ewf2_hash_payload);
    let final_information_size = options
        .ewf2_final_information
        .as_ref()
        .map(|payload| estimated_ewf2_section_size(payload.len() as u64))
        .transpose()?
        .unwrap_or(0);
    let analytical_data = options
        .ewf2_analytical_data
        .as_deref()
        .map(|data| {
            ewf2_string_section_payload(data, options.compression, options.compression_values.level)
        })
        .transpose()?;
    let restart_data = options
        .ewf2_restart_data
        .as_deref()
        .map(|data| {
            ewf2_string_section_payload(data, options.compression, options.compression_values.level)
        })
        .transpose()?;
    let table_entry_bytes = u64::try_from(chunk_count)
        .map_err(|_| EwfError::Malformed("writer segment chunk count does not fit u64".into()))?
        .checked_mul(ewf2::TABLE_ENTRY_SIZE as u64)
        .ok_or_else(|| EwfError::Malformed("writer EWF2 table entry size overflow".into()))?;
    let table_data_size = (EWF2_TABLE_HEADER_V2_SIZE as u64)
        .checked_add(table_entry_bytes)
        .and_then(|value| value.checked_add(EWF2_TABLE_FOOTER_SIZE as u64))
        .ok_or_else(|| EwfError::Malformed("writer EWF2 table size overflow".into()))?;

    checked_sum(
        [
            ewf2::FILE_HEADER_SIZE as u64,
            estimated_ewf2_section_size(device_information.len() as u64)?,
            estimated_ewf2_section_size(case_data.len() as u64)?,
            error_table
                .as_ref()
                .map(|payload| estimated_ewf2_section_size(payload.len() as u64))
                .transpose()?
                .unwrap_or(0),
            session_table
                .as_ref()
                .map(|payload| estimated_ewf2_section_size(payload.len() as u64))
                .transpose()?
                .unwrap_or(0),
            memory_extents_table
                .as_ref()
                .map(|payload| estimated_ewf2_section_size(payload.len() as u64))
                .transpose()?
                .unwrap_or(0),
            increment_data_size,
            single_files_table_0x21
                .as_ref()
                .map(|payload| estimated_ewf2_section_size(payload.len() as u64))
                .transpose()?
                .unwrap_or(0),
            single_files_md5_hash_table
                .as_ref()
                .map(|payload| estimated_ewf2_section_size(payload.len() as u64))
                .transpose()?
                .unwrap_or(0),
            single_files_table_0x23
                .as_ref()
                .map(|payload| estimated_ewf2_section_size(payload.len() as u64))
                .transpose()?
                .unwrap_or(0),
            estimated_ewf2_section_size(table_data_size)?,
            estimated_ewf2_section_size(chunk_payload_size)?,
            md5_hash
                .as_ref()
                .map(|payload| estimated_ewf2_section_size(payload.len() as u64))
                .transpose()?
                .unwrap_or(0),
            sha1_hash
                .as_ref()
                .map(|payload| estimated_ewf2_section_size(payload.len() as u64))
                .transpose()?
                .unwrap_or(0),
            final_information_size,
            analytical_data
                .as_ref()
                .map(|payload| estimated_ewf2_section_size(payload.len() as u64))
                .transpose()?
                .unwrap_or(0),
            restart_data
                .as_ref()
                .map(|payload| estimated_ewf2_section_size(payload.len() as u64))
                .transpose()?
                .unwrap_or(0),
            options
                .single_files
                .as_ref()
                .map(ewf2_single_files_data_payload)
                .transpose()?
                .as_ref()
                .map(|payload| estimated_ewf2_section_size(payload.len() as u64))
                .transpose()?
                .unwrap_or(0),
            ewf2::SECTION_DESCRIPTOR_SIZE as u64,
        ],
        "estimated EWF2 segment size",
    )
}

fn estimated_ewf1_section_size(data_size: u64) -> Result<u64> {
    (ewf1::SECTION_DESCRIPTOR_SIZE as u64)
        .checked_add(data_size)
        .ok_or_else(|| EwfError::Malformed("writer estimated EWF1 section size overflow".into()))
}

fn estimated_ewf2_section_size(data_size: u64) -> Result<u64> {
    (ewf2::SECTION_DESCRIPTOR_SIZE as u64)
        .checked_add(data_size)
        .ok_or_else(|| EwfError::Malformed("writer estimated EWF2 section size overflow".into()))
}

fn checked_sum(parts: impl IntoIterator<Item = u64>, label: &str) -> Result<u64> {
    parts.into_iter().try_fold(0_u64, |total, part| {
        total
            .checked_add(part)
            .ok_or_else(|| EwfError::Malformed(format!("writer {label} overflow")))
    })
}

fn volume_data_size(format: WriteFormat) -> u64 {
    match format {
        WriteFormat::Ewf1Physical | WriteFormat::Ewf1Logical => VOLUME_DATA_SIZE as u64,
        WriteFormat::Ewf1Smart => 94,
        WriteFormat::Ewf2Physical | WriteFormat::Ewf2Logical => {
            unreachable!("EWF2 formats do not use EWF1 volume data")
        }
    }
}

fn segment_path(first_path: &Path, segment_number: usize) -> Result<PathBuf> {
    if segment_number == 1 {
        return Ok(first_path.to_path_buf());
    }
    Ok(first_path.with_extension(v1_segment_extension(first_path, segment_number)?))
}

fn ewf2_segment_path(first_path: &Path, segment_number: usize) -> Result<PathBuf> {
    if segment_number == 1 {
        return Ok(first_path.to_path_buf());
    }
    Ok(first_path.with_extension(v2_segment_extension(first_path, segment_number)?))
}

fn remove_stale_segment_files(
    first_path: &Path,
    written_segment_count: usize,
    is_v2: bool,
) -> Result<()> {
    let path_for_segment = if is_v2 {
        ewf2_segment_path
    } else {
        segment_path
    };
    let mut segment_number = written_segment_count
        .checked_add(1)
        .ok_or_else(|| EwfError::Malformed("writer stale segment cleanup overflow".into()))?;

    loop {
        let path = match path_for_segment(first_path, segment_number) {
            Ok(path) => path,
            Err(EwfError::Unsupported(_)) => return Ok(()),
            Err(err) => return Err(err),
        };
        match fs::remove_file(&path) {
            Ok(()) => {
                segment_number = segment_number.checked_add(1).ok_or_else(|| {
                    EwfError::Malformed("writer stale segment cleanup overflow".into())
                })?;
            }
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(()),
            Err(err) => return Err(err.into()),
        }
    }
}

fn mirror_secondary_segment_files(
    primary_base: &Path,
    secondary_base: Option<&Path>,
    primary_segment_paths: &[PathBuf],
    written_segment_count: usize,
    is_v2: bool,
) -> Result<Vec<PathBuf>> {
    let Some(secondary_base) = secondary_base else {
        return Ok(Vec::new());
    };
    validate_secondary_segment_filename(primary_base, Some(secondary_base))?;

    let path_for_segment = if is_v2 {
        ewf2_segment_path
    } else {
        segment_path
    };
    let mut secondary_segment_paths = Vec::with_capacity(primary_segment_paths.len());
    for segment_number in 1..=primary_segment_paths.len() {
        let secondary_path = path_for_segment(secondary_base, segment_number)?;
        ensure_secondary_segment_path_is_distinct(primary_segment_paths, &secondary_path)?;
        secondary_segment_paths.push(secondary_path);
    }

    for (primary_path, secondary_path) in primary_segment_paths
        .iter()
        .zip(secondary_segment_paths.iter())
    {
        fs::copy(primary_path, secondary_path)?;
    }
    remove_stale_segment_files(secondary_base, written_segment_count, is_v2)?;

    Ok(secondary_segment_paths)
}

fn validate_secondary_segment_filename(
    primary_base: &Path,
    secondary_base: Option<&Path>,
) -> Result<()> {
    let Some(secondary_base) = secondary_base else {
        return Ok(());
    };
    if normalized_output_path(primary_base)? == normalized_output_path(secondary_base)? {
        return Err(EwfError::Unsupported(
            "secondary segment filename overlaps primary output".into(),
        ));
    }
    Ok(())
}

fn ensure_secondary_segment_path_is_distinct(
    primary_segment_paths: &[PathBuf],
    secondary_path: &Path,
) -> Result<()> {
    let secondary_path = normalized_output_path(secondary_path)?;
    for primary_path in primary_segment_paths {
        if normalized_output_path(primary_path)? == secondary_path {
            return Err(EwfError::Unsupported(
                "secondary segment filename overlaps primary output".into(),
            ));
        }
    }
    Ok(())
}

fn normalized_output_path(path: &Path) -> Result<PathBuf> {
    let absolute = if path.is_absolute() {
        path.to_path_buf()
    } else {
        std::env::current_dir()?.join(path)
    };
    let mut normalized = PathBuf::new();
    for component in absolute.components() {
        match component {
            Component::CurDir => {}
            Component::ParentDir => {
                normalized.pop();
            }
            other => normalized.push(other.as_os_str()),
        }
    }
    Ok(normalized)
}

fn v1_segment_extension(first_path: &Path, segment_number: usize) -> Result<String> {
    let prefix = first_path
        .extension()
        .and_then(|value| value.to_str())
        .and_then(|value| value.chars().next())
        .unwrap_or('E')
        .to_ascii_uppercase();
    if segment_number <= 99 {
        return Ok(format!("{prefix}{segment_number:02}"));
    }

    let alpha_index = segment_number - 100;
    let prefix_offset = alpha_index / (26 * 26);
    let prefix = char::from_u32(
        (prefix as u32)
            .checked_add(prefix_offset as u32)
            .ok_or_else(|| {
                EwfError::Unsupported("EWF1 writer segment extension prefix overflow".into())
            })?,
    )
    .ok_or_else(|| EwfError::Unsupported("EWF1 writer segment extension prefix overflow".into()))?;
    if !prefix.is_ascii_uppercase() {
        return Err(EwfError::Unsupported(
            "EWF1 writer segment count exceeds supported extensions".into(),
        ));
    }

    let suffix = alpha_index % (26 * 26);
    let first = char::from(b'A' + u8::try_from(suffix / 26).expect("suffix fits u8"));
    let second = char::from(b'A' + u8::try_from(suffix % 26).expect("suffix fits u8"));
    Ok(format!("{prefix}{first}{second}"))
}

fn v2_segment_extension(first_path: &Path, segment_number: usize) -> Result<String> {
    let prefix = first_path
        .extension()
        .and_then(|value| value.to_str())
        .and_then(|value| value.chars().next())
        .unwrap_or('E')
        .to_ascii_uppercase();
    if segment_number <= 99 {
        return Ok(format!("{prefix}x{segment_number:02}"));
    }

    let alpha_index = segment_number - 100;
    let infix_offset = alpha_index / (26 * 26);
    let infix = char::from_u32(u32::from(b'x') + infix_offset as u32)
        .ok_or_else(|| EwfError::Unsupported("EWF2 writer segment extension overflow".into()))?;
    if !matches!(infix, 'x'..='z') {
        return Err(EwfError::Unsupported(
            "EWF2 writer segment count exceeds supported extensions".into(),
        ));
    }

    let suffix = alpha_index % (26 * 26);
    let first = char::from(b'A' + u8::try_from(suffix / 26).expect("suffix fits u8"));
    let second = char::from(b'A' + u8::try_from(suffix % 26).expect("suffix fits u8"));
    Ok(format!("{prefix}{infix}{first}{second}"))
}

fn volume_data(options: &WriteOptions, chunk_count: u32, sector_count: u64) -> Result<Vec<u8>> {
    let mut volume = vec![0; usize::try_from(volume_data_size(options.format)).expect("fits")];
    if options.format == WriteFormat::Ewf1Smart {
        volume[0] = 1;
    } else {
        volume[0] = ewf1_media_type_value(options.format, options.media_profile.media_type);
        volume[36] = ewf1_media_flags_value(options.format, options.media_profile);
    }
    volume[4..8].copy_from_slice(&chunk_count.to_le_bytes());
    volume[8..12].copy_from_slice(&options.sectors_per_chunk.to_le_bytes());
    volume[12..16].copy_from_slice(&options.bytes_per_sector.to_le_bytes());
    volume[52] = ewf1_compression_level_value(options.compression_values.level);
    if options.format == WriteFormat::Ewf1Smart {
        let sector_count = u32::try_from(sector_count)
            .map_err(|_| EwfError::Unsupported("EWF-S01 writer sector count exceeds u32".into()))?;
        volume[16..20].copy_from_slice(&sector_count.to_le_bytes());
        volume[85..90].copy_from_slice(b"SMART");
    } else {
        volume[16..24].copy_from_slice(&sector_count.to_le_bytes());
    }
    if let Some(identifier) = options
        .set_identifier
        .filter(|_| options.format != WriteFormat::Ewf1Smart)
    {
        volume[64..80].copy_from_slice(&identifier);
    }
    if let Some(error_granularity) = options
        .media_profile
        .error_granularity
        .filter(|_| options.format != WriteFormat::Ewf1Smart)
    {
        let error_granularity = u32::try_from(error_granularity).map_err(|_| {
            EwfError::Unsupported("EWF1 writer error granularity exceeds u32".into())
        })?;
        volume[56..60].copy_from_slice(&error_granularity.to_le_bytes());
    }
    let checksum_offset = volume.len() - 4;
    let checksum = adler32(&volume[..checksum_offset]);
    volume[checksum_offset..].copy_from_slice(&checksum.to_le_bytes());
    Ok(volume)
}

fn ewf1_compression_level_value(level: WriteCompressionLevel) -> u8 {
    match level {
        WriteCompressionLevel::Default | WriteCompressionLevel::None => 0,
        WriteCompressionLevel::Fast => 1,
        WriteCompressionLevel::Best => 2,
    }
}

fn ewf1_media_type_value(format: WriteFormat, media_type: Option<MediaType>) -> u8 {
    media_type.map_or_else(
        || match format {
            WriteFormat::Ewf1Logical => 0x0e,
            WriteFormat::Ewf1Physical | WriteFormat::Ewf1Smart => 0x00,
            WriteFormat::Ewf2Physical | WriteFormat::Ewf2Logical => {
                unreachable!("EWF2 formats do not use EWF1 media type values")
            }
        },
        ewf1_media_type_byte,
    )
}

fn ewf1_media_type_byte(media_type: MediaType) -> u8 {
    match media_type {
        MediaType::Removable => 0x00,
        MediaType::Fixed => 0x01,
        MediaType::Optical => 0x03,
        MediaType::SingleFiles => 0x0e,
        MediaType::Memory => 0x10,
        MediaType::Unknown(value) => value,
    }
}

fn ewf1_media_flags_value(format: WriteFormat, profile: WriteMediaProfile) -> u8 {
    let mut flags = 0x01;
    if format == WriteFormat::Ewf1Physical {
        flags |= 0x02;
    }
    if profile.fastbloc {
        flags |= 0x04;
    }
    if profile.tableau {
        flags |= 0x08;
    }
    flags
}

fn table_header(chunk_count: u32, sectors_data_offset: u64) -> [u8; 24] {
    let mut table = [0; 24];
    table[0..4].copy_from_slice(&chunk_count.to_le_bytes());
    table[8..16].copy_from_slice(&sectors_data_offset.to_le_bytes());
    let checksum = adler32(&table[..20]);
    table[20..24].copy_from_slice(&checksum.to_le_bytes());
    table
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Ewf1TableGroup {
    first_chunk: usize,
    end_chunk: usize,
    payload_size: u64,
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
struct Ewf1TableGroupState {
    group_count: u64,
    current_entry_count: usize,
    current_payload_size: u64,
}

impl Ewf1TableGroupState {
    fn add_chunk(self, data_size: u64, max_entries: usize, max_payload: u64) -> Result<Self> {
        let proposed_payload_size = self
            .current_payload_size
            .checked_add(data_size)
            .ok_or_else(|| EwfError::Malformed("writer table group payload overflow".into()))?;
        if self.current_entry_count != 0
            && (self.current_entry_count >= max_entries || proposed_payload_size > max_payload)
        {
            return Ok(Self {
                group_count: self.group_count.checked_add(1).ok_or_else(|| {
                    EwfError::Malformed("writer table group count overflow".into())
                })?,
                current_entry_count: 1,
                current_payload_size: data_size,
            });
        }

        Ok(Self {
            group_count: self.group_count.max(1),
            current_entry_count: self.current_entry_count.checked_add(1).ok_or_else(|| {
                EwfError::Malformed("writer table group entry count overflow".into())
            })?,
            current_payload_size: proposed_payload_size,
        })
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Ewf1TableGroupLayout {
    first_chunk: usize,
    end_chunk: usize,
    payload_size: u64,
    sectors_desc_offset: u64,
    sectors_data_offset: u64,
    table_desc_offset: u64,
    table_data_size: u64,
    table2_desc_offset: Option<u64>,
    end_offset: u64,
}

fn ewf1_table_groups(
    chunks: &[ChunkDescriptor],
    max_entries: usize,
    max_payload: u64,
) -> Result<Vec<Ewf1TableGroup>> {
    let mut groups = Vec::new();
    let mut first_chunk = 0_usize;
    let mut state = Ewf1TableGroupState::default();
    for (index, chunk) in chunks.iter().enumerate() {
        let next_state = state.add_chunk(chunk.data_size, max_entries, max_payload)?;
        if next_state.group_count > state.group_count && state.current_entry_count != 0 {
            groups.push(Ewf1TableGroup {
                first_chunk,
                end_chunk: index,
                payload_size: state.current_payload_size,
            });
            first_chunk = index;
        }
        state = next_state;
    }
    groups.push(Ewf1TableGroup {
        first_chunk,
        end_chunk: chunks.len(),
        payload_size: state.current_payload_size,
    });
    Ok(groups)
}

fn ewf1_table_group_layouts(
    chunks: &[ChunkDescriptor],
    first_sectors_desc_offset: u64,
    table_footer_bytes: u64,
    writes_table2: bool,
) -> Result<Vec<Ewf1TableGroupLayout>> {
    let groups = ewf1_table_groups(
        chunks,
        EWF1_TABLE_GROUP_MAX_ENTRIES,
        EWF1_TABLE_GROUP_MAX_PAYLOAD,
    )?;
    let mut layouts = Vec::with_capacity(groups.len());
    let mut cursor = first_sectors_desc_offset;
    for group in groups {
        let table_entry_bytes = u64::try_from(group.end_chunk - group.first_chunk)
            .map_err(|_| EwfError::Malformed("writer table entry count does not fit u64".into()))?
            .checked_mul(4)
            .ok_or_else(|| EwfError::Malformed("writer table entry size overflow".into()))?;
        let table_data_size = 24_u64
            .checked_add(table_entry_bytes)
            .and_then(|value| value.checked_add(table_footer_bytes))
            .ok_or_else(|| EwfError::Malformed("writer table data size overflow".into()))?;
        let sectors_desc_offset = cursor;
        let sectors_data_offset = sectors_desc_offset
            .checked_add(ewf1::SECTION_DESCRIPTOR_SIZE as u64)
            .ok_or_else(|| EwfError::Malformed("writer sectors data offset overflow".into()))?;
        let table_desc_offset = sectors_data_offset
            .checked_add(group.payload_size)
            .ok_or_else(|| EwfError::Malformed("writer table descriptor offset overflow".into()))?;
        let table_end_offset = table_desc_offset
            .checked_add(ewf1::SECTION_DESCRIPTOR_SIZE as u64)
            .and_then(|value| value.checked_add(table_data_size))
            .ok_or_else(|| EwfError::Malformed("writer table section range overflow".into()))?;
        let (table2_desc_offset, end_offset) = if writes_table2 {
            let end_offset = table_end_offset
                .checked_add(ewf1::SECTION_DESCRIPTOR_SIZE as u64)
                .and_then(|value| value.checked_add(table_data_size))
                .ok_or_else(|| {
                    EwfError::Malformed("writer table2 section range overflow".into())
                })?;
            (Some(table_end_offset), end_offset)
        } else {
            (None, table_end_offset)
        };
        layouts.push(Ewf1TableGroupLayout {
            first_chunk: group.first_chunk,
            end_chunk: group.end_chunk,
            payload_size: group.payload_size,
            sectors_desc_offset,
            sectors_data_offset,
            table_desc_offset,
            table_data_size,
            table2_desc_offset,
            end_offset,
        });
        cursor = end_offset;
    }
    Ok(layouts)
}

fn append_ewf1_table_data(
    bytes: &mut Vec<u8>,
    chunk_count: u32,
    sectors_data_offset: u64,
    chunks: &[ChunkDescriptor],
    include_footer: bool,
) -> Result<()> {
    bytes.extend_from_slice(&table_header(chunk_count, sectors_data_offset));
    let table_entries_start = bytes.len();
    let mut relative_offset = 0_u64;
    for chunk in chunks {
        let mut entry = u32::try_from(relative_offset).map_err(|_| {
            EwfError::Unsupported("EWF1 writer raw chunk offset exceeds u32".into())
        })?;
        if entry & 0x8000_0000 != 0 {
            return Err(EwfError::Unsupported(
                "EWF1 writer raw chunk offset exceeds 31 bits".into(),
            ));
        }
        if chunk.compressed {
            entry |= 0x8000_0000;
        }
        bytes.extend_from_slice(&entry.to_le_bytes());
        relative_offset = relative_offset
            .checked_add(chunk.data_size)
            .ok_or_else(|| EwfError::Malformed("writer chunk offset overflow".into()))?;
    }
    if include_footer {
        let entries_checksum = adler32(&bytes[table_entries_start..]);
        bytes.extend_from_slice(&entries_checksum.to_le_bytes());
    }
    Ok(())
}

fn section_desc(section_type: &[u8], next: u64, size: u64) -> [u8; ewf1::SECTION_DESCRIPTOR_SIZE] {
    let mut desc = [0; ewf1::SECTION_DESCRIPTOR_SIZE];
    desc[..section_type.len()].copy_from_slice(section_type);
    desc[16..24].copy_from_slice(&next.to_le_bytes());
    desc[24..32].copy_from_slice(&size.to_le_bytes());
    let checksum = adler32(&desc[..ewf1::SECTION_DESCRIPTOR_SIZE - 4]);
    desc[ewf1::SECTION_DESCRIPTOR_SIZE - 4..].copy_from_slice(&checksum.to_le_bytes());
    desc
}

fn header_payload(
    metadata: &EwfMetadata,
    header_codepage: HeaderCodepage,
    compression_level: WriteCompressionLevel,
) -> Result<Option<Vec<u8>>> {
    ewf1_header_text(metadata, Ewf1HeaderDateStyle::Header)
        .map(|text| {
            zlib_payload(
                &encode_header_text(&text, header_codepage),
                compression_level,
            )
        })
        .transpose()
}

fn header2_payload(
    metadata: &EwfMetadata,
    compression_level: WriteCompressionLevel,
) -> Result<Option<Vec<u8>>> {
    ewf1_header_text(metadata, Ewf1HeaderDateStyle::Header2)
        .map(|text| zlib_payload(&utf16le(&text), compression_level))
        .transpose()
}

fn xheader_payload(
    metadata: &EwfMetadata,
    compression_level: WriteCompressionLevel,
) -> Result<Option<Vec<u8>>> {
    let fields = [
        ("case_number", metadata.case_number.as_deref()),
        ("description", metadata.description.as_deref()),
        ("examiner_name", metadata.examiner.as_deref()),
        ("evidence_number", metadata.evidence_number.as_deref()),
        ("notes", metadata.notes.as_deref()),
        ("acquiry_operating_system", metadata.os_version.as_deref()),
        ("acquiry_date", metadata.acquisition_date.as_deref()),
        ("acquiry_software", metadata.acquisition_software.as_deref()),
        (
            "acquiry_software_version",
            metadata.acquisition_software_version.as_deref(),
        ),
        ("password", metadata.password.as_deref()),
    ];
    if fields.iter().all(|(_, value)| value.is_none()) && metadata.header_values.is_empty() {
        return Ok(None);
    }

    let mut xml = String::from("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<xheader>\n");
    for (tag, value) in fields {
        let Some(value) = value else {
            continue;
        };
        if value.is_empty() {
            continue;
        }
        xml.push('\t');
        xml.push('<');
        xml.push_str(tag);
        xml.push('>');
        xml.push_str(&escape_xml_text(&xheader_field_value(tag, value)));
        xml.push_str("</");
        xml.push_str(tag);
        xml.push_str(">\n");
    }
    for (tag, value) in &metadata.header_values {
        if fields.iter().any(|(existing_tag, _)| existing_tag == tag) || value.is_empty() {
            continue;
        }
        xml.push('\t');
        xml.push('<');
        xml.push_str(tag);
        xml.push('>');
        xml.push_str(&escape_xml_text(&xheader_field_value(tag, value)));
        xml.push_str("</");
        xml.push_str(tag);
        xml.push_str(">\n");
    }
    xml.push_str("</xheader>\n\n");

    let mut payload = vec![0xef, 0xbb, 0xbf];
    payload.extend_from_slice(xml.as_bytes());
    Ok(Some(zlib_payload(&payload, compression_level)?))
}

fn xheader_field_value<'a>(tag: &str, value: &'a str) -> Cow<'a, str> {
    if tag == "acquiry_date" {
        format_xheader_date_value(value)
    } else {
        Cow::Borrowed(value)
    }
}

fn zlib_payload(payload: &[u8], compression_level: WriteCompressionLevel) -> Result<Vec<u8>> {
    let mut encoder = ZlibEncoder::new(Vec::new(), zlib_compression(compression_level));
    encoder.write_all(payload)?;
    Ok(encoder.finish()?)
}

fn escape_xml_text(value: &str) -> String {
    let mut escaped = String::with_capacity(value.len());
    for ch in value.chars() {
        match ch {
            '&' => escaped.push_str("&amp;"),
            '<' => escaped.push_str("&lt;"),
            '>' => escaped.push_str("&gt;"),
            '"' => escaped.push_str("&quot;"),
            '\'' => escaped.push_str("&apos;"),
            _ => escaped.push(ch),
        }
    }
    escaped
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Ewf1HeaderDateStyle {
    Header,
    Header2,
}

fn ewf1_header_text(metadata: &EwfMetadata, date_style: Ewf1HeaderDateStyle) -> Option<String> {
    let fields = [
        ("c", metadata.case_number.as_deref()),
        ("n", metadata.evidence_number.as_deref()),
        ("a", metadata.description.as_deref()),
        ("e", metadata.examiner.as_deref()),
        ("t", metadata.notes.as_deref()),
        ("av", metadata.acquisition_software_version.as_deref()),
        ("ov", metadata.os_version.as_deref()),
        ("m", metadata.acquisition_date.as_deref()),
        ("u", metadata.system_date.as_deref()),
        ("p", metadata.password.as_deref()),
    ];
    if fields.iter().all(|(_, value)| value.is_none()) && metadata.header_values.is_empty() {
        return None;
    }

    let mut names = Vec::new();
    let mut values = Vec::new();
    for (name, value) in fields {
        if let Some(value) = value {
            names.push(name.to_string());
            values.push(sanitize_header_value(&ewf1_header_field_value(
                name, value, date_style,
            )));
        }
    }
    for (name, value) in &metadata.header_values {
        let tag = ewf1_header_tag(name);
        if metadata.password.is_some() && tag == "p" {
            continue;
        }
        if names.iter().any(|existing| existing == tag) {
            continue;
        }
        names.push(tag.to_string());
        values.push(sanitize_header_value(&ewf1_header_field_value(
            tag, value, date_style,
        )));
    }

    let text = format!("1\nmain\n{}\n{}\n", names.join("\t"), values.join("\t"));
    Some(text)
}

fn ewf1_header_tag(identifier: &str) -> &str {
    match identifier {
        "acquiry_date" => "m",
        "acquiry_operating_system" => "ov",
        "acquiry_software_version" => "av",
        "case_number" => "c",
        "compression_level" => "r",
        "description" => "a",
        "device_label" => "l",
        "evidence_number" => "n",
        "examiner_name" => "e",
        "extents" => "ext",
        "model" => "md",
        "notes" => "t",
        "password" => "p",
        "process_identifier" => "pid",
        "serial_number" => "sn",
        "system_date" => "u",
        "unknown_dc" => "dc",
        _ => identifier,
    }
}

fn ewf1_header_field_value<'a>(
    name: &str,
    value: &'a str,
    date_style: Ewf1HeaderDateStyle,
) -> Cow<'a, str> {
    if !matches!(name, "m" | "u" | "acquiry_date" | "system_date") {
        return Cow::Borrowed(value);
    }

    match date_style {
        Ewf1HeaderDateStyle::Header => format_ewf1_header_date_value(value),
        Ewf1HeaderDateStyle::Header2 => format_ewf1_header2_date_value(value),
    }
}

fn sanitize_header_value(value: &str) -> String {
    value
        .chars()
        .map(|ch| {
            if matches!(ch, '\t' | '\n' | '\r') {
                ' '
            } else {
                ch
            }
        })
        .collect()
}

fn digest_payload(hashes: &WriteHashes) -> Option<[u8; 80]> {
    if hashes.md5.is_none() && hashes.sha1.is_none() {
        return None;
    }

    let mut digest = [0; 80];
    if let Some(md5) = hashes.md5 {
        digest[..16].copy_from_slice(&md5);
    }
    if let Some(sha1) = hashes.sha1 {
        digest[16..36].copy_from_slice(&sha1);
    }
    let checksum = adler32(&digest[..76]);
    digest[76..80].copy_from_slice(&checksum.to_le_bytes());
    Some(digest)
}

fn xhash_payload(
    hashes: &WriteHashes,
    compression_level: WriteCompressionLevel,
) -> Result<Option<Vec<u8>>> {
    if hashes.md5.is_none() && hashes.sha1.is_none() && hashes.hash_values.is_empty() {
        return Ok(None);
    }

    let mut xml = String::from("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<xhash>\n");
    if let Some(md5) = hashes.md5 {
        xml.push_str("\t<md5>");
        xml.push_str(&hex_string(&md5));
        xml.push_str("</md5>\n");
    }
    if let Some(sha1) = hashes.sha1 {
        xml.push_str("\t<sha1>");
        xml.push_str(&hex_string(&sha1));
        xml.push_str("</sha1>\n");
    }
    for (tag, value) in &hashes.hash_values {
        if matches!(tag.as_str(), "MD5" | "md5" | "SHA1" | "sha1") || value.is_empty() {
            continue;
        }
        xml.push('\t');
        xml.push('<');
        xml.push_str(tag);
        xml.push('>');
        xml.push_str(&escape_xml_text(value));
        xml.push_str("</");
        xml.push_str(tag);
        xml.push_str(">\n");
    }
    xml.push_str("</xhash>\n\n");

    let mut payload = vec![0xef, 0xbb, 0xbf];
    payload.extend_from_slice(xml.as_bytes());
    Ok(Some(zlib_payload(&payload, compression_level)?))
}

fn hex_string(bytes: &[u8]) -> String {
    const HEX: &[u8; 16] = b"0123456789abcdef";
    let mut out = String::with_capacity(bytes.len() * 2);
    for byte in bytes {
        out.push(char::from(HEX[(byte >> 4) as usize]));
        out.push(char::from(HEX[(byte & 0x0f) as usize]));
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    fn chunk(data_size: u64) -> ChunkDescriptor {
        ChunkDescriptor {
            data_offset: 0,
            data_size,
            compressed: false,
            has_checksum: false,
            pattern_fill: None,
        }
    }

    #[test]
    fn table_groups_split_at_31_bit_payload_cap() {
        let one_gib = 0x4000_0000_u64;
        let chunks = vec![chunk(one_gib), chunk(one_gib), chunk(one_gib)];

        let groups = ewf1_table_groups(
            &chunks,
            EWF1_TABLE_GROUP_MAX_ENTRIES,
            EWF1_TABLE_GROUP_MAX_PAYLOAD,
        )
        .unwrap();

        assert_eq!(groups.len(), 3);
        for group in &groups {
            assert!(group.payload_size <= EWF1_TABLE_GROUP_MAX_PAYLOAD);
        }
    }

    #[test]
    fn table_groups_split_at_entry_cap() {
        let chunks = vec![chunk(512); 5];

        let groups = ewf1_table_groups(&chunks, 2, EWF1_TABLE_GROUP_MAX_PAYLOAD).unwrap();

        assert_eq!(
            groups,
            [
                Ewf1TableGroup {
                    first_chunk: 0,
                    end_chunk: 2,
                    payload_size: 1024
                },
                Ewf1TableGroup {
                    first_chunk: 2,
                    end_chunk: 4,
                    payload_size: 1024
                },
                Ewf1TableGroup {
                    first_chunk: 4,
                    end_chunk: 5,
                    payload_size: 512
                },
            ]
        );
    }

    #[test]
    fn table_group_count_estimate_accounts_for_interacting_limits() {
        let large_chunk_size =
            EWF1_TABLE_GROUP_MAX_PAYLOAD / EWF1_TABLE_GROUP_MAX_ENTRIES as u64 + 1;
        let mut chunks = vec![chunk(1); EWF1_TABLE_GROUP_MAX_ENTRIES];
        chunks.extend(std::iter::repeat_n(
            chunk(large_chunk_size),
            EWF1_TABLE_GROUP_MAX_ENTRIES,
        ));
        let actual_groups = ewf1_table_groups(
            &chunks,
            EWF1_TABLE_GROUP_MAX_ENTRIES,
            EWF1_TABLE_GROUP_MAX_PAYLOAD,
        )
        .unwrap();
        let estimated_state = chunks
            .iter()
            .try_fold(Ewf1TableGroupState::default(), |state, chunk| {
                state.add_chunk(
                    chunk.data_size,
                    EWF1_TABLE_GROUP_MAX_ENTRIES,
                    EWF1_TABLE_GROUP_MAX_PAYLOAD,
                )
            })
            .unwrap();

        assert_eq!(actual_groups.len(), 3);
        assert_eq!(estimated_state.group_count, actual_groups.len() as u64);
    }

    #[test]
    fn segment_groups_respect_maximum_size_when_table_limits_interact() {
        let large_chunk_size =
            EWF1_TABLE_GROUP_MAX_PAYLOAD / EWF1_TABLE_GROUP_MAX_ENTRIES as u64 + 1;
        let mut chunks = vec![chunk(1); EWF1_TABLE_GROUP_MAX_ENTRIES];
        chunks.extend(std::iter::repeat_n(
            chunk(large_chunk_size),
            EWF1_TABLE_GROUP_MAX_ENTRIES,
        ));
        let options = WriteOptions::default();
        let payload_size = chunks.iter().map(|chunk| chunk.data_size).sum();
        let old_aggregate_estimate =
            estimated_ewf1_segment_size(chunks.len(), payload_size, 2, &options).unwrap();

        let segments =
            segment_groups(&chunks, Some(old_aggregate_estimate), &options, 0, 0).unwrap();

        assert!(segments.len() > 1);
        for segment_range in segments {
            let segment = &chunks[segment_range];
            let payload_size = segment.iter().map(|chunk| chunk.data_size).sum();
            let table_group_state = segment
                .iter()
                .try_fold(Ewf1TableGroupState::default(), |state, chunk| {
                    state.add_chunk(
                        chunk.data_size,
                        EWF1_TABLE_GROUP_MAX_ENTRIES,
                        EWF1_TABLE_GROUP_MAX_PAYLOAD,
                    )
                })
                .unwrap();
            let estimated_size = estimated_ewf1_segment_size(
                segment.len(),
                payload_size,
                table_group_state.group_count,
                &options,
            )
            .unwrap();
            assert!(estimated_size <= old_aggregate_estimate);
        }
    }

    #[test]
    fn segment_groups_return_ranges_into_descriptor_slice() {
        let chunks = vec![chunk(512); 3];
        let options = WriteOptions::default();
        let one_chunk_segment_size = estimated_ewf1_segment_size(1, 512, 1, &options).unwrap();

        let groups: Vec<std::ops::Range<usize>> =
            segment_groups(&chunks, Some(one_chunk_segment_size), &options, 0, 0).unwrap();

        assert_eq!(groups, [0..1, 1..2, 2..3]);
    }

    #[test]
    fn table_groups_keep_small_payload_in_one_group() {
        let chunks = vec![chunk(32_768), chunk(32_768)];

        let groups = ewf1_table_groups(
            &chunks,
            EWF1_TABLE_GROUP_MAX_ENTRIES,
            EWF1_TABLE_GROUP_MAX_PAYLOAD,
        )
        .unwrap();

        assert_eq!(groups.len(), 1);
        assert_eq!(groups[0].payload_size, 65_536);
    }

    #[test]
    fn table_groups_cover_empty_chunk_list_with_one_empty_group() {
        let groups = ewf1_table_groups(
            &[],
            EWF1_TABLE_GROUP_MAX_ENTRIES,
            EWF1_TABLE_GROUP_MAX_PAYLOAD,
        )
        .unwrap();

        assert_eq!(
            groups,
            [Ewf1TableGroup {
                first_chunk: 0,
                end_chunk: 0,
                payload_size: 0
            }]
        );
    }

    #[test]
    fn table_group_layouts_chain_sequential_section_offsets() {
        let chunks = vec![chunk(0x4000_0000), chunk(0x4000_0000), chunk(0x4000_0000)];

        let layouts = ewf1_table_group_layouts(&chunks, 1000, 4, true).unwrap();

        assert_eq!(layouts.len(), 3);
        let mut expected_offset = 1000;
        for (index, layout) in layouts.iter().enumerate() {
            assert_eq!(layout.sectors_desc_offset, expected_offset);
            assert_eq!(layout.sectors_data_offset, expected_offset + 76);
            assert_eq!(
                layout.table_desc_offset,
                layout.sectors_data_offset + 0x4000_0000
            );
            assert_eq!(layout.table_data_size, 24 + 4 + 4);
            assert_eq!(
                layout.table2_desc_offset,
                Some(layout.table_desc_offset + 76 + layout.table_data_size)
            );
            assert_eq!(layout.first_chunk, index);
            assert_eq!(layout.end_chunk, index + 1);
            expected_offset = layout.end_offset;
        }
    }
}