f213ed6d4d78df843b3e9f32748f9ae3d84b4f65
[SXSI/TextCollection.git] / swcsa / utils / basics.c
1
2 // Basics
3
4 // #include "basics.h" included later to avoid macro recursion for malloc
5 #include <sys/types.h>
6 #include <stdio.h>
7 #include <stdlib.h>
8
9                 // Memory management
10         
11         void *Malloc (int n)
12         
13            { void *p;
14              if (n == 0) return NULL;
15              p = (void*) malloc (n);
16              if (p == NULL)
17                 { fprintf (stderr,"Could not allocate %i bytes\n",n);
18                   exit(1);
19                 }
20              return p;
21            }
22         
23         void Free (void *p)
24         
25            { if (p) free (p); 
26            }
27         
28         void *Realloc (void *p, int n)
29         
30            { if (p == NULL) return Malloc (n);
31              if (n == 0) { Free(p); return NULL; }
32              p = (void*) realloc (p,n);
33              if (p == NULL)
34                 { fprintf (stderr,"Could not allocate %i bytes\n",n);
35                   exit(1);
36                 }
37              return p;
38            }
39
40 #include "basics.h"
41
42         // bits needed to represent a number between 0 and n
43
44 uint bits (uint n)
45
46    { uint b = 0;
47      while (n)
48         { b++; n >>= 1; }
49      return b;
50    }
51
52         // returns e[p..p+len-1], assuming len <= W
53
54 uint bitread (uint *e, uint p, uint len)
55
56    { uint answ;
57      e += p/W; p %= W;
58      answ = *e >> p;
59      if (len == W)
60           { if (p) answ |= (*(e+1)) << (W-p);
61           }
62      else { if (p+len > W) answ |= (*(e+1)) << (W-p);
63             answ &= (1<<len)-1;
64           }
65      return answ;
66    }
67
68
69         // writes e[p..p+len-1] = s, len <= W
70
71 void bitwrite (register uint *e, register uint p, 
72                register uint len, register uint s)
73
74    { e += p/W; p %= W;
75      if (len == W)
76           { *e |= (*e & ((1<<p)-1)) | (s << p);
77             if (!p) return;
78             e++;
79             *e = (*e & ~((1<<p)-1)) | (s >> (W-p));
80           }
81      else { if (p+len <= W)
82                { *e = (*e & ~(((1<<len)-1)<<p)) | (s << p);
83                  return;
84                }
85             *e = (*e & ((1<<p)-1)) | (s << p);
86             e++; len -= W-p;
87             *e = (*e & ~((1<<len)-1)) | (s >> (W-p));
88           }
89    }
90         // writes e[p..p+len-1] = 0
91
92 void bitzero (register uint *e, register uint p, 
93                register uint len)
94
95    { e += p/W; p %= W;
96      if (p+len >= W)
97         { *e &= ~((1<<p)-1);
98           len -= p;
99           e++; p = 0;
100         }
101      while (len >= W)
102         { *e++ = 0;
103           len -= W;
104         }
105      if (len > 0)
106         *e &= ~(((1<<len)-1)<<p);
107    }