// SPDX-License-Identifier: AGPL-3.0-or-later package directory import "strings" // Sibling pages are ordered by a fractional index: a string key that sorts // byte-wise (SQLite's default collation), so moving a page rewrites only that // page. Keys use base-62 digits and never end in the zero digit, which leaves // room for a key below any other. const digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" // maxKeyLen is when to renumber siblings instead of growing keys further // (pages.position allows 128 characters). const maxKeyLen = 64 // keyBetween returns a key that sorts strictly between a and b. "" means no // bound: keyBetween("", "") is the first key of an empty list. func keyBetween(a, b string) string { if b != "" { n := 0 for n < len(b) && digitAt(a, n) == b[n] { n++ } if n > 0 { return b[:n] + keyBetween(a[min(n, len(a)):], b[n:]) } } da := 0 if a != "" { da = strings.IndexByte(digits, a[0]) } db := len(digits) if b != "" { db = strings.IndexByte(digits, b[0]) } if db-da > 1 { return string(digits[(da+db+1)/2]) } if len(b) > 1 { return b[:1] } rest := "" if a != "" { rest = a[1:] } return string(digits[da]) + keyBetween(rest, "") } // digitAt is a's n-th byte, or the zero digit past its end. func digitAt(a string, n int) byte { if n < len(a) { return a[n] } return digits[0] } // evenKeys returns n ascending keys spread evenly, all the same short length. func evenKeys(n int) []string { width, space := 1, len(digits) for space < 2*(n+1) { width++ space *= len(digits) } step := space / (n + 1) keys := make([]string, n) for i := range keys { v := (i + 1) * step b := make([]byte, width) for j := width - 1; j >= 0; j-- { b[j] = digits[v%len(digits)] v /= len(digits) } // step >= 2, so bumping a trailing zero digit keeps keys distinct and ordered. if b[width-1] == digits[0] { b[width-1] = digits[1] } keys[i] = string(b) } return keys }