Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

Playground

gnomod.toml

module = "gno.land/p/nym-moultest123/x/daily/kmp/v0"
gno = "0.9"

[addpkg]
  creator = "g1ml9grtwnpzqn3hre5ve5vjdlmv2srrmpmc0dsv"
  height = 186405
  max_deposit = "5000000ugnot"

kmp.gno

// Package kmp implements Knuth–Morris–Pratt substring search as a pure,
// reusable package.
//
// The naive scan re-compares characters it has already matched, so a hostile
// input like "aaaaaaab" in "aaaaaaaaaaaaaaab" costs O(n*m). KMP precomputes a
// failure table — for every prefix, the length of the longest proper prefix
// that is also a suffix — and uses it to slide the pattern without ever moving
// the text cursor backwards. That makes the scan O(n+m) with O(m) extra memory,
// and it never degrades: worst case equals best case, which is what makes it
// safe to run on chain where a pathological input is an attack, not bad luck.
//
// Operates on BYTES, not runes: gno strings are UTF-8, so a match index is a
// byte offset. That is the right unit for slicing and it keeps the failure
// table cheap; callers doing rune arithmetic must convert.
//
// A live demo of this package is at
// [r/moul/x/daily/kmpdemo](/r/nym-moultest123/x/daily/kmpdemo/v0).
package kmp

// MaxPattern bounds the failure table so gas stays predictable.
const MaxPattern = 1024

// Table returns the KMP failure table for pattern: table[i] is the length of
// the longest proper prefix of pattern[:i+1] that is also a suffix of it.
// Returns nil when the pattern is empty or longer than MaxPattern.
func Table(pattern string) []int {
	m := len(pattern)
	if m == 0 || m > MaxPattern {
		return nil
	}
	t := make([]int, m)
	k := 0
	for i := 1; i < m; i++ {
		for k > 0 && pattern[i] != pattern[k] {
			k = t[k-1]
		}
		if pattern[i] == pattern[k] {
			k++
		}
		t[i] = k
	}
	return t
}

// Index returns the byte offset of the first occurrence of pattern in text, or
// -1 if absent. An empty pattern matches at 0, matching strings.Index.
func Index(text, pattern string) int {
	all := findAll(text, pattern, 1)
	if len(all) == 0 {
		return -1
	}
	return all[0]
}

// Contains reports whether pattern occurs in text.
func Contains(text, pattern string) bool { return Index(text, pattern) >= 0 }

// FindAll returns the byte offsets of every match, including OVERLAPPING ones:
// FindAll("aaaa", "aa") is [0 1 2], not [0 2]. Overlap is the honest reading of
// "every occurrence" and the caller can always filter.
func FindAll(text, pattern string) []int { return findAll(text, pattern, 0) }

// Count returns how many times pattern occurs, counting overlaps.
func Count(text, pattern string) int { return len(FindAll(text, pattern)) }

// findAll collects match offsets, stopping after limit matches (0 = no limit).
func findAll(text, pattern string, limit int) []int {
	m := len(pattern)
	if m == 0 {
		return []int{0}
	}
	if m > len(text) || m > MaxPattern {
		return nil
	}
	t := Table(pattern)
	if t == nil {
		return nil
	}

	var out []int
	k := 0
	for i := 0; i < len(text); i++ {
		for k > 0 && text[i] != pattern[k] {
			k = t[k-1]
		}
		if text[i] == pattern[k] {
			k++
		}
		if k == m {
			out = append(out, i-m+1)
			if limit > 0 && len(out) >= limit {
				return out
			}
			k = t[k-1] // allow overlapping matches
		}
	}
	return out
}

kmp_test.gno

package kmp

import (
	"strings"
	"testing"

	"gno.land/p/nt/uassert/v0"
)

func TestTable(t *testing.T) {
	cases := []struct {
		pattern string
		want    []int
	}{
		{"abcabca", []int{0, 0, 0, 1, 2, 3, 4}},
		{"aaaa", []int{0, 1, 2, 3}},
		{"abcd", []int{0, 0, 0, 0}},
		{"ababaa", []int{0, 0, 1, 2, 3, 1}},
		{"a", []int{0}},
	}
	for _, c := range cases {
		got := Table(c.pattern)
		uassert.Equal(t, len(c.want), len(got), "table length for "+c.pattern)
		for i := range c.want {
			uassert.Equal(t, c.want[i], got[i], "table["+itoa(i)+"] for "+c.pattern)
		}
	}
}

func TestTableRejects(t *testing.T) {
	uassert.True(t, Table("") == nil, "empty pattern has no table")
	uassert.True(t, Table(strings.Repeat("x", MaxPattern+1)) == nil, "oversized pattern refused")
	uassert.False(t, Table(strings.Repeat("x", MaxPattern)) == nil, "exactly MaxPattern is allowed")
}

// TestIndexMatchesStdlib pins KMP against strings.Index across a spread of
// inputs — same contract, different algorithm.
func TestIndexMatchesStdlib(t *testing.T) {
	texts := []string{"", "a", "hello world", "aaaaaaab", "abcabcabd", "mississippi"}
	pats := []string{"", "a", "b", "ab", "abd", "issi", "world", "zzz", "mississippi"}
	for _, text := range texts {
		for _, p := range pats {
			uassert.Equal(t, strings.Index(text, p), Index(text, p),
				"Index("+text+","+p+") should match strings.Index")
		}
	}
}

func TestContains(t *testing.T) {
	uassert.True(t, Contains("hello world", "lo w"))
	uassert.False(t, Contains("hello world", "lo  w"))
	uassert.True(t, Contains("anything", ""), "empty pattern is always contained")
}

// TestFindAllOverlapping is the documented divergence from a naive scan.
func TestFindAllOverlapping(t *testing.T) {
	got := FindAll("aaaa", "aa")
	uassert.Equal(t, 3, len(got), "overlapping matches are all reported")
	uassert.Equal(t, 0, got[0])
	uassert.Equal(t, 1, got[1])
	uassert.Equal(t, 2, got[2])
}

func TestFindAllDisjoint(t *testing.T) {
	got := FindAll("abcabcabc", "abc")
	uassert.Equal(t, 3, len(got))
	uassert.Equal(t, 0, got[0])
	uassert.Equal(t, 3, got[1])
	uassert.Equal(t, 6, got[2])
}

func TestFindAllAbsent(t *testing.T) {
	uassert.Equal(t, 0, len(FindAll("abc", "xyz")))
	uassert.Equal(t, 0, len(FindAll("ab", "abcdef")), "pattern longer than text")
}

func TestCount(t *testing.T) {
	uassert.Equal(t, 4, Count("aaaaa", "aa"))
	uassert.Equal(t, 2, Count("mississippi", "issi"))
	uassert.Equal(t, 0, Count("abc", "d"))
}

// TestPathologicalInput is the reason to use KMP: the naive scan is quadratic
// here, KMP is linear. Correctness is what we assert; the cost is the point.
func TestPathologicalInput(t *testing.T) {
	text := strings.Repeat("a", 2000) + "b"
	pattern := strings.Repeat("a", 200) + "b"
	uassert.Equal(t, 1800, Index(text, pattern))
	uassert.Equal(t, 1, Count(text, pattern))
}

// TestBytesNotRunes documents that offsets are byte offsets.
func TestBytesNotRunes(t *testing.T) {
	// "é" is two bytes in UTF-8, so "x" sits at byte 2, not rune 1.
	uassert.Equal(t, 2, Index("éx", "x"))
	uassert.Equal(t, strings.Index("éx", "x"), Index("éx", "x"))
}

func TestMatchAtStartAndEnd(t *testing.T) {
	uassert.Equal(t, 0, Index("abcdef", "abc"))
	uassert.Equal(t, 3, Index("abcdef", "def"))
	uassert.Equal(t, 0, Index("abc", "abc"), "whole-string match")
}

func itoa(i int) string {
	if i == 0 {
		return "0"
	}
	s := ""
	for i > 0 {
		s = string(rune('0'+i%10)) + s
		i /= 10
	}
	return s
}