cat / 012
clone

a spreadsheet for the terminal: lotus 1-2-3 looks, google sheets keys and formulas, one go binary

cat/module-path
012 / internal / functions / remotekey.go
remotekey.go 2.1K
1package functions23import (4 "encoding/json"5 "fmt"6 "maps"7 "slices"8 "strconv"9 "strings"10)1112// Key identifies a question by its content: the answer cache and the13// engine's list of cells waiting for answers are keyed by it. JEV cells14// are volatile, so every recalculation looks each one up: with thousands15// of them, encoding the key with encoding/json took most of the time an16// answer spent in recalc. The shapes a RemoteCall holds are encoded by17// hand, each value tagged and each string length-prefixed so different18// calls never share a key; anything else falls back to JSON.19func (c RemoteCall) Key() string {20 var b strings.Builder21 b.Grow(64 + len(c.Instructions))22 keyStr(&b, c.Kind)23 keyStr(&b, c.Instructions)24 if keyValue(&b, c.State) && keyValue(&b, c.Criteria) {25 return b.String()26 }27 j, err := json.Marshal(c)28 if err != nil {29 return fmt.Sprintf("%#v", c)30 }31 return "j" + string(j)32}3334func keyStr(b *strings.Builder, s string) {35 b.WriteString(strconv.Itoa(len(s)))36 b.WriteByte(':')37 b.WriteString(s)38}3940// keyValue encodes v and reports whether it is a shape it knows.41func keyValue(b *strings.Builder, v any) bool {42 switch v := v.(type) {43 case nil:44 b.WriteByte('n')45 case string:46 b.WriteByte('s')47 keyStr(b, v)48 case float64:49 b.WriteByte('f')50 b.WriteString(strconv.FormatFloat(v, 'g', -1, 64))51 b.WriteByte(';')52 case bool:53 if v {54 b.WriteByte('T')55 } else {56 b.WriteByte('F')57 }58 case [2]string:59 b.WriteByte('p')60 keyStr(b, v[0])61 keyStr(b, v[1])62 case []string:63 b.WriteByte('l')64 b.WriteString(strconv.Itoa(len(v)))65 for _, s := range v {66 keyStr(b, s)67 }68 case map[string]string:69 b.WriteByte('m')70 b.WriteString(strconv.Itoa(len(v)))71 for _, k := range slices.Sorted(maps.Keys(v)) {72 keyStr(b, k)73 keyStr(b, v[k])74 }75 case []any:76 b.WriteByte('a')77 b.WriteString(strconv.Itoa(len(v)))78 for _, e := range v {79 if !keyValue(b, e) {80 return false81 }82 }83 case [][]any:84 b.WriteByte('r')85 b.WriteString(strconv.Itoa(len(v)))86 for _, row := range v {87 if !keyValue(b, row) {88 return false89 }90 }91 default:92 return false93 }94 return true95}