e_rsatz projects: ([info]e_rsatz) wrote,
@ 2005-08-19 18:24:00
Previous Entry  Add to memories!  Tell a Friend!  Next Entry
Entry tags:python

The Python I like - A CDR streams read method
Here below a function decoding IIOP's CDR streams:

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



Create an Account
Forgot your login or password?
Login w/ OpenID
English • Español • Deutsch • Русский…