Fully persistent data structures. A persistent data structure is a data structure that always preserves the previous version of itself when it is modified. Such data structures are effectively immutable, as their operations do not update the structure in-place, but instead always yield a new structure. Persistent data structures typically share structure among themselves. This allows operations to avoid copying the entire data structure.
package ps

import (
	
	
)
Any is a shorthand for Go's verbose interface{} type.
type Any interface{}
A Map associates unique keys (type string) with values (type Any).
IsNil returns true if the Map is empty
	IsNil() bool
Set returns a new map in which key and value are associated. If the key didn't exist before, it's created; otherwise, the associated value is changed. This operation is O(log N) in the number of keys.
	Set(key string, value Any) Map
Delete returns a new map with the association for key, if any, removed. This operation is O(log N) in the number of keys.
	Delete(key string) Map
Lookup returns the value associated with a key, if any. If the key exists, the second return value is true; otherwise, false. This operation is O(log N) in the number of keys.
	Lookup(key string) (Any, bool)
Size returns the number of key value pairs in the map. This takes O(1) time.
	Size() int
ForEach executes a callback on each key value pair in the map.
	ForEach(f func(key string, val Any))
Keys returns a slice with all keys in this map. This operation is O(N) in the number of keys.
	Keys() []string

	String() string
}
Immutable (i.e. persistent) associative array
const childCount = 8
const shiftSize = 3

type tree struct {
	count    int
	hash     uint64 // hash of the key (used for tree balancing)
	key      string
	value    Any
	children [childCount]*tree
}

var nilMap = &tree{}
Recursively set nilMap's subtrees to point at itself. This eliminates all nil pointers in the map structure. All map nodes are created by cloning this structure so they avoid the problem too.
func () {
	for  := range nilMap.children {
		nilMap.children[] = nilMap
	}
}
NewMap allocates a new, persistent map from strings to values of any type. This is currently implemented as a path-copying binary tree.
func () Map {
	return nilMap
}

func ( *tree) () bool {
	return  == nilMap
}
clone returns an exact duplicate of a tree node
func ( *tree) () *tree {
	var  tree
	 = *
	return &
}
constants for FNV-1a hash algorithm
const (
	offset64 uint64 = 14695981039346656037
	prime64  uint64 = 1099511628211
)
hashKey returns a hash code for a given string
func ( string) uint64 {
	 := offset64
	for ,  := range  {
		 ^= uint64()
		 *= prime64
	}
	return 
}
Set returns a new map similar to this one but with key and value associated. If the key didn't exist, it's created; otherwise, the associated value is changed.
func ( *tree) ( string,  Any) Map {
	 := hashKey()
	return setLowLevel(, , , , )
}

func ( *tree, ,  uint64,  string,  Any) *tree {
	if .IsNil() { // an empty tree is easy
		 := .clone()
		.count = 1
		.hash = 
		.key = 
		.value = 
		return 
	}

	if  != .hash {
		 := .clone()
		 :=  % childCount
		.children[] = (.children[], >>shiftSize, , , )
		recalculateCount()
		return 
	}
replacing a key's previous value
	 := .clone()
	.value = 
	return 
}
modifies a map by recalculating its key count based on the counts of its subtrees
func ( *tree) {
	 := 0
	for ,  := range .children {
		 += .Size()
	}
	.count =  + 1 // add one to count ourself
}

func ( *tree) ( string) Map {
	 := hashKey()
	,  := deleteLowLevel(, , )
	return 
}

empty trees are easy
	if .IsNil() {
		return , false
	}

	if  != .hash {
		 :=  % childCount
		,  := (.children[], >>shiftSize, )
		if ! {
			return , false
		}
		 := .clone()
		.children[] = 
		recalculateCount()
		return , true // ? this wasn't in the original code
	}
we must delete our own node
	if .isLeaf() { // we have no children
		return nilMap, true
if self.subtreeCount() == 1 { only one subtree for _, t := range self.children { if t != nilMap { return t, true } } panic("Tree with 1 subtree actually had no subtrees") }
find a node to replace us
	 := -1
	 := -1
	for ,  := range .children {
		if .Size() >  {
			 = 
			 = .Size()
		}
	}
make chosen leaf smaller
	,  := .children[].deleteLeftmost()
	 := .clone()
	for  := range .children {
		if  ==  {
			.children[] = 
		} else {
			.children[] = .children[]
		}
	}
	recalculateCount()
	return , true
}
delete the leftmost node in a tree returning the node that was deleted and the tree left over after its deletion
func ( *tree) () (*tree, *tree) {
	if .isLeaf() {
		return , nilMap
	}

	for ,  := range .children {
		if  != nilMap {
			,  := .()
			 := .clone()
			.children[] = 
			recalculateCount()
			return , 
		}
	}
	panic("Tree isn't a leaf but also had no children. How does that happen?")
}
isLeaf returns true if this is a leaf node
func ( *tree) () bool {
	return .Size() == 1
}
returns the number of child subtrees we have
func ( *tree) () int {
	 := 0
	for ,  := range .children {
		if  != nilMap {
			++
		}
	}
	return 
}

func ( *tree) ( string) (Any, bool) {
	 := hashKey()
	return lookupLowLevel(, , )
}

func ( *tree, ,  uint64) (Any, bool) {
	if .IsNil() { // an empty tree is easy
		return nil, false
	}

	if  != .hash {
		 :=  % childCount
		return (.children[], >>shiftSize, )
	}
we found it
	return .value, true
}

func ( *tree) () int {
	return .count
}

func ( *tree) ( func( string,  Any)) {
	if .IsNil() {
		return
	}
ourself
	(.key, .value)
children
	for ,  := range .children {
		if  != nilMap {
			.()
		}
	}
}

func ( *tree) () []string {
	 := make([]string, .Size())
	 := 0
	.ForEach(func( string,  Any) {
		[] = 
		++
	})
	return 
}
make it easier to display maps for debugging
func ( *tree) () string {
	 := .Keys()
	 := bytes.NewBufferString("{")
	for ,  := range  {
		,  := .Lookup()
		fmt.Fprintf(, "%s: %s, ", , )
	}
	fmt.Fprintf(, "}\n")
	return .String()