From 3418b14c0a1e3bd34a65942051fa2f3490f57f92 Mon Sep 17 00:00:00 2001 From: anthony4m Date: Fri, 22 Nov 2024 18:46:19 +0000 Subject: [PATCH] #8 refactored --- kfile/file.go | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/kfile/file.go b/kfile/file.go index 96439eb..5e09ce4 100644 --- a/kfile/file.go +++ b/kfile/file.go @@ -11,6 +11,12 @@ type BlockId struct { } func NewBlockId(filename string, blknum int) *BlockId { + if err := ValidateFilename(filename); err != nil { + panic(err) + } + if err := ValidateBlockNumber(blknum); err != nil { + panic(err) + } return &BlockId{ Filename: filename, Blknum: blknum, @@ -50,3 +56,42 @@ func (b *BlockId) HashCode() uint32 { return h.Sum32() } + +func (b *BlockId) Copy() *BlockId { + return NewBlockId(b.Filename, b.Blknum) +} + +func (b *BlockId) NextBlock() *BlockId { + return NewBlockId(b.Filename, b.Blknum+1) +} + +func (b *BlockId) PrevBlock() *BlockId { + if b.Blknum > 0 { + return NewBlockId(b.Filename, b.Blknum-1) + } + return nil +} + +func (b *BlockId) IsFirst() bool { + return b.Blknum == 0 +} + +func ValidateBlockNumber(blknum int) error { + if blknum < 0 { + return fmt.Errorf("block number cannot be negative: %d", blknum) + } + return nil +} + +func ValidateFilename(filename string) error { + if filename == "" { + return fmt.Errorf("filename cannot be empty") + } + return nil +} + +func (b *BlockId) IsValid() bool { + return b != nil && + b.Filename != "" && + b.Blknum >= 0 +}