limnifs-write 0.2.59

LimniFS writer pipeline — directory tree to .lim image
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
//! Compression profiles — predefined codec strategies for different goals.
//!
//! A [`CompressionProfile`] bundles codec selection, parameters, tournament
//! behavior, and chunking into a single named configuration. Four built-in
//! profiles cover the main use cases; users can define custom profiles via
//! TOML.
//!
//! ## Built-in profiles
//!
//! | Profile | Goal | Create speed | Ratio | vs SquashFS | vs DwarFS |
//! |---------|------|-------------|-------|------------|-----------|
//! | `max-ratio` | Smallest output | Slow | Best | Wins ratio | Ties ratio |
//! | `max-speed` | Fastest create | Match SquashFS | OK | Ties speed | Wins speed |
//! | `balanced` | Good trade-off | Medium | Good | Wins ratio | Wins speed |
//! | `competitive` | Beat both | Fast | Best-of-both | **Wins both** | **Wins both** |
//!
//! ## Usage
//!
//! ```toml
//! # Use a built-in profile
//! profile = "competitive"
//!
//! # Or define a custom profile inline
//! [profile]
//! name = "my-custom"
//! text_codec = "brotli"
//! brotli_quality = 7
//! binary_codec = "lz4"
//! chunk_avg_size = 32768
//! tournament = "none"
//! ```

#![allow(warnings)]

use serde::{Deserialize, Serialize};

use crate::config::{
    ChunkingConfig, CodecTunables, Defaults, DictionaryConfig, EncryptionConfig, TournamentConfig,
    WriteConfig,
};

/// Built-in profile names.
pub const MAX_RATIO: &str = "max-ratio";
pub const MAX_SPEED: &str = "max-speed";
pub const BALANCED: &str = "balanced";
pub const COMPETITIVE: &str = "competitive";
pub const MAX_READ: &str = "max-read";
pub const MAX_WRITE: &str = "max-write";
pub const MAX_WRITE_RW: &str = "max-write-rw";
pub const MAX_READ_RW: &str = "max-read-rw";
pub const BALANCED_RW: &str = "balanced-rw";

/// Select a built-in profile by name. Returns a complete [`WriteConfig`]
/// configured for that profile's strategy.
#[must_use]
pub fn select(name: &str) -> Option<WriteConfig> {
    match name {
        MAX_RATIO => Some(max_ratio()),
        MAX_SPEED => Some(max_speed()),
        BALANCED => Some(balanced()),
        COMPETITIVE => Some(competitive()),
        MAX_READ => Some(max_read()),
        MAX_WRITE => Some(max_write()),
        MAX_WRITE_RW => Some(max_write_rw()),
        MAX_READ_RW => Some(max_read_rw()),
        BALANCED_RW => Some(balanced_rw()),
        _ => None,
    }
}

/// Maximum compression ratio. Tries every applicable codec per drop,
/// picks the smallest. Slowest create, smallest output.
///
/// - Text: Brotli q11 + LZMA + PPMd7 (256 MB budget) tournament
/// - Binary: ZSTD L19 + LZMA tournament
/// - Categorizers: all enabled (FLAC, Rice++, FSST+Brotli)
/// - Chunks: 64 KB (better cross-chunk pattern matching)
/// - Whole-file max: 256 MB
#[must_use]
pub fn max_ratio() -> WriteConfig {
    WriteConfig {
        defaults: Defaults {
            text_codec: "brotli".into(),
            binary_codec: "zstd".into(),
            metadata_codec: "brotli".into(),
            metadata_quality: 11,
            metadata_externalize_threshold: crate::METADATA_EXTERNALIZE_THRESHOLD,
            shared_inline: true,
            inline_threshold: 8192,
        },
        categorizers: crate::config::defaults::all_v0_1(),
        chunking: ChunkingConfig {
            name: "fastcdc".into(),
            avg_chunk_size: 65_536,
            min_chunk_size: 8192,
            max_chunk_size: 262_144,
        },
        tournament: TournamentConfig {
            codecs: vec![
                "store".into(),
                "lz4".into(),
                "lz4-hc".into(),
                "zstd".into(),
                "brotli".into(),
                "ppmd".into(),
                "bzip2".into(),
            ],
            min_size_threshold: 256,
            skip_for_binary: false,
            short_circuit_threshold: 0,
        },
        codec_tunables: CodecTunables {
            ppmd7: crate::config::Ppmd7Tunables {
                order: 6,
                memory_budget_mb: 256,
            },
            ppmd8: crate::config::Ppmd8Tunables {
                order: 8,
                memory_budget_mb: 128,
            },
            brotli: crate::config::BrotliTunables {
                quality: 11,
                window: 24,
            },
            lzma: crate::config::LzmaTunables {
                lc: 3,
                lp: 0,
                pb: 2,
                dict_size_mb: 64,
                use_optimal_parser: true,
            },
            bzip2: crate::config::Bzip2Tunables { block_size_kb: 900 },
        },
        encryption: EncryptionConfig {
            aead: "chacha20-poly1305".into(),
            key_wrap: "x25519-hkdf".into(),
        },
        dictionaries: DictionaryConfig {
            enabled: true,
            min_class_size: 50,
            max_dict_size: 131_072,
            trainer: "frequency".into(),
        },
        mode: crate::config::ImageMode::ReadOnly,
        write_codec: "lz4".into(),
        turnover_threshold: 0,
        skip_chunking: false,
    }
}

/// Maximum speed. Single-codec per content class, no tournament.
/// Matches SquashFS LZ4 speed on binary data.
///
/// - Text: LZ4 (instant)
/// - Binary: LZ4 (instant)
/// - Categorizers: disabled (no FLAC, no Rice++)
/// - Tournament: none (classify once, compress once)
/// - Chunks: 4 KB (maximum parallelism)
#[must_use]
pub fn max_speed() -> WriteConfig {
    WriteConfig {
        defaults: Defaults {
            text_codec: "lz4".into(),
            binary_codec: "lz4".into(),
            metadata_codec: "lz4".into(),
            metadata_quality: 1,
            metadata_externalize_threshold: crate::METADATA_EXTERNALIZE_THRESHOLD,
            shared_inline: true,
            inline_threshold: 4096,
        },
        categorizers: vec![],
        chunking: ChunkingConfig {
            name: "fastcdc".into(),
            avg_chunk_size: 4096,
            min_chunk_size: 512,
            max_chunk_size: 16_384,
        },
        tournament: TournamentConfig {
            codecs: vec!["store".into(), "lz4".into()],
            min_size_threshold: 0,
            skip_for_binary: true,
            short_circuit_threshold: 500,
        },
        codec_tunables: CodecTunables {
            brotli: crate::config::BrotliTunables {
                quality: 0,
                window: 10,
            },
            ..CodecTunables::default()
        },
        encryption: EncryptionConfig {
            aead: "chacha20-poly1305".into(),
            key_wrap: "x25519-hkdf".into(),
        },
        dictionaries: DictionaryConfig {
            enabled: false,
            min_class_size: 0,
            max_dict_size: 0,
            trainer: "frequency".into(),
        },
        mode: crate::config::ImageMode::ReadOnly,
        write_codec: "lz4".into(),
        turnover_threshold: 0,
        skip_chunking: false,
    }
}

/// Balanced profile. Good ratio + good speed for general use.
///
/// - Text: Brotli q5 (fast, good ratio)
/// - Binary: LZ4 (fast)
/// - Categorizers: FLAC for small audio, skip large
/// - Tournament: Brotli + ZSTD only
/// - Chunks: 16 KB
#[must_use]
pub fn balanced() -> WriteConfig {
    WriteConfig {
        defaults: Defaults {
            text_codec: "brotli".into(),
            binary_codec: "lz4".into(),
            metadata_codec: "zstd".into(),
            metadata_quality: 3,
            metadata_externalize_threshold: crate::METADATA_EXTERNALIZE_THRESHOLD,
            shared_inline: true,
            inline_threshold: 4096,
        },
        categorizers: crate::config::defaults::all_v0_1(),
        chunking: ChunkingConfig {
            name: "fastcdc".into(),
            avg_chunk_size: 16_384,
            min_chunk_size: 2048,
            max_chunk_size: 65_536,
        },
        tournament: TournamentConfig {
            codecs: vec!["store".into(), "lz4".into(), "brotli".into()],
            min_size_threshold: 256,
            skip_for_binary: true,
            short_circuit_threshold: 250,
        },
        codec_tunables: CodecTunables {
            brotli: crate::config::BrotliTunables {
                quality: 5,
                window: 22,
            },
            ..CodecTunables::default()
        },
        encryption: EncryptionConfig {
            aead: "chacha20-poly1305".into(),
            key_wrap: "x25519-hkdf".into(),
        },
        dictionaries: DictionaryConfig {
            enabled: true,
            min_class_size: 100,
            max_dict_size: 65_536,
            trainer: "frequency".into(),
        },
        mode: crate::config::ImageMode::ReadOnly,
        write_codec: "lz4".into(),
        turnover_threshold: 0,
        skip_chunking: false,
    }
}

/// Competitive profile — beat SquashFS on ratio AND DwarFS on speed.
///
/// Uses ZSTD L1 for text (5x faster compress than Brotli, 3x faster
/// decompress, 3x better ratio than SquashFS LZ4). LZ4 for binary.
#[must_use]
pub fn competitive() -> WriteConfig {
    WriteConfig {
        defaults: Defaults {
            text_codec: "zstd".into(),
            binary_codec: "lz4".into(),
            metadata_codec: "zstd".into(),
            metadata_quality: 3,
            metadata_externalize_threshold: crate::METADATA_EXTERNALIZE_THRESHOLD,
            shared_inline: true,
            inline_threshold: 4096,
        },
        categorizers: crate::config::defaults::all_v0_1(),
        chunking: ChunkingConfig {
            name: "fastcdc".into(),
            avg_chunk_size: 8192,
            min_chunk_size: 1024,
            max_chunk_size: 65_536,
        },
        tournament: TournamentConfig {
            codecs: vec!["store".into(), "lz4".into(), "brotli".into()],
            min_size_threshold: 0,
            skip_for_binary: true,
            short_circuit_threshold: 250,
        },
        codec_tunables: CodecTunables {
            brotli: crate::config::BrotliTunables {
                quality: 5,
                window: 22,
            },
            ..CodecTunables::default()
        },
        encryption: EncryptionConfig {
            aead: "chacha20-poly1305".into(),
            key_wrap: "x25519-hkdf".into(),
        },
        dictionaries: DictionaryConfig {
            enabled: false,
            min_class_size: 0,
            max_dict_size: 0,
            trainer: "frequency".into(),
        },
        mode: crate::config::ImageMode::ReadOnly,
        write_codec: "lz4".into(),
        turnover_threshold: 0,
        skip_chunking: false,
    }
}

/// Maximum read profile — optimized for read-heavy workloads (write
/// once, read many). Uses codecs with the best ratio that still
/// decompresses quickly. Write cost is amortised over many reads.
///
/// - Text/Binary: ZSTD L19 (best ratio among fast-decompress codecs;
///   ZSTD decompresses at ~1500 MB/s vs Brotli's ~500 MB/s)
/// - Metadata: ZSTD L19
/// - Categorizers: enabled (FLAC, Rice++ for best ratio per file type)
/// - Chunks: 64 KB (fewer drops = fewer slab lookups during extract)
/// - Inline threshold: 8192 (more inline = fewer slab reads)
#[must_use]
pub fn max_read() -> WriteConfig {
    WriteConfig {
        defaults: Defaults {
            text_codec: "zstd".into(),
            binary_codec: "zstd".into(),
            metadata_codec: "zstd".into(),
            metadata_quality: 11,
            metadata_externalize_threshold: crate::METADATA_EXTERNALIZE_THRESHOLD,
            shared_inline: true,
            inline_threshold: 8192,
        },
        categorizers: crate::config::defaults::all_v0_1(),
        chunking: ChunkingConfig {
            name: "fastcdc".into(),
            avg_chunk_size: 65_536,
            min_chunk_size: 8192,
            max_chunk_size: 262_144,
        },
        tournament: TournamentConfig {
            codecs: vec!["store".into(), "lz4".into(), "zstd".into(), "brotli".into()],
            min_size_threshold: 256,
            skip_for_binary: false,
            short_circuit_threshold: 200,
        },
        codec_tunables: CodecTunables {
            brotli: crate::config::BrotliTunables {
                quality: 11,
                window: 22,
            },
            lzma: crate::config::LzmaTunables {
                dict_size_mb: 64,
                use_optimal_parser: true,
                ..crate::config::LzmaTunables::default()
            },
            ..CodecTunables::default()
        },
        encryption: EncryptionConfig {
            aead: "chacha20-poly1305".into(),
            key_wrap: "x25519-hkdf".into(),
        },
        dictionaries: DictionaryConfig {
            enabled: true,
            min_class_size: 50,
            max_dict_size: 131_072,
            trainer: "frequency".into(),
        },
        mode: crate::config::ImageMode::ReadOnly,
        write_codec: "lz4".into(),
        turnover_threshold: 0,
        skip_chunking: false,
    }
}

/// Maximum write profile — optimized for write-heavy workloads where
/// write latency matters more than ratio. Uses the fastest possible
/// compression (LZ4 at ~1 GB/s) and skips all categorization/tournament
/// overhead.
///
/// - Text/Binary/Metadata: LZ4 (fastest compress AND decompress)
/// - Categorizers: disabled (zero categorization overhead)
/// - Tournament: none (classify once, compress once)
/// - Chunks: 128 KB (minimal per-chunk overhead)
#[must_use]
pub fn max_write() -> WriteConfig {
    WriteConfig {
        defaults: Defaults {
            text_codec: "lz4".into(),
            binary_codec: "lz4".into(),
            metadata_codec: "lz4".into(),
            metadata_quality: 1,
            metadata_externalize_threshold: crate::METADATA_EXTERNALIZE_THRESHOLD,
            shared_inline: true,
            inline_threshold: 4096,
        },
        categorizers: vec![],
        chunking: ChunkingConfig {
            name: "fastcdc".into(),
            avg_chunk_size: 131_072,
            min_chunk_size: 16_384,
            max_chunk_size: 524_288,
        },
        tournament: TournamentConfig {
            codecs: vec!["store".into(), "lz4".into()],
            min_size_threshold: 0,
            skip_for_binary: true,
            short_circuit_threshold: 500,
        },
        codec_tunables: CodecTunables::default(),
        encryption: EncryptionConfig {
            aead: "chacha20-poly1305".into(),
            key_wrap: "x25519-hkdf".into(),
        },
        dictionaries: DictionaryConfig {
            enabled: false,
            min_class_size: 0,
            max_dict_size: 0,
            trainer: "frequency".into(),
        },
        mode: crate::config::ImageMode::ReadOnly,
        write_codec: "lz4".into(),
        turnover_threshold: 0,
        skip_chunking: true,
    }
}

/// Maximum write profile for RW images — optimized for write-heavy
/// live filesystems where write latency per operation matters most.
///
/// - Write codec: LZ4 (instant compress, minimal write latency)
/// - Turnover codec: ZSTD L12 (re-compaction with decent ratio)
/// - Mode: CopyOnWrite (fast updates, unreferenced blocks reclaimed)
/// - Chunks: 128 KB (minimal per-chunk overhead per write)
/// - Turnover threshold: 500 updates
#[must_use]
pub fn max_write_rw() -> WriteConfig {
    WriteConfig {
        defaults: Defaults {
            text_codec: "lz4".into(),
            binary_codec: "lz4".into(),
            metadata_codec: "lz4".into(),
            metadata_quality: 1,
            metadata_externalize_threshold: crate::METADATA_EXTERNALIZE_THRESHOLD,
            shared_inline: true,
            inline_threshold: 4096,
        },
        categorizers: vec![],
        chunking: ChunkingConfig {
            name: "fastcdc".into(),
            avg_chunk_size: 131_072,
            min_chunk_size: 16_384,
            max_chunk_size: 524_288,
        },
        tournament: TournamentConfig {
            codecs: vec!["store".into(), "lz4".into()],
            min_size_threshold: 0,
            skip_for_binary: true,
            short_circuit_threshold: 500,
        },
        codec_tunables: CodecTunables::default(),
        mode: crate::config::ImageMode::ReadWrite(crate::config::RWMode::CopyOnWrite),
        write_codec: "lz4".into(),
        turnover_threshold: 500,
        skip_chunking: true,
        encryption: EncryptionConfig {
            aead: "chacha20-poly1305".into(),
            key_wrap: "x25519-hkdf".into(),
        },
        dictionaries: DictionaryConfig {
            enabled: false,
            min_class_size: 0,
            max_dict_size: 0,
            trainer: "frequency".into(),
        },
    }
}

/// Maximum read profile for RW images — optimized for read-heavy
/// live filesystems where read throughput and integrity matter.
///
/// - Write codec: ZSTD L6 (good ratio, decent compress speed)
/// - Turnover codec: ZSTD L19 (best ratio for compaction)
/// - Mode: UpdateInPlace (full history for audit trail)
/// - Chunks: 64 KB (fewer drops to traverse during reads)
/// - Turnover threshold: 1000 updates
#[must_use]
pub fn max_read_rw() -> WriteConfig {
    WriteConfig {
        defaults: Defaults {
            text_codec: "zstd".into(),
            binary_codec: "zstd".into(),
            metadata_codec: "zstd".into(),
            metadata_quality: 6,
            metadata_externalize_threshold: crate::METADATA_EXTERNALIZE_THRESHOLD,
            shared_inline: true,
            inline_threshold: 8192,
        },
        categorizers: crate::config::defaults::all_v0_1(),
        chunking: ChunkingConfig {
            name: "fastcdc".into(),
            avg_chunk_size: 65_536,
            min_chunk_size: 8192,
            max_chunk_size: 262_144,
        },
        tournament: TournamentConfig {
            codecs: vec!["store".into(), "lz4".into(), "zstd".into(), "brotli".into()],
            min_size_threshold: 256,
            skip_for_binary: false,
            short_circuit_threshold: 200,
        },
        codec_tunables: CodecTunables {
            brotli: crate::config::BrotliTunables {
                quality: 11,
                window: 22,
            },
            ..CodecTunables::default()
        },
        mode: crate::config::ImageMode::ReadWrite(crate::config::RWMode::UpdateInPlace),
        write_codec: "zstd".into(),
        turnover_threshold: 1000,
        skip_chunking: false,
        encryption: EncryptionConfig {
            aead: "chacha20-poly1305".into(),
            key_wrap: "x25519-hkdf".into(),
        },
        dictionaries: DictionaryConfig {
            enabled: true,
            min_class_size: 50,
            max_dict_size: 131_072,
            trainer: "frequency".into(),
        },
    }
}

/// Balanced RW profile — general-purpose read-write image.
///
/// - Write codec: ZSTD L1 (fast, decent ratio per write)
/// - Turnover codec: Brotli q5 (good ratio compaction)
/// - Mode: UpdateInPlace
/// - Chunks: 16 KB
/// - Turnover threshold: 1000 updates
#[must_use]
pub fn balanced_rw() -> WriteConfig {
    WriteConfig {
        defaults: Defaults {
            text_codec: "zstd".into(),
            binary_codec: "lz4".into(),
            metadata_codec: "zstd".into(),
            metadata_quality: 3,
            metadata_externalize_threshold: crate::METADATA_EXTERNALIZE_THRESHOLD,
            shared_inline: true,
            inline_threshold: 4096,
        },
        categorizers: crate::config::defaults::all_v0_1(),
        chunking: ChunkingConfig {
            name: "fastcdc".into(),
            avg_chunk_size: 16_384,
            min_chunk_size: 2048,
            max_chunk_size: 65_536,
        },
        tournament: TournamentConfig {
            codecs: vec!["store".into(), "lz4".into(), "zstd".into()],
            min_size_threshold: 256,
            skip_for_binary: true,
            short_circuit_threshold: 250,
        },
        codec_tunables: CodecTunables {
            brotli: crate::config::BrotliTunables {
                quality: 5,
                window: 22,
            },
            ..CodecTunables::default()
        },
        mode: crate::config::ImageMode::ReadWrite(crate::config::RWMode::UpdateInPlace),
        write_codec: "zstd".into(),
        turnover_threshold: 1000,
        skip_chunking: false,
        encryption: EncryptionConfig {
            aead: "chacha20-poly1305".into(),
            key_wrap: "x25519-hkdf".into(),
        },
        dictionaries: DictionaryConfig {
            enabled: true,
            min_class_size: 100,
            max_dict_size: 65_536,
            trainer: "frequency".into(),
        },
    }
}

/// TOML-representable profile selector. Either a built-in name or
/// an inline custom profile.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(untagged)]
pub enum ProfileSpec {
    /// Use a built-in profile by name.
    Preset(String),
    /// Define a custom profile inline.
    Custom(CustomProfile),
}

/// User-defined profile fields. Any field not specified inherits from
/// the `balanced` profile.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq, Default)]
pub struct CustomProfile {
    pub name: String,
    #[serde(default = "default_text")]
    pub text_codec: String,
    #[serde(default = "default_binary")]
    pub binary_codec: String,
    #[serde(default = "default_quality")]
    pub brotli_quality: u8,
    #[serde(default)]
    pub chunk_avg_size: u32,
    #[serde(default)]
    pub skip_tournament_for_binary: bool,
    #[serde(default = "default_true")]
    pub enable_flac: bool,
    #[serde(default = "default_true")]
    pub enable_ricepp: bool,
}

fn default_text() -> String {
    "brotli".into()
}
fn default_binary() -> String {
    "lz4".into()
}
fn default_quality() -> u8 {
    5
}
fn default_true() -> bool {
    true
}

/// Resolve a [`ProfileSpec`] into a concrete [`WriteConfig`].
pub fn resolve(spec: &ProfileSpec) -> Option<WriteConfig> {
    match spec {
        ProfileSpec::Preset(name) => select(name),
        ProfileSpec::Custom(custom) => {
            let mut config = balanced();
            if !custom.text_codec.is_empty() {
                config.defaults.text_codec = custom.text_codec.clone();
            }
            if !custom.binary_codec.is_empty() {
                config.defaults.binary_codec = custom.binary_codec.clone();
            }
            if custom.brotli_quality > 0 {
                config.codec_tunables.brotli.quality = custom.brotli_quality;
            }
            if custom.chunk_avg_size > 0 {
                config.chunking.avg_chunk_size = custom.chunk_avg_size;
            }
            config.tournament.skip_for_binary = custom.skip_tournament_for_binary;
            if !custom.enable_flac {
                config.categorizers.retain(|c| c.name != "pcm_audio");
            }
            if !custom.enable_ricepp {
                config.categorizers.retain(|c| c.name != "fits");
            }
            Some(config)
        }
    }
}

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

    #[test]
    fn all_builtins_resolve() {
        for name in [
            MAX_RATIO,
            MAX_SPEED,
            BALANCED,
            COMPETITIVE,
            MAX_READ,
            MAX_WRITE,
            MAX_WRITE_RW,
            MAX_READ_RW,
            BALANCED_RW,
        ] {
            let config = select(name).expect("profile exists");
            config.validate().expect("validates");
        }
    }

    #[test]
    fn competitive_uses_lz4_for_binary() {
        let config = competitive();
        assert_eq!(config.binary_codec_id().unwrap(), 0x01); // LZ4
    }

    #[test]
    fn competitive_uses_zstd_for_text() {
        let config = competitive();
        assert_eq!(config.text_codec_id().unwrap(), 0x02); // ZSTD
    }

    #[test]
    fn max_speed_disables_categorizers() {
        let config = max_speed();
        assert!(config.categorizers.is_empty());
    }

    #[test]
    fn max_ratio_enables_ppmd() {
        let config = max_ratio();
        assert_eq!(config.codec_tunables.ppmd7.memory_budget_mb, 256);
    }

    #[test]
    fn custom_profile_inherits_balanced() {
        let spec = ProfileSpec::Custom(CustomProfile {
            name: "test".into(),
            brotli_quality: 9,
            ..CustomProfile::default()
        });
        let config = resolve(&spec).expect("resolves");
        assert_eq!(config.codec_tunables.brotli.quality, 9);
        // Inherited from balanced
        assert_eq!(config.defaults.text_codec, "brotli");
    }
}