# Collection of code snippets by Arne Vajhøj 
# (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
RECSIZ = 4
FNM = 'jyx.fix'

def recno(ix):
   return (ix - 1) * RECSIZ

eof = 0
ZERO = '\0\0\0\0\n'

def test_write_one(f, ix, buf):
    global eof
    if ix > eof + 1:
        f.seek(recno(eof + 1))
        for i in range(ix - eof - 1):
            f.write(ZERO)
        eof = ix
    f.seek(recno(ix))
    f.write(buf)

def test_write():
    f = open(FNM, 'wb')
    test_write_one(f, 3, 'CCCC')
    test_write_one(f, 2, 'BBBB')
    test_write_one(f, 1, 'AAAA')
    f.close()

def test_read_sequential():
    f = open(FNM, 'rb')
    while True:
        buf = f.read(RECSIZ+1) # will read a fictive LF
        if len(buf) < RECSIZ:
            break
        buf = buf[:-1]
        print('|%s| %d' % (buf, len(buf)))
    f.close()

def test_read_random_one(f, ix):
    f.seek(recno(ix))
    buf = f.read(RECSIZ)
    print('|%s| %d' % (buf, len(buf)))

def test_read_random():
    f = open(FNM, 'rb')
    test_read_random_one(f, 3)
    test_read_random_one(f, 2)
    test_read_random_one(f, 1)
    f.close()

print('Jython seek')
test_write()
test_read_sequential()
test_read_random()
