Skip to content

Improve to avoid heap allocation #60

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading