run modernize

This commit is contained in:
Kovid Goyal
2025-11-11 17:09:37 +05:30
parent 1faf786bd2
commit 6f588a0c29
30 changed files with 46 additions and 60 deletions

View File

@@ -94,7 +94,7 @@ func (n node) ReadFile(name string) ([]byte, error) {
return nil, fs.ErrNotExist return nil, fs.ErrNotExist
} }
p := &n p := &n
for _, x := range strings.Split(strings.Trim(name, string(os.PathSeparator)), string(os.PathSeparator)) { for x := range strings.SplitSeq(strings.Trim(name, string(os.PathSeparator)), string(os.PathSeparator)) {
c, found := p.children[x] c, found := p.children[x]
if !found { if !found {
return nil, fs.ErrNotExist return nil, fs.ErrNotExist
@@ -109,7 +109,7 @@ func (n node) ReadDir(name string) ([]fs.DirEntry, error) {
return n.dir_entries(), nil return n.dir_entries(), nil
} }
p := &n p := &n
for _, x := range strings.Split(strings.Trim(name, string(os.PathSeparator)), string(os.PathSeparator)) { for x := range strings.SplitSeq(strings.Trim(name, string(os.PathSeparator)), string(os.PathSeparator)) {
c, found := p.children[x] c, found := p.children[x]
if !found { if !found {
return nil, fs.ErrNotExist return nil, fs.ErrNotExist
@@ -334,11 +334,11 @@ func TestSortedResults(t *testing.T) {
} }
func run_scoring(b *testing.B, depth, breadth int, query string) { func run_scoring(b *testing.B, depth, breadth int, query string) {
b.StopTimer()
root := node{name: string(os.PathSeparator)} root := node{name: string(os.PathSeparator)}
root.generate_random_tree(depth, breadth) root.generate_random_tree(depth, breadth)
b.StartTimer()
for range b.N { for b.Loop() {
b.StopTimer() b.StopTimer()
wg := sync.WaitGroup{} wg := sync.WaitGroup{}
wg.Add(1) wg.Add(1)

View File

@@ -101,7 +101,7 @@ func (self *face_panel) draw_axis(sz loop.ScreenSize, y int, ax VariableAxis, ax
} }
frac := (min(axis_value, ax.Maximum) - ax.Minimum) / (ax.Maximum - ax.Minimum) frac := (min(axis_value, ax.Maximum) - ax.Minimum) / (ax.Maximum - ax.Minimum)
current_cell := int(math.Floor(frac * float64(num_of_cells-1))) current_cell := int(math.Floor(frac * float64(num_of_cells-1)))
for i := 0; i < num_of_cells; i++ { for i := range num_of_cells {
buf.WriteString(utils.IfElse(i == current_cell, lp.SprintStyled(current_val_style, ``), buf.WriteString(utils.IfElse(i == current_cell, lp.SprintStyled(current_val_style, ``),
tui.InternalHyperlink("•", fmt.Sprintf("axis:%d/%d:%s", i, num_of_cells-1, ax.Tag)))) tui.InternalHyperlink("•", fmt.Sprintf("axis:%d/%d:%s", i, num_of_cells-1, ax.Tag))))
} }

View File

@@ -258,7 +258,7 @@ func parse_escape_code(etype loop.EscapeCodeType, data []byte) (metadata map[str
} }
} }
if len(parts) > 1 { if len(parts) > 1 {
for _, record := range bytes.Split(parts[1], utils.UnsafeStringToBytes(":")) { for record := range bytes.SplitSeq(parts[1], utils.UnsafeStringToBytes(":")) {
rp := bytes.SplitN(record, utils.UnsafeStringToBytes("="), 2) rp := bytes.SplitN(record, utils.UnsafeStringToBytes("="), 2)
v := "" v := ""
if len(rp) == 2 { if len(rp) == 2 {

View File

@@ -452,7 +452,7 @@ Exec=%s desktop-ui run-server
patched_file := "" patched_file := ""
desktops := utils.Filter(strings.Split(d, ":"), func(x string) bool { return x != "" }) desktops := utils.Filter(strings.Split(d, ":"), func(x string) bool { return x != "" })
desktops = append(desktops, "") desktops = append(desktops, "")
for _, x := range strings.Split(d, ":") { for x := range strings.SplitSeq(d, ":") {
q := filepath.Join(cf, utils.IfElse(x == "", "portals.conf", fmt.Sprintf("%s-portals.conf", strings.ToLower(x)))) q := filepath.Join(cf, utils.IfElse(x == "", "portals.conf", fmt.Sprintf("%s-portals.conf", strings.ToLower(x))))
if text, err := os.ReadFile(q); err == nil { if text, err := os.ReadFile(q); err == nil {
text := patch_portals_conf(text) text := patch_portals_conf(text)

View File

@@ -119,10 +119,7 @@ func Diff(oldName, old, newName, new string, num_of_context_lines int) []byte {
// End chunk with common lines for context. // End chunk with common lines for context.
if len(ctext) > 0 { if len(ctext) > 0 {
n := end.x - start.x n := min(end.x-start.x, C)
if n > C {
n = C
}
for _, s := range x[start.x : start.x+n] { for _, s := range x[start.x : start.x+n] {
ctext = append(ctext, " "+s) ctext = append(ctext, " "+s)
count.x++ count.x++
@@ -237,7 +234,7 @@ func tgs(x, y []string) []pair {
for i := range T { for i := range T {
T[i] = n + 1 T[i] = n + 1
} }
for i := 0; i < n; i++ { for i := range n {
k := sort.Search(n, func(k int) bool { k := sort.Search(n, func(k int) bool {
return T[k] >= J[i] return T[k] >= J[i]
}) })

View File

@@ -79,7 +79,7 @@ func process_escape_codes(text string) (ans string, hyperlinks []Mark) {
active_hyperlink_url = url active_hyperlink_url = url
active_hyperlink_start_offset = start active_hyperlink_start_offset = start
if metadata != "" { if metadata != "" {
for _, entry := range strings.Split(metadata, ":") { for entry := range strings.SplitSeq(metadata, ":") {
if strings.HasPrefix(entry, "id=") && len(entry) > 3 { if strings.HasPrefix(entry, "id=") && len(entry) > 3 {
active_hyperlink_id = entry[3:] active_hyperlink_id = entry[3:]
} }

View File

@@ -47,7 +47,7 @@ func get_options_for_rg() (expecting_args map[string]bool, alias_map map[string]
expecting_arg := strings.Contains(s, "=") expecting_arg := strings.Contains(s, "=")
single_letter_aliases := make([]string, 0, 1) single_letter_aliases := make([]string, 0, 1)
long_option_names := make([]string, 0, 1) long_option_names := make([]string, 0, 1)
for _, x := range strings.Split(s, ",") { for x := range strings.SplitSeq(s, ",") {
x = strings.TrimSpace(x) x = strings.TrimSpace(x)
if strings.HasPrefix(x, "--") { if strings.HasPrefix(x, "--") {
lon, _, _ := strings.Cut(x[2:], "=") lon, _, _ := strings.Cut(x[2:], "=")
@@ -136,7 +136,7 @@ func parse_args(args ...string) (delegate_to_rg bool, sanitized_args []string, k
if !found || k != "hyperlink" { if !found || k != "hyperlink" {
return fmt.Errorf("Unknown --kitten option: %s", val) return fmt.Errorf("Unknown --kitten option: %s", val)
} }
for _, x := range strings.Split(v, ",") { for x := range strings.SplitSeq(v, ",") {
switch x { switch x {
case "none": case "none":
kitten_opts.context_lines = false kitten_opts.context_lines = false

View File

@@ -137,7 +137,7 @@ func (p *parsed_data) run_loop() (err error) {
raw := utils.UnsafeBytesToString(data[len(ESC_CODE_PREFIX[2:]):]) raw := utils.UnsafeBytesToString(data[len(ESC_CODE_PREFIX[2:]):])
metadata, payload, _ := strings.Cut(raw, ";") metadata, payload, _ := strings.Cut(raw, ";")
sent_identifier, payload_type := "", "" sent_identifier, payload_type := "", ""
for _, x := range strings.Split(metadata, ":") { for x := range strings.SplitSeq(metadata, ":") {
key, val, _ := strings.Cut(x, "=") key, val, _ := strings.Cut(x, "=")
switch key { switch key {
case "i": case "i":

View File

@@ -18,11 +18,11 @@ func TestFTCSerialization(t *testing.T) {
q := func(expected string) { q := func(expected string) {
actual := ftc.Serialize() actual := ftc.Serialize()
ad := make(map[string]bool) ad := make(map[string]bool)
for _, x := range strings.Split(actual, ";") { for x := range strings.SplitSeq(actual, ";") {
ad[x] = true ad[x] = true
} }
ed := make(map[string]bool) ed := make(map[string]bool)
for _, x := range strings.Split(expected, ";") { for x := range strings.SplitSeq(expected, ";") {
ed[x] = true ed[x] = true
} }
if diff := cmp.Diff(ed, ad); diff != "" { if diff := cmp.Diff(ed, ad); diff != "" {

View File

@@ -45,7 +45,7 @@ func TestPathMappingSend(t *testing.T) {
actual[f.expanded_local_path] = f.remote_path actual[f.expanded_local_path] = f.remote_path
} }
e := make(map[string]string, len(actual)) e := make(map[string]string, len(actual))
for _, rec := range strings.Split(expected, " ") { for rec := range strings.SplitSeq(expected, " ") {
k, v, _ := strings.Cut(rec, ":") k, v, _ := strings.Cut(rec, ":")
e[mp(k, false)] = mp(v, true) e[mp(k, false)] = mp(v, true)
} }

View File

@@ -105,7 +105,7 @@ type Delegate struct {
type Completions struct { type Completions struct {
Groups []*MatchGroup `json:"groups,omitempty"` Groups []*MatchGroup `json:"groups,omitempty"`
Delegate Delegate `json:"delegate,omitempty"` Delegate Delegate `json:"delegate"`
CurrentCmd *Command `json:"-"` CurrentCmd *Command `json:"-"`
AllWords []string `json:"-"` // all words passed to parse_args() AllWords []string `json:"-"` // all words passed to parse_args()

View File

@@ -7,6 +7,7 @@ import (
"mime" "mime"
"os" "os"
"path/filepath" "path/filepath"
"slices"
"strings" "strings"
"golang.org/x/sys/unix" "golang.org/x/sys/unix"
@@ -185,13 +186,7 @@ func complete_by_fnmatch(prefix, cwd string, patterns []string) []string {
} }
func complete_by_mimepat(prefix, cwd string, patterns []string) []string { func complete_by_mimepat(prefix, cwd string, patterns []string) []string {
all_allowed := false all_allowed := slices.Contains(patterns, "*")
for _, p := range patterns {
if p == "*" {
all_allowed = true
break
}
}
return fname_based_completer(prefix, cwd, func(name string) bool { return fname_based_completer(prefix, cwd, func(name string) bool {
if all_allowed { if all_allowed {
return true return true

View File

@@ -19,7 +19,7 @@ var _ = fmt.Print
type Context struct { type Context struct {
fmt_ctx style.Context fmt_ctx style.Context
Cyan, Green, Blue, Magenta, Red, BrightRed, Yellow, Italic, Bold, Dim, Title, Exe, Opt, Emph, Err, Code func(args ...interface{}) string Cyan, Green, Blue, Magenta, Red, BrightRed, Yellow, Italic, Bold, Dim, Title, Exe, Opt, Emph, Err, Code func(args ...any) string
Url func(string, string) string Url func(string, string) string
} }

View File

@@ -184,7 +184,7 @@ func (self *ResponseData) UnmarshalJSON(data []byte) error {
type Response struct { type Response struct {
Ok bool `json:"ok"` Ok bool `json:"ok"`
Data ResponseData `json:"data,omitempty"` Data ResponseData `json:"data"`
Error string `json:"error,omitempty"` Error string `json:"error,omitempty"`
Traceback string `json:"tb,omitempty"` Traceback string `json:"tb,omitempty"`
} }

View File

@@ -39,10 +39,7 @@ func parse_send_text(io_data *rc_io_data, args []string) error {
} }
text := strings.Join(args, " ") text := strings.Join(args, " ")
text_gen := func(io_data *rc_io_data) (bool, error) { text_gen := func(io_data *rc_io_data) (bool, error) {
limit := len(text) limit := min(len(text), 2048)
if limit > 2048 {
limit = 2048
}
set_payload_data(io_data, "base64:"+base64.StdEncoding.EncodeToString(utils.UnsafeStringToBytes(text[:limit]))) set_payload_data(io_data, "base64:"+base64.StdEncoding.EncodeToString(utils.UnsafeStringToBytes(text[:limit])))
text = text[limit:] text = text[limit:]
return len(text) == 0, nil return len(text) == 0, nil

View File

@@ -18,7 +18,7 @@ var _ = fmt.Print
func ParseStrDict(val, record_sep, field_sep string) (map[string]string, error) { func ParseStrDict(val, record_sep, field_sep string) (map[string]string, error) {
ans := make(map[string]string) ans := make(map[string]string)
for _, record := range strings.Split(val, record_sep) { for record := range strings.SplitSeq(val, record_sep) {
key, val, found := strings.Cut(record, field_sep) key, val, found := strings.Cut(record, field_sep)
if found { if found {
ans[key] = val ans[key] = val

View File

@@ -135,7 +135,7 @@ func generate_data(block_size, num_of_blocks int, extra ...string) []byte {
e := strings.Join(extra, "") e := strings.Join(extra, "")
ans := make([]byte, num_of_blocks*block_size+len(e)) ans := make([]byte, num_of_blocks*block_size+len(e))
utils.Memset(ans, '_') utils.Memset(ans, '_')
for i := 0; i < num_of_blocks; i++ { for i := range num_of_blocks {
offset := i * block_size offset := i * block_size
copy(ans[offset:], strconv.Itoa(i)) copy(ans[offset:], strconv.Itoa(i))
} }

View File

@@ -33,7 +33,7 @@ func BenchmarkIndexByte(b *testing.B) {
f = bytes.IndexByte f = bytes.IndexByte
} }
b.Run(fmt.Sprintf("%s_sz=%d", which, pos), func(b *testing.B) { b.Run(fmt.Sprintf("%s_sz=%d", which, pos), func(b *testing.B) {
for i := 0; i < b.N; i++ { for b.Loop() {
f(data, 'q') f(data, 'q')
} }
}) })
@@ -54,7 +54,7 @@ func BenchmarkIndexByte2(b *testing.B) {
f = index_byte2_scalar f = index_byte2_scalar
} }
b.Run(fmt.Sprintf("%s_sz=%d", which, pos), func(b *testing.B) { b.Run(fmt.Sprintf("%s_sz=%d", which, pos), func(b *testing.B) {
for i := 0; i < b.N; i++ { for b.Loop() {
f(data, 'q', 'x') f(data, 'q', 'x')
} }
}) })

View File

@@ -48,7 +48,7 @@ func test_cmpeq_epi8(a, b []byte) []byte {
func test_cmplt_epi8(t *testing.T, a, b []byte) []byte { func test_cmplt_epi8(t *testing.T, a, b []byte) []byte {
ans := make([]byte, len(a)) ans := make([]byte, len(a))
var prev []byte var prev []byte
for which := 0; which < 3; which++ { for which := range 3 {
if len(ans) == 16 { if len(ans) == 16 {
test_cmplt_epi8_asm_128(a, b, which, ans) test_cmplt_epi8_asm_128(a, b, which, ans)
} else { } else {
@@ -161,7 +161,7 @@ func TestSIMDStringOps(t *testing.T) {
} }
// test alignment issues // test alignment issues
q := []byte("abc") q := []byte("abc")
for sz := 0; sz < 32; sz++ { for sz := range 32 {
test(q, '<', '>', sz) test(q, '<', '>', sz)
test(q, ' ', 'b', sz) test(q, ' ', 'b', sz)
test(q, '<', 'a', sz) test(q, '<', 'a', sz)
@@ -172,7 +172,7 @@ func TestSIMDStringOps(t *testing.T) {
tests := func(h string, a, b byte) { tests := func(h string, a, b byte) {
for _, sz := range []int{0, 16, 32, 64, 79} { for _, sz := range []int{0, 16, 32, 64, 79} {
q := strings.Repeat(" ", sz) + h q := strings.Repeat(" ", sz) + h
for sz := 0; sz < 32; sz++ { for sz := range 32 {
test([]byte(q), a, b, sz) test([]byte(q), a, b, sz)
} }
} }
@@ -326,7 +326,7 @@ func TestIntrinsics(t *testing.T) {
if e := test_jump_if_zero(a); e != 0 { if e := test_jump_if_zero(a); e != 0 {
t.Fatalf("Did not detect zero register") t.Fatalf("Did not detect zero register")
} }
for i := 0; i < sz; i++ { for i := range sz {
a = make([]byte, sz) a = make([]byte, sz)
a[i] = 1 a[i] = 1
if e := test_jump_if_zero(a); e != 1 { if e := test_jump_if_zero(a); e != 1 {
@@ -340,7 +340,7 @@ func TestIntrinsics(t *testing.T) {
if e := test_count_to_match(a, 77); e != -1 { if e := test_count_to_match(a, 77); e != -1 {
t.Fatalf("Unexpectedly found byte at: %d", e) t.Fatalf("Unexpectedly found byte at: %d", e)
} }
for i := 0; i < sz; i++ { for i := range sz {
if e := test_count_to_match(a, byte(i)); e != i { if e := test_count_to_match(a, byte(i)); e != i {
t.Fatalf("Failed to find the byte: %d (%d != %d)", i, i, e) t.Fatalf("Failed to find the byte: %d (%d != %d)", i, i, e)
} }

View File

@@ -41,7 +41,7 @@ func index_byte2_string_scalar(data string, a, b byte) int {
} }
func index_c0_scalar(data []byte) int { func index_c0_scalar(data []byte) int {
for i := 0; i < len(data); i++ { for i := range data {
if data[i] == 0x7f || data[i] < ' ' { if data[i] == 0x7f || data[i] < ' ' {
return i return i
} }

View File

@@ -688,7 +688,7 @@ func ColorSettingsAsEscapeCodes(settings map[string]string) string {
set_default_color("selection_foreground", style.DefaultColors.SelectionFg, loop.SELECTION_FG) set_default_color("selection_foreground", style.DefaultColors.SelectionFg, loop.SELECTION_FG)
w.WriteString("\033]4") w.WriteString("\033]4")
for i := 0; i < 256; i++ { for i := range 256 {
key := "color" + strconv.Itoa(i) key := "color" + strconv.Itoa(i)
val := settings[key] val := settings[key]
if val != "" { if val != "" {

View File

@@ -137,7 +137,7 @@ func get_shell_name(argv0 string) (ans string) {
func rc_modification_allowed(ksi string) (allowed bool, set_ksi_env_var bool) { func rc_modification_allowed(ksi string) (allowed bool, set_ksi_env_var bool) {
allowed = ksi != "" allowed = ksi != ""
set_ksi_env_var = true set_ksi_env_var = true
for _, x := range strings.Split(ksi, " ") { for x := range strings.SplitSeq(ksi, " ") {
switch x { switch x {
case "disabled": case "disabled":
allowed = false allowed = false

View File

@@ -110,7 +110,7 @@ func PathToTerminfoDb(term string) (ans string) {
return ans return ans
} }
if td := os.Getenv("TERMINFO_DIRS"); td != "" { if td := os.Getenv("TERMINFO_DIRS"); td != "" {
for _, q := range strings.Split(td, string(os.PathListSeparator)) { for q := range strings.SplitSeq(td, string(os.PathListSeparator)) {
if q == "" { if q == "" {
q = "/usr/share/terminfo" q = "/usr/share/terminfo"
} }

View File

@@ -45,7 +45,7 @@ var decoder_array = sync.OnceValue(func() *[256]byte {
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
} }
for i := 0; i < len(encode); i++ { for i := range len(encode) {
decode[encode[i]] = byte(i) decode[encode[i]] = byte(i)
} }
return &decode return &decode
@@ -101,7 +101,7 @@ func decodeChunk(decode *[256]byte, dst, src []byte) (int, int) {
var val uint32 var val uint32
m := DecodedLen(len(src)) m := DecodedLen(len(src))
buf := [5]byte{84, 84, 84, 84, 84} buf := [5]byte{84, 84, 84, 84, 84}
for i := 0; i < len(src); i++ { for i := range src {
e := decode[src[i]] e := decode[src[i]]
if e == 0xFF { if e == 0xFF {
return 0, i + 1 return 0, i + 1
@@ -109,7 +109,7 @@ func decodeChunk(decode *[256]byte, dst, src []byte) (int, int) {
buf[i] = e buf[i] = e
} }
for i := 0; i < 5; i++ { for i := range 5 {
r := buf[i] r := buf[i]
val += uint32(r) * decode_base[i] val += uint32(r) * decode_base[i]
} }

View File

@@ -100,7 +100,7 @@ func CustomRelTime(a, b time.Time, albl, blbl string, magnitudes []RelTimeMagnit
n = len(magnitudes) - 1 n = len(magnitudes) - 1
} }
mag := magnitudes[n] mag := magnitudes[n]
args := []interface{}{} args := []any{}
escaped := false escaped := false
for _, ch := range mag.Format { for _, ch := range mag.Format {
if escaped { if escaped {

View File

@@ -58,14 +58,14 @@ func LongestCommon(next func() (string, bool), prefix bool) string {
return "" return ""
} }
if prefix { if prefix {
for i := 0; i < max_len; i++ { for i := range max_len {
if xfix[i] != q[i] { if xfix[i] != q[i] {
xfix = xfix[:i] xfix = xfix[:i]
break break
} }
} }
} else { } else {
for i := 0; i < max_len; i++ { for i := range max_len {
xi := xfix_len - i - 1 xi := xfix_len - i - 1
si := q_len - i - 1 si := q_len - i - 1
if xfix[xi] != q[si] { if xfix[xi] != q[si] {

View File

@@ -103,7 +103,7 @@ func ConfigDirForName(name string) (config_dir string) {
add(xh) add(xh)
} }
if dirs := os.Getenv("XDG_CONFIG_DIRS"); dirs != "" { if dirs := os.Getenv("XDG_CONFIG_DIRS"); dirs != "" {
for _, candidate := range strings.Split(dirs, ":") { for candidate := range strings.SplitSeq(dirs, ":") {
add(candidate) add(candidate)
} }
} }

View File

@@ -21,10 +21,7 @@ func num_to_string(number *big.Int, alphabet []rune, alphabet_len *big.Int, pad_
if number.Sign() < 0 { if number.Sign() < 0 {
*number = zero *number = zero
} }
capacity := 64 capacity := max(pad_to_length, 64)
if pad_to_length > capacity {
capacity = pad_to_length
}
ans := make([]rune, 0, capacity) ans := make([]rune, 0, capacity)
for number.Cmp(&zero) == 1 { for number.Cmp(&zero) == 1 {
number.DivMod(number, alphabet_len, &digit) number.DivMod(number, alphabet_len, &digit)

View File

@@ -18,7 +18,7 @@ type LineBuf struct {
func NewLineBuf(xnum, ynum uint) *LineBuf { func NewLineBuf(xnum, ynum uint) *LineBuf {
lm := make([]uint, ynum, ynum+extra_capacity) lm := make([]uint, ynum, ynum+extra_capacity)
var i uint var i uint
for i = 0; i < ynum; i++ { for i = range ynum {
lm[i] = i lm[i] = i
} }
return &LineBuf{ return &LineBuf{

View File

@@ -49,7 +49,7 @@ func (self *WCWidthIterator) handle_csi(csi []byte) error {
num_string := utils.UnsafeBytesToString(csi[:len(csi)-1]) num_string := utils.UnsafeBytesToString(csi[:len(csi)-1])
n, err := strconv.Atoi(num_string) n, err := strconv.Atoi(num_string)
if err == nil && n > 0 { if err == nil && n > 0 {
for i := 0; i < n; i++ { for range n {
err = self.handle_rune(self.prev_ch) err = self.handle_rune(self.prev_ch)
if err != nil { if err != nil {
return err return err