lz4r 1.10.0

LZ4 CLI programs — Rust port of lz4-1.10.0/programs
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
//! Deterministic lorem ipsum text generator.
//!
//! Produces pseudo-random Latin text from a fixed word pool, seeded by an
//! arbitrary `u32`.  The same seed always produces the same output, making
//! this suitable for repeatable compression benchmarks.
//!

use std::sync::OnceLock;

// ---------------------------------------------------------------------------
// Word pool
// ---------------------------------------------------------------------------

static K_WORDS: &[&str] = &[
    "lorem",
    "ipsum",
    "dolor",
    "sit",
    "amet",
    "consectetur",
    "adipiscing",
    "elit",
    "sed",
    "do",
    "eiusmod",
    "tempor",
    "incididunt",
    "ut",
    "labore",
    "et",
    "dolore",
    "magna",
    "aliqua",
    "dis",
    "lectus",
    "vestibulum",
    "mattis",
    "ullamcorper",
    "velit",
    "commodo",
    "a",
    "lacus",
    "arcu",
    "magnis",
    "parturient",
    "montes",
    "nascetur",
    "ridiculus",
    "mus",
    "mauris",
    "nulla",
    "malesuada",
    "pellentesque",
    "eget",
    "gravida",
    "in",
    "dictum",
    "non",
    "erat",
    "nam",
    "voluptat",
    "maecenas",
    "blandit",
    "aliquam",
    "etiam",
    "enim",
    "lobortis",
    "scelerisque",
    "fermentum",
    "dui",
    "faucibus",
    "ornare",
    "at",
    "elementum",
    "eu",
    "facilisis",
    "odio",
    "morbi",
    "quis",
    "eros",
    "donec",
    "ac",
    "orci",
    "purus",
    "turpis",
    "cursus",
    "leo",
    "vel",
    "porta",
    "consequat",
    "interdum",
    "varius",
    "vulputate",
    "aliquet",
    "pharetra",
    "nunc",
    "auctor",
    "urna",
    "id",
    "metus",
    "viverra",
    "nibh",
    "cras",
    "mi",
    "unde",
    "omnis",
    "iste",
    "natus",
    "error",
    "perspiciatis",
    "voluptatem",
    "accusantium",
    "doloremque",
    "laudantium",
    "totam",
    "rem",
    "aperiam",
    "eaque",
    "ipsa",
    "quae",
    "ab",
    "illo",
    "inventore",
    "veritatis",
    "quasi",
    "architecto",
    "beatae",
    "vitae",
    "dicta",
    "sunt",
    "explicabo",
    "nemo",
    "ipsam",
    "quia",
    "voluptas",
    "aspernatur",
    "aut",
    "odit",
    "fugit",
    "consequuntur",
    "magni",
    "dolores",
    "eos",
    "qui",
    "ratione",
    "sequi",
    "nesciunt",
    "neque",
    "porro",
    "quisquam",
    "est",
    "dolorem",
    "adipisci",
    "numquam",
    "eius",
    "modi",
    "tempora",
    "incidunt",
    "magnam",
    "quaerat",
    "ad",
    "minima",
    "veniam",
    "nostrum",
    "ullam",
    "corporis",
    "suscipit",
    "laboriosam",
    "nisi",
    "aliquid",
    "ex",
    "ea",
    "commodi",
    "consequatur",
    "autem",
    "eum",
    "iure",
    "voluptate",
    "esse",
    "quam",
    "nihil",
    "molestiae",
    "illum",
    "fugiat",
    "quo",
    "pariatur",
    "vero",
    "accusamus",
    "iusto",
    "dignissimos",
    "ducimus",
    "blanditiis",
    "praesentium",
    "voluptatum",
    "deleniti",
    "atque",
    "corrupti",
    "quos",
    "quas",
    "molestias",
    "excepturi",
    "sint",
    "occaecati",
    "cupiditate",
    "provident",
    "similique",
    "culpa",
    "officia",
    "deserunt",
    "mollitia",
    "animi",
    "laborum",
    "dolorum",
    "fuga",
    "harum",
    "quidem",
    "rerum",
    "facilis",
    "expedita",
    "distinctio",
    "libero",
    "tempore",
    "cum",
    "soluta",
    "nobis",
    "eligendi",
    "optio",
    "cumque",
    "impedit",
    "minus",
    "quod",
    "maxime",
    "placeat",
    "facere",
    "possimus",
    "assumenda",
    "repellendus",
    "temporibus",
    "quibusdam",
    "officiis",
    "debitis",
    "saepe",
    "eveniet",
    "voluptates",
    "repudiandae",
    "recusandae",
    "itaque",
    "earum",
    "hic",
    "tenetur",
    "sapiente",
    "delectus",
    "reiciendis",
    "cillum",
    "maiores",
    "alias",
    "perferendis",
    "doloribus",
    "asperiores",
    "repellat",
    "minim",
    "nostrud",
    "exercitation",
    "ullamco",
    "laboris",
    "aliquip",
    "duis",
    "aute",
    "irure",
];

/// Sampling weight by word length (index clamped to the last entry for `len ≥ 5`).
/// Shorter words are selected more often to mimic natural language frequency.
static K_WEIGHTS: &[i32] = &[0, 8, 6, 4, 3, 2];

// ---------------------------------------------------------------------------
// Word pool — lazy-initialised once
// ---------------------------------------------------------------------------

struct WordPool {
    word_lens: Vec<usize>,
    /// Distribution table: each entry is an index into K_WORDS.
    distrib: Vec<usize>,
    distrib_count: usize,
}

static WORD_POOL: OnceLock<WordPool> = OnceLock::new();

fn get_pool() -> &'static WordPool {
    WORD_POOL.get_or_init(|| {
        let nb_weights = K_WEIGHTS.len();
        let word_lens: Vec<usize> = K_WORDS.iter().map(|w| w.len()).collect();

        // Total number of distribution slots (sum of weights across all words).
        let distrib_count: usize = word_lens
            .iter()
            .map(|&len| K_WEIGHTS[len.min(nb_weights - 1)].max(0) as usize)
            .sum();

        // Build a weighted distribution table: each word appears as many times
        // as its weight, so uniformly sampling an index yields length-weighted
        // word selection.
        let mut distrib = Vec::with_capacity(distrib_count);
        for (w, &len) in word_lens.iter().enumerate() {
            let lmax = K_WEIGHTS[len.min(nb_weights - 1)].max(0) as usize;
            for _ in 0..lmax {
                distrib.push(w);
            }
        }

        WordPool {
            word_lens,
            distrib,
            distrib_count,
        }
    })
}

// ---------------------------------------------------------------------------
// Per-call generation context (replaces C file-scope globals)
// ---------------------------------------------------------------------------

struct GenCtx<'a> {
    buf: &'a mut [u8],
    nb_chars: usize,
    max_chars: usize,
    rand_root: u32,
}

impl<'a> GenCtx<'a> {
    /// Custom 32-bit PRNG using multiply-then-XOR-rotate operations.
    ///
    /// Returns a pseudo-random value in `[0, range)`.  The state advances
    /// with every call, so consecutive calls produce different values.
    #[inline]
    fn lorem_rand(&mut self, range: u32) -> u32 {
        const PRIME1: u32 = 2_654_435_761;
        const PRIME2: u32 = 2_246_822_519;
        let mut r = self.rand_root;
        r = r.wrapping_mul(PRIME1);
        r ^= PRIME2;
        r = r.rotate_left(13);
        self.rand_root = r;
        ((r as u64 * range as u64) >> 32) as u32
    }

    /// Returns a value distributed approximately around `target` (minimum 1).
    #[inline]
    fn about(&mut self, target: u32) -> u32 {
        self.lorem_rand(target) + self.lorem_rand(target) + 1
    }

    /// Fill remaining buffer space with `. <spaces>\n` and advance to `max_chars`.
    fn write_last_characters(&mut self) {
        debug_assert!(self.max_chars >= self.nb_chars);
        let last_chars = self.max_chars - self.nb_chars;
        if last_chars == 0 {
            return;
        }
        self.buf[self.nb_chars] = b'.';
        self.nb_chars += 1;
        if last_chars > 2 {
            let fill_end = self.nb_chars + (last_chars - 2);
            self.buf[self.nb_chars..fill_end].fill(b' ');
        }
        if last_chars > 1 {
            self.buf[self.max_chars - 1] = b'\n';
        }
        self.nb_chars = self.max_chars;
    }

    /// Write `word` if it fits, then fill remaining space via
    /// [`Self::write_last_characters`].
    fn generate_last_word(&mut self, word: &[u8], up_case: bool) {
        let word_len = word.len();
        if self.nb_chars + word_len + 2 > self.max_chars {
            self.write_last_characters();
            return;
        }
        let dst = self.nb_chars;
        self.buf[dst..dst + word_len].copy_from_slice(word);
        if up_case {
            // 'A' - 'a' = 32; uppercase the first byte
            self.buf[dst] = self.buf[dst].wrapping_sub(32);
        }
        self.nb_chars += word_len;
        self.write_last_characters();
    }

    /// Write one word followed by `sep` into the buffer.
    ///
    /// Falls back to [`Self::generate_last_word`] when the remaining space is
    /// too small for a full word plus two bytes of headroom.
    ///
    /// The reference C implementation unconditionally writes 16 bytes as a
    /// micro-optimisation; this version copies exactly `word.len()` bytes,
    /// which is behaviourally equivalent for the visible output.
    fn generate_word(&mut self, word: &[u8], sep: &[u8], up_case: bool) {
        let word_len = word.len();
        let sep_len = sep.len();
        // wlen = MAX(16, wordLen + 2) — minimum headroom needed
        let wlen = 16usize.max(word_len + 2);
        if self.nb_chars + wlen > self.max_chars {
            self.generate_last_word(word, up_case);
            return;
        }
        let dst = self.nb_chars;
        // See doc comment: the reference C version writes 16 bytes; we write wordLen.
        self.buf[dst..dst + word_len].copy_from_slice(word);
        if up_case {
            self.buf[dst] = self.buf[dst].wrapping_sub(32);
        }
        self.nb_chars += word_len;
        // Append separator (reference C always writes exactly 2 separator bytes).
        let sdst = self.nb_chars;
        self.buf[sdst..sdst + sep_len].copy_from_slice(sep);
        self.nb_chars += sep_len;
    }

    /// Emit one sentence of `nb_words` words, randomly inserting commas and
    /// optionally ending with `?` instead of `.`.
    fn generate_sentence(&mut self, nb_words: u32, pool: &WordPool) {
        let comma_pos = self.about(9);
        let comma2 = comma_pos + self.about(7);
        let qmark = self.lorem_rand(11) == 7;
        let end_sep: &[u8] = if qmark { b"? " } else { b". " };

        for i in 0..nb_words {
            let word_id = pool.distrib[self.lorem_rand(pool.distrib_count as u32) as usize];
            let word = K_WORDS[word_id].as_bytes();
            let sep: &[u8] = if i == nb_words - 1 {
                end_sep
            } else if i == comma_pos || i == comma2 {
                b", "
            } else {
                b" "
            };
            self.generate_word(word, sep, i == 0);
        }
    }

    /// Emit one paragraph of `nb_sentences` sentences followed by a blank line.
    fn generate_paragraph(&mut self, nb_sentences: u32, pool: &WordPool) {
        for _ in 0..nb_sentences {
            let words_per_sentence = self.about(11);
            self.generate_sentence(words_per_sentence, pool);
        }
        if self.nb_chars < self.max_chars {
            self.buf[self.nb_chars] = b'\n';
            self.nb_chars += 1;
        }
        if self.nb_chars < self.max_chars {
            self.buf[self.nb_chars] = b'\n';
            self.nb_chars += 1;
        }
    }

    /// Emit the canonical opening sentence ("Lorem ipsum dolor sit amet, …")
    /// using the first 19 words of the fixed word pool.
    fn generate_first_sentence(&mut self, pool: &WordPool) {
        for i in 0..18usize {
            let sep: &[u8] = if i == 4 || i == 7 { b", " } else { b" " };
            let word = K_WORDS[i].as_bytes();
            let word_len = pool.word_lens[i];
            self.generate_word(&word[..word_len], sep, i == 0);
        }
        // word 18 with ". " separator
        let word = K_WORDS[18].as_bytes();
        let word_len = pool.word_lens[18];
        self.generate_word(&word[..word_len], b". ", false);
    }
}

// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------

/// Generate at most `buf.len()` bytes of lorem ipsum text.
///
/// Equivalent to `LOREM_genBlock` in C.
///
/// - `first`: if true, prepend the canonical "Lorem ipsum…" opening sentence.
/// - `fill`:  if true, fill the entire buffer; otherwise generate one paragraph.
///
/// Returns the number of bytes actually written.
pub fn gen_block(buf: &mut [u8], seed: u32, first: bool, fill: bool) -> usize {
    let pool = get_pool();
    let max_chars = buf.len();
    let mut ctx = GenCtx {
        buf,
        nb_chars: 0,
        max_chars,
        rand_root: seed,
    };

    if first {
        ctx.generate_first_sentence(pool);
    }

    while ctx.nb_chars < ctx.max_chars {
        let sentences_per_paragraph = ctx.about(7);
        ctx.generate_paragraph(sentences_per_paragraph, pool);
        if !fill {
            break; // only one paragraph in non-fill mode
        }
    }

    ctx.nb_chars
}

/// Fill a `Vec<u8>` of exactly `size` bytes with lorem ipsum text.
///
/// Equivalent to `LOREM_genBuffer` in C.
pub fn gen_buffer(size: usize, seed: u32) -> Vec<u8> {
    let mut buf = vec![0u8; size];
    gen_block(&mut buf, seed, true, true);
    buf
}