Here below a function decoding IIOP's CDR streams:
I like nested functions...
And I like functions returning tuples !
Usage examples:
# reads a 13 bytes string and actualize index
__aString, index, ok = ACE_read(0)(buffer, index, 13)
if not ok: doSomething()
# reads an aligned-4-byte-long integer located somewhere by index
__anInteger, index, ok = ACE_read(4)(buffer, index)
|
def ACE_read(typeLength): if typeLength: # scalar (char:1, int:4, ...) def sclRead(buf, index, big=1): alignedIndex=(index + (typeLength-1)) & ~(typeLength-1) if alignedIndex + typeLength > len(buf): return None, None, False endIndex=alignedIndex + typeLength return ordn(big)(buf[alignedIndex:endIndex]), endIndex, True return sclRead else: # string def strRead(buf,index,length,big=1): endIndex =index + length if endIndex > len(buf): return None, None, False return buf[index:endIndex], endIndex, True return strRead |
I like nested functions...
And I like functions returning tuples !
Usage examples:
# reads a 13 bytes string and actualize index
__aString, index, ok = ACE_read(0)(buffer, index, 13)
if not ok: doSomething()
# reads an aligned-4-byte-long integer located somewhere by index
__anInteger, index, ok = ACE_read(4)(buffer, index)
| This entry |
The following function converts a sequence of bytes into an integer. It is endianness-sensitive:
>>> ordn(1)('\x01\x00')
256
>>> ordn(0)('\x01\x00')
1
Ok, that's probably not the prettiest nor the fastest way to do...
|
def ordn(big=1): if big % 2: def bordn(seq): if len(seq) > 1: return ord(seq[-1]) + (bordn(seq[:-1]) << 8) else: return ord(seq[0]) return bordn else: def lordn(seq): if len(seq) >1: return ord(seq[0]) + (lordn(seq[1:]) << 8) else: return ord(seq[0]) return lordn |
>>> ordn(1)('\x01\x00')
256
>>> ordn(0)('\x01\x00')
1
Ok, that's probably not the prettiest nor the fastest way to do...
| This entry |
To insert a white space before each uppercase letter within a string:
"".join([(i.isupper() and " "+i) or i for i in "PythonIsCool"])
or for the ones who like functional programming:
"".join(map(lambda x:(x.isupper() and " "+x) or x,"PythonIsCool"))
But I do personnally do like list comprehensions...
archives
sources



