From e076b0fdd8dea6d3007f7f614e1ad3b76a099abc Mon Sep 17 00:00:00 2001 From: Mikhail Knyazhev Date: Fri, 17 Jul 2026 18:08:29 +0300 Subject: [PATCH 1/6] compare --- comp/common.go | 16 ++++++ comp/damerau_levenshtein.go | 92 ++++++++++++++++++++++++++++++ comp/damerau_levenshtein_test.go | 44 +++++++++++++++ comp/hamming.go | 47 ++++++++++++++++ comp/hamming_test.go | 44 +++++++++++++++ comp/jaro.go | 97 ++++++++++++++++++++++++++++++++ comp/jaro_test.go | 44 +++++++++++++++ comp/lcs.go | 66 ++++++++++++++++++++++ comp/lcs_test.go | 44 +++++++++++++++ comp/levenshtein.go | 84 +++++++++++++++++++++++++++ comp/levenshtein_test.go | 44 +++++++++++++++ encoding/token/token_test.go | 2 +- go.mod | 2 +- go.sum | 4 +- 14 files changed, 626 insertions(+), 4 deletions(-) create mode 100644 comp/common.go create mode 100644 comp/damerau_levenshtein.go create mode 100644 comp/damerau_levenshtein_test.go create mode 100644 comp/hamming.go create mode 100644 comp/hamming_test.go create mode 100644 comp/jaro.go create mode 100644 comp/jaro_test.go create mode 100644 comp/lcs.go create mode 100644 comp/lcs_test.go create mode 100644 comp/levenshtein.go create mode 100644 comp/levenshtein_test.go diff --git a/comp/common.go b/comp/common.go new file mode 100644 index 0000000..425c730 --- /dev/null +++ b/comp/common.go @@ -0,0 +1,16 @@ +/* + * Copyright (c) 2019-2026 Mikhail Knyazhev . All rights reserved. + * Use of this source code is governed by a BSD 3-Clause license that can be found in the LICENSE file. + */ + +package comp + +import "math" + +type Comparer[T comparable] interface { + Similarity(a, b []T) float64 +} + +func round(x float64) float64 { + return math.Round(x*1_00_00) / 100 +} diff --git a/comp/damerau_levenshtein.go b/comp/damerau_levenshtein.go new file mode 100644 index 0000000..80c557c --- /dev/null +++ b/comp/damerau_levenshtein.go @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2019-2026 Mikhail Knyazhev . All rights reserved. + * Use of this source code is governed by a BSD 3-Clause license that can be found in the LICENSE file. + */ + +package comp + +type damerauLevenshtein[T comparable] struct { +} + +func NewDamerauLevenshtein[T comparable]() Comparer[T] { + return &damerauLevenshtein[T]{} +} + +func (l *damerauLevenshtein[T]) Distance(a, b []T) int { + n, m := len(a), len(b) + + if n == 0 { + return m + } + if m == 0 { + return n + } + if n < m { + b, a = a, b + n, m = m, n + } + + size := m + 1 + + var buf [192]int + var prev2, prev1, curr []int + + if size <= 64 { + prev2 = buf[0:size] + prev1 = buf[64 : 64+size] + curr = buf[128 : 128+size] + } else { + heapBuf := make([]int, size*3) + prev2 = heapBuf[0:size] + prev1 = heapBuf[size : size*2] + curr = heapBuf[size*2 : size*3] + } + + for j := 0; j <= m; j++ { + prev1[j] = j + } + + for i := 1; i <= n; i++ { + curr[0] = i + + aItem1 := a[i-1] + var aItem2 T + if i > 1 { + aItem2 = a[i-2] + } + + for j := 1; j <= m; j++ { + bItem1 := b[j-1] + + cost := 0 + if aItem1 != bItem1 { + cost = 1 + } + + curr[j] = min( + prev1[j]+1, // удаление + curr[j-1]+1, // вставка + prev1[j-1]+cost, // замена + ) + + if i > 1 && j > 1 && aItem1 == b[j-2] && aItem2 == bItem1 { + curr[j] = min(curr[j], prev2[j-2]+1) // транспозиция + } + } + + prev2, prev1, curr = prev1, curr, prev2 + } + + return prev1[m] +} + +func (l *damerauLevenshtein[T]) Similarity(a, b []T) float64 { + maxLen := max(len(a), len(b)) + if maxLen == 0 { + return 1.0 + } + + dist := l.Distance(a, b) + + return round(1.0 - float64(dist)/float64(maxLen)) +} diff --git a/comp/damerau_levenshtein_test.go b/comp/damerau_levenshtein_test.go new file mode 100644 index 0000000..8695efe --- /dev/null +++ b/comp/damerau_levenshtein_test.go @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2019-2026 Mikhail Knyazhev . All rights reserved. + * Use of this source code is governed by a BSD 3-Clause license that can be found in the LICENSE file. + */ + +package comp + +import ( + "testing" + + "go.osspkg.com/casecheck" +) + +func TestUnit_NewDamerauLevenshtein(t *testing.T) { + { + c := NewDamerauLevenshtein[rune]() + + casecheck.Equal(t, 81.82, c.Similarity([]rune("Hello world"), []rune("Hello-World"))) + casecheck.Equal(t, 100.0, c.Similarity([]rune("Hello world"), []rune("Hello world"))) + casecheck.Equal(t, 27.27, c.Similarity([]rune("Hello world"), []rune("world Hello"))) + casecheck.Equal(t, 90.91, c.Similarity([]rune("Hello world"), []rune("Helle world"))) + } + + { + c := NewDamerauLevenshtein[int]() + + casecheck.Equal(t, 100.0, c.Similarity([]int{1, 2, 3}, []int{1, 2, 3})) + casecheck.Equal(t, 66.67, c.Similarity([]int{1, 2, 3}, []int{1, 3, 2})) + casecheck.Equal(t, 0.0, c.Similarity([]int{1, 2, 3}, []int{4, 5, 6})) + } +} + +func Benchmark_NewDamerauLevenshtein(b *testing.B) { + c := NewDamerauLevenshtein[rune]() + m1, m2 := []rune("Hello world"), []rune("Hello-World") + + b.ReportAllocs() + b.ResetTimer() + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + c.Similarity(m1, m2) + } + }) +} diff --git a/comp/hamming.go b/comp/hamming.go new file mode 100644 index 0000000..95e8388 --- /dev/null +++ b/comp/hamming.go @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2019-2026 Mikhail Knyazhev . All rights reserved. + * Use of this source code is governed by a BSD 3-Clause license that can be found in the LICENSE file. + */ + +package comp + +type hamming[T comparable] struct { +} + +func NewHamming[T comparable]() Comparer[T] { + return &hamming[T]{} +} + +func (h *hamming[T]) Distance(a, b []T) int { + n, m := len(a), len(b) + if n != m { + return -1 + } + + dist := 0 + for i := 0; i < n; i++ { + if a[i] != b[i] { + dist++ + } + } + + return dist +} + +func (h *hamming[T]) Similarity(a, b []T) float64 { + n, m := len(a), len(b) + if n != m { + return 0.0 + } + + if n == 0 { + return 1.0 + } + + dist := h.Distance(a, b) + if dist < 0 { + return 0.0 + } + + return round(1.0 - float64(dist)/float64(n)) +} diff --git a/comp/hamming_test.go b/comp/hamming_test.go new file mode 100644 index 0000000..6dae942 --- /dev/null +++ b/comp/hamming_test.go @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2019-2026 Mikhail Knyazhev . All rights reserved. + * Use of this source code is governed by a BSD 3-Clause license that can be found in the LICENSE file. + */ + +package comp + +import ( + "testing" + + "go.osspkg.com/casecheck" +) + +func TestUnit_NewHamming(t *testing.T) { + { + c := NewHamming[rune]() + + casecheck.Equal(t, 81.82, c.Similarity([]rune("Hello world"), []rune("Hello-World"))) + casecheck.Equal(t, 100.0, c.Similarity([]rune("Hello world"), []rune("Hello world"))) + casecheck.Equal(t, 27.27, c.Similarity([]rune("Hello world"), []rune("world Hello"))) + casecheck.Equal(t, 90.91, c.Similarity([]rune("Hello world"), []rune("Helle world"))) + } + + { + c := NewHamming[int]() + + casecheck.Equal(t, 100.0, c.Similarity([]int{1, 2, 3}, []int{1, 2, 3})) + casecheck.Equal(t, 33.33, c.Similarity([]int{1, 2, 3}, []int{1, 3, 2})) + casecheck.Equal(t, 0.0, c.Similarity([]int{1, 2, 3}, []int{4, 5, 6})) + } +} + +func Benchmark_NewHamming(b *testing.B) { + c := NewHamming[rune]() + m1, m2 := []rune("Hello world"), []rune("Hello-World") + + b.ReportAllocs() + b.ResetTimer() + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + c.Similarity(m1, m2) + } + }) +} diff --git a/comp/jaro.go b/comp/jaro.go new file mode 100644 index 0000000..ed091db --- /dev/null +++ b/comp/jaro.go @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2019-2026 Mikhail Knyazhev . All rights reserved. + * Use of this source code is governed by a BSD 3-Clause license that can be found in the LICENSE file. + */ + +package comp + +import "slices" + +type jaro[T comparable] struct { +} + +func NewJaroWinkler[T comparable]() Comparer[T] { + return &jaro[T]{} +} + +func (l *jaro[T]) Similarity(a, b []T) float64 { + if slices.Equal(a, b) { + return 100.0 + } + + if len(a) == 0 || len(b) == 0 { + return 0.0 + } + + r1, r2 := a, b + l1, l2 := len(r1), len(r2) + + matchDistance := l1 + if l2 > matchDistance { + matchDistance = l2 + } + matchDistance = (matchDistance / 2) - 1 + if matchDistance < 0 { + matchDistance = 0 + } + + var m1Buf, m2Buf [64]bool + var m1, m2 []bool + if l1 <= 64 { + m1 = m1Buf[:l1] + } else { + m1 = make([]bool, l1) + } + if l2 <= 64 { + m2 = m2Buf[:l2] + } else { + m2 = make([]bool, l2) + } + + matches := 0 + for i := 0; i < l1; i++ { + start := i - matchDistance + if start < 0 { + start = 0 + } + end := i + matchDistance + 1 + if end > l2 { + end = l2 + } + + for j := start; j < end; j++ { + if m2[j] { + continue + } + if r1[i] == r2[j] { + m1[i] = true + m2[j] = true + matches++ + break + } + } + } + + if matches == 0 { + return 0.0 + } + + t := 0 + k := 0 + for i := 0; i < l1; i++ { + if !m1[i] { + continue + } + for !m2[k] { + k++ + } + if r1[i] != r2[k] { + t++ + } + k++ + } + t /= 2 + + m := float64(matches) + return round((m/float64(l1) + m/float64(l2) + (m-float64(t))/m) / 3.0) +} diff --git a/comp/jaro_test.go b/comp/jaro_test.go new file mode 100644 index 0000000..ceee309 --- /dev/null +++ b/comp/jaro_test.go @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2019-2026 Mikhail Knyazhev . All rights reserved. + * Use of this source code is governed by a BSD 3-Clause license that can be found in the LICENSE file. + */ + +package comp + +import ( + "testing" + + "go.osspkg.com/casecheck" +) + +func TestUnit_NewJaroWinkler(t *testing.T) { + { + c := NewJaroWinkler[rune]() + + casecheck.Equal(t, 87.88, c.Similarity([]rune("Hello world"), []rune("Hello-World"))) + casecheck.Equal(t, 100.0, c.Similarity([]rune("Hello world"), []rune("Hello world"))) + casecheck.Equal(t, 50.3, c.Similarity([]rune("Hello world"), []rune("world Hello"))) + casecheck.Equal(t, 90.61, c.Similarity([]rune("Hello world"), []rune("Helle world"))) + } + + { + c := NewJaroWinkler[int]() + + casecheck.Equal(t, 100.0, c.Similarity([]int{1, 2, 3}, []int{1, 2, 3})) + casecheck.Equal(t, 55.56, c.Similarity([]int{1, 2, 3}, []int{1, 3, 2})) + casecheck.Equal(t, 0.0, c.Similarity([]int{1, 2, 3}, []int{4, 5, 6})) + } +} + +func Benchmark_NewJaroWinkler(b *testing.B) { + c := NewJaroWinkler[rune]() + m1, m2 := []rune("Hello world"), []rune("Hello-World") + + b.ReportAllocs() + b.ResetTimer() + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + c.Similarity(m1, m2) + } + }) +} diff --git a/comp/lcs.go b/comp/lcs.go new file mode 100644 index 0000000..79a9ca7 --- /dev/null +++ b/comp/lcs.go @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2019-2026 Mikhail Knyazhev . All rights reserved. + * Use of this source code is governed by a BSD 3-Clause license that can be found in the LICENSE file. + */ + +package comp + +type lcs[T comparable] struct { +} + +func NewLCS[T comparable]() Comparer[T] { + return &lcs[T]{} +} + +func (l *lcs[T]) Distance(a, b []T) int { + x, y := a, b + n, m := len(x), len(y) + + if n == 0 { + return m + } + if m == 0 { + return n + } + if n < m { + y, x = x, y + n, m = m, n + } + + size := m + 1 + + var buf [128]int + var prev, curr []int + + if size <= 64 { + prev = buf[0:size] + curr = buf[64 : 64+size] + } else { + heapBuf := make([]int, size*2) + prev = heapBuf[0:size] + curr = heapBuf[size : size*2] + } + + for i := 1; i <= n; i++ { + aItem := x[i-1] + + for j := 1; j <= m; j++ { + if aItem == y[j-1] { + curr[j] = prev[j-1] + 1 + } else { + curr[j] = max(prev[j], curr[j-1]) + } + } + prev, curr = curr, prev + } + + return m + n - 2*prev[m] +} + +func (l *lcs[T]) Similarity(a, b []T) float64 { + if len(a) == 0 && len(b) == 0 { + return 1.0 + } + + return round((float64(len(a)+len(b)-l.Distance(a, b)) / 2) / float64(max(len(a), len(b)))) +} diff --git a/comp/lcs_test.go b/comp/lcs_test.go new file mode 100644 index 0000000..38759a6 --- /dev/null +++ b/comp/lcs_test.go @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2019-2026 Mikhail Knyazhev . All rights reserved. + * Use of this source code is governed by a BSD 3-Clause license that can be found in the LICENSE file. + */ + +package comp + +import ( + "testing" + + "go.osspkg.com/casecheck" +) + +func TestUnit_NewLCS(t *testing.T) { + { + c := NewLCS[rune]() + + casecheck.Equal(t, 81.82, c.Similarity([]rune("Hello world"), []rune("Hello-World"))) + casecheck.Equal(t, 100.0, c.Similarity([]rune("Hello world"), []rune("Hello world"))) + casecheck.Equal(t, 45.45, c.Similarity([]rune("Hello world"), []rune("world Hello"))) + casecheck.Equal(t, 90.91, c.Similarity([]rune("Hello world"), []rune("Helle world"))) + } + + { + c := NewLCS[int]() + + casecheck.Equal(t, 100.0, c.Similarity([]int{1, 2, 3}, []int{1, 2, 3})) + casecheck.Equal(t, 66.67, c.Similarity([]int{1, 2, 3}, []int{1, 3, 2})) + casecheck.Equal(t, 0.0, c.Similarity([]int{1, 2, 3}, []int{4, 5, 6})) + } +} + +func Benchmark_NewLCS(b *testing.B) { + c := NewLCS[rune]() + m1, m2 := []rune("Hello world"), []rune("Hello-World") + + b.ReportAllocs() + b.ResetTimer() + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + c.Similarity(m1, m2) + } + }) +} diff --git a/comp/levenshtein.go b/comp/levenshtein.go new file mode 100644 index 0000000..1a56214 --- /dev/null +++ b/comp/levenshtein.go @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2019-2026 Mikhail Knyazhev . All rights reserved. + * Use of this source code is governed by a BSD 3-Clause license that can be found in the LICENSE file. + */ + +package comp + +type levenshtein[T comparable] struct { +} + +func NewLevenshtein[T comparable]() Comparer[T] { + return &levenshtein[T]{} +} + +func (l *levenshtein[T]) Distance(a, b []T) int { + n, m := len(a), len(b) + + if n == 0 { + return m + } + if m == 0 { + return n + } + if n < m { + b, a = a, b + n, m = m, n + } + + size := m + 1 + + var buf [64]int + var col []int + + if size <= 64 { + col = buf[:size] + } else { + col = make([]int, size) + } + + for j := 0; j < size; j++ { + col[j] = j + } + + for i := 1; i <= n; i++ { + prevDiag := col[0] + col[0] = i + + aItem := a[i-1] + + for j := 1; j <= m; j++ { + currDiag := col[j] + + cost := 0 + if aItem != b[j-1] { + cost = 1 + } + + minVal := col[j] + 1 // удаление + + if ins := col[j-1] + 1; ins < minVal { + minVal = ins // вставка + } + if sub := prevDiag + cost; sub < minVal { + minVal = sub // замена + } + + col[j] = minVal + prevDiag = currDiag + } + } + + return col[m] +} + +func (l *levenshtein[T]) Similarity(a, b []T) float64 { + maxLen := max(len(a), len(b)) + if maxLen == 0 { + return 1.0 + } + + dist := l.Distance(a, b) + + return round(1.0 - float64(dist)/float64(maxLen)) +} diff --git a/comp/levenshtein_test.go b/comp/levenshtein_test.go new file mode 100644 index 0000000..7b94be3 --- /dev/null +++ b/comp/levenshtein_test.go @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2019-2026 Mikhail Knyazhev . All rights reserved. + * Use of this source code is governed by a BSD 3-Clause license that can be found in the LICENSE file. + */ + +package comp + +import ( + "testing" + + "go.osspkg.com/casecheck" +) + +func TestUnit_NewLevenshtein(t *testing.T) { + { + c := NewLevenshtein[rune]() + + casecheck.Equal(t, 81.82, c.Similarity([]rune("Hello world"), []rune("Hello-World"))) + casecheck.Equal(t, 100.0, c.Similarity([]rune("Hello world"), []rune("Hello world"))) + casecheck.Equal(t, 27.27, c.Similarity([]rune("Hello world"), []rune("world Hello"))) + casecheck.Equal(t, 90.91, c.Similarity([]rune("Hello world"), []rune("Helle world"))) + } + + { + c := NewLevenshtein[int]() + + casecheck.Equal(t, 100.0, c.Similarity([]int{1, 2, 3}, []int{1, 2, 3})) + casecheck.Equal(t, 33.33, c.Similarity([]int{1, 2, 3}, []int{1, 3, 2})) + casecheck.Equal(t, 0.0, c.Similarity([]int{1, 2, 3}, []int{4, 5, 6})) + } +} + +func Benchmark_NewLevenshtein(b *testing.B) { + c := NewLevenshtein[rune]() + m1, m2 := []rune("Hello world"), []rune("Hello-World") + + b.ReportAllocs() + b.ResetTimer() + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + c.Similarity(m1, m2) + } + }) +} diff --git a/encoding/token/token_test.go b/encoding/token/token_test.go index 3094900..cbd9705 100644 --- a/encoding/token/token_test.go +++ b/encoding/token/token_test.go @@ -161,7 +161,7 @@ func TestUnit_NewByTime(t *testing.T) { tok := NewByTime() val := binary.BigEndian.Uint64(tok[:]) // Допускаем небольшое расхождение из-за времени выполнения. - if val < uint64(now) || val > uint64(now)+1000 { + if val < uint64(now) || val > uint64(now)+10000 { t.Errorf("NewByTime value %d not close to now %d", val, now) } } diff --git a/go.mod b/go.mod index d0f5182..c37162f 100644 --- a/go.mod +++ b/go.mod @@ -4,5 +4,5 @@ go 1.24.0 require ( github.com/cespare/xxhash/v2 v2.3.0 - go.osspkg.com/casecheck v0.3.0 + go.osspkg.com/casecheck v0.3.1 ) diff --git a/go.sum b/go.sum index c8c23eb..9f2f726 100644 --- a/go.sum +++ b/go.sum @@ -1,4 +1,4 @@ github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= -go.osspkg.com/casecheck v0.3.0 h1:x15blEszElbrHrEH5H02JIIhGIg/lGZzIt1kQlD3pwM= -go.osspkg.com/casecheck v0.3.0/go.mod h1:TRFXDMFJEOtnlp3ET2Hix3osbxwPWhvaiT/HfD3+gBA= +go.osspkg.com/casecheck v0.3.1 h1:mxg1WaWy/tv7J05jvf5Idy3ydDYbac3gOOV9NPdjxvU= +go.osspkg.com/casecheck v0.3.1/go.mod h1:TRFXDMFJEOtnlp3ET2Hix3osbxwPWhvaiT/HfD3+gBA= From 43ff17b3eb7c7de7af0b68211416e0f94b5d6fd5 Mon Sep 17 00:00:00 2001 From: Mikhail Knyazhev Date: Sat, 12 Sep 2026 05:13:31 +0300 Subject: [PATCH 2/6] optimize --- comp/damerau_levenshtein.go | 6 + comp/hamming.go | 8 +- comp/levenshtein.go | 6 + encoding/base62/base62.go | 32 ++-- encoding/base62/base62_test.go | 10 ++ encoding/otp/totp.go | 41 ++++-- encoding/token/common.go | 35 +---- encoding/token/token.go | 56 ++++--- graph/dfs/graph.go | 19 ++- graph/dfs/graph_test.go | 24 +++ skills/osspkg-algorithms/SKILL.md | 41 ++++++ .../references/comparisons.md | 57 ++++++++ .../osspkg-algorithms/references/encoding.md | 120 +++++++++++++++ .../references/sorting-and-graphs.md | 138 ++++++++++++++++++ .../references/structures.md | 129 ++++++++++++++++ sorts/insertion.go | 2 +- sorts/merge.go | 2 +- structs/bitmap/bitmap.go | 82 ++++++----- structs/bitmap/bitmap_test.go | 19 +++ structs/bloom/bloom.go | 63 +++++--- trees/btree/btree.go | 25 +++- trees/btree/btree_test.go | 2 +- 22 files changed, 777 insertions(+), 140 deletions(-) create mode 100644 skills/osspkg-algorithms/SKILL.md create mode 100644 skills/osspkg-algorithms/references/comparisons.md create mode 100644 skills/osspkg-algorithms/references/encoding.md create mode 100644 skills/osspkg-algorithms/references/sorting-and-graphs.md create mode 100644 skills/osspkg-algorithms/references/structures.md diff --git a/comp/damerau_levenshtein.go b/comp/damerau_levenshtein.go index 80c557c..9f587fd 100644 --- a/comp/damerau_levenshtein.go +++ b/comp/damerau_levenshtein.go @@ -5,6 +5,8 @@ package comp +import "slices" + type damerauLevenshtein[T comparable] struct { } @@ -13,6 +15,10 @@ func NewDamerauLevenshtein[T comparable]() Comparer[T] { } func (l *damerauLevenshtein[T]) Distance(a, b []T) int { + if slices.Equal(a, b) { + return 0 + } + n, m := len(a), len(b) if n == 0 { diff --git a/comp/hamming.go b/comp/hamming.go index 95e8388..41ffaab 100644 --- a/comp/hamming.go +++ b/comp/hamming.go @@ -38,9 +38,11 @@ func (h *hamming[T]) Similarity(a, b []T) float64 { return 1.0 } - dist := h.Distance(a, b) - if dist < 0 { - return 0.0 + dist := 0 + for i := 0; i < n; i++ { + if a[i] != b[i] { + dist++ + } } return round(1.0 - float64(dist)/float64(n)) diff --git a/comp/levenshtein.go b/comp/levenshtein.go index 1a56214..b0d14f8 100644 --- a/comp/levenshtein.go +++ b/comp/levenshtein.go @@ -5,6 +5,8 @@ package comp +import "slices" + type levenshtein[T comparable] struct { } @@ -13,6 +15,10 @@ func NewLevenshtein[T comparable]() Comparer[T] { } func (l *levenshtein[T]) Distance(a, b []T) int { + if slices.Equal(a, b) { + return 0 + } + n, m := len(a), len(b) if n == 0 { diff --git a/encoding/base62/base62.go b/encoding/base62/base62.go index 9c2b2e8..8956a03 100644 --- a/encoding/base62/base62.go +++ b/encoding/base62/base62.go @@ -6,16 +6,14 @@ package base62 import ( - "bytes" - - "go.osspkg.com/algorithms/sorts" + "math" ) const size = 62 type Base62 struct { enc []byte - dec map[byte]uint64 + dec [256]byte } func New(alphabet string) *Base62 { @@ -24,28 +22,38 @@ func New(alphabet string) *Base62 { } v := &Base62{ enc: []byte(alphabet), - dec: make(map[byte]uint64, size), + } + for i := range v.dec { + v.dec[i] = 0xff } for i, b := range v.enc { - v.dec[b] = uint64(i) + if v.dec[b] != 0xff { + panic("encoding alphabet contains duplicate bytes") + } + v.dec[b] = byte(i) } return v } func (v *Base62) Encode(id uint64) string { - result := make([]byte, 0, 11) + var result [11]byte + i := len(result) for id > 0 { - result = append(result, v.enc[id%size]) + i-- + result[i] = v.enc[id%size] id /= size } - sorts.Reverse(result) - return string(result) + return string(result[i:]) } func (v *Base62) Decode(data string) uint64 { var id uint64 - for _, r := range data { - id = id*size + uint64(bytes.IndexRune(v.enc, r)) + for i := 0; i < len(data); i++ { + value := v.dec[data[i]] + if value == 0xff || id > (math.MaxUint64-uint64(value))/size { + return 0 + } + id = id*size + uint64(value) } return id } diff --git a/encoding/base62/base62_test.go b/encoding/base62/base62_test.go index 2a781ed..bb44c65 100644 --- a/encoding/base62/base62_test.go +++ b/encoding/base62/base62_test.go @@ -50,6 +50,16 @@ func TestEncode_EncodeDecode(t *testing.T) { } } +func TestDecode_InvalidInput(t *testing.T) { + v := New("0123456789QAZWSXEDCRFVTGBYHNUJMIKOLPqazwsxedcrfvtgbyhnujmikolp") + if got := v.Decode("!"); got != 0 { + t.Fatalf("invalid input decoded to %d", got) + } + if got := v.Decode("VVVVVVVVVVVVVVVVVVVV"); got != 0 { + t.Fatalf("overflowing input decoded to %d", got) + } +} + func TestCheckAll(t *testing.T) { v := New("0123456789QAZWSXEDCRFVTGBYHNUJMIKOLPqazwsxedcrfvtgbyhnujmikolp") diff --git a/encoding/otp/totp.go b/encoding/otp/totp.go index 5cc64aa..a4ee47b 100644 --- a/encoding/otp/totp.go +++ b/encoding/otp/totp.go @@ -76,14 +76,26 @@ func (o *OTP) generate(secret string, counter uint64, delta int64) (string, erro return "", err } - counterBytes := make([]byte, 8) - binary.BigEndian.PutUint64(counterBytes, uint64(int64(counter)+delta)) + if delta >= 0 { + if uint64(delta) > math.MaxUint64-counter { + return "", fmt.Errorf("counter overflow") + } + counter += uint64(delta) + } else { + decrement := uint64(-(delta + 1)) + 1 + if decrement > counter { + return "", fmt.Errorf("counter underflow") + } + counter -= decrement + } + + var counterBytes [8]byte + binary.BigEndian.PutUint64(counterBytes[:], counter) hm := hmac.New(o.hash, b) - if _, err := hm.Write(counterBytes); err != nil { - return strings.Repeat("0", o.codeSize), err - } - timeHash := hm.Sum(nil) + _, _ = hm.Write(counterBytes[:]) + var digest [64]byte + timeHash := hm.Sum(digest[:0]) offset := int(timeHash[len(timeHash)-1] & 0x0F) truncHash := int64( @@ -92,14 +104,23 @@ func (o *OTP) generate(secret string, counter uint64, delta int64) (string, erro (int(timeHash[offset+2])&0xff)<<8 | (int(timeHash[offset+3]) & 0xff)) - otp := truncHash % int64(math.Pow10(o.codeSize)) + modulo := int64(1_000_000) + if o.codeSize == 8 { + modulo = 100_000_000 + } + otp := truncHash % modulo - return fmt.Sprintf(o.codeTmpl, otp), nil + var code [8]byte + for i := o.codeSize - 1; i >= 0; i-- { + code[i] = byte(otp%10) + '0' + otp /= 10 + } + return string(code[:o.codeSize]), nil } func (o *OTP) GenerateTOTP(secret string, delta int64) (string, error) { currentTime := time.Now().Unix() - counter := uint64(math.Floor(float64(currentTime) / float64(o.period))) + counter := uint64(currentTime / o.period) return o.generate(secret, counter, delta) } @@ -136,7 +157,7 @@ func (o *OTP) UrlHOTP(secret, account, issuer string, counter uint64) string { "algorithm": []string{o.algorithm}, "digits": []string{strconv.Itoa(o.codeSize)}, "period": []string{strconv.Itoa(int(o.period))}, - "counter": []string{strconv.Itoa(int(counter))}, + "counter": []string{strconv.FormatUint(counter, 10)}, } uri := url.URL{ diff --git a/encoding/token/common.go b/encoding/token/common.go index 6616043..50505c4 100644 --- a/encoding/token/common.go +++ b/encoding/token/common.go @@ -7,41 +7,13 @@ package token import ( "errors" - "math/rand/v2" "sync" - "time" ) -var ( - poolRnd = sync.Pool{New: func() any { - return createRand() - }} - poolDigest = sync.Pool{New: func() any { - return createDigest(createRand(), 128) - }} -) - -type digest struct { - D []byte -} - -func createRand() *rand.Rand { - seed2 := uint64(time.Now().UnixNano()) - return rand.New(rand.NewPCG(seed2/100, seed2)) //nolint:gosec -} - -func createDigest(rnd *rand.Rand, n int) *digest { - b := make([]byte, 0, n) - for i := 0; i < n; i++ { - v := rnd.IntN(255) - b = append(b, byte(v)) - } - return &digest{D: b} -} - var ( table []byte reverseTable [255]int + tableMu sync.RWMutex ) func init() { @@ -68,12 +40,17 @@ func SetTable(s string) error { r[i] = -1 } for i, b := range t { + if b == 0xff { + return errors.New("token: table cannot contain byte 0xff") + } if _, ok := uniq[b]; ok { return errors.New("token: duplicate chars in table") } uniq[b] = struct{}{} r[b] = i } + tableMu.Lock() table, reverseTable = t, r + tableMu.Unlock() return nil } diff --git a/encoding/token/token.go b/encoding/token/token.go index 2399a9e..59c6f74 100644 --- a/encoding/token/token.go +++ b/encoding/token/token.go @@ -9,7 +9,6 @@ import ( "crypto/md5" crand "crypto/rand" "encoding/binary" - "math/rand/v2" "time" ) @@ -18,6 +17,9 @@ type T64 [8]byte var Nil T64 func (t T64) String() string { + tableMu.RLock() + defer tableMu.RUnlock() + var dst [18]byte dlt := len(table) j := 0 @@ -43,6 +45,9 @@ func (t T64) Uint64() uint64 { } func ParseBytes(s []byte) (T64, bool) { + tableMu.RLock() + defer tableMu.RUnlock() + n := len(s) if n != 18 || s[6] != '-' || s[11] != '-' { return Nil, false @@ -64,7 +69,7 @@ func ParseBytes(s []byte) (T64, bool) { if a == -1 || b == -1 { return Nil, false } - t[j] = byte(reverseTable[s[i]]*dlt + reverseTable[s[i+1]]) + t[j] = byte(a*dlt + b) j++ } @@ -72,7 +77,31 @@ func ParseBytes(s []byte) (T64, bool) { } func Parse(s string) (T64, bool) { - return ParseBytes([]byte(s)) + tableMu.RLock() + defer tableMu.RUnlock() + + if len(s) != 18 || s[6] != '-' || s[11] != '-' { + return Nil, false + } + + dlt := len(table) + var t T64 + j := 0 + for i := 0; i < len(s); i += 2 { + if i == 6 || i == 11 { + i-- + continue + } + a := reverseTable[s[i]] + b := reverseTable[s[i+1]] + if a == -1 || b == -1 { + return Nil, false + } + t[j] = byte(a*dlt + b) + j++ + } + + return t, true } func NewByTime() (t T64) { @@ -93,9 +122,8 @@ func NewByUint(v uint64) (t T64) { } func NewByBytes(b []byte) (t T64) { - h := md5.New() //nolint:gosec - h.Write(b) - copy(t[:], h.Sum(nil)) + sum := md5.Sum(b) //nolint:gosec + copy(t[:], sum[:]) return } @@ -111,21 +139,5 @@ func NewRandom() (t T64) { return } - rnd := poolRnd.Get().(*rand.Rand) - defer poolRnd.Put(rnd) - - dgst := poolDigest.Get().(*digest) - defer poolDigest.Put(dgst) - - rnd.Shuffle(len(dgst.D), func(i, j int) { - dgst.D[i], dgst.D[j] = dgst.D[j], dgst.D[i] - }) - - ld, lt := len(dgst.D), len(t) - - for i := 0; i < lt; i++ { - t[i] = dgst.D[rnd.IntN(ld)] - } - return } diff --git a/graph/dfs/graph.go b/graph/dfs/graph.go index 559255b..ec5f747 100644 --- a/graph/dfs/graph.go +++ b/graph/dfs/graph.go @@ -17,6 +17,11 @@ var ( ErrNodeKeyExist = errors.New("node key exist") ) +const ( + stateVisiting uint8 = 1 + stateDone uint8 = 2 +) + type Graph[K comparable] struct { mu sync.RWMutex nodes map[K]struct{} @@ -65,19 +70,19 @@ func (g *Graph[K]) TopologicalSort() ([]K, error) { g.mu.RLock() defer g.mu.RUnlock() - visited := make(map[K]bool) + visited := make(map[K]uint8, len(g.nodes)) order := make([]K, 0, len(g.nodes)) var dfs func(node K) error dfs = func(node K) error { - if inProcess, exists := visited[node]; exists { - if inProcess { - return ErrCycleDetected - } + switch visited[node] { + case stateVisiting: + return ErrCycleDetected + case stateDone: return nil } - visited[node] = true + visited[node] = stateVisiting for neighbor := range g.adjacency[node] { if err := dfs(neighbor); err != nil { @@ -85,7 +90,7 @@ func (g *Graph[K]) TopologicalSort() ([]K, error) { } } - visited[node] = false + visited[node] = stateDone order = append(order, node) return nil diff --git a/graph/dfs/graph_test.go b/graph/dfs/graph_test.go index cb612af..10ac194 100644 --- a/graph/dfs/graph_test.go +++ b/graph/dfs/graph_test.go @@ -35,3 +35,27 @@ func TestUnit_DAG(t *testing.T) { _, err = dag.TopologicalSort() casecheck.Error(t, err) } + +func BenchmarkTopologicalSort(b *testing.B) { + const nodes = 1_000 + + dag := NewGraph[int]() + for i := 0; i < nodes; i++ { + if err := dag.AddNode(i); err != nil { + b.Fatal(err) + } + if i > 0 { + if err := dag.AddEdge(i-1, i); err != nil { + b.Fatal(err) + } + } + } + + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + if _, err := dag.TopologicalSort(); err != nil { + b.Fatal(err) + } + } +} diff --git a/skills/osspkg-algorithms/SKILL.md b/skills/osspkg-algorithms/SKILL.md new file mode 100644 index 0000000..ac02624 --- /dev/null +++ b/skills/osspkg-algorithms/SKILL.md @@ -0,0 +1,41 @@ +--- +name: osspkg-algorithms +description: Use the go.osspkg.com/algorithms Go module for sequence comparison, sorting, graph ordering, encodings, probabilistic filters, bitmaps, and B-trees; read the package-specific references for exact APIs and behavior. +metadata: + short-description: Use OSSPkg Go algorithms +--- + +# OSSPkg Algorithms + +Use this skill when writing or reviewing Go code that imports +`go.osspkg.com/algorithms`. The library has no useful root package: import the +specific subpackage you need. + +## Routing + +Load only the relevant reference: + +- [comparisons.md](references/comparisons.md) — `comp`: string similarity and arbitrary comparable sequences. +- [sorting-and-graphs.md](references/sorting-and-graphs.md) — `sorts`, `graph/dfs`, `graph/kahn`. +- [encoding.md](references/encoding.md) — `encoding/base62`, `encoding/otp`, `encoding/token`. +- [structures.md](references/structures.md) — `structs/bitmap`, `structs/bloom`, `trees/btree`. + +## General rules + +- Use imports such as `go.osspkg.com/algorithms/` and explicit type + arguments when a generic constructor cannot infer them from its arguments: + `comp.NewLevenshtein[rune]()`, `dfs.NewGraph[string]()` and + `btree.New[int, string](2)`. +- Check the signature of the public constructor itself. For example, `comp` + returns a `Comparer` interface whose only public method is `Similarity`; the + internal `Distance` method is not part of the external API. +- Handle every returned error. Also account for APIs that report failure with a + `bool` or return a zero value instead of an `error`. +- Sorting functions mutate the provided slice in place, and the comparison + callback receives indices into the current slice, not the values themselves. +- Before implementing new behavior, check the library's current source and + tests: these references document API usage, not hidden implementation details. + +For a dependency in another Go module, use `go get go.osspkg.com/algorithms`. +In this checkout, verify changes in the consuming package or test and run +`go test ./...`. diff --git a/skills/osspkg-algorithms/references/comparisons.md b/skills/osspkg-algorithms/references/comparisons.md new file mode 100644 index 0000000..64b8f3b --- /dev/null +++ b/skills/osspkg-algorithms/references/comparisons.md @@ -0,0 +1,57 @@ +# Sequence comparison: `comp` + +Import: + +```go +import "go.osspkg.com/algorithms/comp" +``` + +Public constructors: + +| Constructor | Suitable use case | +| --- | --- | +| `NewHamming[T]()` | equal-length sequences; counts positional mismatches | +| `NewLevenshtein[T]()` | insertions, deletions, and substitutions | +| `NewDamerauLevenshtein[T]()` | the same, plus adjacent transpositions | +| `NewLCS[T]()` | similarity based on the longest common subsequence | +| `NewJaroWinkler[T]()` | short sequences and near matches | + +`T` must satisfy `comparable`. The constructors return `comp.Comparer[T]`, so +external code calls `Similarity`: + +```go +package main + +import ( + "fmt" + + "go.osspkg.com/algorithms/comp" +) + +func main() { + cmp := comp.NewLevenshtein[rune]() + score := cmp.Similarity([]rune("kitten"), []rune("sitting")) + fmt.Printf("similarity: %.2f\n", score) +} +``` + +`Similarity` returns a value on a `0..100` scale, rounded to two decimal places; +two equal empty sequences return `100`. For text, use `[]rune` when comparison +should operate on Unicode code points, and `[]byte` when the comparison must be +byte-oriented. + +Selection notes: + +- `Hamming` is intended for equal-length inputs; with different lengths its + `Similarity` returns `0`. +- `Levenshtein` fits typo matching where insertions, deletions, and substitutions + matter. +- `Damerau-Levenshtein` is useful for swapped adjacent characters. +- `LCS` better reflects the preserved order of a common subsequence. +- `Jaro-Winkler` is useful for short values; calibrate thresholds on domain data. + +Do not call `Distance` on a constructor result from an external package: +implementations have internal distance methods, but their types are unexported +and `Comparer` does not declare that method. + +Verified examples in the checkout: `comp/*_test.go`. diff --git a/skills/osspkg-algorithms/references/encoding.md b/skills/osspkg-algorithms/references/encoding.md new file mode 100644 index 0000000..f4ef705 --- /dev/null +++ b/skills/osspkg-algorithms/references/encoding.md @@ -0,0 +1,120 @@ +# Encoding, OTP, and compact tokens + +## Base62: `encoding/base62` + +```go +package main + +import ( + "fmt" + + "go.osspkg.com/algorithms/encoding/base62" +) + +func main() { + codec := base62.New("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz") + encoded := codec.Encode(123456) + decoded := codec.Decode(encoded) + fmt.Println(encoded, decoded) +} +``` + +`New` requires exactly 62 unique bytes and panics for an invalid alphabet. +`Encode(0)` returns an empty string, and `Decode("")` returns `0`. Invalid or +overflowing input to `Decode` also becomes `0`, so the API cannot distinguish +the value `0` from an error; validate the format or check a round-trip when that +distinction matters. + +After `Base62` is created, its tables do not change, so one codec can be reused +for encoding and decoding. + +## TOTP/HOTP: `encoding/otp` + +Import `go.osspkg.com/algorithms/encoding/otp`. The defaults are SHA-1, a +30-second TOTP period, and 6 digits: + +```go +package main + +import ( + "fmt" + + "go.osspkg.com/algorithms/encoding/otp" +) + +func main() { + gen, err := otp.New(otp.OptHashSHA256(), otp.OptCode8Digits(), otp.OptPeriod(60)) + if err != nil { + panic(err) + } + + secret, err := gen.NewSecret(20) + if err != nil { + panic(err) + } + code, err := gen.GenerateTOTP(secret, 0) + if err != nil { + panic(err) + } + uri := gen.UrlTOTP(secret, "alice@example.com", "Example") + fmt.Println(code, uri) +} +``` + +`NewSecret` creates a Base32 secret without padding; validation also accepts +spaces, lowercase letters, and unpadded Base32. `delta` in `GenerateTOTP` is an +offset measured in periods, not seconds. For HOTP, use +`GenerateHOTP(secret, counter)` and `UrlHOTP(secret, account, issuer, counter)`. +`OptPeriod` clamps the period to 30–120 seconds, while an invalid secret or +counter returns an error. + +The secret and `otpauth` URI contain the key: do not log them or expose them in +ordinary traces or client responses without an explicit need. + +## `T64`: `encoding/token` + +`T64` is an 8-byte value with an 18-character text representation in the +`XXXXXX-XXXX-XXXXXX` format: + +```go +package main + +import ( + "fmt" + + "go.osspkg.com/algorithms/encoding/token" +) + +func main() { + id := token.NewRandom() + wire := id.String() + parsed, ok := token.Parse(wire) + if !ok { + panic("invalid token") + } + fmt.Println(parsed == id, id.Uint64()) +} +``` + +Factories: + +- `NewRandom()` — a random `T64`; +- `NewByTime()` and `NewFormTime(time.Time)` — UnixNano in big-endian order; +- `NewByUint(uint64)` — a number in big-endian order; +- `NewByBytes([]byte)` and `NewByString(string)` — the first 8 bytes of an MD5 + hash, suitable for a deterministic identifier but not for storing a secret. + +`Parse`/`ParseBytes` return `(T64, bool)`. `SetTable` changes the process-wide +representation table: it must have an even length from 16 to 254, contain +unique bytes, and exclude `0xff`. Configure it once at startup, before tokens +are exchanged; the byte value of `T64` itself does not change. + +`T64` provides text/binary and SQL `Scanner`/`Valuer` integration: `Value` +returns a string, while `Scan` accepts `nil`, empty values, `string`, and +`[]byte`. For JSON, do not rely solely on the presence of `MarshalJSON`: the +current implementation delegates to `MarshalText` without adding JSON quotes. +For JSON fields, use an explicit string wrapper and check the round-trip with +`Parse` until this contract is separately confirmed. + +Verified examples in the checkout: `encoding/base62/base62_test.go`, +`encoding/otp/totp_test.go`, and `encoding/token/token_test.go`. diff --git a/skills/osspkg-algorithms/references/sorting-and-graphs.md b/skills/osspkg-algorithms/references/sorting-and-graphs.md new file mode 100644 index 0000000..9eee42c --- /dev/null +++ b/skills/osspkg-algorithms/references/sorting-and-graphs.md @@ -0,0 +1,138 @@ +# Sorting and topological ordering + +## Sorting: `sorts` + +Import: + +```go +import "go.osspkg.com/algorithms/sorts" +``` + +All functions mutate the input slice. The `less(i, j)` function must return +`true` when the element at index `i` should come before the element at index `j` +in the current slice: + +```go +type Job struct { + Name string + Priority int +} + +jobs := []Job{ + {Name: "backup", Priority: 30}, + {Name: "deploy", Priority: 10}, + {Name: "test", Priority: 20}, +} + +sorts.Merge(jobs, func(i, j int) bool { + return jobs[i].Priority < jobs[j].Priority +}) +// jobs: deploy, test, backup +``` + +Available functions are `Bubble`, `Cocktail`, `Heapsort`, `Insertion`, `Merge`, +`Selection`, and `Reverse`. For ordinary application sorting, first compare the +requirements with `slices.SortFunc`/`sort.Slice`; when stability is required, +explicitly use a stable standard-library sort because stability is not a general +contract of these functions. + +Practical selection: + +- `Merge` and `Heapsort` — for the general `O(n log n)` case; +- `Insertion` — for small or nearly sorted slices; +- `Bubble`, `Cocktail`, and `Selection` — for educational or narrow cases with + small data sets; +- `Reverse` — a linear reversal without a callback. + +Do not pass a callback that reads a separate copy of the slice: the algorithm +reorders elements while running and passes indices for the current state. + +## DFS graph: `graph/dfs` + +The DFS variant supports generic `comparable` keys, requires both vertices to be +added before an edge, and returns an error for a missing vertex or a cycle: + +```go +package main + +import ( + "errors" + "fmt" + + "go.osspkg.com/algorithms/graph/dfs" +) + +func main() { + g := dfs.NewGraph[string]() + for _, node := range []string{"clean", "compile", "test", "deploy"} { + if err := g.AddNode(node); err != nil { + panic(err) + } + } + for _, edge := range [][2]string{ + {"clean", "compile"}, + {"compile", "test"}, + {"test", "deploy"}, + } { + if err := g.AddEdge(edge[0], edge[1]); err != nil { + panic(err) + } + } + + order, err := g.TopologicalSort() + if errors.Is(err, dfs.ErrCycleDetected) { + panic("dependency cycle") + } + if err != nil { + panic(err) + } + fmt.Println(order) +} +``` + +The edge direction `from -> to` means that `from` must come before `to`. For +independent vertices, define your own stabilization rule: because the graph +iterates over a map, the complete order of such vertices is not guaranteed. + +## Kahn graph: `graph/kahn` + +This variant works with `string` keys, registers vertices automatically through +`Add`, sorts the initial queue by key, and exposes the result through `Result`: + +```go +package main + +import ( + "errors" + "fmt" + + "go.osspkg.com/algorithms/graph/kahn" +) + +func main() { + g := kahn.New() + g.Add("base", "lib") + g.Add("lib", "app") + g.Add("unrelated", "unused") + g.BreakPoint("app") + + if err := g.Build(); err != nil { + if errors.Is(err, kahn.ErrBreakPoint) { + panic("break point is absent") + } + if errors.Is(err, kahn.ErrBuild) { + panic("cycle in active dependencies") + } + panic(err) + } + fmt.Println(g.Result()) // [base lib app] +} +``` + +`BreakPoint` keeps only the target vertex and its transitive dependencies +(ancestors); unrelated vertices and cycles outside this subgraph do not affect +`Build`. Without `BreakPoint`, the complete graph is built. Edge direction is +the same: add a dependency first, for example `g.Add("base", "lib")`. + +Verified examples in the checkout: `graph/dfs/graph_test.go` and +`graph/kahn/graph_test.go`. diff --git a/skills/osspkg-algorithms/references/structures.md b/skills/osspkg-algorithms/references/structures.md new file mode 100644 index 0000000..f233a8d --- /dev/null +++ b/skills/osspkg-algorithms/references/structures.md @@ -0,0 +1,129 @@ +# Data structures + +## Bitmap: `structs/bitmap` + +```go +package main + +import ( + "log" + + "go.osspkg.com/algorithms/structs/bitmap" +) + +func main() { + bm := bitmap.New(bitmap.OptMaxIndex(1024)) + bm.Set(42) + if !bm.Has(42) { + log.Fatal("bit was not set") + } + bm.Del(42) + + data, err := bm.MarshalBinary() + if err != nil { + log.Fatal(err) + } + copyBM := bitmap.New() + if err := copyBM.UnmarshalBinary(data); err != nil { + log.Fatal(err) + } +} +``` + +`Set`, `Del`, and `Has` use `uint64` indices; the bitmap grows automatically to +the requested index, but values above the exported `bitmap.MaxIndex` are +ignored or treated as absent. `MarshalBinary` returns a copy of the raw bytes. +`UnmarshalBinary` rejects empty input. + +Operations are protected by an `RWMutex` by default. Use `OptDisableLock()` only +when access is strictly single-threaded or synchronization is fully handled +externally; it is not a safe default optimization. + +## Bloom filter: `structs/bloom` + +```go +package main + +import ( + "bytes" + "log" + + "go.osspkg.com/algorithms/structs/bloom" +) + +func main() { + filter, err := bloom.New(bloom.Quantity(100_000, 0.01)) + if err != nil { + log.Fatal(err) + } + filter.Add("user:42") + if !filter.Contain("user:42") { + log.Fatal("inserted value is absent") + } + + var buf bytes.Buffer + if err := filter.Dump(&buf); err != nil { + log.Fatal(err) + } + + restored, err := bloom.New(bloom.Quantity(100_000, 0.01)) + if err != nil { + log.Fatal(err) + } + if err := restored.Restore(bytes.NewReader(buf.Bytes())); err != nil { + log.Fatal(err) + } +} +``` + +`Quantity(expectedItems, falsePositiveRate)` sets the expected number of items +and the target false-positive probability; the size must be greater than zero, +and the rate must be strictly between `0` and `1`. xxhash is used by default. +With `HashFunc`, provide a `func() hash.Hash` factory such as `sha256.New`. + +The filter answers "definitely not" or "possibly present": false positives are +normal, and `Contain` does not replace the source of truth. Use the same key +representation with `Add` and `Contain`; the library converts strings, bytes, +integers, and values implementing supported interfaces into bytes. + +`Dump` stores the salts and bitmap, but does not store the hash function or the +original `Quantity` for the consuming code. To restore, use the same quantity +configuration and hash factory as when the filter was written, then check the +error from `Restore`. `CopyTo` copies the filter state independently of the +source. + +## B-tree: `trees/btree` + +```go +package main + +import ( + "fmt" + + "go.osspkg.com/algorithms/trees/btree" +) + +func main() { + tree := btree.New[int, string](2) + tree.Insert(10, "ten") + tree.Insert(20, "twenty") + tree.Insert(10, "TEN") // duplicate key updates the value + + if value, ok := tree.Find(10); ok { + fmt.Println(value) // TEN + } + tree.Delete(20) +} +``` + +Key `K` must satisfy `cmp.Ordered`, while value `V` can be any type. `degree < 2` +is automatically replaced with `2`. `Insert` updates the value for a duplicate +key; `Find` returns `(zeroValue, false)` for a missing key, so always check the +`bool`. `Delete` does nothing for a missing key. There is no public traversal or +iterator. + +`BTree` protects `Find`, `Insert`, and `Delete` with an internal `RWMutex`, but +do not copy the value after creation: pass around the pointer returned by `New`. + +Verified examples in the checkout: `structs/bitmap/bitmap_test.go`, +`structs/bloom/bloom_test.go`, and `trees/btree/btree_test.go`. diff --git a/sorts/insertion.go b/sorts/insertion.go index a88c158..62d2265 100644 --- a/sorts/insertion.go +++ b/sorts/insertion.go @@ -13,7 +13,7 @@ func Insertion[T any](list []T, less func(i, j int) bool) { } for el := 1; el < len(list); el++ { for i := el; i > 0; i-- { - if less(i-1, i) { + if !less(i, i-1) { break } list[i-1], list[i] = list[i], list[i-1] diff --git a/sorts/merge.go b/sorts/merge.go index 0ea4bba..09aa0b7 100644 --- a/sorts/merge.go +++ b/sorts/merge.go @@ -8,7 +8,7 @@ package sorts func Merge[T any](list []T, less func(i, j int) bool) { - tmp := make([]T, 0, len(list)/2+1) + tmp := make([]T, 0, len(list)) mergeSplitSortJoin[T](list, tmp, 0, len(list)-1, less) } diff --git a/structs/bitmap/bitmap.go b/structs/bitmap/bitmap.go index 16a929b..bf24e99 100644 --- a/structs/bitmap/bitmap.go +++ b/structs/bitmap/bitmap.go @@ -6,6 +6,7 @@ package bitmap import ( + "fmt" "sync" ) @@ -51,39 +52,32 @@ func New(opts ...Option) *Bitmap { } func (b *Bitmap) resize(index uint64) { - size := index / blockSize - if index-(size%blockSize) > 0 { - size++ - } + size := index/blockSize + 1 b.bits = append(b.bits, make([]byte, size-b.blocks)...) b.blocks = uint64(len(b.bits)) b.max = b.blocks*blockSize - 1 } -func (b *Bitmap) getBlock(index uint64) uint64 { - return index / blockSize -} - -func (b *Bitmap) getBit(index uint64) byte { - return 1 << (index - b.getBlock(index)*blockSize) -} - func (b *Bitmap) Set(index uint64) { if index > MaxIndex { return } - if !b.lockoff { - b.mux.Lock() - defer b.mux.Unlock() + if b.lockoff { + if index > b.max { + b.resize(index) + } + b.bits[index/blockSize] |= 1 << (index % blockSize) + return } + b.mux.Lock() if index > b.max { b.resize(index) } - - b.bits[b.getBlock(index)] |= b.getBit(index) + b.bits[index/blockSize] |= 1 << (index % blockSize) + b.mux.Unlock() } func (b *Bitmap) Del(index uint64) { @@ -91,12 +85,14 @@ func (b *Bitmap) Del(index uint64) { return } - if !b.lockoff { - b.mux.Lock() - defer b.mux.Unlock() + if b.lockoff { + b.bits[index/blockSize] &^= 1 << (index % blockSize) + return } - b.bits[b.getBlock(index)] &^= b.getBit(index) + b.mux.Lock() + b.bits[index/blockSize] &^= 1 << (index % blockSize) + b.mux.Unlock() } func (b *Bitmap) Has(index uint64) bool { @@ -104,12 +100,14 @@ func (b *Bitmap) Has(index uint64) bool { return false } - if !b.lockoff { - b.mux.RLock() - defer b.mux.RUnlock() + if b.lockoff { + return (b.bits[index/blockSize] & (1 << (index % blockSize))) > 0 } - return (b.bits[b.getBlock(index)] & b.getBit(index)) > 0 + b.mux.RLock() + result := (b.bits[index/blockSize] & (1 << (index % blockSize))) > 0 + b.mux.RUnlock() + return result } func (b *Bitmap) MarshalBinary() ([]byte, error) { @@ -125,6 +123,14 @@ func (b *Bitmap) MarshalBinary() ([]byte, error) { } func (b *Bitmap) UnmarshalBinary(in []byte) error { + maxBlocks := MaxIndex/blockSize + 1 + if len(in) == 0 { + return fmt.Errorf("bitmap cannot be empty") + } + if uint64(len(in)) > maxBlocks { + return fmt.Errorf("bitmap is too large") + } + if !b.lockoff { b.mux.Lock() defer b.mux.Unlock() @@ -134,24 +140,34 @@ func (b *Bitmap) UnmarshalBinary(in []byte) error { copy(b.bits, in) b.blocks = uint64(len(in)) - b.max = b.blocks * blockSize + b.max = b.blocks*blockSize - 1 return nil } func (b *Bitmap) CopyTo(dst *Bitmap) { + if b == dst { + return + } + if !b.lockoff { b.mux.Lock() - defer b.mux.Unlock() } + + bits := make([]byte, len(b.bits)) + copy(bits, b.bits) + blocks, max, lockoff := b.blocks, b.max, b.lockoff + + if !b.lockoff { + b.mux.Unlock() + } + if !dst.lockoff { dst.mux.Lock() defer dst.mux.Unlock() } - - dst.bits = make([]byte, len(b.bits)) - copy(dst.bits, b.bits) - dst.blocks = b.blocks - dst.max = b.max - dst.lockoff = b.lockoff + dst.bits = bits + dst.blocks = blocks + dst.max = max + dst.lockoff = lockoff } diff --git a/structs/bitmap/bitmap_test.go b/structs/bitmap/bitmap_test.go index bc9c762..c41d220 100644 --- a/structs/bitmap/bitmap_test.go +++ b/structs/bitmap/bitmap_test.go @@ -70,6 +70,25 @@ func TestUnit_Bitmap_Marshaling(t *testing.T) { } +func TestUnit_Bitmap_UnmarshalBounds(t *testing.T) { + bm := New() + if err := bm.UnmarshalBinary([]byte{0}); err != nil { + t.Fatal(err) + } + + bm.Set(7) + if !bm.Has(7) { + t.Fatal("bit 7 should be set") + } + if bm.Has(8) { + t.Fatal("bit 8 must be outside a one-byte bitmap") + } + bm.Set(8) + if !bm.Has(8) { + t.Fatal("bit 8 should resize the bitmap") + } +} + /* goos: linux goarch: amd64 diff --git a/structs/bloom/bloom.go b/structs/bloom/bloom.go index b7788e1..b2ed1a7 100644 --- a/structs/bloom/bloom.go +++ b/structs/bloom/bloom.go @@ -37,6 +37,11 @@ import ( const saltSize = 8 +const ( + maxRestoreBytes = 64 << 20 + maxRestoreSalts = 1 << 20 +) + type Bloom struct { bits *bitmap.Bitmap size uint64 @@ -100,20 +105,24 @@ func New(opts ...Option) (*Bloom, error) { } func (b *Bloom) CopyTo(dst *Bloom) { - b.mux.Lock() - defer b.mux.Unlock() + if b == dst { + return + } + + b.mux.RLock() + bits := bitmap.New(bitmap.OptDisableLock()) + b.bits.CopyTo(bits) + size, optSize, optRate := b.size, b.optSize, b.optRate + salts := append([][saltSize]byte(nil), b.salts...) + b.mux.RUnlock() dst.mux.Lock() defer dst.mux.Unlock() - - b.bits.CopyTo(dst.bits) - dst.size = b.size - - dst.salts = make([][saltSize]byte, len(b.salts)) - copy(dst.salts, b.salts) - - dst.optSize = b.optSize - dst.optRate = b.optRate + dst.bits = bits + dst.size = size + dst.salts = salts + dst.optSize = optSize + dst.optRate = optRate } func (b *Bloom) Dump(w io.Writer) error { @@ -154,7 +163,7 @@ func (b *Bloom) Restore(r io.Reader) error { b.mux.Lock() defer b.mux.Unlock() - reader := bufio.NewReader(r) + reader := bufio.NewReader(io.LimitReader(r, maxRestoreBytes+1)) head, err := reader.ReadBytes('\n') if err != nil { @@ -174,11 +183,11 @@ func (b *Bloom) Restore(r io.Reader) error { return fmt.Errorf("invalid countSalt: %w", err) } - if count <= 0 { - return fmt.Errorf("invalid countSalt: got negative value") + if count <= 0 || count > maxRestoreSalts { + return fmt.Errorf("invalid countSalt") } - b.salts = make([][saltSize]byte, count) + salts := make([][saltSize]byte, count) for i := 0; i < count; i++ { salt, err0 := reader.ReadBytes('\n') @@ -191,15 +200,27 @@ func (b *Bloom) Restore(r io.Reader) error { return fmt.Errorf("invalid salt[%d], want 64 got %d", i, len(salt)) } - b.salts[i] = [saltSize]byte(salt) + salts[i] = [saltSize]byte(salt) } bm, err := io.ReadAll(reader) if err != nil { return fmt.Errorf("read bitmap: %w", err) } + if len(bm) == 0 || len(bm) > maxRestoreBytes { + return fmt.Errorf("invalid bitmap size") + } + if uint64(len(bm)) > bitmap.MaxIndex/8+1 { + return fmt.Errorf("bitmap is too large") + } - return b.bits.UnmarshalBinary(bm) + bits := bitmap.New(bitmap.OptDisableLock()) + if err := bits.UnmarshalBinary(bm); err != nil { + return fmt.Errorf("restore bitmap: %w", err) + } + b.bits = bits + b.salts = salts + return nil } func (b *Bloom) Add(arg any) { @@ -215,12 +236,14 @@ func (b *Bloom) Add(arg any) { b.mux.Lock() defer b.mux.Unlock() + sum := make([]byte, 0, h.Size()) for i := 0; i < len(b.salts); i++ { h.Reset() h.Write(val) h.Write(b.salts[i][:]) - key := binary.BigEndian.Uint64(h.Sum(nil)) % b.size + sum = h.Sum(sum[:0]) + key := binary.BigEndian.Uint64(sum) % b.size b.bits.Set(key) } @@ -239,12 +262,14 @@ func (b *Bloom) Contain(arg any) bool { b.mux.RLock() defer b.mux.RUnlock() + sum := make([]byte, 0, h.Size()) for i := 0; i < len(b.salts); i++ { h.Reset() h.Write(val) h.Write(b.salts[i][:]) - key := binary.BigEndian.Uint64(h.Sum(nil)) % b.size + sum = h.Sum(sum[:0]) + key := binary.BigEndian.Uint64(sum) % b.size if !b.bits.Has(key) { return false diff --git a/trees/btree/btree.go b/trees/btree/btree.go index 7d0858d..c3876c5 100644 --- a/trees/btree/btree.go +++ b/trees/btree/btree.go @@ -51,7 +51,6 @@ func New[K cmp.Ordered, V any](degree int) *BTree[K, V] { func (t *BTree[K, V]) Find(key K) (V, bool) { t.mu.RLock() - defer t.mu.RUnlock() curr := t.root for curr != nil { @@ -61,7 +60,9 @@ func (t *BTree[K, V]) Find(key K) (V, bool) { } if i < curr.numKeys && key == curr.keys[i] { - return curr.values[i], true + value := curr.values[i] + t.mu.RUnlock() + return value, true } if curr.isLeaf { @@ -71,6 +72,7 @@ func (t *BTree[K, V]) Find(key K) (V, bool) { } var zero V + t.mu.RUnlock() return zero, false } @@ -201,6 +203,9 @@ func (t *BTree[K, V]) deleteFromNode(x *node[K, V], key K) { x.values[i] = x.values[i+1] } x.numKeys-- + var zeroK K + var zeroV V + x.keys[x.numKeys], x.values[x.numKeys] = zeroK, zeroV } else { t.deleteFromInternalNode(x, idx) } @@ -298,6 +303,12 @@ func (t *BTree[K, V]) borrowFromPrev(x *node[K, V], idx int) { child.numKeys++ sibling.numKeys-- + var zeroK K + var zeroV V + sibling.keys[sibling.numKeys], sibling.values[sibling.numKeys] = zeroK, zeroV + if !sibling.isLeaf { + sibling.children[sibling.numKeys+1] = nil + } } func (t *BTree[K, V]) borrowFromNext(x *node[K, V], idx int) { @@ -327,6 +338,12 @@ func (t *BTree[K, V]) borrowFromNext(x *node[K, V], idx int) { child.numKeys++ sibling.numKeys-- + var zeroK K + var zeroV V + sibling.keys[sibling.numKeys], sibling.values[sibling.numKeys] = zeroK, zeroV + if !sibling.isLeaf { + sibling.children[sibling.numKeys+1] = nil + } } func (t *BTree[K, V]) merge(x *node[K, V], idx int) { @@ -357,4 +374,8 @@ func (t *BTree[K, V]) merge(x *node[K, V], idx int) { child.numKeys += sibling.numKeys + 1 x.numKeys-- + var zeroK K + var zeroV V + x.keys[x.numKeys], x.values[x.numKeys] = zeroK, zeroV + x.children[x.numKeys+1] = nil } diff --git a/trees/btree/btree_test.go b/trees/btree/btree_test.go index d66af7a..ece7925 100644 --- a/trees/btree/btree_test.go +++ b/trees/btree/btree_test.go @@ -67,7 +67,7 @@ func TestUnit_BTreeDuplicate(t *testing.T) { tree.Delete(5) // После удаления одного ключа 5 должно остаться два вхождения - v, found = tree.Find(5) + _, found = tree.Find(5) if found { t.Fatal("key 5 should still exist after one deletion") } From 56df40b48e638e17520488d0e2757cc5078c57a6 Mon Sep 17 00:00:00 2001 From: Mikhail Knyazhev Date: Sat, 12 Sep 2026 05:21:18 +0300 Subject: [PATCH 3/6] update readme --- README.md | 300 +++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 295 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 0fe8cb7..d76f1ba 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,303 @@ # Algorithms -Algorithmic calculation methods +[![Go Reference](https://pkg.go.dev/badge/go.osspkg.com/algorithms.svg)](https://pkg.go.dev/go.osspkg.com/algorithms) +[![Go 1.24+](https://img.shields.io/badge/go-1.24%2B-00ADD8?logo=go&logoColor=white)](https://go.dev/) +[![License](https://img.shields.io/badge/license-BSD--3--Clause-blue.svg)](LICENSE) -## Install +A collection of generic algorithms, encoders, graphs, filters, and data +structures for Go. -```shell -go get -u go.osspkg.com/algorithms +The module is intentionally split into focused subpackages. Import only the +package you need; the module root does not expose a general-purpose API. + +## Requirements + +- Go 1.24 or newer + +## Installation + +```bash +go get go.osspkg.com/algorithms@latest +``` + +## Packages + +| Package | Provides | +| --- | --- | +| [`comp`](https://pkg.go.dev/go.osspkg.com/algorithms/comp) | Hamming, Levenshtein, Damerau-Levenshtein, LCS, and Jaro-Winkler sequence comparison | +| [`sorts`](https://pkg.go.dev/go.osspkg.com/algorithms/sorts) | Bubble, cocktail, heap, insertion, merge, and selection sort; slice reversal | +| [`graph/dfs`](https://pkg.go.dev/go.osspkg.com/algorithms/graph/dfs) | Generic depth-first topological sorting with cycle detection | +| [`graph/kahn`](https://pkg.go.dev/go.osspkg.com/algorithms/graph/kahn) | String-keyed Kahn topological sorting with dependency subgraphs | +| [`encoding/base62`](https://pkg.go.dev/go.osspkg.com/algorithms/encoding/base62) | Configurable Base62 encoding for `uint64` values | +| [`encoding/otp`](https://pkg.go.dev/go.osspkg.com/algorithms/encoding/otp) | TOTP/HOTP generation and `otpauth` URLs | +| [`encoding/token`](https://pkg.go.dev/go.osspkg.com/algorithms/encoding/token) | Compact `T64` identifiers with text, binary, and SQL integration | +| [`structs/bitmap`](https://pkg.go.dev/go.osspkg.com/algorithms/structs/bitmap) | Concurrent growable bitmap | +| [`structs/bloom`](https://pkg.go.dev/go.osspkg.com/algorithms/structs/bloom) | Space-efficient Bloom filter with persistence support | +| [`trees/btree`](https://pkg.go.dev/go.osspkg.com/algorithms/trees/btree) | Concurrent generic B-tree | + +## Usage + +### Compare sequences + +Comparers work with any `comparable` element type. `Similarity` returns a score +from `0` to `100`; use `[]rune` for Unicode-aware text comparison. + +```go +package main + +import ( + "fmt" + + "go.osspkg.com/algorithms/comp" +) + +func main() { + cmp := comp.NewLevenshtein[rune]() + score := cmp.Similarity([]rune("kitten"), []rune("sitting")) + + fmt.Printf("similarity: %.2f\n", score) +} +``` + +Choose the comparer according to the type of difference you need to model: + +- `NewHamming` compares equal-length sequences and counts positional changes. +- `NewLevenshtein` accounts for insertions, deletions, and substitutions. +- `NewDamerauLevenshtein` also accounts for adjacent transpositions. +- `NewLCS` measures the longest common subsequence. +- `NewJaroWinkler` is suited to short values and near matches. + +### Sort a slice + +Sorting functions mutate the supplied slice in place. The comparison callback +receives indexes into the slice's current state. + +```go +package main + +import ( + "fmt" + + "go.osspkg.com/algorithms/sorts" +) + +type job struct { + name string + priority int +} + +func main() { + jobs := []job{ + {name: "backup", priority: 30}, + {name: "deploy", priority: 10}, + {name: "test", priority: 20}, + } + + sorts.Merge(jobs, func(i, j int) bool { + return jobs[i].priority < jobs[j].priority + }) + + fmt.Println(jobs) // [{deploy 10} {test 20} {backup 30}] +} +``` + +Available functions are `Bubble`, `Cocktail`, `Heapsort`, `Insertion`, `Merge`, +`Selection`, and `Reverse`. For ordinary application sorting, compare these +algorithms with the Go standard library's `slices.SortFunc` or `sort.Slice`. + +### Order a dependency graph + +The DFS implementation supports generic comparable keys. Add vertices before +adding edges; an edge `from -> to` means that `from` must come first. + +```go +package main + +import ( + "fmt" + "log" + + "go.osspkg.com/algorithms/graph/dfs" +) + +func main() { + g := dfs.NewGraph[string]() + for _, node := range []string{"clean", "compile", "test"} { + if err := g.AddNode(node); err != nil { + log.Fatal(err) + } + } + if err := g.AddEdge("clean", "compile"); err != nil { + log.Fatal(err) + } + if err := g.AddEdge("compile", "test"); err != nil { + log.Fatal(err) + } + + order, err := g.TopologicalSort() + if err != nil { + log.Fatal(err) + } + fmt.Println(order) +} +``` + +`graph/kahn` is an alternative for string-keyed graphs. It registers vertices +automatically with `Add` and supports `BreakPoint` when only one target and its +transitive dependencies should be ordered. + +### Encode values + +```go +package main + +import ( + "fmt" + + "go.osspkg.com/algorithms/encoding/base62" +) + +func main() { + codec := base62.New("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz") + encoded := codec.Encode(123456) + decoded := codec.Decode(encoded) + + fmt.Println(encoded, decoded) +} +``` + +`base62.New` requires an alphabet of exactly 62 unique bytes. `Encode(0)` and +`Decode("")` both produce the zero value. Invalid input to `Decode` also +produces `0`, so validate input or use a round-trip check when zero must be +distinguished from invalid data. + +For one-time passwords, use `encoding/otp`: + +```go +package main + +import ( + "fmt" + "log" + + "go.osspkg.com/algorithms/encoding/otp" +) + +func main() { + generator, err := otp.New(otp.OptHashSHA256(), otp.OptCode8Digits()) + if err != nil { + log.Fatal(err) + } + + secret, err := generator.NewSecret(20) + if err != nil { + log.Fatal(err) + } + code, err := generator.GenerateTOTP(secret, 0) + if err != nil { + log.Fatal(err) + } + fmt.Println(code) +} +``` + +The default OTP configuration is SHA-1, a 30-second TOTP period, and 6-digit +codes. Treat secrets and `otpauth` URLs as sensitive credentials. + +`encoding/token` provides compact `T64` identifiers: + +```go +package main + +import ( + "fmt" + + "go.osspkg.com/algorithms/encoding/token" +) + +func main() { + id := token.NewRandom() + wire := id.String() + parsed, ok := token.Parse(wire) + if !ok { + panic("invalid token") + } + fmt.Println(parsed == id) +} +``` + +`T64` also exposes marshal methods for text, binary, and JSON-oriented +serialization, plus `database/sql` scanner and valuer integration. Its current +`MarshalJSON` method returns the text representation without JSON quotes; wrap +the value as a string when standard JSON encoding is required. + +### Use data structures + +```go +package main + +import ( + "fmt" + + "go.osspkg.com/algorithms/structs/bitmap" + "go.osspkg.com/algorithms/trees/btree" +) + +func main() { + bm := bitmap.New() + bm.Set(42) + fmt.Println(bm.Has(42)) // true + + tree := btree.New[int, string](2) + tree.Insert(10, "ten") + value, ok := tree.Find(10) + if ok { + fmt.Println(value) // ten + } +} +``` + +`structs/bloom` is useful when a fast membership check can tolerate false +positives. It never guarantees that a reported item is present, so keep a +source of truth behind the filter: + +```go +package main + +import ( + "log" + + "go.osspkg.com/algorithms/structs/bloom" +) + +func main() { + filter, err := bloom.New(bloom.Quantity(100_000, 0.01)) + if err != nil { + log.Fatal(err) + } + filter.Add("user:42") + possiblyPresent := filter.Contain("user:42") + log.Println(possiblyPresent) +} +``` + +`structs/bitmap` and `trees/btree` use synchronization by default. Disable +bitmap locking only when access is strictly single-threaded or synchronized by +the caller. + +## Testing + +Run the complete test suite with: + +```bash +go test ./... ``` +## Contributing + +See [CONTRIBUTING.md](CONTRIBUTING.md). Please open an issue for larger +changes and include tests, documentation, and an example when appropriate. + ## License -BSD-3-Clause License. See the LICENSE file for details +Algorithms is released under the [BSD 3-Clause License](LICENSE). From 58e250188ad7dffe104c8a16dd02c808ff6d8732 Mon Sep 17 00:00:00 2001 From: Mikhail Knyazhev Date: Wed, 25 Nov 2026 03:41:00 +0300 Subject: [PATCH 4/6] change --- .github/workflows/ci.yml | 2 +- .golangci.yml | 2 +- go.mod | 4 +-- go.sum | 2 ++ trees/btree/btree.go | 64 ++++++++++++++++------------------------ 5 files changed, 31 insertions(+), 43 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9c6b96c..7270150 100755 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -12,7 +12,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - go: [ '1.24.0' ] + go: [ '1.26' ] steps: - uses: actions/checkout@v3 diff --git a/.golangci.yml b/.golangci.yml index 60f1183..f2b16a7 100755 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,7 +1,7 @@ version: "2" run: - go: "1.24" + go: "1.26" timeout: 5m tests: false issues-exit-code: 1 diff --git a/go.mod b/go.mod index c37162f..1c18248 100644 --- a/go.mod +++ b/go.mod @@ -1,8 +1,8 @@ module go.osspkg.com/algorithms -go 1.24.0 +go 1.26 require ( github.com/cespare/xxhash/v2 v2.3.0 - go.osspkg.com/casecheck v0.3.1 + go.osspkg.com/casecheck v0.3.2 ) diff --git a/go.sum b/go.sum index 9f2f726..99ca1e6 100644 --- a/go.sum +++ b/go.sum @@ -2,3 +2,5 @@ github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UF github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= go.osspkg.com/casecheck v0.3.1 h1:mxg1WaWy/tv7J05jvf5Idy3ydDYbac3gOOV9NPdjxvU= go.osspkg.com/casecheck v0.3.1/go.mod h1:TRFXDMFJEOtnlp3ET2Hix3osbxwPWhvaiT/HfD3+gBA= +go.osspkg.com/casecheck v0.3.2 h1:KDdtEsEnGcDKjtg8FKL0hjnVZ7kusmXBD/VS/5IKSjE= +go.osspkg.com/casecheck v0.3.2/go.mod h1:nf1vimi3VPl1o0hV+bKZsy3+1Qi8wNRRWiNGqivFV1A= diff --git a/trees/btree/btree.go b/trees/btree/btree.go index c3876c5..02f808d 100644 --- a/trees/btree/btree.go +++ b/trees/btree/btree.go @@ -19,12 +19,15 @@ type node[K cmp.Ordered, V any] struct { } func newNode[K cmp.Ordered, V any](size int, isLeaf bool) *node[K, V] { - return &node[K, V]{ - isLeaf: isLeaf, - keys: make([]K, size), - values: make([]V, size), - children: make([]*node[K, V], size+1), + x := &node[K, V]{ + isLeaf: isLeaf, + keys: make([]K, size), + values: make([]V, size), } + if !isLeaf { + x.children = make([]*node[K, V], size+1) + } + return x } type BTree[K cmp.Ordered, V any] struct { @@ -80,11 +83,6 @@ func (t *BTree[K, V]) Insert(key K, val V) { t.mu.Lock() defer t.mu.Unlock() - if v := t.search(t.root, key); v != nil { - *v = val - return - } - root := t.root if root.numKeys == t.maxKeys { newRoot := newNode[K, V](t.maxKeys, false) @@ -97,23 +95,6 @@ func (t *BTree[K, V]) Insert(key K, val V) { } } -func (t *BTree[K, V]) search(x *node[K, V], key K) *V { - for x != nil { - i := 0 - for i < x.numKeys && key > x.keys[i] { - i++ - } - if i < x.numKeys && key == x.keys[i] { - return &x.values[i] - } - if x.isLeaf { - break - } - x = x.children[i] - } - return nil -} - func (t *BTree[K, V]) splitChild(x *node[K, V], i int, y *node[K, V]) { z := newNode[K, V](t.maxKeys, y.isLeaf) z.numKeys = t.minKeys @@ -147,25 +128,30 @@ func (t *BTree[K, V]) splitChild(x *node[K, V], i int, y *node[K, V]) { } func (t *BTree[K, V]) insertNonFull(x *node[K, V], key K, val V) { - i := x.numKeys - 1 + i := x.numKeys + for i > 0 && key < x.keys[i-1] { + i-- + } + if i > 0 && key == x.keys[i-1] { + x.values[i-1] = val + return + } if x.isLeaf { - for i >= 0 && key < x.keys[i] { - x.keys[i+1] = x.keys[i] - x.values[i+1] = x.values[i] - i-- + for j := x.numKeys; j > i; j-- { + x.keys[j] = x.keys[j-1] + x.values[j] = x.values[j-1] } - x.keys[i+1] = key - x.values[i+1] = val + x.keys[i] = key + x.values[i] = val x.numKeys++ } else { - for i >= 0 && key < x.keys[i] { - i-- - } - i++ - if x.children[i].numKeys == t.maxKeys { t.splitChild(x, i, x.children[i]) + if key == x.keys[i] { + x.values[i] = val + return + } if key > x.keys[i] { i++ } From 878e05524433aaa5a1ae2412bb11dd33f57ace91 Mon Sep 17 00:00:00 2001 From: Mikhail Knyazhev Date: Wed, 25 Nov 2026 04:10:32 +0300 Subject: [PATCH 5/6] change --- trees/btree/btree.go | 173 ++++++++++++++++++++++---------------- trees/btree/btree_test.go | 48 +++++------ 2 files changed, 126 insertions(+), 95 deletions(-) diff --git a/trees/btree/btree.go b/trees/btree/btree.go index 02f808d..f5a6a5f 100644 --- a/trees/btree/btree.go +++ b/trees/btree/btree.go @@ -30,6 +30,9 @@ func newNode[K cmp.Ordered, V any](size int, isLeaf bool) *node[K, V] { return x } +// Linear scans are cheaper for narrow nodes; binary search is used above this width. +const linearSearchThreshold = 255 + type BTree[K cmp.Ordered, V any] struct { degree int maxKeys int @@ -55,23 +58,53 @@ func New[K cmp.Ordered, V any](degree int) *BTree[K, V] { func (t *BTree[K, V]) Find(key K) (V, bool) { t.mu.RLock() - curr := t.root - for curr != nil { - i := 0 - for i < curr.numKeys && key > curr.keys[i] { - i++ - } - - if i < curr.numKeys && key == curr.keys[i] { - value := curr.values[i] - t.mu.RUnlock() - return value, true + if t.maxKeys <= linearSearchThreshold { + curr := t.root + for curr != nil { + i := 0 + for i < curr.numKeys && key > curr.keys[i] { + i++ + } + if i < curr.numKeys && key == curr.keys[i] { + value := curr.values[i] + t.mu.RUnlock() + return value, true + } + if curr.isLeaf { + break + } + curr = curr.children[i] } - - if curr.isLeaf { - break + } else { + curr := t.root + for curr != nil { + i := 0 + if curr.numKeys > linearSearchThreshold { + lo, hi := 0, curr.numKeys + for lo < hi { + mid := lo + (hi-lo)/2 + if key > curr.keys[mid] { + lo = mid + 1 + } else { + hi = mid + } + } + i = lo + } else { + for i < curr.numKeys && key > curr.keys[i] { + i++ + } + } + if i < curr.numKeys && key == curr.keys[i] { + value := curr.values[i] + t.mu.RUnlock() + return value, true + } + if curr.isLeaf { + break + } + curr = curr.children[i] } - curr = curr.children[i] } var zero V @@ -99,28 +132,20 @@ func (t *BTree[K, V]) splitChild(x *node[K, V], i int, y *node[K, V]) { z := newNode[K, V](t.maxKeys, y.isLeaf) z.numKeys = t.minKeys - for j := 0; j < t.minKeys; j++ { - z.keys[j] = y.keys[j+t.degree] - z.values[j] = y.values[j+t.degree] - } + copy(z.keys[:t.minKeys], y.keys[t.degree:t.degree+t.minKeys]) + copy(z.values[:t.minKeys], y.values[t.degree:t.degree+t.minKeys]) if !y.isLeaf { - for j := 0; j < t.degree; j++ { - z.children[j] = y.children[j+t.degree] - } + copy(z.children[:t.degree], y.children[t.degree:t.degree*2]) } y.numKeys = t.minKeys - for j := x.numKeys; j >= i+1; j-- { - x.children[j+1] = x.children[j] - } + copy(x.children[i+2:x.numKeys+2], x.children[i+1:x.numKeys+1]) x.children[i+1] = z - for j := x.numKeys - 1; j >= i; j-- { - x.keys[j+1] = x.keys[j] - x.values[j+1] = x.values[j] - } + copy(x.keys[i+1:x.numKeys+1], x.keys[i:x.numKeys]) + copy(x.values[i+1:x.numKeys+1], x.values[i:x.numKeys]) x.keys[i] = y.keys[t.minKeys] x.values[i] = y.values[t.minKeys] @@ -129,19 +154,31 @@ func (t *BTree[K, V]) splitChild(x *node[K, V], i int, y *node[K, V]) { func (t *BTree[K, V]) insertNonFull(x *node[K, V], key K, val V) { i := x.numKeys - for i > 0 && key < x.keys[i-1] { - i-- + if x.numKeys <= linearSearchThreshold { + for i > 0 && key < x.keys[i-1] { + i-- + } + } else { + lo, hi := 0, x.numKeys + for lo < hi { + mid := lo + (hi-lo)/2 + if key < x.keys[mid] { + hi = mid + } else { + lo = mid + 1 + } + } + i = lo } - if i > 0 && key == x.keys[i-1] { + found := i > 0 && key == x.keys[i-1] + if found { x.values[i-1] = val return } if x.isLeaf { - for j := x.numKeys; j > i; j-- { - x.keys[j] = x.keys[j-1] - x.values[j] = x.values[j-1] - } + copy(x.keys[i+1:x.numKeys+1], x.keys[i:x.numKeys]) + copy(x.values[i+1:x.numKeys+1], x.values[i:x.numKeys]) x.keys[i] = key x.values[i] = val x.numKeys++ @@ -178,16 +215,26 @@ func (t *BTree[K, V]) Delete(key K) { func (t *BTree[K, V]) deleteFromNode(x *node[K, V], key K) { idx := 0 - for idx < x.numKeys && key > x.keys[idx] { - idx++ + if x.numKeys <= linearSearchThreshold { + for idx < x.numKeys && key > x.keys[idx] { + idx++ + } + } else { + lo, hi := 0, x.numKeys + for lo < hi { + mid := lo + (hi-lo)/2 + if key > x.keys[mid] { + lo = mid + 1 + } else { + hi = mid + } + } + idx = lo } - if idx < x.numKeys && key == x.keys[idx] { if x.isLeaf { - for i := idx; i < x.numKeys-1; i++ { - x.keys[i] = x.keys[i+1] - x.values[i] = x.values[i+1] - } + copy(x.keys[idx:x.numKeys-1], x.keys[idx+1:x.numKeys]) + copy(x.values[idx:x.numKeys-1], x.values[idx+1:x.numKeys]) x.numKeys-- var zeroK K var zeroV V @@ -270,15 +317,11 @@ func (t *BTree[K, V]) borrowFromPrev(x *node[K, V], idx int) { child := x.children[idx] sibling := x.children[idx-1] - for i := child.numKeys - 1; i >= 0; i-- { - child.keys[i+1] = child.keys[i] - child.values[i+1] = child.values[i] - } + copy(child.keys[1:child.numKeys+1], child.keys[:child.numKeys]) + copy(child.values[1:child.numKeys+1], child.values[:child.numKeys]) if !child.isLeaf { - for i := child.numKeys; i >= 0; i-- { - child.children[i+1] = child.children[i] - } + copy(child.children[1:child.numKeys+2], child.children[:child.numKeys+1]) child.children[0] = sibling.children[sibling.numKeys] } @@ -311,15 +354,11 @@ func (t *BTree[K, V]) borrowFromNext(x *node[K, V], idx int) { x.keys[idx] = sibling.keys[0] x.values[idx] = sibling.values[0] - for i := 1; i < sibling.numKeys; i++ { - sibling.keys[i-1] = sibling.keys[i] - sibling.values[i-1] = sibling.values[i] - } + copy(sibling.keys[:sibling.numKeys-1], sibling.keys[1:sibling.numKeys]) + copy(sibling.values[:sibling.numKeys-1], sibling.values[1:sibling.numKeys]) if !sibling.isLeaf { - for i := 1; i <= sibling.numKeys; i++ { - sibling.children[i-1] = sibling.children[i] - } + copy(sibling.children[:sibling.numKeys], sibling.children[1:sibling.numKeys+1]) } child.numKeys++ @@ -339,24 +378,16 @@ func (t *BTree[K, V]) merge(x *node[K, V], idx int) { child.keys[t.minKeys] = x.keys[idx] child.values[t.minKeys] = x.values[idx] - for i := 0; i < sibling.numKeys; i++ { - child.keys[i+t.degree] = sibling.keys[i] - child.values[i+t.degree] = sibling.values[i] - } + copy(child.keys[t.degree:t.degree+sibling.numKeys], sibling.keys[:sibling.numKeys]) + copy(child.values[t.degree:t.degree+sibling.numKeys], sibling.values[:sibling.numKeys]) if !child.isLeaf { - for i := 0; i <= sibling.numKeys; i++ { - child.children[i+t.degree] = sibling.children[i] - } + copy(child.children[t.degree:t.degree+sibling.numKeys+1], sibling.children[:sibling.numKeys+1]) } - for i := idx + 1; i < x.numKeys; i++ { - x.keys[i-1] = x.keys[i] - x.values[i-1] = x.values[i] - } - for i := idx + 2; i <= x.numKeys; i++ { - x.children[i-1] = x.children[i] - } + copy(x.keys[idx:x.numKeys-1], x.keys[idx+1:x.numKeys]) + copy(x.values[idx:x.numKeys-1], x.values[idx+1:x.numKeys]) + copy(x.children[idx+1:x.numKeys], x.children[idx+2:x.numKeys+1]) child.numKeys += sibling.numKeys + 1 x.numKeys-- diff --git a/trees/btree/btree_test.go b/trees/btree/btree_test.go index ece7925..aa6a4e9 100644 --- a/trees/btree/btree_test.go +++ b/trees/btree/btree_test.go @@ -358,23 +358,23 @@ pkg: go.osspkg.com/algorithms/trees/btree cpu: 12th Gen Intel(R) Core(TM) i9-12900KF BenchmarkBTree_Insert BenchmarkBTree_Insert/Sequential -BenchmarkBTree_Insert/Sequential-4 896 1382861 ns/op 484544 B/op 904 allocs/op +BenchmarkBTree_Insert/Sequential-4 1184 1088393 ns/op 373029 B/op 686 allocs/op BenchmarkBTree_Insert/Parallel -BenchmarkBTree_Insert/Parallel-4 10466346 129.5 ns/op 0 B/op 0 allocs/op +BenchmarkBTree_Insert/Parallel-4 7756344 220.0 ns/op 0 B/op 0 allocs/op BenchmarkBTree_Find BenchmarkBTree_Find/Hit -BenchmarkBTree_Find/Hit-4 21723561 54.69 ns/op 0 B/op 0 allocs/op +BenchmarkBTree_Find/Hit-4 22326198 52.01 ns/op 0 B/op 0 allocs/op BenchmarkBTree_Find/Miss -BenchmarkBTree_Find/Miss-4 100000000 11.33 ns/op 0 B/op 0 allocs/op +BenchmarkBTree_Find/Miss-4 100000000 10.28 ns/op 0 B/op 0 allocs/op BenchmarkBTree_Find/Parallel -BenchmarkBTree_Find/Parallel-4 33573949 36.75 ns/op 0 B/op 0 allocs/op +BenchmarkBTree_Find/Parallel-4 33712418 35.67 ns/op 0 B/op 0 allocs/op BenchmarkBTree_Delete BenchmarkBTree_Delete/Sequential -BenchmarkBTree_Delete/Sequential-4 1158 1100783 ns/op 0 B/op 0 allocs/op +BenchmarkBTree_Delete/Sequential-4 1351 893818 ns/op 0 B/op 0 allocs/op BenchmarkBTree_Delete/Parallel -BenchmarkBTree_Delete/Parallel-4 39781627 33.21 ns/op 17 B/op 0 allocs/op +BenchmarkBTree_Delete/Parallel-4 46522065 24.40 ns/op 13 B/op 0 allocs/op BenchmarkBTree_MixedLoad_Parallel -BenchmarkBTree_MixedLoad_Parallel-4 5782959 236.1 ns/op 0 B/op 0 allocs/op +BenchmarkBTree_MixedLoad_Parallel-4 5302496 253.2 ns/op 0 B/op 0 allocs/op */ /* @@ -385,23 +385,23 @@ pkg: go.osspkg.com/algorithms/trees/btree cpu: 12th Gen Intel(R) Core(TM) i9-12900KF BenchmarkBTree_Insert BenchmarkBTree_Insert/Sequential -BenchmarkBTree_Insert/Sequential-4 392 2917484 ns/op 1147816 B/op 22956 allocs/op +BenchmarkBTree_Insert/Sequential-4 478 2189770 ns/op 1020594 B/op 19190 allocs/op BenchmarkBTree_Insert/Parallel -BenchmarkBTree_Insert/Parallel-4 3160122 404.0 ns/op 0 B/op 0 allocs/op +BenchmarkBTree_Insert/Parallel-4 3800583 647.6 ns/op 0 B/op 0 allocs/op BenchmarkBTree_Find BenchmarkBTree_Find/Hit -BenchmarkBTree_Find/Hit-4 10859036 106.3 ns/op 0 B/op 0 allocs/op +BenchmarkBTree_Find/Hit-4 11525403 100.7 ns/op 0 B/op 0 allocs/op BenchmarkBTree_Find/Miss -BenchmarkBTree_Find/Miss-4 59257408 19.98 ns/op 0 B/op 0 allocs/op +BenchmarkBTree_Find/Miss-4 70991496 15.96 ns/op 0 B/op 0 allocs/op BenchmarkBTree_Find/Parallel -BenchmarkBTree_Find/Parallel-4 27232424 44.92 ns/op 0 B/op 0 allocs/op +BenchmarkBTree_Find/Parallel-4 25875890 43.28 ns/op 0 B/op 0 allocs/op BenchmarkBTree_Delete BenchmarkBTree_Delete/Sequential -BenchmarkBTree_Delete/Sequential-4 802 1506062 ns/op 0 B/op 0 allocs/op +BenchmarkBTree_Delete/Sequential-4 655 1842586 ns/op 0 B/op 0 allocs/op BenchmarkBTree_Delete/Parallel -BenchmarkBTree_Delete/Parallel-4 15402082 73.63 ns/op 40 B/op 0 allocs/op +BenchmarkBTree_Delete/Parallel-4 17943026 64.75 ns/op 32 B/op 0 allocs/op BenchmarkBTree_MixedLoad_Parallel -BenchmarkBTree_MixedLoad_Parallel-4 4454574 258.9 ns/op 0 B/op 0 allocs/op +BenchmarkBTree_MixedLoad_Parallel-4 5571058 557.3 ns/op 11 B/op 0 allocs/op */ /* @@ -412,23 +412,23 @@ pkg: go.osspkg.com/algorithms/trees/btree cpu: 12th Gen Intel(R) Core(TM) i9-12900KF BenchmarkBTree_Insert BenchmarkBTree_Insert/Sequential -BenchmarkBTree_Insert/Sequential-4 592 1755761 ns/op 505440 B/op 468 allocs/op +BenchmarkBTree_Insert/Sequential-4 1015 1142945 ns/op 381318 B/op 361 allocs/op BenchmarkBTree_Insert/Parallel -BenchmarkBTree_Insert/Parallel-4 4480512 262.2 ns/op 0 B/op 0 allocs/op +BenchmarkBTree_Insert/Parallel-4 4092752 295.0 ns/op 0 B/op 0 allocs/op BenchmarkBTree_Find BenchmarkBTree_Find/Hit -BenchmarkBTree_Find/Hit-4 18538779 62.38 ns/op 0 B/op 0 allocs/op +BenchmarkBTree_Find/Hit-4 16128752 66.88 ns/op 0 B/op 0 allocs/op BenchmarkBTree_Find/Miss -BenchmarkBTree_Find/Miss-4 100000000 10.69 ns/op 0 B/op 0 allocs/op +BenchmarkBTree_Find/Miss-4 100000000 10.31 ns/op 0 B/op 0 allocs/op BenchmarkBTree_Find/Parallel -BenchmarkBTree_Find/Parallel-4 29789313 36.98 ns/op 0 B/op 0 allocs/op +BenchmarkBTree_Find/Parallel-4 35377850 33.33 ns/op 0 B/op 0 allocs/op BenchmarkBTree_Delete BenchmarkBTree_Delete/Sequential -BenchmarkBTree_Delete/Sequential-4 874 1433584 ns/op 0 B/op 0 allocs/op +BenchmarkBTree_Delete/Sequential-4 1312 955427 ns/op 0 B/op 0 allocs/op BenchmarkBTree_Delete/Parallel -BenchmarkBTree_Delete/Parallel-4 30289316 41.55 ns/op 19 B/op 0 allocs/op +BenchmarkBTree_Delete/Parallel-4 40201903 26.73 ns/op 14 B/op 0 allocs/op BenchmarkBTree_MixedLoad_Parallel -BenchmarkBTree_MixedLoad_Parallel-4 6820371 396.0 ns/op 0 B/op 0 allocs/op +BenchmarkBTree_MixedLoad_Parallel-4 7727888 362.3 ns/op 0 B/op 0 allocs/op */ const ( From b1c62732f163e00fc176719e70264aa0f058e458 Mon Sep 17 00:00:00 2001 From: Mikhail Knyazhev Date: Wed, 25 Nov 2026 04:36:12 +0300 Subject: [PATCH 6/6] change --- README.md | 38 +++++++------ comp/README.md | 41 ++++++++++++++ encoding/base62/README.md | 35 ++++++++++++ encoding/otp/README.md | 55 ++++++++++++++++++ encoding/token/README.md | 56 +++++++++++++++++++ graph/dfs/README.md | 51 +++++++++++++++++ graph/kahn/README.md | 48 ++++++++++++++++ skills/osspkg-algorithms/SKILL.md | 5 +- .../references/comparisons.md | 8 ++- .../osspkg-algorithms/references/encoding.md | 8 ++- .../references/sorting-and-graphs.md | 10 ++++ .../references/structures.md | 25 ++++++--- sorts/README.md | 47 ++++++++++++++++ structs/bitmap/README.md | 42 ++++++++++++++ structs/bloom/README.md | 50 +++++++++++++++++ trees/btree/README.md | 43 ++++++++++++++ 16 files changed, 529 insertions(+), 33 deletions(-) create mode 100644 comp/README.md create mode 100644 encoding/base62/README.md create mode 100644 encoding/otp/README.md create mode 100644 encoding/token/README.md create mode 100644 graph/dfs/README.md create mode 100644 graph/kahn/README.md create mode 100644 sorts/README.md create mode 100644 structs/bitmap/README.md create mode 100644 structs/bloom/README.md create mode 100644 trees/btree/README.md diff --git a/README.md b/README.md index d76f1ba..91c1b9c 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # Algorithms [![Go Reference](https://pkg.go.dev/badge/go.osspkg.com/algorithms.svg)](https://pkg.go.dev/go.osspkg.com/algorithms) -[![Go 1.24+](https://img.shields.io/badge/go-1.24%2B-00ADD8?logo=go&logoColor=white)](https://go.dev/) +[![Go 1.26+](https://img.shields.io/badge/go-1.26%2B-00ADD8?logo=go&logoColor=white)](https://go.dev/) [![License](https://img.shields.io/badge/license-BSD--3--Clause-blue.svg)](LICENSE) A collection of generic algorithms, encoders, graphs, filters, and data @@ -12,7 +12,7 @@ package you need; the module root does not expose a general-purpose API. ## Requirements -- Go 1.24 or newer +- Go 1.26 or newer ## Installation @@ -22,18 +22,18 @@ go get go.osspkg.com/algorithms@latest ## Packages -| Package | Provides | -| --- | --- | -| [`comp`](https://pkg.go.dev/go.osspkg.com/algorithms/comp) | Hamming, Levenshtein, Damerau-Levenshtein, LCS, and Jaro-Winkler sequence comparison | -| [`sorts`](https://pkg.go.dev/go.osspkg.com/algorithms/sorts) | Bubble, cocktail, heap, insertion, merge, and selection sort; slice reversal | -| [`graph/dfs`](https://pkg.go.dev/go.osspkg.com/algorithms/graph/dfs) | Generic depth-first topological sorting with cycle detection | -| [`graph/kahn`](https://pkg.go.dev/go.osspkg.com/algorithms/graph/kahn) | String-keyed Kahn topological sorting with dependency subgraphs | -| [`encoding/base62`](https://pkg.go.dev/go.osspkg.com/algorithms/encoding/base62) | Configurable Base62 encoding for `uint64` values | -| [`encoding/otp`](https://pkg.go.dev/go.osspkg.com/algorithms/encoding/otp) | TOTP/HOTP generation and `otpauth` URLs | -| [`encoding/token`](https://pkg.go.dev/go.osspkg.com/algorithms/encoding/token) | Compact `T64` identifiers with text, binary, and SQL integration | -| [`structs/bitmap`](https://pkg.go.dev/go.osspkg.com/algorithms/structs/bitmap) | Concurrent growable bitmap | -| [`structs/bloom`](https://pkg.go.dev/go.osspkg.com/algorithms/structs/bloom) | Space-efficient Bloom filter with persistence support | -| [`trees/btree`](https://pkg.go.dev/go.osspkg.com/algorithms/trees/btree) | Concurrent generic B-tree | +| Package | Provides | Guide | +| --- | --- | --- | +| [`comp`](https://pkg.go.dev/go.osspkg.com/algorithms/comp) | Hamming, Levenshtein, Damerau-Levenshtein, LCS, and Jaro-style sequence comparison | [README](comp/README.md) | +| [`sorts`](https://pkg.go.dev/go.osspkg.com/algorithms/sorts) | Bubble, cocktail, heap, insertion, merge, and selection sort; slice reversal | [README](sorts/README.md) | +| [`graph/dfs`](https://pkg.go.dev/go.osspkg.com/algorithms/graph/dfs) | Generic depth-first topological sorting with cycle detection | [README](graph/dfs/README.md) | +| [`graph/kahn`](https://pkg.go.dev/go.osspkg.com/algorithms/graph/kahn) | String-keyed Kahn topological sorting with dependency subgraphs | [README](graph/kahn/README.md) | +| [`encoding/base62`](https://pkg.go.dev/go.osspkg.com/algorithms/encoding/base62) | Configurable Base62 encoding for `uint64` values | [README](encoding/base62/README.md) | +| [`encoding/otp`](https://pkg.go.dev/go.osspkg.com/algorithms/encoding/otp) | TOTP/HOTP generation and `otpauth` URLs | [README](encoding/otp/README.md) | +| [`encoding/token`](https://pkg.go.dev/go.osspkg.com/algorithms/encoding/token) | Compact `T64` identifiers with text, binary, and SQL integration | [README](encoding/token/README.md) | +| [`structs/bitmap`](https://pkg.go.dev/go.osspkg.com/algorithms/structs/bitmap) | Concurrent growable bitmap | [README](structs/bitmap/README.md) | +| [`structs/bloom`](https://pkg.go.dev/go.osspkg.com/algorithms/structs/bloom) | Space-efficient Bloom filter with persistence support | [README](structs/bloom/README.md) | +| [`trees/btree`](https://pkg.go.dev/go.osspkg.com/algorithms/trees/btree) | Concurrent generic B-tree | [README](trees/btree/README.md) | ## Usage @@ -65,7 +65,8 @@ Choose the comparer according to the type of difference you need to model: - `NewLevenshtein` accounts for insertions, deletions, and substitutions. - `NewDamerauLevenshtein` also accounts for adjacent transpositions. - `NewLCS` measures the longest common subsequence. -- `NewJaroWinkler` is suited to short values and near matches. +- `NewJaroWinkler` currently uses Jaro-style matching-window similarity and + does not apply a separate Winkler prefix boost. ### Sort a slice @@ -281,9 +282,10 @@ func main() { } ``` -`structs/bitmap` and `trees/btree` use synchronization by default. Disable -bitmap locking only when access is strictly single-threaded or synchronized by -the caller. +`structs/bitmap` and `trees/btree` use synchronization by default. If a bitmap +`Set` may grow its storage, serialize it with concurrent `Has` or `Del` calls. +Disable bitmap locking only when access is strictly single-threaded or +synchronized by the caller. ## Testing diff --git a/comp/README.md b/comp/README.md new file mode 100644 index 0000000..8ac6386 --- /dev/null +++ b/comp/README.md @@ -0,0 +1,41 @@ +# Package `comp` + +## Abstract + +`comp` compares sequences of comparable values. Its constructors return a +`Comparer[T]`, whose public interface exposes a normalized `Similarity` score. +Use `[]rune` for Unicode text, `[]byte` for byte sequences, or slices of other +comparable values for tokens and symbols. + +## Algorithms + +| Constructor | Measures | +| --- | --- | +| `NewHamming[T]` | Positional differences; input lengths must match for a non-zero similarity. | +| `NewLevenshtein[T]` | Insertions, deletions, and substitutions. | +| `NewDamerauLevenshtein[T]` | Levenshtein edits plus adjacent transpositions using the restricted optimal-string-alignment variant. | +| `NewLCS[T]` | Longest common subsequence, not longest common substring. | +| `NewJaroWinkler[T]` | Jaro-style matching-window similarity. The current implementation does not apply a separate Winkler prefix boost. | + +`Similarity` returns a score from `0` to `100`, rounded to two decimal +places. Two empty sequences score `100`. Hamming comparison of unequal-length +sequences scores `0`. + +```go +package main + +import ( + "fmt" + + "go.osspkg.com/algorithms/comp" +) + +func main() { + comparer := comp.NewLevenshtein[rune]() + score := comparer.Similarity([]rune("kitten"), []rune("sitting")) + fmt.Printf("%.2f\n", score) +} +``` + +The constructors expose `Similarity` through `Comparer[T]`; distance methods +are not part of that interface. diff --git a/encoding/base62/README.md b/encoding/base62/README.md new file mode 100644 index 0000000..dbb1c23 --- /dev/null +++ b/encoding/base62/README.md @@ -0,0 +1,35 @@ +# Package `base62` + +## Abstract + +`base62` encodes and decodes `uint64` values using a caller-supplied alphabet +of 62 unique bytes. The alphabet defines the digit order and is kept by the +`Base62` value for subsequent operations. + +## API and behavior + +`New(alphabet)` panics unless the alphabet is exactly 62 bytes long and every +byte is unique. Callers MUST validate externally supplied alphabets before +constructing a codec. `Encode(0)` returns the empty string. `Decode` returns +zero for empty input, invalid characters, or arithmetic overflow; its return +value does not distinguish those cases from a valid encoding of zero. + +```go +package main + +import ( + "fmt" + + "go.osspkg.com/algorithms/encoding/base62" +) + +func main() { + codec := base62.New("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz") + text := codec.Encode(123456) + value := codec.Decode(text) + fmt.Println(text, value) +} +``` + +Base62 is a representation, not encryption or authentication. Callers SHOULD +not use an encoded value to hide or protect sensitive data. diff --git a/encoding/otp/README.md b/encoding/otp/README.md new file mode 100644 index 0000000..e05191f --- /dev/null +++ b/encoding/otp/README.md @@ -0,0 +1,55 @@ +# Package `otp` + +## Abstract + +`otp` generates HOTP and TOTP values using HMAC and creates `otpauth`-style +provisioning URIs. HOTP follows the counter-based construction in [RFC 4226]; +TOTP uses the time-based moving factor described in [RFC 6238]. This package +generates values; it does not verify them, enforce a replay policy, or choose +a verifier's accepted clock window. + +## Configuration + +`New` defaults to HMAC-SHA1, a 30-second TOTP period, and six digits. Options +can select SHA-1, SHA-256, or SHA-512; six or eight digits; and a period. The +period is clamped to the inclusive range 30–120 seconds. + +`NewSecret(size)` generates `size` random bytes and returns unpadded Base32. +Values below one use a 10-byte default. `GenerateHOTP` takes an explicit +counter. `GenerateTOTP` uses the current Unix time; its `delta` argument shifts +the time-step counter, not seconds. + +`UrlTOTP` and `UrlHOTP` create provisioning URIs using the `otpauth` scheme. +`UrlHOTP` includes both the counter and the configured period in its query. + +```go +package main + +import ( + "fmt" + "log" + + "go.osspkg.com/algorithms/encoding/otp" +) + +func main() { + generator, err := otp.New(otp.OptHashSHA256(), otp.OptCode8Digits()) + if err != nil { + log.Fatal(err) + } + secret, err := generator.NewSecret(20) + if err != nil { + log.Fatal(err) + } + code, err := generator.GenerateTOTP(secret, 0) + if err != nil { + log.Fatal(err) + } + fmt.Println(code) +} +``` + +The URI methods encode account and issuer values as URL components. Provisioning +URIs contain the secret and MUST be treated as credentials. Applications +SHOULD protect secrets at rest and in transit, use synchronized clocks, and +avoid logging codes, secrets, or generated URIs. diff --git a/encoding/token/README.md b/encoding/token/README.md new file mode 100644 index 0000000..57f410d --- /dev/null +++ b/encoding/token/README.md @@ -0,0 +1,56 @@ +# Package `token` + +## Abstract + +`token` represents an eight-byte value as `T64`. It supports construction from +time, integers, bytes, strings, or cryptographic randomness; text and binary +marshalling; and `database/sql` scanning and value conversion. + +## Representation and API + +`T64.String` uses the package's process-wide encoding table and emits 18 bytes +with hyphens at positions 6 and 11. The default table is +`ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789`. `SetTable` replaces it for all +`T64` values; a table MUST contain 16–254 unique bytes, have even length, and +MUST NOT contain byte `0xff`. + +- `NewByUint` stores a `uint64` in big-endian order; `Uint64` reverses it. +- `NewByTime` and `NewFormTime` store Unix nanoseconds. +- `NewByBytes` and `NewByString` store the first eight bytes of an MD5 digest. +- `NewRandom` reads a random 64-bit value. It returns `Nil` if all read + attempts fail; the API does not return an error. +- `Parse` and `ParseBytes` return a token and a success flag. +- `Scan` accepts `string`, `[]byte`, or `nil`; empty and nil values leave the + receiver unchanged. `Value` returns the textual form as a database string. + +```go +package main + +import ( + "fmt" + + "go.osspkg.com/algorithms/encoding/token" +) + +func main() { + id := token.NewByUint(42) + text := id.String() + parsed, ok := token.Parse(text) + fmt.Println(text, ok, parsed == id) +} +``` + +## Interoperability and security considerations + +`MarshalText` and `MarshalBinary` both emit the textual form. The current +`MarshalJSON` also emits that raw text without JSON quotes, so it is not a +standard JSON value; callers SHOULD encode `T64.String()` as a JSON string. +`UnmarshalJSON` expects the same raw form. + +The encoding table is global: changing it changes the text form used by every +token. `NewByTime` is predictable, and the MD5-based constructors are not +collision-resistant identifiers. Applications MUST NOT use them as secrets or +authentication credentials. For untrusted parser input, callers MUST reject +byte `0xff` before calling `Parse` or `ParseBytes`; the current lookup table +does not safely index that byte. + diff --git a/graph/dfs/README.md b/graph/dfs/README.md new file mode 100644 index 0000000..caaba64 --- /dev/null +++ b/graph/dfs/README.md @@ -0,0 +1,51 @@ +# Package `dfs` + +## Abstract + +`dfs` builds generic directed graphs and returns a depth-first topological +ordering. An edge `from -> to` means `from` MUST precede `to` in the result. + +## API and behavior + +- `NewGraph[K comparable]` creates an empty, synchronized graph. +- `AddNode` registers a vertex. Adding an existing key returns an error that + wraps `ErrNodeKeyExist`. +- `AddEdge` requires both vertices to exist and returns an error wrapping + `ErrNodeNotFound` otherwise. Repeated edges are stored once. +- `TopologicalSort` returns an ordering for a DAG or `ErrCycleDetected` when a + cycle is reachable in the graph. + +Callers SHOULD add vertices before edges and SHOULD test errors with +`errors.Is`. The order of unrelated vertices is not guaranteed because map +iteration determines traversal order. + +```go +package main + +import ( + "fmt" + "log" + + "go.osspkg.com/algorithms/graph/dfs" +) + +func main() { + g := dfs.NewGraph[string]() + for _, node := range []string{"compile", "test"} { + if err := g.AddNode(node); err != nil { + log.Fatal(err) + } + } + if err := g.AddEdge("compile", "test"); err != nil { + log.Fatal(err) + } + order, err := g.TopologicalSort() + if err != nil { + log.Fatal(err) + } + fmt.Println(order) +} +``` + +The traversal takes O(V + E) time and uses O(V) auxiliary state. The graph +protects mutations and sorting with an internal read-write mutex. diff --git a/graph/kahn/README.md b/graph/kahn/README.md new file mode 100644 index 0000000..f0f9374 --- /dev/null +++ b/graph/kahn/README.md @@ -0,0 +1,48 @@ +# Package `kahn` + +## Abstract + +`kahn` implements Kahn's topological-sorting algorithm for string-keyed +directed graphs. An edge `from -> to` means that `from` MUST precede `to`. + +## API and behavior + +- `New` creates an empty graph. +- `Add(from, to)` adds both endpoint vertices and records the directed edge. +- `BreakPoint(target)` limits the next build to `target` and its transitive + prerequisites. With no breakpoint, `Build` considers the whole graph. +- `Build` stores an ordering or returns `ErrBuild` if the active subgraph has + a cycle. A non-empty unknown breakpoint returns `ErrBreakPoint`. +- `Result` returns a copy of the most recent successful result. Callers MUST + call `Build` before expecting a populated result. + +The graph is not synchronized; callers MUST serialize concurrent access. With +a breakpoint, edges outside the target's prerequisite subgraph are ignored. +If several valid orders exist, callers SHOULD rely only on the dependency +constraints, not on a particular tie order. + +```go +package main + +import ( + "fmt" + "log" + + "go.osspkg.com/algorithms/graph/kahn" +) + +func main() { + g := kahn.New() + g.Add("compile", "test") + g.Add("test", "package") + g.BreakPoint("package") + if err := g.Build(); err != nil { + log.Fatal(err) + } + fmt.Println(g.Result()) +} +``` + +Building the whole graph takes O(V log V + E) time: initial zero-indegree +vertices are sorted before processing. The active graph and result require +O(V + E) storage. diff --git a/skills/osspkg-algorithms/SKILL.md b/skills/osspkg-algorithms/SKILL.md index ac02624..d004240 100644 --- a/skills/osspkg-algorithms/SKILL.md +++ b/skills/osspkg-algorithms/SKILL.md @@ -33,8 +33,9 @@ Load only the relevant reference: `bool` or return a zero value instead of an `error`. - Sorting functions mutate the provided slice in place, and the comparison callback receives indices into the current slice, not the values themselves. -- Before implementing new behavior, check the library's current source and - tests: these references document API usage, not hidden implementation details. +- Before implementing behavior, check the package README, exported source, and + tests in the current checkout. These references summarize API usage and may + lag the checked-out implementation. For a dependency in another Go module, use `go get go.osspkg.com/algorithms`. In this checkout, verify changes in the consuming package or test and run diff --git a/skills/osspkg-algorithms/references/comparisons.md b/skills/osspkg-algorithms/references/comparisons.md index 64b8f3b..f2351d4 100644 --- a/skills/osspkg-algorithms/references/comparisons.md +++ b/skills/osspkg-algorithms/references/comparisons.md @@ -13,8 +13,8 @@ Public constructors: | `NewHamming[T]()` | equal-length sequences; counts positional mismatches | | `NewLevenshtein[T]()` | insertions, deletions, and substitutions | | `NewDamerauLevenshtein[T]()` | the same, plus adjacent transpositions | -| `NewLCS[T]()` | similarity based on the longest common subsequence | -| `NewJaroWinkler[T]()` | short sequences and near matches | +| `NewLCS[T]()` | similarity based on the longest common subsequence, not substring | +| `NewJaroWinkler[T]()` | Jaro-style matching-window similarity | `T` must satisfy `comparable`. The constructors return `comp.Comparer[T]`, so external code calls `Similarity`: @@ -48,7 +48,9 @@ Selection notes: matter. - `Damerau-Levenshtein` is useful for swapped adjacent characters. - `LCS` better reflects the preserved order of a common subsequence. -- `Jaro-Winkler` is useful for short values; calibrate thresholds on domain data. +- `NewJaroWinkler` currently does not apply a separate Winkler prefix boost; + treat its result as Jaro-style similarity and calibrate thresholds on domain + data. Do not call `Distance` on a constructor result from an external package: implementations have internal distance methods, but their types are unexported diff --git a/skills/osspkg-algorithms/references/encoding.md b/skills/osspkg-algorithms/references/encoding.md index f4ef705..2793d55 100644 --- a/skills/osspkg-algorithms/references/encoding.md +++ b/skills/osspkg-algorithms/references/encoding.md @@ -65,6 +65,7 @@ func main() { spaces, lowercase letters, and unpadded Base32. `delta` in `GenerateTOTP` is an offset measured in periods, not seconds. For HOTP, use `GenerateHOTP(secret, counter)` and `UrlHOTP(secret, account, issuer, counter)`. +`UrlHOTP` includes both the counter and configured period in its query. `OptPeriod` clamps the period to 30–120 seconds, while an invalid secret or counter returns an error. @@ -109,9 +110,14 @@ representation table: it must have an even length from 16 to 254, contain unique bytes, and exclude `0xff`. Configure it once at startup, before tokens are exchanged; the byte value of `T64` itself does not change. +Reject input containing byte `0xff` before calling `Parse` or `ParseBytes`: +these parsers can panic on that byte. `NewByTime` is predictable. +`NewRandom` does not return an error and yields `Nil` if random reads fail. + `T64` provides text/binary and SQL `Scanner`/`Valuer` integration: `Value` returns a string, while `Scan` accepts `nil`, empty values, `string`, and -`[]byte`. For JSON, do not rely solely on the presence of `MarshalJSON`: the +`[]byte`; nil and empty values leave the receiver unchanged. For JSON, do not +rely solely on the presence of `MarshalJSON`: the current implementation delegates to `MarshalText` without adding JSON quotes. For JSON fields, use an explicit string wrapper and check the round-trip with `Parse` until this contract is separately confirmed. diff --git a/skills/osspkg-algorithms/references/sorting-and-graphs.md b/skills/osspkg-algorithms/references/sorting-and-graphs.md index 9eee42c..5729290 100644 --- a/skills/osspkg-algorithms/references/sorting-and-graphs.md +++ b/skills/osspkg-algorithms/references/sorting-and-graphs.md @@ -36,6 +36,16 @@ requirements with `slices.SortFunc`/`sort.Slice`; when stability is required, explicitly use a stable standard-library sort because stability is not a general contract of these functions. +| Function | Time | Extra storage | Stability | +| --- | --- | --- | --- | +| `Bubble` | O(n²), O(n) when already sorted | O(1) | Stable | +| `Cocktail` | O(n²) | O(1) | Stable | +| `Insertion` | O(n²), O(n) when already sorted | O(1) | Stable | +| `Selection` | O(n²) | O(1) | Unstable | +| `Heapsort` | O(n log n) | O(1) | Unstable | +| `Merge` | O(n log n) | O(n) | No stability guarantee | +| `Reverse` | O(n) | O(1) | Not applicable | + Practical selection: - `Merge` and `Heapsort` — for the general `O(n log n)` case; diff --git a/skills/osspkg-algorithms/references/structures.md b/skills/osspkg-algorithms/references/structures.md index f233a8d..a1c0aa9 100644 --- a/skills/osspkg-algorithms/references/structures.md +++ b/skills/osspkg-algorithms/references/structures.md @@ -33,11 +33,13 @@ func main() { `Set`, `Del`, and `Has` use `uint64` indices; the bitmap grows automatically to the requested index, but values above the exported `bitmap.MaxIndex` are ignored or treated as absent. `MarshalBinary` returns a copy of the raw bytes. -`UnmarshalBinary` rejects empty input. +`UnmarshalBinary` rejects empty input. The raw format has no versioned header. Operations are protected by an `RWMutex` by default. Use `OptDisableLock()` only when access is strictly single-threaded or synchronization is fully handled -externally; it is not a safe default optimization. +externally; it is not a safe default optimization. Even with the default lock, +externally serialize a `Set` that may grow storage with concurrent `Has` or +`Del` calls. `CopyTo` copies the source's lock setting along with its bit data. ## Bloom filter: `structs/bloom` @@ -78,19 +80,21 @@ func main() { `Quantity(expectedItems, falsePositiveRate)` sets the expected number of items and the target false-positive probability; the size must be greater than zero, -and the rate must be strictly between `0` and `1`. xxhash is used by default. -With `HashFunc`, provide a `func() hash.Hash` factory such as `sha256.New`. +and the rate must be strictly between `0` and `1`. Defaults are 10,000,000 +items and a 0.1 false-positive rate; xxhash is used by default. With `HashFunc`, +provide a non-nil `func() hash.Hash` factory such as `sha256.New`. Each filter +gets random salts, so independently created filters are not interchangeable. The filter answers "definitely not" or "possibly present": false positives are normal, and `Contain` does not replace the source of truth. Use the same key representation with `Add` and `Contain`; the library converts strings, bytes, integers, and values implementing supported interfaces into bytes. -`Dump` stores the salts and bitmap, but does not store the hash function or the -original `Quantity` for the consuming code. To restore, use the same quantity -configuration and hash factory as when the filter was written, then check the -error from `Restore`. `CopyTo` copies the filter state independently of the -source. +`Dump` stores the salts and bitmap, but not the hash function or the original +`Quantity`; `Restore` is limited to 64 MiB. To restore, create the destination +with the same quantity configuration and hash factory as the source, then +check the error from `Restore`. `CopyTo` copies bits and salts but does not +replace the destination's hash factory, which MUST match the source. ## B-tree: `trees/btree` @@ -124,6 +128,9 @@ iterator. `BTree` protects `Find`, `Insert`, and `Delete` with an internal `RWMutex`, but do not copy the value after creation: pass around the pointer returned by `New`. +Keys must have a consistent total ordering; do not use floating-point NaN keys. +The degree controls keys per node, so choose it for the key type, workload, and +memory/cache trade-offs. Verified examples in the checkout: `structs/bitmap/bitmap_test.go`, `structs/bloom/bloom_test.go`, and `trees/btree/btree_test.go`. diff --git a/sorts/README.md b/sorts/README.md new file mode 100644 index 0000000..42ce026 --- /dev/null +++ b/sorts/README.md @@ -0,0 +1,47 @@ +# Package `sorts` + +## Abstract + +`sorts` provides generic in-place sorting algorithms and slice reversal. Each +sort accepts a slice and a comparison callback that receives indexes into the +slice's current, partially sorted state. + +## Operations + +| Function | Time | Extra storage | Stable | +| --- | --- | --- | --- | +| `Bubble` | O(n²), O(n) when already sorted | O(1) | Yes | +| `Cocktail` | O(n²) | O(1) | Yes | +| `Insertion` | O(n²), O(n) when already sorted | O(1) | Yes | +| `Selection` | O(n²) | O(1) | No | +| `Heapsort` | O(n log n) | O(1) | No | +| `Merge` | O(n log n) | O(n) | No guarantee | +| `Reverse` | O(n) | O(1) | N/A | + +`less(i, j)` MUST return true when the element currently at index `i` should +precede the element at index `j`. It SHOULD define a strict weak ordering. +Because sorting mutates the slice, the callback MUST read the current indexed +elements rather than assume that indexes still refer to their original values. + +```go +package main + +import ( + "fmt" + + "go.osspkg.com/algorithms/sorts" +) + +func main() { + values := []int{5, 1, 4, 2, 3} + sorts.Merge(values, func(i, j int) bool { + return values[i] < values[j] + }) + fmt.Println(values) // [1 2 3 4 5] +} +``` + +All sorting functions mutate the supplied slice. `Merge` allocates a temporary +buffer; the other operations use constant auxiliary storage. For general +application sorting, callers SHOULD also consider `slices.SortFunc` or +`sort.Slice` from the Go standard library. diff --git a/structs/bitmap/README.md b/structs/bitmap/README.md new file mode 100644 index 0000000..f36c74b --- /dev/null +++ b/structs/bitmap/README.md @@ -0,0 +1,42 @@ +# Package `bitmap` + +## Abstract + +`bitmap` stores membership flags for unsigned integer indexes in a growable, +byte-backed bitmap. `Set` grows storage as needed; `Has` tests a bit and `Del` +clears it. + +## API and limits + +`New` accepts `OptMaxIndex` to choose initial capacity. Storage grows when +`Set` reaches a larger index. The maximum supported index is the inclusive +constant `MaxIndex` (`1 << 34`); `Set` silently ignores larger indexes, while +`Has` returns false and `Del` does nothing for them. + +Internal locking is enabled by default. `OptDisableLock` removes it; callers +using that option MUST provide synchronization. Because the bounds check in +`Has` and `Del` can overlap a resize, callers MUST externally serialize a +`Set` that may grow the bitmap with concurrent reads or deletes. `CopyTo` +copies the bit storage and the source's lock setting into the destination. + +`MarshalBinary` returns the raw bitmap bytes without a versioned header. +`UnmarshalBinary` replaces the receiver's contents and rejects empty or +oversized data. The serialized bytes SHOULD be stored with any metadata needed +to identify their meaning. + +```go +package main + +import ( + "fmt" + + "go.osspkg.com/algorithms/structs/bitmap" +) + +func main() { + bm := bitmap.New(bitmap.OptMaxIndex(1024)) + bm.Set(42) + fmt.Println(bm.Has(42)) // true + bm.Del(42) +} +``` diff --git a/structs/bloom/README.md b/structs/bloom/README.md new file mode 100644 index 0000000..38f39a7 --- /dev/null +++ b/structs/bloom/README.md @@ -0,0 +1,50 @@ +# Package `bloom` + +## Abstract + +`bloom` implements a space-efficient probabilistic membership filter. A +negative `Contain` result means the value is definitely absent; a positive +result means it may be present. False positives are possible; false negatives +are not expected when the filter is used and restored with matching data. + +## Configuration and operations + +`New` defaults to an expected capacity of 10,000,000 values and a target false +positive rate of 0.1. `Quantity(n, p)` sets those values; `n` MUST be non-zero +and `p` MUST be strictly between zero and one. `HashFunc` selects a non-nil +`hash.Hash` factory; xxhash is the default. Each new filter also gets random +salts, so independently created filters are not interchangeable. + +`Add` and `Contain` accept strings, byte slices, integer types, and values +implementing supported byte, string, or encoding interfaces. Other values are +formatted with `fmt`. Callers SHOULD use a stable byte representation for a +value across additions, lookups, and persistence. + +```go +package main + +import ( + "fmt" + "log" + + "go.osspkg.com/algorithms/structs/bloom" +) + +func main() { + filter, err := bloom.New(bloom.Quantity(100_000, 0.01)) + if err != nil { + log.Fatal(err) + } + filter.Add("user:42") + fmt.Println(filter.Contain("user:42")) // true +} +``` + +The filter is synchronized for concurrent use. `Dump` and `Restore` use a +package-specific binary format; `Restore` is limited to 64 MiB. The dump does +not contain the sizing parameters, so callers MUST create the destination +with matching `Quantity` and `HashFunc` settings before restoring. `CopyTo` +copies the bits and salts but does not replace the destination's hash factory, +so the destination MUST use the same hash configuration. A Bloom filter is +not a source of truth and MUST NOT be used as an authorization decision by +itself. diff --git a/trees/btree/README.md b/trees/btree/README.md new file mode 100644 index 0000000..c01f02a --- /dev/null +++ b/trees/btree/README.md @@ -0,0 +1,43 @@ +# Package `btree` + +## Abstract + +`btree` provides a concurrent generic B-tree for keys ordered by Go's +`cmp.Ordered` constraint and arbitrary values. + +## API and behavior + +- `New[K, V](degree)` creates a tree. Degrees below two are raised to two. +- `Insert(key, value)` inserts a key or replaces the value for an existing key. +- `Find(key)` returns the value and `true` when present; otherwise it returns + the zero value of `V` and `false`. +- `Delete(key)` removes a key if present and otherwise does nothing. + +The tree uses internal synchronization by default and supports concurrent +operations. Keys MUST have a consistent total ordering. In particular, callers +MUST NOT insert floating-point NaN keys because ordinary comparisons do not +order NaN consistently. + +```go +package main + +import ( + "fmt" + + "go.osspkg.com/algorithms/trees/btree" +) + +func main() { + tree := btree.New[int, string](16) + tree.Insert(42, "answer") + if value, ok := tree.Find(42); ok { + fmt.Println(value) + } + tree.Delete(42) +} +``` + +The degree controls the number of keys stored per node and SHOULD be selected +for the expected key type, workload, and memory/cache trade-offs. Operations +take logarithmic tree depth with work inside each node proportional to its key +count.