# Collection of code snippets by Arne Vajhøj 
# (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
from construct import *
from vms.rms.IndexedFile import IndexedFile

class DataRec:
    def __init__(self, id, val):
        self.id = id
        self.val = val

class DataFile(IndexedFile):
    def __init__(self, fnm):
        IndexedFile.__init__(self, fnm, Struct('data_rec', String('id', 4), SNInt32('val')))
    def primary_keynum(self):
        return 0
    def pack_key(self, keynum, keyval):
        return keyval
    def keyval(self, rec, keynum):
        return rec.id

def test_write_one(db, id, val):
    db.put(DataRec(id, val))

def test_write():
    db = DataFile('py.isq')
    test_write_one(db, 'CCCC', 3)
    test_write_one(db, 'BBBB', 2)
    test_write_one(db, 'AAAA', 1)

def test_read_sequential():
    db = DataFile('py.isq')
    for rec in db:
        res = DataRec(rec.id, rec.val)
        print('%s -> %d' % (res.id, res.val))

def test_read_random_one(db, id):
    rec = db.fetch(0, id)
    res = DataRec(rec.id, rec.val)
    print('%s -> %d' % (res.id, res.val))

def test_read_random():
    db = DataFile('py.isq')
    test_read_random_one(db, 'CCCC')
    test_read_random_one(db, 'BBBB')
    test_read_random_one(db, 'AAAA')

print('Python')
test_write()
test_read_sequential()
test_read_random()
