# stydy bytes, bytearray, memoryview, and struct

import  os;             os.system('clear')

# literals
b1 = b'hello world'
print(b1)

# zero filled
b2 = bytes(10)
print(b2)

# from iterable
b3 = bytes(range(10))
print(b3)

# Copying binary data via the buffer protocol
ba = bytearray(b'hello\x01\x02')
print(ba)
b4 = bytes(ba)
print(b4)

# string with bytes
b5= bytes.fromhex('a1 09 55AA')
print(b5)

# copy to file
with open('bytes.bin', 'wb') as f:
    f.write(b3)

# load from file
with open('bytes.bin', 'rb') as f:
    b6 = f.read()
print(type(b6), b6)

# memory view of buffer protocol
mv = memoryview(b1)
print(mv)
print(type(mv[1]), mv[1])
print(bytes(mv[:5]))

# modifying in memoryview
b7 = bytearray(b'123456789')
mv = memoryview(b7)
mv[2:4] = mv[6:8]
print(b7, '\n')

# see: https://docs.python.org/3/library/struct.html
import struct
b8 = struct.pack('3s', b'123')
print(len(b8), b8)
b8 = struct.pack('?3s', True, b'123')
print(len(b8), b8)
b8 = struct.pack('?h3s', True, 2, b'123')   # padding byte for bytes 32 bit
print(len(b8), b8)
b8 = struct.pack('?hh3s', True, 2, 5, b'123')
print(len(b8), b8)
x = struct.unpack('@?hh3s', b8)
print(x, '\n')

# convert string to bytes of fixed length
a1 = 'test.txt'
a1 = a1[:10]
a2 = b''.join([a1.encode(), bytes(10-len(a1))])
print(len(a2), a2)
a3 = a2.decode().rstrip('\x00')
print(len(a3), a3)

# convert begin, end and id into a 16_bytes
def toFatRec(begin, end, id):
    id = id[:10]
    id = b''.join([id.encode(), bytes(12-len(id))])
    return struct.pack('HH12s', begin, end, id)

def fromFatRec(rec):
    begin, end, id = struct.unpack('HH12s', rec)
    id = id.decode().rstrip('\x00')
    return begin, end, id

a = toFatRec(513, 1026, 'test.txt')
print(a)
print(fromFatRec(a))
