Debian Codegraph @

tests/bitwise.c

raw
1 /* Copyright (C) 2011 Vincent Penquerc'h.
2 This file is part of the Kate codec library.
3 Written by Vincent Penquerc'h.
4
5 Use, distribution and reproduction of this library is governed
6 by a BSD style source license included with this source in the
7 file 'COPYING'. Please read these terms before distributing. */
8
9
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <string.h>
13 #include "kate/kate.h"
14 #include "../src/kate_bitwise.h"
15
16 static kate_uint32_t getrnd(kate_uint32_t *rnd)
17 {
18 return *rnd=*rnd*1103515245+12345;
19 }
20
21 static void test_bitwise_size(size_t bits,kate_uint32_t start_rnd)
22 {
23 kate_pack_buffer kpb;
24 size_t data_size=bits*4; /* good margin */
25 unsigned char *data=alloca(data_size);
26 size_t n,d;
27 kate_uint32_t rnd;
28 int read;
29
30 rnd=start_rnd;
31 d=0;
32 kate_pack_writeinit(&kpb);
33 for (n=0;n<bits;) {
34 kate_uint32_t b=1+getrnd(&rnd)%32;
35 kate_uint32_t r=getrnd(&rnd);
36 if (d>=data_size) {
37 printf("Warning: cut short\n");
38 break;
39 }
40 if (b>bits-n) b=bits-n;
41 r=r&((1<<b)-1);
42 data[d++]=r;
43 kate_pack_write(&kpb,r,b);
44 n+=b;
45 }
46
47 if (kate_pack_bits(&kpb)!=bits) {
48 fprintf(stderr,"Expected %zu bits, got %ld\n",bits,kate_pack_bits(&kpb));
49 exit(1);
50 }
51
52 /* do not reset, reuse allocated buffer as is */
53 kate_pack_readinit(&kpb,kpb.buffer,kate_pack_bytes(&kpb));
54
55 d=0;
56 rnd=start_rnd;
57 for (n=0;n<bits;) {
58 kate_uint32_t b=1+getrnd(&rnd)%32;
59 kate_uint32_t r=getrnd(&rnd);
60 if (b>bits-n) b=bits-n;
61 r=r&((1<<b)-1);
62 if (d>=data_size) break;
63 read=kate_pack_read(&kpb,b);
64 if (r!=read) {
65 fprintf(stderr,"Read %d from %u bits at bit offset %zu, expected %u\n",read,b,n,r);
66 exit(1);
67 }
68 n+=b;
69 }
70
71 kate_pack_writeclear(&kpb);
72 }
73
74 int main()
75 {
76 size_t n,r;
77
78 for (n=0;n<4096;++n) {
79 for (r=0;r<16;++r) {
80 test_bitwise_size(n,r);
81 }
82 }
83 return 0;
84 }
85