Skip to content

Commit

Permalink
nes cartridge: support loading binary buffer without header
Browse files Browse the repository at this point in the history
  • Loading branch information
cornelk committed Nov 5, 2024
1 parent cddedcd commit 931e147
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
28 changes: 28 additions & 0 deletions arch/nes/cartridge/ines.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,3 +75,31 @@ func LoadFile(reader io.Reader) (*Cartridge, error) {
VideoFormat: header.VideoFormat,
}, nil
}

// LoadBuffer loads an raw binary buffer.
func LoadBuffer(reader io.Reader) (*Cartridge, error) {
b, err := io.ReadAll(reader)
if err != nil {
return nil, fmt.Errorf("reading PRG: %w", err)
}

size := len(b) / 16384
if len(b)%16384 != 0 {
size++
}
size *= 16384

prg := make([]byte, size)
copy(prg, b)

return &Cartridge{
PRG: prg,
CHR: make([]byte, 8192),
RAM: 0,
Trainer: nil,
Mapper: 0,
Mirror: MirrorVertical,
Battery: 0,
VideoFormat: 0,
}, nil
}
19 changes: 19 additions & 0 deletions arch/nes/cartridge/ines_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,22 @@ func TestCartridgeSave(t *testing.T) {
b := buf.Bytes()
assert.Equal(t, rom, b)
}

func TestLoadBuffer(t *testing.T) {
// test a small buffer
buf := []byte{0x60}
reader := bytes.NewReader(buf)

cart, err := LoadBuffer(reader)
assert.NoError(t, err)
assert.Equal(t, 0x60, cart.PRG[0])

// test a large buffer
buf = make([]byte, 16384+1000)
buf[0] = 0x60
reader = bytes.NewReader(buf)

cart, err = LoadBuffer(reader)
assert.NoError(t, err)
assert.Equal(t, 0x60, cart.PRG[0])
}

0 comments on commit 931e147

Please sign in to comment.