Most pythonic way to implement byte filling algorithm

I am doing some stuff for serial protocol and want to implement byte byte byte algorithm in python. I'm struggling to determine what is the most pythonic way to do this.

Filling in bytes basically just replaces any "reserved" bytes with a pair of escape bytes, and the original byte is converted in a reversible way (for example, xor'ed).

So far I have come up with 5 different approaches, and each of them has something that I don't like:

1 Via generator

def stuff1(bits):
    for byte in bits:
        if byte in _EscapeCodes:
            yield PacketCode.Escape
            yield byte ^ 0xFF
        else:
            yield byte

It may be my favorite, but maybe just because crop-based generators carry me around. I was worried that the generator would make it slow, but it was actually the second fastest of the group.

2 Just bytes ()

def stuff2(bits):
    result = bytes()
    for byte in bits:
        if byte in _EscapeCodes:
            result += bytes([PacketCode.Escape, byte ^ 0xFF])
        else:
            result += bytes([byte])
    return result

, , - " ". .

3 ()

def stuff3(bits):
    result = bytearray()
    for byte in bits:
        if byte in _EscapeCodes:
            result.append(PacketCode.Escape)
            result.append(byte ^ 0xFF)
        else:
            result.append(byte)
    return result

, bytes(). , , ( 1 ). . .

4 BytesIO()

def stuff4(bits):
    bio = BytesIO()
    for byte in bits:
        if byte in _EscapeCodes:
            bio.write(bytes([PacketCode.Escape, byte ^ 0xFF]))
        else:
            bio.write(bytes([byte]))
    return bio.getbuffer()

, . , , , - API write1, 1 , bytes. " ", . .

5 replace()

def stuff5(bits):
    escapeStuffed = bytes(bits).replace(bytes([PacketCode.Escape]), bytes([PacketCode.Escape, PacketCode.Escape ^ 0xFF]))
    stopStuffed = escapeStuffed.replace(bytes([PacketCode.Stop]), bytes([PacketCode.Escape, PacketCode.Stop ^ 0xFF]))
    return stopStuffed.replace(bytes([PacketCode.Start]), bytes([PacketCode.Escape, PacketCode.Start ^ 0xFF]))

. .

translate(), AFAICT, 1:1 .

+4

Source: https://habr.com/ru/post/1696227/


All Articles