immutable.go 79 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734
  1. // Package immutable provides immutable collection types.
  2. //
  3. // Introduction
  4. //
  5. // Immutable collections provide an efficient, safe way to share collections
  6. // of data while minimizing locks. The collections in this package provide
  7. // List, Map, and SortedMap implementations. These act similarly to slices
  8. // and maps, respectively, except that altering a collection returns a new
  9. // copy of the collection with that change.
  10. //
  11. // Because collections are unable to change, they are safe for multiple
  12. // goroutines to read from at the same time without a mutex. However, these
  13. // types of collections come with increased CPU & memory usage as compared
  14. // with Go's built-in collection types so please evaluate for your specific
  15. // use.
  16. //
  17. // Collection Types
  18. //
  19. // The List type provides an API similar to Go slices. They allow appending,
  20. // prepending, and updating of elements. Elements can also be fetched by index
  21. // or iterated over using a ListIterator.
  22. //
  23. // The Map & SortedMap types provide an API similar to Go maps. They allow
  24. // values to be assigned to unique keys and allow for the deletion of keys.
  25. // Values can be fetched by key and key/value pairs can be iterated over using
  26. // the appropriate iterator type. Both map types provide the same API. The
  27. // SortedMap, however, provides iteration over sorted keys while the Map
  28. // provides iteration over unsorted keys. Maps improved performance and memory
  29. // usage as compared to SortedMaps.
  30. //
  31. // Hashing and Sorting
  32. //
  33. // Map types require the use of a Hasher implementation to calculate hashes for
  34. // their keys and check for key equality. SortedMaps require the use of a
  35. // Comparer implementation to sort keys in the map.
  36. //
  37. // These collection types automatically provide built-in hasher and comparers
  38. // for int, string, and byte slice keys. If you are using one of these key types
  39. // then simply pass a nil into the constructor. Otherwise you will need to
  40. // implement a custom Hasher or Comparer type. Please see the provided
  41. // implementations for reference.
  42. package immutable
  43. import (
  44. "bytes"
  45. "fmt"
  46. "math/bits"
  47. "reflect"
  48. "sort"
  49. "strings"
  50. )
  51. // List is a dense, ordered, indexed collections. They are analogous to slices
  52. // in Go. They can be updated by appending to the end of the list, prepending
  53. // values to the beginning of the list, or updating existing indexes in the
  54. // list.
  55. type List struct {
  56. root listNode // root node
  57. origin int // offset to zero index element
  58. size int // total number of elements in use
  59. }
  60. // NewList returns a new empty instance of List.
  61. func NewList() *List {
  62. return &List{
  63. root: &listLeafNode{},
  64. }
  65. }
  66. // clone returns a copy of the list.
  67. func (l *List) clone() *List {
  68. other := *l
  69. return &other
  70. }
  71. // Len returns the number of elements in the list.
  72. func (l *List) Len() int {
  73. return l.size
  74. }
  75. // cap returns the total number of possible elements for the current depth.
  76. func (l *List) cap() int {
  77. return 1 << (l.root.depth() * listNodeBits)
  78. }
  79. // Get returns the value at the given index. Similar to slices, this method will
  80. // panic if index is below zero or is greater than or equal to the list size.
  81. func (l *List) Get(index int) interface{} {
  82. if index < 0 || index >= l.size {
  83. panic(fmt.Sprintf("immutable.List.Get: index %d out of bounds", index))
  84. }
  85. return l.root.get(l.origin + index)
  86. }
  87. // Set returns a new list with value set at index. Similar to slices, this
  88. // method will panic if index is below zero or if the index is greater than
  89. // or equal to the list size.
  90. func (l *List) Set(index int, value interface{}) *List {
  91. return l.set(index, value, false)
  92. }
  93. func (l *List) set(index int, value interface{}, mutable bool) *List {
  94. if index < 0 || index >= l.size {
  95. panic(fmt.Sprintf("immutable.List.Set: index %d out of bounds", index))
  96. }
  97. other := l
  98. if !mutable {
  99. other = l.clone()
  100. }
  101. other.root = other.root.set(l.origin+index, value, mutable)
  102. return other
  103. }
  104. // Append returns a new list with value added to the end of the list.
  105. func (l *List) Append(value interface{}) *List {
  106. return l.append(value, false)
  107. }
  108. func (l *List) append(value interface{}, mutable bool) *List {
  109. other := l
  110. if !mutable {
  111. other = l.clone()
  112. }
  113. // Expand list to the right if no slots remain.
  114. if other.size+other.origin >= l.cap() {
  115. newRoot := &listBranchNode{d: other.root.depth() + 1}
  116. newRoot.children[0] = other.root
  117. other.root = newRoot
  118. }
  119. // Increase size and set the last element to the new value.
  120. other.size++
  121. other.root = other.root.set(other.origin+other.size-1, value, mutable)
  122. return other
  123. }
  124. // Prepend returns a new list with value added to the beginning of the list.
  125. func (l *List) Prepend(value interface{}) *List {
  126. return l.prepend(value, false)
  127. }
  128. func (l *List) prepend(value interface{}, mutable bool) *List {
  129. other := l
  130. if !mutable {
  131. other = l.clone()
  132. }
  133. // Expand list to the left if no slots remain.
  134. if other.origin == 0 {
  135. newRoot := &listBranchNode{d: other.root.depth() + 1}
  136. newRoot.children[listNodeSize-1] = other.root
  137. other.root = newRoot
  138. other.origin += (listNodeSize - 1) << (other.root.depth() * listNodeBits)
  139. }
  140. // Increase size and move origin back. Update first element to value.
  141. other.size++
  142. other.origin--
  143. other.root = other.root.set(other.origin, value, mutable)
  144. return other
  145. }
  146. // Slice returns a new list of elements between start index and end index.
  147. // Similar to slices, this method will panic if start or end are below zero or
  148. // greater than the list size. A panic will also occur if start is greater than
  149. // end.
  150. //
  151. // Unlike Go slices, references to inaccessible elements will be automatically
  152. // removed so they can be garbage collected.
  153. func (l *List) Slice(start, end int) *List {
  154. return l.slice(start, end, false)
  155. }
  156. func (l *List) slice(start, end int, mutable bool) *List {
  157. // Panics similar to Go slices.
  158. if start < 0 || start > l.size {
  159. panic(fmt.Sprintf("immutable.List.Slice: start index %d out of bounds", start))
  160. } else if end < 0 || end > l.size {
  161. panic(fmt.Sprintf("immutable.List.Slice: end index %d out of bounds", end))
  162. } else if start > end {
  163. panic(fmt.Sprintf("immutable.List.Slice: invalid slice index: [%d:%d]", start, end))
  164. }
  165. // Return the same list if the start and end are the entire range.
  166. if start == 0 && end == l.size {
  167. return l
  168. }
  169. // Create copy, if immutable.
  170. other := l
  171. if !mutable {
  172. other = l.clone()
  173. }
  174. // Update origin/size.
  175. other.origin = l.origin + start
  176. other.size = end - start
  177. // Contract tree while the start & end are in the same child node.
  178. for other.root.depth() > 1 {
  179. i := (other.origin >> (other.root.depth() * listNodeBits)) & listNodeMask
  180. j := ((other.origin + other.size - 1) >> (other.root.depth() * listNodeBits)) & listNodeMask
  181. if i != j {
  182. break // branch contains at least two nodes, exit
  183. }
  184. // Replace the current root with the single child & update origin offset.
  185. other.origin -= i << (other.root.depth() * listNodeBits)
  186. other.root = other.root.(*listBranchNode).children[i]
  187. }
  188. // Ensure all references are removed before start & after end.
  189. other.root = other.root.deleteBefore(other.origin, mutable)
  190. other.root = other.root.deleteAfter(other.origin+other.size-1, mutable)
  191. return other
  192. }
  193. // Iterator returns a new iterator for this list positioned at the first index.
  194. func (l *List) Iterator() *ListIterator {
  195. itr := &ListIterator{list: l}
  196. itr.First()
  197. return itr
  198. }
  199. // ListBuilder represents an efficient builder for creating new Lists.
  200. type ListBuilder struct {
  201. list *List // current state
  202. }
  203. // NewListBuilder returns a new instance of ListBuilder.
  204. func NewListBuilder() *ListBuilder {
  205. return &ListBuilder{list: NewList()}
  206. }
  207. // List returns the current copy of the list.
  208. // The builder should not be used again after the list after this call.
  209. func (b *ListBuilder) List() *List {
  210. assert(b.list != nil, "immutable.ListBuilder.List(): duplicate call to fetch list")
  211. list := b.list
  212. b.list = nil
  213. return list
  214. }
  215. // Len returns the number of elements in the underlying list.
  216. func (b *ListBuilder) Len() int {
  217. assert(b.list != nil, "immutable.ListBuilder: builder invalid after List() invocation")
  218. return b.list.Len()
  219. }
  220. // Get returns the value at the given index. Similar to slices, this method will
  221. // panic if index is below zero or is greater than or equal to the list size.
  222. func (b *ListBuilder) Get(index int) interface{} {
  223. assert(b.list != nil, "immutable.ListBuilder: builder invalid after List() invocation")
  224. return b.list.Get(index)
  225. }
  226. // Set updates the value at the given index. Similar to slices, this method will
  227. // panic if index is below zero or if the index is greater than or equal to the
  228. // list size.
  229. func (b *ListBuilder) Set(index int, value interface{}) {
  230. assert(b.list != nil, "immutable.ListBuilder: builder invalid after List() invocation")
  231. b.list = b.list.set(index, value, true)
  232. }
  233. // Append adds value to the end of the list.
  234. func (b *ListBuilder) Append(value interface{}) {
  235. assert(b.list != nil, "immutable.ListBuilder: builder invalid after List() invocation")
  236. b.list = b.list.append(value, true)
  237. }
  238. // Prepend adds value to the beginning of the list.
  239. func (b *ListBuilder) Prepend(value interface{}) {
  240. assert(b.list != nil, "immutable.ListBuilder: builder invalid after List() invocation")
  241. b.list = b.list.prepend(value, true)
  242. }
  243. // Slice updates the list with a sublist of elements between start and end index.
  244. // See List.Slice() for more details.
  245. func (b *ListBuilder) Slice(start, end int) {
  246. assert(b.list != nil, "immutable.ListBuilder: builder invalid after List() invocation")
  247. b.list = b.list.slice(start, end, true)
  248. }
  249. // Iterator returns a new iterator for the underlying list.
  250. func (b *ListBuilder) Iterator() *ListIterator {
  251. assert(b.list != nil, "immutable.ListBuilder: builder invalid after List() invocation")
  252. return b.list.Iterator()
  253. }
  254. // Constants for bit shifts used for levels in the List trie.
  255. const (
  256. listNodeBits = 5
  257. listNodeSize = 1 << listNodeBits
  258. listNodeMask = listNodeSize - 1
  259. )
  260. // listNode represents either a branch or leaf node in a List.
  261. type listNode interface {
  262. depth() uint
  263. get(index int) interface{}
  264. set(index int, v interface{}, mutable bool) listNode
  265. containsBefore(index int) bool
  266. containsAfter(index int) bool
  267. deleteBefore(index int, mutable bool) listNode
  268. deleteAfter(index int, mutable bool) listNode
  269. }
  270. // newListNode returns a leaf node for depth zero, otherwise returns a branch node.
  271. func newListNode(depth uint) listNode {
  272. if depth == 0 {
  273. return &listLeafNode{}
  274. }
  275. return &listBranchNode{d: depth}
  276. }
  277. // listBranchNode represents a branch of a List tree at a given depth.
  278. type listBranchNode struct {
  279. d uint // depth
  280. children [listNodeSize]listNode
  281. }
  282. // depth returns the depth of this branch node from the leaf.
  283. func (n *listBranchNode) depth() uint { return n.d }
  284. // get returns the child node at the segment of the index for this depth.
  285. func (n *listBranchNode) get(index int) interface{} {
  286. idx := (index >> (n.d * listNodeBits)) & listNodeMask
  287. return n.children[idx].get(index)
  288. }
  289. // set recursively updates the value at index for each lower depth from the node.
  290. func (n *listBranchNode) set(index int, v interface{}, mutable bool) listNode {
  291. idx := (index >> (n.d * listNodeBits)) & listNodeMask
  292. // Find child for the given value in the branch. Create new if it doesn't exist.
  293. child := n.children[idx]
  294. if child == nil {
  295. child = newListNode(n.depth() - 1)
  296. }
  297. // Return a copy of this branch with the new child.
  298. var other *listBranchNode
  299. if mutable {
  300. other = n
  301. } else {
  302. tmp := *n
  303. other = &tmp
  304. }
  305. other.children[idx] = child.set(index, v, mutable)
  306. return other
  307. }
  308. // containsBefore returns true if non-nil values exists between [0,index).
  309. func (n *listBranchNode) containsBefore(index int) bool {
  310. idx := (index >> (n.d * listNodeBits)) & listNodeMask
  311. // Quickly check if any direct children exist before this segment of the index.
  312. for i := 0; i < idx; i++ {
  313. if n.children[i] != nil {
  314. return true
  315. }
  316. }
  317. // Recursively check for children directly at the given index at this segment.
  318. if n.children[idx] != nil && n.children[idx].containsBefore(index) {
  319. return true
  320. }
  321. return false
  322. }
  323. // containsAfter returns true if non-nil values exists between (index,listNodeSize).
  324. func (n *listBranchNode) containsAfter(index int) bool {
  325. idx := (index >> (n.d * listNodeBits)) & listNodeMask
  326. // Quickly check if any direct children exist after this segment of the index.
  327. for i := idx + 1; i < len(n.children); i++ {
  328. if n.children[i] != nil {
  329. return true
  330. }
  331. }
  332. // Recursively check for children directly at the given index at this segment.
  333. if n.children[idx] != nil && n.children[idx].containsAfter(index) {
  334. return true
  335. }
  336. return false
  337. }
  338. // deleteBefore returns a new node with all elements before index removed.
  339. func (n *listBranchNode) deleteBefore(index int, mutable bool) listNode {
  340. // Ignore if no nodes exist before the given index.
  341. if !n.containsBefore(index) {
  342. return n
  343. }
  344. // Return a copy with any nodes prior to the index removed.
  345. idx := (index >> (n.d * listNodeBits)) & listNodeMask
  346. var other *listBranchNode
  347. if mutable {
  348. other = n
  349. for i := 0; i < idx; i++ {
  350. n.children[i] = nil
  351. }
  352. } else {
  353. other = &listBranchNode{d: n.d}
  354. copy(other.children[idx:][:], n.children[idx:][:])
  355. }
  356. if other.children[idx] != nil {
  357. other.children[idx] = other.children[idx].deleteBefore(index, mutable)
  358. }
  359. return other
  360. }
  361. // deleteBefore returns a new node with all elements before index removed.
  362. func (n *listBranchNode) deleteAfter(index int, mutable bool) listNode {
  363. // Ignore if no nodes exist after the given index.
  364. if !n.containsAfter(index) {
  365. return n
  366. }
  367. // Return a copy with any nodes after the index removed.
  368. idx := (index >> (n.d * listNodeBits)) & listNodeMask
  369. var other *listBranchNode
  370. if mutable {
  371. other = n
  372. for i := idx + 1; i < len(n.children); i++ {
  373. n.children[i] = nil
  374. }
  375. } else {
  376. other = &listBranchNode{d: n.d}
  377. copy(other.children[:idx+1], n.children[:idx+1])
  378. }
  379. if other.children[idx] != nil {
  380. other.children[idx] = other.children[idx].deleteAfter(index, mutable)
  381. }
  382. return other
  383. }
  384. // listLeafNode represents a leaf node in a List.
  385. type listLeafNode struct {
  386. children [listNodeSize]interface{}
  387. }
  388. // depth always returns 0 for leaf nodes.
  389. func (n *listLeafNode) depth() uint { return 0 }
  390. // get returns the value at the given index.
  391. func (n *listLeafNode) get(index int) interface{} {
  392. return n.children[index&listNodeMask]
  393. }
  394. // set returns a copy of the node with the value at the index updated to v.
  395. func (n *listLeafNode) set(index int, v interface{}, mutable bool) listNode {
  396. idx := index & listNodeMask
  397. var other *listLeafNode
  398. if mutable {
  399. other = n
  400. } else {
  401. tmp := *n
  402. other = &tmp
  403. }
  404. other.children[idx] = v
  405. return other
  406. }
  407. // containsBefore returns true if non-nil values exists between [0,index).
  408. func (n *listLeafNode) containsBefore(index int) bool {
  409. idx := index & listNodeMask
  410. for i := 0; i < idx; i++ {
  411. if n.children[i] != nil {
  412. return true
  413. }
  414. }
  415. return false
  416. }
  417. // containsAfter returns true if non-nil values exists between (index,listNodeSize).
  418. func (n *listLeafNode) containsAfter(index int) bool {
  419. idx := index & listNodeMask
  420. for i := idx + 1; i < len(n.children); i++ {
  421. if n.children[i] != nil {
  422. return true
  423. }
  424. }
  425. return false
  426. }
  427. // deleteBefore returns a new node with all elements before index removed.
  428. func (n *listLeafNode) deleteBefore(index int, mutable bool) listNode {
  429. if !n.containsBefore(index) {
  430. return n
  431. }
  432. idx := index & listNodeMask
  433. var other *listLeafNode
  434. if mutable {
  435. other = n
  436. for i := 0; i < idx; i++ {
  437. other.children[i] = nil
  438. }
  439. } else {
  440. other = &listLeafNode{}
  441. copy(other.children[idx:][:], n.children[idx:][:])
  442. }
  443. return other
  444. }
  445. // deleteBefore returns a new node with all elements before index removed.
  446. func (n *listLeafNode) deleteAfter(index int, mutable bool) listNode {
  447. if !n.containsAfter(index) {
  448. return n
  449. }
  450. idx := index & listNodeMask
  451. var other *listLeafNode
  452. if mutable {
  453. other = n
  454. for i := idx + 1; i < len(n.children); i++ {
  455. other.children[i] = nil
  456. }
  457. } else {
  458. other = &listLeafNode{}
  459. copy(other.children[:idx+1][:], n.children[:idx+1][:])
  460. }
  461. return other
  462. }
  463. // ListIterator represents an ordered iterator over a list.
  464. type ListIterator struct {
  465. list *List // source list
  466. index int // current index position
  467. stack [32]listIteratorElem // search stack
  468. depth int // stack depth
  469. }
  470. // Done returns true if no more elements remain in the iterator.
  471. func (itr *ListIterator) Done() bool {
  472. return itr.index < 0 || itr.index >= itr.list.Len()
  473. }
  474. // First positions the iterator on the first index.
  475. // If source list is empty then no change is made.
  476. func (itr *ListIterator) First() {
  477. if itr.list.Len() != 0 {
  478. itr.Seek(0)
  479. }
  480. }
  481. // Last positions the iterator on the last index.
  482. // If source list is empty then no change is made.
  483. func (itr *ListIterator) Last() {
  484. if n := itr.list.Len(); n != 0 {
  485. itr.Seek(n - 1)
  486. }
  487. }
  488. // Seek moves the iterator position to the given index in the list.
  489. // Similar to Go slices, this method will panic if index is below zero or if
  490. // the index is greater than or equal to the list size.
  491. func (itr *ListIterator) Seek(index int) {
  492. // Panic similar to Go slices.
  493. if index < 0 || index >= itr.list.Len() {
  494. panic(fmt.Sprintf("immutable.ListIterator.Seek: index %d out of bounds", index))
  495. }
  496. itr.index = index
  497. // Reset to the bottom of the stack at seek to the correct position.
  498. itr.stack[0] = listIteratorElem{node: itr.list.root}
  499. itr.depth = 0
  500. itr.seek(index)
  501. }
  502. // Next returns the current index and its value & moves the iterator forward.
  503. // Returns an index of -1 if the there are no more elements to return.
  504. func (itr *ListIterator) Next() (index int, value interface{}) {
  505. // Exit immediately if there are no elements remaining.
  506. if itr.Done() {
  507. return -1, nil
  508. }
  509. // Retrieve current index & value.
  510. elem := &itr.stack[itr.depth]
  511. index, value = itr.index, elem.node.(*listLeafNode).children[elem.index]
  512. // Increase index. If index is at the end then return immediately.
  513. itr.index++
  514. if itr.Done() {
  515. return index, value
  516. }
  517. // Move up stack until we find a node that has remaining position ahead.
  518. for ; itr.depth > 0 && itr.stack[itr.depth].index >= listNodeSize-1; itr.depth-- {
  519. }
  520. // Seek to correct position from current depth.
  521. itr.seek(itr.index)
  522. return index, value
  523. }
  524. // Prev returns the current index and value and moves the iterator backward.
  525. // Returns an index of -1 if the there are no more elements to return.
  526. func (itr *ListIterator) Prev() (index int, value interface{}) {
  527. // Exit immediately if there are no elements remaining.
  528. if itr.Done() {
  529. return -1, nil
  530. }
  531. // Retrieve current index & value.
  532. elem := &itr.stack[itr.depth]
  533. index, value = itr.index, elem.node.(*listLeafNode).children[elem.index]
  534. // Decrease index. If index is past the beginning then return immediately.
  535. itr.index--
  536. if itr.Done() {
  537. return index, value
  538. }
  539. // Move up stack until we find a node that has remaining position behind.
  540. for ; itr.depth > 0 && itr.stack[itr.depth].index == 0; itr.depth-- {
  541. }
  542. // Seek to correct position from current depth.
  543. itr.seek(itr.index)
  544. return index, value
  545. }
  546. // seek positions the stack to the given index from the current depth.
  547. // Elements and indexes below the current depth are assumed to be correct.
  548. func (itr *ListIterator) seek(index int) {
  549. // Iterate over each level until we reach a leaf node.
  550. for {
  551. elem := &itr.stack[itr.depth]
  552. elem.index = ((itr.list.origin + index) >> (elem.node.depth() * listNodeBits)) & listNodeMask
  553. switch node := elem.node.(type) {
  554. case *listBranchNode:
  555. child := node.children[elem.index]
  556. itr.stack[itr.depth+1] = listIteratorElem{node: child}
  557. itr.depth++
  558. case *listLeafNode:
  559. return
  560. }
  561. }
  562. }
  563. // listIteratorElem represents the node and it's child index within the stack.
  564. type listIteratorElem struct {
  565. node listNode
  566. index int
  567. }
  568. // Size thresholds for each type of branch node.
  569. const (
  570. maxArrayMapSize = 8
  571. maxBitmapIndexedSize = 16
  572. )
  573. // Segment bit shifts within the map tree.
  574. const (
  575. mapNodeBits = 5
  576. mapNodeSize = 1 << mapNodeBits
  577. mapNodeMask = mapNodeSize - 1
  578. )
  579. // Map represents an immutable hash map implementation. The map uses a Hasher
  580. // to generate hashes and check for equality of key values.
  581. //
  582. // It is implemented as an Hash Array Mapped Trie.
  583. type Map struct {
  584. size int // total number of key/value pairs
  585. root mapNode // root node of trie
  586. hasher Hasher // hasher implementation
  587. }
  588. // NewMap returns a new instance of Map. If hasher is nil, a default hasher
  589. // implementation will automatically be chosen based on the first key added.
  590. // Default hasher implementations only exist for int, string, and byte slice types.
  591. func NewMap(hasher Hasher) *Map {
  592. return &Map{
  593. hasher: hasher,
  594. }
  595. }
  596. // Len returns the number of elements in the map.
  597. func (m *Map) Len() int {
  598. return m.size
  599. }
  600. // clone returns a shallow copy of m.
  601. func (m *Map) clone() *Map {
  602. other := *m
  603. return &other
  604. }
  605. // Get returns the value for a given key and a flag indicating whether the
  606. // key exists. This flag distinguishes a nil value set on a key versus a
  607. // non-existent key in the map.
  608. func (m *Map) Get(key interface{}) (value interface{}, ok bool) {
  609. if m.root == nil {
  610. return nil, false
  611. }
  612. keyHash := m.hasher.Hash(key)
  613. return m.root.get(key, 0, keyHash, m.hasher)
  614. }
  615. // Set returns a map with the key set to the new value. A nil value is allowed.
  616. //
  617. // This function will return a new map even if the updated value is the same as
  618. // the existing value because Map does not track value equality.
  619. func (m *Map) Set(key, value interface{}) *Map {
  620. return m.set(key, value, false)
  621. }
  622. func (m *Map) set(key, value interface{}, mutable bool) *Map {
  623. // Set a hasher on the first value if one does not already exist.
  624. hasher := m.hasher
  625. if hasher == nil {
  626. hasher = NewHasher(key)
  627. }
  628. // Generate copy if necessary.
  629. other := m
  630. if !mutable {
  631. other = m.clone()
  632. }
  633. other.hasher = hasher
  634. // If the map is empty, initialize with a simple array node.
  635. if m.root == nil {
  636. other.size = 1
  637. other.root = &mapArrayNode{entries: []mapEntry{{key: key, value: value}}}
  638. return other
  639. }
  640. // Otherwise copy the map and delegate insertion to the root.
  641. // Resized will return true if the key does not currently exist.
  642. var resized bool
  643. other.root = m.root.set(key, value, 0, hasher.Hash(key), hasher, mutable, &resized)
  644. if resized {
  645. other.size++
  646. }
  647. return other
  648. }
  649. // Delete returns a map with the given key removed.
  650. // Removing a non-existent key will cause this method to return the same map.
  651. func (m *Map) Delete(key interface{}) *Map {
  652. return m.delete(key, false)
  653. }
  654. func (m *Map) delete(key interface{}, mutable bool) *Map {
  655. // Return original map if no keys exist.
  656. if m.root == nil {
  657. return m
  658. }
  659. // If the delete did not change the node then return the original map.
  660. var resized bool
  661. newRoot := m.root.delete(key, 0, m.hasher.Hash(key), m.hasher, mutable, &resized)
  662. if !resized {
  663. return m
  664. }
  665. // Generate copy if necessary.
  666. other := m
  667. if !mutable {
  668. other = m.clone()
  669. }
  670. // Return copy of map with new root and decreased size.
  671. other.size = m.size - 1
  672. other.root = newRoot
  673. return other
  674. }
  675. // Iterator returns a new iterator for the map.
  676. func (m *Map) Iterator() *MapIterator {
  677. itr := &MapIterator{m: m}
  678. itr.First()
  679. return itr
  680. }
  681. // MapBuilder represents an efficient builder for creating Maps.
  682. type MapBuilder struct {
  683. m *Map // current state
  684. }
  685. // NewMapBuilder returns a new instance of MapBuilder.
  686. func NewMapBuilder(hasher Hasher) *MapBuilder {
  687. return &MapBuilder{m: NewMap(hasher)}
  688. }
  689. // Map returns the underlying map. Only call once.
  690. // Builder is invalid after call. Will panic on second invocation.
  691. func (b *MapBuilder) Map() *Map {
  692. assert(b.m != nil, "immutable.SortedMapBuilder.Map(): duplicate call to fetch map")
  693. m := b.m
  694. b.m = nil
  695. return m
  696. }
  697. // Len returns the number of elements in the underlying map.
  698. func (b *MapBuilder) Len() int {
  699. assert(b.m != nil, "immutable.MapBuilder: builder invalid after Map() invocation")
  700. return b.m.Len()
  701. }
  702. // Get returns the value for the given key.
  703. func (b *MapBuilder) Get(key interface{}) (value interface{}, ok bool) {
  704. assert(b.m != nil, "immutable.MapBuilder: builder invalid after Map() invocation")
  705. return b.m.Get(key)
  706. }
  707. // Set sets the value of the given key. See Map.Set() for additional details.
  708. func (b *MapBuilder) Set(key, value interface{}) {
  709. assert(b.m != nil, "immutable.MapBuilder: builder invalid after Map() invocation")
  710. b.m = b.m.set(key, value, true)
  711. }
  712. // Delete removes the given key. See Map.Delete() for additional details.
  713. func (b *MapBuilder) Delete(key interface{}) {
  714. assert(b.m != nil, "immutable.MapBuilder: builder invalid after Map() invocation")
  715. b.m = b.m.delete(key, true)
  716. }
  717. // Iterator returns a new iterator for the underlying map.
  718. func (b *MapBuilder) Iterator() *MapIterator {
  719. assert(b.m != nil, "immutable.MapBuilder: builder invalid after Map() invocation")
  720. return b.m.Iterator()
  721. }
  722. // mapNode represents any node in the map tree.
  723. type mapNode interface {
  724. get(key interface{}, shift uint, keyHash uint32, h Hasher) (value interface{}, ok bool)
  725. set(key, value interface{}, shift uint, keyHash uint32, h Hasher, mutable bool, resized *bool) mapNode
  726. delete(key interface{}, shift uint, keyHash uint32, h Hasher, mutable bool, resized *bool) mapNode
  727. }
  728. var _ mapNode = (*mapArrayNode)(nil)
  729. var _ mapNode = (*mapBitmapIndexedNode)(nil)
  730. var _ mapNode = (*mapHashArrayNode)(nil)
  731. var _ mapNode = (*mapValueNode)(nil)
  732. var _ mapNode = (*mapHashCollisionNode)(nil)
  733. // mapLeafNode represents a node that stores a single key hash at the leaf of the map tree.
  734. type mapLeafNode interface {
  735. mapNode
  736. keyHashValue() uint32
  737. }
  738. var _ mapLeafNode = (*mapValueNode)(nil)
  739. var _ mapLeafNode = (*mapHashCollisionNode)(nil)
  740. // mapArrayNode is a map node that stores key/value pairs in a slice.
  741. // Entries are stored in insertion order. An array node expands into a bitmap
  742. // indexed node once a given threshold size is crossed.
  743. type mapArrayNode struct {
  744. entries []mapEntry
  745. }
  746. // indexOf returns the entry index of the given key. Returns -1 if key not found.
  747. func (n *mapArrayNode) indexOf(key interface{}, h Hasher) int {
  748. for i := range n.entries {
  749. if h.Equal(n.entries[i].key, key) {
  750. return i
  751. }
  752. }
  753. return -1
  754. }
  755. // get returns the value for the given key.
  756. func (n *mapArrayNode) get(key interface{}, shift uint, keyHash uint32, h Hasher) (value interface{}, ok bool) {
  757. i := n.indexOf(key, h)
  758. if i == -1 {
  759. return nil, false
  760. }
  761. return n.entries[i].value, true
  762. }
  763. // set inserts or updates the value for a given key. If the key is inserted and
  764. // the new size crosses the max size threshold, a bitmap indexed node is returned.
  765. func (n *mapArrayNode) set(key, value interface{}, shift uint, keyHash uint32, h Hasher, mutable bool, resized *bool) mapNode {
  766. idx := n.indexOf(key, h)
  767. // Mark as resized if the key doesn't exist.
  768. if idx == -1 {
  769. *resized = true
  770. }
  771. // If we are adding and it crosses the max size threshold, expand the node.
  772. // We do this by continually setting the entries to a value node and expanding.
  773. if idx == -1 && len(n.entries) >= maxArrayMapSize {
  774. var node mapNode = newMapValueNode(h.Hash(key), key, value)
  775. for _, entry := range n.entries {
  776. node = node.set(entry.key, entry.value, 0, h.Hash(entry.key), h, false, resized)
  777. }
  778. return node
  779. }
  780. // Update in-place if mutable.
  781. if mutable {
  782. if idx != -1 {
  783. n.entries[idx] = mapEntry{key, value}
  784. } else {
  785. n.entries = append(n.entries, mapEntry{key, value})
  786. }
  787. return n
  788. }
  789. // Update existing entry if a match is found.
  790. // Otherwise append to the end of the element list if it doesn't exist.
  791. var other mapArrayNode
  792. if idx != -1 {
  793. other.entries = make([]mapEntry, len(n.entries))
  794. copy(other.entries, n.entries)
  795. other.entries[idx] = mapEntry{key, value}
  796. } else {
  797. other.entries = make([]mapEntry, len(n.entries)+1)
  798. copy(other.entries, n.entries)
  799. other.entries[len(other.entries)-1] = mapEntry{key, value}
  800. }
  801. return &other
  802. }
  803. // delete removes the given key from the node. Returns the same node if key does
  804. // not exist. Returns a nil node when removing the last entry.
  805. func (n *mapArrayNode) delete(key interface{}, shift uint, keyHash uint32, h Hasher, mutable bool, resized *bool) mapNode {
  806. idx := n.indexOf(key, h)
  807. // Return original node if key does not exist.
  808. if idx == -1 {
  809. return n
  810. }
  811. *resized = true
  812. // Return nil if this node will contain no nodes.
  813. if len(n.entries) == 1 {
  814. return nil
  815. }
  816. // Update in-place, if mutable.
  817. if mutable {
  818. copy(n.entries[idx:], n.entries[idx+1:])
  819. n.entries[len(n.entries)-1] = mapEntry{}
  820. n.entries = n.entries[:len(n.entries)-1]
  821. return n
  822. }
  823. // Otherwise create a copy with the given entry removed.
  824. other := &mapArrayNode{entries: make([]mapEntry, len(n.entries)-1)}
  825. copy(other.entries[:idx], n.entries[:idx])
  826. copy(other.entries[idx:], n.entries[idx+1:])
  827. return other
  828. }
  829. // mapBitmapIndexedNode represents a map branch node with a variable number of
  830. // node slots and indexed using a bitmap. Indexes for the node slots are
  831. // calculated by counting the number of set bits before the target bit using popcount.
  832. type mapBitmapIndexedNode struct {
  833. bitmap uint32
  834. nodes []mapNode
  835. }
  836. // get returns the value for the given key.
  837. func (n *mapBitmapIndexedNode) get(key interface{}, shift uint, keyHash uint32, h Hasher) (value interface{}, ok bool) {
  838. bit := uint32(1) << ((keyHash >> shift) & mapNodeMask)
  839. if (n.bitmap & bit) == 0 {
  840. return nil, false
  841. }
  842. child := n.nodes[bits.OnesCount32(n.bitmap&(bit-1))]
  843. return child.get(key, shift+mapNodeBits, keyHash, h)
  844. }
  845. // set inserts or updates the value for the given key. If a new key is inserted
  846. // and the size crosses the max size threshold then a hash array node is returned.
  847. func (n *mapBitmapIndexedNode) set(key, value interface{}, shift uint, keyHash uint32, h Hasher, mutable bool, resized *bool) mapNode {
  848. // Extract the index for the bit segment of the key hash.
  849. keyHashFrag := (keyHash >> shift) & mapNodeMask
  850. // Determine the bit based on the hash index.
  851. bit := uint32(1) << keyHashFrag
  852. exists := (n.bitmap & bit) != 0
  853. // Mark as resized if the key doesn't exist.
  854. if !exists {
  855. *resized = true
  856. }
  857. // Find index of node based on popcount of bits before it.
  858. idx := bits.OnesCount32(n.bitmap & (bit - 1))
  859. // If the node already exists, delegate set operation to it.
  860. // If the node doesn't exist then create a simple value leaf node.
  861. var newNode mapNode
  862. if exists {
  863. newNode = n.nodes[idx].set(key, value, shift+mapNodeBits, keyHash, h, mutable, resized)
  864. } else {
  865. newNode = newMapValueNode(keyHash, key, value)
  866. }
  867. // Convert to a hash-array node once we exceed the max bitmap size.
  868. // Copy each node based on their bit position within the bitmap.
  869. if !exists && len(n.nodes) > maxBitmapIndexedSize {
  870. var other mapHashArrayNode
  871. for i := uint(0); i < uint(len(other.nodes)); i++ {
  872. if n.bitmap&(uint32(1)<<i) != 0 {
  873. other.nodes[i] = n.nodes[other.count]
  874. other.count++
  875. }
  876. }
  877. other.nodes[keyHashFrag] = newNode
  878. other.count++
  879. return &other
  880. }
  881. // Update in-place if mutable.
  882. if mutable {
  883. if exists {
  884. n.nodes[idx] = newNode
  885. } else {
  886. n.bitmap |= bit
  887. n.nodes = append(n.nodes, nil)
  888. copy(n.nodes[idx+1:], n.nodes[idx:])
  889. n.nodes[idx] = newNode
  890. }
  891. return n
  892. }
  893. // If node exists at given slot then overwrite it with new node.
  894. // Otherwise expand the node list and insert new node into appropriate position.
  895. other := &mapBitmapIndexedNode{bitmap: n.bitmap | bit}
  896. if exists {
  897. other.nodes = make([]mapNode, len(n.nodes))
  898. copy(other.nodes, n.nodes)
  899. other.nodes[idx] = newNode
  900. } else {
  901. other.nodes = make([]mapNode, len(n.nodes)+1)
  902. copy(other.nodes, n.nodes[:idx])
  903. other.nodes[idx] = newNode
  904. copy(other.nodes[idx+1:], n.nodes[idx:])
  905. }
  906. return other
  907. }
  908. // delete removes the key from the tree. If the key does not exist then the
  909. // original node is returned. If removing the last child node then a nil is
  910. // returned. Note that shrinking the node will not convert it to an array node.
  911. func (n *mapBitmapIndexedNode) delete(key interface{}, shift uint, keyHash uint32, h Hasher, mutable bool, resized *bool) mapNode {
  912. bit := uint32(1) << ((keyHash >> shift) & mapNodeMask)
  913. // Return original node if key does not exist.
  914. if (n.bitmap & bit) == 0 {
  915. return n
  916. }
  917. // Find index of node based on popcount of bits before it.
  918. idx := bits.OnesCount32(n.bitmap & (bit - 1))
  919. // Delegate delete to child node.
  920. child := n.nodes[idx]
  921. newChild := child.delete(key, shift+mapNodeBits, keyHash, h, mutable, resized)
  922. // Return original node if key doesn't exist in child.
  923. if !*resized {
  924. return n
  925. }
  926. // Remove if returned child has been deleted.
  927. if newChild == nil {
  928. // If we won't have any children then return nil.
  929. if len(n.nodes) == 1 {
  930. return nil
  931. }
  932. // Update in-place if mutable.
  933. if mutable {
  934. n.bitmap ^= bit
  935. copy(n.nodes[idx:], n.nodes[idx+1:])
  936. n.nodes[len(n.nodes)-1] = nil
  937. n.nodes = n.nodes[:len(n.nodes)-1]
  938. return n
  939. }
  940. // Return copy with bit removed from bitmap and node removed from node list.
  941. other := &mapBitmapIndexedNode{bitmap: n.bitmap ^ bit, nodes: make([]mapNode, len(n.nodes)-1)}
  942. copy(other.nodes[:idx], n.nodes[:idx])
  943. copy(other.nodes[idx:], n.nodes[idx+1:])
  944. return other
  945. }
  946. // Generate copy, if necessary.
  947. other := n
  948. if !mutable {
  949. other = &mapBitmapIndexedNode{bitmap: n.bitmap, nodes: make([]mapNode, len(n.nodes))}
  950. copy(other.nodes, n.nodes)
  951. }
  952. // Update child.
  953. other.nodes[idx] = newChild
  954. return other
  955. }
  956. // mapHashArrayNode is a map branch node that stores nodes in a fixed length
  957. // array. Child nodes are indexed by their index bit segment for the current depth.
  958. type mapHashArrayNode struct {
  959. count uint // number of set nodes
  960. nodes [mapNodeSize]mapNode // child node slots, may contain empties
  961. }
  962. // clone returns a shallow copy of n.
  963. func (n *mapHashArrayNode) clone() *mapHashArrayNode {
  964. other := *n
  965. return &other
  966. }
  967. // get returns the value for the given key.
  968. func (n *mapHashArrayNode) get(key interface{}, shift uint, keyHash uint32, h Hasher) (value interface{}, ok bool) {
  969. node := n.nodes[(keyHash>>shift)&mapNodeMask]
  970. if node == nil {
  971. return nil, false
  972. }
  973. return node.get(key, shift+mapNodeBits, keyHash, h)
  974. }
  975. // set returns a node with the value set for the given key.
  976. func (n *mapHashArrayNode) set(key, value interface{}, shift uint, keyHash uint32, h Hasher, mutable bool, resized *bool) mapNode {
  977. idx := (keyHash >> shift) & mapNodeMask
  978. node := n.nodes[idx]
  979. // If node at index doesn't exist, create a simple value leaf node.
  980. // Otherwise delegate set to child node.
  981. var newNode mapNode
  982. if node == nil {
  983. *resized = true
  984. newNode = newMapValueNode(keyHash, key, value)
  985. } else {
  986. newNode = node.set(key, value, shift+mapNodeBits, keyHash, h, mutable, resized)
  987. }
  988. // Generate copy, if necessary.
  989. other := n
  990. if !mutable {
  991. other = n.clone()
  992. }
  993. // Update child node (and update size, if new).
  994. if node == nil {
  995. other.count++
  996. }
  997. other.nodes[idx] = newNode
  998. return other
  999. }
  1000. // delete returns a node with the given key removed. Returns the same node if
  1001. // the key does not exist. If node shrinks to within bitmap-indexed size then
  1002. // converts to a bitmap-indexed node.
  1003. func (n *mapHashArrayNode) delete(key interface{}, shift uint, keyHash uint32, h Hasher, mutable bool, resized *bool) mapNode {
  1004. idx := (keyHash >> shift) & mapNodeMask
  1005. node := n.nodes[idx]
  1006. // Return original node if child is not found.
  1007. if node == nil {
  1008. return n
  1009. }
  1010. // Return original node if child is unchanged.
  1011. newNode := node.delete(key, shift+mapNodeBits, keyHash, h, mutable, resized)
  1012. if !*resized {
  1013. return n
  1014. }
  1015. // If we remove a node and drop below a threshold, convert back to bitmap indexed node.
  1016. if newNode == nil && n.count <= maxBitmapIndexedSize {
  1017. other := &mapBitmapIndexedNode{nodes: make([]mapNode, 0, n.count-1)}
  1018. for i, child := range n.nodes {
  1019. if child != nil && uint32(i) != idx {
  1020. other.bitmap |= 1 << uint(i)
  1021. other.nodes = append(other.nodes, child)
  1022. }
  1023. }
  1024. return other
  1025. }
  1026. // Generate copy, if necessary.
  1027. other := n
  1028. if !mutable {
  1029. other = n.clone()
  1030. }
  1031. // Return copy of node with child updated.
  1032. other.nodes[idx] = newNode
  1033. if newNode == nil {
  1034. other.count--
  1035. }
  1036. return other
  1037. }
  1038. // mapValueNode represents a leaf node with a single key/value pair.
  1039. // A value node can be converted to a hash collision leaf node if a different
  1040. // key with the same keyHash is inserted.
  1041. type mapValueNode struct {
  1042. keyHash uint32
  1043. key interface{}
  1044. value interface{}
  1045. }
  1046. // newMapValueNode returns a new instance of mapValueNode.
  1047. func newMapValueNode(keyHash uint32, key, value interface{}) *mapValueNode {
  1048. return &mapValueNode{
  1049. keyHash: keyHash,
  1050. key: key,
  1051. value: value,
  1052. }
  1053. }
  1054. // keyHashValue returns the key hash for this node.
  1055. func (n *mapValueNode) keyHashValue() uint32 {
  1056. return n.keyHash
  1057. }
  1058. // get returns the value for the given key.
  1059. func (n *mapValueNode) get(key interface{}, shift uint, keyHash uint32, h Hasher) (value interface{}, ok bool) {
  1060. if !h.Equal(n.key, key) {
  1061. return nil, false
  1062. }
  1063. return n.value, true
  1064. }
  1065. // set returns a new node with the new value set for the key. If the key equals
  1066. // the node's key then a new value node is returned. If key is not equal to the
  1067. // node's key but has the same hash then a hash collision node is returned.
  1068. // Otherwise the nodes are merged into a branch node.
  1069. func (n *mapValueNode) set(key, value interface{}, shift uint, keyHash uint32, h Hasher, mutable bool, resized *bool) mapNode {
  1070. // If the keys match then return a new value node overwriting the value.
  1071. if h.Equal(n.key, key) {
  1072. // Update in-place if mutable.
  1073. if mutable {
  1074. n.value = value
  1075. return n
  1076. }
  1077. // Otherwise return a new copy.
  1078. return newMapValueNode(n.keyHash, key, value)
  1079. }
  1080. *resized = true
  1081. // Recursively merge nodes together if key hashes are different.
  1082. if n.keyHash != keyHash {
  1083. return mergeIntoNode(n, shift, keyHash, key, value)
  1084. }
  1085. // Merge into collision node if hash matches.
  1086. return &mapHashCollisionNode{keyHash: keyHash, entries: []mapEntry{
  1087. {key: n.key, value: n.value},
  1088. {key: key, value: value},
  1089. }}
  1090. }
  1091. // delete returns nil if the key matches the node's key. Otherwise returns the original node.
  1092. func (n *mapValueNode) delete(key interface{}, shift uint, keyHash uint32, h Hasher, mutable bool, resized *bool) mapNode {
  1093. // Return original node if the keys do not match.
  1094. if !h.Equal(n.key, key) {
  1095. return n
  1096. }
  1097. // Otherwise remove the node if keys do match.
  1098. *resized = true
  1099. return nil
  1100. }
  1101. // mapHashCollisionNode represents a leaf node that contains two or more key/value
  1102. // pairs with the same key hash. Single pairs for a hash are stored as value nodes.
  1103. type mapHashCollisionNode struct {
  1104. keyHash uint32 // key hash for all entries
  1105. entries []mapEntry
  1106. }
  1107. // keyHashValue returns the key hash for all entries on the node.
  1108. func (n *mapHashCollisionNode) keyHashValue() uint32 {
  1109. return n.keyHash
  1110. }
  1111. // indexOf returns the index of the entry for the given key.
  1112. // Returns -1 if the key does not exist in the node.
  1113. func (n *mapHashCollisionNode) indexOf(key interface{}, h Hasher) int {
  1114. for i := range n.entries {
  1115. if h.Equal(n.entries[i].key, key) {
  1116. return i
  1117. }
  1118. }
  1119. return -1
  1120. }
  1121. // get returns the value for the given key.
  1122. func (n *mapHashCollisionNode) get(key interface{}, shift uint, keyHash uint32, h Hasher) (value interface{}, ok bool) {
  1123. for i := range n.entries {
  1124. if h.Equal(n.entries[i].key, key) {
  1125. return n.entries[i].value, true
  1126. }
  1127. }
  1128. return nil, false
  1129. }
  1130. // set returns a copy of the node with key set to the given value.
  1131. func (n *mapHashCollisionNode) set(key, value interface{}, shift uint, keyHash uint32, h Hasher, mutable bool, resized *bool) mapNode {
  1132. // Merge node with key/value pair if this is not a hash collision.
  1133. if n.keyHash != keyHash {
  1134. *resized = true
  1135. return mergeIntoNode(n, shift, keyHash, key, value)
  1136. }
  1137. // Update in-place if mutable.
  1138. if mutable {
  1139. if idx := n.indexOf(key, h); idx == -1 {
  1140. *resized = true
  1141. n.entries = append(n.entries, mapEntry{key, value})
  1142. } else {
  1143. n.entries[idx] = mapEntry{key, value}
  1144. }
  1145. return n
  1146. }
  1147. // Append to end of node if key doesn't exist & mark resized.
  1148. // Otherwise copy nodes and overwrite at matching key index.
  1149. other := &mapHashCollisionNode{keyHash: n.keyHash}
  1150. if idx := n.indexOf(key, h); idx == -1 {
  1151. *resized = true
  1152. other.entries = make([]mapEntry, len(n.entries)+1)
  1153. copy(other.entries, n.entries)
  1154. other.entries[len(other.entries)-1] = mapEntry{key, value}
  1155. } else {
  1156. other.entries = make([]mapEntry, len(n.entries))
  1157. copy(other.entries, n.entries)
  1158. other.entries[idx] = mapEntry{key, value}
  1159. }
  1160. return other
  1161. }
  1162. // delete returns a node with the given key deleted. Returns the same node if
  1163. // the key does not exist. If removing the key would shrink the node to a single
  1164. // entry then a value node is returned.
  1165. func (n *mapHashCollisionNode) delete(key interface{}, shift uint, keyHash uint32, h Hasher, mutable bool, resized *bool) mapNode {
  1166. idx := n.indexOf(key, h)
  1167. // Return original node if key is not found.
  1168. if idx == -1 {
  1169. return n
  1170. }
  1171. // Mark as resized if key exists.
  1172. *resized = true
  1173. // Convert to value node if we move to one entry.
  1174. if len(n.entries) == 2 {
  1175. return &mapValueNode{
  1176. keyHash: n.keyHash,
  1177. key: n.entries[idx^1].key,
  1178. value: n.entries[idx^1].value,
  1179. }
  1180. }
  1181. // Remove entry in-place if mutable.
  1182. if mutable {
  1183. copy(n.entries[idx:], n.entries[idx+1:])
  1184. n.entries[len(n.entries)-1] = mapEntry{}
  1185. n.entries = n.entries[:len(n.entries)-1]
  1186. return n
  1187. }
  1188. // Return copy without entry if immutable.
  1189. other := &mapHashCollisionNode{keyHash: n.keyHash, entries: make([]mapEntry, len(n.entries)-1)}
  1190. copy(other.entries[:idx], n.entries[:idx])
  1191. copy(other.entries[idx:], n.entries[idx+1:])
  1192. return other
  1193. }
  1194. // mergeIntoNode merges a key/value pair into an existing node.
  1195. // Caller must verify that node's keyHash is not equal to keyHash.
  1196. func mergeIntoNode(node mapLeafNode, shift uint, keyHash uint32, key, value interface{}) mapNode {
  1197. idx1 := (node.keyHashValue() >> shift) & mapNodeMask
  1198. idx2 := (keyHash >> shift) & mapNodeMask
  1199. // Recursively build branch nodes to combine the node and its key.
  1200. other := &mapBitmapIndexedNode{bitmap: (1 << idx1) | (1 << idx2)}
  1201. if idx1 == idx2 {
  1202. other.nodes = []mapNode{mergeIntoNode(node, shift+mapNodeBits, keyHash, key, value)}
  1203. } else {
  1204. if newNode := newMapValueNode(keyHash, key, value); idx1 < idx2 {
  1205. other.nodes = []mapNode{node, newNode}
  1206. } else {
  1207. other.nodes = []mapNode{newNode, node}
  1208. }
  1209. }
  1210. return other
  1211. }
  1212. // mapEntry represents a single key/value pair.
  1213. type mapEntry struct {
  1214. key interface{}
  1215. value interface{}
  1216. }
  1217. // MapIterator represents an iterator over a map's key/value pairs. Although
  1218. // map keys are not sorted, the iterator's order is deterministic.
  1219. type MapIterator struct {
  1220. m *Map // source map
  1221. stack [32]mapIteratorElem // search stack
  1222. depth int // stack depth
  1223. }
  1224. // Done returns true if no more elements remain in the iterator.
  1225. func (itr *MapIterator) Done() bool {
  1226. return itr.depth == -1
  1227. }
  1228. // First resets the iterator to the first key/value pair.
  1229. func (itr *MapIterator) First() {
  1230. // Exit immediately if the map is empty.
  1231. if itr.m.root == nil {
  1232. itr.depth = -1
  1233. return
  1234. }
  1235. // Initialize the stack to the left most element.
  1236. itr.stack[0] = mapIteratorElem{node: itr.m.root}
  1237. itr.depth = 0
  1238. itr.first()
  1239. }
  1240. // Next returns the next key/value pair. Returns a nil key when no elements remain.
  1241. func (itr *MapIterator) Next() (key, value interface{}) {
  1242. // Return nil key if iteration is done.
  1243. if itr.Done() {
  1244. return nil, nil
  1245. }
  1246. // Retrieve current index & value. Current node is always a leaf.
  1247. elem := &itr.stack[itr.depth]
  1248. switch node := elem.node.(type) {
  1249. case *mapArrayNode:
  1250. entry := &node.entries[elem.index]
  1251. key, value = entry.key, entry.value
  1252. case *mapValueNode:
  1253. key, value = node.key, node.value
  1254. case *mapHashCollisionNode:
  1255. entry := &node.entries[elem.index]
  1256. key, value = entry.key, entry.value
  1257. }
  1258. // Move up stack until we find a node that has remaining position ahead
  1259. // and move that element forward by one.
  1260. itr.next()
  1261. return key, value
  1262. }
  1263. // next moves to the next available key.
  1264. func (itr *MapIterator) next() {
  1265. for ; itr.depth >= 0; itr.depth-- {
  1266. elem := &itr.stack[itr.depth]
  1267. switch node := elem.node.(type) {
  1268. case *mapArrayNode:
  1269. if elem.index < len(node.entries)-1 {
  1270. elem.index++
  1271. return
  1272. }
  1273. case *mapBitmapIndexedNode:
  1274. if elem.index < len(node.nodes)-1 {
  1275. elem.index++
  1276. itr.stack[itr.depth+1].node = node.nodes[elem.index]
  1277. itr.depth++
  1278. itr.first()
  1279. return
  1280. }
  1281. case *mapHashArrayNode:
  1282. for i := elem.index + 1; i < len(node.nodes); i++ {
  1283. if node.nodes[i] != nil {
  1284. elem.index = i
  1285. itr.stack[itr.depth+1].node = node.nodes[elem.index]
  1286. itr.depth++
  1287. itr.first()
  1288. return
  1289. }
  1290. }
  1291. case *mapValueNode:
  1292. continue // always the last value, traverse up
  1293. case *mapHashCollisionNode:
  1294. if elem.index < len(node.entries)-1 {
  1295. elem.index++
  1296. return
  1297. }
  1298. }
  1299. }
  1300. }
  1301. // first positions the stack left most index.
  1302. // Elements and indexes at and below the current depth are assumed to be correct.
  1303. func (itr *MapIterator) first() {
  1304. for ; ; itr.depth++ {
  1305. elem := &itr.stack[itr.depth]
  1306. switch node := elem.node.(type) {
  1307. case *mapBitmapIndexedNode:
  1308. elem.index = 0
  1309. itr.stack[itr.depth+1].node = node.nodes[0]
  1310. case *mapHashArrayNode:
  1311. for i := 0; i < len(node.nodes); i++ {
  1312. if node.nodes[i] != nil { // find first node
  1313. elem.index = i
  1314. itr.stack[itr.depth+1].node = node.nodes[i]
  1315. break
  1316. }
  1317. }
  1318. default: // *mapArrayNode, mapLeafNode
  1319. elem.index = 0
  1320. return
  1321. }
  1322. }
  1323. }
  1324. // mapIteratorElem represents a node/index pair in the MapIterator stack.
  1325. type mapIteratorElem struct {
  1326. node mapNode
  1327. index int
  1328. }
  1329. // Sorted map child node limit size.
  1330. const (
  1331. sortedMapNodeSize = 32
  1332. )
  1333. // SortedMap represents a map of key/value pairs sorted by key. The sort order
  1334. // is determined by the Comparer used by the map.
  1335. //
  1336. // This map is implemented as a B+tree.
  1337. type SortedMap struct {
  1338. size int // total number of key/value pairs
  1339. root sortedMapNode // root of b+tree
  1340. comparer Comparer
  1341. }
  1342. // NewSortedMap returns a new instance of SortedMap. If comparer is nil then
  1343. // a default comparer is set after the first key is inserted. Default comparers
  1344. // exist for int, string, and byte slice keys.
  1345. func NewSortedMap(comparer Comparer) *SortedMap {
  1346. return &SortedMap{
  1347. comparer: comparer,
  1348. }
  1349. }
  1350. // Len returns the number of elements in the sorted map.
  1351. func (m *SortedMap) Len() int {
  1352. return m.size
  1353. }
  1354. // Get returns the value for a given key and a flag indicating if the key is set.
  1355. // The flag can be used to distinguish between a nil-set key versus an unset key.
  1356. func (m *SortedMap) Get(key interface{}) (interface{}, bool) {
  1357. if m.root == nil {
  1358. return nil, false
  1359. }
  1360. return m.root.get(key, m.comparer)
  1361. }
  1362. // Set returns a copy of the map with the key set to the given value.
  1363. func (m *SortedMap) Set(key, value interface{}) *SortedMap {
  1364. return m.set(key, value, false)
  1365. }
  1366. func (m *SortedMap) set(key, value interface{}, mutable bool) *SortedMap {
  1367. // Set a comparer on the first value if one does not already exist.
  1368. comparer := m.comparer
  1369. if comparer == nil {
  1370. comparer = NewComparer(key)
  1371. }
  1372. // Create copy, if necessary.
  1373. other := m
  1374. if !mutable {
  1375. other = m.clone()
  1376. }
  1377. other.comparer = comparer
  1378. // If no values are set then initialize with a leaf node.
  1379. if m.root == nil {
  1380. other.size = 1
  1381. other.root = &sortedMapLeafNode{entries: []mapEntry{{key: key, value: value}}}
  1382. return other
  1383. }
  1384. // Otherwise delegate to root node.
  1385. // If a split occurs then grow the tree from the root.
  1386. var resized bool
  1387. newRoot, splitNode := m.root.set(key, value, comparer, mutable, &resized)
  1388. if splitNode != nil {
  1389. newRoot = newSortedMapBranchNode(newRoot, splitNode)
  1390. }
  1391. // Update root and size (if resized).
  1392. other.size = m.size
  1393. other.root = newRoot
  1394. if resized {
  1395. other.size++
  1396. }
  1397. return other
  1398. }
  1399. // Delete returns a copy of the map with the key removed.
  1400. // Returns the original map if key does not exist.
  1401. func (m *SortedMap) Delete(key interface{}) *SortedMap {
  1402. return m.delete(key, false)
  1403. }
  1404. func (m *SortedMap) delete(key interface{}, mutable bool) *SortedMap {
  1405. // Return original map if no keys exist.
  1406. if m.root == nil {
  1407. return m
  1408. }
  1409. // If the delete did not change the node then return the original map.
  1410. var resized bool
  1411. newRoot := m.root.delete(key, m.comparer, mutable, &resized)
  1412. if !resized {
  1413. return m
  1414. }
  1415. // Create copy, if necessary.
  1416. other := m
  1417. if !mutable {
  1418. other = m.clone()
  1419. }
  1420. // Update root and size.
  1421. other.size = m.size - 1
  1422. other.root = newRoot
  1423. return other
  1424. }
  1425. // clone returns a shallow copy of m.
  1426. func (m *SortedMap) clone() *SortedMap {
  1427. other := *m
  1428. return &other
  1429. }
  1430. // Iterator returns a new iterator for this map positioned at the first key.
  1431. func (m *SortedMap) Iterator() *SortedMapIterator {
  1432. itr := &SortedMapIterator{m: m}
  1433. itr.First()
  1434. return itr
  1435. }
  1436. // SortedMapBuilder represents an efficient builder for creating sorted maps.
  1437. type SortedMapBuilder struct {
  1438. m *SortedMap // current state
  1439. }
  1440. // NewSortedMapBuilder returns a new instance of SortedMapBuilder.
  1441. func NewSortedMapBuilder(comparer Comparer) *SortedMapBuilder {
  1442. return &SortedMapBuilder{m: NewSortedMap(comparer)}
  1443. }
  1444. // SortedMap returns the current copy of the map.
  1445. // The returned map is safe to use even if after the builder continues to be used.
  1446. func (b *SortedMapBuilder) Map() *SortedMap {
  1447. assert(b.m != nil, "immutable.SortedMapBuilder.Map(): duplicate call to fetch map")
  1448. m := b.m
  1449. b.m = nil
  1450. return m
  1451. }
  1452. // Len returns the number of elements in the underlying map.
  1453. func (b *SortedMapBuilder) Len() int {
  1454. assert(b.m != nil, "immutable.SortedMapBuilder: builder invalid after Map() invocation")
  1455. return b.m.Len()
  1456. }
  1457. // Get returns the value for the given key.
  1458. func (b *SortedMapBuilder) Get(key interface{}) (value interface{}, ok bool) {
  1459. assert(b.m != nil, "immutable.SortedMapBuilder: builder invalid after Map() invocation")
  1460. return b.m.Get(key)
  1461. }
  1462. // Set sets the value of the given key. See SortedMap.Set() for additional details.
  1463. func (b *SortedMapBuilder) Set(key, value interface{}) {
  1464. assert(b.m != nil, "immutable.SortedMapBuilder: builder invalid after Map() invocation")
  1465. b.m = b.m.set(key, value, true)
  1466. }
  1467. // Delete removes the given key. See SortedMap.Delete() for additional details.
  1468. func (b *SortedMapBuilder) Delete(key interface{}) {
  1469. assert(b.m != nil, "immutable.SortedMapBuilder: builder invalid after Map() invocation")
  1470. b.m = b.m.delete(key, true)
  1471. }
  1472. // Iterator returns a new iterator for the underlying map positioned at the first key.
  1473. func (b *SortedMapBuilder) Iterator() *SortedMapIterator {
  1474. assert(b.m != nil, "immutable.SortedMapBuilder: builder invalid after Map() invocation")
  1475. return b.m.Iterator()
  1476. }
  1477. // sortedMapNode represents a branch or leaf node in the sorted map.
  1478. type sortedMapNode interface {
  1479. minKey() interface{}
  1480. indexOf(key interface{}, c Comparer) int
  1481. get(key interface{}, c Comparer) (value interface{}, ok bool)
  1482. set(key, value interface{}, c Comparer, mutable bool, resized *bool) (sortedMapNode, sortedMapNode)
  1483. delete(key interface{}, c Comparer, mutable bool, resized *bool) sortedMapNode
  1484. }
  1485. var _ sortedMapNode = (*sortedMapBranchNode)(nil)
  1486. var _ sortedMapNode = (*sortedMapLeafNode)(nil)
  1487. // sortedMapBranchNode represents a branch in the sorted map.
  1488. type sortedMapBranchNode struct {
  1489. elems []sortedMapBranchElem
  1490. }
  1491. // newSortedMapBranchNode returns a new branch node with the given child nodes.
  1492. func newSortedMapBranchNode(children ...sortedMapNode) *sortedMapBranchNode {
  1493. // Fetch min keys for every child.
  1494. elems := make([]sortedMapBranchElem, len(children))
  1495. for i, child := range children {
  1496. elems[i] = sortedMapBranchElem{
  1497. key: child.minKey(),
  1498. node: child,
  1499. }
  1500. }
  1501. return &sortedMapBranchNode{elems: elems}
  1502. }
  1503. // minKey returns the lowest key stored in this node's tree.
  1504. func (n *sortedMapBranchNode) minKey() interface{} {
  1505. return n.elems[0].node.minKey()
  1506. }
  1507. // indexOf returns the index of the key within the child nodes.
  1508. func (n *sortedMapBranchNode) indexOf(key interface{}, c Comparer) int {
  1509. if idx := sort.Search(len(n.elems), func(i int) bool { return c.Compare(n.elems[i].key, key) == 1 }); idx > 0 {
  1510. return idx - 1
  1511. }
  1512. return 0
  1513. }
  1514. // get returns the value for the given key.
  1515. func (n *sortedMapBranchNode) get(key interface{}, c Comparer) (value interface{}, ok bool) {
  1516. idx := n.indexOf(key, c)
  1517. return n.elems[idx].node.get(key, c)
  1518. }
  1519. // set returns a copy of the node with the key set to the given value.
  1520. func (n *sortedMapBranchNode) set(key, value interface{}, c Comparer, mutable bool, resized *bool) (sortedMapNode, sortedMapNode) {
  1521. idx := n.indexOf(key, c)
  1522. // Delegate insert to child node.
  1523. newNode, splitNode := n.elems[idx].node.set(key, value, c, mutable, resized)
  1524. // Update in-place, if mutable.
  1525. if mutable {
  1526. n.elems[idx] = sortedMapBranchElem{key: newNode.minKey(), node: newNode}
  1527. if splitNode != nil {
  1528. n.elems = append(n.elems, sortedMapBranchElem{})
  1529. copy(n.elems[idx+1:], n.elems[idx:])
  1530. n.elems[idx+1] = sortedMapBranchElem{key: splitNode.minKey(), node: splitNode}
  1531. }
  1532. // If the child splits and we have no more room then we split too.
  1533. if len(n.elems) > sortedMapNodeSize {
  1534. splitIdx := len(n.elems) / 2
  1535. newNode := &sortedMapBranchNode{elems: n.elems[:splitIdx:splitIdx]}
  1536. splitNode := &sortedMapBranchNode{elems: n.elems[splitIdx:]}
  1537. return newNode, splitNode
  1538. }
  1539. return n, nil
  1540. }
  1541. // If no split occurs, copy branch and update keys.
  1542. // If the child splits, insert new key/child into copy of branch.
  1543. var other sortedMapBranchNode
  1544. if splitNode == nil {
  1545. other.elems = make([]sortedMapBranchElem, len(n.elems))
  1546. copy(other.elems, n.elems)
  1547. other.elems[idx] = sortedMapBranchElem{
  1548. key: newNode.minKey(),
  1549. node: newNode,
  1550. }
  1551. } else {
  1552. other.elems = make([]sortedMapBranchElem, len(n.elems)+1)
  1553. copy(other.elems[:idx], n.elems[:idx])
  1554. copy(other.elems[idx+1:], n.elems[idx:])
  1555. other.elems[idx] = sortedMapBranchElem{
  1556. key: newNode.minKey(),
  1557. node: newNode,
  1558. }
  1559. other.elems[idx+1] = sortedMapBranchElem{
  1560. key: splitNode.minKey(),
  1561. node: splitNode,
  1562. }
  1563. }
  1564. // If the child splits and we have no more room then we split too.
  1565. if len(other.elems) > sortedMapNodeSize {
  1566. splitIdx := len(other.elems) / 2
  1567. newNode := &sortedMapBranchNode{elems: other.elems[:splitIdx:splitIdx]}
  1568. splitNode := &sortedMapBranchNode{elems: other.elems[splitIdx:]}
  1569. return newNode, splitNode
  1570. }
  1571. // Otherwise return the new branch node with the updated entry.
  1572. return &other, nil
  1573. }
  1574. // delete returns a node with the key removed. Returns the same node if the key
  1575. // does not exist. Returns nil if all child nodes are removed.
  1576. func (n *sortedMapBranchNode) delete(key interface{}, c Comparer, mutable bool, resized *bool) sortedMapNode {
  1577. idx := n.indexOf(key, c)
  1578. // Return original node if child has not changed.
  1579. newNode := n.elems[idx].node.delete(key, c, mutable, resized)
  1580. if !*resized {
  1581. return n
  1582. }
  1583. // Remove child if it is now nil.
  1584. if newNode == nil {
  1585. // If this node will become empty then simply return nil.
  1586. if len(n.elems) == 1 {
  1587. return nil
  1588. }
  1589. // If mutable, update in-place.
  1590. if mutable {
  1591. copy(n.elems[idx:], n.elems[idx+1:])
  1592. n.elems[len(n.elems)-1] = sortedMapBranchElem{}
  1593. n.elems = n.elems[:len(n.elems)-1]
  1594. return n
  1595. }
  1596. // Return a copy without the given node.
  1597. other := &sortedMapBranchNode{elems: make([]sortedMapBranchElem, len(n.elems)-1)}
  1598. copy(other.elems[:idx], n.elems[:idx])
  1599. copy(other.elems[idx:], n.elems[idx+1:])
  1600. return other
  1601. }
  1602. // If mutable, update in-place.
  1603. if mutable {
  1604. n.elems[idx] = sortedMapBranchElem{key: newNode.minKey(), node: newNode}
  1605. return n
  1606. }
  1607. // Return a copy with the updated node.
  1608. other := &sortedMapBranchNode{elems: make([]sortedMapBranchElem, len(n.elems))}
  1609. copy(other.elems, n.elems)
  1610. other.elems[idx] = sortedMapBranchElem{
  1611. key: newNode.minKey(),
  1612. node: newNode,
  1613. }
  1614. return other
  1615. }
  1616. type sortedMapBranchElem struct {
  1617. key interface{}
  1618. node sortedMapNode
  1619. }
  1620. // sortedMapLeafNode represents a leaf node in the sorted map.
  1621. type sortedMapLeafNode struct {
  1622. entries []mapEntry
  1623. }
  1624. // minKey returns the first key stored in this node.
  1625. func (n *sortedMapLeafNode) minKey() interface{} {
  1626. return n.entries[0].key
  1627. }
  1628. // indexOf returns the index of the given key.
  1629. func (n *sortedMapLeafNode) indexOf(key interface{}, c Comparer) int {
  1630. return sort.Search(len(n.entries), func(i int) bool {
  1631. return c.Compare(n.entries[i].key, key) != -1 // GTE
  1632. })
  1633. }
  1634. // get returns the value of the given key.
  1635. func (n *sortedMapLeafNode) get(key interface{}, c Comparer) (value interface{}, ok bool) {
  1636. idx := n.indexOf(key, c)
  1637. // If the index is beyond the entry count or the key is not equal then return 'not found'.
  1638. if idx == len(n.entries) || c.Compare(n.entries[idx].key, key) != 0 {
  1639. return nil, false
  1640. }
  1641. // If the key matches then return its value.
  1642. return n.entries[idx].value, true
  1643. }
  1644. // set returns a copy of node with the key set to the given value. If the update
  1645. // causes the node to grow beyond the maximum size then it is split in two.
  1646. func (n *sortedMapLeafNode) set(key, value interface{}, c Comparer, mutable bool, resized *bool) (sortedMapNode, sortedMapNode) {
  1647. // Find the insertion index for the key.
  1648. idx := n.indexOf(key, c)
  1649. exists := idx < len(n.entries) && c.Compare(n.entries[idx].key, key) == 0
  1650. // Update in-place, if mutable.
  1651. if mutable {
  1652. if !exists {
  1653. *resized = true
  1654. n.entries = append(n.entries, mapEntry{})
  1655. copy(n.entries[idx+1:], n.entries[idx:])
  1656. }
  1657. n.entries[idx] = mapEntry{key: key, value: value}
  1658. // If the key doesn't exist and we exceed our max allowed values then split.
  1659. if len(n.entries) > sortedMapNodeSize {
  1660. splitIdx := len(n.entries) / 2
  1661. newNode := &sortedMapLeafNode{entries: n.entries[:splitIdx:splitIdx]}
  1662. splitNode := &sortedMapLeafNode{entries: n.entries[splitIdx:]}
  1663. return newNode, splitNode
  1664. }
  1665. return n, nil
  1666. }
  1667. // If the key matches then simply return a copy with the entry overridden.
  1668. // If there is no match then insert new entry and mark as resized.
  1669. var newEntries []mapEntry
  1670. if exists {
  1671. newEntries = make([]mapEntry, len(n.entries))
  1672. copy(newEntries, n.entries)
  1673. newEntries[idx] = mapEntry{key: key, value: value}
  1674. } else {
  1675. *resized = true
  1676. newEntries = make([]mapEntry, len(n.entries)+1)
  1677. copy(newEntries[:idx], n.entries[:idx])
  1678. newEntries[idx] = mapEntry{key: key, value: value}
  1679. copy(newEntries[idx+1:], n.entries[idx:])
  1680. }
  1681. // If the key doesn't exist and we exceed our max allowed values then split.
  1682. if len(newEntries) > sortedMapNodeSize {
  1683. splitIdx := len(newEntries) / 2
  1684. newNode := &sortedMapLeafNode{entries: newEntries[:splitIdx:splitIdx]}
  1685. splitNode := &sortedMapLeafNode{entries: newEntries[splitIdx:]}
  1686. return newNode, splitNode
  1687. }
  1688. // Otherwise return the new leaf node with the updated entry.
  1689. return &sortedMapLeafNode{entries: newEntries}, nil
  1690. }
  1691. // delete returns a copy of node with key removed. Returns the original node if
  1692. // the key does not exist. Returns nil if the removed key is the last remaining key.
  1693. func (n *sortedMapLeafNode) delete(key interface{}, c Comparer, mutable bool, resized *bool) sortedMapNode {
  1694. idx := n.indexOf(key, c)
  1695. // Return original node if key is not found.
  1696. if idx >= len(n.entries) || c.Compare(n.entries[idx].key, key) != 0 {
  1697. return n
  1698. }
  1699. *resized = true
  1700. // If this is the last entry then return nil.
  1701. if len(n.entries) == 1 {
  1702. return nil
  1703. }
  1704. // Update in-place, if mutable.
  1705. if mutable {
  1706. copy(n.entries[idx:], n.entries[idx+1:])
  1707. n.entries[len(n.entries)-1] = mapEntry{}
  1708. n.entries = n.entries[:len(n.entries)-1]
  1709. return n
  1710. }
  1711. // Return copy of node with entry removed.
  1712. other := &sortedMapLeafNode{entries: make([]mapEntry, len(n.entries)-1)}
  1713. copy(other.entries[:idx], n.entries[:idx])
  1714. copy(other.entries[idx:], n.entries[idx+1:])
  1715. return other
  1716. }
  1717. // SortedMapIterator represents an iterator over a sorted map.
  1718. // Iteration can occur in natural or reverse order based on use of Next() or Prev().
  1719. type SortedMapIterator struct {
  1720. m *SortedMap // source map
  1721. stack [32]sortedMapIteratorElem // search stack
  1722. depth int // stack depth
  1723. }
  1724. // Done returns true if no more key/value pairs remain in the iterator.
  1725. func (itr *SortedMapIterator) Done() bool {
  1726. return itr.depth == -1
  1727. }
  1728. // First moves the iterator to the first key/value pair.
  1729. func (itr *SortedMapIterator) First() {
  1730. if itr.m.root == nil {
  1731. itr.depth = -1
  1732. return
  1733. }
  1734. itr.stack[0] = sortedMapIteratorElem{node: itr.m.root}
  1735. itr.depth = 0
  1736. itr.first()
  1737. }
  1738. // Last moves the iterator to the last key/value pair.
  1739. func (itr *SortedMapIterator) Last() {
  1740. if itr.m.root == nil {
  1741. itr.depth = -1
  1742. return
  1743. }
  1744. itr.stack[0] = sortedMapIteratorElem{node: itr.m.root}
  1745. itr.depth = 0
  1746. itr.last()
  1747. }
  1748. // Seek moves the iterator position to the given key in the map.
  1749. // If the key does not exist then the next key is used. If no more keys exist
  1750. // then the iteartor is marked as done.
  1751. func (itr *SortedMapIterator) Seek(key interface{}) {
  1752. if itr.m.root == nil {
  1753. itr.depth = -1
  1754. return
  1755. }
  1756. itr.stack[0] = sortedMapIteratorElem{node: itr.m.root}
  1757. itr.depth = 0
  1758. itr.seek(key)
  1759. }
  1760. // Next returns the current key/value pair and moves the iterator forward.
  1761. // Returns a nil key if the there are no more elements to return.
  1762. func (itr *SortedMapIterator) Next() (key, value interface{}) {
  1763. // Return nil key if iteration is complete.
  1764. if itr.Done() {
  1765. return nil, nil
  1766. }
  1767. // Retrieve current key/value pair.
  1768. leafElem := &itr.stack[itr.depth]
  1769. leafNode := leafElem.node.(*sortedMapLeafNode)
  1770. leafEntry := &leafNode.entries[leafElem.index]
  1771. key, value = leafEntry.key, leafEntry.value
  1772. // Move to the next available key/value pair.
  1773. itr.next()
  1774. // Only occurs when iterator is done.
  1775. return key, value
  1776. }
  1777. // next moves to the next key. If no keys are after then depth is set to -1.
  1778. func (itr *SortedMapIterator) next() {
  1779. for ; itr.depth >= 0; itr.depth-- {
  1780. elem := &itr.stack[itr.depth]
  1781. switch node := elem.node.(type) {
  1782. case *sortedMapLeafNode:
  1783. if elem.index < len(node.entries)-1 {
  1784. elem.index++
  1785. return
  1786. }
  1787. case *sortedMapBranchNode:
  1788. if elem.index < len(node.elems)-1 {
  1789. elem.index++
  1790. itr.stack[itr.depth+1].node = node.elems[elem.index].node
  1791. itr.depth++
  1792. itr.first()
  1793. return
  1794. }
  1795. }
  1796. }
  1797. }
  1798. // Prev returns the current key/value pair and moves the iterator backward.
  1799. // Returns a nil key if the there are no more elements to return.
  1800. func (itr *SortedMapIterator) Prev() (key, value interface{}) {
  1801. // Return nil key if iteration is complete.
  1802. if itr.Done() {
  1803. return nil, nil
  1804. }
  1805. // Retrieve current key/value pair.
  1806. leafElem := &itr.stack[itr.depth]
  1807. leafNode := leafElem.node.(*sortedMapLeafNode)
  1808. leafEntry := &leafNode.entries[leafElem.index]
  1809. key, value = leafEntry.key, leafEntry.value
  1810. itr.prev()
  1811. return key, value
  1812. }
  1813. // prev moves to the previous key. If no keys are before then depth is set to -1.
  1814. func (itr *SortedMapIterator) prev() {
  1815. for ; itr.depth >= 0; itr.depth-- {
  1816. elem := &itr.stack[itr.depth]
  1817. switch node := elem.node.(type) {
  1818. case *sortedMapLeafNode:
  1819. if elem.index > 0 {
  1820. elem.index--
  1821. return
  1822. }
  1823. case *sortedMapBranchNode:
  1824. if elem.index > 0 {
  1825. elem.index--
  1826. itr.stack[itr.depth+1].node = node.elems[elem.index].node
  1827. itr.depth++
  1828. itr.last()
  1829. return
  1830. }
  1831. }
  1832. }
  1833. }
  1834. // first positions the stack to the leftmost key from the current depth.
  1835. // Elements and indexes below the current depth are assumed to be correct.
  1836. func (itr *SortedMapIterator) first() {
  1837. for {
  1838. elem := &itr.stack[itr.depth]
  1839. elem.index = 0
  1840. switch node := elem.node.(type) {
  1841. case *sortedMapBranchNode:
  1842. itr.stack[itr.depth+1] = sortedMapIteratorElem{node: node.elems[elem.index].node}
  1843. itr.depth++
  1844. case *sortedMapLeafNode:
  1845. return
  1846. }
  1847. }
  1848. }
  1849. // last positions the stack to the rightmost key from the current depth.
  1850. // Elements and indexes below the current depth are assumed to be correct.
  1851. func (itr *SortedMapIterator) last() {
  1852. for {
  1853. elem := &itr.stack[itr.depth]
  1854. switch node := elem.node.(type) {
  1855. case *sortedMapBranchNode:
  1856. elem.index = len(node.elems) - 1
  1857. itr.stack[itr.depth+1] = sortedMapIteratorElem{node: node.elems[elem.index].node}
  1858. itr.depth++
  1859. case *sortedMapLeafNode:
  1860. elem.index = len(node.entries) - 1
  1861. return
  1862. }
  1863. }
  1864. }
  1865. // seek positions the stack to the given key from the current depth.
  1866. // Elements and indexes below the current depth are assumed to be correct.
  1867. func (itr *SortedMapIterator) seek(key interface{}) {
  1868. for {
  1869. elem := &itr.stack[itr.depth]
  1870. elem.index = elem.node.indexOf(key, itr.m.comparer)
  1871. switch node := elem.node.(type) {
  1872. case *sortedMapBranchNode:
  1873. itr.stack[itr.depth+1] = sortedMapIteratorElem{node: node.elems[elem.index].node}
  1874. itr.depth++
  1875. case *sortedMapLeafNode:
  1876. if elem.index == len(node.entries) {
  1877. itr.next()
  1878. }
  1879. return
  1880. }
  1881. }
  1882. }
  1883. // sortedMapIteratorElem represents node/index pair in the SortedMapIterator stack.
  1884. type sortedMapIteratorElem struct {
  1885. node sortedMapNode
  1886. index int
  1887. }
  1888. // Hasher hashes keys and checks them for equality.
  1889. type Hasher interface {
  1890. // Computes a 32-bit hash for key.
  1891. Hash(key interface{}) uint32
  1892. // Returns true if a and b are equal.
  1893. Equal(a, b interface{}) bool
  1894. }
  1895. // NewHasher returns the built-in hasher for a given key type.
  1896. func NewHasher(key interface{}) Hasher {
  1897. // Attempt to use non-reflection based hasher first.
  1898. switch key.(type) {
  1899. case int:
  1900. return &intHasher{}
  1901. case int8:
  1902. return &int8Hasher{}
  1903. case int16:
  1904. return &int16Hasher{}
  1905. case int32:
  1906. return &int32Hasher{}
  1907. case int64:
  1908. return &int64Hasher{}
  1909. case uint:
  1910. return &uintHasher{}
  1911. case uint8:
  1912. return &uint8Hasher{}
  1913. case uint16:
  1914. return &uint16Hasher{}
  1915. case uint32:
  1916. return &uint32Hasher{}
  1917. case uint64:
  1918. return &uint64Hasher{}
  1919. case string:
  1920. return &stringHasher{}
  1921. case []byte:
  1922. return &byteSliceHasher{}
  1923. }
  1924. // Fallback to reflection-based hasher otherwise.
  1925. // This is used when caller wraps a type around a primitive type.
  1926. switch reflect.TypeOf(key).Kind() {
  1927. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  1928. return &reflectIntHasher{}
  1929. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  1930. return &reflectUintHasher{}
  1931. case reflect.String:
  1932. return &reflectStringHasher{}
  1933. }
  1934. // If no hashers match then panic.
  1935. // This is a compile time issue so it should not return an error.
  1936. panic(fmt.Sprintf("immutable.NewHasher: must set hasher for %T type", key))
  1937. }
  1938. // intHasher implements Hasher for int keys.
  1939. type intHasher struct{}
  1940. // Hash returns a hash for key.
  1941. func (h *intHasher) Hash(key interface{}) uint32 {
  1942. return hashUint64(uint64(key.(int)))
  1943. }
  1944. // Equal returns true if a is equal to b. Otherwise returns false.
  1945. // Panics if a and b are not ints.
  1946. func (h *intHasher) Equal(a, b interface{}) bool {
  1947. return a.(int) == b.(int)
  1948. }
  1949. // int8Hasher implements Hasher for int8 keys.
  1950. type int8Hasher struct{}
  1951. // Hash returns a hash for key.
  1952. func (h *int8Hasher) Hash(key interface{}) uint32 {
  1953. return hashUint64(uint64(key.(int8)))
  1954. }
  1955. // Equal returns true if a is equal to b. Otherwise returns false.
  1956. // Panics if a and b are not int8s.
  1957. func (h *int8Hasher) Equal(a, b interface{}) bool {
  1958. return a.(int8) == b.(int8)
  1959. }
  1960. // int16Hasher implements Hasher for int16 keys.
  1961. type int16Hasher struct{}
  1962. // Hash returns a hash for key.
  1963. func (h *int16Hasher) Hash(key interface{}) uint32 {
  1964. return hashUint64(uint64(key.(int16)))
  1965. }
  1966. // Equal returns true if a is equal to b. Otherwise returns false.
  1967. // Panics if a and b are not int16s.
  1968. func (h *int16Hasher) Equal(a, b interface{}) bool {
  1969. return a.(int16) == b.(int16)
  1970. }
  1971. // int32Hasher implements Hasher for int32 keys.
  1972. type int32Hasher struct{}
  1973. // Hash returns a hash for key.
  1974. func (h *int32Hasher) Hash(key interface{}) uint32 {
  1975. return hashUint64(uint64(key.(int32)))
  1976. }
  1977. // Equal returns true if a is equal to b. Otherwise returns false.
  1978. // Panics if a and b are not int32s.
  1979. func (h *int32Hasher) Equal(a, b interface{}) bool {
  1980. return a.(int32) == b.(int32)
  1981. }
  1982. // int64Hasher implements Hasher for int64 keys.
  1983. type int64Hasher struct{}
  1984. // Hash returns a hash for key.
  1985. func (h *int64Hasher) Hash(key interface{}) uint32 {
  1986. return hashUint64(uint64(key.(int64)))
  1987. }
  1988. // Equal returns true if a is equal to b. Otherwise returns false.
  1989. // Panics if a and b are not int64s.
  1990. func (h *int64Hasher) Equal(a, b interface{}) bool {
  1991. return a.(int64) == b.(int64)
  1992. }
  1993. // uintHasher implements Hasher for uint keys.
  1994. type uintHasher struct{}
  1995. // Hash returns a hash for key.
  1996. func (h *uintHasher) Hash(key interface{}) uint32 {
  1997. return hashUint64(uint64(key.(uint)))
  1998. }
  1999. // Equal returns true if a is equal to b. Otherwise returns false.
  2000. // Panics if a and b are not uints.
  2001. func (h *uintHasher) Equal(a, b interface{}) bool {
  2002. return a.(uint) == b.(uint)
  2003. }
  2004. // uint8Hasher implements Hasher for uint8 keys.
  2005. type uint8Hasher struct{}
  2006. // Hash returns a hash for key.
  2007. func (h *uint8Hasher) Hash(key interface{}) uint32 {
  2008. return hashUint64(uint64(key.(uint8)))
  2009. }
  2010. // Equal returns true if a is equal to b. Otherwise returns false.
  2011. // Panics if a and b are not uint8s.
  2012. func (h *uint8Hasher) Equal(a, b interface{}) bool {
  2013. return a.(uint8) == b.(uint8)
  2014. }
  2015. // uint16Hasher implements Hasher for uint16 keys.
  2016. type uint16Hasher struct{}
  2017. // Hash returns a hash for key.
  2018. func (h *uint16Hasher) Hash(key interface{}) uint32 {
  2019. return hashUint64(uint64(key.(uint16)))
  2020. }
  2021. // Equal returns true if a is equal to b. Otherwise returns false.
  2022. // Panics if a and b are not uint16s.
  2023. func (h *uint16Hasher) Equal(a, b interface{}) bool {
  2024. return a.(uint16) == b.(uint16)
  2025. }
  2026. // uint32Hasher implements Hasher for uint32 keys.
  2027. type uint32Hasher struct{}
  2028. // Hash returns a hash for key.
  2029. func (h *uint32Hasher) Hash(key interface{}) uint32 {
  2030. return hashUint64(uint64(key.(uint32)))
  2031. }
  2032. // Equal returns true if a is equal to b. Otherwise returns false.
  2033. // Panics if a and b are not uint32s.
  2034. func (h *uint32Hasher) Equal(a, b interface{}) bool {
  2035. return a.(uint32) == b.(uint32)
  2036. }
  2037. // uint64Hasher implements Hasher for uint64 keys.
  2038. type uint64Hasher struct{}
  2039. // Hash returns a hash for key.
  2040. func (h *uint64Hasher) Hash(key interface{}) uint32 {
  2041. return hashUint64(key.(uint64))
  2042. }
  2043. // Equal returns true if a is equal to b. Otherwise returns false.
  2044. // Panics if a and b are not uint64s.
  2045. func (h *uint64Hasher) Equal(a, b interface{}) bool {
  2046. return a.(uint64) == b.(uint64)
  2047. }
  2048. // stringHasher implements Hasher for string keys.
  2049. type stringHasher struct{}
  2050. // Hash returns a hash for value.
  2051. func (h *stringHasher) Hash(value interface{}) uint32 {
  2052. var hash uint32
  2053. for i, value := 0, value.(string); i < len(value); i++ {
  2054. hash = 31*hash + uint32(value[i])
  2055. }
  2056. return hash
  2057. }
  2058. // Equal returns true if a is equal to b. Otherwise returns false.
  2059. // Panics if a and b are not strings.
  2060. func (h *stringHasher) Equal(a, b interface{}) bool {
  2061. return a.(string) == b.(string)
  2062. }
  2063. // byteSliceHasher implements Hasher for byte slice keys.
  2064. type byteSliceHasher struct{}
  2065. // Hash returns a hash for value.
  2066. func (h *byteSliceHasher) Hash(value interface{}) uint32 {
  2067. var hash uint32
  2068. for i, value := 0, value.([]byte); i < len(value); i++ {
  2069. hash = 31*hash + uint32(value[i])
  2070. }
  2071. return hash
  2072. }
  2073. // Equal returns true if a is equal to b. Otherwise returns false.
  2074. // Panics if a and b are not byte slices.
  2075. func (h *byteSliceHasher) Equal(a, b interface{}) bool {
  2076. return bytes.Equal(a.([]byte), b.([]byte))
  2077. }
  2078. // reflectIntHasher implements a reflection-based Hasher for int keys.
  2079. type reflectIntHasher struct{}
  2080. // Hash returns a hash for key.
  2081. func (h *reflectIntHasher) Hash(key interface{}) uint32 {
  2082. return hashUint64(uint64(reflect.ValueOf(key).Int()))
  2083. }
  2084. // Equal returns true if a is equal to b. Otherwise returns false.
  2085. // Panics if a and b are not ints.
  2086. func (h *reflectIntHasher) Equal(a, b interface{}) bool {
  2087. return reflect.ValueOf(a).Int() == reflect.ValueOf(b).Int()
  2088. }
  2089. // reflectUintHasher implements a reflection-based Hasher for uint keys.
  2090. type reflectUintHasher struct{}
  2091. // Hash returns a hash for key.
  2092. func (h *reflectUintHasher) Hash(key interface{}) uint32 {
  2093. return hashUint64(reflect.ValueOf(key).Uint())
  2094. }
  2095. // Equal returns true if a is equal to b. Otherwise returns false.
  2096. // Panics if a and b are not ints.
  2097. func (h *reflectUintHasher) Equal(a, b interface{}) bool {
  2098. return reflect.ValueOf(a).Uint() == reflect.ValueOf(b).Uint()
  2099. }
  2100. // reflectStringHasher implements a refletion-based Hasher for string keys.
  2101. type reflectStringHasher struct{}
  2102. // Hash returns a hash for value.
  2103. func (h *reflectStringHasher) Hash(value interface{}) uint32 {
  2104. var hash uint32
  2105. s := reflect.ValueOf(value).String()
  2106. for i := 0; i < len(s); i++ {
  2107. hash = 31*hash + uint32(s[i])
  2108. }
  2109. return hash
  2110. }
  2111. // Equal returns true if a is equal to b. Otherwise returns false.
  2112. // Panics if a and b are not strings.
  2113. func (h *reflectStringHasher) Equal(a, b interface{}) bool {
  2114. return reflect.ValueOf(a).String() == reflect.ValueOf(b).String()
  2115. }
  2116. // hashUint64 returns a 32-bit hash for a 64-bit value.
  2117. func hashUint64(value uint64) uint32 {
  2118. hash := value
  2119. for value > 0xffffffff {
  2120. value /= 0xffffffff
  2121. hash ^= value
  2122. }
  2123. return uint32(hash)
  2124. }
  2125. // Comparer allows the comparison of two keys for the purpose of sorting.
  2126. type Comparer interface {
  2127. // Returns -1 if a is less than b, returns 1 if a is greater than b,
  2128. // and returns 0 if a is equal to b.
  2129. Compare(a, b interface{}) int
  2130. }
  2131. // NewComparer returns the built-in comparer for a given key type.
  2132. func NewComparer(key interface{}) Comparer {
  2133. // Attempt to use non-reflection based comparer first.
  2134. switch key.(type) {
  2135. case int:
  2136. return &intComparer{}
  2137. case int8:
  2138. return &int8Comparer{}
  2139. case int16:
  2140. return &int16Comparer{}
  2141. case int32:
  2142. return &int32Comparer{}
  2143. case int64:
  2144. return &int64Comparer{}
  2145. case uint:
  2146. return &uintComparer{}
  2147. case uint8:
  2148. return &uint8Comparer{}
  2149. case uint16:
  2150. return &uint16Comparer{}
  2151. case uint32:
  2152. return &uint32Comparer{}
  2153. case uint64:
  2154. return &uint64Comparer{}
  2155. case string:
  2156. return &stringComparer{}
  2157. case []byte:
  2158. return &byteSliceComparer{}
  2159. }
  2160. // Fallback to reflection-based comparer otherwise.
  2161. // This is used when caller wraps a type around a primitive type.
  2162. switch reflect.TypeOf(key).Kind() {
  2163. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  2164. return &reflectIntComparer{}
  2165. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  2166. return &reflectUintComparer{}
  2167. case reflect.String:
  2168. return &reflectStringComparer{}
  2169. }
  2170. // If no comparers match then panic.
  2171. // This is a compile time issue so it should not return an error.
  2172. panic(fmt.Sprintf("immutable.NewComparer: must set comparer for %T type", key))
  2173. }
  2174. // intComparer compares two integers. Implements Comparer.
  2175. type intComparer struct{}
  2176. // Compare returns -1 if a is less than b, returns 1 if a is greater than b, and
  2177. // returns 0 if a is equal to b. Panic if a or b is not an int.
  2178. func (c *intComparer) Compare(a, b interface{}) int {
  2179. if i, j := a.(int), b.(int); i < j {
  2180. return -1
  2181. } else if i > j {
  2182. return 1
  2183. }
  2184. return 0
  2185. }
  2186. // int8Comparer compares two int8 values. Implements Comparer.
  2187. type int8Comparer struct{}
  2188. // Compare returns -1 if a is less than b, returns 1 if a is greater than b, and
  2189. // returns 0 if a is equal to b. Panic if a or b is not an int8.
  2190. func (c *int8Comparer) Compare(a, b interface{}) int {
  2191. if i, j := a.(int8), b.(int8); i < j {
  2192. return -1
  2193. } else if i > j {
  2194. return 1
  2195. }
  2196. return 0
  2197. }
  2198. // int16Comparer compares two int16 values. Implements Comparer.
  2199. type int16Comparer struct{}
  2200. // Compare returns -1 if a is less than b, returns 1 if a is greater than b, and
  2201. // returns 0 if a is equal to b. Panic if a or b is not an int16.
  2202. func (c *int16Comparer) Compare(a, b interface{}) int {
  2203. if i, j := a.(int16), b.(int16); i < j {
  2204. return -1
  2205. } else if i > j {
  2206. return 1
  2207. }
  2208. return 0
  2209. }
  2210. // int32Comparer compares two int32 values. Implements Comparer.
  2211. type int32Comparer struct{}
  2212. // Compare returns -1 if a is less than b, returns 1 if a is greater than b, and
  2213. // returns 0 if a is equal to b. Panic if a or b is not an int32.
  2214. func (c *int32Comparer) Compare(a, b interface{}) int {
  2215. if i, j := a.(int32), b.(int32); i < j {
  2216. return -1
  2217. } else if i > j {
  2218. return 1
  2219. }
  2220. return 0
  2221. }
  2222. // int64Comparer compares two int64 values. Implements Comparer.
  2223. type int64Comparer struct{}
  2224. // Compare returns -1 if a is less than b, returns 1 if a is greater than b, and
  2225. // returns 0 if a is equal to b. Panic if a or b is not an int64.
  2226. func (c *int64Comparer) Compare(a, b interface{}) int {
  2227. if i, j := a.(int64), b.(int64); i < j {
  2228. return -1
  2229. } else if i > j {
  2230. return 1
  2231. }
  2232. return 0
  2233. }
  2234. // uintComparer compares two uint values. Implements Comparer.
  2235. type uintComparer struct{}
  2236. // Compare returns -1 if a is less than b, returns 1 if a is greater than b, and
  2237. // returns 0 if a is equal to b. Panic if a or b is not an uint.
  2238. func (c *uintComparer) Compare(a, b interface{}) int {
  2239. if i, j := a.(uint), b.(uint); i < j {
  2240. return -1
  2241. } else if i > j {
  2242. return 1
  2243. }
  2244. return 0
  2245. }
  2246. // uint8Comparer compares two uint8 values. Implements Comparer.
  2247. type uint8Comparer struct{}
  2248. // Compare returns -1 if a is less than b, returns 1 if a is greater than b, and
  2249. // returns 0 if a is equal to b. Panic if a or b is not an uint8.
  2250. func (c *uint8Comparer) Compare(a, b interface{}) int {
  2251. if i, j := a.(uint8), b.(uint8); i < j {
  2252. return -1
  2253. } else if i > j {
  2254. return 1
  2255. }
  2256. return 0
  2257. }
  2258. // uint16Comparer compares two uint16 values. Implements Comparer.
  2259. type uint16Comparer struct{}
  2260. // Compare returns -1 if a is less than b, returns 1 if a is greater than b, and
  2261. // returns 0 if a is equal to b. Panic if a or b is not an uint16.
  2262. func (c *uint16Comparer) Compare(a, b interface{}) int {
  2263. if i, j := a.(uint16), b.(uint16); i < j {
  2264. return -1
  2265. } else if i > j {
  2266. return 1
  2267. }
  2268. return 0
  2269. }
  2270. // uint32Comparer compares two uint32 values. Implements Comparer.
  2271. type uint32Comparer struct{}
  2272. // Compare returns -1 if a is less than b, returns 1 if a is greater than b, and
  2273. // returns 0 if a is equal to b. Panic if a or b is not an uint32.
  2274. func (c *uint32Comparer) Compare(a, b interface{}) int {
  2275. if i, j := a.(uint32), b.(uint32); i < j {
  2276. return -1
  2277. } else if i > j {
  2278. return 1
  2279. }
  2280. return 0
  2281. }
  2282. // uint64Comparer compares two uint64 values. Implements Comparer.
  2283. type uint64Comparer struct{}
  2284. // Compare returns -1 if a is less than b, returns 1 if a is greater than b, and
  2285. // returns 0 if a is equal to b. Panic if a or b is not an uint64.
  2286. func (c *uint64Comparer) Compare(a, b interface{}) int {
  2287. if i, j := a.(uint64), b.(uint64); i < j {
  2288. return -1
  2289. } else if i > j {
  2290. return 1
  2291. }
  2292. return 0
  2293. }
  2294. // stringComparer compares two strings. Implements Comparer.
  2295. type stringComparer struct{}
  2296. // Compare returns -1 if a is less than b, returns 1 if a is greater than b, and
  2297. // returns 0 if a is equal to b. Panic if a or b is not a string.
  2298. func (c *stringComparer) Compare(a, b interface{}) int {
  2299. return strings.Compare(a.(string), b.(string))
  2300. }
  2301. // byteSliceComparer compares two byte slices. Implements Comparer.
  2302. type byteSliceComparer struct{}
  2303. // Compare returns -1 if a is less than b, returns 1 if a is greater than b, and
  2304. // returns 0 if a is equal to b. Panic if a or b is not a byte slice.
  2305. func (c *byteSliceComparer) Compare(a, b interface{}) int {
  2306. return bytes.Compare(a.([]byte), b.([]byte))
  2307. }
  2308. // reflectIntComparer compares two int values using reflection. Implements Comparer.
  2309. type reflectIntComparer struct{}
  2310. // Compare returns -1 if a is less than b, returns 1 if a is greater than b, and
  2311. // returns 0 if a is equal to b. Panic if a or b is not an int.
  2312. func (c *reflectIntComparer) Compare(a, b interface{}) int {
  2313. if i, j := reflect.ValueOf(a).Int(), reflect.ValueOf(b).Int(); i < j {
  2314. return -1
  2315. } else if i > j {
  2316. return 1
  2317. }
  2318. return 0
  2319. }
  2320. // reflectUintComparer compares two uint values using reflection. Implements Comparer.
  2321. type reflectUintComparer struct{}
  2322. // Compare returns -1 if a is less than b, returns 1 if a is greater than b, and
  2323. // returns 0 if a is equal to b. Panic if a or b is not an int.
  2324. func (c *reflectUintComparer) Compare(a, b interface{}) int {
  2325. if i, j := reflect.ValueOf(a).Uint(), reflect.ValueOf(b).Uint(); i < j {
  2326. return -1
  2327. } else if i > j {
  2328. return 1
  2329. }
  2330. return 0
  2331. }
  2332. // reflectStringComparer compares two string values using reflection. Implements Comparer.
  2333. type reflectStringComparer struct{}
  2334. // Compare returns -1 if a is less than b, returns 1 if a is greater than b, and
  2335. // returns 0 if a is equal to b. Panic if a or b is not an int.
  2336. func (c *reflectStringComparer) Compare(a, b interface{}) int {
  2337. return strings.Compare(reflect.ValueOf(a).String(), reflect.ValueOf(b).String())
  2338. }
  2339. func assert(condition bool, message string) {
  2340. if !condition {
  2341. panic(message)
  2342. }
  2343. }