exip  Alpha 0.5.4
 All Data Structures Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
streamRead.c
Go to the documentation of this file.
1 /*==================================================================*\
2 | EXIP - Embeddable EXI Processor in C |
3 |--------------------------------------------------------------------|
4 | This work is licensed under BSD 3-Clause License |
5 | The full license terms and conditions are located in LICENSE.txt |
6 \===================================================================*/
7 
18 #include "streamRead.h"
19 #include "ioUtil.h"
20 
21 const unsigned char BIT_MASK[] = { (char) 0x00, // 0b00000000
22  (char) 0x01, // 0b00000001
23  (char) 0x03, // 0b00000011
24  (char) 0x07, // 0b00000111
25  (char) 0x0F, // 0b00001111
26  (char) 0x1F, // 0b00011111
27  (char) 0x3F, // 0b00111111
28  (char) 0x7F, // 0b01111111
29  (char) 0xFF }; // 0b11111111
30 
31 errorCode readNextBit(EXIStream* strm, boolean* bit_val)
32 {
33  if(strm->buffer.bufContent <= strm->context.bufferIndx) // the whole buffer is parsed! read another portion
34  {
35  strm->context.bitPointer = 0;
36  strm->context.bufferIndx = 0;
37  strm->buffer.bufContent = 0;
38  if(strm->buffer.ioStrm.readWriteToStream == NULL)
41  if(strm->buffer.bufContent == 0)
43  }
44 
45  *bit_val = (strm->buffer.buf[strm->context.bufferIndx] & (1<<REVERSE_BIT_POSITION(strm->context.bitPointer))) != 0;
46 
47  moveBitPointer(strm, 1);
48  DEBUG_MSG(INFO, DEBUG_STREAM_IO, (" @%u:%u", (unsigned int) strm->context.bufferIndx, strm->context.bitPointer));
49  return EXIP_OK;
50 }
51 
52 errorCode readBits(EXIStream* strm, unsigned char n, unsigned int* bits_val)
53 {
54  unsigned int numBytesToBeRead = 1 + ((n + strm->context.bitPointer - 1) / 8);
55  unsigned int byteIndx = 1;
56  unsigned char *buf;
57 
58  if(strm->buffer.bufContent < strm->context.bufferIndx + numBytesToBeRead)
59  {
60  // The buffer end is reached: there are fewer than n bits left unparsed
61  errorCode tmp_err_code = EXIP_UNEXPECTED_ERROR;
62 
63  TRY(readEXIChunkForParsing(strm, numBytesToBeRead));
64  }
65 
66  buf = (unsigned char *) strm->buffer.buf + strm->context.bufferIndx;
67 
68  *bits_val = (buf[0] & BIT_MASK[8 - strm->context.bitPointer])<<((numBytesToBeRead-1)*8);
69 
70  while(byteIndx < numBytesToBeRead)
71  {
72  *bits_val += (unsigned int) (buf[byteIndx])<<((numBytesToBeRead-byteIndx-1)*8);
73  byteIndx++;
74  }
75 
76  *bits_val = *bits_val >> (numBytesToBeRead*8 - n - strm->context.bitPointer);
77 
78  DEBUG_MSG(INFO, DEBUG_STREAM_IO, (">> %d [0x%X] (%u bits)", *bits_val, *bits_val, n));
79 
80  n += strm->context.bitPointer;
81  strm->context.bufferIndx += n / 8;
82  strm->context.bitPointer = n % 8;
83 
84  DEBUG_MSG(INFO, DEBUG_STREAM_IO, (" @%u:%u\n", (unsigned int) strm->context.bufferIndx, strm->context.bitPointer));
85 
86  return EXIP_OK;
87 }
88