blob: f877f21ef5148c8d32defa4f43feca0df99a8235 [file] [log] [blame]
Piotr Krysik9e2e8352018-02-27 12:16:25 +01001/* (C) 2009 by Harald Welte <laforge@gnumonks.org>
2 * (C) 2012 Ivan Klyuchnikov
3 * (C) 2015 by sysmocom - s.f.m.c. GmbH
4 *
5 * All Rights Reserved
6 *
7 * SPDX-License-Identifier: GPL-2.0+
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22 *
23 */
24
25/*! \addtogroup bitvec
26 * @{
27 * Osmocom bit vector abstraction utility routines.
28 *
29 * These functions assume a MSB (most significant bit) first layout of the
30 * bits, so that for instance the 5 bit number abcde (a is MSB) can be
31 * embedded into a byte sequence like in xxxxxxab cdexxxxx. The bit count
32 * starts with the MSB, so the bits in a byte are numbered (MSB) 01234567 (LSB).
33 * Note that there are other incompatible encodings, like it is used
34 * for the EGPRS RLC data block headers (there the bits are numbered from LSB
35 * to MSB).
36 *
37 * \file bitvec.c */
38
Piotr Krysikd8a57662018-03-04 19:35:00 +010039#include <stdlib.h>
Piotr Krysik9e2e8352018-02-27 12:16:25 +010040#include <errno.h>
41#include <stdint.h>
42#include <string.h>
43#include <stdio.h>
44#include <stdbool.h>
45
46#include <osmocom/core/bits.h>
47#include <osmocom/core/bitvec.h>
48
49#define BITNUM_FROM_COMP(byte, bit) ((byte*8)+bit)
50
51static inline unsigned int bytenum_from_bitnum(unsigned int bitnum)
52{
53 unsigned int bytenum = bitnum / 8;
54
55 return bytenum;
56}
57
58/* convert ZERO/ONE/L/H to a bitmask at given pos in a byte */
59static uint8_t bitval2mask(enum bit_value bit, uint8_t bitnum)
60{
61 int bitval;
62
63 switch (bit) {
64 case ZERO:
65 bitval = (0 << bitnum);
66 break;
67 case ONE:
68 bitval = (1 << bitnum);
69 break;
70 case L:
71 bitval = ((0x2b ^ (0 << bitnum)) & (1 << bitnum));
72 break;
73 case H:
74 bitval = ((0x2b ^ (1 << bitnum)) & (1 << bitnum));
75 break;
76 default:
77 return 0;
78 }
79 return bitval;
80}
81
82/*! check if the bit is 0 or 1 for a given position inside a bitvec
83 * \param[in] bv the bit vector on which to check
84 * \param[in] bitnr the bit number inside the bit vector to check
85 * \return value of the requested bit
86 */
87enum bit_value bitvec_get_bit_pos(const struct bitvec *bv, unsigned int bitnr)
88{
89 unsigned int bytenum = bytenum_from_bitnum(bitnr);
90 unsigned int bitnum = 7 - (bitnr % 8);
91 uint8_t bitval;
92
93 if (bytenum >= bv->data_len)
94 return -EINVAL;
95
96 bitval = bitval2mask(ONE, bitnum);
97
98 if (bv->data[bytenum] & bitval)
99 return ONE;
100
101 return ZERO;
102}
103
104/*! check if the bit is L or H for a given position inside a bitvec
105 * \param[in] bv the bit vector on which to check
106 * \param[in] bitnr the bit number inside the bit vector to check
107 * \return value of the requested bit
108 */
109enum bit_value bitvec_get_bit_pos_high(const struct bitvec *bv,
110 unsigned int bitnr)
111{
112 unsigned int bytenum = bytenum_from_bitnum(bitnr);
113 unsigned int bitnum = 7 - (bitnr % 8);
114 uint8_t bitval;
115
116 if (bytenum >= bv->data_len)
117 return -EINVAL;
118
119 bitval = bitval2mask(H, bitnum);
120
121 if ((bv->data[bytenum] & (1 << bitnum)) == bitval)
122 return H;
123
124 return L;
125}
126
127/*! get the Nth set bit inside the bit vector
128 * \param[in] bv the bit vector to use
129 * \param[in] n the bit number to get
130 * \returns the bit number (offset) of the Nth set bit in \a bv
131 */
132unsigned int bitvec_get_nth_set_bit(const struct bitvec *bv, unsigned int n)
133{
134 unsigned int i, k = 0;
135
136 for (i = 0; i < bv->data_len*8; i++) {
137 if (bitvec_get_bit_pos(bv, i) == ONE) {
138 k++;
139 if (k == n)
140 return i;
141 }
142 }
143
144 return 0;
145}
146
147/*! set a bit at given position in a bit vector
148 * \param[in] bv bit vector on which to operate
149 * \param[in] bitnr number of bit to be set
150 * \param[in] bit value to which the bit is to be set
151 * \returns 0 on success, negative value on error
152 */
153inline int bitvec_set_bit_pos(struct bitvec *bv, unsigned int bitnr,
154 enum bit_value bit)
155{
156 unsigned int bytenum = bytenum_from_bitnum(bitnr);
157 unsigned int bitnum = 7 - (bitnr % 8);
158 uint8_t bitval;
159
160 if (bytenum >= bv->data_len)
161 return -EINVAL;
162
163 /* first clear the bit */
164 bitval = bitval2mask(ONE, bitnum);
165 bv->data[bytenum] &= ~bitval;
166
167 /* then set it to desired value */
168 bitval = bitval2mask(bit, bitnum);
169 bv->data[bytenum] |= bitval;
170
171 return 0;
172}
173
174/*! set the next bit inside a bitvec
175 * \param[in] bv bit vector to be used
176 * \param[in] bit value of the bit to be set
177 * \returns 0 on success, negative value on error
178 */
179inline int bitvec_set_bit(struct bitvec *bv, enum bit_value bit)
180{
181 int rc;
182
183 rc = bitvec_set_bit_pos(bv, bv->cur_bit, bit);
184 if (!rc)
185 bv->cur_bit++;
186
187 return rc;
188}
189
190/*! get the next bit (low/high) inside a bitvec
191 * \return value of th next bit in the vector */
192int bitvec_get_bit_high(struct bitvec *bv)
193{
194 int rc;
195
196 rc = bitvec_get_bit_pos_high(bv, bv->cur_bit);
197 if (rc >= 0)
198 bv->cur_bit++;
199
200 return rc;
201}
202
203/*! set multiple bits (based on array of bitvals) at current pos
204 * \param[in] bv bit vector
205 * \param[in] bits array of \ref bit_value
206 * \param[in] count number of bits to set
207 * \return 0 on success; negative in case of error */
208int bitvec_set_bits(struct bitvec *bv, const enum bit_value *bits, unsigned int count)
209{
210 int i, rc;
211
212 for (i = 0; i < count; i++) {
213 rc = bitvec_set_bit(bv, bits[i]);
214 if (rc)
215 return rc;
216 }
217
218 return 0;
219}
220
221/*! set multiple bits (based on numeric value) at current pos.
222 * \param[in] bv bit vector.
223 * \param[in] v mask representing which bits needs to be set.
224 * \param[in] num_bits number of meaningful bits in the mask.
225 * \param[in] use_lh whether to interpret the bits as L/H values or as 0/1.
226 * \return 0 on success; negative in case of error. */
227int bitvec_set_u64(struct bitvec *bv, uint64_t v, uint8_t num_bits, bool use_lh)
228{
229 uint8_t i;
230
231 if (num_bits > 64)
232 return -E2BIG;
233
234 for (i = 0; i < num_bits; i++) {
235 int rc;
236 enum bit_value bit = use_lh ? L : 0;
237
238 if (v & ((uint64_t)1 << (num_bits - i - 1)))
239 bit = use_lh ? H : 1;
240
241 rc = bitvec_set_bit(bv, bit);
242 if (rc != 0)
243 return rc;
244 }
245
246 return 0;
247}
248
249/*! set multiple bits (based on numeric value) at current pos.
250 * \return 0 in case of success; negative in case of error. */
251int bitvec_set_uint(struct bitvec *bv, unsigned int ui, unsigned int num_bits)
252{
253 return bitvec_set_u64(bv, ui, num_bits, false);
254}
255
256/*! get multiple bits (num_bits) from beginning of vector (MSB side)
257 * \return 16bit signed integer retrieved from bit vector */
258int16_t bitvec_get_int16_msb(const struct bitvec *bv, unsigned int num_bits)
259{
260 if (num_bits > 15 || bv->cur_bit < num_bits)
261 return -EINVAL;
262
263 if (num_bits < 9)
264 return bv->data[0] >> (8 - num_bits);
265
266 return osmo_load16be(bv->data) >> (16 - num_bits);
267}
268
269/*! get multiple bits (based on numeric value) from current pos
270 * \return integer value retrieved from bit vector */
271int bitvec_get_uint(struct bitvec *bv, unsigned int num_bits)
272{
273 int i;
274 unsigned int ui = 0;
275
276 for (i = 0; i < num_bits; i++) {
277 int bit = bitvec_get_bit_pos(bv, bv->cur_bit);
278 if (bit < 0)
279 return bit;
280 if (bit)
281 ui |= (1 << (num_bits - i - 1));
282 bv->cur_bit++;
283 }
284
285 return ui;
286}
287
288/*! fill num_bits with \fill starting from the current position
289 * \return 0 on success; negative otherwise (out of vector boundary)
290 */
291int bitvec_fill(struct bitvec *bv, unsigned int num_bits, enum bit_value fill)
292{
293 unsigned i, stop = bv->cur_bit + num_bits;
294 for (i = bv->cur_bit; i < stop; i++)
295 if (bitvec_set_bit(bv, fill) < 0)
296 return -EINVAL;
297
298 return 0;
299}
300
301/*! pad all remaining bits up to num_bits
302 * \return 0 on success; negative otherwise */
303int bitvec_spare_padding(struct bitvec *bv, unsigned int up_to_bit)
304{
305 int n = up_to_bit - bv->cur_bit + 1;
306 if (n < 1)
307 return 0;
308
309 return bitvec_fill(bv, n, L);
310}
311
312/*! find first bit set in bit vector
313 * \return 0 on success; negative otherwise */
314int bitvec_find_bit_pos(const struct bitvec *bv, unsigned int n,
315 enum bit_value val)
316{
317 unsigned int i;
318
319 for (i = n; i < bv->data_len*8; i++) {
320 if (bitvec_get_bit_pos(bv, i) == val)
321 return i;
322 }
323
324 return -1;
325}
326
327/*! get multiple bytes from current pos
328 * Assumes MSB first encoding.
329 * \param[in] bv bit vector
330 * \param[in] bytes array
331 * \param[in] count number of bytes to copy
332 * \return 0 on success; negative otherwise
333 */
334int bitvec_get_bytes(struct bitvec *bv, uint8_t *bytes, unsigned int count)
335{
336 int byte_offs = bytenum_from_bitnum(bv->cur_bit);
337 int bit_offs = bv->cur_bit % 8;
338 uint8_t c, last_c;
339 int i;
340 uint8_t *src;
341
342 if (byte_offs + count + (bit_offs ? 1 : 0) > bv->data_len)
343 return -EINVAL;
344
345 if (bit_offs == 0) {
346 memcpy(bytes, bv->data + byte_offs, count);
347 } else {
348 src = bv->data + byte_offs;
349 last_c = *(src++);
350 for (i = count; i > 0; i--) {
351 c = *(src++);
352 *(bytes++) =
353 (last_c << bit_offs) |
354 (c >> (8 - bit_offs));
355 last_c = c;
356 }
357 }
358
359 bv->cur_bit += count * 8;
360 return 0;
361}
362
363/*! set multiple bytes at current pos
364 * Assumes MSB first encoding.
365 * \param[in] bv bit vector
366 * \param[in] bytes array
367 * \param[in] count number of bytes to copy
368 * \return 0 on success; negative otherwise
369 */
370int bitvec_set_bytes(struct bitvec *bv, const uint8_t *bytes, unsigned int count)
371{
372 int byte_offs = bytenum_from_bitnum(bv->cur_bit);
373 int bit_offs = bv->cur_bit % 8;
374 uint8_t c, last_c;
375 int i;
376 uint8_t *dst;
377
378 if (byte_offs + count + (bit_offs ? 1 : 0) > bv->data_len)
379 return -EINVAL;
380
381 if (bit_offs == 0) {
382 memcpy(bv->data + byte_offs, bytes, count);
383 } else if (count > 0) {
384 dst = bv->data + byte_offs;
385 /* Get lower bits of first dst byte */
386 last_c = *dst >> (8 - bit_offs);
387 for (i = count; i > 0; i--) {
388 c = *(bytes++);
389 *(dst++) =
390 (last_c << (8 - bit_offs)) |
391 (c >> bit_offs);
392 last_c = c;
393 }
394 /* Overwrite lower bits of N+1 dst byte */
395 *dst = (*dst & ((1 << (8 - bit_offs)) - 1)) |
396 (last_c << (8 - bit_offs));
397 }
398
399 bv->cur_bit += count * 8;
400 return 0;
401}
402
403/*! Allocate a bit vector
404 * \param[in] size Number of bits in the vector
405 * \param[in] ctx Context from which to allocate
406 * \return pointer to allocated vector; NULL in case of error /
407struct bitvec *bitvec_alloc(unsigned int size, TALLOC_CTX *ctx)
408{
409 struct bitvec *bv = talloc_zero(ctx, struct bitvec);
410 if (!bv)
411 return NULL;
412
413 bv->data = talloc_zero_array(bv, uint8_t, size);
414 if (!(bv->data)) {
415 talloc_free(bv);
416 return NULL;
417 }
418
419 bv->data_len = size;
420 bv->cur_bit = 0;
421 return bv;
422}
423
424/*! Free a bit vector (release its memory)
425 * \param[in] bit vector to free *
426void bitvec_free(struct bitvec *bv)
427{
428 talloc_free(bv->data);
429 talloc_free(bv);
430}
431*/
432/*! Export a bit vector to a buffer
433 * \param[in] bitvec (unpacked bits)
434 * \param[out] buffer for the unpacked bits
435 * \return number of bytes (= bits) copied */
436unsigned int bitvec_pack(const struct bitvec *bv, uint8_t *buffer)
437{
438 unsigned int i = 0;
439 for (i = 0; i < bv->data_len; i++)
440 buffer[i] = bv->data[i];
441
442 return i;
443}
444
445/*! Copy buffer of unpacked bits into bit vector
446 * \param[in] buffer unpacked input bits
447 * \param[out] bv unpacked bit vector
448 * \return number of bytes (= bits) copied */
449unsigned int bitvec_unpack(struct bitvec *bv, const uint8_t *buffer)
450{
451 unsigned int i = 0;
452 for (i = 0; i < bv->data_len; i++)
453 bv->data[i] = buffer[i];
454
455 return i;
456}
457
458/*! read hexadecimap string into a bit vector
459 * \param[in] src string containing hex digits
460 * \param[out] bv unpacked bit vector
461 * \return 0 in case of success; 1 in case of error
462 */
463int bitvec_unhex(struct bitvec *bv, const char *src)
464{
465 unsigned i;
466 unsigned val;
467 unsigned write_index = 0;
468 unsigned digits = bv->data_len * 2;
469
470 for (i = 0; i < digits; i++) {
471 if (sscanf(src + i, "%1x", &val) < 1) {
472 return 1;
473 }
474 bitvec_write_field(bv, &write_index, val, 4);
475 }
476 return 0;
477}
478
479/*! read part of the vector
480 * \param[in] bv The boolean vector to work on
481 * \param[in,out] read_index Where reading supposed to start in the vector
482 * \param[in] len How many bits to read from vector
483 * \returns read bits or negative value on error
484 */
485uint64_t bitvec_read_field(struct bitvec *bv, unsigned int *read_index, unsigned int len)
486{
487 unsigned int i;
488 uint64_t ui = 0;
489 bv->cur_bit = *read_index;
490
491 for (i = 0; i < len; i++) {
492 int bit = bitvec_get_bit_pos((const struct bitvec *)bv, bv->cur_bit);
493 if (bit < 0)
494 return bit;
495 if (bit)
496 ui |= ((uint64_t)1 << (len - i - 1));
497 bv->cur_bit++;
498 }
499 *read_index += len;
500 return ui;
501}
502
503/*! write into the vector
504 * \param[in] bv The boolean vector to work on
505 * \param[in,out] write_index Where writing supposed to start in the vector
506 * \param[in] len How many bits to write
507 * \returns next write index or negative value on error
508 */
509int bitvec_write_field(struct bitvec *bv, unsigned int *write_index, uint64_t val, unsigned int len)
510{
511 int rc;
512
513 bv->cur_bit = *write_index;
514
515 rc = bitvec_set_u64(bv, val, len, false);
516 if (rc != 0)
517 return rc;
518
519 *write_index += len;
520
521 return 0;
522}
523
524/*! convert enum to corresponding character
525 * \param v input value (bit)
526 * \return single character, either 0, 1, L or H */
527char bit_value_to_char(enum bit_value v)
528{
529 switch (v) {
530 case ZERO: return '0';
531 case ONE: return '1';
532 case L: return 'L';
533 case H: return 'H';
534 default: abort();
535 }
536}
537
538/*! prints bit vector to provided string
539 * It's caller's responsibility to ensure that we won't shoot him in the foot:
540 * the provided buffer should be at lest cur_bit + 1 bytes long
541 */
542void bitvec_to_string_r(const struct bitvec *bv, char *str)
543{
544 unsigned i, pos = 0;
545 char *cur = str;
546 for (i = 0; i < bv->cur_bit; i++) {
547 if (0 == i % 8)
548 *cur++ = ' ';
549 *cur++ = bit_value_to_char(bitvec_get_bit_pos(bv, i));
550 pos++;
551 }
552 *cur = 0;
553}
554
555/* we assume that x have at least 1 non-b bit */
556static inline unsigned leading_bits(uint8_t x, bool b)
557{
558 if (b) {
559 if (x < 0x80) return 0;
560 if (x < 0xC0) return 1;
561 if (x < 0xE0) return 2;
562 if (x < 0xF0) return 3;
563 if (x < 0xF8) return 4;
564 if (x < 0xFC) return 5;
565 if (x < 0xFE) return 6;
566 } else {
567 if (x > 0x7F) return 0;
568 if (x > 0x3F) return 1;
569 if (x > 0x1F) return 2;
570 if (x > 0xF) return 3;
571 if (x > 7) return 4;
572 if (x > 3) return 5;
573 if (x > 1) return 6;
574 }
575 return 7;
576}
577/*! force bit vector to all 0 and current bit to the beginnig of the vector */
578void bitvec_zero(struct bitvec *bv)
579{
580 bv->cur_bit = 0;
581 memset(bv->data, 0, bv->data_len);
582}
583
584/*! Return number (bits) of uninterrupted bit run in vector starting from the MSB
585 * \param[in] bv The boolean vector to work on
586 * \param[in] b The boolean, sequence of which is looked at from the vector start
587 * \returns Number of consecutive bits of \p b in \p bv
588 */
589unsigned bitvec_rl(const struct bitvec *bv, bool b)
590{
591 unsigned i;
592 for (i = 0; i < (bv->cur_bit % 8 ? bv->cur_bit / 8 + 1 : bv->cur_bit / 8); i++) {
593 if ( (b ? 0xFF : 0) != bv->data[i])
594 return i * 8 + leading_bits(bv->data[i], b);
595 }
596
597 return bv->cur_bit;
598}
599
600/*! Return number (bits) of uninterrupted bit run in vector
601 * starting from the current bit
602 * \param[in] bv The boolean vector to work on
603 * \param[in] b The boolean, sequence of 1's or 0's to be checked
604 * \param[in] max_bits Total Number of Uncmopresed bits
605 * \returns Number of consecutive bits of \p b in \p bv and cur_bit will
606 * \go to cur_bit + number of consecutive bit
607 */
608unsigned bitvec_rl_curbit(struct bitvec *bv, bool b, int max_bits)
609{
610 unsigned i = 0;
611 unsigned j = 8;
612 int temp_res = 0;
613 int count = 0;
614 unsigned readIndex = bv->cur_bit;
615 unsigned remaining_bits = max_bits % 8;
616 unsigned remaining_bytes = max_bits / 8;
617 unsigned byte_mask = 0xFF;
618
619 if (readIndex % 8) {
620 for (j -= (readIndex % 8) ; j > 0 ; j--) {
621 if (readIndex < max_bits && bitvec_read_field(bv, &readIndex, 1) == b)
622 temp_res++;
623 else {
624 bv->cur_bit--;
625 return temp_res;
626 }
627 }
628 }
629 for (i = (readIndex / 8);
630 i < (remaining_bits ? remaining_bytes + 1 : remaining_bytes);
631 i++, count++) {
632 if ((b ? byte_mask : 0) != bv->data[i]) {
633 bv->cur_bit = (count * 8 +
634 leading_bits(bv->data[i], b) + readIndex);
635 return count * 8 +
636 leading_bits(bv->data[i], b) + temp_res;
637 }
638 }
639 bv->cur_bit = (temp_res + (count * 8)) + readIndex;
640 if (bv->cur_bit > max_bits)
641 bv->cur_bit = max_bits;
642 return (bv->cur_bit - readIndex + temp_res);
643}
644
645/*! Shifts bitvec to the left, n MSB bits lost */
646void bitvec_shiftl(struct bitvec *bv, unsigned n)
647{
648 if (0 == n)
649 return;
650 if (n >= bv->cur_bit) {
651 bitvec_zero(bv);
652 return;
653 }
654
655 memmove(bv->data, bv->data + n / 8, bv->data_len - n / 8);
656
657 uint8_t tmp[2];
658 unsigned i;
659 for (i = 0; i < bv->data_len - 2; i++) {
660 uint16_t t = osmo_load16be(bv->data + i);
661 osmo_store16be(t << (n % 8), &tmp);
662 bv->data[i] = tmp[0];
663 }
664
665 bv->data[bv->data_len - 1] <<= (n % 8);
666 bv->cur_bit -= n;
667}
668
669/*! Add given array to bitvec
670 * \param[in,out] bv bit vector to work with
671 * \param[in] array elements to be added
672 * \param[in] array_len length of array
673 * \param[in] dry_run indicates whether to return number of bits required
674 * instead of adding anything to bv for real
675 * \param[in] num_bits number of bits to consider in each element of array
676 * \returns number of bits necessary to add array elements if dry_run is true,
677 * 0 otherwise (only in this case bv is actually changed)
678 *
679 * N. B: no length checks are performed on bv - it's caller's job to ensure
680 * enough space is available - for example by calling with dry_run = true first.
681 *
682 * Useful for common pattern in CSN.1 spec which looks like:
683 * { 1 < XXX : bit (num_bits) > } ** 0
684 * which means repeat any times (between 0 and infinity),
685 * start each repetition with 1, mark end of repetitions with 0 bit
686 * see app. note in 3GPP TS 24.007 ยง B.2.1 Rule A2
687 */
688unsigned int bitvec_add_array(struct bitvec *bv, const uint32_t *array,
689 unsigned int array_len, bool dry_run,
690 unsigned int num_bits)
691{
692 unsigned i, bits = 1; /* account for stop bit */
693 for (i = 0; i < array_len; i++) {
694 if (dry_run) {
695 bits += (1 + num_bits);
696 } else {
697 bitvec_set_bit(bv, 1);
698 bitvec_set_uint(bv, array[i], num_bits);
699 }
700 }
701
702 if (dry_run)
703 return bits;
704
705 bitvec_set_bit(bv, 0); /* stop bit - end of the sequence */
706 return 0;
707}
708
709/*! @} */