repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
sequence
docstring
stringlengths
3
17.3k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
scott-griffiths/bitstring
bitstring.py
ConstByteStore._appendstore
def _appendstore(self, store): """Join another store on to the end of this one.""" if not store.bitlength: return # Set new array offset to the number of bits in the final byte of current array. store = offsetcopy(store, (self.offset + self.bitlength) % 8) if store.offset: # first do the byte with the join. joinval = (self._rawarray.pop() & (255 ^ (255 >> store.offset)) | (store.getbyte(0) & (255 >> store.offset))) self._rawarray.append(joinval) self._rawarray.extend(store._rawarray[1:]) else: self._rawarray.extend(store._rawarray) self.bitlength += store.bitlength
python
def _appendstore(self, store): """Join another store on to the end of this one.""" if not store.bitlength: return # Set new array offset to the number of bits in the final byte of current array. store = offsetcopy(store, (self.offset + self.bitlength) % 8) if store.offset: # first do the byte with the join. joinval = (self._rawarray.pop() & (255 ^ (255 >> store.offset)) | (store.getbyte(0) & (255 >> store.offset))) self._rawarray.append(joinval) self._rawarray.extend(store._rawarray[1:]) else: self._rawarray.extend(store._rawarray) self.bitlength += store.bitlength
[ "def", "_appendstore", "(", "self", ",", "store", ")", ":", "if", "not", "store", ".", "bitlength", ":", "return", "# Set new array offset to the number of bits in the final byte of current array.", "store", "=", "offsetcopy", "(", "store", ",", "(", "self", ".", "offset", "+", "self", ".", "bitlength", ")", "%", "8", ")", "if", "store", ".", "offset", ":", "# first do the byte with the join.", "joinval", "=", "(", "self", ".", "_rawarray", ".", "pop", "(", ")", "&", "(", "255", "^", "(", "255", ">>", "store", ".", "offset", ")", ")", "|", "(", "store", ".", "getbyte", "(", "0", ")", "&", "(", "255", ">>", "store", ".", "offset", ")", ")", ")", "self", ".", "_rawarray", ".", "append", "(", "joinval", ")", "self", ".", "_rawarray", ".", "extend", "(", "store", ".", "_rawarray", "[", "1", ":", "]", ")", "else", ":", "self", ".", "_rawarray", ".", "extend", "(", "store", ".", "_rawarray", ")", "self", ".", "bitlength", "+=", "store", ".", "bitlength" ]
Join another store on to the end of this one.
[ "Join", "another", "store", "on", "to", "the", "end", "of", "this", "one", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L173-L187
train
scott-griffiths/bitstring
bitstring.py
ConstByteStore._prependstore
def _prependstore(self, store): """Join another store on to the start of this one.""" if not store.bitlength: return # Set the offset of copy of store so that it's final byte # ends in a position that matches the offset of self, # then join self on to the end of it. store = offsetcopy(store, (self.offset - store.bitlength) % 8) assert (store.offset + store.bitlength) % 8 == self.offset % 8 bit_offset = self.offset % 8 if bit_offset: # first do the byte with the join. store.setbyte(-1, (store.getbyte(-1) & (255 ^ (255 >> bit_offset)) | \ (self._rawarray[self.byteoffset] & (255 >> bit_offset)))) store._rawarray.extend(self._rawarray[self.byteoffset + 1: self.byteoffset + self.bytelength]) else: store._rawarray.extend(self._rawarray[self.byteoffset: self.byteoffset + self.bytelength]) self._rawarray = store._rawarray self.offset = store.offset self.bitlength += store.bitlength
python
def _prependstore(self, store): """Join another store on to the start of this one.""" if not store.bitlength: return # Set the offset of copy of store so that it's final byte # ends in a position that matches the offset of self, # then join self on to the end of it. store = offsetcopy(store, (self.offset - store.bitlength) % 8) assert (store.offset + store.bitlength) % 8 == self.offset % 8 bit_offset = self.offset % 8 if bit_offset: # first do the byte with the join. store.setbyte(-1, (store.getbyte(-1) & (255 ^ (255 >> bit_offset)) | \ (self._rawarray[self.byteoffset] & (255 >> bit_offset)))) store._rawarray.extend(self._rawarray[self.byteoffset + 1: self.byteoffset + self.bytelength]) else: store._rawarray.extend(self._rawarray[self.byteoffset: self.byteoffset + self.bytelength]) self._rawarray = store._rawarray self.offset = store.offset self.bitlength += store.bitlength
[ "def", "_prependstore", "(", "self", ",", "store", ")", ":", "if", "not", "store", ".", "bitlength", ":", "return", "# Set the offset of copy of store so that it's final byte", "# ends in a position that matches the offset of self,", "# then join self on to the end of it.", "store", "=", "offsetcopy", "(", "store", ",", "(", "self", ".", "offset", "-", "store", ".", "bitlength", ")", "%", "8", ")", "assert", "(", "store", ".", "offset", "+", "store", ".", "bitlength", ")", "%", "8", "==", "self", ".", "offset", "%", "8", "bit_offset", "=", "self", ".", "offset", "%", "8", "if", "bit_offset", ":", "# first do the byte with the join.", "store", ".", "setbyte", "(", "-", "1", ",", "(", "store", ".", "getbyte", "(", "-", "1", ")", "&", "(", "255", "^", "(", "255", ">>", "bit_offset", ")", ")", "|", "(", "self", ".", "_rawarray", "[", "self", ".", "byteoffset", "]", "&", "(", "255", ">>", "bit_offset", ")", ")", ")", ")", "store", ".", "_rawarray", ".", "extend", "(", "self", ".", "_rawarray", "[", "self", ".", "byteoffset", "+", "1", ":", "self", ".", "byteoffset", "+", "self", ".", "bytelength", "]", ")", "else", ":", "store", ".", "_rawarray", ".", "extend", "(", "self", ".", "_rawarray", "[", "self", ".", "byteoffset", ":", "self", ".", "byteoffset", "+", "self", ".", "bytelength", "]", ")", "self", ".", "_rawarray", "=", "store", ".", "_rawarray", "self", ".", "offset", "=", "store", ".", "offset", "self", ".", "bitlength", "+=", "store", ".", "bitlength" ]
Join another store on to the start of this one.
[ "Join", "another", "store", "on", "to", "the", "start", "of", "this", "one", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L189-L208
train
scott-griffiths/bitstring
bitstring.py
Bits._assertsanity
def _assertsanity(self): """Check internal self consistency as a debugging aid.""" assert self.len >= 0 assert 0 <= self._offset, "offset={0}".format(self._offset) assert (self.len + self._offset + 7) // 8 == self._datastore.bytelength + self._datastore.byteoffset return True
python
def _assertsanity(self): """Check internal self consistency as a debugging aid.""" assert self.len >= 0 assert 0 <= self._offset, "offset={0}".format(self._offset) assert (self.len + self._offset + 7) // 8 == self._datastore.bytelength + self._datastore.byteoffset return True
[ "def", "_assertsanity", "(", "self", ")", ":", "assert", "self", ".", "len", ">=", "0", "assert", "0", "<=", "self", ".", "_offset", ",", "\"offset={0}\"", ".", "format", "(", "self", ".", "_offset", ")", "assert", "(", "self", ".", "len", "+", "self", ".", "_offset", "+", "7", ")", "//", "8", "==", "self", ".", "_datastore", ".", "bytelength", "+", "self", ".", "_datastore", ".", "byteoffset", "return", "True" ]
Check internal self consistency as a debugging aid.
[ "Check", "internal", "self", "consistency", "as", "a", "debugging", "aid", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1195-L1200
train
scott-griffiths/bitstring
bitstring.py
Bits._setauto
def _setauto(self, s, length, offset): """Set bitstring from a bitstring, file, bool, integer, array, iterable or string.""" # As s can be so many different things it's important to do the checks # in the correct order, as some types are also other allowed types. # So basestring must be checked before Iterable # and bytes/bytearray before Iterable but after basestring! if isinstance(s, Bits): if length is None: length = s.len - offset self._setbytes_unsafe(s._datastore.rawbytes, length, s._offset + offset) return if isinstance(s, file): if offset is None: offset = 0 if length is None: length = os.path.getsize(s.name) * 8 - offset byteoffset, offset = divmod(offset, 8) bytelength = (length + byteoffset * 8 + offset + 7) // 8 - byteoffset m = MmapByteArray(s, bytelength, byteoffset) if length + byteoffset * 8 + offset > m.filelength * 8: raise CreationError("File is not long enough for specified " "length and offset.") self._datastore = ConstByteStore(m, length, offset) return if length is not None: raise CreationError("The length keyword isn't applicable to this initialiser.") if offset: raise CreationError("The offset keyword isn't applicable to this initialiser.") if isinstance(s, basestring): bs = self._converttobitstring(s) assert bs._offset == 0 self._setbytes_unsafe(bs._datastore.rawbytes, bs.length, 0) return if isinstance(s, (bytes, bytearray)): self._setbytes_unsafe(bytearray(s), len(s) * 8, 0) return if isinstance(s, array.array): b = s.tostring() self._setbytes_unsafe(bytearray(b), len(b) * 8, 0) return if isinstance(s, numbers.Integral): # Initialise with s zero bits. if s < 0: msg = "Can't create bitstring of negative length {0}." raise CreationError(msg, s) data = bytearray((s + 7) // 8) self._datastore = ByteStore(data, s, 0) return if isinstance(s, collections.Iterable): # Evaluate each item as True or False and set bits to 1 or 0. self._setbin_unsafe(''.join(str(int(bool(x))) for x in s)) return raise TypeError("Cannot initialise bitstring from {0}.".format(type(s)))
python
def _setauto(self, s, length, offset): """Set bitstring from a bitstring, file, bool, integer, array, iterable or string.""" # As s can be so many different things it's important to do the checks # in the correct order, as some types are also other allowed types. # So basestring must be checked before Iterable # and bytes/bytearray before Iterable but after basestring! if isinstance(s, Bits): if length is None: length = s.len - offset self._setbytes_unsafe(s._datastore.rawbytes, length, s._offset + offset) return if isinstance(s, file): if offset is None: offset = 0 if length is None: length = os.path.getsize(s.name) * 8 - offset byteoffset, offset = divmod(offset, 8) bytelength = (length + byteoffset * 8 + offset + 7) // 8 - byteoffset m = MmapByteArray(s, bytelength, byteoffset) if length + byteoffset * 8 + offset > m.filelength * 8: raise CreationError("File is not long enough for specified " "length and offset.") self._datastore = ConstByteStore(m, length, offset) return if length is not None: raise CreationError("The length keyword isn't applicable to this initialiser.") if offset: raise CreationError("The offset keyword isn't applicable to this initialiser.") if isinstance(s, basestring): bs = self._converttobitstring(s) assert bs._offset == 0 self._setbytes_unsafe(bs._datastore.rawbytes, bs.length, 0) return if isinstance(s, (bytes, bytearray)): self._setbytes_unsafe(bytearray(s), len(s) * 8, 0) return if isinstance(s, array.array): b = s.tostring() self._setbytes_unsafe(bytearray(b), len(b) * 8, 0) return if isinstance(s, numbers.Integral): # Initialise with s zero bits. if s < 0: msg = "Can't create bitstring of negative length {0}." raise CreationError(msg, s) data = bytearray((s + 7) // 8) self._datastore = ByteStore(data, s, 0) return if isinstance(s, collections.Iterable): # Evaluate each item as True or False and set bits to 1 or 0. self._setbin_unsafe(''.join(str(int(bool(x))) for x in s)) return raise TypeError("Cannot initialise bitstring from {0}.".format(type(s)))
[ "def", "_setauto", "(", "self", ",", "s", ",", "length", ",", "offset", ")", ":", "# As s can be so many different things it's important to do the checks", "# in the correct order, as some types are also other allowed types.", "# So basestring must be checked before Iterable", "# and bytes/bytearray before Iterable but after basestring!", "if", "isinstance", "(", "s", ",", "Bits", ")", ":", "if", "length", "is", "None", ":", "length", "=", "s", ".", "len", "-", "offset", "self", ".", "_setbytes_unsafe", "(", "s", ".", "_datastore", ".", "rawbytes", ",", "length", ",", "s", ".", "_offset", "+", "offset", ")", "return", "if", "isinstance", "(", "s", ",", "file", ")", ":", "if", "offset", "is", "None", ":", "offset", "=", "0", "if", "length", "is", "None", ":", "length", "=", "os", ".", "path", ".", "getsize", "(", "s", ".", "name", ")", "*", "8", "-", "offset", "byteoffset", ",", "offset", "=", "divmod", "(", "offset", ",", "8", ")", "bytelength", "=", "(", "length", "+", "byteoffset", "*", "8", "+", "offset", "+", "7", ")", "//", "8", "-", "byteoffset", "m", "=", "MmapByteArray", "(", "s", ",", "bytelength", ",", "byteoffset", ")", "if", "length", "+", "byteoffset", "*", "8", "+", "offset", ">", "m", ".", "filelength", "*", "8", ":", "raise", "CreationError", "(", "\"File is not long enough for specified \"", "\"length and offset.\"", ")", "self", ".", "_datastore", "=", "ConstByteStore", "(", "m", ",", "length", ",", "offset", ")", "return", "if", "length", "is", "not", "None", ":", "raise", "CreationError", "(", "\"The length keyword isn't applicable to this initialiser.\"", ")", "if", "offset", ":", "raise", "CreationError", "(", "\"The offset keyword isn't applicable to this initialiser.\"", ")", "if", "isinstance", "(", "s", ",", "basestring", ")", ":", "bs", "=", "self", ".", "_converttobitstring", "(", "s", ")", "assert", "bs", ".", "_offset", "==", "0", "self", ".", "_setbytes_unsafe", "(", "bs", ".", "_datastore", ".", "rawbytes", ",", "bs", ".", "length", ",", "0", ")", "return", "if", "isinstance", "(", "s", ",", "(", "bytes", ",", "bytearray", ")", ")", ":", "self", ".", "_setbytes_unsafe", "(", "bytearray", "(", "s", ")", ",", "len", "(", "s", ")", "*", "8", ",", "0", ")", "return", "if", "isinstance", "(", "s", ",", "array", ".", "array", ")", ":", "b", "=", "s", ".", "tostring", "(", ")", "self", ".", "_setbytes_unsafe", "(", "bytearray", "(", "b", ")", ",", "len", "(", "b", ")", "*", "8", ",", "0", ")", "return", "if", "isinstance", "(", "s", ",", "numbers", ".", "Integral", ")", ":", "# Initialise with s zero bits.", "if", "s", "<", "0", ":", "msg", "=", "\"Can't create bitstring of negative length {0}.\"", "raise", "CreationError", "(", "msg", ",", "s", ")", "data", "=", "bytearray", "(", "(", "s", "+", "7", ")", "//", "8", ")", "self", ".", "_datastore", "=", "ByteStore", "(", "data", ",", "s", ",", "0", ")", "return", "if", "isinstance", "(", "s", ",", "collections", ".", "Iterable", ")", ":", "# Evaluate each item as True or False and set bits to 1 or 0.", "self", ".", "_setbin_unsafe", "(", "''", ".", "join", "(", "str", "(", "int", "(", "bool", "(", "x", ")", ")", ")", "for", "x", "in", "s", ")", ")", "return", "raise", "TypeError", "(", "\"Cannot initialise bitstring from {0}.\"", ".", "format", "(", "type", "(", "s", ")", ")", ")" ]
Set bitstring from a bitstring, file, bool, integer, array, iterable or string.
[ "Set", "bitstring", "from", "a", "bitstring", "file", "bool", "integer", "array", "iterable", "or", "string", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1245-L1297
train
scott-griffiths/bitstring
bitstring.py
Bits._setfile
def _setfile(self, filename, length, offset): """Use file as source of bits.""" source = open(filename, 'rb') if offset is None: offset = 0 if length is None: length = os.path.getsize(source.name) * 8 - offset byteoffset, offset = divmod(offset, 8) bytelength = (length + byteoffset * 8 + offset + 7) // 8 - byteoffset m = MmapByteArray(source, bytelength, byteoffset) if length + byteoffset * 8 + offset > m.filelength * 8: raise CreationError("File is not long enough for specified " "length and offset.") self._datastore = ConstByteStore(m, length, offset)
python
def _setfile(self, filename, length, offset): """Use file as source of bits.""" source = open(filename, 'rb') if offset is None: offset = 0 if length is None: length = os.path.getsize(source.name) * 8 - offset byteoffset, offset = divmod(offset, 8) bytelength = (length + byteoffset * 8 + offset + 7) // 8 - byteoffset m = MmapByteArray(source, bytelength, byteoffset) if length + byteoffset * 8 + offset > m.filelength * 8: raise CreationError("File is not long enough for specified " "length and offset.") self._datastore = ConstByteStore(m, length, offset)
[ "def", "_setfile", "(", "self", ",", "filename", ",", "length", ",", "offset", ")", ":", "source", "=", "open", "(", "filename", ",", "'rb'", ")", "if", "offset", "is", "None", ":", "offset", "=", "0", "if", "length", "is", "None", ":", "length", "=", "os", ".", "path", ".", "getsize", "(", "source", ".", "name", ")", "*", "8", "-", "offset", "byteoffset", ",", "offset", "=", "divmod", "(", "offset", ",", "8", ")", "bytelength", "=", "(", "length", "+", "byteoffset", "*", "8", "+", "offset", "+", "7", ")", "//", "8", "-", "byteoffset", "m", "=", "MmapByteArray", "(", "source", ",", "bytelength", ",", "byteoffset", ")", "if", "length", "+", "byteoffset", "*", "8", "+", "offset", ">", "m", ".", "filelength", "*", "8", ":", "raise", "CreationError", "(", "\"File is not long enough for specified \"", "\"length and offset.\"", ")", "self", ".", "_datastore", "=", "ConstByteStore", "(", "m", ",", "length", ",", "offset", ")" ]
Use file as source of bits.
[ "Use", "file", "as", "source", "of", "bits", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1299-L1312
train
scott-griffiths/bitstring
bitstring.py
Bits._setbytes_safe
def _setbytes_safe(self, data, length=None, offset=0): """Set the data from a string.""" data = bytearray(data) if length is None: # Use to the end of the data length = len(data)*8 - offset self._datastore = ByteStore(data, length, offset) else: if length + offset > len(data) * 8: msg = "Not enough data present. Need {0} bits, have {1}." raise CreationError(msg, length + offset, len(data) * 8) if length == 0: self._datastore = ByteStore(bytearray(0)) else: self._datastore = ByteStore(data, length, offset)
python
def _setbytes_safe(self, data, length=None, offset=0): """Set the data from a string.""" data = bytearray(data) if length is None: # Use to the end of the data length = len(data)*8 - offset self._datastore = ByteStore(data, length, offset) else: if length + offset > len(data) * 8: msg = "Not enough data present. Need {0} bits, have {1}." raise CreationError(msg, length + offset, len(data) * 8) if length == 0: self._datastore = ByteStore(bytearray(0)) else: self._datastore = ByteStore(data, length, offset)
[ "def", "_setbytes_safe", "(", "self", ",", "data", ",", "length", "=", "None", ",", "offset", "=", "0", ")", ":", "data", "=", "bytearray", "(", "data", ")", "if", "length", "is", "None", ":", "# Use to the end of the data", "length", "=", "len", "(", "data", ")", "*", "8", "-", "offset", "self", ".", "_datastore", "=", "ByteStore", "(", "data", ",", "length", ",", "offset", ")", "else", ":", "if", "length", "+", "offset", ">", "len", "(", "data", ")", "*", "8", ":", "msg", "=", "\"Not enough data present. Need {0} bits, have {1}.\"", "raise", "CreationError", "(", "msg", ",", "length", "+", "offset", ",", "len", "(", "data", ")", "*", "8", ")", "if", "length", "==", "0", ":", "self", ".", "_datastore", "=", "ByteStore", "(", "bytearray", "(", "0", ")", ")", "else", ":", "self", ".", "_datastore", "=", "ByteStore", "(", "data", ",", "length", ",", "offset", ")" ]
Set the data from a string.
[ "Set", "the", "data", "from", "a", "string", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1314-L1328
train
scott-griffiths/bitstring
bitstring.py
Bits._setbytes_unsafe
def _setbytes_unsafe(self, data, length, offset): """Unchecked version of _setbytes_safe.""" self._datastore = ByteStore(data[:], length, offset) assert self._assertsanity()
python
def _setbytes_unsafe(self, data, length, offset): """Unchecked version of _setbytes_safe.""" self._datastore = ByteStore(data[:], length, offset) assert self._assertsanity()
[ "def", "_setbytes_unsafe", "(", "self", ",", "data", ",", "length", ",", "offset", ")", ":", "self", ".", "_datastore", "=", "ByteStore", "(", "data", "[", ":", "]", ",", "length", ",", "offset", ")", "assert", "self", ".", "_assertsanity", "(", ")" ]
Unchecked version of _setbytes_safe.
[ "Unchecked", "version", "of", "_setbytes_safe", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1330-L1333
train
scott-griffiths/bitstring
bitstring.py
Bits._readbytes
def _readbytes(self, length, start): """Read bytes and return them. Note that length is in bits.""" assert length % 8 == 0 assert start + length <= self.len if not (start + self._offset) % 8: return bytes(self._datastore.getbyteslice((start + self._offset) // 8, (start + self._offset + length) // 8)) return self._slice(start, start + length).tobytes()
python
def _readbytes(self, length, start): """Read bytes and return them. Note that length is in bits.""" assert length % 8 == 0 assert start + length <= self.len if not (start + self._offset) % 8: return bytes(self._datastore.getbyteslice((start + self._offset) // 8, (start + self._offset + length) // 8)) return self._slice(start, start + length).tobytes()
[ "def", "_readbytes", "(", "self", ",", "length", ",", "start", ")", ":", "assert", "length", "%", "8", "==", "0", "assert", "start", "+", "length", "<=", "self", ".", "len", "if", "not", "(", "start", "+", "self", ".", "_offset", ")", "%", "8", ":", "return", "bytes", "(", "self", ".", "_datastore", ".", "getbyteslice", "(", "(", "start", "+", "self", ".", "_offset", ")", "//", "8", ",", "(", "start", "+", "self", ".", "_offset", "+", "length", ")", "//", "8", ")", ")", "return", "self", ".", "_slice", "(", "start", ",", "start", "+", "length", ")", ".", "tobytes", "(", ")" ]
Read bytes and return them. Note that length is in bits.
[ "Read", "bytes", "and", "return", "them", ".", "Note", "that", "length", "is", "in", "bits", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1335-L1342
train
scott-griffiths/bitstring
bitstring.py
Bits._setuint
def _setuint(self, uint, length=None): """Reset the bitstring to have given unsigned int interpretation.""" try: if length is None: # Use the whole length. Deliberately not using .len here. length = self._datastore.bitlength except AttributeError: # bitstring doesn't have a _datastore as it hasn't been created! pass # TODO: All this checking code should be hoisted out of here! if length is None or length == 0: raise CreationError("A non-zero length must be specified with a " "uint initialiser.") if uint >= (1 << length): msg = "{0} is too large an unsigned integer for a bitstring of length {1}. "\ "The allowed range is [0, {2}]." raise CreationError(msg, uint, length, (1 << length) - 1) if uint < 0: raise CreationError("uint cannot be initialsed by a negative number.") s = hex(uint)[2:] s = s.rstrip('L') if len(s) & 1: s = '0' + s try: data = bytes.fromhex(s) except AttributeError: # the Python 2.x way data = binascii.unhexlify(s) # Now add bytes as needed to get the right length. extrabytes = ((length + 7) // 8) - len(data) if extrabytes > 0: data = b'\x00' * extrabytes + data offset = 8 - (length % 8) if offset == 8: offset = 0 self._setbytes_unsafe(bytearray(data), length, offset)
python
def _setuint(self, uint, length=None): """Reset the bitstring to have given unsigned int interpretation.""" try: if length is None: # Use the whole length. Deliberately not using .len here. length = self._datastore.bitlength except AttributeError: # bitstring doesn't have a _datastore as it hasn't been created! pass # TODO: All this checking code should be hoisted out of here! if length is None or length == 0: raise CreationError("A non-zero length must be specified with a " "uint initialiser.") if uint >= (1 << length): msg = "{0} is too large an unsigned integer for a bitstring of length {1}. "\ "The allowed range is [0, {2}]." raise CreationError(msg, uint, length, (1 << length) - 1) if uint < 0: raise CreationError("uint cannot be initialsed by a negative number.") s = hex(uint)[2:] s = s.rstrip('L') if len(s) & 1: s = '0' + s try: data = bytes.fromhex(s) except AttributeError: # the Python 2.x way data = binascii.unhexlify(s) # Now add bytes as needed to get the right length. extrabytes = ((length + 7) // 8) - len(data) if extrabytes > 0: data = b'\x00' * extrabytes + data offset = 8 - (length % 8) if offset == 8: offset = 0 self._setbytes_unsafe(bytearray(data), length, offset)
[ "def", "_setuint", "(", "self", ",", "uint", ",", "length", "=", "None", ")", ":", "try", ":", "if", "length", "is", "None", ":", "# Use the whole length. Deliberately not using .len here.", "length", "=", "self", ".", "_datastore", ".", "bitlength", "except", "AttributeError", ":", "# bitstring doesn't have a _datastore as it hasn't been created!", "pass", "# TODO: All this checking code should be hoisted out of here!", "if", "length", "is", "None", "or", "length", "==", "0", ":", "raise", "CreationError", "(", "\"A non-zero length must be specified with a \"", "\"uint initialiser.\"", ")", "if", "uint", ">=", "(", "1", "<<", "length", ")", ":", "msg", "=", "\"{0} is too large an unsigned integer for a bitstring of length {1}. \"", "\"The allowed range is [0, {2}].\"", "raise", "CreationError", "(", "msg", ",", "uint", ",", "length", ",", "(", "1", "<<", "length", ")", "-", "1", ")", "if", "uint", "<", "0", ":", "raise", "CreationError", "(", "\"uint cannot be initialsed by a negative number.\"", ")", "s", "=", "hex", "(", "uint", ")", "[", "2", ":", "]", "s", "=", "s", ".", "rstrip", "(", "'L'", ")", "if", "len", "(", "s", ")", "&", "1", ":", "s", "=", "'0'", "+", "s", "try", ":", "data", "=", "bytes", ".", "fromhex", "(", "s", ")", "except", "AttributeError", ":", "# the Python 2.x way", "data", "=", "binascii", ".", "unhexlify", "(", "s", ")", "# Now add bytes as needed to get the right length.", "extrabytes", "=", "(", "(", "length", "+", "7", ")", "//", "8", ")", "-", "len", "(", "data", ")", "if", "extrabytes", ">", "0", ":", "data", "=", "b'\\x00'", "*", "extrabytes", "+", "data", "offset", "=", "8", "-", "(", "length", "%", "8", ")", "if", "offset", "==", "8", ":", "offset", "=", "0", "self", ".", "_setbytes_unsafe", "(", "bytearray", "(", "data", ")", ",", "length", ",", "offset", ")" ]
Reset the bitstring to have given unsigned int interpretation.
[ "Reset", "the", "bitstring", "to", "have", "given", "unsigned", "int", "interpretation", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1351-L1386
train
scott-griffiths/bitstring
bitstring.py
Bits._readuint
def _readuint(self, length, start): """Read bits and interpret as an unsigned int.""" if not length: raise InterpretError("Cannot interpret a zero length bitstring " "as an integer.") offset = self._offset startbyte = (start + offset) // 8 endbyte = (start + offset + length - 1) // 8 b = binascii.hexlify(bytes(self._datastore.getbyteslice(startbyte, endbyte + 1))) assert b i = int(b, 16) final_bits = 8 - ((start + offset + length) % 8) if final_bits != 8: i >>= final_bits i &= (1 << length) - 1 return i
python
def _readuint(self, length, start): """Read bits and interpret as an unsigned int.""" if not length: raise InterpretError("Cannot interpret a zero length bitstring " "as an integer.") offset = self._offset startbyte = (start + offset) // 8 endbyte = (start + offset + length - 1) // 8 b = binascii.hexlify(bytes(self._datastore.getbyteslice(startbyte, endbyte + 1))) assert b i = int(b, 16) final_bits = 8 - ((start + offset + length) % 8) if final_bits != 8: i >>= final_bits i &= (1 << length) - 1 return i
[ "def", "_readuint", "(", "self", ",", "length", ",", "start", ")", ":", "if", "not", "length", ":", "raise", "InterpretError", "(", "\"Cannot interpret a zero length bitstring \"", "\"as an integer.\"", ")", "offset", "=", "self", ".", "_offset", "startbyte", "=", "(", "start", "+", "offset", ")", "//", "8", "endbyte", "=", "(", "start", "+", "offset", "+", "length", "-", "1", ")", "//", "8", "b", "=", "binascii", ".", "hexlify", "(", "bytes", "(", "self", ".", "_datastore", ".", "getbyteslice", "(", "startbyte", ",", "endbyte", "+", "1", ")", ")", ")", "assert", "b", "i", "=", "int", "(", "b", ",", "16", ")", "final_bits", "=", "8", "-", "(", "(", "start", "+", "offset", "+", "length", ")", "%", "8", ")", "if", "final_bits", "!=", "8", ":", "i", ">>=", "final_bits", "i", "&=", "(", "1", "<<", "length", ")", "-", "1", "return", "i" ]
Read bits and interpret as an unsigned int.
[ "Read", "bits", "and", "interpret", "as", "an", "unsigned", "int", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1388-L1404
train
scott-griffiths/bitstring
bitstring.py
Bits._setint
def _setint(self, int_, length=None): """Reset the bitstring to have given signed int interpretation.""" # If no length given, and we've previously been given a length, use it. if length is None and hasattr(self, 'len') and self.len != 0: length = self.len if length is None or length == 0: raise CreationError("A non-zero length must be specified with an int initialiser.") if int_ >= (1 << (length - 1)) or int_ < -(1 << (length - 1)): raise CreationError("{0} is too large a signed integer for a bitstring of length {1}. " "The allowed range is [{2}, {3}].", int_, length, -(1 << (length - 1)), (1 << (length - 1)) - 1) if int_ >= 0: self._setuint(int_, length) return # TODO: We should decide whether to just use the _setuint, or to do the bit flipping, # based upon which will be quicker. If the -ive number is less than half the maximum # possible then it's probably quicker to do the bit flipping... # Do the 2's complement thing. Add one, set to minus number, then flip bits. int_ += 1 self._setuint(-int_, length) self._invert_all()
python
def _setint(self, int_, length=None): """Reset the bitstring to have given signed int interpretation.""" # If no length given, and we've previously been given a length, use it. if length is None and hasattr(self, 'len') and self.len != 0: length = self.len if length is None or length == 0: raise CreationError("A non-zero length must be specified with an int initialiser.") if int_ >= (1 << (length - 1)) or int_ < -(1 << (length - 1)): raise CreationError("{0} is too large a signed integer for a bitstring of length {1}. " "The allowed range is [{2}, {3}].", int_, length, -(1 << (length - 1)), (1 << (length - 1)) - 1) if int_ >= 0: self._setuint(int_, length) return # TODO: We should decide whether to just use the _setuint, or to do the bit flipping, # based upon which will be quicker. If the -ive number is less than half the maximum # possible then it's probably quicker to do the bit flipping... # Do the 2's complement thing. Add one, set to minus number, then flip bits. int_ += 1 self._setuint(-int_, length) self._invert_all()
[ "def", "_setint", "(", "self", ",", "int_", ",", "length", "=", "None", ")", ":", "# If no length given, and we've previously been given a length, use it.", "if", "length", "is", "None", "and", "hasattr", "(", "self", ",", "'len'", ")", "and", "self", ".", "len", "!=", "0", ":", "length", "=", "self", ".", "len", "if", "length", "is", "None", "or", "length", "==", "0", ":", "raise", "CreationError", "(", "\"A non-zero length must be specified with an int initialiser.\"", ")", "if", "int_", ">=", "(", "1", "<<", "(", "length", "-", "1", ")", ")", "or", "int_", "<", "-", "(", "1", "<<", "(", "length", "-", "1", ")", ")", ":", "raise", "CreationError", "(", "\"{0} is too large a signed integer for a bitstring of length {1}. \"", "\"The allowed range is [{2}, {3}].\"", ",", "int_", ",", "length", ",", "-", "(", "1", "<<", "(", "length", "-", "1", ")", ")", ",", "(", "1", "<<", "(", "length", "-", "1", ")", ")", "-", "1", ")", "if", "int_", ">=", "0", ":", "self", ".", "_setuint", "(", "int_", ",", "length", ")", "return", "# TODO: We should decide whether to just use the _setuint, or to do the bit flipping,", "# based upon which will be quicker. If the -ive number is less than half the maximum", "# possible then it's probably quicker to do the bit flipping...", "# Do the 2's complement thing. Add one, set to minus number, then flip bits.", "int_", "+=", "1", "self", ".", "_setuint", "(", "-", "int_", ",", "length", ")", "self", ".", "_invert_all", "(", ")" ]
Reset the bitstring to have given signed int interpretation.
[ "Reset", "the", "bitstring", "to", "have", "given", "signed", "int", "interpretation", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1410-L1431
train
scott-griffiths/bitstring
bitstring.py
Bits._readint
def _readint(self, length, start): """Read bits and interpret as a signed int""" ui = self._readuint(length, start) if not ui >> (length - 1): # Top bit not set, number is positive return ui # Top bit is set, so number is negative tmp = (~(ui - 1)) & ((1 << length) - 1) return -tmp
python
def _readint(self, length, start): """Read bits and interpret as a signed int""" ui = self._readuint(length, start) if not ui >> (length - 1): # Top bit not set, number is positive return ui # Top bit is set, so number is negative tmp = (~(ui - 1)) & ((1 << length) - 1) return -tmp
[ "def", "_readint", "(", "self", ",", "length", ",", "start", ")", ":", "ui", "=", "self", ".", "_readuint", "(", "length", ",", "start", ")", "if", "not", "ui", ">>", "(", "length", "-", "1", ")", ":", "# Top bit not set, number is positive", "return", "ui", "# Top bit is set, so number is negative", "tmp", "=", "(", "~", "(", "ui", "-", "1", ")", ")", "&", "(", "(", "1", "<<", "length", ")", "-", "1", ")", "return", "-", "tmp" ]
Read bits and interpret as a signed int
[ "Read", "bits", "and", "interpret", "as", "a", "signed", "int" ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1433-L1441
train
scott-griffiths/bitstring
bitstring.py
Bits._setuintbe
def _setuintbe(self, uintbe, length=None): """Set the bitstring to a big-endian unsigned int interpretation.""" if length is not None and length % 8 != 0: raise CreationError("Big-endian integers must be whole-byte. " "Length = {0} bits.", length) self._setuint(uintbe, length)
python
def _setuintbe(self, uintbe, length=None): """Set the bitstring to a big-endian unsigned int interpretation.""" if length is not None and length % 8 != 0: raise CreationError("Big-endian integers must be whole-byte. " "Length = {0} bits.", length) self._setuint(uintbe, length)
[ "def", "_setuintbe", "(", "self", ",", "uintbe", ",", "length", "=", "None", ")", ":", "if", "length", "is", "not", "None", "and", "length", "%", "8", "!=", "0", ":", "raise", "CreationError", "(", "\"Big-endian integers must be whole-byte. \"", "\"Length = {0} bits.\"", ",", "length", ")", "self", ".", "_setuint", "(", "uintbe", ",", "length", ")" ]
Set the bitstring to a big-endian unsigned int interpretation.
[ "Set", "the", "bitstring", "to", "a", "big", "-", "endian", "unsigned", "int", "interpretation", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1447-L1452
train
scott-griffiths/bitstring
bitstring.py
Bits._readuintbe
def _readuintbe(self, length, start): """Read bits and interpret as a big-endian unsigned int.""" if length % 8: raise InterpretError("Big-endian integers must be whole-byte. " "Length = {0} bits.", length) return self._readuint(length, start)
python
def _readuintbe(self, length, start): """Read bits and interpret as a big-endian unsigned int.""" if length % 8: raise InterpretError("Big-endian integers must be whole-byte. " "Length = {0} bits.", length) return self._readuint(length, start)
[ "def", "_readuintbe", "(", "self", ",", "length", ",", "start", ")", ":", "if", "length", "%", "8", ":", "raise", "InterpretError", "(", "\"Big-endian integers must be whole-byte. \"", "\"Length = {0} bits.\"", ",", "length", ")", "return", "self", ".", "_readuint", "(", "length", ",", "start", ")" ]
Read bits and interpret as a big-endian unsigned int.
[ "Read", "bits", "and", "interpret", "as", "a", "big", "-", "endian", "unsigned", "int", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1454-L1459
train
scott-griffiths/bitstring
bitstring.py
Bits._setintbe
def _setintbe(self, intbe, length=None): """Set bitstring to a big-endian signed int interpretation.""" if length is not None and length % 8 != 0: raise CreationError("Big-endian integers must be whole-byte. " "Length = {0} bits.", length) self._setint(intbe, length)
python
def _setintbe(self, intbe, length=None): """Set bitstring to a big-endian signed int interpretation.""" if length is not None and length % 8 != 0: raise CreationError("Big-endian integers must be whole-byte. " "Length = {0} bits.", length) self._setint(intbe, length)
[ "def", "_setintbe", "(", "self", ",", "intbe", ",", "length", "=", "None", ")", ":", "if", "length", "is", "not", "None", "and", "length", "%", "8", "!=", "0", ":", "raise", "CreationError", "(", "\"Big-endian integers must be whole-byte. \"", "\"Length = {0} bits.\"", ",", "length", ")", "self", ".", "_setint", "(", "intbe", ",", "length", ")" ]
Set bitstring to a big-endian signed int interpretation.
[ "Set", "bitstring", "to", "a", "big", "-", "endian", "signed", "int", "interpretation", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1465-L1470
train
scott-griffiths/bitstring
bitstring.py
Bits._readintbe
def _readintbe(self, length, start): """Read bits and interpret as a big-endian signed int.""" if length % 8: raise InterpretError("Big-endian integers must be whole-byte. " "Length = {0} bits.", length) return self._readint(length, start)
python
def _readintbe(self, length, start): """Read bits and interpret as a big-endian signed int.""" if length % 8: raise InterpretError("Big-endian integers must be whole-byte. " "Length = {0} bits.", length) return self._readint(length, start)
[ "def", "_readintbe", "(", "self", ",", "length", ",", "start", ")", ":", "if", "length", "%", "8", ":", "raise", "InterpretError", "(", "\"Big-endian integers must be whole-byte. \"", "\"Length = {0} bits.\"", ",", "length", ")", "return", "self", ".", "_readint", "(", "length", ",", "start", ")" ]
Read bits and interpret as a big-endian signed int.
[ "Read", "bits", "and", "interpret", "as", "a", "big", "-", "endian", "signed", "int", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1472-L1477
train
scott-griffiths/bitstring
bitstring.py
Bits._readuintle
def _readuintle(self, length, start): """Read bits and interpret as a little-endian unsigned int.""" if length % 8: raise InterpretError("Little-endian integers must be whole-byte. " "Length = {0} bits.", length) assert start + length <= self.len absolute_pos = start + self._offset startbyte, offset = divmod(absolute_pos, 8) val = 0 if not offset: endbyte = (absolute_pos + length - 1) // 8 chunksize = 4 # for 'L' format while endbyte - chunksize + 1 >= startbyte: val <<= 8 * chunksize val += struct.unpack('<L', bytes(self._datastore.getbyteslice(endbyte + 1 - chunksize, endbyte + 1)))[0] endbyte -= chunksize for b in xrange(endbyte, startbyte - 1, -1): val <<= 8 val += self._datastore.getbyte(b) else: data = self._slice(start, start + length) assert data.len % 8 == 0 data._reversebytes(0, self.len) for b in bytearray(data.bytes): val <<= 8 val += b return val
python
def _readuintle(self, length, start): """Read bits and interpret as a little-endian unsigned int.""" if length % 8: raise InterpretError("Little-endian integers must be whole-byte. " "Length = {0} bits.", length) assert start + length <= self.len absolute_pos = start + self._offset startbyte, offset = divmod(absolute_pos, 8) val = 0 if not offset: endbyte = (absolute_pos + length - 1) // 8 chunksize = 4 # for 'L' format while endbyte - chunksize + 1 >= startbyte: val <<= 8 * chunksize val += struct.unpack('<L', bytes(self._datastore.getbyteslice(endbyte + 1 - chunksize, endbyte + 1)))[0] endbyte -= chunksize for b in xrange(endbyte, startbyte - 1, -1): val <<= 8 val += self._datastore.getbyte(b) else: data = self._slice(start, start + length) assert data.len % 8 == 0 data._reversebytes(0, self.len) for b in bytearray(data.bytes): val <<= 8 val += b return val
[ "def", "_readuintle", "(", "self", ",", "length", ",", "start", ")", ":", "if", "length", "%", "8", ":", "raise", "InterpretError", "(", "\"Little-endian integers must be whole-byte. \"", "\"Length = {0} bits.\"", ",", "length", ")", "assert", "start", "+", "length", "<=", "self", ".", "len", "absolute_pos", "=", "start", "+", "self", ".", "_offset", "startbyte", ",", "offset", "=", "divmod", "(", "absolute_pos", ",", "8", ")", "val", "=", "0", "if", "not", "offset", ":", "endbyte", "=", "(", "absolute_pos", "+", "length", "-", "1", ")", "//", "8", "chunksize", "=", "4", "# for 'L' format", "while", "endbyte", "-", "chunksize", "+", "1", ">=", "startbyte", ":", "val", "<<=", "8", "*", "chunksize", "val", "+=", "struct", ".", "unpack", "(", "'<L'", ",", "bytes", "(", "self", ".", "_datastore", ".", "getbyteslice", "(", "endbyte", "+", "1", "-", "chunksize", ",", "endbyte", "+", "1", ")", ")", ")", "[", "0", "]", "endbyte", "-=", "chunksize", "for", "b", "in", "xrange", "(", "endbyte", ",", "startbyte", "-", "1", ",", "-", "1", ")", ":", "val", "<<=", "8", "val", "+=", "self", ".", "_datastore", ".", "getbyte", "(", "b", ")", "else", ":", "data", "=", "self", ".", "_slice", "(", "start", ",", "start", "+", "length", ")", "assert", "data", ".", "len", "%", "8", "==", "0", "data", ".", "_reversebytes", "(", "0", ",", "self", ".", "len", ")", "for", "b", "in", "bytearray", "(", "data", ".", "bytes", ")", ":", "val", "<<=", "8", "val", "+=", "b", "return", "val" ]
Read bits and interpret as a little-endian unsigned int.
[ "Read", "bits", "and", "interpret", "as", "a", "little", "-", "endian", "unsigned", "int", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1490-L1516
train
scott-griffiths/bitstring
bitstring.py
Bits._readintle
def _readintle(self, length, start): """Read bits and interpret as a little-endian signed int.""" ui = self._readuintle(length, start) if not ui >> (length - 1): # Top bit not set, number is positive return ui # Top bit is set, so number is negative tmp = (~(ui - 1)) & ((1 << length) - 1) return -tmp
python
def _readintle(self, length, start): """Read bits and interpret as a little-endian signed int.""" ui = self._readuintle(length, start) if not ui >> (length - 1): # Top bit not set, number is positive return ui # Top bit is set, so number is negative tmp = (~(ui - 1)) & ((1 << length) - 1) return -tmp
[ "def", "_readintle", "(", "self", ",", "length", ",", "start", ")", ":", "ui", "=", "self", ".", "_readuintle", "(", "length", ",", "start", ")", "if", "not", "ui", ">>", "(", "length", "-", "1", ")", ":", "# Top bit not set, number is positive", "return", "ui", "# Top bit is set, so number is negative", "tmp", "=", "(", "~", "(", "ui", "-", "1", ")", ")", "&", "(", "(", "1", "<<", "length", ")", "-", "1", ")", "return", "-", "tmp" ]
Read bits and interpret as a little-endian signed int.
[ "Read", "bits", "and", "interpret", "as", "a", "little", "-", "endian", "signed", "int", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1528-L1536
train
scott-griffiths/bitstring
bitstring.py
Bits._readfloat
def _readfloat(self, length, start): """Read bits and interpret as a float.""" if not (start + self._offset) % 8: startbyte = (start + self._offset) // 8 if length == 32: f, = struct.unpack('>f', bytes(self._datastore.getbyteslice(startbyte, startbyte + 4))) elif length == 64: f, = struct.unpack('>d', bytes(self._datastore.getbyteslice(startbyte, startbyte + 8))) else: if length == 32: f, = struct.unpack('>f', self._readbytes(32, start)) elif length == 64: f, = struct.unpack('>d', self._readbytes(64, start)) try: return f except NameError: raise InterpretError("floats can only be 32 or 64 bits long, not {0} bits", length)
python
def _readfloat(self, length, start): """Read bits and interpret as a float.""" if not (start + self._offset) % 8: startbyte = (start + self._offset) // 8 if length == 32: f, = struct.unpack('>f', bytes(self._datastore.getbyteslice(startbyte, startbyte + 4))) elif length == 64: f, = struct.unpack('>d', bytes(self._datastore.getbyteslice(startbyte, startbyte + 8))) else: if length == 32: f, = struct.unpack('>f', self._readbytes(32, start)) elif length == 64: f, = struct.unpack('>d', self._readbytes(64, start)) try: return f except NameError: raise InterpretError("floats can only be 32 or 64 bits long, not {0} bits", length)
[ "def", "_readfloat", "(", "self", ",", "length", ",", "start", ")", ":", "if", "not", "(", "start", "+", "self", ".", "_offset", ")", "%", "8", ":", "startbyte", "=", "(", "start", "+", "self", ".", "_offset", ")", "//", "8", "if", "length", "==", "32", ":", "f", ",", "=", "struct", ".", "unpack", "(", "'>f'", ",", "bytes", "(", "self", ".", "_datastore", ".", "getbyteslice", "(", "startbyte", ",", "startbyte", "+", "4", ")", ")", ")", "elif", "length", "==", "64", ":", "f", ",", "=", "struct", ".", "unpack", "(", "'>d'", ",", "bytes", "(", "self", ".", "_datastore", ".", "getbyteslice", "(", "startbyte", ",", "startbyte", "+", "8", ")", ")", ")", "else", ":", "if", "length", "==", "32", ":", "f", ",", "=", "struct", ".", "unpack", "(", "'>f'", ",", "self", ".", "_readbytes", "(", "32", ",", "start", ")", ")", "elif", "length", "==", "64", ":", "f", ",", "=", "struct", ".", "unpack", "(", "'>d'", ",", "self", ".", "_readbytes", "(", "64", ",", "start", ")", ")", "try", ":", "return", "f", "except", "NameError", ":", "raise", "InterpretError", "(", "\"floats can only be 32 or 64 bits long, not {0} bits\"", ",", "length", ")" ]
Read bits and interpret as a float.
[ "Read", "bits", "and", "interpret", "as", "a", "float", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1557-L1573
train
scott-griffiths/bitstring
bitstring.py
Bits._readfloatle
def _readfloatle(self, length, start): """Read bits and interpret as a little-endian float.""" startbyte, offset = divmod(start + self._offset, 8) if not offset: if length == 32: f, = struct.unpack('<f', bytes(self._datastore.getbyteslice(startbyte, startbyte + 4))) elif length == 64: f, = struct.unpack('<d', bytes(self._datastore.getbyteslice(startbyte, startbyte + 8))) else: if length == 32: f, = struct.unpack('<f', self._readbytes(32, start)) elif length == 64: f, = struct.unpack('<d', self._readbytes(64, start)) try: return f except NameError: raise InterpretError("floats can only be 32 or 64 bits long, " "not {0} bits", length)
python
def _readfloatle(self, length, start): """Read bits and interpret as a little-endian float.""" startbyte, offset = divmod(start + self._offset, 8) if not offset: if length == 32: f, = struct.unpack('<f', bytes(self._datastore.getbyteslice(startbyte, startbyte + 4))) elif length == 64: f, = struct.unpack('<d', bytes(self._datastore.getbyteslice(startbyte, startbyte + 8))) else: if length == 32: f, = struct.unpack('<f', self._readbytes(32, start)) elif length == 64: f, = struct.unpack('<d', self._readbytes(64, start)) try: return f except NameError: raise InterpretError("floats can only be 32 or 64 bits long, " "not {0} bits", length)
[ "def", "_readfloatle", "(", "self", ",", "length", ",", "start", ")", ":", "startbyte", ",", "offset", "=", "divmod", "(", "start", "+", "self", ".", "_offset", ",", "8", ")", "if", "not", "offset", ":", "if", "length", "==", "32", ":", "f", ",", "=", "struct", ".", "unpack", "(", "'<f'", ",", "bytes", "(", "self", ".", "_datastore", ".", "getbyteslice", "(", "startbyte", ",", "startbyte", "+", "4", ")", ")", ")", "elif", "length", "==", "64", ":", "f", ",", "=", "struct", ".", "unpack", "(", "'<d'", ",", "bytes", "(", "self", ".", "_datastore", ".", "getbyteslice", "(", "startbyte", ",", "startbyte", "+", "8", ")", ")", ")", "else", ":", "if", "length", "==", "32", ":", "f", ",", "=", "struct", ".", "unpack", "(", "'<f'", ",", "self", ".", "_readbytes", "(", "32", ",", "start", ")", ")", "elif", "length", "==", "64", ":", "f", ",", "=", "struct", ".", "unpack", "(", "'<d'", ",", "self", ".", "_readbytes", "(", "64", ",", "start", ")", ")", "try", ":", "return", "f", "except", "NameError", ":", "raise", "InterpretError", "(", "\"floats can only be 32 or 64 bits long, \"", "\"not {0} bits\"", ",", "length", ")" ]
Read bits and interpret as a little-endian float.
[ "Read", "bits", "and", "interpret", "as", "a", "little", "-", "endian", "float", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1595-L1612
train
scott-griffiths/bitstring
bitstring.py
Bits._setue
def _setue(self, i): """Initialise bitstring with unsigned exponential-Golomb code for integer i. Raises CreationError if i < 0. """ if i < 0: raise CreationError("Cannot use negative initialiser for unsigned " "exponential-Golomb.") if not i: self._setbin_unsafe('1') return tmp = i + 1 leadingzeros = -1 while tmp > 0: tmp >>= 1 leadingzeros += 1 remainingpart = i + 1 - (1 << leadingzeros) binstring = '0' * leadingzeros + '1' + Bits(uint=remainingpart, length=leadingzeros).bin self._setbin_unsafe(binstring)
python
def _setue(self, i): """Initialise bitstring with unsigned exponential-Golomb code for integer i. Raises CreationError if i < 0. """ if i < 0: raise CreationError("Cannot use negative initialiser for unsigned " "exponential-Golomb.") if not i: self._setbin_unsafe('1') return tmp = i + 1 leadingzeros = -1 while tmp > 0: tmp >>= 1 leadingzeros += 1 remainingpart = i + 1 - (1 << leadingzeros) binstring = '0' * leadingzeros + '1' + Bits(uint=remainingpart, length=leadingzeros).bin self._setbin_unsafe(binstring)
[ "def", "_setue", "(", "self", ",", "i", ")", ":", "if", "i", "<", "0", ":", "raise", "CreationError", "(", "\"Cannot use negative initialiser for unsigned \"", "\"exponential-Golomb.\"", ")", "if", "not", "i", ":", "self", ".", "_setbin_unsafe", "(", "'1'", ")", "return", "tmp", "=", "i", "+", "1", "leadingzeros", "=", "-", "1", "while", "tmp", ">", "0", ":", "tmp", ">>=", "1", "leadingzeros", "+=", "1", "remainingpart", "=", "i", "+", "1", "-", "(", "1", "<<", "leadingzeros", ")", "binstring", "=", "'0'", "*", "leadingzeros", "+", "'1'", "+", "Bits", "(", "uint", "=", "remainingpart", ",", "length", "=", "leadingzeros", ")", ".", "bin", "self", ".", "_setbin_unsafe", "(", "binstring", ")" ]
Initialise bitstring with unsigned exponential-Golomb code for integer i. Raises CreationError if i < 0.
[ "Initialise", "bitstring", "with", "unsigned", "exponential", "-", "Golomb", "code", "for", "integer", "i", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1618-L1638
train
scott-griffiths/bitstring
bitstring.py
Bits._readue
def _readue(self, pos): """Return interpretation of next bits as unsigned exponential-Golomb code. Raises ReadError if the end of the bitstring is encountered while reading the code. """ 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
python
def _readue(self, pos): """Return interpretation of next bits as unsigned exponential-Golomb code. Raises ReadError if the end of the bitstring is encountered while reading the code. """ 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
[ "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" ]
Return interpretation of next bits as unsigned exponential-Golomb code. Raises ReadError if the end of the bitstring is encountered while reading the code.
[ "Return", "interpretation", "of", "next", "bits", "as", "unsigned", "exponential", "-", "Golomb", "code", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1640-L1663
train
scott-griffiths/bitstring
bitstring.py
Bits._getue
def _getue(self): """Return data as unsigned exponential-Golomb code. Raises InterpretError if bitstring is not a single exponential-Golomb code. """ try: value, newpos = self._readue(0) if value is None or newpos != self.len: raise ReadError except ReadError: raise InterpretError("Bitstring is not a single exponential-Golomb code.") return value
python
def _getue(self): """Return data as unsigned exponential-Golomb code. Raises InterpretError if bitstring is not a single exponential-Golomb code. """ try: value, newpos = self._readue(0) if value is None or newpos != self.len: raise ReadError except ReadError: raise InterpretError("Bitstring is not a single exponential-Golomb code.") return value
[ "def", "_getue", "(", "self", ")", ":", "try", ":", "value", ",", "newpos", "=", "self", ".", "_readue", "(", "0", ")", "if", "value", "is", "None", "or", "newpos", "!=", "self", ".", "len", ":", "raise", "ReadError", "except", "ReadError", ":", "raise", "InterpretError", "(", "\"Bitstring is not a single exponential-Golomb code.\"", ")", "return", "value" ]
Return data as unsigned exponential-Golomb code. Raises InterpretError if bitstring is not a single exponential-Golomb code.
[ "Return", "data", "as", "unsigned", "exponential", "-", "Golomb", "code", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1665-L1677
train
scott-griffiths/bitstring
bitstring.py
Bits._setse
def _setse(self, i): """Initialise bitstring with signed exponential-Golomb code for integer i.""" if i > 0: u = (i * 2) - 1 else: u = -2 * i self._setue(u)
python
def _setse(self, i): """Initialise bitstring with signed exponential-Golomb code for integer i.""" if i > 0: u = (i * 2) - 1 else: u = -2 * i self._setue(u)
[ "def", "_setse", "(", "self", ",", "i", ")", ":", "if", "i", ">", "0", ":", "u", "=", "(", "i", "*", "2", ")", "-", "1", "else", ":", "u", "=", "-", "2", "*", "i", "self", ".", "_setue", "(", "u", ")" ]
Initialise bitstring with signed exponential-Golomb code for integer i.
[ "Initialise", "bitstring", "with", "signed", "exponential", "-", "Golomb", "code", "for", "integer", "i", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1679-L1685
train
scott-griffiths/bitstring
bitstring.py
Bits._getse
def _getse(self): """Return data as signed exponential-Golomb code. Raises InterpretError if bitstring is not a single exponential-Golomb code. """ try: value, newpos = self._readse(0) if value is None or newpos != self.len: raise ReadError except ReadError: raise InterpretError("Bitstring is not a single exponential-Golomb code.") return value
python
def _getse(self): """Return data as signed exponential-Golomb code. Raises InterpretError if bitstring is not a single exponential-Golomb code. """ try: value, newpos = self._readse(0) if value is None or newpos != self.len: raise ReadError except ReadError: raise InterpretError("Bitstring is not a single exponential-Golomb code.") return value
[ "def", "_getse", "(", "self", ")", ":", "try", ":", "value", ",", "newpos", "=", "self", ".", "_readse", "(", "0", ")", "if", "value", "is", "None", "or", "newpos", "!=", "self", ".", "len", ":", "raise", "ReadError", "except", "ReadError", ":", "raise", "InterpretError", "(", "\"Bitstring is not a single exponential-Golomb code.\"", ")", "return", "value" ]
Return data as signed exponential-Golomb code. Raises InterpretError if bitstring is not a single exponential-Golomb code.
[ "Return", "data", "as", "signed", "exponential", "-", "Golomb", "code", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1687-L1699
train
scott-griffiths/bitstring
bitstring.py
Bits._readse
def _readse(self, pos): """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. """ codenum, pos = self._readue(pos) m = (codenum + 1) // 2 if not codenum % 2: return -m, pos else: return m, pos
python
def _readse(self, pos): """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. """ codenum, pos = self._readue(pos) m = (codenum + 1) // 2 if not codenum % 2: return -m, pos else: return m, pos
[ "def", "_readse", "(", "self", ",", "pos", ")", ":", "codenum", ",", "pos", "=", "self", ".", "_readue", "(", "pos", ")", "m", "=", "(", "codenum", "+", "1", ")", "//", "2", "if", "not", "codenum", "%", "2", ":", "return", "-", "m", ",", "pos", "else", ":", "return", "m", ",", "pos" ]
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.
[ "Return", "interpretation", "of", "next", "bits", "as", "a", "signed", "exponential", "-", "Golomb", "code", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1701-L1715
train
scott-griffiths/bitstring
bitstring.py
Bits._setuie
def _setuie(self, i): """Initialise bitstring with unsigned interleaved exponential-Golomb code for integer i. Raises CreationError if i < 0. """ if i < 0: raise CreationError("Cannot use negative initialiser for unsigned " "interleaved exponential-Golomb.") self._setbin_unsafe('1' if i == 0 else '0' + '0'.join(bin(i + 1)[3:]) + '1')
python
def _setuie(self, i): """Initialise bitstring with unsigned interleaved exponential-Golomb code for integer i. Raises CreationError if i < 0. """ if i < 0: raise CreationError("Cannot use negative initialiser for unsigned " "interleaved exponential-Golomb.") self._setbin_unsafe('1' if i == 0 else '0' + '0'.join(bin(i + 1)[3:]) + '1')
[ "def", "_setuie", "(", "self", ",", "i", ")", ":", "if", "i", "<", "0", ":", "raise", "CreationError", "(", "\"Cannot use negative initialiser for unsigned \"", "\"interleaved exponential-Golomb.\"", ")", "self", ".", "_setbin_unsafe", "(", "'1'", "if", "i", "==", "0", "else", "'0'", "+", "'0'", ".", "join", "(", "bin", "(", "i", "+", "1", ")", "[", "3", ":", "]", ")", "+", "'1'", ")" ]
Initialise bitstring with unsigned interleaved exponential-Golomb code for integer i. Raises CreationError if i < 0.
[ "Initialise", "bitstring", "with", "unsigned", "interleaved", "exponential", "-", "Golomb", "code", "for", "integer", "i", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1717-L1726
train
scott-griffiths/bitstring
bitstring.py
Bits._getuie
def _getuie(self): """Return data as unsigned interleaved exponential-Golomb code. Raises InterpretError if bitstring is not a single exponential-Golomb code. """ try: value, newpos = self._readuie(0) if value is None or newpos != self.len: raise ReadError except ReadError: raise InterpretError("Bitstring is not a single interleaved exponential-Golomb code.") return value
python
def _getuie(self): """Return data as unsigned interleaved exponential-Golomb code. Raises InterpretError if bitstring is not a single exponential-Golomb code. """ try: value, newpos = self._readuie(0) if value is None or newpos != self.len: raise ReadError except ReadError: raise InterpretError("Bitstring is not a single interleaved exponential-Golomb code.") return value
[ "def", "_getuie", "(", "self", ")", ":", "try", ":", "value", ",", "newpos", "=", "self", ".", "_readuie", "(", "0", ")", "if", "value", "is", "None", "or", "newpos", "!=", "self", ".", "len", ":", "raise", "ReadError", "except", "ReadError", ":", "raise", "InterpretError", "(", "\"Bitstring is not a single interleaved exponential-Golomb code.\"", ")", "return", "value" ]
Return data as unsigned interleaved exponential-Golomb code. Raises InterpretError if bitstring is not a single exponential-Golomb code.
[ "Return", "data", "as", "unsigned", "interleaved", "exponential", "-", "Golomb", "code", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1748-L1760
train
scott-griffiths/bitstring
bitstring.py
Bits._setsie
def _setsie(self, i): """Initialise bitstring with signed interleaved exponential-Golomb code for integer i.""" if not i: self._setbin_unsafe('1') else: self._setuie(abs(i)) self._append(Bits([i < 0]))
python
def _setsie(self, i): """Initialise bitstring with signed interleaved exponential-Golomb code for integer i.""" if not i: self._setbin_unsafe('1') else: self._setuie(abs(i)) self._append(Bits([i < 0]))
[ "def", "_setsie", "(", "self", ",", "i", ")", ":", "if", "not", "i", ":", "self", ".", "_setbin_unsafe", "(", "'1'", ")", "else", ":", "self", ".", "_setuie", "(", "abs", "(", "i", ")", ")", "self", ".", "_append", "(", "Bits", "(", "[", "i", "<", "0", "]", ")", ")" ]
Initialise bitstring with signed interleaved exponential-Golomb code for integer i.
[ "Initialise", "bitstring", "with", "signed", "interleaved", "exponential", "-", "Golomb", "code", "for", "integer", "i", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1762-L1768
train
scott-griffiths/bitstring
bitstring.py
Bits._getsie
def _getsie(self): """Return data as signed interleaved exponential-Golomb code. Raises InterpretError if bitstring is not a single exponential-Golomb code. """ try: value, newpos = self._readsie(0) if value is None or newpos != self.len: raise ReadError except ReadError: raise InterpretError("Bitstring is not a single interleaved exponential-Golomb code.") return value
python
def _getsie(self): """Return data as signed interleaved exponential-Golomb code. Raises InterpretError if bitstring is not a single exponential-Golomb code. """ try: value, newpos = self._readsie(0) if value is None or newpos != self.len: raise ReadError except ReadError: raise InterpretError("Bitstring is not a single interleaved exponential-Golomb code.") return value
[ "def", "_getsie", "(", "self", ")", ":", "try", ":", "value", ",", "newpos", "=", "self", ".", "_readsie", "(", "0", ")", "if", "value", "is", "None", "or", "newpos", "!=", "self", ".", "len", ":", "raise", "ReadError", "except", "ReadError", ":", "raise", "InterpretError", "(", "\"Bitstring is not a single interleaved exponential-Golomb code.\"", ")", "return", "value" ]
Return data as signed interleaved exponential-Golomb code. Raises InterpretError if bitstring is not a single exponential-Golomb code.
[ "Return", "data", "as", "signed", "interleaved", "exponential", "-", "Golomb", "code", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1770-L1782
train
scott-griffiths/bitstring
bitstring.py
Bits._readsie
def _readsie(self, pos): """Return interpretation of next bits as a signed interleaved exponential-Golomb code. Advances position to after the read code. Raises ReadError if the end of the bitstring is encountered while reading the code. """ codenum, pos = self._readuie(pos) if not codenum: return 0, pos try: if self[pos]: return -codenum, pos + 1 else: return codenum, pos + 1 except IndexError: raise ReadError("Read off end of bitstring trying to read code.")
python
def _readsie(self, pos): """Return interpretation of next bits as a signed interleaved exponential-Golomb code. Advances position to after the read code. Raises ReadError if the end of the bitstring is encountered while reading the code. """ codenum, pos = self._readuie(pos) if not codenum: return 0, pos try: if self[pos]: return -codenum, pos + 1 else: return codenum, pos + 1 except IndexError: raise ReadError("Read off end of bitstring trying to read code.")
[ "def", "_readsie", "(", "self", ",", "pos", ")", ":", "codenum", ",", "pos", "=", "self", ".", "_readuie", "(", "pos", ")", "if", "not", "codenum", ":", "return", "0", ",", "pos", "try", ":", "if", "self", "[", "pos", "]", ":", "return", "-", "codenum", ",", "pos", "+", "1", "else", ":", "return", "codenum", ",", "pos", "+", "1", "except", "IndexError", ":", "raise", "ReadError", "(", "\"Read off end of bitstring trying to read code.\"", ")" ]
Return interpretation of next bits as a signed interleaved exponential-Golomb code. Advances position to after the read code. Raises ReadError if the end of the bitstring is encountered while reading the code.
[ "Return", "interpretation", "of", "next", "bits", "as", "a", "signed", "interleaved", "exponential", "-", "Golomb", "code", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1784-L1802
train
scott-griffiths/bitstring
bitstring.py
Bits._setbin_safe
def _setbin_safe(self, binstring): """Reset the bitstring to the value given in binstring.""" binstring = tidy_input_string(binstring) # remove any 0b if present binstring = binstring.replace('0b', '') self._setbin_unsafe(binstring)
python
def _setbin_safe(self, binstring): """Reset the bitstring to the value given in binstring.""" binstring = tidy_input_string(binstring) # remove any 0b if present binstring = binstring.replace('0b', '') self._setbin_unsafe(binstring)
[ "def", "_setbin_safe", "(", "self", ",", "binstring", ")", ":", "binstring", "=", "tidy_input_string", "(", "binstring", ")", "# remove any 0b if present", "binstring", "=", "binstring", ".", "replace", "(", "'0b'", ",", "''", ")", "self", ".", "_setbin_unsafe", "(", "binstring", ")" ]
Reset the bitstring to the value given in binstring.
[ "Reset", "the", "bitstring", "to", "the", "value", "given", "in", "binstring", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1823-L1828
train
scott-griffiths/bitstring
bitstring.py
Bits._setbin_unsafe
def _setbin_unsafe(self, binstring): """Same as _setbin_safe, but input isn't sanity checked. binstring mustn't start with '0b'.""" length = len(binstring) # pad with zeros up to byte boundary if needed boundary = ((length + 7) // 8) * 8 padded_binstring = binstring + '0' * (boundary - length)\ if len(binstring) < boundary else binstring try: bytelist = [int(padded_binstring[x:x + 8], 2) for x in xrange(0, len(padded_binstring), 8)] except ValueError: raise CreationError("Invalid character in bin initialiser {0}.", binstring) self._setbytes_unsafe(bytearray(bytelist), length, 0)
python
def _setbin_unsafe(self, binstring): """Same as _setbin_safe, but input isn't sanity checked. binstring mustn't start with '0b'.""" length = len(binstring) # pad with zeros up to byte boundary if needed boundary = ((length + 7) // 8) * 8 padded_binstring = binstring + '0' * (boundary - length)\ if len(binstring) < boundary else binstring try: bytelist = [int(padded_binstring[x:x + 8], 2) for x in xrange(0, len(padded_binstring), 8)] except ValueError: raise CreationError("Invalid character in bin initialiser {0}.", binstring) self._setbytes_unsafe(bytearray(bytelist), length, 0)
[ "def", "_setbin_unsafe", "(", "self", ",", "binstring", ")", ":", "length", "=", "len", "(", "binstring", ")", "# pad with zeros up to byte boundary if needed", "boundary", "=", "(", "(", "length", "+", "7", ")", "//", "8", ")", "*", "8", "padded_binstring", "=", "binstring", "+", "'0'", "*", "(", "boundary", "-", "length", ")", "if", "len", "(", "binstring", ")", "<", "boundary", "else", "binstring", "try", ":", "bytelist", "=", "[", "int", "(", "padded_binstring", "[", "x", ":", "x", "+", "8", "]", ",", "2", ")", "for", "x", "in", "xrange", "(", "0", ",", "len", "(", "padded_binstring", ")", ",", "8", ")", "]", "except", "ValueError", ":", "raise", "CreationError", "(", "\"Invalid character in bin initialiser {0}.\"", ",", "binstring", ")", "self", ".", "_setbytes_unsafe", "(", "bytearray", "(", "bytelist", ")", ",", "length", ",", "0", ")" ]
Same as _setbin_safe, but input isn't sanity checked. binstring mustn't start with '0b'.
[ "Same", "as", "_setbin_safe", "but", "input", "isn", "t", "sanity", "checked", ".", "binstring", "mustn", "t", "start", "with", "0b", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1830-L1842
train
scott-griffiths/bitstring
bitstring.py
Bits._readbin
def _readbin(self, length, start): """Read bits and interpret as a binary string.""" 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]
python
def _readbin(self, length, start): """Read bits and interpret as a binary string.""" 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]
[ "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", "]" ]
Read bits and interpret as a binary string.
[ "Read", "bits", "and", "interpret", "as", "a", "binary", "string", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1844-L1859
train
scott-griffiths/bitstring
bitstring.py
Bits._setoct
def _setoct(self, octstring): """Reset the bitstring to have the value given in octstring.""" octstring = tidy_input_string(octstring) # remove any 0o if present octstring = octstring.replace('0o', '') binlist = [] for i in octstring: try: if not 0 <= int(i) < 8: raise ValueError binlist.append(OCT_TO_BITS[int(i)]) except ValueError: raise CreationError("Invalid symbol '{0}' in oct initialiser.", i) self._setbin_unsafe(''.join(binlist))
python
def _setoct(self, octstring): """Reset the bitstring to have the value given in octstring.""" octstring = tidy_input_string(octstring) # remove any 0o if present octstring = octstring.replace('0o', '') binlist = [] for i in octstring: try: if not 0 <= int(i) < 8: raise ValueError binlist.append(OCT_TO_BITS[int(i)]) except ValueError: raise CreationError("Invalid symbol '{0}' in oct initialiser.", i) self._setbin_unsafe(''.join(binlist))
[ "def", "_setoct", "(", "self", ",", "octstring", ")", ":", "octstring", "=", "tidy_input_string", "(", "octstring", ")", "# remove any 0o if present", "octstring", "=", "octstring", ".", "replace", "(", "'0o'", ",", "''", ")", "binlist", "=", "[", "]", "for", "i", "in", "octstring", ":", "try", ":", "if", "not", "0", "<=", "int", "(", "i", ")", "<", "8", ":", "raise", "ValueError", "binlist", ".", "append", "(", "OCT_TO_BITS", "[", "int", "(", "i", ")", "]", ")", "except", "ValueError", ":", "raise", "CreationError", "(", "\"Invalid symbol '{0}' in oct initialiser.\"", ",", "i", ")", "self", ".", "_setbin_unsafe", "(", "''", ".", "join", "(", "binlist", ")", ")" ]
Reset the bitstring to have the value given in octstring.
[ "Reset", "the", "bitstring", "to", "have", "the", "value", "given", "in", "octstring", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1865-L1878
train
scott-griffiths/bitstring
bitstring.py
Bits._readoct
def _readoct(self, length, start): """Read bits and interpret as an octal string.""" if length % 3: raise InterpretError("Cannot convert to octal unambiguously - " "not multiple of 3 bits.") if not length: return '' # Get main octal bit by converting from int. # Strip starting 0 or 0o depending on Python version. end = oct(self._readuint(length, start))[LEADING_OCT_CHARS:] if end.endswith('L'): end = end[:-1] middle = '0' * (length // 3 - len(end)) return middle + end
python
def _readoct(self, length, start): """Read bits and interpret as an octal string.""" if length % 3: raise InterpretError("Cannot convert to octal unambiguously - " "not multiple of 3 bits.") if not length: return '' # Get main octal bit by converting from int. # Strip starting 0 or 0o depending on Python version. end = oct(self._readuint(length, start))[LEADING_OCT_CHARS:] if end.endswith('L'): end = end[:-1] middle = '0' * (length // 3 - len(end)) return middle + end
[ "def", "_readoct", "(", "self", ",", "length", ",", "start", ")", ":", "if", "length", "%", "3", ":", "raise", "InterpretError", "(", "\"Cannot convert to octal unambiguously - \"", "\"not multiple of 3 bits.\"", ")", "if", "not", "length", ":", "return", "''", "# Get main octal bit by converting from int.", "# Strip starting 0 or 0o depending on Python version.", "end", "=", "oct", "(", "self", ".", "_readuint", "(", "length", ",", "start", ")", ")", "[", "LEADING_OCT_CHARS", ":", "]", "if", "end", ".", "endswith", "(", "'L'", ")", ":", "end", "=", "end", "[", ":", "-", "1", "]", "middle", "=", "'0'", "*", "(", "length", "//", "3", "-", "len", "(", "end", ")", ")", "return", "middle", "+", "end" ]
Read bits and interpret as an octal string.
[ "Read", "bits", "and", "interpret", "as", "an", "octal", "string", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1880-L1893
train
scott-griffiths/bitstring
bitstring.py
Bits._sethex
def _sethex(self, hexstring): """Reset the bitstring to have the value given in hexstring.""" hexstring = tidy_input_string(hexstring) # remove any 0x if present hexstring = hexstring.replace('0x', '') length = len(hexstring) if length % 2: hexstring += '0' try: try: data = bytearray.fromhex(hexstring) except TypeError: # Python 2.6 needs a unicode string (a bug). 2.7 and 3.x work fine. data = bytearray.fromhex(unicode(hexstring)) except ValueError: raise CreationError("Invalid symbol in hex initialiser.") self._setbytes_unsafe(data, length * 4, 0)
python
def _sethex(self, hexstring): """Reset the bitstring to have the value given in hexstring.""" hexstring = tidy_input_string(hexstring) # remove any 0x if present hexstring = hexstring.replace('0x', '') length = len(hexstring) if length % 2: hexstring += '0' try: try: data = bytearray.fromhex(hexstring) except TypeError: # Python 2.6 needs a unicode string (a bug). 2.7 and 3.x work fine. data = bytearray.fromhex(unicode(hexstring)) except ValueError: raise CreationError("Invalid symbol in hex initialiser.") self._setbytes_unsafe(data, length * 4, 0)
[ "def", "_sethex", "(", "self", ",", "hexstring", ")", ":", "hexstring", "=", "tidy_input_string", "(", "hexstring", ")", "# remove any 0x if present", "hexstring", "=", "hexstring", ".", "replace", "(", "'0x'", ",", "''", ")", "length", "=", "len", "(", "hexstring", ")", "if", "length", "%", "2", ":", "hexstring", "+=", "'0'", "try", ":", "try", ":", "data", "=", "bytearray", ".", "fromhex", "(", "hexstring", ")", "except", "TypeError", ":", "# Python 2.6 needs a unicode string (a bug). 2.7 and 3.x work fine.", "data", "=", "bytearray", ".", "fromhex", "(", "unicode", "(", "hexstring", ")", ")", "except", "ValueError", ":", "raise", "CreationError", "(", "\"Invalid symbol in hex initialiser.\"", ")", "self", ".", "_setbytes_unsafe", "(", "data", ",", "length", "*", "4", ",", "0", ")" ]
Reset the bitstring to have the value given in hexstring.
[ "Reset", "the", "bitstring", "to", "have", "the", "value", "given", "in", "hexstring", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1899-L1915
train
scott-griffiths/bitstring
bitstring.py
Bits._readhex
def _readhex(self, length, start): """Read bits and interpret as a hex string.""" if length % 4: raise InterpretError("Cannot convert to hex unambiguously - " "not multiple of 4 bits.") if not length: return '' s = self._slice(start, start + length).tobytes() try: s = s.hex() # Available in Python 3.5 except AttributeError: # This monstrosity is the only thing I could get to work for both 2.6 and 3.1. # TODO: Is utf-8 really what we mean here? s = str(binascii.hexlify(s).decode('utf-8')) # If there's one nibble too many then cut it off return s[:-1] if (length // 4) % 2 else s
python
def _readhex(self, length, start): """Read bits and interpret as a hex string.""" if length % 4: raise InterpretError("Cannot convert to hex unambiguously - " "not multiple of 4 bits.") if not length: return '' s = self._slice(start, start + length).tobytes() try: s = s.hex() # Available in Python 3.5 except AttributeError: # This monstrosity is the only thing I could get to work for both 2.6 and 3.1. # TODO: Is utf-8 really what we mean here? s = str(binascii.hexlify(s).decode('utf-8')) # If there's one nibble too many then cut it off return s[:-1] if (length // 4) % 2 else s
[ "def", "_readhex", "(", "self", ",", "length", ",", "start", ")", ":", "if", "length", "%", "4", ":", "raise", "InterpretError", "(", "\"Cannot convert to hex unambiguously - \"", "\"not multiple of 4 bits.\"", ")", "if", "not", "length", ":", "return", "''", "s", "=", "self", ".", "_slice", "(", "start", ",", "start", "+", "length", ")", ".", "tobytes", "(", ")", "try", ":", "s", "=", "s", ".", "hex", "(", ")", "# Available in Python 3.5", "except", "AttributeError", ":", "# This monstrosity is the only thing I could get to work for both 2.6 and 3.1.", "# TODO: Is utf-8 really what we mean here?", "s", "=", "str", "(", "binascii", ".", "hexlify", "(", "s", ")", ".", "decode", "(", "'utf-8'", ")", ")", "# If there's one nibble too many then cut it off", "return", "s", "[", ":", "-", "1", "]", "if", "(", "length", "//", "4", ")", "%", "2", "else", "s" ]
Read bits and interpret as a hex string.
[ "Read", "bits", "and", "interpret", "as", "a", "hex", "string", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1917-L1932
train
scott-griffiths/bitstring
bitstring.py
Bits._ensureinmemory
def _ensureinmemory(self): """Ensure the data is held in memory, not in a file.""" self._setbytes_unsafe(self._datastore.getbyteslice(0, self._datastore.bytelength), self.len, self._offset)
python
def _ensureinmemory(self): """Ensure the data is held in memory, not in a file.""" self._setbytes_unsafe(self._datastore.getbyteslice(0, self._datastore.bytelength), self.len, self._offset)
[ "def", "_ensureinmemory", "(", "self", ")", ":", "self", ".", "_setbytes_unsafe", "(", "self", ".", "_datastore", ".", "getbyteslice", "(", "0", ",", "self", ".", "_datastore", ".", "bytelength", ")", ",", "self", ".", "len", ",", "self", ".", "_offset", ")" ]
Ensure the data is held in memory, not in a file.
[ "Ensure", "the", "data", "is", "held", "in", "memory", "not", "in", "a", "file", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1949-L1952
train
scott-griffiths/bitstring
bitstring.py
Bits._converttobitstring
def _converttobitstring(cls, bs, offset=0, cache={}): """Convert bs to a bitstring and return it. offset gives the suggested bit offset of first significant bit, to optimise append etc. """ if isinstance(bs, Bits): return bs try: return cache[(bs, offset)] except KeyError: if isinstance(bs, basestring): b = cls() try: _, tokens = tokenparser(bs) except ValueError as e: raise CreationError(*e.args) if tokens: b._append(Bits._init_with_token(*tokens[0])) b._datastore = offsetcopy(b._datastore, offset) for token in tokens[1:]: b._append(Bits._init_with_token(*token)) assert b._assertsanity() assert b.len == 0 or b._offset == offset if len(cache) < CACHE_SIZE: cache[(bs, offset)] = b return b except TypeError: # Unhashable type pass return cls(bs)
python
def _converttobitstring(cls, bs, offset=0, cache={}): """Convert bs to a bitstring and return it. offset gives the suggested bit offset of first significant bit, to optimise append etc. """ if isinstance(bs, Bits): return bs try: return cache[(bs, offset)] except KeyError: if isinstance(bs, basestring): b = cls() try: _, tokens = tokenparser(bs) except ValueError as e: raise CreationError(*e.args) if tokens: b._append(Bits._init_with_token(*tokens[0])) b._datastore = offsetcopy(b._datastore, offset) for token in tokens[1:]: b._append(Bits._init_with_token(*token)) assert b._assertsanity() assert b.len == 0 or b._offset == offset if len(cache) < CACHE_SIZE: cache[(bs, offset)] = b return b except TypeError: # Unhashable type pass return cls(bs)
[ "def", "_converttobitstring", "(", "cls", ",", "bs", ",", "offset", "=", "0", ",", "cache", "=", "{", "}", ")", ":", "if", "isinstance", "(", "bs", ",", "Bits", ")", ":", "return", "bs", "try", ":", "return", "cache", "[", "(", "bs", ",", "offset", ")", "]", "except", "KeyError", ":", "if", "isinstance", "(", "bs", ",", "basestring", ")", ":", "b", "=", "cls", "(", ")", "try", ":", "_", ",", "tokens", "=", "tokenparser", "(", "bs", ")", "except", "ValueError", "as", "e", ":", "raise", "CreationError", "(", "*", "e", ".", "args", ")", "if", "tokens", ":", "b", ".", "_append", "(", "Bits", ".", "_init_with_token", "(", "*", "tokens", "[", "0", "]", ")", ")", "b", ".", "_datastore", "=", "offsetcopy", "(", "b", ".", "_datastore", ",", "offset", ")", "for", "token", "in", "tokens", "[", "1", ":", "]", ":", "b", ".", "_append", "(", "Bits", ".", "_init_with_token", "(", "*", "token", ")", ")", "assert", "b", ".", "_assertsanity", "(", ")", "assert", "b", ".", "len", "==", "0", "or", "b", ".", "_offset", "==", "offset", "if", "len", "(", "cache", ")", "<", "CACHE_SIZE", ":", "cache", "[", "(", "bs", ",", "offset", ")", "]", "=", "b", "return", "b", "except", "TypeError", ":", "# Unhashable type", "pass", "return", "cls", "(", "bs", ")" ]
Convert bs to a bitstring and return it. offset gives the suggested bit offset of first significant bit, to optimise append etc.
[ "Convert", "bs", "to", "a", "bitstring", "and", "return", "it", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1955-L1986
train
scott-griffiths/bitstring
bitstring.py
Bits._slice
def _slice(self, start, end): """Used internally to get a slice, without error checking.""" if end == start: return self.__class__() offset = self._offset startbyte, newoffset = divmod(start + offset, 8) endbyte = (end + offset - 1) // 8 bs = self.__class__() bs._setbytes_unsafe(self._datastore.getbyteslice(startbyte, endbyte + 1), end - start, newoffset) return bs
python
def _slice(self, start, end): """Used internally to get a slice, without error checking.""" if end == start: return self.__class__() offset = self._offset startbyte, newoffset = divmod(start + offset, 8) endbyte = (end + offset - 1) // 8 bs = self.__class__() bs._setbytes_unsafe(self._datastore.getbyteslice(startbyte, endbyte + 1), end - start, newoffset) return bs
[ "def", "_slice", "(", "self", ",", "start", ",", "end", ")", ":", "if", "end", "==", "start", ":", "return", "self", ".", "__class__", "(", ")", "offset", "=", "self", ".", "_offset", "startbyte", ",", "newoffset", "=", "divmod", "(", "start", "+", "offset", ",", "8", ")", "endbyte", "=", "(", "end", "+", "offset", "-", "1", ")", "//", "8", "bs", "=", "self", ".", "__class__", "(", ")", "bs", ".", "_setbytes_unsafe", "(", "self", ".", "_datastore", ".", "getbyteslice", "(", "startbyte", ",", "endbyte", "+", "1", ")", ",", "end", "-", "start", ",", "newoffset", ")", "return", "bs" ]
Used internally to get a slice, without error checking.
[ "Used", "internally", "to", "get", "a", "slice", "without", "error", "checking", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1995-L2004
train
scott-griffiths/bitstring
bitstring.py
Bits._readtoken
def _readtoken(self, name, pos, length): """Reads a token from the bitstring and returns the result.""" if length is not None and int(length) > self.length - pos: raise ReadError("Reading off the end of the data. " "Tried to read {0} bits when only {1} available.".format(int(length), self.length - pos)) try: val = name_to_read[name](self, length, pos) return val, pos + length except KeyError: if name == 'pad': return None, pos + length raise ValueError("Can't parse token {0}:{1}".format(name, length)) except TypeError: # This is for the 'ue', 'se' and 'bool' tokens. They will also return the new pos. return name_to_read[name](self, pos)
python
def _readtoken(self, name, pos, length): """Reads a token from the bitstring and returns the result.""" if length is not None and int(length) > self.length - pos: raise ReadError("Reading off the end of the data. " "Tried to read {0} bits when only {1} available.".format(int(length), self.length - pos)) try: val = name_to_read[name](self, length, pos) return val, pos + length except KeyError: if name == 'pad': return None, pos + length raise ValueError("Can't parse token {0}:{1}".format(name, length)) except TypeError: # This is for the 'ue', 'se' and 'bool' tokens. They will also return the new pos. return name_to_read[name](self, pos)
[ "def", "_readtoken", "(", "self", ",", "name", ",", "pos", ",", "length", ")", ":", "if", "length", "is", "not", "None", "and", "int", "(", "length", ")", ">", "self", ".", "length", "-", "pos", ":", "raise", "ReadError", "(", "\"Reading off the end of the data. \"", "\"Tried to read {0} bits when only {1} available.\"", ".", "format", "(", "int", "(", "length", ")", ",", "self", ".", "length", "-", "pos", ")", ")", "try", ":", "val", "=", "name_to_read", "[", "name", "]", "(", "self", ",", "length", ",", "pos", ")", "return", "val", ",", "pos", "+", "length", "except", "KeyError", ":", "if", "name", "==", "'pad'", ":", "return", "None", ",", "pos", "+", "length", "raise", "ValueError", "(", "\"Can't parse token {0}:{1}\"", ".", "format", "(", "name", ",", "length", ")", ")", "except", "TypeError", ":", "# This is for the 'ue', 'se' and 'bool' tokens. They will also return the new pos.", "return", "name_to_read", "[", "name", "]", "(", "self", ",", "pos", ")" ]
Reads a token from the bitstring and returns the result.
[ "Reads", "a", "token", "from", "the", "bitstring", "and", "returns", "the", "result", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2006-L2020
train
scott-griffiths/bitstring
bitstring.py
Bits._reverse
def _reverse(self): """Reverse all bits in-place.""" # Reverse the contents of each byte n = [BYTE_REVERSAL_DICT[b] for b in self._datastore.rawbytes] # Then reverse the order of the bytes n.reverse() # The new offset is the number of bits that were unused at the end. newoffset = 8 - (self._offset + self.len) % 8 if newoffset == 8: newoffset = 0 self._setbytes_unsafe(bytearray().join(n), self.length, newoffset)
python
def _reverse(self): """Reverse all bits in-place.""" # Reverse the contents of each byte n = [BYTE_REVERSAL_DICT[b] for b in self._datastore.rawbytes] # Then reverse the order of the bytes n.reverse() # The new offset is the number of bits that were unused at the end. newoffset = 8 - (self._offset + self.len) % 8 if newoffset == 8: newoffset = 0 self._setbytes_unsafe(bytearray().join(n), self.length, newoffset)
[ "def", "_reverse", "(", "self", ")", ":", "# Reverse the contents of each byte", "n", "=", "[", "BYTE_REVERSAL_DICT", "[", "b", "]", "for", "b", "in", "self", ".", "_datastore", ".", "rawbytes", "]", "# Then reverse the order of the bytes", "n", ".", "reverse", "(", ")", "# The new offset is the number of bits that were unused at the end.", "newoffset", "=", "8", "-", "(", "self", ".", "_offset", "+", "self", ".", "len", ")", "%", "8", "if", "newoffset", "==", "8", ":", "newoffset", "=", "0", "self", ".", "_setbytes_unsafe", "(", "bytearray", "(", ")", ".", "join", "(", "n", ")", ",", "self", ".", "length", ",", "newoffset", ")" ]
Reverse all bits in-place.
[ "Reverse", "all", "bits", "in", "-", "place", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2030-L2040
train
scott-griffiths/bitstring
bitstring.py
Bits._truncateend
def _truncateend(self, bits): """Truncate bits from the end of the bitstring.""" assert 0 <= bits <= self.len if not bits: return if bits == self.len: self._clear() return newlength_in_bytes = (self._offset + self.len - bits + 7) // 8 self._setbytes_unsafe(self._datastore.getbyteslice(0, newlength_in_bytes), self.len - bits, self._offset) assert self._assertsanity()
python
def _truncateend(self, bits): """Truncate bits from the end of the bitstring.""" assert 0 <= bits <= self.len if not bits: return if bits == self.len: self._clear() return newlength_in_bytes = (self._offset + self.len - bits + 7) // 8 self._setbytes_unsafe(self._datastore.getbyteslice(0, newlength_in_bytes), self.len - bits, self._offset) assert self._assertsanity()
[ "def", "_truncateend", "(", "self", ",", "bits", ")", ":", "assert", "0", "<=", "bits", "<=", "self", ".", "len", "if", "not", "bits", ":", "return", "if", "bits", "==", "self", ".", "len", ":", "self", ".", "_clear", "(", ")", "return", "newlength_in_bytes", "=", "(", "self", ".", "_offset", "+", "self", ".", "len", "-", "bits", "+", "7", ")", "//", "8", "self", ".", "_setbytes_unsafe", "(", "self", ".", "_datastore", ".", "getbyteslice", "(", "0", ",", "newlength_in_bytes", ")", ",", "self", ".", "len", "-", "bits", ",", "self", ".", "_offset", ")", "assert", "self", ".", "_assertsanity", "(", ")" ]
Truncate bits from the end of the bitstring.
[ "Truncate", "bits", "from", "the", "end", "of", "the", "bitstring", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2055-L2066
train
scott-griffiths/bitstring
bitstring.py
Bits._insert
def _insert(self, bs, pos): """Insert bs at pos.""" assert 0 <= pos <= self.len if pos > self.len // 2: # Inserting nearer end, so cut off end. end = self._slice(pos, self.len) self._truncateend(self.len - pos) self._append(bs) self._append(end) else: # Inserting nearer start, so cut off start. start = self._slice(0, pos) self._truncatestart(pos) self._prepend(bs) self._prepend(start) try: self._pos = pos + bs.len except AttributeError: pass assert self._assertsanity()
python
def _insert(self, bs, pos): """Insert bs at pos.""" assert 0 <= pos <= self.len if pos > self.len // 2: # Inserting nearer end, so cut off end. end = self._slice(pos, self.len) self._truncateend(self.len - pos) self._append(bs) self._append(end) else: # Inserting nearer start, so cut off start. start = self._slice(0, pos) self._truncatestart(pos) self._prepend(bs) self._prepend(start) try: self._pos = pos + bs.len except AttributeError: pass assert self._assertsanity()
[ "def", "_insert", "(", "self", ",", "bs", ",", "pos", ")", ":", "assert", "0", "<=", "pos", "<=", "self", ".", "len", "if", "pos", ">", "self", ".", "len", "//", "2", ":", "# Inserting nearer end, so cut off end.", "end", "=", "self", ".", "_slice", "(", "pos", ",", "self", ".", "len", ")", "self", ".", "_truncateend", "(", "self", ".", "len", "-", "pos", ")", "self", ".", "_append", "(", "bs", ")", "self", ".", "_append", "(", "end", ")", "else", ":", "# Inserting nearer start, so cut off start.", "start", "=", "self", ".", "_slice", "(", "0", ",", "pos", ")", "self", ".", "_truncatestart", "(", "pos", ")", "self", ".", "_prepend", "(", "bs", ")", "self", ".", "_prepend", "(", "start", ")", "try", ":", "self", ".", "_pos", "=", "pos", "+", "bs", ".", "len", "except", "AttributeError", ":", "pass", "assert", "self", ".", "_assertsanity", "(", ")" ]
Insert bs at pos.
[ "Insert", "bs", "at", "pos", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2068-L2087
train
scott-griffiths/bitstring
bitstring.py
Bits._overwrite
def _overwrite(self, bs, pos): """Overwrite with bs at pos.""" assert 0 <= pos < self.len if bs is self: # Just overwriting with self, so do nothing. assert pos == 0 return firstbytepos = (self._offset + pos) // 8 lastbytepos = (self._offset + pos + bs.len - 1) // 8 bytepos, bitoffset = divmod(self._offset + pos, 8) if firstbytepos == lastbytepos: mask = ((1 << bs.len) - 1) << (8 - bs.len - bitoffset) self._datastore.setbyte(bytepos, self._datastore.getbyte(bytepos) & (~mask)) d = offsetcopy(bs._datastore, bitoffset) self._datastore.setbyte(bytepos, self._datastore.getbyte(bytepos) | (d.getbyte(0) & mask)) else: # Do first byte mask = (1 << (8 - bitoffset)) - 1 self._datastore.setbyte(bytepos, self._datastore.getbyte(bytepos) & (~mask)) d = offsetcopy(bs._datastore, bitoffset) self._datastore.setbyte(bytepos, self._datastore.getbyte(bytepos) | (d.getbyte(0) & mask)) # Now do all the full bytes self._datastore.setbyteslice(firstbytepos + 1, lastbytepos, d.getbyteslice(1, lastbytepos - firstbytepos)) # and finally the last byte bitsleft = (self._offset + pos + bs.len) % 8 if not bitsleft: bitsleft = 8 mask = (1 << (8 - bitsleft)) - 1 self._datastore.setbyte(lastbytepos, self._datastore.getbyte(lastbytepos) & mask) self._datastore.setbyte(lastbytepos, self._datastore.getbyte(lastbytepos) | (d.getbyte(d.bytelength - 1) & ~mask)) assert self._assertsanity()
python
def _overwrite(self, bs, pos): """Overwrite with bs at pos.""" assert 0 <= pos < self.len if bs is self: # Just overwriting with self, so do nothing. assert pos == 0 return firstbytepos = (self._offset + pos) // 8 lastbytepos = (self._offset + pos + bs.len - 1) // 8 bytepos, bitoffset = divmod(self._offset + pos, 8) if firstbytepos == lastbytepos: mask = ((1 << bs.len) - 1) << (8 - bs.len - bitoffset) self._datastore.setbyte(bytepos, self._datastore.getbyte(bytepos) & (~mask)) d = offsetcopy(bs._datastore, bitoffset) self._datastore.setbyte(bytepos, self._datastore.getbyte(bytepos) | (d.getbyte(0) & mask)) else: # Do first byte mask = (1 << (8 - bitoffset)) - 1 self._datastore.setbyte(bytepos, self._datastore.getbyte(bytepos) & (~mask)) d = offsetcopy(bs._datastore, bitoffset) self._datastore.setbyte(bytepos, self._datastore.getbyte(bytepos) | (d.getbyte(0) & mask)) # Now do all the full bytes self._datastore.setbyteslice(firstbytepos + 1, lastbytepos, d.getbyteslice(1, lastbytepos - firstbytepos)) # and finally the last byte bitsleft = (self._offset + pos + bs.len) % 8 if not bitsleft: bitsleft = 8 mask = (1 << (8 - bitsleft)) - 1 self._datastore.setbyte(lastbytepos, self._datastore.getbyte(lastbytepos) & mask) self._datastore.setbyte(lastbytepos, self._datastore.getbyte(lastbytepos) | (d.getbyte(d.bytelength - 1) & ~mask)) assert self._assertsanity()
[ "def", "_overwrite", "(", "self", ",", "bs", ",", "pos", ")", ":", "assert", "0", "<=", "pos", "<", "self", ".", "len", "if", "bs", "is", "self", ":", "# Just overwriting with self, so do nothing.", "assert", "pos", "==", "0", "return", "firstbytepos", "=", "(", "self", ".", "_offset", "+", "pos", ")", "//", "8", "lastbytepos", "=", "(", "self", ".", "_offset", "+", "pos", "+", "bs", ".", "len", "-", "1", ")", "//", "8", "bytepos", ",", "bitoffset", "=", "divmod", "(", "self", ".", "_offset", "+", "pos", ",", "8", ")", "if", "firstbytepos", "==", "lastbytepos", ":", "mask", "=", "(", "(", "1", "<<", "bs", ".", "len", ")", "-", "1", ")", "<<", "(", "8", "-", "bs", ".", "len", "-", "bitoffset", ")", "self", ".", "_datastore", ".", "setbyte", "(", "bytepos", ",", "self", ".", "_datastore", ".", "getbyte", "(", "bytepos", ")", "&", "(", "~", "mask", ")", ")", "d", "=", "offsetcopy", "(", "bs", ".", "_datastore", ",", "bitoffset", ")", "self", ".", "_datastore", ".", "setbyte", "(", "bytepos", ",", "self", ".", "_datastore", ".", "getbyte", "(", "bytepos", ")", "|", "(", "d", ".", "getbyte", "(", "0", ")", "&", "mask", ")", ")", "else", ":", "# Do first byte", "mask", "=", "(", "1", "<<", "(", "8", "-", "bitoffset", ")", ")", "-", "1", "self", ".", "_datastore", ".", "setbyte", "(", "bytepos", ",", "self", ".", "_datastore", ".", "getbyte", "(", "bytepos", ")", "&", "(", "~", "mask", ")", ")", "d", "=", "offsetcopy", "(", "bs", ".", "_datastore", ",", "bitoffset", ")", "self", ".", "_datastore", ".", "setbyte", "(", "bytepos", ",", "self", ".", "_datastore", ".", "getbyte", "(", "bytepos", ")", "|", "(", "d", ".", "getbyte", "(", "0", ")", "&", "mask", ")", ")", "# Now do all the full bytes", "self", ".", "_datastore", ".", "setbyteslice", "(", "firstbytepos", "+", "1", ",", "lastbytepos", ",", "d", ".", "getbyteslice", "(", "1", ",", "lastbytepos", "-", "firstbytepos", ")", ")", "# and finally the last byte", "bitsleft", "=", "(", "self", ".", "_offset", "+", "pos", "+", "bs", ".", "len", ")", "%", "8", "if", "not", "bitsleft", ":", "bitsleft", "=", "8", "mask", "=", "(", "1", "<<", "(", "8", "-", "bitsleft", ")", ")", "-", "1", "self", ".", "_datastore", ".", "setbyte", "(", "lastbytepos", ",", "self", ".", "_datastore", ".", "getbyte", "(", "lastbytepos", ")", "&", "mask", ")", "self", ".", "_datastore", ".", "setbyte", "(", "lastbytepos", ",", "self", ".", "_datastore", ".", "getbyte", "(", "lastbytepos", ")", "|", "(", "d", ".", "getbyte", "(", "d", ".", "bytelength", "-", "1", ")", "&", "~", "mask", ")", ")", "assert", "self", ".", "_assertsanity", "(", ")" ]
Overwrite with bs at pos.
[ "Overwrite", "with", "bs", "at", "pos", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2089-L2120
train
scott-griffiths/bitstring
bitstring.py
Bits._delete
def _delete(self, bits, pos): """Delete bits at pos.""" assert 0 <= pos <= self.len assert pos + bits <= self.len if not pos: # Cutting bits off at the start. self._truncatestart(bits) return if pos + bits == self.len: # Cutting bits off at the end. self._truncateend(bits) return if pos > self.len - pos - bits: # More bits before cut point than after it, so do bit shifting # on the final bits. end = self._slice(pos + bits, self.len) assert self.len - pos > 0 self._truncateend(self.len - pos) self._append(end) return # More bits after the cut point than before it. start = self._slice(0, pos) self._truncatestart(pos + bits) self._prepend(start) return
python
def _delete(self, bits, pos): """Delete bits at pos.""" assert 0 <= pos <= self.len assert pos + bits <= self.len if not pos: # Cutting bits off at the start. self._truncatestart(bits) return if pos + bits == self.len: # Cutting bits off at the end. self._truncateend(bits) return if pos > self.len - pos - bits: # More bits before cut point than after it, so do bit shifting # on the final bits. end = self._slice(pos + bits, self.len) assert self.len - pos > 0 self._truncateend(self.len - pos) self._append(end) return # More bits after the cut point than before it. start = self._slice(0, pos) self._truncatestart(pos + bits) self._prepend(start) return
[ "def", "_delete", "(", "self", ",", "bits", ",", "pos", ")", ":", "assert", "0", "<=", "pos", "<=", "self", ".", "len", "assert", "pos", "+", "bits", "<=", "self", ".", "len", "if", "not", "pos", ":", "# Cutting bits off at the start.", "self", ".", "_truncatestart", "(", "bits", ")", "return", "if", "pos", "+", "bits", "==", "self", ".", "len", ":", "# Cutting bits off at the end.", "self", ".", "_truncateend", "(", "bits", ")", "return", "if", "pos", ">", "self", ".", "len", "-", "pos", "-", "bits", ":", "# More bits before cut point than after it, so do bit shifting", "# on the final bits.", "end", "=", "self", ".", "_slice", "(", "pos", "+", "bits", ",", "self", ".", "len", ")", "assert", "self", ".", "len", "-", "pos", ">", "0", "self", ".", "_truncateend", "(", "self", ".", "len", "-", "pos", ")", "self", ".", "_append", "(", "end", ")", "return", "# More bits after the cut point than before it.", "start", "=", "self", ".", "_slice", "(", "0", ",", "pos", ")", "self", ".", "_truncatestart", "(", "pos", "+", "bits", ")", "self", ".", "_prepend", "(", "start", ")", "return" ]
Delete bits at pos.
[ "Delete", "bits", "at", "pos", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2122-L2146
train
scott-griffiths/bitstring
bitstring.py
Bits._reversebytes
def _reversebytes(self, start, end): """Reverse bytes in-place.""" # Make the start occur on a byte boundary # TODO: We could be cleverer here to avoid changing the offset. newoffset = 8 - (start % 8) if newoffset == 8: newoffset = 0 self._datastore = offsetcopy(self._datastore, newoffset) # Now just reverse the byte data toreverse = bytearray(self._datastore.getbyteslice((newoffset + start) // 8, (newoffset + end) // 8)) toreverse.reverse() self._datastore.setbyteslice((newoffset + start) // 8, (newoffset + end) // 8, toreverse)
python
def _reversebytes(self, start, end): """Reverse bytes in-place.""" # Make the start occur on a byte boundary # TODO: We could be cleverer here to avoid changing the offset. newoffset = 8 - (start % 8) if newoffset == 8: newoffset = 0 self._datastore = offsetcopy(self._datastore, newoffset) # Now just reverse the byte data toreverse = bytearray(self._datastore.getbyteslice((newoffset + start) // 8, (newoffset + end) // 8)) toreverse.reverse() self._datastore.setbyteslice((newoffset + start) // 8, (newoffset + end) // 8, toreverse)
[ "def", "_reversebytes", "(", "self", ",", "start", ",", "end", ")", ":", "# Make the start occur on a byte boundary", "# TODO: We could be cleverer here to avoid changing the offset.", "newoffset", "=", "8", "-", "(", "start", "%", "8", ")", "if", "newoffset", "==", "8", ":", "newoffset", "=", "0", "self", ".", "_datastore", "=", "offsetcopy", "(", "self", ".", "_datastore", ",", "newoffset", ")", "# Now just reverse the byte data", "toreverse", "=", "bytearray", "(", "self", ".", "_datastore", ".", "getbyteslice", "(", "(", "newoffset", "+", "start", ")", "//", "8", ",", "(", "newoffset", "+", "end", ")", "//", "8", ")", ")", "toreverse", ".", "reverse", "(", ")", "self", ".", "_datastore", ".", "setbyteslice", "(", "(", "newoffset", "+", "start", ")", "//", "8", ",", "(", "newoffset", "+", "end", ")", "//", "8", ",", "toreverse", ")" ]
Reverse bytes in-place.
[ "Reverse", "bytes", "in", "-", "place", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2148-L2159
train
scott-griffiths/bitstring
bitstring.py
Bits._set
def _set(self, pos): """Set bit at pos to 1.""" assert 0 <= pos < self.len self._datastore.setbit(pos)
python
def _set(self, pos): """Set bit at pos to 1.""" assert 0 <= pos < self.len self._datastore.setbit(pos)
[ "def", "_set", "(", "self", ",", "pos", ")", ":", "assert", "0", "<=", "pos", "<", "self", ".", "len", "self", ".", "_datastore", ".", "setbit", "(", "pos", ")" ]
Set bit at pos to 1.
[ "Set", "bit", "at", "pos", "to", "1", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2161-L2164
train
scott-griffiths/bitstring
bitstring.py
Bits._unset
def _unset(self, pos): """Set bit at pos to 0.""" assert 0 <= pos < self.len self._datastore.unsetbit(pos)
python
def _unset(self, pos): """Set bit at pos to 0.""" assert 0 <= pos < self.len self._datastore.unsetbit(pos)
[ "def", "_unset", "(", "self", ",", "pos", ")", ":", "assert", "0", "<=", "pos", "<", "self", ".", "len", "self", ".", "_datastore", ".", "unsetbit", "(", "pos", ")" ]
Set bit at pos to 0.
[ "Set", "bit", "at", "pos", "to", "0", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2166-L2169
train
scott-griffiths/bitstring
bitstring.py
Bits._invert_all
def _invert_all(self): """Invert every bit.""" set = self._datastore.setbyte get = self._datastore.getbyte for p in xrange(self._datastore.byteoffset, self._datastore.byteoffset + self._datastore.bytelength): set(p, 256 + ~get(p))
python
def _invert_all(self): """Invert every bit.""" set = self._datastore.setbyte get = self._datastore.getbyte for p in xrange(self._datastore.byteoffset, self._datastore.byteoffset + self._datastore.bytelength): set(p, 256 + ~get(p))
[ "def", "_invert_all", "(", "self", ")", ":", "set", "=", "self", ".", "_datastore", ".", "setbyte", "get", "=", "self", ".", "_datastore", ".", "getbyte", "for", "p", "in", "xrange", "(", "self", ".", "_datastore", ".", "byteoffset", ",", "self", ".", "_datastore", ".", "byteoffset", "+", "self", ".", "_datastore", ".", "bytelength", ")", ":", "set", "(", "p", ",", "256", "+", "~", "get", "(", "p", ")", ")" ]
Invert every bit.
[ "Invert", "every", "bit", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2176-L2181
train
scott-griffiths/bitstring
bitstring.py
Bits._ilshift
def _ilshift(self, n): """Shift bits by n to the left in place. Return self.""" assert 0 < n <= self.len self._append(Bits(n)) self._truncatestart(n) return self
python
def _ilshift(self, n): """Shift bits by n to the left in place. Return self.""" assert 0 < n <= self.len self._append(Bits(n)) self._truncatestart(n) return self
[ "def", "_ilshift", "(", "self", ",", "n", ")", ":", "assert", "0", "<", "n", "<=", "self", ".", "len", "self", ".", "_append", "(", "Bits", "(", "n", ")", ")", "self", ".", "_truncatestart", "(", "n", ")", "return", "self" ]
Shift bits by n to the left in place. Return self.
[ "Shift", "bits", "by", "n", "to", "the", "left", "in", "place", ".", "Return", "self", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2183-L2188
train
scott-griffiths/bitstring
bitstring.py
Bits._irshift
def _irshift(self, n): """Shift bits by n to the right in place. Return self.""" assert 0 < n <= self.len self._prepend(Bits(n)) self._truncateend(n) return self
python
def _irshift(self, n): """Shift bits by n to the right in place. Return self.""" assert 0 < n <= self.len self._prepend(Bits(n)) self._truncateend(n) return self
[ "def", "_irshift", "(", "self", ",", "n", ")", ":", "assert", "0", "<", "n", "<=", "self", ".", "len", "self", ".", "_prepend", "(", "Bits", "(", "n", ")", ")", "self", ".", "_truncateend", "(", "n", ")", "return", "self" ]
Shift bits by n to the right in place. Return self.
[ "Shift", "bits", "by", "n", "to", "the", "right", "in", "place", ".", "Return", "self", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2190-L2195
train
scott-griffiths/bitstring
bitstring.py
Bits._imul
def _imul(self, n): """Concatenate n copies of self in place. Return self.""" assert n >= 0 if not n: self._clear() return self m = 1 old_len = self.len while m * 2 < n: self._append(self) m *= 2 self._append(self[0:(n - m) * old_len]) return self
python
def _imul(self, n): """Concatenate n copies of self in place. Return self.""" assert n >= 0 if not n: self._clear() return self m = 1 old_len = self.len while m * 2 < n: self._append(self) m *= 2 self._append(self[0:(n - m) * old_len]) return self
[ "def", "_imul", "(", "self", ",", "n", ")", ":", "assert", "n", ">=", "0", "if", "not", "n", ":", "self", ".", "_clear", "(", ")", "return", "self", "m", "=", "1", "old_len", "=", "self", ".", "len", "while", "m", "*", "2", "<", "n", ":", "self", ".", "_append", "(", "self", ")", "m", "*=", "2", "self", ".", "_append", "(", "self", "[", "0", ":", "(", "n", "-", "m", ")", "*", "old_len", "]", ")", "return", "self" ]
Concatenate n copies of self in place. Return self.
[ "Concatenate", "n", "copies", "of", "self", "in", "place", ".", "Return", "self", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2197-L2209
train
scott-griffiths/bitstring
bitstring.py
Bits._validate_slice
def _validate_slice(self, start, end): """Validate start and end and return them as positive bit positions.""" if start is None: start = 0 elif start < 0: start += self.len if end is None: end = self.len elif end < 0: end += self.len if not 0 <= end <= self.len: raise ValueError("end is not a valid position in the bitstring.") if not 0 <= start <= self.len: raise ValueError("start is not a valid position in the bitstring.") if end < start: raise ValueError("end must not be less than start.") return start, end
python
def _validate_slice(self, start, end): """Validate start and end and return them as positive bit positions.""" if start is None: start = 0 elif start < 0: start += self.len if end is None: end = self.len elif end < 0: end += self.len if not 0 <= end <= self.len: raise ValueError("end is not a valid position in the bitstring.") if not 0 <= start <= self.len: raise ValueError("start is not a valid position in the bitstring.") if end < start: raise ValueError("end must not be less than start.") return start, end
[ "def", "_validate_slice", "(", "self", ",", "start", ",", "end", ")", ":", "if", "start", "is", "None", ":", "start", "=", "0", "elif", "start", "<", "0", ":", "start", "+=", "self", ".", "len", "if", "end", "is", "None", ":", "end", "=", "self", ".", "len", "elif", "end", "<", "0", ":", "end", "+=", "self", ".", "len", "if", "not", "0", "<=", "end", "<=", "self", ".", "len", ":", "raise", "ValueError", "(", "\"end is not a valid position in the bitstring.\"", ")", "if", "not", "0", "<=", "start", "<=", "self", ".", "len", ":", "raise", "ValueError", "(", "\"start is not a valid position in the bitstring.\"", ")", "if", "end", "<", "start", ":", "raise", "ValueError", "(", "\"end must not be less than start.\"", ")", "return", "start", ",", "end" ]
Validate start and end and return them as positive bit positions.
[ "Validate", "start", "and", "end", "and", "return", "them", "as", "positive", "bit", "positions", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2240-L2256
train
scott-griffiths/bitstring
bitstring.py
Bits._findbytes
def _findbytes(self, bytes_, start, end, bytealigned): """Quicker version of find when everything's whole byte and byte aligned. """ assert self._datastore.offset == 0 assert bytealigned is True # Extract data bytes from bitstring to be found. bytepos = (start + 7) // 8 found = False p = bytepos finalpos = end // 8 increment = max(1024, len(bytes_) * 10) buffersize = increment + len(bytes_) while p < finalpos: # Read in file or from memory in overlapping chunks and search the chunks. buf = bytearray(self._datastore.getbyteslice(p, min(p + buffersize, finalpos))) pos = buf.find(bytes_) if pos != -1: found = True p += pos break p += increment if not found: return () return (p * 8,)
python
def _findbytes(self, bytes_, start, end, bytealigned): """Quicker version of find when everything's whole byte and byte aligned. """ assert self._datastore.offset == 0 assert bytealigned is True # Extract data bytes from bitstring to be found. bytepos = (start + 7) // 8 found = False p = bytepos finalpos = end // 8 increment = max(1024, len(bytes_) * 10) buffersize = increment + len(bytes_) while p < finalpos: # Read in file or from memory in overlapping chunks and search the chunks. buf = bytearray(self._datastore.getbyteslice(p, min(p + buffersize, finalpos))) pos = buf.find(bytes_) if pos != -1: found = True p += pos break p += increment if not found: return () return (p * 8,)
[ "def", "_findbytes", "(", "self", ",", "bytes_", ",", "start", ",", "end", ",", "bytealigned", ")", ":", "assert", "self", ".", "_datastore", ".", "offset", "==", "0", "assert", "bytealigned", "is", "True", "# Extract data bytes from bitstring to be found.", "bytepos", "=", "(", "start", "+", "7", ")", "//", "8", "found", "=", "False", "p", "=", "bytepos", "finalpos", "=", "end", "//", "8", "increment", "=", "max", "(", "1024", ",", "len", "(", "bytes_", ")", "*", "10", ")", "buffersize", "=", "increment", "+", "len", "(", "bytes_", ")", "while", "p", "<", "finalpos", ":", "# Read in file or from memory in overlapping chunks and search the chunks.", "buf", "=", "bytearray", "(", "self", ".", "_datastore", ".", "getbyteslice", "(", "p", ",", "min", "(", "p", "+", "buffersize", ",", "finalpos", ")", ")", ")", "pos", "=", "buf", ".", "find", "(", "bytes_", ")", "if", "pos", "!=", "-", "1", ":", "found", "=", "True", "p", "+=", "pos", "break", "p", "+=", "increment", "if", "not", "found", ":", "return", "(", ")", "return", "(", "p", "*", "8", ",", ")" ]
Quicker version of find when everything's whole byte and byte aligned.
[ "Quicker", "version", "of", "find", "when", "everything", "s", "whole", "byte", "and", "byte", "aligned", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2352-L2377
train
scott-griffiths/bitstring
bitstring.py
Bits._findregex
def _findregex(self, reg_ex, start, end, bytealigned): """Find first occurrence of a compiled regular expression. Note that this doesn't support arbitrary regexes, in particular they must match a known length. """ p = start length = len(reg_ex.pattern) # We grab overlapping chunks of the binary representation and # do an ordinary string search within that. increment = max(4096, length * 10) buffersize = increment + length while p < end: buf = self._readbin(min(buffersize, end - p), p) # Test using regular expressions... m = reg_ex.search(buf) if m: pos = m.start() # pos = buf.find(targetbin) # if pos != -1: # if bytealigned then we only accept byte aligned positions. if not bytealigned or (p + pos) % 8 == 0: return (p + pos,) if bytealigned: # Advance to just beyond the non-byte-aligned match and try again... p += pos + 1 continue p += increment # Not found, return empty tuple return ()
python
def _findregex(self, reg_ex, start, end, bytealigned): """Find first occurrence of a compiled regular expression. Note that this doesn't support arbitrary regexes, in particular they must match a known length. """ p = start length = len(reg_ex.pattern) # We grab overlapping chunks of the binary representation and # do an ordinary string search within that. increment = max(4096, length * 10) buffersize = increment + length while p < end: buf = self._readbin(min(buffersize, end - p), p) # Test using regular expressions... m = reg_ex.search(buf) if m: pos = m.start() # pos = buf.find(targetbin) # if pos != -1: # if bytealigned then we only accept byte aligned positions. if not bytealigned or (p + pos) % 8 == 0: return (p + pos,) if bytealigned: # Advance to just beyond the non-byte-aligned match and try again... p += pos + 1 continue p += increment # Not found, return empty tuple return ()
[ "def", "_findregex", "(", "self", ",", "reg_ex", ",", "start", ",", "end", ",", "bytealigned", ")", ":", "p", "=", "start", "length", "=", "len", "(", "reg_ex", ".", "pattern", ")", "# We grab overlapping chunks of the binary representation and", "# do an ordinary string search within that.", "increment", "=", "max", "(", "4096", ",", "length", "*", "10", ")", "buffersize", "=", "increment", "+", "length", "while", "p", "<", "end", ":", "buf", "=", "self", ".", "_readbin", "(", "min", "(", "buffersize", ",", "end", "-", "p", ")", ",", "p", ")", "# Test using regular expressions...", "m", "=", "reg_ex", ".", "search", "(", "buf", ")", "if", "m", ":", "pos", "=", "m", ".", "start", "(", ")", "# pos = buf.find(targetbin)", "# if pos != -1:", "# if bytealigned then we only accept byte aligned positions.", "if", "not", "bytealigned", "or", "(", "p", "+", "pos", ")", "%", "8", "==", "0", ":", "return", "(", "p", "+", "pos", ",", ")", "if", "bytealigned", ":", "# Advance to just beyond the non-byte-aligned match and try again...", "p", "+=", "pos", "+", "1", "continue", "p", "+=", "increment", "# Not found, return empty tuple", "return", "(", ")" ]
Find first occurrence of a compiled regular expression. Note that this doesn't support arbitrary regexes, in particular they must match a known length.
[ "Find", "first", "occurrence", "of", "a", "compiled", "regular", "expression", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2379-L2409
train
scott-griffiths/bitstring
bitstring.py
Bits.find
def find(self, bs, start=None, end=None, bytealigned=None): """Find first occurrence of substring bs. Returns a single item tuple with the bit position if found, or an empty tuple if not found. The bit position (pos property) will also be set to the start of the substring if it is found. bs -- The bitstring to find. start -- The bit position to start the search. Defaults to 0. end -- The bit position one past the last bit to search. Defaults to self.len. bytealigned -- If True the bitstring will only be found on byte boundaries. Raises ValueError if bs is empty, if start < 0, if end > self.len or if end < start. >>> BitArray('0xc3e').find('0b1111') (6,) """ bs = Bits(bs) if not bs.len: raise ValueError("Cannot find an empty bitstring.") start, end = self._validate_slice(start, end) if bytealigned is None: bytealigned = globals()['bytealigned'] if bytealigned and not bs.len % 8 and not self._datastore.offset: p = self._findbytes(bs.bytes, start, end, bytealigned) else: p = self._findregex(re.compile(bs._getbin()), start, end, bytealigned) # If called from a class that has a pos, set it try: self._pos = p[0] except (AttributeError, IndexError): pass return p
python
def find(self, bs, start=None, end=None, bytealigned=None): """Find first occurrence of substring bs. Returns a single item tuple with the bit position if found, or an empty tuple if not found. The bit position (pos property) will also be set to the start of the substring if it is found. bs -- The bitstring to find. start -- The bit position to start the search. Defaults to 0. end -- The bit position one past the last bit to search. Defaults to self.len. bytealigned -- If True the bitstring will only be found on byte boundaries. Raises ValueError if bs is empty, if start < 0, if end > self.len or if end < start. >>> BitArray('0xc3e').find('0b1111') (6,) """ bs = Bits(bs) if not bs.len: raise ValueError("Cannot find an empty bitstring.") start, end = self._validate_slice(start, end) if bytealigned is None: bytealigned = globals()['bytealigned'] if bytealigned and not bs.len % 8 and not self._datastore.offset: p = self._findbytes(bs.bytes, start, end, bytealigned) else: p = self._findregex(re.compile(bs._getbin()), start, end, bytealigned) # If called from a class that has a pos, set it try: self._pos = p[0] except (AttributeError, IndexError): pass return p
[ "def", "find", "(", "self", ",", "bs", ",", "start", "=", "None", ",", "end", "=", "None", ",", "bytealigned", "=", "None", ")", ":", "bs", "=", "Bits", "(", "bs", ")", "if", "not", "bs", ".", "len", ":", "raise", "ValueError", "(", "\"Cannot find an empty bitstring.\"", ")", "start", ",", "end", "=", "self", ".", "_validate_slice", "(", "start", ",", "end", ")", "if", "bytealigned", "is", "None", ":", "bytealigned", "=", "globals", "(", ")", "[", "'bytealigned'", "]", "if", "bytealigned", "and", "not", "bs", ".", "len", "%", "8", "and", "not", "self", ".", "_datastore", ".", "offset", ":", "p", "=", "self", ".", "_findbytes", "(", "bs", ".", "bytes", ",", "start", ",", "end", ",", "bytealigned", ")", "else", ":", "p", "=", "self", ".", "_findregex", "(", "re", ".", "compile", "(", "bs", ".", "_getbin", "(", ")", ")", ",", "start", ",", "end", ",", "bytealigned", ")", "# If called from a class that has a pos, set it", "try", ":", "self", ".", "_pos", "=", "p", "[", "0", "]", "except", "(", "AttributeError", ",", "IndexError", ")", ":", "pass", "return", "p" ]
Find first occurrence of substring bs. Returns a single item tuple with the bit position if found, or an empty tuple if not found. The bit position (pos property) will also be set to the start of the substring if it is found. bs -- The bitstring to find. start -- The bit position to start the search. Defaults to 0. end -- The bit position one past the last bit to search. Defaults to self.len. bytealigned -- If True the bitstring will only be found on byte boundaries. Raises ValueError if bs is empty, if start < 0, if end > self.len or if end < start. >>> BitArray('0xc3e').find('0b1111') (6,)
[ "Find", "first", "occurrence", "of", "substring", "bs", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2411-L2447
train
scott-griffiths/bitstring
bitstring.py
Bits.findall
def findall(self, bs, start=None, end=None, count=None, bytealigned=None): """Find all occurrences of bs. Return generator of bit positions. bs -- The bitstring to find. start -- The bit position to start the search. Defaults to 0. end -- The bit position one past the last bit to search. Defaults to self.len. count -- The maximum number of occurrences to find. bytealigned -- If True the bitstring will only be found on byte boundaries. Raises ValueError if bs is empty, if start < 0, if end > self.len or if end < start. Note that all occurrences of bs are found, even if they overlap. """ if count is not None and count < 0: raise ValueError("In findall, count must be >= 0.") bs = Bits(bs) start, end = self._validate_slice(start, end) if bytealigned is None: bytealigned = globals()['bytealigned'] c = 0 if bytealigned and not bs.len % 8 and not self._datastore.offset: # Use the quick find method f = self._findbytes x = bs._getbytes() else: f = self._findregex x = re.compile(bs._getbin()) while True: p = f(x, start, end, bytealigned) if not p: break if count is not None and c >= count: return c += 1 try: self._pos = p[0] except AttributeError: pass yield p[0] if bytealigned: start = p[0] + 8 else: start = p[0] + 1 if start >= end: break return
python
def findall(self, bs, start=None, end=None, count=None, bytealigned=None): """Find all occurrences of bs. Return generator of bit positions. bs -- The bitstring to find. start -- The bit position to start the search. Defaults to 0. end -- The bit position one past the last bit to search. Defaults to self.len. count -- The maximum number of occurrences to find. bytealigned -- If True the bitstring will only be found on byte boundaries. Raises ValueError if bs is empty, if start < 0, if end > self.len or if end < start. Note that all occurrences of bs are found, even if they overlap. """ if count is not None and count < 0: raise ValueError("In findall, count must be >= 0.") bs = Bits(bs) start, end = self._validate_slice(start, end) if bytealigned is None: bytealigned = globals()['bytealigned'] c = 0 if bytealigned and not bs.len % 8 and not self._datastore.offset: # Use the quick find method f = self._findbytes x = bs._getbytes() else: f = self._findregex x = re.compile(bs._getbin()) while True: p = f(x, start, end, bytealigned) if not p: break if count is not None and c >= count: return c += 1 try: self._pos = p[0] except AttributeError: pass yield p[0] if bytealigned: start = p[0] + 8 else: start = p[0] + 1 if start >= end: break return
[ "def", "findall", "(", "self", ",", "bs", ",", "start", "=", "None", ",", "end", "=", "None", ",", "count", "=", "None", ",", "bytealigned", "=", "None", ")", ":", "if", "count", "is", "not", "None", "and", "count", "<", "0", ":", "raise", "ValueError", "(", "\"In findall, count must be >= 0.\"", ")", "bs", "=", "Bits", "(", "bs", ")", "start", ",", "end", "=", "self", ".", "_validate_slice", "(", "start", ",", "end", ")", "if", "bytealigned", "is", "None", ":", "bytealigned", "=", "globals", "(", ")", "[", "'bytealigned'", "]", "c", "=", "0", "if", "bytealigned", "and", "not", "bs", ".", "len", "%", "8", "and", "not", "self", ".", "_datastore", ".", "offset", ":", "# Use the quick find method", "f", "=", "self", ".", "_findbytes", "x", "=", "bs", ".", "_getbytes", "(", ")", "else", ":", "f", "=", "self", ".", "_findregex", "x", "=", "re", ".", "compile", "(", "bs", ".", "_getbin", "(", ")", ")", "while", "True", ":", "p", "=", "f", "(", "x", ",", "start", ",", "end", ",", "bytealigned", ")", "if", "not", "p", ":", "break", "if", "count", "is", "not", "None", "and", "c", ">=", "count", ":", "return", "c", "+=", "1", "try", ":", "self", ".", "_pos", "=", "p", "[", "0", "]", "except", "AttributeError", ":", "pass", "yield", "p", "[", "0", "]", "if", "bytealigned", ":", "start", "=", "p", "[", "0", "]", "+", "8", "else", ":", "start", "=", "p", "[", "0", "]", "+", "1", "if", "start", ">=", "end", ":", "break", "return" ]
Find all occurrences of bs. Return generator of bit positions. bs -- The bitstring to find. start -- The bit position to start the search. Defaults to 0. end -- The bit position one past the last bit to search. Defaults to self.len. count -- The maximum number of occurrences to find. bytealigned -- If True the bitstring will only be found on byte boundaries. Raises ValueError if bs is empty, if start < 0, if end > self.len or if end < start. Note that all occurrences of bs are found, even if they overlap.
[ "Find", "all", "occurrences", "of", "bs", ".", "Return", "generator", "of", "bit", "positions", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2449-L2499
train
scott-griffiths/bitstring
bitstring.py
Bits.rfind
def rfind(self, bs, start=None, end=None, bytealigned=None): """Find final occurrence of substring bs. Returns a single item tuple with the bit position if found, or an empty tuple if not found. The bit position (pos property) will also be set to the start of the substring if it is found. bs -- The bitstring to find. start -- The bit position to end the reverse search. Defaults to 0. end -- The bit position one past the first bit to reverse search. Defaults to self.len. bytealigned -- If True the bitstring will only be found on byte boundaries. Raises ValueError if bs is empty, if start < 0, if end > self.len or if end < start. """ bs = Bits(bs) start, end = self._validate_slice(start, end) if bytealigned is None: bytealigned = globals()['bytealigned'] if not bs.len: raise ValueError("Cannot find an empty bitstring.") # Search chunks starting near the end and then moving back # until we find bs. increment = max(8192, bs.len * 80) buffersize = min(increment + bs.len, end - start) pos = max(start, end - buffersize) while True: found = list(self.findall(bs, start=pos, end=pos + buffersize, bytealigned=bytealigned)) if not found: if pos == start: return () pos = max(start, pos - increment) continue return (found[-1],)
python
def rfind(self, bs, start=None, end=None, bytealigned=None): """Find final occurrence of substring bs. Returns a single item tuple with the bit position if found, or an empty tuple if not found. The bit position (pos property) will also be set to the start of the substring if it is found. bs -- The bitstring to find. start -- The bit position to end the reverse search. Defaults to 0. end -- The bit position one past the first bit to reverse search. Defaults to self.len. bytealigned -- If True the bitstring will only be found on byte boundaries. Raises ValueError if bs is empty, if start < 0, if end > self.len or if end < start. """ bs = Bits(bs) start, end = self._validate_slice(start, end) if bytealigned is None: bytealigned = globals()['bytealigned'] if not bs.len: raise ValueError("Cannot find an empty bitstring.") # Search chunks starting near the end and then moving back # until we find bs. increment = max(8192, bs.len * 80) buffersize = min(increment + bs.len, end - start) pos = max(start, end - buffersize) while True: found = list(self.findall(bs, start=pos, end=pos + buffersize, bytealigned=bytealigned)) if not found: if pos == start: return () pos = max(start, pos - increment) continue return (found[-1],)
[ "def", "rfind", "(", "self", ",", "bs", ",", "start", "=", "None", ",", "end", "=", "None", ",", "bytealigned", "=", "None", ")", ":", "bs", "=", "Bits", "(", "bs", ")", "start", ",", "end", "=", "self", ".", "_validate_slice", "(", "start", ",", "end", ")", "if", "bytealigned", "is", "None", ":", "bytealigned", "=", "globals", "(", ")", "[", "'bytealigned'", "]", "if", "not", "bs", ".", "len", ":", "raise", "ValueError", "(", "\"Cannot find an empty bitstring.\"", ")", "# Search chunks starting near the end and then moving back", "# until we find bs.", "increment", "=", "max", "(", "8192", ",", "bs", ".", "len", "*", "80", ")", "buffersize", "=", "min", "(", "increment", "+", "bs", ".", "len", ",", "end", "-", "start", ")", "pos", "=", "max", "(", "start", ",", "end", "-", "buffersize", ")", "while", "True", ":", "found", "=", "list", "(", "self", ".", "findall", "(", "bs", ",", "start", "=", "pos", ",", "end", "=", "pos", "+", "buffersize", ",", "bytealigned", "=", "bytealigned", ")", ")", "if", "not", "found", ":", "if", "pos", "==", "start", ":", "return", "(", ")", "pos", "=", "max", "(", "start", ",", "pos", "-", "increment", ")", "continue", "return", "(", "found", "[", "-", "1", "]", ",", ")" ]
Find final occurrence of substring bs. Returns a single item tuple with the bit position if found, or an empty tuple if not found. The bit position (pos property) will also be set to the start of the substring if it is found. bs -- The bitstring to find. start -- The bit position to end the reverse search. Defaults to 0. end -- The bit position one past the first bit to reverse search. Defaults to self.len. bytealigned -- If True the bitstring will only be found on byte boundaries. Raises ValueError if bs is empty, if start < 0, if end > self.len or if end < start.
[ "Find", "final", "occurrence", "of", "substring", "bs", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2501-L2538
train
scott-griffiths/bitstring
bitstring.py
Bits.cut
def cut(self, bits, start=None, end=None, count=None): """Return bitstring generator by cutting into bits sized chunks. bits -- The size in bits of the bitstring chunks to generate. start -- The bit position to start the first cut. Defaults to 0. end -- The bit position one past the last bit to use in the cut. Defaults to self.len. count -- If specified then at most count items are generated. Default is to cut as many times as possible. """ start, end = self._validate_slice(start, end) if count is not None and count < 0: raise ValueError("Cannot cut - count must be >= 0.") if bits <= 0: raise ValueError("Cannot cut - bits must be >= 0.") c = 0 while count is None or c < count: c += 1 nextchunk = self._slice(start, min(start + bits, end)) if nextchunk.len != bits: return assert nextchunk._assertsanity() yield nextchunk start += bits return
python
def cut(self, bits, start=None, end=None, count=None): """Return bitstring generator by cutting into bits sized chunks. bits -- The size in bits of the bitstring chunks to generate. start -- The bit position to start the first cut. Defaults to 0. end -- The bit position one past the last bit to use in the cut. Defaults to self.len. count -- If specified then at most count items are generated. Default is to cut as many times as possible. """ start, end = self._validate_slice(start, end) if count is not None and count < 0: raise ValueError("Cannot cut - count must be >= 0.") if bits <= 0: raise ValueError("Cannot cut - bits must be >= 0.") c = 0 while count is None or c < count: c += 1 nextchunk = self._slice(start, min(start + bits, end)) if nextchunk.len != bits: return assert nextchunk._assertsanity() yield nextchunk start += bits return
[ "def", "cut", "(", "self", ",", "bits", ",", "start", "=", "None", ",", "end", "=", "None", ",", "count", "=", "None", ")", ":", "start", ",", "end", "=", "self", ".", "_validate_slice", "(", "start", ",", "end", ")", "if", "count", "is", "not", "None", "and", "count", "<", "0", ":", "raise", "ValueError", "(", "\"Cannot cut - count must be >= 0.\"", ")", "if", "bits", "<=", "0", ":", "raise", "ValueError", "(", "\"Cannot cut - bits must be >= 0.\"", ")", "c", "=", "0", "while", "count", "is", "None", "or", "c", "<", "count", ":", "c", "+=", "1", "nextchunk", "=", "self", ".", "_slice", "(", "start", ",", "min", "(", "start", "+", "bits", ",", "end", ")", ")", "if", "nextchunk", ".", "len", "!=", "bits", ":", "return", "assert", "nextchunk", ".", "_assertsanity", "(", ")", "yield", "nextchunk", "start", "+=", "bits", "return" ]
Return bitstring generator by cutting into bits sized chunks. bits -- The size in bits of the bitstring chunks to generate. start -- The bit position to start the first cut. Defaults to 0. end -- The bit position one past the last bit to use in the cut. Defaults to self.len. count -- If specified then at most count items are generated. Default is to cut as many times as possible.
[ "Return", "bitstring", "generator", "by", "cutting", "into", "bits", "sized", "chunks", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2540-L2565
train
scott-griffiths/bitstring
bitstring.py
Bits.split
def split(self, delimiter, start=None, end=None, count=None, bytealigned=None): """Return bitstring generator by splittling using a delimiter. The first item returned is the initial bitstring before the delimiter, which may be an empty bitstring. delimiter -- The bitstring used as the divider. start -- The bit position to start the split. Defaults to 0. end -- The bit position one past the last bit to use in the split. Defaults to self.len. count -- If specified then at most count items are generated. Default is to split as many times as possible. bytealigned -- If True splits will only occur on byte boundaries. Raises ValueError if the delimiter is empty. """ delimiter = Bits(delimiter) if not delimiter.len: raise ValueError("split delimiter cannot be empty.") start, end = self._validate_slice(start, end) if bytealigned is None: bytealigned = globals()['bytealigned'] if count is not None and count < 0: raise ValueError("Cannot split - count must be >= 0.") if count == 0: return if bytealigned and not delimiter.len % 8 and not self._datastore.offset: # Use the quick find method f = self._findbytes x = delimiter._getbytes() else: f = self._findregex x = re.compile(delimiter._getbin()) found = f(x, start, end, bytealigned) if not found: # Initial bits are the whole bitstring being searched yield self._slice(start, end) return # yield the bytes before the first occurrence of the delimiter, even if empty yield self._slice(start, found[0]) startpos = pos = found[0] c = 1 while count is None or c < count: pos += delimiter.len found = f(x, pos, end, bytealigned) if not found: # No more occurrences, so return the rest of the bitstring yield self._slice(startpos, end) return c += 1 yield self._slice(startpos, found[0]) startpos = pos = found[0] # Have generated count bitstrings, so time to quit. return
python
def split(self, delimiter, start=None, end=None, count=None, bytealigned=None): """Return bitstring generator by splittling using a delimiter. The first item returned is the initial bitstring before the delimiter, which may be an empty bitstring. delimiter -- The bitstring used as the divider. start -- The bit position to start the split. Defaults to 0. end -- The bit position one past the last bit to use in the split. Defaults to self.len. count -- If specified then at most count items are generated. Default is to split as many times as possible. bytealigned -- If True splits will only occur on byte boundaries. Raises ValueError if the delimiter is empty. """ delimiter = Bits(delimiter) if not delimiter.len: raise ValueError("split delimiter cannot be empty.") start, end = self._validate_slice(start, end) if bytealigned is None: bytealigned = globals()['bytealigned'] if count is not None and count < 0: raise ValueError("Cannot split - count must be >= 0.") if count == 0: return if bytealigned and not delimiter.len % 8 and not self._datastore.offset: # Use the quick find method f = self._findbytes x = delimiter._getbytes() else: f = self._findregex x = re.compile(delimiter._getbin()) found = f(x, start, end, bytealigned) if not found: # Initial bits are the whole bitstring being searched yield self._slice(start, end) return # yield the bytes before the first occurrence of the delimiter, even if empty yield self._slice(start, found[0]) startpos = pos = found[0] c = 1 while count is None or c < count: pos += delimiter.len found = f(x, pos, end, bytealigned) if not found: # No more occurrences, so return the rest of the bitstring yield self._slice(startpos, end) return c += 1 yield self._slice(startpos, found[0]) startpos = pos = found[0] # Have generated count bitstrings, so time to quit. return
[ "def", "split", "(", "self", ",", "delimiter", ",", "start", "=", "None", ",", "end", "=", "None", ",", "count", "=", "None", ",", "bytealigned", "=", "None", ")", ":", "delimiter", "=", "Bits", "(", "delimiter", ")", "if", "not", "delimiter", ".", "len", ":", "raise", "ValueError", "(", "\"split delimiter cannot be empty.\"", ")", "start", ",", "end", "=", "self", ".", "_validate_slice", "(", "start", ",", "end", ")", "if", "bytealigned", "is", "None", ":", "bytealigned", "=", "globals", "(", ")", "[", "'bytealigned'", "]", "if", "count", "is", "not", "None", "and", "count", "<", "0", ":", "raise", "ValueError", "(", "\"Cannot split - count must be >= 0.\"", ")", "if", "count", "==", "0", ":", "return", "if", "bytealigned", "and", "not", "delimiter", ".", "len", "%", "8", "and", "not", "self", ".", "_datastore", ".", "offset", ":", "# Use the quick find method", "f", "=", "self", ".", "_findbytes", "x", "=", "delimiter", ".", "_getbytes", "(", ")", "else", ":", "f", "=", "self", ".", "_findregex", "x", "=", "re", ".", "compile", "(", "delimiter", ".", "_getbin", "(", ")", ")", "found", "=", "f", "(", "x", ",", "start", ",", "end", ",", "bytealigned", ")", "if", "not", "found", ":", "# Initial bits are the whole bitstring being searched", "yield", "self", ".", "_slice", "(", "start", ",", "end", ")", "return", "# yield the bytes before the first occurrence of the delimiter, even if empty", "yield", "self", ".", "_slice", "(", "start", ",", "found", "[", "0", "]", ")", "startpos", "=", "pos", "=", "found", "[", "0", "]", "c", "=", "1", "while", "count", "is", "None", "or", "c", "<", "count", ":", "pos", "+=", "delimiter", ".", "len", "found", "=", "f", "(", "x", ",", "pos", ",", "end", ",", "bytealigned", ")", "if", "not", "found", ":", "# No more occurrences, so return the rest of the bitstring", "yield", "self", ".", "_slice", "(", "startpos", ",", "end", ")", "return", "c", "+=", "1", "yield", "self", ".", "_slice", "(", "startpos", ",", "found", "[", "0", "]", ")", "startpos", "=", "pos", "=", "found", "[", "0", "]", "# Have generated count bitstrings, so time to quit.", "return" ]
Return bitstring generator by splittling using a delimiter. The first item returned is the initial bitstring before the delimiter, which may be an empty bitstring. delimiter -- The bitstring used as the divider. start -- The bit position to start the split. Defaults to 0. end -- The bit position one past the last bit to use in the split. Defaults to self.len. count -- If specified then at most count items are generated. Default is to split as many times as possible. bytealigned -- If True splits will only occur on byte boundaries. Raises ValueError if the delimiter is empty.
[ "Return", "bitstring", "generator", "by", "splittling", "using", "a", "delimiter", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2567-L2622
train
scott-griffiths/bitstring
bitstring.py
Bits.join
def join(self, sequence): """Return concatenation of bitstrings joined by self. sequence -- A sequence of bitstrings. """ s = self.__class__() i = iter(sequence) try: s._append(Bits(next(i))) while True: n = next(i) s._append(self) s._append(Bits(n)) except StopIteration: pass return s
python
def join(self, sequence): """Return concatenation of bitstrings joined by self. sequence -- A sequence of bitstrings. """ s = self.__class__() i = iter(sequence) try: s._append(Bits(next(i))) while True: n = next(i) s._append(self) s._append(Bits(n)) except StopIteration: pass return s
[ "def", "join", "(", "self", ",", "sequence", ")", ":", "s", "=", "self", ".", "__class__", "(", ")", "i", "=", "iter", "(", "sequence", ")", "try", ":", "s", ".", "_append", "(", "Bits", "(", "next", "(", "i", ")", ")", ")", "while", "True", ":", "n", "=", "next", "(", "i", ")", "s", ".", "_append", "(", "self", ")", "s", ".", "_append", "(", "Bits", "(", "n", ")", ")", "except", "StopIteration", ":", "pass", "return", "s" ]
Return concatenation of bitstrings joined by self. sequence -- A sequence of bitstrings.
[ "Return", "concatenation", "of", "bitstrings", "joined", "by", "self", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2624-L2640
train
scott-griffiths/bitstring
bitstring.py
Bits.tobytes
def tobytes(self): """Return the bitstring as bytes, padding with zero bits if needed. Up to seven zero bits will be added at the end to byte align. """ d = offsetcopy(self._datastore, 0).rawbytes # Need to ensure that unused bits at end are set to zero unusedbits = 8 - self.len % 8 if unusedbits != 8: d[-1] &= (0xff << unusedbits) return bytes(d)
python
def tobytes(self): """Return the bitstring as bytes, padding with zero bits if needed. Up to seven zero bits will be added at the end to byte align. """ d = offsetcopy(self._datastore, 0).rawbytes # Need to ensure that unused bits at end are set to zero unusedbits = 8 - self.len % 8 if unusedbits != 8: d[-1] &= (0xff << unusedbits) return bytes(d)
[ "def", "tobytes", "(", "self", ")", ":", "d", "=", "offsetcopy", "(", "self", ".", "_datastore", ",", "0", ")", ".", "rawbytes", "# Need to ensure that unused bits at end are set to zero", "unusedbits", "=", "8", "-", "self", ".", "len", "%", "8", "if", "unusedbits", "!=", "8", ":", "d", "[", "-", "1", "]", "&=", "(", "0xff", "<<", "unusedbits", ")", "return", "bytes", "(", "d", ")" ]
Return the bitstring as bytes, padding with zero bits if needed. Up to seven zero bits will be added at the end to byte align.
[ "Return", "the", "bitstring", "as", "bytes", "padding", "with", "zero", "bits", "if", "needed", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2642-L2653
train
scott-griffiths/bitstring
bitstring.py
Bits.tofile
def tofile(self, f): """Write the bitstring to a file object, padding with zero bits if needed. Up to seven zero bits will be added at the end to byte align. """ # If the bitstring is file based then we don't want to read it all # in to memory. chunksize = 1024 * 1024 # 1 MB chunks if not self._offset: a = 0 bytelen = self._datastore.bytelength p = self._datastore.getbyteslice(a, min(a + chunksize, bytelen - 1)) while len(p) == chunksize: f.write(p) a += chunksize p = self._datastore.getbyteslice(a, min(a + chunksize, bytelen - 1)) f.write(p) # Now the final byte, ensuring that unused bits at end are set to 0. bits_in_final_byte = self.len % 8 if not bits_in_final_byte: bits_in_final_byte = 8 f.write(self[-bits_in_final_byte:].tobytes()) else: # Really quite inefficient... a = 0 b = a + chunksize * 8 while b <= self.len: f.write(self._slice(a, b)._getbytes()) a += chunksize * 8 b += chunksize * 8 if a != self.len: f.write(self._slice(a, self.len).tobytes())
python
def tofile(self, f): """Write the bitstring to a file object, padding with zero bits if needed. Up to seven zero bits will be added at the end to byte align. """ # If the bitstring is file based then we don't want to read it all # in to memory. chunksize = 1024 * 1024 # 1 MB chunks if not self._offset: a = 0 bytelen = self._datastore.bytelength p = self._datastore.getbyteslice(a, min(a + chunksize, bytelen - 1)) while len(p) == chunksize: f.write(p) a += chunksize p = self._datastore.getbyteslice(a, min(a + chunksize, bytelen - 1)) f.write(p) # Now the final byte, ensuring that unused bits at end are set to 0. bits_in_final_byte = self.len % 8 if not bits_in_final_byte: bits_in_final_byte = 8 f.write(self[-bits_in_final_byte:].tobytes()) else: # Really quite inefficient... a = 0 b = a + chunksize * 8 while b <= self.len: f.write(self._slice(a, b)._getbytes()) a += chunksize * 8 b += chunksize * 8 if a != self.len: f.write(self._slice(a, self.len).tobytes())
[ "def", "tofile", "(", "self", ",", "f", ")", ":", "# If the bitstring is file based then we don't want to read it all", "# in to memory.", "chunksize", "=", "1024", "*", "1024", "# 1 MB chunks", "if", "not", "self", ".", "_offset", ":", "a", "=", "0", "bytelen", "=", "self", ".", "_datastore", ".", "bytelength", "p", "=", "self", ".", "_datastore", ".", "getbyteslice", "(", "a", ",", "min", "(", "a", "+", "chunksize", ",", "bytelen", "-", "1", ")", ")", "while", "len", "(", "p", ")", "==", "chunksize", ":", "f", ".", "write", "(", "p", ")", "a", "+=", "chunksize", "p", "=", "self", ".", "_datastore", ".", "getbyteslice", "(", "a", ",", "min", "(", "a", "+", "chunksize", ",", "bytelen", "-", "1", ")", ")", "f", ".", "write", "(", "p", ")", "# Now the final byte, ensuring that unused bits at end are set to 0.", "bits_in_final_byte", "=", "self", ".", "len", "%", "8", "if", "not", "bits_in_final_byte", ":", "bits_in_final_byte", "=", "8", "f", ".", "write", "(", "self", "[", "-", "bits_in_final_byte", ":", "]", ".", "tobytes", "(", ")", ")", "else", ":", "# Really quite inefficient...", "a", "=", "0", "b", "=", "a", "+", "chunksize", "*", "8", "while", "b", "<=", "self", ".", "len", ":", "f", ".", "write", "(", "self", ".", "_slice", "(", "a", ",", "b", ")", ".", "_getbytes", "(", ")", ")", "a", "+=", "chunksize", "*", "8", "b", "+=", "chunksize", "*", "8", "if", "a", "!=", "self", ".", "len", ":", "f", ".", "write", "(", "self", ".", "_slice", "(", "a", ",", "self", ".", "len", ")", ".", "tobytes", "(", ")", ")" ]
Write the bitstring to a file object, padding with zero bits if needed. Up to seven zero bits will be added at the end to byte align.
[ "Write", "the", "bitstring", "to", "a", "file", "object", "padding", "with", "zero", "bits", "if", "needed", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2655-L2687
train
scott-griffiths/bitstring
bitstring.py
Bits.startswith
def startswith(self, prefix, start=None, end=None): """Return whether the current bitstring starts with prefix. prefix -- The bitstring to search for. start -- The bit position to start from. Defaults to 0. end -- The bit position to end at. Defaults to self.len. """ prefix = Bits(prefix) start, end = self._validate_slice(start, end) if end < start + prefix.len: return False end = start + prefix.len return self._slice(start, end) == prefix
python
def startswith(self, prefix, start=None, end=None): """Return whether the current bitstring starts with prefix. prefix -- The bitstring to search for. start -- The bit position to start from. Defaults to 0. end -- The bit position to end at. Defaults to self.len. """ prefix = Bits(prefix) start, end = self._validate_slice(start, end) if end < start + prefix.len: return False end = start + prefix.len return self._slice(start, end) == prefix
[ "def", "startswith", "(", "self", ",", "prefix", ",", "start", "=", "None", ",", "end", "=", "None", ")", ":", "prefix", "=", "Bits", "(", "prefix", ")", "start", ",", "end", "=", "self", ".", "_validate_slice", "(", "start", ",", "end", ")", "if", "end", "<", "start", "+", "prefix", ".", "len", ":", "return", "False", "end", "=", "start", "+", "prefix", ".", "len", "return", "self", ".", "_slice", "(", "start", ",", "end", ")", "==", "prefix" ]
Return whether the current bitstring starts with prefix. prefix -- The bitstring to search for. start -- The bit position to start from. Defaults to 0. end -- The bit position to end at. Defaults to self.len.
[ "Return", "whether", "the", "current", "bitstring", "starts", "with", "prefix", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2689-L2702
train
scott-griffiths/bitstring
bitstring.py
Bits.endswith
def endswith(self, suffix, start=None, end=None): """Return whether the current bitstring ends with suffix. suffix -- The bitstring to search for. start -- The bit position to start from. Defaults to 0. end -- The bit position to end at. Defaults to self.len. """ suffix = Bits(suffix) start, end = self._validate_slice(start, end) if start + suffix.len > end: return False start = end - suffix.len return self._slice(start, end) == suffix
python
def endswith(self, suffix, start=None, end=None): """Return whether the current bitstring ends with suffix. suffix -- The bitstring to search for. start -- The bit position to start from. Defaults to 0. end -- The bit position to end at. Defaults to self.len. """ suffix = Bits(suffix) start, end = self._validate_slice(start, end) if start + suffix.len > end: return False start = end - suffix.len return self._slice(start, end) == suffix
[ "def", "endswith", "(", "self", ",", "suffix", ",", "start", "=", "None", ",", "end", "=", "None", ")", ":", "suffix", "=", "Bits", "(", "suffix", ")", "start", ",", "end", "=", "self", ".", "_validate_slice", "(", "start", ",", "end", ")", "if", "start", "+", "suffix", ".", "len", ">", "end", ":", "return", "False", "start", "=", "end", "-", "suffix", ".", "len", "return", "self", ".", "_slice", "(", "start", ",", "end", ")", "==", "suffix" ]
Return whether the current bitstring ends with suffix. suffix -- The bitstring to search for. start -- The bit position to start from. Defaults to 0. end -- The bit position to end at. Defaults to self.len.
[ "Return", "whether", "the", "current", "bitstring", "ends", "with", "suffix", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2704-L2717
train
scott-griffiths/bitstring
bitstring.py
Bits.all
def all(self, value, pos=None): """Return True if one or many bits are all set to value. value -- If value is True then checks for bits set to 1, otherwise checks for bits set to 0. pos -- An iterable of bit positions. Negative numbers are treated in the same way as slice indices. Defaults to the whole bitstring. """ value = bool(value) length = self.len if pos is None: pos = xrange(self.len) for p in pos: if p < 0: p += length if not 0 <= p < length: raise IndexError("Bit position {0} out of range.".format(p)) if not self._datastore.getbit(p) is value: return False return True
python
def all(self, value, pos=None): """Return True if one or many bits are all set to value. value -- If value is True then checks for bits set to 1, otherwise checks for bits set to 0. pos -- An iterable of bit positions. Negative numbers are treated in the same way as slice indices. Defaults to the whole bitstring. """ value = bool(value) length = self.len if pos is None: pos = xrange(self.len) for p in pos: if p < 0: p += length if not 0 <= p < length: raise IndexError("Bit position {0} out of range.".format(p)) if not self._datastore.getbit(p) is value: return False return True
[ "def", "all", "(", "self", ",", "value", ",", "pos", "=", "None", ")", ":", "value", "=", "bool", "(", "value", ")", "length", "=", "self", ".", "len", "if", "pos", "is", "None", ":", "pos", "=", "xrange", "(", "self", ".", "len", ")", "for", "p", "in", "pos", ":", "if", "p", "<", "0", ":", "p", "+=", "length", "if", "not", "0", "<=", "p", "<", "length", ":", "raise", "IndexError", "(", "\"Bit position {0} out of range.\"", ".", "format", "(", "p", ")", ")", "if", "not", "self", ".", "_datastore", ".", "getbit", "(", "p", ")", "is", "value", ":", "return", "False", "return", "True" ]
Return True if one or many bits are all set to value. value -- If value is True then checks for bits set to 1, otherwise checks for bits set to 0. pos -- An iterable of bit positions. Negative numbers are treated in the same way as slice indices. Defaults to the whole bitstring.
[ "Return", "True", "if", "one", "or", "many", "bits", "are", "all", "set", "to", "value", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2719-L2739
train
scott-griffiths/bitstring
bitstring.py
Bits.count
def count(self, value): """Return count of total number of either zero or one bits. value -- If True then bits set to 1 are counted, otherwise bits set to 0 are counted. >>> Bits('0xef').count(1) 7 """ if not self.len: return 0 # count the number of 1s (from which it's easy to work out the 0s). # Don't count the final byte yet. count = sum(BIT_COUNT[self._datastore.getbyte(i)] for i in xrange(self._datastore.bytelength - 1)) # adjust for bits at start that aren't part of the bitstring if self._offset: count -= BIT_COUNT[self._datastore.getbyte(0) >> (8 - self._offset)] # and count the last 1 - 8 bits at the end. endbits = self._datastore.bytelength * 8 - (self._offset + self.len) count += BIT_COUNT[self._datastore.getbyte(self._datastore.bytelength - 1) >> endbits] return count if value else self.len - count
python
def count(self, value): """Return count of total number of either zero or one bits. value -- If True then bits set to 1 are counted, otherwise bits set to 0 are counted. >>> Bits('0xef').count(1) 7 """ if not self.len: return 0 # count the number of 1s (from which it's easy to work out the 0s). # Don't count the final byte yet. count = sum(BIT_COUNT[self._datastore.getbyte(i)] for i in xrange(self._datastore.bytelength - 1)) # adjust for bits at start that aren't part of the bitstring if self._offset: count -= BIT_COUNT[self._datastore.getbyte(0) >> (8 - self._offset)] # and count the last 1 - 8 bits at the end. endbits = self._datastore.bytelength * 8 - (self._offset + self.len) count += BIT_COUNT[self._datastore.getbyte(self._datastore.bytelength - 1) >> endbits] return count if value else self.len - count
[ "def", "count", "(", "self", ",", "value", ")", ":", "if", "not", "self", ".", "len", ":", "return", "0", "# count the number of 1s (from which it's easy to work out the 0s).", "# Don't count the final byte yet.", "count", "=", "sum", "(", "BIT_COUNT", "[", "self", ".", "_datastore", ".", "getbyte", "(", "i", ")", "]", "for", "i", "in", "xrange", "(", "self", ".", "_datastore", ".", "bytelength", "-", "1", ")", ")", "# adjust for bits at start that aren't part of the bitstring", "if", "self", ".", "_offset", ":", "count", "-=", "BIT_COUNT", "[", "self", ".", "_datastore", ".", "getbyte", "(", "0", ")", ">>", "(", "8", "-", "self", ".", "_offset", ")", "]", "# and count the last 1 - 8 bits at the end.", "endbits", "=", "self", ".", "_datastore", ".", "bytelength", "*", "8", "-", "(", "self", ".", "_offset", "+", "self", ".", "len", ")", "count", "+=", "BIT_COUNT", "[", "self", ".", "_datastore", ".", "getbyte", "(", "self", ".", "_datastore", ".", "bytelength", "-", "1", ")", ">>", "endbits", "]", "return", "count", "if", "value", "else", "self", ".", "len", "-", "count" ]
Return count of total number of either zero or one bits. value -- If True then bits set to 1 are counted, otherwise bits set to 0 are counted. >>> Bits('0xef').count(1) 7
[ "Return", "count", "of", "total", "number", "of", "either", "zero", "or", "one", "bits", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2763-L2784
train
scott-griffiths/bitstring
bitstring.py
BitArray.replace
def replace(self, old, new, start=None, end=None, count=None, bytealigned=None): """Replace all occurrences of old with new in place. Returns number of replacements made. old -- The bitstring to replace. new -- The replacement bitstring. start -- Any occurrences that start before this will not be replaced. Defaults to 0. end -- Any occurrences that finish after this will not be replaced. Defaults to self.len. count -- The maximum number of replacements to make. Defaults to replace all occurrences. bytealigned -- If True replacements will only be made on byte boundaries. Raises ValueError if old is empty or if start or end are out of range. """ old = Bits(old) new = Bits(new) if not old.len: raise ValueError("Empty bitstring cannot be replaced.") start, end = self._validate_slice(start, end) if bytealigned is None: bytealigned = globals()['bytealigned'] # Adjust count for use in split() if count is not None: count += 1 sections = self.split(old, start, end, count, bytealigned) lengths = [s.len for s in sections] if len(lengths) == 1: # Didn't find anything to replace. return 0 # no replacements done if new is self: # Prevent self assignment woes new = copy.copy(self) positions = [lengths[0] + start] for l in lengths[1:-1]: # Next position is the previous one plus the length of the next section. positions.append(positions[-1] + l) # We have all the positions that need replacements. We do them # in reverse order so that they won't move around as we replace. positions.reverse() try: # Need to calculate new pos, if this is a bitstream newpos = self._pos for p in positions: self[p:p + old.len] = new if old.len != new.len: diff = new.len - old.len for p in positions: if p >= newpos: continue if p + old.len <= newpos: newpos += diff else: newpos = p self._pos = newpos except AttributeError: for p in positions: self[p:p + old.len] = new assert self._assertsanity() return len(lengths) - 1
python
def replace(self, old, new, start=None, end=None, count=None, bytealigned=None): """Replace all occurrences of old with new in place. Returns number of replacements made. old -- The bitstring to replace. new -- The replacement bitstring. start -- Any occurrences that start before this will not be replaced. Defaults to 0. end -- Any occurrences that finish after this will not be replaced. Defaults to self.len. count -- The maximum number of replacements to make. Defaults to replace all occurrences. bytealigned -- If True replacements will only be made on byte boundaries. Raises ValueError if old is empty or if start or end are out of range. """ old = Bits(old) new = Bits(new) if not old.len: raise ValueError("Empty bitstring cannot be replaced.") start, end = self._validate_slice(start, end) if bytealigned is None: bytealigned = globals()['bytealigned'] # Adjust count for use in split() if count is not None: count += 1 sections = self.split(old, start, end, count, bytealigned) lengths = [s.len for s in sections] if len(lengths) == 1: # Didn't find anything to replace. return 0 # no replacements done if new is self: # Prevent self assignment woes new = copy.copy(self) positions = [lengths[0] + start] for l in lengths[1:-1]: # Next position is the previous one plus the length of the next section. positions.append(positions[-1] + l) # We have all the positions that need replacements. We do them # in reverse order so that they won't move around as we replace. positions.reverse() try: # Need to calculate new pos, if this is a bitstream newpos = self._pos for p in positions: self[p:p + old.len] = new if old.len != new.len: diff = new.len - old.len for p in positions: if p >= newpos: continue if p + old.len <= newpos: newpos += diff else: newpos = p self._pos = newpos except AttributeError: for p in positions: self[p:p + old.len] = new assert self._assertsanity() return len(lengths) - 1
[ "def", "replace", "(", "self", ",", "old", ",", "new", ",", "start", "=", "None", ",", "end", "=", "None", ",", "count", "=", "None", ",", "bytealigned", "=", "None", ")", ":", "old", "=", "Bits", "(", "old", ")", "new", "=", "Bits", "(", "new", ")", "if", "not", "old", ".", "len", ":", "raise", "ValueError", "(", "\"Empty bitstring cannot be replaced.\"", ")", "start", ",", "end", "=", "self", ".", "_validate_slice", "(", "start", ",", "end", ")", "if", "bytealigned", "is", "None", ":", "bytealigned", "=", "globals", "(", ")", "[", "'bytealigned'", "]", "# Adjust count for use in split()", "if", "count", "is", "not", "None", ":", "count", "+=", "1", "sections", "=", "self", ".", "split", "(", "old", ",", "start", ",", "end", ",", "count", ",", "bytealigned", ")", "lengths", "=", "[", "s", ".", "len", "for", "s", "in", "sections", "]", "if", "len", "(", "lengths", ")", "==", "1", ":", "# Didn't find anything to replace.", "return", "0", "# no replacements done", "if", "new", "is", "self", ":", "# Prevent self assignment woes", "new", "=", "copy", ".", "copy", "(", "self", ")", "positions", "=", "[", "lengths", "[", "0", "]", "+", "start", "]", "for", "l", "in", "lengths", "[", "1", ":", "-", "1", "]", ":", "# Next position is the previous one plus the length of the next section.", "positions", ".", "append", "(", "positions", "[", "-", "1", "]", "+", "l", ")", "# We have all the positions that need replacements. We do them", "# in reverse order so that they won't move around as we replace.", "positions", ".", "reverse", "(", ")", "try", ":", "# Need to calculate new pos, if this is a bitstream", "newpos", "=", "self", ".", "_pos", "for", "p", "in", "positions", ":", "self", "[", "p", ":", "p", "+", "old", ".", "len", "]", "=", "new", "if", "old", ".", "len", "!=", "new", ".", "len", ":", "diff", "=", "new", ".", "len", "-", "old", ".", "len", "for", "p", "in", "positions", ":", "if", "p", ">=", "newpos", ":", "continue", "if", "p", "+", "old", ".", "len", "<=", "newpos", ":", "newpos", "+=", "diff", "else", ":", "newpos", "=", "p", "self", ".", "_pos", "=", "newpos", "except", "AttributeError", ":", "for", "p", "in", "positions", ":", "self", "[", "p", ":", "p", "+", "old", ".", "len", "]", "=", "new", "assert", "self", ".", "_assertsanity", "(", ")", "return", "len", "(", "lengths", ")", "-", "1" ]
Replace all occurrences of old with new in place. Returns number of replacements made. old -- The bitstring to replace. new -- The replacement bitstring. start -- Any occurrences that start before this will not be replaced. Defaults to 0. end -- Any occurrences that finish after this will not be replaced. Defaults to self.len. count -- The maximum number of replacements to make. Defaults to replace all occurrences. bytealigned -- If True replacements will only be made on byte boundaries. Raises ValueError if old is empty or if start or end are out of range.
[ "Replace", "all", "occurrences", "of", "old", "with", "new", "in", "place", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L3298-L3363
train
scott-griffiths/bitstring
bitstring.py
BitArray.insert
def insert(self, bs, pos=None): """Insert bs at bit position pos. bs -- The bitstring to insert. pos -- The bit position to insert at. Raises ValueError if pos < 0 or pos > self.len. """ bs = Bits(bs) if not bs.len: return self if bs is self: bs = self.__copy__() if pos is None: try: pos = self._pos except AttributeError: raise TypeError("insert require a bit position for this type.") if pos < 0: pos += self.len if not 0 <= pos <= self.len: raise ValueError("Invalid insert position.") self._insert(bs, pos)
python
def insert(self, bs, pos=None): """Insert bs at bit position pos. bs -- The bitstring to insert. pos -- The bit position to insert at. Raises ValueError if pos < 0 or pos > self.len. """ bs = Bits(bs) if not bs.len: return self if bs is self: bs = self.__copy__() if pos is None: try: pos = self._pos except AttributeError: raise TypeError("insert require a bit position for this type.") if pos < 0: pos += self.len if not 0 <= pos <= self.len: raise ValueError("Invalid insert position.") self._insert(bs, pos)
[ "def", "insert", "(", "self", ",", "bs", ",", "pos", "=", "None", ")", ":", "bs", "=", "Bits", "(", "bs", ")", "if", "not", "bs", ".", "len", ":", "return", "self", "if", "bs", "is", "self", ":", "bs", "=", "self", ".", "__copy__", "(", ")", "if", "pos", "is", "None", ":", "try", ":", "pos", "=", "self", ".", "_pos", "except", "AttributeError", ":", "raise", "TypeError", "(", "\"insert require a bit position for this type.\"", ")", "if", "pos", "<", "0", ":", "pos", "+=", "self", ".", "len", "if", "not", "0", "<=", "pos", "<=", "self", ".", "len", ":", "raise", "ValueError", "(", "\"Invalid insert position.\"", ")", "self", ".", "_insert", "(", "bs", ",", "pos", ")" ]
Insert bs at bit position pos. bs -- The bitstring to insert. pos -- The bit position to insert at. Raises ValueError if pos < 0 or pos > self.len.
[ "Insert", "bs", "at", "bit", "position", "pos", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L3365-L3388
train
scott-griffiths/bitstring
bitstring.py
BitArray.overwrite
def overwrite(self, bs, pos=None): """Overwrite with bs at bit position pos. bs -- The bitstring to overwrite with. pos -- The bit position to begin overwriting from. Raises ValueError if pos < 0 or pos + bs.len > self.len """ bs = Bits(bs) if not bs.len: return if pos is None: try: pos = self._pos except AttributeError: raise TypeError("overwrite require a bit position for this type.") if pos < 0: pos += self.len if pos < 0 or pos + bs.len > self.len: raise ValueError("Overwrite exceeds boundary of bitstring.") self._overwrite(bs, pos) try: self._pos = pos + bs.len except AttributeError: pass
python
def overwrite(self, bs, pos=None): """Overwrite with bs at bit position pos. bs -- The bitstring to overwrite with. pos -- The bit position to begin overwriting from. Raises ValueError if pos < 0 or pos + bs.len > self.len """ bs = Bits(bs) if not bs.len: return if pos is None: try: pos = self._pos except AttributeError: raise TypeError("overwrite require a bit position for this type.") if pos < 0: pos += self.len if pos < 0 or pos + bs.len > self.len: raise ValueError("Overwrite exceeds boundary of bitstring.") self._overwrite(bs, pos) try: self._pos = pos + bs.len except AttributeError: pass
[ "def", "overwrite", "(", "self", ",", "bs", ",", "pos", "=", "None", ")", ":", "bs", "=", "Bits", "(", "bs", ")", "if", "not", "bs", ".", "len", ":", "return", "if", "pos", "is", "None", ":", "try", ":", "pos", "=", "self", ".", "_pos", "except", "AttributeError", ":", "raise", "TypeError", "(", "\"overwrite require a bit position for this type.\"", ")", "if", "pos", "<", "0", ":", "pos", "+=", "self", ".", "len", "if", "pos", "<", "0", "or", "pos", "+", "bs", ".", "len", ">", "self", ".", "len", ":", "raise", "ValueError", "(", "\"Overwrite exceeds boundary of bitstring.\"", ")", "self", ".", "_overwrite", "(", "bs", ",", "pos", ")", "try", ":", "self", ".", "_pos", "=", "pos", "+", "bs", ".", "len", "except", "AttributeError", ":", "pass" ]
Overwrite with bs at bit position pos. bs -- The bitstring to overwrite with. pos -- The bit position to begin overwriting from. Raises ValueError if pos < 0 or pos + bs.len > self.len
[ "Overwrite", "with", "bs", "at", "bit", "position", "pos", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L3390-L3415
train
scott-griffiths/bitstring
bitstring.py
BitArray.append
def append(self, bs): """Append a bitstring to the current bitstring. bs -- The bitstring to append. """ # The offset is a hint to make bs easily appendable. bs = self._converttobitstring(bs, offset=(self.len + self._offset) % 8) self._append(bs)
python
def append(self, bs): """Append a bitstring to the current bitstring. bs -- The bitstring to append. """ # The offset is a hint to make bs easily appendable. bs = self._converttobitstring(bs, offset=(self.len + self._offset) % 8) self._append(bs)
[ "def", "append", "(", "self", ",", "bs", ")", ":", "# The offset is a hint to make bs easily appendable.", "bs", "=", "self", ".", "_converttobitstring", "(", "bs", ",", "offset", "=", "(", "self", ".", "len", "+", "self", ".", "_offset", ")", "%", "8", ")", "self", ".", "_append", "(", "bs", ")" ]
Append a bitstring to the current bitstring. bs -- The bitstring to append.
[ "Append", "a", "bitstring", "to", "the", "current", "bitstring", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L3417-L3425
train
scott-griffiths/bitstring
bitstring.py
BitArray.reverse
def reverse(self, start=None, end=None): """Reverse bits in-place. start -- Position of first bit to reverse. Defaults to 0. end -- One past the position of the last bit to reverse. Defaults to self.len. Using on an empty bitstring will have no effect. Raises ValueError if start < 0, end > self.len or end < start. """ start, end = self._validate_slice(start, end) if start == 0 and end == self.len: self._reverse() return s = self._slice(start, end) s._reverse() self[start:end] = s
python
def reverse(self, start=None, end=None): """Reverse bits in-place. start -- Position of first bit to reverse. Defaults to 0. end -- One past the position of the last bit to reverse. Defaults to self.len. Using on an empty bitstring will have no effect. Raises ValueError if start < 0, end > self.len or end < start. """ start, end = self._validate_slice(start, end) if start == 0 and end == self.len: self._reverse() return s = self._slice(start, end) s._reverse() self[start:end] = s
[ "def", "reverse", "(", "self", ",", "start", "=", "None", ",", "end", "=", "None", ")", ":", "start", ",", "end", "=", "self", ".", "_validate_slice", "(", "start", ",", "end", ")", "if", "start", "==", "0", "and", "end", "==", "self", ".", "len", ":", "self", ".", "_reverse", "(", ")", "return", "s", "=", "self", ".", "_slice", "(", "start", ",", "end", ")", "s", ".", "_reverse", "(", ")", "self", "[", "start", ":", "end", "]", "=", "s" ]
Reverse bits in-place. start -- Position of first bit to reverse. Defaults to 0. end -- One past the position of the last bit to reverse. Defaults to self.len. Using on an empty bitstring will have no effect. Raises ValueError if start < 0, end > self.len or end < start.
[ "Reverse", "bits", "in", "-", "place", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L3436-L3454
train
scott-griffiths/bitstring
bitstring.py
BitArray.set
def set(self, value, pos=None): """Set one or many bits to 1 or 0. value -- If True bits are set to 1, otherwise they are set to 0. pos -- Either a single bit position or an iterable of bit positions. Negative numbers are treated in the same way as slice indices. Defaults to the entire bitstring. Raises IndexError if pos < -self.len or pos >= self.len. """ f = self._set if value else self._unset if pos is None: pos = xrange(self.len) try: length = self.len for p in pos: if p < 0: p += length if not 0 <= p < length: raise IndexError("Bit position {0} out of range.".format(p)) f(p) except TypeError: # Single pos if pos < 0: pos += self.len if not 0 <= pos < length: raise IndexError("Bit position {0} out of range.".format(pos)) f(pos)
python
def set(self, value, pos=None): """Set one or many bits to 1 or 0. value -- If True bits are set to 1, otherwise they are set to 0. pos -- Either a single bit position or an iterable of bit positions. Negative numbers are treated in the same way as slice indices. Defaults to the entire bitstring. Raises IndexError if pos < -self.len or pos >= self.len. """ f = self._set if value else self._unset if pos is None: pos = xrange(self.len) try: length = self.len for p in pos: if p < 0: p += length if not 0 <= p < length: raise IndexError("Bit position {0} out of range.".format(p)) f(p) except TypeError: # Single pos if pos < 0: pos += self.len if not 0 <= pos < length: raise IndexError("Bit position {0} out of range.".format(pos)) f(pos)
[ "def", "set", "(", "self", ",", "value", ",", "pos", "=", "None", ")", ":", "f", "=", "self", ".", "_set", "if", "value", "else", "self", ".", "_unset", "if", "pos", "is", "None", ":", "pos", "=", "xrange", "(", "self", ".", "len", ")", "try", ":", "length", "=", "self", ".", "len", "for", "p", "in", "pos", ":", "if", "p", "<", "0", ":", "p", "+=", "length", "if", "not", "0", "<=", "p", "<", "length", ":", "raise", "IndexError", "(", "\"Bit position {0} out of range.\"", ".", "format", "(", "p", ")", ")", "f", "(", "p", ")", "except", "TypeError", ":", "# Single pos", "if", "pos", "<", "0", ":", "pos", "+=", "self", ".", "len", "if", "not", "0", "<=", "pos", "<", "length", ":", "raise", "IndexError", "(", "\"Bit position {0} out of range.\"", ".", "format", "(", "pos", ")", ")", "f", "(", "pos", ")" ]
Set one or many bits to 1 or 0. value -- If True bits are set to 1, otherwise they are set to 0. pos -- Either a single bit position or an iterable of bit positions. Negative numbers are treated in the same way as slice indices. Defaults to the entire bitstring. Raises IndexError if pos < -self.len or pos >= self.len.
[ "Set", "one", "or", "many", "bits", "to", "1", "or", "0", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L3456-L3484
train
scott-griffiths/bitstring
bitstring.py
BitArray.invert
def invert(self, pos=None): """Invert one or many bits from 0 to 1 or vice versa. pos -- Either a single bit position or an iterable of bit positions. Negative numbers are treated in the same way as slice indices. Raises IndexError if pos < -self.len or pos >= self.len. """ if pos is None: self._invert_all() return if not isinstance(pos, collections.Iterable): pos = (pos,) length = self.len for p in pos: if p < 0: p += length if not 0 <= p < length: raise IndexError("Bit position {0} out of range.".format(p)) self._invert(p)
python
def invert(self, pos=None): """Invert one or many bits from 0 to 1 or vice versa. pos -- Either a single bit position or an iterable of bit positions. Negative numbers are treated in the same way as slice indices. Raises IndexError if pos < -self.len or pos >= self.len. """ if pos is None: self._invert_all() return if not isinstance(pos, collections.Iterable): pos = (pos,) length = self.len for p in pos: if p < 0: p += length if not 0 <= p < length: raise IndexError("Bit position {0} out of range.".format(p)) self._invert(p)
[ "def", "invert", "(", "self", ",", "pos", "=", "None", ")", ":", "if", "pos", "is", "None", ":", "self", ".", "_invert_all", "(", ")", "return", "if", "not", "isinstance", "(", "pos", ",", "collections", ".", "Iterable", ")", ":", "pos", "=", "(", "pos", ",", ")", "length", "=", "self", ".", "len", "for", "p", "in", "pos", ":", "if", "p", "<", "0", ":", "p", "+=", "length", "if", "not", "0", "<=", "p", "<", "length", ":", "raise", "IndexError", "(", "\"Bit position {0} out of range.\"", ".", "format", "(", "p", ")", ")", "self", ".", "_invert", "(", "p", ")" ]
Invert one or many bits from 0 to 1 or vice versa. pos -- Either a single bit position or an iterable of bit positions. Negative numbers are treated in the same way as slice indices. Raises IndexError if pos < -self.len or pos >= self.len.
[ "Invert", "one", "or", "many", "bits", "from", "0", "to", "1", "or", "vice", "versa", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L3486-L3507
train
scott-griffiths/bitstring
bitstring.py
BitArray.ror
def ror(self, bits, start=None, end=None): """Rotate bits to the right in-place. bits -- The number of bits to rotate by. start -- Start of slice to rotate. Defaults to 0. end -- End of slice to rotate. Defaults to self.len. Raises ValueError if bits < 0. """ if not self.len: raise Error("Cannot rotate an empty bitstring.") if bits < 0: raise ValueError("Cannot rotate right by negative amount.") start, end = self._validate_slice(start, end) bits %= (end - start) if not bits: return rhs = self._slice(end - bits, end) self._delete(bits, end - bits) self._insert(rhs, start)
python
def ror(self, bits, start=None, end=None): """Rotate bits to the right in-place. bits -- The number of bits to rotate by. start -- Start of slice to rotate. Defaults to 0. end -- End of slice to rotate. Defaults to self.len. Raises ValueError if bits < 0. """ if not self.len: raise Error("Cannot rotate an empty bitstring.") if bits < 0: raise ValueError("Cannot rotate right by negative amount.") start, end = self._validate_slice(start, end) bits %= (end - start) if not bits: return rhs = self._slice(end - bits, end) self._delete(bits, end - bits) self._insert(rhs, start)
[ "def", "ror", "(", "self", ",", "bits", ",", "start", "=", "None", ",", "end", "=", "None", ")", ":", "if", "not", "self", ".", "len", ":", "raise", "Error", "(", "\"Cannot rotate an empty bitstring.\"", ")", "if", "bits", "<", "0", ":", "raise", "ValueError", "(", "\"Cannot rotate right by negative amount.\"", ")", "start", ",", "end", "=", "self", ".", "_validate_slice", "(", "start", ",", "end", ")", "bits", "%=", "(", "end", "-", "start", ")", "if", "not", "bits", ":", "return", "rhs", "=", "self", ".", "_slice", "(", "end", "-", "bits", ",", "end", ")", "self", ".", "_delete", "(", "bits", ",", "end", "-", "bits", ")", "self", ".", "_insert", "(", "rhs", ",", "start", ")" ]
Rotate bits to the right in-place. bits -- The number of bits to rotate by. start -- Start of slice to rotate. Defaults to 0. end -- End of slice to rotate. Defaults to self.len. Raises ValueError if bits < 0.
[ "Rotate", "bits", "to", "the", "right", "in", "-", "place", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L3509-L3529
train
scott-griffiths/bitstring
bitstring.py
BitArray.rol
def rol(self, bits, start=None, end=None): """Rotate bits to the left in-place. bits -- The number of bits to rotate by. start -- Start of slice to rotate. Defaults to 0. end -- End of slice to rotate. Defaults to self.len. Raises ValueError if bits < 0. """ 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)
python
def rol(self, bits, start=None, end=None): """Rotate bits to the left in-place. bits -- The number of bits to rotate by. start -- Start of slice to rotate. Defaults to 0. end -- End of slice to rotate. Defaults to self.len. Raises ValueError if bits < 0. """ 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)
[ "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", ")" ]
Rotate bits to the left in-place. bits -- The number of bits to rotate by. start -- Start of slice to rotate. Defaults to 0. end -- End of slice to rotate. Defaults to self.len. Raises ValueError if bits < 0.
[ "Rotate", "bits", "to", "the", "left", "in", "-", "place", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L3531-L3551
train
scott-griffiths/bitstring
bitstring.py
BitArray.byteswap
def byteswap(self, fmt=None, start=None, end=None, repeat=True): """Change the endianness in-place. Return number of repeats of fmt done. fmt -- A compact structure string, an integer number of bytes or an iterable of integers. Defaults to 0, which byte reverses the whole bitstring. start -- Start bit position, defaults to 0. end -- End bit position, defaults to self.len. repeat -- If True (the default) the byte swapping pattern is repeated as much as possible. """ start, end = self._validate_slice(start, end) if fmt is None or fmt == 0: # reverse all of the whole bytes. bytesizes = [(end - start) // 8] elif isinstance(fmt, numbers.Integral): if fmt < 0: raise ValueError("Improper byte length {0}.".format(fmt)) bytesizes = [fmt] elif isinstance(fmt, basestring): m = STRUCT_PACK_RE.match(fmt) if not m: raise ValueError("Cannot parse format string {0}.".format(fmt)) # Split the format string into a list of 'q', '4h' etc. formatlist = re.findall(STRUCT_SPLIT_RE, m.group('fmt')) # Now deal with multiplicative factors, 4h -> hhhh etc. bytesizes = [] for f in formatlist: if len(f) == 1: bytesizes.append(PACK_CODE_SIZE[f]) else: bytesizes.extend([PACK_CODE_SIZE[f[-1]]] * int(f[:-1])) elif isinstance(fmt, collections.Iterable): bytesizes = fmt for bytesize in bytesizes: if not isinstance(bytesize, numbers.Integral) or bytesize < 0: raise ValueError("Improper byte length {0}.".format(bytesize)) else: raise TypeError("Format must be an integer, string or iterable.") repeats = 0 totalbitsize = 8 * sum(bytesizes) if not totalbitsize: return 0 if repeat: # Try to repeat up to the end of the bitstring. finalbit = end else: # Just try one (set of) byteswap(s). finalbit = start + totalbitsize for patternend in xrange(start + totalbitsize, finalbit + 1, totalbitsize): bytestart = patternend - totalbitsize for bytesize in bytesizes: byteend = bytestart + bytesize * 8 self._reversebytes(bytestart, byteend) bytestart += bytesize * 8 repeats += 1 return repeats
python
def byteswap(self, fmt=None, start=None, end=None, repeat=True): """Change the endianness in-place. Return number of repeats of fmt done. fmt -- A compact structure string, an integer number of bytes or an iterable of integers. Defaults to 0, which byte reverses the whole bitstring. start -- Start bit position, defaults to 0. end -- End bit position, defaults to self.len. repeat -- If True (the default) the byte swapping pattern is repeated as much as possible. """ start, end = self._validate_slice(start, end) if fmt is None or fmt == 0: # reverse all of the whole bytes. bytesizes = [(end - start) // 8] elif isinstance(fmt, numbers.Integral): if fmt < 0: raise ValueError("Improper byte length {0}.".format(fmt)) bytesizes = [fmt] elif isinstance(fmt, basestring): m = STRUCT_PACK_RE.match(fmt) if not m: raise ValueError("Cannot parse format string {0}.".format(fmt)) # Split the format string into a list of 'q', '4h' etc. formatlist = re.findall(STRUCT_SPLIT_RE, m.group('fmt')) # Now deal with multiplicative factors, 4h -> hhhh etc. bytesizes = [] for f in formatlist: if len(f) == 1: bytesizes.append(PACK_CODE_SIZE[f]) else: bytesizes.extend([PACK_CODE_SIZE[f[-1]]] * int(f[:-1])) elif isinstance(fmt, collections.Iterable): bytesizes = fmt for bytesize in bytesizes: if not isinstance(bytesize, numbers.Integral) or bytesize < 0: raise ValueError("Improper byte length {0}.".format(bytesize)) else: raise TypeError("Format must be an integer, string or iterable.") repeats = 0 totalbitsize = 8 * sum(bytesizes) if not totalbitsize: return 0 if repeat: # Try to repeat up to the end of the bitstring. finalbit = end else: # Just try one (set of) byteswap(s). finalbit = start + totalbitsize for patternend in xrange(start + totalbitsize, finalbit + 1, totalbitsize): bytestart = patternend - totalbitsize for bytesize in bytesizes: byteend = bytestart + bytesize * 8 self._reversebytes(bytestart, byteend) bytestart += bytesize * 8 repeats += 1 return repeats
[ "def", "byteswap", "(", "self", ",", "fmt", "=", "None", ",", "start", "=", "None", ",", "end", "=", "None", ",", "repeat", "=", "True", ")", ":", "start", ",", "end", "=", "self", ".", "_validate_slice", "(", "start", ",", "end", ")", "if", "fmt", "is", "None", "or", "fmt", "==", "0", ":", "# reverse all of the whole bytes.", "bytesizes", "=", "[", "(", "end", "-", "start", ")", "//", "8", "]", "elif", "isinstance", "(", "fmt", ",", "numbers", ".", "Integral", ")", ":", "if", "fmt", "<", "0", ":", "raise", "ValueError", "(", "\"Improper byte length {0}.\"", ".", "format", "(", "fmt", ")", ")", "bytesizes", "=", "[", "fmt", "]", "elif", "isinstance", "(", "fmt", ",", "basestring", ")", ":", "m", "=", "STRUCT_PACK_RE", ".", "match", "(", "fmt", ")", "if", "not", "m", ":", "raise", "ValueError", "(", "\"Cannot parse format string {0}.\"", ".", "format", "(", "fmt", ")", ")", "# Split the format string into a list of 'q', '4h' etc.", "formatlist", "=", "re", ".", "findall", "(", "STRUCT_SPLIT_RE", ",", "m", ".", "group", "(", "'fmt'", ")", ")", "# Now deal with multiplicative factors, 4h -> hhhh etc.", "bytesizes", "=", "[", "]", "for", "f", "in", "formatlist", ":", "if", "len", "(", "f", ")", "==", "1", ":", "bytesizes", ".", "append", "(", "PACK_CODE_SIZE", "[", "f", "]", ")", "else", ":", "bytesizes", ".", "extend", "(", "[", "PACK_CODE_SIZE", "[", "f", "[", "-", "1", "]", "]", "]", "*", "int", "(", "f", "[", ":", "-", "1", "]", ")", ")", "elif", "isinstance", "(", "fmt", ",", "collections", ".", "Iterable", ")", ":", "bytesizes", "=", "fmt", "for", "bytesize", "in", "bytesizes", ":", "if", "not", "isinstance", "(", "bytesize", ",", "numbers", ".", "Integral", ")", "or", "bytesize", "<", "0", ":", "raise", "ValueError", "(", "\"Improper byte length {0}.\"", ".", "format", "(", "bytesize", ")", ")", "else", ":", "raise", "TypeError", "(", "\"Format must be an integer, string or iterable.\"", ")", "repeats", "=", "0", "totalbitsize", "=", "8", "*", "sum", "(", "bytesizes", ")", "if", "not", "totalbitsize", ":", "return", "0", "if", "repeat", ":", "# Try to repeat up to the end of the bitstring.", "finalbit", "=", "end", "else", ":", "# Just try one (set of) byteswap(s).", "finalbit", "=", "start", "+", "totalbitsize", "for", "patternend", "in", "xrange", "(", "start", "+", "totalbitsize", ",", "finalbit", "+", "1", ",", "totalbitsize", ")", ":", "bytestart", "=", "patternend", "-", "totalbitsize", "for", "bytesize", "in", "bytesizes", ":", "byteend", "=", "bytestart", "+", "bytesize", "*", "8", "self", ".", "_reversebytes", "(", "bytestart", ",", "byteend", ")", "bytestart", "+=", "bytesize", "*", "8", "repeats", "+=", "1", "return", "repeats" ]
Change the endianness in-place. Return number of repeats of fmt done. fmt -- A compact structure string, an integer number of bytes or an iterable of integers. Defaults to 0, which byte reverses the whole bitstring. start -- Start bit position, defaults to 0. end -- End bit position, defaults to self.len. repeat -- If True (the default) the byte swapping pattern is repeated as much as possible.
[ "Change", "the", "endianness", "in", "-", "place", ".", "Return", "number", "of", "repeats", "of", "fmt", "done", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L3553-L3611
train
scott-griffiths/bitstring
bitstring.py
ConstBitStream._setbitpos
def _setbitpos(self, pos): """Move to absolute postion bit in bitstream.""" if pos < 0: raise ValueError("Bit position cannot be negative.") if pos > self.len: raise ValueError("Cannot seek past the end of the data.") self._pos = pos
python
def _setbitpos(self, pos): """Move to absolute postion bit in bitstream.""" if pos < 0: raise ValueError("Bit position cannot be negative.") if pos > self.len: raise ValueError("Cannot seek past the end of the data.") self._pos = pos
[ "def", "_setbitpos", "(", "self", ",", "pos", ")", ":", "if", "pos", "<", "0", ":", "raise", "ValueError", "(", "\"Bit position cannot be negative.\"", ")", "if", "pos", ">", "self", ".", "len", ":", "raise", "ValueError", "(", "\"Cannot seek past the end of the data.\"", ")", "self", ".", "_pos", "=", "pos" ]
Move to absolute postion bit in bitstream.
[ "Move", "to", "absolute", "postion", "bit", "in", "bitstream", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L3806-L3812
train
scott-griffiths/bitstring
bitstring.py
ConstBitStream.read
def read(self, fmt): """Interpret next bits according to the format string and return result. fmt -- Token string describing how to interpret the next bits. Token examples: 'int:12' : 12 bits as a signed integer 'uint:8' : 8 bits as an unsigned integer 'float:64' : 8 bytes as a big-endian float 'intbe:16' : 2 bytes as a big-endian signed integer 'uintbe:16' : 2 bytes as a big-endian unsigned integer 'intle:32' : 4 bytes as a little-endian signed integer 'uintle:32' : 4 bytes as a little-endian unsigned integer 'floatle:64': 8 bytes as a little-endian float 'intne:24' : 3 bytes as a native-endian signed integer 'uintne:24' : 3 bytes as a native-endian unsigned integer 'floatne:32': 4 bytes as a native-endian float 'hex:80' : 80 bits as a hex string 'oct:9' : 9 bits as an octal string 'bin:1' : single bit binary string 'ue' : next bits as unsigned exp-Golomb code 'se' : next bits as signed exp-Golomb code 'uie' : next bits as unsigned interleaved exp-Golomb code 'sie' : next bits as signed interleaved exp-Golomb code 'bits:5' : 5 bits as a bitstring 'bytes:10' : 10 bytes as a bytes object 'bool' : 1 bit as a bool 'pad:3' : 3 bits of padding to ignore - returns None fmt may also be an integer, which will be treated like the 'bits' token. The position in the bitstring is advanced to after the read items. Raises ReadError if not enough bits are available. Raises ValueError if the format is not understood. """ if isinstance(fmt, numbers.Integral): if fmt < 0: raise ValueError("Cannot read negative amount.") if fmt > self.len - self._pos: raise ReadError("Cannot read {0} bits, only {1} available.", fmt, self.len - self._pos) bs = self._slice(self._pos, self._pos + fmt) self._pos += fmt return bs p = self._pos _, token = tokenparser(fmt) if len(token) != 1: self._pos = p raise ValueError("Format string should be a single token, not {0} " "tokens - use readlist() instead.".format(len(token))) name, length, _ = token[0] if length is None: length = self.len - self._pos value, self._pos = self._readtoken(name, self._pos, length) return value
python
def read(self, fmt): """Interpret next bits according to the format string and return result. fmt -- Token string describing how to interpret the next bits. Token examples: 'int:12' : 12 bits as a signed integer 'uint:8' : 8 bits as an unsigned integer 'float:64' : 8 bytes as a big-endian float 'intbe:16' : 2 bytes as a big-endian signed integer 'uintbe:16' : 2 bytes as a big-endian unsigned integer 'intle:32' : 4 bytes as a little-endian signed integer 'uintle:32' : 4 bytes as a little-endian unsigned integer 'floatle:64': 8 bytes as a little-endian float 'intne:24' : 3 bytes as a native-endian signed integer 'uintne:24' : 3 bytes as a native-endian unsigned integer 'floatne:32': 4 bytes as a native-endian float 'hex:80' : 80 bits as a hex string 'oct:9' : 9 bits as an octal string 'bin:1' : single bit binary string 'ue' : next bits as unsigned exp-Golomb code 'se' : next bits as signed exp-Golomb code 'uie' : next bits as unsigned interleaved exp-Golomb code 'sie' : next bits as signed interleaved exp-Golomb code 'bits:5' : 5 bits as a bitstring 'bytes:10' : 10 bytes as a bytes object 'bool' : 1 bit as a bool 'pad:3' : 3 bits of padding to ignore - returns None fmt may also be an integer, which will be treated like the 'bits' token. The position in the bitstring is advanced to after the read items. Raises ReadError if not enough bits are available. Raises ValueError if the format is not understood. """ if isinstance(fmt, numbers.Integral): if fmt < 0: raise ValueError("Cannot read negative amount.") if fmt > self.len - self._pos: raise ReadError("Cannot read {0} bits, only {1} available.", fmt, self.len - self._pos) bs = self._slice(self._pos, self._pos + fmt) self._pos += fmt return bs p = self._pos _, token = tokenparser(fmt) if len(token) != 1: self._pos = p raise ValueError("Format string should be a single token, not {0} " "tokens - use readlist() instead.".format(len(token))) name, length, _ = token[0] if length is None: length = self.len - self._pos value, self._pos = self._readtoken(name, self._pos, length) return value
[ "def", "read", "(", "self", ",", "fmt", ")", ":", "if", "isinstance", "(", "fmt", ",", "numbers", ".", "Integral", ")", ":", "if", "fmt", "<", "0", ":", "raise", "ValueError", "(", "\"Cannot read negative amount.\"", ")", "if", "fmt", ">", "self", ".", "len", "-", "self", ".", "_pos", ":", "raise", "ReadError", "(", "\"Cannot read {0} bits, only {1} available.\"", ",", "fmt", ",", "self", ".", "len", "-", "self", ".", "_pos", ")", "bs", "=", "self", ".", "_slice", "(", "self", ".", "_pos", ",", "self", ".", "_pos", "+", "fmt", ")", "self", ".", "_pos", "+=", "fmt", "return", "bs", "p", "=", "self", ".", "_pos", "_", ",", "token", "=", "tokenparser", "(", "fmt", ")", "if", "len", "(", "token", ")", "!=", "1", ":", "self", ".", "_pos", "=", "p", "raise", "ValueError", "(", "\"Format string should be a single token, not {0} \"", "\"tokens - use readlist() instead.\"", ".", "format", "(", "len", "(", "token", ")", ")", ")", "name", ",", "length", ",", "_", "=", "token", "[", "0", "]", "if", "length", "is", "None", ":", "length", "=", "self", ".", "len", "-", "self", ".", "_pos", "value", ",", "self", ".", "_pos", "=", "self", ".", "_readtoken", "(", "name", ",", "self", ".", "_pos", ",", "length", ")", "return", "value" ]
Interpret next bits according to the format string and return result. fmt -- Token string describing how to interpret the next bits. Token examples: 'int:12' : 12 bits as a signed integer 'uint:8' : 8 bits as an unsigned integer 'float:64' : 8 bytes as a big-endian float 'intbe:16' : 2 bytes as a big-endian signed integer 'uintbe:16' : 2 bytes as a big-endian unsigned integer 'intle:32' : 4 bytes as a little-endian signed integer 'uintle:32' : 4 bytes as a little-endian unsigned integer 'floatle:64': 8 bytes as a little-endian float 'intne:24' : 3 bytes as a native-endian signed integer 'uintne:24' : 3 bytes as a native-endian unsigned integer 'floatne:32': 4 bytes as a native-endian float 'hex:80' : 80 bits as a hex string 'oct:9' : 9 bits as an octal string 'bin:1' : single bit binary string 'ue' : next bits as unsigned exp-Golomb code 'se' : next bits as signed exp-Golomb code 'uie' : next bits as unsigned interleaved exp-Golomb code 'sie' : next bits as signed interleaved exp-Golomb code 'bits:5' : 5 bits as a bitstring 'bytes:10' : 10 bytes as a bytes object 'bool' : 1 bit as a bool 'pad:3' : 3 bits of padding to ignore - returns None fmt may also be an integer, which will be treated like the 'bits' token. The position in the bitstring is advanced to after the read items. Raises ReadError if not enough bits are available. Raises ValueError if the format is not understood.
[ "Interpret", "next", "bits", "according", "to", "the", "format", "string", "and", "return", "result", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L3842-L3897
train
scott-griffiths/bitstring
bitstring.py
ConstBitStream.readto
def readto(self, bs, bytealigned=None): """Read up to and including next occurrence of bs and return result. bs -- The bitstring to find. An integer is not permitted. bytealigned -- If True the bitstring will only be found on byte boundaries. Raises ValueError if bs is empty. Raises ReadError if bs is not found. """ if isinstance(bs, numbers.Integral): raise ValueError("Integers cannot be searched for") bs = Bits(bs) oldpos = self._pos p = self.find(bs, self._pos, bytealigned=bytealigned) if not p: raise ReadError("Substring not found") self._pos += bs.len return self._slice(oldpos, self._pos)
python
def readto(self, bs, bytealigned=None): """Read up to and including next occurrence of bs and return result. bs -- The bitstring to find. An integer is not permitted. bytealigned -- If True the bitstring will only be found on byte boundaries. Raises ValueError if bs is empty. Raises ReadError if bs is not found. """ if isinstance(bs, numbers.Integral): raise ValueError("Integers cannot be searched for") bs = Bits(bs) oldpos = self._pos p = self.find(bs, self._pos, bytealigned=bytealigned) if not p: raise ReadError("Substring not found") self._pos += bs.len return self._slice(oldpos, self._pos)
[ "def", "readto", "(", "self", ",", "bs", ",", "bytealigned", "=", "None", ")", ":", "if", "isinstance", "(", "bs", ",", "numbers", ".", "Integral", ")", ":", "raise", "ValueError", "(", "\"Integers cannot be searched for\"", ")", "bs", "=", "Bits", "(", "bs", ")", "oldpos", "=", "self", ".", "_pos", "p", "=", "self", ".", "find", "(", "bs", ",", "self", ".", "_pos", ",", "bytealigned", "=", "bytealigned", ")", "if", "not", "p", ":", "raise", "ReadError", "(", "\"Substring not found\"", ")", "self", ".", "_pos", "+=", "bs", ".", "len", "return", "self", ".", "_slice", "(", "oldpos", ",", "self", ".", "_pos", ")" ]
Read up to and including next occurrence of bs and return result. bs -- The bitstring to find. An integer is not permitted. bytealigned -- If True the bitstring will only be found on byte boundaries. Raises ValueError if bs is empty. Raises ReadError if bs is not found.
[ "Read", "up", "to", "and", "including", "next", "occurrence", "of", "bs", "and", "return", "result", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L3923-L3942
train
scott-griffiths/bitstring
bitstring.py
ConstBitStream.peek
def peek(self, fmt): """Interpret next bits according to format string and return result. fmt -- Token string describing how to interpret the next bits. The position in the bitstring is not changed. If not enough bits are available then all bits to the end of the bitstring will be used. Raises ReadError if not enough bits are available. Raises ValueError if the format is not understood. See the docstring for 'read' for token examples. """ pos_before = self._pos value = self.read(fmt) self._pos = pos_before return value
python
def peek(self, fmt): """Interpret next bits according to format string and return result. fmt -- Token string describing how to interpret the next bits. The position in the bitstring is not changed. If not enough bits are available then all bits to the end of the bitstring will be used. Raises ReadError if not enough bits are available. Raises ValueError if the format is not understood. See the docstring for 'read' for token examples. """ pos_before = self._pos value = self.read(fmt) self._pos = pos_before return value
[ "def", "peek", "(", "self", ",", "fmt", ")", ":", "pos_before", "=", "self", ".", "_pos", "value", "=", "self", ".", "read", "(", "fmt", ")", "self", ".", "_pos", "=", "pos_before", "return", "value" ]
Interpret next bits according to format string and return result. fmt -- Token string describing how to interpret the next bits. The position in the bitstring is not changed. If not enough bits are available then all bits to the end of the bitstring will be used. Raises ReadError if not enough bits are available. Raises ValueError if the format is not understood. See the docstring for 'read' for token examples.
[ "Interpret", "next", "bits", "according", "to", "format", "string", "and", "return", "result", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L3944-L3961
train
scott-griffiths/bitstring
bitstring.py
ConstBitStream.bytealign
def bytealign(self): """Align to next byte and return number of skipped bits. Raises ValueError if the end of the bitstring is reached before aligning to the next byte. """ skipped = (8 - (self._pos % 8)) % 8 self.pos += self._offset + skipped assert self._assertsanity() return skipped
python
def bytealign(self): """Align to next byte and return number of skipped bits. Raises ValueError if the end of the bitstring is reached before aligning to the next byte. """ skipped = (8 - (self._pos % 8)) % 8 self.pos += self._offset + skipped assert self._assertsanity() return skipped
[ "def", "bytealign", "(", "self", ")", ":", "skipped", "=", "(", "8", "-", "(", "self", ".", "_pos", "%", "8", ")", ")", "%", "8", "self", ".", "pos", "+=", "self", ".", "_offset", "+", "skipped", "assert", "self", ".", "_assertsanity", "(", ")", "return", "skipped" ]
Align to next byte and return number of skipped bits. Raises ValueError if the end of the bitstring is reached before aligning to the next byte.
[ "Align", "to", "next", "byte", "and", "return", "number", "of", "skipped", "bits", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L3985-L3995
train
scott-griffiths/bitstring
bitstring.py
BitStream.prepend
def prepend(self, bs): """Prepend a bitstring to the current bitstring. bs -- The bitstring to prepend. """ bs = self._converttobitstring(bs) self._prepend(bs) self._pos += bs.len
python
def prepend(self, bs): """Prepend a bitstring to the current bitstring. bs -- The bitstring to prepend. """ bs = self._converttobitstring(bs) self._prepend(bs) self._pos += bs.len
[ "def", "prepend", "(", "self", ",", "bs", ")", ":", "bs", "=", "self", ".", "_converttobitstring", "(", "bs", ")", "self", ".", "_prepend", "(", "bs", ")", "self", ".", "_pos", "+=", "bs", ".", "len" ]
Prepend a bitstring to the current bitstring. bs -- The bitstring to prepend.
[ "Prepend", "a", "bitstring", "to", "the", "current", "bitstring", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L4150-L4158
train
g2p/bedup
bedup/dedup.py
find_inodes_in_use
def find_inodes_in_use(fds): """ Find which of these inodes are in use, and give their open modes. Does not count the passed fds as an use of the inode they point to, but if the current process has the same inodes open with different file descriptors these will be listed. Looks at /proc/*/fd and /proc/*/map_files (Linux 3.3). Conceivably there are other uses we're missing, to be foolproof will require support in btrfs itself; a share-same-range ioctl would work well. """ self_pid = os.getpid() id_fd_assoc = collections.defaultdict(list) for fd in fds: st = os.fstat(fd) id_fd_assoc[(st.st_dev, st.st_ino)].append(fd) def st_id_candidates(it): # map proc paths to stat identifiers (devno and ino) for proc_path in it: try: st = os.stat(proc_path) except OSError as e: # glob opens directories during matching, # and other processes might close their fds in the meantime. # This isn't a problem for the immutable-locked use case. # ESTALE could happen with NFS or Docker if e.errno in (errno.ENOENT, errno.ESTALE): continue raise st_id = (st.st_dev, st.st_ino) if st_id not in id_fd_assoc: continue yield proc_path, st_id for proc_path, st_id in st_id_candidates(glob.glob('/proc/[1-9]*/fd/*')): other_pid, other_fd = map( int, PROC_PATH_RE.match(proc_path).groups()) original_fds = id_fd_assoc[st_id] if other_pid == self_pid: if other_fd in original_fds: continue use_info = proc_use_info(proc_path) if not use_info: continue for fd in original_fds: yield (fd, use_info) # Requires Linux 3.3 for proc_path, st_id in st_id_candidates( glob.glob('/proc/[1-9]*/map_files/*') ): use_info = proc_use_info(proc_path) if not use_info: continue original_fds = id_fd_assoc[st_id] for fd in original_fds: yield (fd, use_info)
python
def find_inodes_in_use(fds): """ Find which of these inodes are in use, and give their open modes. Does not count the passed fds as an use of the inode they point to, but if the current process has the same inodes open with different file descriptors these will be listed. Looks at /proc/*/fd and /proc/*/map_files (Linux 3.3). Conceivably there are other uses we're missing, to be foolproof will require support in btrfs itself; a share-same-range ioctl would work well. """ self_pid = os.getpid() id_fd_assoc = collections.defaultdict(list) for fd in fds: st = os.fstat(fd) id_fd_assoc[(st.st_dev, st.st_ino)].append(fd) def st_id_candidates(it): # map proc paths to stat identifiers (devno and ino) for proc_path in it: try: st = os.stat(proc_path) except OSError as e: # glob opens directories during matching, # and other processes might close their fds in the meantime. # This isn't a problem for the immutable-locked use case. # ESTALE could happen with NFS or Docker if e.errno in (errno.ENOENT, errno.ESTALE): continue raise st_id = (st.st_dev, st.st_ino) if st_id not in id_fd_assoc: continue yield proc_path, st_id for proc_path, st_id in st_id_candidates(glob.glob('/proc/[1-9]*/fd/*')): other_pid, other_fd = map( int, PROC_PATH_RE.match(proc_path).groups()) original_fds = id_fd_assoc[st_id] if other_pid == self_pid: if other_fd in original_fds: continue use_info = proc_use_info(proc_path) if not use_info: continue for fd in original_fds: yield (fd, use_info) # Requires Linux 3.3 for proc_path, st_id in st_id_candidates( glob.glob('/proc/[1-9]*/map_files/*') ): use_info = proc_use_info(proc_path) if not use_info: continue original_fds = id_fd_assoc[st_id] for fd in original_fds: yield (fd, use_info)
[ "def", "find_inodes_in_use", "(", "fds", ")", ":", "self_pid", "=", "os", ".", "getpid", "(", ")", "id_fd_assoc", "=", "collections", ".", "defaultdict", "(", "list", ")", "for", "fd", "in", "fds", ":", "st", "=", "os", ".", "fstat", "(", "fd", ")", "id_fd_assoc", "[", "(", "st", ".", "st_dev", ",", "st", ".", "st_ino", ")", "]", ".", "append", "(", "fd", ")", "def", "st_id_candidates", "(", "it", ")", ":", "# map proc paths to stat identifiers (devno and ino)", "for", "proc_path", "in", "it", ":", "try", ":", "st", "=", "os", ".", "stat", "(", "proc_path", ")", "except", "OSError", "as", "e", ":", "# glob opens directories during matching,", "# and other processes might close their fds in the meantime.", "# This isn't a problem for the immutable-locked use case.", "# ESTALE could happen with NFS or Docker", "if", "e", ".", "errno", "in", "(", "errno", ".", "ENOENT", ",", "errno", ".", "ESTALE", ")", ":", "continue", "raise", "st_id", "=", "(", "st", ".", "st_dev", ",", "st", ".", "st_ino", ")", "if", "st_id", "not", "in", "id_fd_assoc", ":", "continue", "yield", "proc_path", ",", "st_id", "for", "proc_path", ",", "st_id", "in", "st_id_candidates", "(", "glob", ".", "glob", "(", "'/proc/[1-9]*/fd/*'", ")", ")", ":", "other_pid", ",", "other_fd", "=", "map", "(", "int", ",", "PROC_PATH_RE", ".", "match", "(", "proc_path", ")", ".", "groups", "(", ")", ")", "original_fds", "=", "id_fd_assoc", "[", "st_id", "]", "if", "other_pid", "==", "self_pid", ":", "if", "other_fd", "in", "original_fds", ":", "continue", "use_info", "=", "proc_use_info", "(", "proc_path", ")", "if", "not", "use_info", ":", "continue", "for", "fd", "in", "original_fds", ":", "yield", "(", "fd", ",", "use_info", ")", "# Requires Linux 3.3", "for", "proc_path", ",", "st_id", "in", "st_id_candidates", "(", "glob", ".", "glob", "(", "'/proc/[1-9]*/map_files/*'", ")", ")", ":", "use_info", "=", "proc_use_info", "(", "proc_path", ")", "if", "not", "use_info", ":", "continue", "original_fds", "=", "id_fd_assoc", "[", "st_id", "]", "for", "fd", "in", "original_fds", ":", "yield", "(", "fd", ",", "use_info", ")" ]
Find which of these inodes are in use, and give their open modes. Does not count the passed fds as an use of the inode they point to, but if the current process has the same inodes open with different file descriptors these will be listed. Looks at /proc/*/fd and /proc/*/map_files (Linux 3.3). Conceivably there are other uses we're missing, to be foolproof will require support in btrfs itself; a share-same-range ioctl would work well.
[ "Find", "which", "of", "these", "inodes", "are", "in", "use", "and", "give", "their", "open", "modes", "." ]
9694f6f718844c33017052eb271f68b6c0d0b7d3
https://github.com/g2p/bedup/blob/9694f6f718844c33017052eb271f68b6c0d0b7d3/bedup/dedup.py#L120-L186
train
g2p/bedup
bedup/platform/ioprio.py
set_idle_priority
def set_idle_priority(pid=None): """ Puts a process in the idle io priority class. If pid is omitted, applies to the current process. """ if pid is None: pid = os.getpid() lib.ioprio_set( lib.IOPRIO_WHO_PROCESS, pid, lib.IOPRIO_PRIO_VALUE(lib.IOPRIO_CLASS_IDLE, 0))
python
def set_idle_priority(pid=None): """ Puts a process in the idle io priority class. If pid is omitted, applies to the current process. """ if pid is None: pid = os.getpid() lib.ioprio_set( lib.IOPRIO_WHO_PROCESS, pid, lib.IOPRIO_PRIO_VALUE(lib.IOPRIO_CLASS_IDLE, 0))
[ "def", "set_idle_priority", "(", "pid", "=", "None", ")", ":", "if", "pid", "is", "None", ":", "pid", "=", "os", ".", "getpid", "(", ")", "lib", ".", "ioprio_set", "(", "lib", ".", "IOPRIO_WHO_PROCESS", ",", "pid", ",", "lib", ".", "IOPRIO_PRIO_VALUE", "(", "lib", ".", "IOPRIO_CLASS_IDLE", ",", "0", ")", ")" ]
Puts a process in the idle io priority class. If pid is omitted, applies to the current process.
[ "Puts", "a", "process", "in", "the", "idle", "io", "priority", "class", "." ]
9694f6f718844c33017052eb271f68b6c0d0b7d3
https://github.com/g2p/bedup/blob/9694f6f718844c33017052eb271f68b6c0d0b7d3/bedup/platform/ioprio.py#L82-L93
train
g2p/bedup
bedup/platform/futimens.py
futimens
def futimens(fd, ns): """ set inode atime and mtime ns is (atime, mtime), a pair of struct timespec with nanosecond resolution. """ # ctime can't easily be reset # also, we have no way to do mandatory locking without # changing the ctime. times = ffi.new('struct timespec[2]') atime, mtime = ns assert 0 <= atime.tv_nsec < 1e9 assert 0 <= mtime.tv_nsec < 1e9 times[0] = atime times[1] = mtime if lib.futimens(fd, times) != 0: raise IOError( ffi.errno, os.strerror(ffi.errno), (fd, atime.tv_sec, atime.tv_nsec, mtime.tv_sec, mtime.tv_nsec))
python
def futimens(fd, ns): """ set inode atime and mtime ns is (atime, mtime), a pair of struct timespec with nanosecond resolution. """ # ctime can't easily be reset # also, we have no way to do mandatory locking without # changing the ctime. times = ffi.new('struct timespec[2]') atime, mtime = ns assert 0 <= atime.tv_nsec < 1e9 assert 0 <= mtime.tv_nsec < 1e9 times[0] = atime times[1] = mtime if lib.futimens(fd, times) != 0: raise IOError( ffi.errno, os.strerror(ffi.errno), (fd, atime.tv_sec, atime.tv_nsec, mtime.tv_sec, mtime.tv_nsec))
[ "def", "futimens", "(", "fd", ",", "ns", ")", ":", "# ctime can't easily be reset", "# also, we have no way to do mandatory locking without", "# changing the ctime.", "times", "=", "ffi", ".", "new", "(", "'struct timespec[2]'", ")", "atime", ",", "mtime", "=", "ns", "assert", "0", "<=", "atime", ".", "tv_nsec", "<", "1e9", "assert", "0", "<=", "mtime", ".", "tv_nsec", "<", "1e9", "times", "[", "0", "]", "=", "atime", "times", "[", "1", "]", "=", "mtime", "if", "lib", ".", "futimens", "(", "fd", ",", "times", ")", "!=", "0", ":", "raise", "IOError", "(", "ffi", ".", "errno", ",", "os", ".", "strerror", "(", "ffi", ".", "errno", ")", ",", "(", "fd", ",", "atime", ".", "tv_sec", ",", "atime", ".", "tv_nsec", ",", "mtime", ".", "tv_sec", ",", "mtime", ".", "tv_nsec", ")", ")" ]
set inode atime and mtime ns is (atime, mtime), a pair of struct timespec with nanosecond resolution.
[ "set", "inode", "atime", "and", "mtime" ]
9694f6f718844c33017052eb271f68b6c0d0b7d3
https://github.com/g2p/bedup/blob/9694f6f718844c33017052eb271f68b6c0d0b7d3/bedup/platform/futimens.py#L70-L90
train
g2p/bedup
bedup/platform/openat.py
fopenat
def fopenat(base_fd, path): """ Does openat read-only, then does fdopen to get a file object """ return os.fdopen(openat(base_fd, path, os.O_RDONLY), 'rb')
python
def fopenat(base_fd, path): """ Does openat read-only, then does fdopen to get a file object """ return os.fdopen(openat(base_fd, path, os.O_RDONLY), 'rb')
[ "def", "fopenat", "(", "base_fd", ",", "path", ")", ":", "return", "os", ".", "fdopen", "(", "openat", "(", "base_fd", ",", "path", ",", "os", ".", "O_RDONLY", ")", ",", "'rb'", ")" ]
Does openat read-only, then does fdopen to get a file object
[ "Does", "openat", "read", "-", "only", "then", "does", "fdopen", "to", "get", "a", "file", "object" ]
9694f6f718844c33017052eb271f68b6c0d0b7d3
https://github.com/g2p/bedup/blob/9694f6f718844c33017052eb271f68b6c0d0b7d3/bedup/platform/openat.py#L44-L49
train
g2p/bedup
bedup/platform/openat.py
fopenat_rw
def fopenat_rw(base_fd, path): """ Does openat read-write, then does fdopen to get a file object """ return os.fdopen(openat(base_fd, path, os.O_RDWR), 'rb+')
python
def fopenat_rw(base_fd, path): """ Does openat read-write, then does fdopen to get a file object """ return os.fdopen(openat(base_fd, path, os.O_RDWR), 'rb+')
[ "def", "fopenat_rw", "(", "base_fd", ",", "path", ")", ":", "return", "os", ".", "fdopen", "(", "openat", "(", "base_fd", ",", "path", ",", "os", ".", "O_RDWR", ")", ",", "'rb+'", ")" ]
Does openat read-write, then does fdopen to get a file object
[ "Does", "openat", "read", "-", "write", "then", "does", "fdopen", "to", "get", "a", "file", "object" ]
9694f6f718844c33017052eb271f68b6c0d0b7d3
https://github.com/g2p/bedup/blob/9694f6f718844c33017052eb271f68b6c0d0b7d3/bedup/platform/openat.py#L52-L57
train
g2p/bedup
bedup/platform/fiemap.py
fiemap
def fiemap(fd): """ Gets a map of file extents. """ count = 72 fiemap_cbuf = ffi.new( 'char[]', ffi.sizeof('struct fiemap') + count * ffi.sizeof('struct fiemap_extent')) fiemap_pybuf = ffi.buffer(fiemap_cbuf) fiemap_ptr = ffi.cast('struct fiemap*', fiemap_cbuf) assert ffi.sizeof(fiemap_cbuf) <= 4096 while True: fiemap_ptr.fm_length = lib.FIEMAP_MAX_OFFSET fiemap_ptr.fm_extent_count = count fcntl.ioctl(fd, lib.FS_IOC_FIEMAP, fiemap_pybuf) if fiemap_ptr.fm_mapped_extents == 0: break for i in range(fiemap_ptr.fm_mapped_extents): extent = fiemap_ptr.fm_extents[i] yield FiemapExtent( extent.fe_logical, extent.fe_physical, extent.fe_length, extent.fe_flags) fiemap_ptr.fm_start = extent.fe_logical + extent.fe_length
python
def fiemap(fd): """ Gets a map of file extents. """ count = 72 fiemap_cbuf = ffi.new( 'char[]', ffi.sizeof('struct fiemap') + count * ffi.sizeof('struct fiemap_extent')) fiemap_pybuf = ffi.buffer(fiemap_cbuf) fiemap_ptr = ffi.cast('struct fiemap*', fiemap_cbuf) assert ffi.sizeof(fiemap_cbuf) <= 4096 while True: fiemap_ptr.fm_length = lib.FIEMAP_MAX_OFFSET fiemap_ptr.fm_extent_count = count fcntl.ioctl(fd, lib.FS_IOC_FIEMAP, fiemap_pybuf) if fiemap_ptr.fm_mapped_extents == 0: break for i in range(fiemap_ptr.fm_mapped_extents): extent = fiemap_ptr.fm_extents[i] yield FiemapExtent( extent.fe_logical, extent.fe_physical, extent.fe_length, extent.fe_flags) fiemap_ptr.fm_start = extent.fe_logical + extent.fe_length
[ "def", "fiemap", "(", "fd", ")", ":", "count", "=", "72", "fiemap_cbuf", "=", "ffi", ".", "new", "(", "'char[]'", ",", "ffi", ".", "sizeof", "(", "'struct fiemap'", ")", "+", "count", "*", "ffi", ".", "sizeof", "(", "'struct fiemap_extent'", ")", ")", "fiemap_pybuf", "=", "ffi", ".", "buffer", "(", "fiemap_cbuf", ")", "fiemap_ptr", "=", "ffi", ".", "cast", "(", "'struct fiemap*'", ",", "fiemap_cbuf", ")", "assert", "ffi", ".", "sizeof", "(", "fiemap_cbuf", ")", "<=", "4096", "while", "True", ":", "fiemap_ptr", ".", "fm_length", "=", "lib", ".", "FIEMAP_MAX_OFFSET", "fiemap_ptr", ".", "fm_extent_count", "=", "count", "fcntl", ".", "ioctl", "(", "fd", ",", "lib", ".", "FS_IOC_FIEMAP", ",", "fiemap_pybuf", ")", "if", "fiemap_ptr", ".", "fm_mapped_extents", "==", "0", ":", "break", "for", "i", "in", "range", "(", "fiemap_ptr", ".", "fm_mapped_extents", ")", ":", "extent", "=", "fiemap_ptr", ".", "fm_extents", "[", "i", "]", "yield", "FiemapExtent", "(", "extent", ".", "fe_logical", ",", "extent", ".", "fe_physical", ",", "extent", ".", "fe_length", ",", "extent", ".", "fe_flags", ")", "fiemap_ptr", ".", "fm_start", "=", "extent", ".", "fe_logical", "+", "extent", ".", "fe_length" ]
Gets a map of file extents.
[ "Gets", "a", "map", "of", "file", "extents", "." ]
9694f6f718844c33017052eb271f68b6c0d0b7d3
https://github.com/g2p/bedup/blob/9694f6f718844c33017052eb271f68b6c0d0b7d3/bedup/platform/fiemap.py#L93-L118
train
g2p/bedup
bedup/platform/chattr.py
getflags
def getflags(fd): """ Gets per-file filesystem flags. """ flags_ptr = ffi.new('uint64_t*') flags_buf = ffi.buffer(flags_ptr) fcntl.ioctl(fd, lib.FS_IOC_GETFLAGS, flags_buf) return flags_ptr[0]
python
def getflags(fd): """ Gets per-file filesystem flags. """ flags_ptr = ffi.new('uint64_t*') flags_buf = ffi.buffer(flags_ptr) fcntl.ioctl(fd, lib.FS_IOC_GETFLAGS, flags_buf) return flags_ptr[0]
[ "def", "getflags", "(", "fd", ")", ":", "flags_ptr", "=", "ffi", ".", "new", "(", "'uint64_t*'", ")", "flags_buf", "=", "ffi", ".", "buffer", "(", "flags_ptr", ")", "fcntl", ".", "ioctl", "(", "fd", ",", "lib", ".", "FS_IOC_GETFLAGS", ",", "flags_buf", ")", "return", "flags_ptr", "[", "0", "]" ]
Gets per-file filesystem flags.
[ "Gets", "per", "-", "file", "filesystem", "flags", "." ]
9694f6f718844c33017052eb271f68b6c0d0b7d3
https://github.com/g2p/bedup/blob/9694f6f718844c33017052eb271f68b6c0d0b7d3/bedup/platform/chattr.py#L74-L82
train
g2p/bedup
bedup/platform/chattr.py
editflags
def editflags(fd, add_flags=0, remove_flags=0): """ Sets and unsets per-file filesystem flags. """ if add_flags & remove_flags != 0: raise ValueError( 'Added and removed flags shouldn\'t overlap', add_flags, remove_flags) # The ext2progs code uses int or unsigned long, # the kernel uses an implicit int, # let's be explicit here. flags_ptr = ffi.new('uint64_t*') flags_buf = ffi.buffer(flags_ptr) fcntl.ioctl(fd, lib.FS_IOC_GETFLAGS, flags_buf) prev_flags = flags_ptr[0] flags_ptr[0] |= add_flags # Python represents negative numbers with an infinite number of # ones in bitops, so this will work correctly. flags_ptr[0] &= ~remove_flags fcntl.ioctl(fd, lib.FS_IOC_SETFLAGS, flags_buf) return prev_flags & (add_flags | remove_flags)
python
def editflags(fd, add_flags=0, remove_flags=0): """ Sets and unsets per-file filesystem flags. """ if add_flags & remove_flags != 0: raise ValueError( 'Added and removed flags shouldn\'t overlap', add_flags, remove_flags) # The ext2progs code uses int or unsigned long, # the kernel uses an implicit int, # let's be explicit here. flags_ptr = ffi.new('uint64_t*') flags_buf = ffi.buffer(flags_ptr) fcntl.ioctl(fd, lib.FS_IOC_GETFLAGS, flags_buf) prev_flags = flags_ptr[0] flags_ptr[0] |= add_flags # Python represents negative numbers with an infinite number of # ones in bitops, so this will work correctly. flags_ptr[0] &= ~remove_flags fcntl.ioctl(fd, lib.FS_IOC_SETFLAGS, flags_buf) return prev_flags & (add_flags | remove_flags)
[ "def", "editflags", "(", "fd", ",", "add_flags", "=", "0", ",", "remove_flags", "=", "0", ")", ":", "if", "add_flags", "&", "remove_flags", "!=", "0", ":", "raise", "ValueError", "(", "'Added and removed flags shouldn\\'t overlap'", ",", "add_flags", ",", "remove_flags", ")", "# The ext2progs code uses int or unsigned long,", "# the kernel uses an implicit int,", "# let's be explicit here.", "flags_ptr", "=", "ffi", ".", "new", "(", "'uint64_t*'", ")", "flags_buf", "=", "ffi", ".", "buffer", "(", "flags_ptr", ")", "fcntl", ".", "ioctl", "(", "fd", ",", "lib", ".", "FS_IOC_GETFLAGS", ",", "flags_buf", ")", "prev_flags", "=", "flags_ptr", "[", "0", "]", "flags_ptr", "[", "0", "]", "|=", "add_flags", "# Python represents negative numbers with an infinite number of", "# ones in bitops, so this will work correctly.", "flags_ptr", "[", "0", "]", "&=", "~", "remove_flags", "fcntl", ".", "ioctl", "(", "fd", ",", "lib", ".", "FS_IOC_SETFLAGS", ",", "flags_buf", ")", "return", "prev_flags", "&", "(", "add_flags", "|", "remove_flags", ")" ]
Sets and unsets per-file filesystem flags.
[ "Sets", "and", "unsets", "per", "-", "file", "filesystem", "flags", "." ]
9694f6f718844c33017052eb271f68b6c0d0b7d3
https://github.com/g2p/bedup/blob/9694f6f718844c33017052eb271f68b6c0d0b7d3/bedup/platform/chattr.py#L85-L107
train
luqasz/librouteros
librouteros/__init__.py
connect
def connect(host, username, password, **kwargs): """ Connect and login to routeros device. Upon success return a Api class. :param host: Hostname to connecto to. May be ipv4,ipv6,FQDN. :param username: Username to login with. :param password: Password to login with. Only ASCII characters allowed. :param timeout: Socket timeout. Defaults to 10. :param port: Destination port to be used. Defaults to 8728. :param saddr: Source address to bind to. :param subclass: Subclass of Api class. Defaults to Api class from library. :param ssl_wrapper: Callable (e.g. ssl.SSLContext instance) to wrap socket with. :param login_methods: Tuple with callables to login methods to try in order. """ arguments = ChainMap(kwargs, defaults) transport = create_transport(host, **arguments) protocol = ApiProtocol(transport=transport, encoding=arguments['encoding']) api = arguments['subclass'](protocol=protocol) for method in arguments['login_methods']: try: method(api=api, username=username, password=password) return api except (TrapError, MultiTrapError): pass except (ConnectionError, FatalError): transport.close() raise
python
def connect(host, username, password, **kwargs): """ Connect and login to routeros device. Upon success return a Api class. :param host: Hostname to connecto to. May be ipv4,ipv6,FQDN. :param username: Username to login with. :param password: Password to login with. Only ASCII characters allowed. :param timeout: Socket timeout. Defaults to 10. :param port: Destination port to be used. Defaults to 8728. :param saddr: Source address to bind to. :param subclass: Subclass of Api class. Defaults to Api class from library. :param ssl_wrapper: Callable (e.g. ssl.SSLContext instance) to wrap socket with. :param login_methods: Tuple with callables to login methods to try in order. """ arguments = ChainMap(kwargs, defaults) transport = create_transport(host, **arguments) protocol = ApiProtocol(transport=transport, encoding=arguments['encoding']) api = arguments['subclass'](protocol=protocol) for method in arguments['login_methods']: try: method(api=api, username=username, password=password) return api except (TrapError, MultiTrapError): pass except (ConnectionError, FatalError): transport.close() raise
[ "def", "connect", "(", "host", ",", "username", ",", "password", ",", "*", "*", "kwargs", ")", ":", "arguments", "=", "ChainMap", "(", "kwargs", ",", "defaults", ")", "transport", "=", "create_transport", "(", "host", ",", "*", "*", "arguments", ")", "protocol", "=", "ApiProtocol", "(", "transport", "=", "transport", ",", "encoding", "=", "arguments", "[", "'encoding'", "]", ")", "api", "=", "arguments", "[", "'subclass'", "]", "(", "protocol", "=", "protocol", ")", "for", "method", "in", "arguments", "[", "'login_methods'", "]", ":", "try", ":", "method", "(", "api", "=", "api", ",", "username", "=", "username", ",", "password", "=", "password", ")", "return", "api", "except", "(", "TrapError", ",", "MultiTrapError", ")", ":", "pass", "except", "(", "ConnectionError", ",", "FatalError", ")", ":", "transport", ".", "close", "(", ")", "raise" ]
Connect and login to routeros device. Upon success return a Api class. :param host: Hostname to connecto to. May be ipv4,ipv6,FQDN. :param username: Username to login with. :param password: Password to login with. Only ASCII characters allowed. :param timeout: Socket timeout. Defaults to 10. :param port: Destination port to be used. Defaults to 8728. :param saddr: Source address to bind to. :param subclass: Subclass of Api class. Defaults to Api class from library. :param ssl_wrapper: Callable (e.g. ssl.SSLContext instance) to wrap socket with. :param login_methods: Tuple with callables to login methods to try in order.
[ "Connect", "and", "login", "to", "routeros", "device", ".", "Upon", "success", "return", "a", "Api", "class", "." ]
59293eb49c07a339af87b0416e4619e78ca5176d
https://github.com/luqasz/librouteros/blob/59293eb49c07a339af87b0416e4619e78ca5176d/librouteros/__init__.py#L26-L54
train
luqasz/librouteros
librouteros/api.py
Api._readSentence
def _readSentence(self): """ Read one sentence and parse words. :returns: Reply word, dict with attribute words. """ reply_word, words = self.protocol.readSentence() words = dict(parseWord(word) for word in words) return reply_word, words
python
def _readSentence(self): """ Read one sentence and parse words. :returns: Reply word, dict with attribute words. """ reply_word, words = self.protocol.readSentence() words = dict(parseWord(word) for word in words) return reply_word, words
[ "def", "_readSentence", "(", "self", ")", ":", "reply_word", ",", "words", "=", "self", ".", "protocol", ".", "readSentence", "(", ")", "words", "=", "dict", "(", "parseWord", "(", "word", ")", "for", "word", "in", "words", ")", "return", "reply_word", ",", "words" ]
Read one sentence and parse words. :returns: Reply word, dict with attribute words.
[ "Read", "one", "sentence", "and", "parse", "words", "." ]
59293eb49c07a339af87b0416e4619e78ca5176d
https://github.com/luqasz/librouteros/blob/59293eb49c07a339af87b0416e4619e78ca5176d/librouteros/api.py#L29-L37
train
luqasz/librouteros
librouteros/api.py
Api._readResponse
def _readResponse(self): """ Yield each row of response untill !done is received. :throws TrapError: If one !trap is received. :throws MultiTrapError: If > 1 !trap is received. """ traps = [] reply_word = None while reply_word != '!done': reply_word, words = self._readSentence() if reply_word == '!trap': traps.append(TrapError(**words)) elif reply_word in ('!re', '!done') and words: yield words if len(traps) > 1: raise MultiTrapError(*traps) elif len(traps) == 1: raise traps[0]
python
def _readResponse(self): """ Yield each row of response untill !done is received. :throws TrapError: If one !trap is received. :throws MultiTrapError: If > 1 !trap is received. """ traps = [] reply_word = None while reply_word != '!done': reply_word, words = self._readSentence() if reply_word == '!trap': traps.append(TrapError(**words)) elif reply_word in ('!re', '!done') and words: yield words if len(traps) > 1: raise MultiTrapError(*traps) elif len(traps) == 1: raise traps[0]
[ "def", "_readResponse", "(", "self", ")", ":", "traps", "=", "[", "]", "reply_word", "=", "None", "while", "reply_word", "!=", "'!done'", ":", "reply_word", ",", "words", "=", "self", ".", "_readSentence", "(", ")", "if", "reply_word", "==", "'!trap'", ":", "traps", ".", "append", "(", "TrapError", "(", "*", "*", "words", ")", ")", "elif", "reply_word", "in", "(", "'!re'", ",", "'!done'", ")", "and", "words", ":", "yield", "words", "if", "len", "(", "traps", ")", ">", "1", ":", "raise", "MultiTrapError", "(", "*", "traps", ")", "elif", "len", "(", "traps", ")", "==", "1", ":", "raise", "traps", "[", "0", "]" ]
Yield each row of response untill !done is received. :throws TrapError: If one !trap is received. :throws MultiTrapError: If > 1 !trap is received.
[ "Yield", "each", "row", "of", "response", "untill", "!done", "is", "received", "." ]
59293eb49c07a339af87b0416e4619e78ca5176d
https://github.com/luqasz/librouteros/blob/59293eb49c07a339af87b0416e4619e78ca5176d/librouteros/api.py#L39-L58
train
luqasz/librouteros
librouteros/connections.py
Encoder.encodeSentence
def encodeSentence(self, *words): """ Encode given sentence in API format. :param words: Words to endoce. :returns: Encoded sentence. """ encoded = map(self.encodeWord, words) encoded = b''.join(encoded) # append EOS (end of sentence) byte encoded += b'\x00' return encoded
python
def encodeSentence(self, *words): """ Encode given sentence in API format. :param words: Words to endoce. :returns: Encoded sentence. """ encoded = map(self.encodeWord, words) encoded = b''.join(encoded) # append EOS (end of sentence) byte encoded += b'\x00' return encoded
[ "def", "encodeSentence", "(", "self", ",", "*", "words", ")", ":", "encoded", "=", "map", "(", "self", ".", "encodeWord", ",", "words", ")", "encoded", "=", "b''", ".", "join", "(", "encoded", ")", "# append EOS (end of sentence) byte", "encoded", "+=", "b'\\x00'", "return", "encoded" ]
Encode given sentence in API format. :param words: Words to endoce. :returns: Encoded sentence.
[ "Encode", "given", "sentence", "in", "API", "format", "." ]
59293eb49c07a339af87b0416e4619e78ca5176d
https://github.com/luqasz/librouteros/blob/59293eb49c07a339af87b0416e4619e78ca5176d/librouteros/connections.py#L14-L25
train
luqasz/librouteros
librouteros/connections.py
Encoder.encodeWord
def encodeWord(self, word): """ Encode word in API format. :param word: Word to encode. :returns: Encoded word. """ encoded_word = word.encode(encoding=self.encoding, errors='strict') return Encoder.encodeLength(len(word)) + encoded_word
python
def encodeWord(self, word): """ Encode word in API format. :param word: Word to encode. :returns: Encoded word. """ encoded_word = word.encode(encoding=self.encoding, errors='strict') return Encoder.encodeLength(len(word)) + encoded_word
[ "def", "encodeWord", "(", "self", ",", "word", ")", ":", "encoded_word", "=", "word", ".", "encode", "(", "encoding", "=", "self", ".", "encoding", ",", "errors", "=", "'strict'", ")", "return", "Encoder", ".", "encodeLength", "(", "len", "(", "word", ")", ")", "+", "encoded_word" ]
Encode word in API format. :param word: Word to encode. :returns: Encoded word.
[ "Encode", "word", "in", "API", "format", "." ]
59293eb49c07a339af87b0416e4619e78ca5176d
https://github.com/luqasz/librouteros/blob/59293eb49c07a339af87b0416e4619e78ca5176d/librouteros/connections.py#L27-L35
train
luqasz/librouteros
librouteros/connections.py
Encoder.encodeLength
def encodeLength(length): """ Encode given length in mikrotik format. :param length: Integer < 268435456. :returns: Encoded length. """ if length < 128: ored_length = length offset = -1 elif length < 16384: ored_length = length | 0x8000 offset = -2 elif length < 2097152: ored_length = length | 0xC00000 offset = -3 elif length < 268435456: ored_length = length | 0xE0000000 offset = -4 else: raise ConnectionError('Unable to encode length of {}'.format(length)) return pack('!I', ored_length)[offset:]
python
def encodeLength(length): """ Encode given length in mikrotik format. :param length: Integer < 268435456. :returns: Encoded length. """ if length < 128: ored_length = length offset = -1 elif length < 16384: ored_length = length | 0x8000 offset = -2 elif length < 2097152: ored_length = length | 0xC00000 offset = -3 elif length < 268435456: ored_length = length | 0xE0000000 offset = -4 else: raise ConnectionError('Unable to encode length of {}'.format(length)) return pack('!I', ored_length)[offset:]
[ "def", "encodeLength", "(", "length", ")", ":", "if", "length", "<", "128", ":", "ored_length", "=", "length", "offset", "=", "-", "1", "elif", "length", "<", "16384", ":", "ored_length", "=", "length", "|", "0x8000", "offset", "=", "-", "2", "elif", "length", "<", "2097152", ":", "ored_length", "=", "length", "|", "0xC00000", "offset", "=", "-", "3", "elif", "length", "<", "268435456", ":", "ored_length", "=", "length", "|", "0xE0000000", "offset", "=", "-", "4", "else", ":", "raise", "ConnectionError", "(", "'Unable to encode length of {}'", ".", "format", "(", "length", ")", ")", "return", "pack", "(", "'!I'", ",", "ored_length", ")", "[", "offset", ":", "]" ]
Encode given length in mikrotik format. :param length: Integer < 268435456. :returns: Encoded length.
[ "Encode", "given", "length", "in", "mikrotik", "format", "." ]
59293eb49c07a339af87b0416e4619e78ca5176d
https://github.com/luqasz/librouteros/blob/59293eb49c07a339af87b0416e4619e78ca5176d/librouteros/connections.py#L38-L60
train
luqasz/librouteros
librouteros/connections.py
Decoder.determineLength
def determineLength(length): """ Given first read byte, determine how many more bytes needs to be known in order to get fully encoded length. :param length: First read byte. :return: How many bytes to read. """ integer = ord(length) if integer < 128: return 0 elif integer < 192: return 1 elif integer < 224: return 2 elif integer < 240: return 3 else: raise ConnectionError('Unknown controll byte {}'.format(length))
python
def determineLength(length): """ Given first read byte, determine how many more bytes needs to be known in order to get fully encoded length. :param length: First read byte. :return: How many bytes to read. """ integer = ord(length) if integer < 128: return 0 elif integer < 192: return 1 elif integer < 224: return 2 elif integer < 240: return 3 else: raise ConnectionError('Unknown controll byte {}'.format(length))
[ "def", "determineLength", "(", "length", ")", ":", "integer", "=", "ord", "(", "length", ")", "if", "integer", "<", "128", ":", "return", "0", "elif", "integer", "<", "192", ":", "return", "1", "elif", "integer", "<", "224", ":", "return", "2", "elif", "integer", "<", "240", ":", "return", "3", "else", ":", "raise", "ConnectionError", "(", "'Unknown controll byte {}'", ".", "format", "(", "length", ")", ")" ]
Given first read byte, determine how many more bytes needs to be known in order to get fully encoded length. :param length: First read byte. :return: How many bytes to read.
[ "Given", "first", "read", "byte", "determine", "how", "many", "more", "bytes", "needs", "to", "be", "known", "in", "order", "to", "get", "fully", "encoded", "length", "." ]
59293eb49c07a339af87b0416e4619e78ca5176d
https://github.com/luqasz/librouteros/blob/59293eb49c07a339af87b0416e4619e78ca5176d/librouteros/connections.py#L66-L85
train