Skip to content

Commit

Permalink
Improve to avoid heap allocation (#60)
Browse files Browse the repository at this point in the history
  • Loading branch information
sago35 authored Dec 12, 2024
1 parent 3eaeb11 commit 9d02bba
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 3 deletions.
5 changes: 4 additions & 1 deletion kbsquaredmatrix.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ type SquaredMatrixKeyboard struct {
Pins []machine.Pin
cycleCounter []uint8
debounce uint8

colsBuf []int
}

func (d *Device) AddSquaredMatrixKeyboard(pins []machine.Pin, keys [][]Keycode) *SquaredMatrixKeyboard {
Expand Down Expand Up @@ -41,6 +43,7 @@ func (d *Device) AddSquaredMatrixKeyboard(pins []machine.Pin, keys [][]Keycode)
callback: func(layer, index int, state State) {},
cycleCounter: cycleCnt,
debounce: 8,
colsBuf: make([]int, len(pins)),
}

d.kb = append(d.kb, k)
Expand All @@ -59,7 +62,7 @@ func (d *SquaredMatrixKeyboard) Callback(layer, index int, state State) {

func (d *SquaredMatrixKeyboard) Get() []State {
c := int(0)
cols := []int{}
cols := d.colsBuf[:0]
for i := range d.Pins {
for j := range d.Pins {
d.Pins[j].Configure(machine.PinConfig{Mode: machine.PinInputPullup})
Expand Down
10 changes: 8 additions & 2 deletions keyboard.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ type Device struct {
combosReleased []uint32
combosKey uint32
combosFounds []Keycode

pressToReleaseBuf []uint32
noneToPressBuf []uint32
}

type KBer interface {
Expand Down Expand Up @@ -83,6 +86,9 @@ func New() *Device {
combosReleased: make([]uint32, 0, 10),
combosKey: 0xFFFFFFFF,
combosFounds: make([]Keycode, 10),

pressToReleaseBuf: make([]uint32, 0, 20),
noneToPressBuf: make([]uint32, 0, 20),
}

SetDevice(d)
Expand Down Expand Up @@ -192,7 +198,7 @@ func (d *Device) GetMaxKeyCount() int {
}

func (d *Device) Tick() error {
pressToRelease := []uint32{}
pressToRelease := d.pressToReleaseBuf[:0]

select {
case <-d.flashCh:
Expand All @@ -210,7 +216,7 @@ func (d *Device) Tick() error {
}

// read from key matrix
noneToPress := []uint32{}
noneToPress := d.noneToPressBuf[:0]
for kbidx, k := range d.kb {
state := k.Get()
for i := range state {
Expand Down

0 comments on commit 9d02bba

Please sign in to comment.