Return interpretation of next bits as a signed exponential-Golomb code.

        Advances position to after the read code.

        Raises ReadError if the end of the bitstring is encountered while
        reading the code.
968011
def _readse(self, pos):
        
        codenum, pos = self._readue(pos)
        m = (codenum + 1) // 2
        if not codenum % 2:
            return -m, pos
        else:
            return m, pos
1315589
def _readbin(self, length, start):
        """"""
        if not length:
            return ''
        # Get the byte slice containing our bit slice
        startbyte, startoffset = divmod(start + self._offset, 8)
        endbyte = (start + self._offset + length - 1) // 8
        b = self._datastore.getbyteslice(startbyte, endbyte + 1)
        # Convert to a string of '0' and '1's (via a hex string an and int!)
        try:
            c = "{:0{}b}".format(int(binascii.hexlify(b), 16), 8*len(b))
        except TypeError:
            # Hack to get Python 2.6 working
            c = "{0:0{1}b}".format(int(binascii.hexlify(str(b)), 16), 8*len(b))
        # Finally chop off any extra bits.
        return c[startoffset:startoffset + length]
783311
protected void readForward(Decoder decoder) throws IOException {
    short numberOfTokens = decoder.in.readVarShort(3);
    if (0 < numberOfTokens) {
      long seek = decoder.in.peekLongCoord(decoder.node.getCursorCount());
      TrieNode toNode = decoder.node.traverse(seek + decoder.node.getCursorIndex());
      while (toNode.getDepth() > decoder.node.getDepth() + numberOfTokens) toNode = toNode.getParent();
      Interval interval = decoder.node.intervalTo(toNode);
      String str = toNode.getString(decoder.node);
      Bits bits = interval.toBits();
      if (verbose != null) {
        verbose.println(String.format("Read %s forward from %s to %s = %s", numberOfTokens, decoder.node.getDebugString(), toNode.getDebugString(), bits));
      }
      decoder.in.expect(bits);
      decoder.out.append(str);
      decoder.node = toNode;
    }
    else {
      assert (0 == decoder.node.index);
    }
  }
207756
def decode(self, offset):
        
        new_offset = offset + 1
        (ctrl_byte,) = struct.unpack(b'!B', self._buffer[offset:new_offset])
        type_num = ctrl_byte >> 5
        # Extended type
        if not type_num:
            (type_num, new_offset) = self._read_extended(new_offset)

        (size, new_offset) = self._size_from_ctrl_byte(
            ctrl_byte, new_offset, type_num)
        return self._type_decoder[type_num](self, size, new_offset)
1075452
def readbits(self, bits):
        
        
        if bits == 0:
            return 0
        
        # fast byte-aligned path
        if bits % 8 == 0 and self._bits_pending == 0:
            return self._read_bytes_aligned(bits // 8)
        
        out = 0
        masks = self._masks
        
        def transfer_bits(x, y, n, t):
            """
            transfers t bits from the top of y_n to the bottom of x.
            then returns x and the remaining bits in y
            """
            if n == t:
                # taking all
                return (x << t) | y, 0
            
            mask = masks[t]           # (1 << t) - 1
            remainmask = masks[n - t] # (1 << n - t) - 1
            taken = ((y >> n - t) & mask)
            return (x << t) | taken, y & remainmask
        
        while bits > 0:
            if self._bits_pending > 0:
                assert self._partial_byte is not None
                take = min(self._bits_pending, bits)
                out, self._partial_byte = transfer_bits(out, self._partial_byte, self._bits_pending, take)
                
                if take == self._bits_pending:
                    # we took them all
                    self._partial_byte = None
                self._bits_pending -= take
                bits -= take
                continue
            
            r = self.f.read(1)
            if r == b'':
                raise EOFError
            self._partial_byte = ord(r)
            self._bits_pending = 8
        
        return out
1027307
def bitpos(self, key, bit, start=None, end=None):
        
        if bit not in (1, 0):
            raise ValueError("bit argument must be either 1 or 0")
        bytes_range = []
        if start is not None:
            bytes_range.append(start)
        if end is not None:
            if start is None:
                bytes_range = [0, end]
            else:
                bytes_range.append(end)
        return self.execute(b'BITPOS', key, bit, *bytes_range)
356241
def _find_read_pos(self) -> Optional[int]:
        
        if self._read_bytes is not None and (
            self._read_buffer_size >= self._read_bytes
            or (self._read_partial and self._read_buffer_size > 0)
        ):
            num_bytes = min(self._read_bytes, self._read_buffer_size)
            return num_bytes
        elif self._read_delimiter is not None:
            # Multi-byte delimiters (e.g. '\r\n') may straddle two
            # chunks in the read buffer, so we can't easily find them
            # without collapsing the buffer.  However, since protocols
            # using delimited reads (as opposed to reads of a known
            # length) tend to be "line" oriented, the delimiter is likely
            # to be in the first few chunks.  Merge the buffer gradually
            # since large merges are relatively expensive and get undone in
            # _consume().
            if self._read_buffer:
                loc = self._read_buffer.find(
                    self._read_delimiter, self._read_buffer_pos
                )
                if loc != -1:
                    loc -= self._read_buffer_pos
                    delimiter_len = len(self._read_delimiter)
                    self._check_max_bytes(self._read_delimiter, loc + delimiter_len)
                    return loc + delimiter_len
                self._check_max_bytes(self._read_delimiter, self._read_buffer_size)
        elif self._read_regex is not None:
            if self._read_buffer:
                m = self._read_regex.search(self._read_buffer, self._read_buffer_pos)
                if m is not None:
                    loc = m.end() - self._read_buffer_pos
                    self._check_max_bytes(self._read_regex, loc)
                    return loc
                self._check_max_bytes(self._read_regex, self._read_buffer_size)
        return None
1312512
def _parse_next(self):
        ''''''
        if self.data_len - self.offset < 3:
            return None
            
        hdr = self.data[self.offset:self.offset+3]
        skip_bytes = 0
        skip_type = None
        # skip over bad messages
        while (ord(hdr[0]) != self.HEAD1 or ord(hdr[1]) != self.HEAD2 or ord(hdr[2]) not in self.formats):
            if skip_type is None:
                skip_type = (ord(hdr[0]), ord(hdr[1]), ord(hdr[2]))
                skip_start = self.offset
            skip_bytes += 1
            self.offset += 1
            if self.data_len - self.offset < 3:
                return None
            hdr = self.data[self.offset:self.offset+3]
        msg_type = ord(hdr[2])
        if skip_bytes != 0:
            if self.remaining < 528:
                return None
            print("Skipped %u bad bytes in log at offset %u, type=%s" % (skip_bytes, skip_start, skip_type))
            self.remaining -= skip_bytes

        self.offset += 3
        self.remaining -= 3

        if not msg_type in self.formats:
            if self.verbose:
                print("unknown message type %02x" % msg_type)
            raise Exception("Unknown message type %02x" % msg_type)
        fmt = self.formats[msg_type]
        if self.remaining < fmt.len-3:
            # out of data - can often happen half way through a message
            if self.verbose:
                print("out of data")
            return None
        body = self.data[self.offset:self.offset+(fmt.len-3)]
        elements = None
        try:
            elements = list(struct.unpack(fmt.msg_struct, body))
        except Exception:
            if self.remaining < 528:
                # we can have garbage at the end of an APM2 log
                return None
            # we should also cope with other corruption; logs
            # transfered via DataFlash_MAVLink may have blocks of 0s
            # in them, for example
            print("Failed to parse %s/%s with len %u (remaining %u)" % (fmt.name, fmt.msg_struct, len(body), self.remaining))
        if elements is None:
            return self._parse_next()
        name = null_term(fmt.name)
        if name == 'FMT':
            # add to formats
            # name, len, format, headings
            self.formats[elements[0]] = DFFormat(elements[0],
                                                 null_term(elements[2]), elements[1],
                                                 null_term(elements[3]), null_term(elements[4]))

        self.offset += fmt.len-3
        self.remaining -= fmt.len-3
        m = DFMessage(fmt, elements, True)
        self._add_msg(m)

        self.percent = 100.0 * (self.offset / float(self.data_len))
        
        return m
816042
def _readue(self, pos):
        
        oldpos = pos
        try:
            while not self[pos]:
                pos += 1
        except IndexError:
            raise ReadError("Read off end of bitstring trying to read code.")
        leadingzeros = pos - oldpos
        codenum = (1 << leadingzeros) - 1
        if leadingzeros > 0:
            if pos + leadingzeros + 1 > self.len:
                raise ReadError("Read off end of bitstring trying to read code.")
            codenum += self._readuint(leadingzeros, pos + 1)
            pos += leadingzeros + 1
        else:
            assert codenum == 0
            pos += 1
        return codenum, pos
470920
def rol(self, bits, start=None, end=None):
        
        if not self.len:
            raise Error("Cannot rotate an empty bitstring.")
        if bits < 0:
            raise ValueError("Cannot rotate left by negative amount.")
        start, end = self._validate_slice(start, end)
        bits %= (end - start)
        if not bits:
            return
        lhs = self._slice(start, start + bits)
        self._delete(bits, start)
        self._insert(lhs, end - bits)
332138
def peek(self, n):
        
        pos = self._read_pos
        end = pos + n
        return self.raw[pos:end]
996147
function next () {
      let doNext = true
      let decoded = false

      const decodeCb = (err, msg) => {
        decoded = true
        if (err) {
          p.end(err)
          doNext = false
        } else {
          p.push(msg)
          if (!doNext) {
            next()
          }
        }
      }

      while (doNext) {
        decoded = false
        _decodeFromReader(reader, opts, decodeCb)
        if (!decoded) {
          doNext = false
        }
      }
    }
586154
function (n) { /* Read n bytes off the big end of number */
			if (bits - n < 0) { /* Not enough bits */
				throw {
					name: 'RangeError',
					message: 'Not enough bits left to read '+n+' bits!'
				};
			}
			/* Extract our value. We use maths rather than bitwise operations because every number is a floating point in javascript */
			var value = Math.floor(number / Math.pow(2, bits - n)) % Math.pow(2, n);
			/* Move the bit we start from along */
			bits -= n;

			return value;
		}
428965
public int getNextCode() {
        // Attempt to get the next code. The exception is caught to make
        // this robust to cases wherein the EndOfInformation code has been
        // omitted from a strip. Examples of such cases have been observed
        // in practice.
        try {
            nextData = (nextData << 8) | (data[bytePointer++] & 0xff);
            nextBits += 8;
            
            if (nextBits < bitsToGet) {
                nextData = (nextData << 8) | (data[bytePointer++] & 0xff);
                nextBits += 8;
            }
            
            int code =
            (nextData >> (nextBits - bitsToGet)) & andTable[bitsToGet-9];
            nextBits -= bitsToGet;
            
            return code;
        } catch(ArrayIndexOutOfBoundsException e) {
            // Strip not terminated as expected: return EndOfInformation code.
            return 257;
        }
    }
749264
def next(self):
        
        try:
            res, excp = self._stride_buffer.next()
        except (StopIteration, AttributeError):
            try:
                self._stride_buffer = izip(*self._repeat_buffer.next())
            except (StopIteration, AttributeError):
                self._rebuffer()
                self._stride_buffer = izip(*self._repeat_buffer.next())
            res, excp = self._stride_buffer.next()
        if excp:
            raise res
        else:
            return res
391884
def read_instruction(fio, start_pos):
    
    op = fio.read(1)

    if not op:
        return None

    op = ord(op)

    ins = opcode_table[op]
    operands = ins['operands']
    name = ins['mnemonic']

    final_operands = []
    # Most opcodes have simple operands.
    if operands:
        for fmt, type_ in operands:
            final_operands.append(
                Operand(
                    type_,
                    fmt.value.unpack(fio.read(fmt.value.size))[0]
                )
            )
    # Special case for lookupswitch.
    elif op == 0xAB:
        # Get rid of the alignment padding.
        padding = 4 - (start_pos + 1) % 4
        padding = padding if padding != 4 else 0
        fio.read(padding)

        # Default branch address and branch count.
        default, npairs = unpack('>ii', fio.read(8))

        pairs = {}
        for _ in repeat(None, npairs):
            match, offset = unpack('>ii', fio.read(8))
            pairs[match] = offset

        final_operands.append(pairs)
        final_operands.append(Operand(OperandTypes.BRANCH, default))
    # Special case for tableswitch
    elif op == 0xAA:
        # Get rid of the alignment padding.
        padding = 4 - (start_pos + 1) % 4
        padding = padding if padding != 4 else 0
        fio.read(padding)

        default, low, high = unpack('>iii', fio.read(12))
        final_operands.append(Operand(OperandTypes.BRANCH, default))
        final_operands.append(Operand(OperandTypes.LITERAL, low))
        final_operands.append(Operand(OperandTypes.LITERAL, high))

        for _ in repeat(None, high - low + 1):
            offset = unpack('>i', fio.read(4))[0]
            final_operands.append(Operand(OperandTypes.BRANCH, offset))
    # Special case for the wide prefix
    elif op == 0xC4:
        real_op = unpack('>B', fio.read(1))[0]
        ins = opcode_table[real_op]
        name = ins['mnemonic']

        final_operands.append(Operand(
            OperandTypes.LOCAL_INDEX,
            unpack('>H', fio.read(2))[0]
        ))
        # Further special case for iinc.
        if real_op == 0x84:
            final_operands.append(Operand(
                OperandTypes.LITERAL,
                unpack('>H', fio.read(2))[0]
            ))

    return Instruction(name, op, final_operands, start_pos)
622939
public int nextBit(int x) {
        Assert.check(currentState != BitsState.UNKNOWN);
        int windex = x >>> wordshift;
        if (windex >= bits.length) {
            return -1;
        }
        int word = bits[windex] & ~((1 << (x & wordmask))-1);
        while (true) {
            if (word != 0) {
                return (windex << wordshift) + trailingZeroBits(word);
            }
            windex++;
            if (windex >= bits.length) {
                return -1;
            }
            word = bits[windex];
        }
    }