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