Debian Codegraph @

easel/esl_varint.c

raw symbols SCIP
1 /* Variable-length binary prefix codes for integers
2 *
3 * Contents:
4 * 1. Exponential Golomb codes
5 * 2. Golomb-Rice codes
6 * 3. Elias delta code
7 * 4. Google varint codes
8 * 5. Unit tests
9 * 6. Test driver
10 * 7. Example
11 *
12 * See also:
13 * esl_huffman : Huffman coding
14 */
15 #include <esl_config.h>
16
17 #include <stdio.h>
18 #include <limits.h>
19
20 #include "easel.h"
21 #include "esl_varint.h"
22
23 /*****************************************************************
24 * 1. Exponential Golomb codes
25 *****************************************************************/
26
27 /* Function: esl_varint_expgol()
28 * Synopsis: Generalized exponential Golomb coding
29 * Incept: SRE, Wed 09 Jan 2019
30 *
31 * Purpose: Encode nonnegative integer <v> in exponential-Golomb-<k>
32 * code. $k=0$ is standard exponential Golomb code; $k>0$
33 * are the generalized Golomb codes. Optionally return codeword in
34 * low-order bits of <*opt_code> (i.e. right flush), and
35 * its length in <*opt_n>.
36 *
37 * Args: v : integer to encode; v >= 0
38 * k : parameter for which exp-Golomb code; k >= 0
39 * opt_code : optRETURN: encoding, right flushed (low order bits)
40 * opt_n : optRETURN: length of encoding in bits
41 *
42 * Returns: <eslOK> on success.
43 *
44 * Throws: <eslERANGE> if caller requested <*opt_code> to be returned,
45 * but encoding doesn't fit in a single <uint64_t>. Now <*opt_code>
46 * and <*opt_n> are set to 0.
47 */
48 int
49 esl_varint_expgol(int v, int k, uint64_t *opt_code, int *opt_n)
50 {
51 ESL_DASSERT1(( v >= 0 && k >= 0 ));
52
53 uint64_t m = (1 << k); // 2^k. For k=0 standard expgol: m=1,
54 uint64_t q = v / m; // \floor (v / 2^k) piece, to be encoded in exp-golomb-0 ... q=v, all bits here,
55 uint64_t r = v % m; // will become rightmost bits ... r=0, no bits stored
56 int n = 0;
57 uint64_t code = q+1;
58 int status;
59
60 // q stored in exp-golomb-0. We already set low order bits to q+1; now we just need to determine width of q+1.
61 q = q+1;
62 while (q) { q >>= 1; n++; } // Let a = # of bits needed to represent q+1
63 n = 2 * n - 1; // now a-1 leading bits are 0, followed by a bits of q+1, for an exp-golomb-0 code.
64
65 if (opt_code && n > 64) ESL_XEXCEPTION(eslERANGE, "exponential Golomb codeword length > 64");
66
67 // r stored in its binary representation, k bits.
68 code = (code << k) | r;
69 n += k;
70
71 if (opt_code) *opt_code = code;
72 if (opt_n) *opt_n = n;
73 return eslOK;
74
75 ERROR:
76 if (opt_code) *opt_code = 0;
77 if (opt_n) *opt_n = 0;
78 return status;
79 }
80
81
82 /* Function: esl_varint_expgol_decode()
83 * Synopsis: Decode an exponential Golomb codeword.
84 * Incept: SRE, Thu 10 Jan 2019 [Slaid Cleaves, Still Fighting the War]
85 *
86 * Purpose: Decode the leading (high order) prefix bits of <code>
87 * according to exponential-Golomb-<k> code. Optionally
88 * return the decoded integer value in <*opt_v>, and the
89 * length of the decoded codeword in <*opt_n>.
90 *
91 * Note that <code> is _left flush_ for decoding: the
92 * prefix codeword is decoded from the leftmost, most
93 * significant bit.
94 *
95 * If <code> consists of only 0's, and therefore has no
96 * complete codeword, return <eslEOD>. This can be used to
97 * detect normal end of a bit string.
98 *
99 * If <code> does contain a 1 bit but does not contain a
100 * complete codeword, assume it is corrupted somehow,
101 * and return <eslECORRUPT>.
102 *
103 * Args: code : bit string to decode, starting from MSB
104 * k : parameter for which exp-Golomb code; k >= 0
105 * opt_v: optRETURN: integer value
106 * opt_n: optRETURN: length of decoded prefix codeword, in bits
107 *
108 * Returns: <eslOK> on success.
109 *
110 * <eslEOD> if <code> is all 0 bits.
111 * <eslECORRUPT> if at least one 1 bit is set, yet no
112 * codeword is present. On errors, <*opt_v> and <*opt_n>
113 * are 0.
114 */
115 int
116 esl_varint_expgol_decode(uint64_t code, int k, int *opt_v, int *opt_n)
117 {
118 int b,n,r,v;
119 int status;
120
121 if (! code) { status = eslEOD; goto ERROR; } // all exp-Golomb codewords contain at least one 1
122
123 for (b = 63; b >= 0; b--)
124 if (code & (1ull << b)) break; // now b is position of leftmost 1 bit (i.e. MSB); 63..0.
125 n = 2*(64-b)+k-1; // ...and from that, we know the size of the codeword.
126 if (n > 64) { status = eslECORRUPT; goto ERROR; } // looks like a code but can't be valid
127
128 // the n-bit codeword consists of the binary representation of q+1 (with leading zeros),
129 // followed by a k-bit remainder.
130 code >>= 64-n;
131 r = code & ((1ull << k) - 1);
132 code >>= k;
133 v = (code-1) * (1ull << k) + r;
134
135 if (opt_v) *opt_v = v;
136 if (opt_n) *opt_n = n;
137 return eslOK;
138
139 ERROR:
140 if (opt_v) *opt_v = 0;
141 if (opt_n) *opt_n = 0;
142 return status;
143 }
144
145
146 /*****************************************************************
147 * 2. Golomb-Rice codes
148 *****************************************************************/
149
150 /* Function: esl_varint_rice()
151 * Synopsis: Golomb-Rice coding
152 * Incept: SRE, Sat 12 Jan 2019 [Ramin Djawadi, Westworld, The Maze]
153 *
154 * Purpose: Encode nonnegative integer <v> in Golomb-Rice-<k> code,
155 * for $k \geq 0$. Optionally return codeword in low-order bits of
156 * <*opt_code> (i.e. right flush) and its length in <*opt_n>.
157 *
158 * Args: v : integer to encode; v >= 0
159 * k : parameter for which Golomb-Rice code; k >= 0
160 * opt_code : optRETURN: encoding, right flushed (low order bits)
161 * opt_n : optRETURN: length of encoding in bits
162 *
163 * Returns: <eslOK> on success.
164 *
165 * Throws: <eslERANGE> if caller requested <*opt_code> to be returned,
166 * but encoding doesn't fit in a single <uint64_t>. Now <*opt_code>
167 * and <*opt_n> are set to 0.
168 */
169 int
170 esl_varint_rice(int v, int k, uint64_t *opt_code, int *opt_n)
171 {
172 ESL_DASSERT1(( v >= 0 && k >= 0));
173 int m = (1 << k); // 2^k
174 int q = v / m; // int(v / 2^k), quotient. code leads with this many 1's; then a 0
175 int r = v % m; // remainder. encoded in k bits
176 uint64_t code = 0;
177 int status;
178
179 if (opt_code && q > 64-(k+1)) ESL_XEXCEPTION(eslERANGE, "Golomb-Rice codeword length > 64");
180
181 code = (1ull << q) - 1; // sets q low-order bits to 1; we know 2^{q+1} fits in uint64_t
182 code = code << (1 + k); // bit k+1 is a 0; low-order k bits hold r
183 code |= r;
184
185 if (opt_code) *opt_code = code;
186 if (opt_n) *opt_n = q + k + 1;
187 return eslOK;
188
189 ERROR:
190 if (opt_code) *opt_code = 0;
191 if (opt_n) *opt_n = 0;
192 return status;
193 }
194
195
196 /* Function: esl_varint_rice_decode()
197 * Synopsis: Decode a Golomb-Rice codeword
198 * Incept: SRE, Sat 12 Jan 2019 [Real Madrid v. Leganes]
199 *
200 * Purpose: Decode the leading (high order) prefix bits of <code>
201 * according to Golomb-Rice-<k> code. Optionally return the
202 * decoded integer value in <*opt_v>, and the length
203 * of the decoded codeword in <*opt_n>.
204 *
205 * Note that <code> is _left flush_ for decoding:
206 * the prefix codeword is decoded from the leftmost,
207 * most significant bit.
208 *
209 * If <code> does not contain a 0 bit, return <eslEOD>; it
210 * cannot contain a valid codeword. A caller can shift on
211 * a pattern of all 1 bits to signal EOD.
212 *
213 * There is no check for overflowing <v>. We assume that
214 * <code> encodes a value that fits in an int.
215 *
216 * Args: code : bit string to decode, starting from MSB
217 * k : parameter for which Google varint code; k >= 2
218 * opt_v: optRETURN: integer value
219 * opt_n: optRETURN: length of decoded prefix codeword, in bits
220 *
221 * Returns: <eslOK> on success.
222 * <eslEOD> if <code> has no completed codeword.
223 *
224 * Throws: (no abnormal error conditions)
225 */
226 int
227 esl_varint_rice_decode(uint64_t code, int k, int *opt_v, int *opt_n)
228 {
229 int q;
230 int status;
231
232 if (~code == 0) { status = eslEOD; goto ERROR; } // valid rice code has at least one 0 bit
233
234 for (q = 0; q <= 64-k; q++)
235 if ( (~code) & (1ull << (63-q))) break; // q = # of leading 1 bits. +1, +k: n = q + k + 1.
236
237 code >>= 64-(q+k+1); // shift 64 - (q+k+1) bits off to the right, right-flushing the codeword.
238 /* q * 2^k + r, obtained by masking low k bits */
239 if (opt_v) *opt_v = (int) (q * (1ull << k) + (code & ( (1ull << (k+1)) - 1)));
240 if (opt_n) *opt_n = q + k + 1;
241 return eslOK;
242
243 ERROR:
244 if (opt_v) *opt_v = 0;
245 if (opt_n) *opt_n = 0;
246 return status;
247 }
248
249
250
251 /*****************************************************************
252 * 3. Elias delta code
253 *****************************************************************/
254
255 /* Function: esl_varint_delta
256 * Synopsis: Elias delta coding
257 * Incept: SRE, Sat 12 Jan 2019
258 *
259 * Purpose: Encode positive integer <v> in Elias delta code.
260 * Optionally return codeword in low-order bits of
261 * <*opt_code> (i.e. right flush), and its length
262 * in <*opt_n>.
263 *
264 * Args: v : integer to encode; v >= 1
265 * opt_code : optRETURN: encoding, right flushed (low order bits)
266 * opt_n : optRETURN: length of encoding in bits
267 *
268 * Returns: <eslOK> on success.
269 *
270 * Throws: <eslERANGE> if caller requested <*opt_code> to be returned,
271 * but encoding doesn't fit in a single <uint64_t>. Now <*opt_code>
272 * and <*opt_n> are set to 0.
273 */
274 int
275 esl_varint_delta(int v, uint64_t *opt_code, int *opt_n)
276 {
277 ESL_DASSERT1(( v >= 1 ));
278 int a = 0; // \floor log_2 v 2^a is the highest power of 2 in v
279 int b = 0; // \floor log_2 (a+1)
280 int n = 0;
281 uint64_t code = 0;
282 uint64_t tmp;
283 int status;
284
285 tmp = ((uint64_t) v >> 1); while (tmp) { tmp = tmp >> 1; a++; }
286 tmp = ((uint64_t) (a+1) >> 1); while (tmp) { tmp = tmp >> 1; b++; }
287
288 n = b; // b leading zeros
289 n += b+1; code = a+1; // b+1 bits, representation of a+1
290 n += a; code = (code << a) | (v & ((1 << a) - 1)); // a bits, v % 2^a
291
292 if (opt_code && n > 64) ESL_XEXCEPTION(eslERANGE, "Elias delta codeword length > 64");
293
294 if (opt_code) *opt_code = code;
295 if (opt_n) *opt_n = n;
296 return eslOK;
297
298 ERROR:
299 if (opt_code) *opt_code = 0;
300 if (opt_n) *opt_n = 0;
301 return status;
302 }
303
304
305 /* Function: esl_varint_delta_decode()
306 * Synopsis: Decode an Elias delta codeword.
307 * Incept: SRE, Sat 12 Jan 2019
308 *
309 * Purpose: Decode the leading (high order) prefix bits of <code>
310 * using Elias delta code. Optionally return the decoded
311 * integer value in <*opt_v>, and/or the length of the
312 * decoded codeword in <*opt_n>.
313 *
314 * Note that <code> is _left flush_ for decoding: the
315 * prefix codeword is decoded from the leftmost, most
316 * significant bit.
317 *
318 * If <code> consists of only 0's, and therefore has
319 * no complete codeword, return <eslEOD>. This can be
320 * used to detect the normal end of a bit string.
321 *
322 * If <code> does contain a 1 bit but does not contain a
323 * complete codeword, assume it is corrupted somehow, and
324 * throw <eslECORRUPT>.
325 *
326 * Args: code : bit string to decode, starting from MSB
327 * opt_v: optRETURN: integer value
328 * opt_n: optRETURN: length of decoded prefix codeword, in bits
329 *
330 * Returns: <eslOK> on success.
331 *
332 * <eslEOD> if <code> is all 0 bits.
333 * <eslECORRUPT> if at least one 1 bit is set, yet no codeword
334 * is present. On errors, <*opt_v> and <*opt_n> are 0.
335 */
336 int
337 esl_varint_delta_decode(uint64_t code, int *opt_v, int *opt_n)
338 {
339 int a,b,n,status;
340
341 if (code == 0) { status = eslEOD; goto ERROR; }
342
343 for (b = 0; b < 64; b++)
344 if (code & (1ull << (63-b))) break; // stop on first 1. b = # of leading 0 bits
345 a = (code >> (63 - 2*b)) - 1; // After b leading 0's, b+1 bits encode a+1
346 n = 2*b + a + 1;
347
348 if (n > 64) { status = eslECORRUPT; goto ERROR; }
349
350 // Last a bits encodes v mod 2^a, all but the highest order bit;
351 // shift and mask to get those a bits, then add 2^a back.
352 if (opt_v) *opt_v = (1<<a) + ((code >> (64 - n)) & ( (1<<a)-1));
353 if (opt_n) *opt_n = n;
354 return eslOK;
355
356 ERROR:
357 if (opt_v) *opt_v = 0;
358 if (opt_n) *opt_n = 0;
359 return status;
360 }
361
362
363
364
365 /*****************************************************************
366 * 4. Google varint codes
367 *****************************************************************/
368
369 /* Function: esl_varint_google()
370 * Synopsis: Google varint coding
371 * Incept: SRE, Fri 11 Jan 2019 [Eminem, Lose Yourself]
372 *
373 * Purpose: Encode nonnegative integer <v> in Google varint-<k> code;
374 * $k \geq 2$; $k=8$ gives you one-byte codewords, the code
375 * used by Google Protobuf. Optionally return code in
376 * low-order bits of <*opt_code> (i.e. right flushed), and
377 * length of that code in <*opt_n>.
378 *
379 * Args: v : integer to encode; v >= 0
380 * k : parameter for which Google varint code; k >= 2
381 * opt_code : optRETURN: encoding, right flushed (low order bits)
382 * opt_n : optRETURN: length of encoding in bits
383 *
384 * Returns: <eslOK> on success.
385 *
386 * Throws: <eslERANGE> if caller requested <*opt_code> to be returned,
387 * but binary encoding won't fit in a single
388 * <uint64_t>. <*opt_code> and <*opt_n> are set to 0.
389 */
390 int
391 esl_varint_google(int v, int k, uint64_t *opt_code, int *opt_n)
392 {
393 ESL_DASSERT1(( k >= 2 ));
394 ESL_DASSERT1(( v >= 0 ));
395
396 int base = 1 << (k-1); // 2^(k-1)
397 uint64_t code = 0;
398 int n = 0;
399 int status;
400
401 code |= v % base;
402 v /= base;
403 n += k;
404 while (v > 0)
405 {
406 code |= (1 << (k-1));
407 code = code << k;
408
409 code |= v % base;
410 v /= base;
411 n += k;
412 }
413 if (n > 64 && opt_code) ESL_XEXCEPTION(eslERANGE, "google varint code length > 64");
414
415 if (opt_code) *opt_code = code;
416 if (opt_n) *opt_n = n;
417 return eslOK;
418
419 ERROR:
420 if (opt_code) *opt_code = 0;
421 if (opt_n) *opt_n = 0;
422 return status;
423 }
424
425
426 /* Function: esl_varint_google_decode()
427 * Synopsis: Decode a Google varint codeword
428 * Incept: SRE, Fri 11 Jan 2019
429 *
430 * Purpose: Decode the leading (high order) prefix bits of <code>
431 * according to Google varint-<k> code. Optionally
432 * return the decoded integer value in <*opt_v>, and the
433 * length of the decoded codeword in <*opt_n>.
434 *
435 * Note that <code> is _left flush_ for decoding: the
436 * prefix codeword is decoded from the leftmost, most
437 * significant bit.
438 *
439 * If <code> does not contain a termination codegroup (i.e.
440 * it consists only of continuation groups that start with
441 * 1), return <eslEOD>. A caller can shift on a pattern of
442 * all 1 bits to signal EOD.
443 *
444 * There is no check for overflowing <v>. We assume that
445 * <code> encodes a value that fits in an int.
446 *
447 * Args: code : bit string to decode, starting from MSB
448 * k : parameter for which Google varint code; k >= 2
449 * opt_v: optRETURN: integer value
450 * opt_n: optRETURN: length of decoded prefix codeword, in bits
451 *
452 * Returns: <eslOK> on success.
453 * <eslEOD> if <code> has no completed codeword.
454 */
455 int
456 esl_varint_google_decode(uint64_t code, int k, int *opt_v, int *opt_n)
457 {
458 uint64_t cmask = 1ull << (k-1);
459 uint64_t vmask = cmask-1;
460 int v = 0;
461 uint64_t grp; // current k-bit code group
462 int g; // which group (least significant group first)
463 int status;
464
465 for (g = 0; g < 64/k; code <<= k, g++)
466 {
467 grp = code >> (64-k);
468 v += (grp & vmask) << (g*(k-1));
469 if (!(grp & cmask)) break;
470 }
471 if (grp & cmask) { status = eslEOD; goto ERROR; }
472
473 if (opt_v) *opt_v = v;
474 if (opt_n) *opt_n = (g+1)*k;
475 return eslOK;
476
477 ERROR:
478 if (opt_v) *opt_v = 0;
479 if (opt_n) *opt_n = 0;
480 return status;
481 }
482
483
484
485
486 /*****************************************************************
487 * 5. Unit tests
488 *****************************************************************/
489 #ifdef eslVARINT_TESTDRIVE
490
491 #include "esl_random.h"
492
493 /* floor_log2()
494 * Returns $w = \lfloor \log_2 v \rfloor$
495 * w is the highest power of 2 in v;
496 * equivalently, w is the MSB set in v
497 *
498 * Example: v=53 ==> 00110101 ==> w=5 (2^5 = 32)
499 */
500 static int
501 floor_log2(int v)
502 {
503 return (v == 0 ? 0 : (int) floor(log2(v)));
504 }
505
506 /* floor_log2k()
507 * Returns $\lfloor \log_{2^k} v \rfloor$
508 */
509 static int
510 floor_log2k(int v, int k)
511 {
512 return ( v == 0 ? 0 : (int) floor( log2(v)) / k);
513 }
514
515 int len_expgol(int v, int k) { return (2 * floor_log2((v / (1<<k)) + 1) + 1 + k); }
516 int64_t max_expgol(int b, int k) { return (((1ull << (((b-k-1)/2) + 1)) - 1) << k) - 1; }
517 int len_rice (int v, int k) { return (1 + k + (v / (1ull << k))); }
518 int max_rice (int b, int k) { return ( (1ull << k) * (b-k) - 1); }
519 int len_delta (int v) { return (floor_log2(v) + 2 * floor_log2( (floor_log2(v) + 1)) + 1); }
520 int len_google(int v, int k) { return ( k * (floor_log2k(v,k-1) + 1)); }
521 int64_t max_google(int b, int k) { return ((1ull << ((b/k) * (k-1))) - 1); }
522
523
524 static void
525 utest_expgol(ESL_RANDOMNESS *rng)
526 {
527 char msg[] = "utest_expgol exponential Golomb tests failed";
528 uint64_t code;
529 int64_t maxv;
530 int v, v2;
531 int n, n2;
532 int k;
533 int b;
534 int i;
535
536 /* Spot check exponential Golomb (standard, k=0) against
537 * documentation's example table.
538 * 9 encodes as 0001010, len 7, e.g. 0xa
539 */
540 if ( esl_varint_expgol( 9, 0, &code, &n) != eslOK) esl_fatal(msg);
541 if ( code != 0xall || n != 7) esl_fatal(msg);
542
543 /* Also spot check documented exp-Golomb-2 code
544 * 9 encodes as 01101, len 5, e.g. 0xd
545 */
546 if ( esl_varint_expgol( 9, 2, &code, &n) != eslOK) esl_fatal(msg);
547 if ( code != 0xdll || n != 5) esl_fatal(msg);
548
549 /* Systematically check exp-Golomb-k codes from k=0..10 */
550 for (k = 0; k <= 10; k++)
551 {
552 /* Check encoding of v=0..999 */
553 for (v = 0; v < 1000; v++)
554 {
555 if ( esl_varint_expgol(v, k, &code, &n) != eslOK) esl_fatal(msg);
556 if ( esl_varint_expgol_decode(code << (64-n), k, &v2, &n2) != eslOK) esl_fatal(msg);
557 if (n != len_expgol(v, k)) esl_fatal(msg);
558 if (v != v2 || n != n2) esl_fatal(msg);
559 }
560
561 /* Check a bunch of random values on valid range */
562 maxv = ESL_MIN(INT_MAX, max_expgol(64, k)); // this is always INT_MAX
563 for (i = 0; i < 1000; i++)
564 {
565 v = esl_rnd_Roll(rng, (int) maxv); // 0..maxv-1, anyway.
566 if ( esl_varint_expgol(v, k, &code, &n) != eslOK) esl_fatal(msg);
567 if ( esl_varint_expgol_decode(code << (64-n), k, &v2, &n2) != eslOK) esl_fatal(msg);
568 if (n != len_expgol(v, k)) esl_fatal(msg);
569 if (v != v2 || n != n2) esl_fatal(msg);
570 }
571
572 /* Check our documented maxv calculations, and encoding at each max */
573 for (b = k+1; b <= 62; b++) // 62, because maxv+1 will need larger code, and exp-golomb codes grow in steps of 2
574 {
575 maxv = max_expgol(b, k);
576 if (maxv <= INT_MAX) // check that we can represent maxv in an int
577 {
578 if ( esl_varint_expgol((int) maxv, k, &code, &n) != eslOK) esl_fatal(msg);
579 if ( esl_varint_expgol_decode(code << (64-n), k, &v2, &n2) != eslOK) esl_fatal(msg);
580 if (n != len_expgol(maxv, k)) esl_fatal(msg);
581 if (maxv != v2 || n != n2) esl_fatal(msg);
582 }
583 if (maxv < INT_MAX) // maxv+1 can be coded
584 {
585 if ( esl_varint_expgol((int) (maxv+1), k, NULL, &n2) != eslOK) esl_fatal(msg);
586 if (n2 <= n) esl_fatal(msg);
587 }
588 }
589 }
590 }
591
592
593 static void
594 utest_rice(ESL_RANDOMNESS *rng)
595 {
596 char msg[] = "utest_rice Golomb-Rice tests failed";
597 uint64_t code;
598 int64_t maxv;
599 int v, v2;
600 int n, n2;
601 int k;
602 int b;
603 int i;
604
605 /* Spot check against documentation's example table for Golomb-Rice-2.
606 * 9 encodes as 11001, len 5, e.g. 0x19
607 */
608 if ( esl_varint_rice( 9, 2, &code, &n) != eslOK) esl_fatal(msg);
609 if ( code != 0x19ll || n != 5) esl_fatal(msg);
610
611 /* Systematically check Golomb-Rice-k codes from k=0..10 */
612 for (k = 0; k <= 10; k++)
613 {
614 /* Check encoding of v=0..1000 */
615 maxv = ESL_MIN(1000, max_rice(64, k));
616 for (v = 0; v <= maxv; v++)
617 {
618 if ( esl_varint_rice(v, k, &code, &n) != eslOK) esl_fatal(msg);
619 if ( esl_varint_rice_decode(code << (64-n), k, &v2, &n2) != eslOK) esl_fatal(msg);
620 if (n != len_rice(v, k)) esl_fatal(msg);
621 if (v != v2 || n != n2) esl_fatal(msg);
622 }
623
624 /* Check a bunch of random values on valid range */
625 maxv = ESL_MIN(INT_MAX, max_rice(64, k)); // Rice codes have limited range.
626 for (i = 0; i < 1000; i++)
627 {
628 v = esl_rnd_Roll(rng, (int) maxv); // 0..maxv-1, anyway.
629 if ( esl_varint_rice(v, k, &code, &n) != eslOK) esl_fatal(msg);
630 if ( esl_varint_rice_decode(code << (64-n), k, &v2, &n2) != eslOK) esl_fatal(msg);
631 if (n != len_rice(v, k)) esl_fatal(msg);
632 if (v != v2 || n != n2) esl_fatal(msg);
633 }
634
635 /* Check our documented maxv calculations, and encoding at each max */
636 for (b = k+1; b <= 63; b++) // 63, because maxv+1 will need larger code, and Golomb-Rice codes grow in steps of 1
637 {
638 maxv = max_rice(b, k);
639 if (maxv <= INT_MAX) // check that we can represent maxv in an int
640 {
641 if ( esl_varint_rice((int) maxv, k, &code, &n) != eslOK) esl_fatal(msg);
642 if ( esl_varint_rice_decode(code << (64-n), k, &v2, &n2) != eslOK) esl_fatal(msg);
643 if (n != len_rice(maxv, k)) esl_fatal(msg);
644 if (maxv != v2 || n != n2) esl_fatal(msg);
645 }
646 if (maxv < INT_MAX) // maxv+1 can be coded
647 {
648 if ( esl_varint_rice((int) (maxv+1), k, NULL, &n2) != eslOK) esl_fatal(msg);
649 if (n2 <= n) esl_fatal(msg);
650 }
651 }
652 }
653 }
654
655 static void
656 utest_delta(ESL_RANDOMNESS *rng)
657 {
658 char msg[] = "utest_delta Elias delta tests failed";
659 uint64_t code;
660 int64_t maxv;
661 int v, v2;
662 int n, n2;
663 int i;
664
665 /* Spot check against documentation's example table for Elias delta.
666 * 9 encodes as 00100001, len 8, e.g. 0x21
667 */
668 if ( esl_varint_delta( 9, &code, &n) != eslOK) esl_fatal(msg);
669 if ( code != 0x21ll || n != 8) esl_fatal(msg);
670
671 /* Check encoding of v=1..999 */
672 for (v = 1; v < 1000; v++)
673 {
674 if ( esl_varint_delta(v, &code, &n) != eslOK) esl_fatal(msg);
675 if ( esl_varint_delta_decode(code << (64-n), &v2, &n2) != eslOK) esl_fatal(msg);
676 if (n != len_delta(v)) esl_fatal(msg);
677 if (v != v2 || n != n2) esl_fatal(msg);
678 }
679
680 /* Check a bunch of random values on valid range */
681 maxv = INT_MAX;
682 for (i = 0; i < 1000; i++)
683 {
684 v = 1 + esl_rnd_Roll(rng, (int) maxv); // 1..INT_MAX
685 if ( esl_varint_delta(v, &code, &n) != eslOK) esl_fatal(msg);
686 if ( esl_varint_delta_decode(code << (64-n), &v2, &n2) != eslOK) esl_fatal(msg);
687 if (n != len_delta(v)) esl_fatal(msg);
688 if (v != v2 || n != n2) esl_fatal(msg);
689 }
690
691 /* (we didn't document or even bother to analyze maxv given b bits for Elias delta) */
692 }
693
694
695
696 static void
697 utest_google(ESL_RANDOMNESS *rng)
698 {
699 char msg[] = "utest_google Google varint tests failed";
700 uint64_t code;
701 int v, v2;
702 int n, n2;
703 int k;
704 int b;
705 int i;
706 int64_t maxv;
707
708 /* Spot check against our documentation's example table:
709 * 9, in google-2, encodes as 11101001, len 8; e.g. 0xe9
710 */
711 if ( esl_varint_google( 9, 2, &code, &n) != eslOK) esl_fatal(msg);
712 if ( code != 0xe9ll) esl_fatal(msg);
713 if ( n != 8) esl_fatal(msg);
714
715 /* Systematically check all codes k=2..10 */
716 for (k = 2; k <= 10; k++)
717 {
718 /* Check encoding of all values up to 999 */
719 for (v = 0; v < 1000; v++)
720 {
721 if ( esl_varint_google(v, k, &code, &n) != eslOK) esl_fatal(msg);
722 if ( esl_varint_google_decode(code << (64-n), k, &v2, &n2) != eslOK) esl_fatal(msg);
723 if (n != len_google(v, k)) esl_fatal(msg);
724 if (v != v2) esl_fatal(msg);
725 if (n != n2) esl_fatal(msg);
726 }
727
728 /* Check a bunch of random values on valid range
729 */
730 maxv = ESL_MIN(INT_MAX, max_google(64, k)); // this calculation is always INT_MAX but its heart is in the right place
731 for (i = 0; i < 1000; i++)
732 {
733 v = esl_rnd_Roll(rng, (int) maxv); // well, that's 0..maxv-1 anyway. getting 0..maxv, when maxv is INT_MAX, is more trouble than it's worth.
734 if ( esl_varint_google(v, k, &code, &n) != eslOK) esl_fatal(msg);
735 if ( esl_varint_google_decode(code << (64-n), k, &v2, &n2) != eslOK) esl_fatal(msg);
736 if (n != len_google(v, k)) esl_fatal(msg);
737 if (v != v2) esl_fatal(msg);
738 if (n != n2) esl_fatal(msg);
739 }
740
741 /* Check our maxv calculations, and encoding at each max
742 */
743 for (b = k; b <= 64-k; b++) // 64-k because maxv+1 needs larger code, and google codes grow in steps of k
744 {
745 maxv = max_google(b, k);
746 if (maxv <= INT_MAX) // check that we can represent maxv in an int
747 {
748 if ( esl_varint_google((int) maxv, k, &code, &n) != eslOK) esl_fatal(msg);
749 if ( esl_varint_google_decode(code << (64-n), k, &v2, &n2) != eslOK) esl_fatal(msg);
750 if (n != len_google(maxv, k)) esl_fatal(msg);
751 if (maxv != v2) esl_fatal(msg);
752 if (n != n2) esl_fatal(msg);
753 }
754 if (maxv < INT_MAX) // and does maxv+1 fit in an int - check that size indeed steps up
755 {
756 if ( esl_varint_google((int) (maxv+1), k, NULL, &n2) != eslOK) esl_fatal(msg);
757 if (n2 <= n) esl_fatal(msg);
758 }
759 }
760 }
761 }
762 #endif // eslVARINT_TESTDRIVE
763
764
765 /*****************************************************************
766 * 6. Test driver
767 *****************************************************************/
768 #ifdef eslVARINT_TESTDRIVE
769
770 #include "easel.h"
771 #include "esl_getopts.h"
772 #include "esl_random.h"
773
774 static ESL_OPTIONS options[] = {
775 /* name type default env range toggles reqs incomp help docgroup*/
776 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show brief help on version and usage", 0 },
777 { "-s", eslARG_INT, "0", NULL, NULL, NULL, NULL, NULL, "set random number seed to <n>", 0 },
778 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
779 };
780 static char usage[] = "[-options]";
781 static char banner[] = "test driver for varint module";
782
783
784 int
785 main(int argc, char **argv)
786 {
787 ESL_GETOPTS *go = esl_getopts_CreateDefaultApp(options, 0, argc, argv, banner, usage);
788 ESL_RANDOMNESS *rng = esl_randomness_Create(esl_opt_GetInteger(go, "-s"));
789
790 fprintf(stderr, "## %s\n", argv[0]);
791 fprintf(stderr, "# rng seed = %" PRIu32 "\n", esl_randomness_GetSeed(rng));
792
793 utest_expgol(rng);
794 utest_rice (rng);
795 utest_delta (rng);
796 utest_google(rng);
797
798 fprintf(stderr, "# status = ok\n");
799
800 esl_randomness_Destroy(rng);
801 esl_getopts_Destroy(go);
802 return eslOK;
803 }
804 #endif // eslVARINT_TESTDRIVE
805
806 /*****************************************************************
807 * 7. Example
808 *****************************************************************/
809 #ifdef eslVARINT_EXAMPLE
810
811 #include "esl_getopts.h"
812
813 /* `./esl_varint` or `./esl_varint --tbl` (--tbl is default)
814 * makes tables of int v | codelen | codeword, as used in documentation.
815 * Markdown table format.
816 * `./esl_varint -1 --fig1`
817 * makes xy data file of value vs. codelen, XMGRACE XY format.
818 * `./esl_varint -1 --fig2`
819 * makes xy data file of value vs. implicit probability, XMGRACE XY format.
820 *
821 * The -1 option is because when we encode runlengths, we never need
822 * to encode 0. We get shorter codes if we offset our integer
823 * runlength by -1 before encoding it.
824 */
825
826 #define CODEOPTS "--expgol,--rice,--google,--delta"
827 #define OUTOPTS "--tbl,--fig1,--fig2"
828
829 static ESL_OPTIONS options[] = {
830 /* name type default env range toggles reqs incomp help docgroup*/
831 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show help and usage", 0},
832 { "-k", eslARG_INT, "2", NULL, NULL, NULL, NULL,"--delta", "k parameter for an encoding", 0},
833 { "-L", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, "-t", "only show lengths, not code (for large -n)",0},
834 { "-n", eslARG_INT, "200", NULL, NULL, NULL, NULL, NULL, "show table for encoding of up to v=<n>", 0},
835 { "-t", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "format table for LaTeX tabular", 0},
836 { "-1", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL,"--delta", "encode v-1 (i.e. 1..n not 0..n)", 0},
837 { "--expgol", eslARG_NONE,"default",NULL, NULL, CODEOPTS, NULL, NULL, "Use exp-Golomb-k encoding", 0},
838 { "--rice", eslARG_NONE, FALSE, NULL, NULL, CODEOPTS, NULL, NULL, "Use Golomb-Rice-k encoding", 0},
839 { "--delta", eslARG_NONE, FALSE, NULL, NULL, CODEOPTS, NULL, NULL, "Use Elias delta encoding", 0},
840 { "--google", eslARG_NONE, FALSE, NULL, NULL, CODEOPTS, NULL, NULL, "Use Varint-k encoding", 0},
841 { "--tbl", eslARG_NONE,"default",NULL, NULL, OUTOPTS, NULL, NULL, "output table of ints and their codes", 0},
842 { "--fig1", eslARG_NONE, FALSE, NULL, NULL, OUTOPTS, NULL, NULL, "output XY fig data for v vs codelen", 0},
843 { "--fig2", eslARG_NONE, FALSE, NULL, NULL, OUTOPTS, NULL, NULL, "output XY fig data for v vs implicit prob", 0},
844 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
845 };
846
847
848 static char banner[] = "table and figure data for varint prefix codes";
849 static char usage[] = "[-options]";
850
851 static void
852 dump_uint64(FILE *fp, uint64_t code, int n, int fieldwidth)
853 {
854 ESL_DASSERT1(( n > 0 ));
855 ESL_DASSERT1(( fieldwidth > 0 ));
856 int i;
857
858 fprintf(fp, "%*s", fieldwidth-n, ""); // i.e. right justification of the output
859 for (i = n-1; i >= 0; i--)
860 putc( (code & (1ull<<i)) ? '1' : '0', fp); // note the 1ull, not 1; else C99 will try to do this in a 32bit int and fail.
861 }
862
863 int
864 main(int argc, char **argv)
865 {
866 ESL_GETOPTS *go = esl_getopts_CreateDefaultApp(options, 0, argc, argv, banner, usage);
867 int k = esl_opt_GetInteger(go, "-k");
868 int vmin = esl_opt_GetBoolean(go, "--delta") ? 1 : 0; // All codes except Elias delta code start with 0.
869 int vmax = esl_opt_GetInteger(go, "-n");
870 int do_offset = esl_opt_GetBoolean(go, "-1");
871 int v;
872 uint64_t code;
873 int n;
874 int do_encoding = esl_opt_GetBoolean(go, "--tbl") ? TRUE : FALSE;
875
876 for (v = vmin; v <= vmax; v++)
877 {
878 /* If we're printing the code table, we need the code (obviously); otherwise just retrieve the length.
879 * Golomb-Rice codes have limited range, and blow up a 64-bit codelen limit, and we want to see that in our plots.
880 */
881 if (esl_opt_GetBoolean(go, "--expgol")) esl_varint_expgol(v, k, do_encoding? &code : NULL, &n);
882 else if (esl_opt_GetBoolean(go, "--rice")) esl_varint_rice (v, k, do_encoding? &code : NULL, &n);
883 else if (esl_opt_GetBoolean(go, "--google")) esl_varint_google(v, k, do_encoding? &code : NULL, &n);
884 else if (esl_opt_GetBoolean(go, "--delta")) esl_varint_delta (v, do_encoding? &code : NULL, &n);
885
886 if (esl_opt_GetBoolean(go, "--tbl"))
887 {
888 printf("| %10d | %2d | ", do_offset ? v+1 : v, n);
889 dump_uint64(stdout, code, n, 30);
890 printf("\n");
891 }
892 else if (esl_opt_GetBoolean(go, "--fig1")) printf("%d %d\n", do_offset? v+1 : v, n);
893 else if (esl_opt_GetBoolean(go, "--fig2")) printf("%d %g\n", do_offset? v+1 : v, pow(2., -1. * n));
894 }
895
896 if (esl_opt_GetBoolean(go, "--fig1") || esl_opt_GetBoolean(go, "--fig2"))
897 printf("&\n"); // Termination of an XY set in XMGRACE formats
898
899 esl_getopts_Destroy(go);
900 return eslOK;
901 }
902 #endif // eslVARINT_EXAMPLE
903
904