~taiite/public-inbox

senpai: ui: buffers: sort buffer list v1 PROPOSED

Kalyan Sriram: 1
 ui: buffers: sort buffer list

 1 files changed, 39 insertions(+), 29 deletions(-)
Export patchset (mbox)
How do I use this?

Copy & paste the following snippet into your terminal to import this patchset into git:

curl -s https://lists.sr.ht/~taiite/public-inbox/patches/27225/mbox | git am -3
Learn more about email & git

[PATCH senpai] ui: buffers: sort buffer list Export this patch

Cleans up BufferList.Add function using sort.Search(), and implements
sorting of both network names and buffer names inside networks.
---
 ui/buffers.go | 68 +++++++++++++++++++++++++++++----------------------
 1 file changed, 39 insertions(+), 29 deletions(-)

diff --git a/ui/buffers.go b/ui/buffers.go
index aa5e9fe..0be1779 100644
--- a/ui/buffers.go
+++ b/ui/buffers.go
@@ -1,8 +1,10 @@
package ui

import (
	"errors"
	"fmt"
	"math"
	"sort"
	"strings"
	"time"

@@ -252,38 +254,46 @@ func (bs *BufferList) Previous() {

func (bs *BufferList) Add(netID, netName, title string) (i int, added bool) {
	lTitle := strings.ToLower(title)
	gotNetID := false
	for i, b := range bs.list {
		lbTitle := strings.ToLower(b.title)
		if b.netID == netID {
			gotNetID = true
			if lbTitle == lTitle {
				return i, false
			}
		} else if gotNetID || (b.netID == netID && lbTitle < lTitle) {
			b := buffer{
				netID:   netID,
				netName: netName,
				title:   title,
			}
			bs.list = append(bs.list[:i+1], bs.list[i:]...)
			bs.list[i] = b
			if i <= bs.current && bs.current < len(bs.list) {
				bs.current++
			}
			return i, true
		}
	insertIdx := -1

	netIdx := sort.Search(len(bs.list), func(sIdx int) bool {
		return bs.list[sIdx].netID == netID
	})

	if netIdx == len(bs.list) {
		// network not found - first buffer for network, insert sorted by netName
		insertIdx = sort.Search(len(bs.list), func(sIdx int) bool {
			return strings.Compare(bs.list[sIdx].netName, netName) == 1
		})
	} else {
		// insert at sorted location inside subset of buffers in network
		insertIdx = sort.Search(len(bs.list), func(sIdx int) bool {
			b := bs.list[sIdx]
			return (b.netID == netID) && (strings.Compare(b.title, lTitle) == 1)
		})
	}

	if netName == "" {
		netName = netID
	if insertIdx == -1 {
		// we should never get here
		panic(errors.New("ui: add buffer: insertIdx == -1"))
	} else if insertIdx == len(bs.list) {
		// at the end of the list, just append
		bs.list = append(bs.list, buffer{
			netID:   netID,
			netName: netName,
			title:   title,
		})
	} else {
		// somewhere in the middle, insert
		bs.list = append(bs.list[:insertIdx+1], bs.list[insertIdx:]...)
		bs.list[insertIdx] = buffer{
			netID:   netID,
			netName: netName,
			title:   title,
		}
	}
	bs.list = append(bs.list, buffer{
		netID:   netID,
		netName: netName,
		title:   title,
	})
	return len(bs.list) - 1, true

	return insertIdx, true
}

func (bs *BufferList) Remove(netID, title string) bool {
-- 
2.34.1