pax_global_header00006660000000000000000000000064151114327310014510gustar00rootroot0000000000000052 comment=15d98d46693b3a13a8b64e12403c81aa01d58106 generics-0.2.0/000077500000000000000000000000001511143273100133065ustar00rootroot00000000000000generics-0.2.0/LICENSE000066400000000000000000000405251511143273100143210ustar00rootroot00000000000000Mozilla Public License Version 2.0 ================================== 1. Definitions -------------- 1.1. "Contributor" means each individual or legal entity that creates, contributes to the creation of, or owns Covered Software. 1.2. "Contributor Version" means the combination of the Contributions of others (if any) used by a Contributor and that particular Contributor's Contribution. 1.3. "Contribution" means Covered Software of a particular Contributor. 1.4. "Covered Software" means Source Code Form to which the initial Contributor has attached the notice in Exhibit A, the Executable Form of such Source Code Form, and Modifications of such Source Code Form, in each case including portions thereof. 1.5. "Incompatible With Secondary Licenses" means (a) that the initial Contributor has attached the notice described in Exhibit B to the Covered Software; or (b) that the Covered Software was made available under the terms of version 1.1 or earlier of the License, but not also under the terms of a Secondary License. 1.6. "Executable Form" means any form of the work other than Source Code Form. 1.7. "Larger Work" means a work that combines Covered Software with other material, in a separate file or files, that is not Covered Software. 1.8. "License" means this document. 1.9. "Licensable" means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently, any and all of the rights conveyed by this License. 1.10. "Modifications" means any of the following: (a) any file in Source Code Form that results from an addition to, deletion from, or modification of the contents of Covered Software; or (b) any new file in Source Code Form that contains any Covered Software. 1.11. "Patent Claims" of a Contributor means any patent claim(s), including without limitation, method, process, and apparatus claims, in any patent Licensable by such Contributor that would be infringed, but for the grant of the License, by the making, using, selling, offering for sale, having made, import, or transfer of either its Contributions or its Contributor Version. 1.12. "Secondary License" means either the GNU General Public License, Version 2.0, the GNU Lesser General Public License, Version 2.1, the GNU Affero General Public License, Version 3.0, or any later versions of those licenses. 1.13. "Source Code Form" means the form of the work preferred for making modifications. 1.14. "You" (or "Your") means an individual or a legal entity exercising rights under this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with You. For purposes of this definition, "control" means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity. 2. License Grants and Conditions -------------------------------- 2.1. Grants Each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license: (a) under intellectual property rights (other than patent or trademark) Licensable by such Contributor to use, reproduce, make available, modify, display, perform, distribute, and otherwise exploit its Contributions, either on an unmodified basis, with Modifications, or as part of a Larger Work; and (b) under Patent Claims of such Contributor to make, use, sell, offer for sale, have made, import, and otherwise transfer either its Contributions or its Contributor Version. 2.2. Effective Date The licenses granted in Section 2.1 with respect to any Contribution become effective for each Contribution on the date the Contributor first distributes such Contribution. 2.3. Limitations on Grant Scope The licenses granted in this Section 2 are the only rights granted under this License. No additional rights or licenses will be implied from the distribution or licensing of Covered Software under this License. Notwithstanding Section 2.1(b) above, no patent license is granted by a Contributor: (a) for any code that a Contributor has removed from Covered Software; or (b) for infringements caused by: (i) Your and any other third party's modifications of Covered Software, or (ii) the combination of its Contributions with other software (except as part of its Contributor Version); or (c) under Patent Claims infringed by Covered Software in the absence of its Contributions. This License does not grant any rights in the trademarks, service marks, or logos of any Contributor (except as may be necessary to comply with the notice requirements in Section 3.4). 2.4. Subsequent Licenses No Contributor makes additional grants as a result of Your choice to distribute the Covered Software under a subsequent version of this License (see Section 10.2) or under the terms of a Secondary License (if permitted under the terms of Section 3.3). 2.5. Representation Each Contributor represents that the Contributor believes its Contributions are its original creation(s) or it has sufficient rights to grant the rights to its Contributions conveyed by this License. 2.6. Fair Use This License is not intended to limit any rights You have under applicable copyright doctrines of fair use, fair dealing, or other equivalents. 2.7. Conditions Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in Section 2.1. 3. Responsibilities ------------------- 3.1. Distribution of Source Form All distribution of Covered Software in Source Code Form, including any Modifications that You create or to which You contribute, must be under the terms of this License. You must inform recipients that the Source Code Form of the Covered Software is governed by the terms of this License, and how they can obtain a copy of this License. You may not attempt to alter or restrict the recipients' rights in the Source Code Form. 3.2. Distribution of Executable Form If You distribute Covered Software in Executable Form then: (a) such Covered Software must also be made available in Source Code Form, as described in Section 3.1, and You must inform recipients of the Executable Form how they can obtain a copy of such Source Code Form by reasonable means in a timely manner, at a charge no more than the cost of distribution to the recipient; and (b) You may distribute such Executable Form under the terms of this License, or sublicense it under different terms, provided that the license for the Executable Form does not attempt to limit or alter the recipients' rights in the Source Code Form under this License. 3.3. Distribution of a Larger Work You may create and distribute a Larger Work under terms of Your choice, provided that You also comply with the requirements of this License for the Covered Software. If the Larger Work is a combination of Covered Software with a work governed by one or more Secondary Licenses, and the Covered Software is not Incompatible With Secondary Licenses, this License permits You to additionally distribute such Covered Software under the terms of such Secondary License(s), so that the recipient of the Larger Work may, at their option, further distribute the Covered Software under the terms of either this License or such Secondary License(s). 3.4. Notices You may not remove or alter the substance of any license notices (including copyright notices, patent notices, disclaimers of warranty, or limitations of liability) contained within the Source Code Form of the Covered Software, except that You may alter any license notices to the extent required to remedy known factual inaccuracies. 3.5. Application of Additional Terms You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Software. However, You may do so only on Your own behalf, and not on behalf of any Contributor. You must make it absolutely clear that any such warranty, support, indemnity, or liability obligation is offered by You alone, and You hereby agree to indemnify every Contributor for any liability incurred by such Contributor as a result of warranty, support, indemnity or liability terms You offer. You may include additional disclaimers of warranty and limitations of liability specific to any jurisdiction. 4. Inability to Comply Due to Statute or Regulation --------------------------------------------------- If it is impossible for You to comply with any of the terms of this License with respect to some or all of the Covered Software due to statute, judicial order, or regulation then You must: (a) comply with the terms of this License to the maximum extent possible; and (b) describe the limitations and the code they affect. Such description must be placed in a text file included with all distributions of the Covered Software under this License. Except to the extent prohibited by statute or regulation, such description must be sufficiently detailed for a recipient of ordinary skill to be able to understand it. 5. Termination -------------- 5.1. The rights granted under this License will terminate automatically if You fail to comply with any of its terms. However, if You become compliant, then the rights granted under this License from a particular Contributor are reinstated (a) provisionally, unless and until such Contributor explicitly and finally terminates Your grants, and (b) on an ongoing basis, if such Contributor fails to notify You of the non-compliance by some reasonable means prior to 60 days after You have come back into compliance. Moreover, Your grants from a particular Contributor are reinstated on an ongoing basis if such Contributor notifies You of the non-compliance by some reasonable means, this is the first time You have received notice of non-compliance with this License from such Contributor, and You become compliant prior to 30 days after Your receipt of the notice. 5.2. If You initiate litigation against any entity by asserting a patent infringement claim (excluding declaratory judgment actions, counter-claims, and cross-claims) alleging that a Contributor Version directly or indirectly infringes any patent, then the rights granted to You by any and all Contributors for the Covered Software under Section 2.1 of this License shall terminate. 5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user license agreements (excluding distributors and resellers) which have been validly granted by You or Your distributors under this License prior to termination shall survive termination. ************************************************************************ * * * 6. Disclaimer of Warranty * * ------------------------- * * * * Covered Software is provided under this License on an "as is" * * basis, without warranty of any kind, either expressed, implied, or * * statutory, including, without limitation, warranties that the * * Covered Software is free of defects, merchantable, fit for a * * particular purpose or non-infringing. The entire risk as to the * * quality and performance of the Covered Software is with You. * * Should any Covered Software prove defective in any respect, You * * (not any Contributor) assume the cost of any necessary servicing, * * repair, or correction. This disclaimer of warranty constitutes an * * essential part of this License. No use of any Covered Software is * * authorized under this License except under this disclaimer. * * * ************************************************************************ ************************************************************************ * * * 7. Limitation of Liability * * -------------------------- * * * * Under no circumstances and under no legal theory, whether tort * * (including negligence), contract, or otherwise, shall any * * Contributor, or anyone who distributes Covered Software as * * permitted above, be liable to You for any direct, indirect, * * special, incidental, or consequential damages of any character * * including, without limitation, damages for lost profits, loss of * * goodwill, work stoppage, computer failure or malfunction, or any * * and all other commercial damages or losses, even if such party * * shall have been informed of the possibility of such damages. This * * limitation of liability shall not apply to liability for death or * * personal injury resulting from such party's negligence to the * * extent applicable law prohibits such limitation. Some * * jurisdictions do not allow the exclusion or limitation of * * incidental or consequential damages, so this exclusion and * * limitation may not apply to You. * * * ************************************************************************ 8. Litigation ------------- Any litigation relating to this License may be brought only in the courts of a jurisdiction where the defendant maintains its principal place of business and such litigation shall be governed by laws of that jurisdiction, without reference to its conflict-of-law provisions. Nothing in this Section shall prevent a party's ability to bring cross-claims or counter-claims. 9. Miscellaneous ---------------- This License represents the complete agreement concerning the subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not be used to construe this License against a Contributor. 10. Versions of the License --------------------------- 10.1. New Versions Mozilla Foundation is the license steward. Except as provided in Section 10.3, no one other than the license steward has the right to modify or publish new versions of this License. Each version will be given a distinguishing version number. 10.2. Effect of New Versions You may distribute the Covered Software under the terms of the version of the License under which You originally received the Covered Software, or under the terms of any subsequent version published by the license steward. 10.3. Modified Versions If you create software not governed by this License, and you want to create a new license for such software, you may create and use a modified version of this License if you rename the license and remove any references to the name of the license steward (except to note that such modified license differs from this License). 10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses If You choose to distribute Source Code Form that is Incompatible With Secondary Licenses under the terms of this version of the License, the notice described in Exhibit B of this License must be attached. Exhibit A - Source Code Form License Notice ------------------------------------------- This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. If it is not possible or desirable to put the notice in a particular file, then You may include the notice in a location (such as a LICENSE file in a relevant directory) where a recipient would be likely to look for such a notice. You may add additional accurate notices of copyright ownership. Exhibit B - "Incompatible With Secondary Licenses" Notice --------------------------------------------------------- This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0. generics-0.2.0/agg.go000066400000000000000000000003361511143273100143750ustar00rootroot00000000000000package generics import "golang.org/x/exp/constraints" func Min[T constraints.Ordered](a, b T) T { if a < b { return a } return b } func Max[T constraints.Ordered](a, b T) T { if a > b { return a } return b } generics-0.2.0/chan.go000066400000000000000000000003701511143273100145460ustar00rootroot00000000000000package generics import "golang.org/x/exp/constraints" // I can't seem to make a common function for things the make function works with. "no core type" func MakeChanWithLen[T chan U, U any, L constraints.Integer](m *T, l L) { *m = make(T, l) } generics-0.2.0/errors.go000066400000000000000000000001601511143273100151460ustar00rootroot00000000000000package generics func UnwrapErrorTuple[T any](t T, err error) T { if err != nil { panic(err) } return t } generics-0.2.0/future.go000066400000000000000000000001421511143273100151440ustar00rootroot00000000000000package generics import "context" type Future[T any] interface { Wait(ctx context.Context) T } generics-0.2.0/generics.go000066400000000000000000000010071511143273100154320ustar00rootroot00000000000000package generics import "golang.org/x/exp/constraints" func InitNew[T any](p **T) { *p = new(T) } func SetZero[T any](p *T) { *p = ZeroValue[T]() } func PtrTo[T any](t T) *T { return &t } // Returns a zero-size, zero-allocation slice of the given length that can be used with range to // loop n times. Also has the advantage of not requiring a loop variable. Similar to bradfitz's // iter.N, and my clone in anacrolix/missinggo. func Range[T constraints.Integer](n T) []struct{} { return make([]struct{}, n) } generics-0.2.0/go.mod000066400000000000000000000001541511143273100144140ustar00rootroot00000000000000module github.com/anacrolix/generics go 1.18 require golang.org/x/exp v0.0.0-20240823005443-9b4947da3948 generics-0.2.0/go.sum000066400000000000000000000003171511143273100144420ustar00rootroot00000000000000golang.org/x/exp v0.0.0-20240823005443-9b4947da3948 h1:kx6Ds3MlpiUHKj7syVnbp57++8WpuKPcR5yjLBjvLEA= golang.org/x/exp v0.0.0-20240823005443-9b4947da3948/go.mod h1:akd2r19cwCdwSwWeIdzYQGa/EZZyqcOdwWiwj5L5eKQ= generics-0.2.0/heap/000077500000000000000000000000001511143273100142235ustar00rootroot00000000000000generics-0.2.0/heap/README000066400000000000000000000000771511143273100151070ustar00rootroot00000000000000"container/heap" with generics in the bare minimum of changes. generics-0.2.0/heap/example_intheap_test.go000066400000000000000000000021531511143273100207550ustar00rootroot00000000000000// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // This example demonstrates an integer heap built using the heap interface. package heap_test import ( "container/heap" "fmt" ) // An IntHeap is a min-heap of ints. type IntHeap []int func (h IntHeap) Len() int { return len(h) } func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] } func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } func (h *IntHeap) Push(x any) { // Push and Pop use pointer receivers because they modify the slice's length, // not just its contents. *h = append(*h, x.(int)) } func (h *IntHeap) Pop() any { old := *h n := len(old) x := old[n-1] *h = old[0 : n-1] return x } // This example inserts several ints into an IntHeap, checks the minimum, // and removes them in order of priority. func Example_intHeap() { h := &IntHeap{2, 1, 5} heap.Init(h) heap.Push(h, 3) fmt.Printf("minimum: %d\n", (*h)[0]) for h.Len() > 0 { fmt.Printf("%d ", heap.Pop(h)) } // Output: // minimum: 1 // 1 2 3 5 } generics-0.2.0/heap/example_pq_test.go000066400000000000000000000047361511143273100177560ustar00rootroot00000000000000// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // This example demonstrates a priority queue built using the heap interface. package heap_test import ( "container/heap" "fmt" ) // An Item is something we manage in a priority queue. type Item struct { value string // The value of the item; arbitrary. priority int // The priority of the item in the queue. // The index is needed by update and is maintained by the heap.Interface methods. index int // The index of the item in the heap. } // A PriorityQueue implements heap.Interface and holds Items. type PriorityQueue []*Item func (pq PriorityQueue) Len() int { return len(pq) } func (pq PriorityQueue) Less(i, j int) bool { // We want Pop to give us the highest, not lowest, priority so we use greater than here. return pq[i].priority > pq[j].priority } func (pq PriorityQueue) Swap(i, j int) { pq[i], pq[j] = pq[j], pq[i] pq[i].index = i pq[j].index = j } func (pq *PriorityQueue) Push(x any) { n := len(*pq) item := x.(*Item) item.index = n *pq = append(*pq, item) } func (pq *PriorityQueue) Pop() any { old := *pq n := len(old) item := old[n-1] old[n-1] = nil // avoid memory leak item.index = -1 // for safety *pq = old[0 : n-1] return item } // update modifies the priority and value of an Item in the queue. func (pq *PriorityQueue) update(item *Item, value string, priority int) { item.value = value item.priority = priority heap.Fix(pq, item.index) } // This example creates a PriorityQueue with some items, adds and manipulates an item, // and then removes the items in priority order. func Example_priorityQueue() { // Some items and their priorities. items := map[string]int{ "banana": 3, "apple": 2, "pear": 4, } // Create a priority queue, put the items in it, and // establish the priority queue (heap) invariants. pq := make(PriorityQueue, len(items)) i := 0 for value, priority := range items { pq[i] = &Item{ value: value, priority: priority, index: i, } i++ } heap.Init(&pq) // Insert a new item and then modify its priority. item := &Item{ value: "orange", priority: 1, } heap.Push(&pq, item) pq.update(item, item.value, 5) // Take the items out; they arrive in decreasing priority order. for pq.Len() > 0 { item := heap.Pop(&pq).(*Item) fmt.Printf("%.2d:%s ", item.priority, item.value) } // Output: // 05:orange 04:pear 03:banana 02:apple } generics-0.2.0/heap/heap.go000066400000000000000000000065631511143273100155010ustar00rootroot00000000000000// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package heap provides heap operations for any type that implements // heap.Interface. A heap is a tree with the property that each node is the // minimum-valued node in its subtree. // // The minimum element in the tree is the root, at index 0. // // A heap is a common way to implement a priority queue. To build a priority // queue, implement the Heap interface with the (negative) priority as the // ordering for the Less method, so Push adds items while Pop removes the // highest-priority item from the queue. The Examples include such an // implementation; the file example_pq_test.go has the complete source. package heap import "sort" // The Interface type describes the requirements // for a type using the routines in this package. // Any type that implements it may be used as a // min-heap with the following invariants (established after // Init has been called or if the data is empty or sorted): // // !h.Less(j, i) for 0 <= i < h.Len() and 2*i+1 <= j <= 2*i+2 and j < h.Len() // // Note that Push and Pop in this interface are for package heap's // implementation to call. To add and remove things from the heap, // use heap.Push and heap.Pop. type Interface[T any] interface { sort.Interface Push(x T) // add x as element Len() Pop() T // remove and return element Len() - 1. } // Init establishes the heap invariants required by the other routines in this package. // Init is idempotent with respect to the heap invariants // and may be called whenever the heap invariants may have been invalidated. // The complexity is O(n) where n = h.Len(). func Init[T any](h Interface[T]) { // heapify n := h.Len() for i := n/2 - 1; i >= 0; i-- { down(h, i, n) } } // Push pushes the element x onto the heap. // The complexity is O(log n) where n = h.Len(). func Push[T any](h Interface[T], x T) { h.Push(x) up(h, h.Len()-1) } // Pop removes and returns the minimum element (according to Less) from the heap. // The complexity is O(log n) where n = h.Len(). // Pop is equivalent to Remove(h, 0). func Pop[T any](h Interface[T]) T { n := h.Len() - 1 h.Swap(0, n) down(h, 0, n) return h.Pop() } // Remove removes and returns the element at index i from the heap. // The complexity is O(log n) where n = h.Len(). func Remove[T any](h Interface[T], i int) T { n := h.Len() - 1 if n != i { h.Swap(i, n) if !down(h, i, n) { up(h, i) } } return h.Pop() } // Fix re-establishes the heap ordering after the element at index i has changed its value. // Changing the value of the element at index i and then calling Fix is equivalent to, // but less expensive than, calling Remove(h, i) followed by a Push of the new value. // The complexity is O(log n) where n = h.Len(). func Fix[T any](h Interface[T], i int) { if !down(h, i, h.Len()) { up(h, i) } } func up[T any](h Interface[T], j int) { for { i := (j - 1) / 2 // parent if i == j || !h.Less(j, i) { break } h.Swap(i, j) j = i } } func down[T any](h Interface[T], i0, n int) bool { i := i0 for { j1 := 2*i + 1 if j1 >= n || j1 < 0 { // j1 < 0 after int overflow break } j := j1 // left child if j2 := j1 + 1; j2 < n && h.Less(j2, j1) { j = j2 // = 2*i + 2 // right child } if !h.Less(j, i) { break } h.Swap(i, j) i = j } return i > i0 } generics-0.2.0/heap/heap_test.go000066400000000000000000000070561511143273100165360ustar00rootroot00000000000000// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package heap import ( "math/rand" "testing" ) type myHeap []int func (h *myHeap) Less(i, j int) bool { return (*h)[i] < (*h)[j] } func (h *myHeap) Swap(i, j int) { (*h)[i], (*h)[j] = (*h)[j], (*h)[i] } func (h *myHeap) Len() int { return len(*h) } func (h *myHeap) Pop() (v int) { *h, v = (*h)[:h.Len()-1], (*h)[h.Len()-1] return } func (h *myHeap) Push(v int) { *h = append(*h, v) } func (h myHeap) verify(t *testing.T, i int) { t.Helper() n := h.Len() j1 := 2*i + 1 j2 := 2*i + 2 if j1 < n { if h.Less(j1, i) { t.Errorf("heap invariant invalidated [%d] = %d > [%d] = %d", i, h[i], j1, h[j1]) return } h.verify(t, j1) } if j2 < n { if h.Less(j2, i) { t.Errorf("heap invariant invalidated [%d] = %d > [%d] = %d", i, h[i], j1, h[j2]) return } h.verify(t, j2) } } func TestInit0(t *testing.T) { _h := new(myHeap) var h Interface[int] = _h for i := 20; i > 0; i-- { h.Push(0) // all elements are the same } Init(h) _h.verify(t, 0) for i := 1; h.Len() > 0; i++ { x := Pop(h) _h.verify(t, 0) if x != 0 { t.Errorf("%d.th pop got %d; want %d", i, x, 0) } } } func TestInit1(t *testing.T) { _h := new(myHeap) var h Interface[int] = _h for i := 20; i > 0; i-- { h.Push(i) // all elements are different } Init(h) _h.verify(t, 0) for i := 1; h.Len() > 0; i++ { x := Pop(h) _h.verify(t, 0) if x != i { t.Errorf("%d.th pop got %d; want %d", i, x, i) } } } func Test(t *testing.T) { _h := new(myHeap) var h Interface[int] = _h _h.verify(t, 0) for i := 20; i > 10; i-- { h.Push(i) } Init(h) _h.verify(t, 0) for i := 10; i > 0; i-- { Push(h, i) _h.verify(t, 0) } for i := 1; h.Len() > 0; i++ { x := Pop(h) if i < 20 { Push(h, 20+i) } _h.verify(t, 0) if x != i { t.Errorf("%d.th pop got %d; want %d", i, x, i) } } } func TestRemove0(t *testing.T) { _h := new(myHeap) var h Interface[int] = _h for i := 0; i < 10; i++ { h.Push(i) } _h.verify(t, 0) for h.Len() > 0 { i := h.Len() - 1 x := Remove(h, i) if x != i { t.Errorf("Remove(%d) got %d; want %d", i, x, i) } _h.verify(t, 0) } } func TestRemove1(t *testing.T) { _h := new(myHeap) var h Interface[int] = _h for i := 0; i < 10; i++ { h.Push(i) } _h.verify(t, 0) for i := 0; h.Len() > 0; i++ { x := Remove(h, 0) if x != i { t.Errorf("Remove(0) got %d; want %d", x, i) } _h.verify(t, 0) } } func TestRemove2(t *testing.T) { N := 10 _h := new(myHeap) var h Interface[int] = _h for i := 0; i < N; i++ { h.Push(i) } _h.verify(t, 0) m := make(map[int]bool) for h.Len() > 0 { m[Remove(h, (h.Len()-1)/2)] = true _h.verify(t, 0) } if len(m) != N { t.Errorf("len(m) = %d; want %d", len(m), N) } for i := 0; i < len(m); i++ { if !m[i] { t.Errorf("m[%d] doesn't exist", i) } } } func BenchmarkDup(b *testing.B) { const n = 10000 h := make(myHeap, 0, n) for i := 0; i < b.N; i++ { for j := 0; j < n; j++ { Push[int](&h, 0) // all elements are the same } for h.Len() > 0 { Pop[int](&h) } } } func TestFix(t *testing.T) { h := new(myHeap) h.verify(t, 0) for i := 200; i > 0; i -= 10 { Push[int](h, i) } h.verify(t, 0) if (*h)[0] != 10 { t.Fatalf("Expected head to be 10, was %d", (*h)[0]) } (*h)[0] = 210 Fix[int](h, 0) h.verify(t, 0) for i := 100; i > 0; i-- { elem := rand.Intn(h.Len()) if i&1 == 0 { (*h)[elem] *= 2 } else { (*h)[elem] /= 2 } Fix[int](h, elem) h.verify(t, 0) } } generics-0.2.0/heap/slice.go000066400000000000000000000030461511143273100156540ustar00rootroot00000000000000package heap type sliceInterface[T any] struct { slice *[]T less func(T, T) bool } // This is for use by the heap package's global functions, you probably don't mean to call this // directly. func (me sliceInterface[T]) Less(i, j int) bool { return me.less((*me.slice)[i], (*me.slice)[j]) } // This is for use by the heap package's global functions, you probably don't mean to call this // directly. func (me sliceInterface[T]) Swap(i, j int) { s := *me.slice s[i], s[j] = s[j], s[i] *me.slice = s } // This is for use by the heap package's global functions, you probably don't mean to call this // directly. func (me sliceInterface[T]) Push(x T) { *me.slice = append(*me.slice, x) } // This is for use by the heap package's global functions, you probably don't mean to call this // directly. func (me sliceInterface[T]) Pop() T { s := *me.slice n := len(s) ret := s[n-1] *me.slice = s[:n-1] return ret } func (me sliceInterface[T]) Len() int { return len(*me.slice) } // Creates an Interface that operates on a slice in place. The Interface should be used with the // heap package's global functions just like you would with a manual implementation of Interface for // a slice. i.e. don't call Interface.{Push,Pop}, call heap.{Push,Pop} and pass the return value // from this function. TODO: Shouldn't this return a value type rather than interface to give more // opportunity for escape analysis in the caller? func InterfaceForSlice[T any](sl *[]T, less func(l T, r T) bool) Interface[T] { return sliceInterface[T]{ slice: sl, less: less, } } generics-0.2.0/list/000077500000000000000000000000001511143273100142615ustar00rootroot00000000000000generics-0.2.0/list/LICENSE000066400000000000000000000027071511143273100152740ustar00rootroot00000000000000Copyright (c) 2009 The Go Authors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Google Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. generics-0.2.0/list/README000066400000000000000000000000771511143273100151450ustar00rootroot00000000000000"container/list" with generics in the bare minimum of changes. generics-0.2.0/list/example_test.go000066400000000000000000000010771511143273100173070ustar00rootroot00000000000000// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package list_test import ( "fmt" "github.com/anacrolix/generics/list" ) func Example() { // Create a new list and put some numbers in it. l := list.New[int]() e4 := l.PushBack(4) e1 := l.PushFront(1) l.InsertBefore(3, e4) l.InsertAfter(2, e1) // Iterate through list and print its contents. for e := l.Front(); e != nil; e = e.Next() { fmt.Println(e.Value) } // Output: // 1 // 2 // 3 // 4 } generics-0.2.0/list/list.go000066400000000000000000000150511511143273100155650ustar00rootroot00000000000000// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package list implements a doubly linked list. The implementation is a direct port with generics // of "container/list" from the Go standard library. // // To iterate over a list (where l is a *List): // // for e := l.Front(); e != nil; e = e.Next() { // // do something with e.Value // } package list // Element is an element of a linked list. type Element[V any] struct { // Next and previous pointers in the doubly-linked list of elements. // To simplify the implementation, internally a list l is implemented // as a ring, such that &l.root is both the next element of the last // list element (l.Back()) and the previous element of the first list // element (l.Front()). next, prev *Element[V] // The list to which this element belongs. list *List[V] // The value stored with this element. Value V } // Next returns the next list element or nil. func (e *Element[V]) Next() *Element[V] { if p := e.next; e.list != nil && p != &e.list.root { return p } return nil } // Prev returns the previous list element or nil. func (e *Element[V]) Prev() *Element[V] { if p := e.prev; e.list != nil && p != &e.list.root { return p } return nil } // List represents a doubly linked list. // The zero value for List is an empty list ready to use. type List[V any] struct { root Element[V] // sentinel list element, only &root, root.prev, and root.next are used len int // current list length excluding (this) sentinel element } // Init initializes or clears list l. func (l *List[V]) Init() *List[V] { l.root.next = &l.root l.root.prev = &l.root l.len = 0 return l } // New returns an initialized list. func New[V any]() *List[V] { return new(List[V]).Init() } // Len returns the number of elements of list l. // The complexity is O(1). func (l *List[V]) Len() int { return l.len } // Front returns the first element of list l or nil if the list is empty. func (l *List[V]) Front() *Element[V] { if l.len == 0 { return nil } return l.root.next } // Back returns the last element of list l or nil if the list is empty. func (l *List[V]) Back() *Element[V] { if l.len == 0 { return nil } return l.root.prev } // lazyInit lazily initializes a zero List value. func (l *List[V]) lazyInit() { if l.root.next == nil { l.Init() } } // insert inserts e after at, increments l.len, and returns e. func (l *List[V]) insert(e, at *Element[V]) *Element[V] { e.prev = at e.next = at.next e.prev.next = e e.next.prev = e e.list = l l.len++ return e } // insertValue is a convenience wrapper for insert(&Element{Value: v}, at). func (l *List[V]) insertValue(v V, at *Element[V]) *Element[V] { return l.insert(&Element[V]{Value: v}, at) } // remove removes e from its list, decrements l.len func (l *List[V]) remove(e *Element[V]) { e.prev.next = e.next e.next.prev = e.prev e.next = nil // avoid memory leaks e.prev = nil // avoid memory leaks e.list = nil l.len-- } // move moves e to next to at. func (l *List[V]) move(e, at *Element[V]) { if e == at { return } e.prev.next = e.next e.next.prev = e.prev e.prev = at e.next = at.next e.prev.next = e e.next.prev = e } // Remove removes e from l if e is an element of list l. // It returns the element value e.Value. // The element must not be nil. func (l *List[V]) Remove(e *Element[V]) V { if e.list == l { // if e.list == l, l must have been initialized when e was inserted // in l or l == nil (e is a zero Element) and l.remove will crash l.remove(e) } return e.Value } // PushFront inserts a new element e with value v at the front of list l and returns e. func (l *List[V]) PushFront(v V) *Element[V] { l.lazyInit() return l.insertValue(v, &l.root) } // PushBack inserts a new element e with value v at the back of list l and returns e. func (l *List[V]) PushBack(v V) *Element[V] { l.lazyInit() return l.insertValue(v, l.root.prev) } // InsertBefore inserts a new element e with value v immediately before mark and returns e. // If mark is not an element of l, the list is not modified. // The mark must not be nil. func (l *List[V]) InsertBefore(v V, mark *Element[V]) *Element[V] { if mark.list != l { return nil } // see comment in List.Remove about initialization of l return l.insertValue(v, mark.prev) } // InsertAfter inserts a new element e with value v immediately after mark and returns e. // If mark is not an element of l, the list is not modified. // The mark must not be nil. func (l *List[V]) InsertAfter(v V, mark *Element[V]) *Element[V] { if mark.list != l { return nil } // see comment in List.Remove about initialization of l return l.insertValue(v, mark) } // MoveToFront moves element e to the front of list l. // If e is not an element of l, the list is not modified. // The element must not be nil. func (l *List[V]) MoveToFront(e *Element[V]) { if e.list != l || l.root.next == e { return } // see comment in List.Remove about initialization of l l.move(e, &l.root) } // MoveToBack moves element e to the back of list l. // If e is not an element of l, the list is not modified. // The element must not be nil. func (l *List[V]) MoveToBack(e *Element[V]) { if e.list != l || l.root.prev == e { return } // see comment in List.Remove about initialization of l l.move(e, l.root.prev) } // MoveBefore moves element e to its new position before mark. // If e or mark is not an element of l, or e == mark, the list is not modified. // The element and mark must not be nil. func (l *List[V]) MoveBefore(e, mark *Element[V]) { if e.list != l || e == mark || mark.list != l { return } l.move(e, mark.prev) } // MoveAfter moves element e to its new position after mark. // If e or mark is not an element of l, or e == mark, the list is not modified. // The element and mark must not be nil. func (l *List[V]) MoveAfter(e, mark *Element[V]) { if e.list != l || e == mark || mark.list != l { return } l.move(e, mark) } // PushBackList inserts a copy of another list at the back of list l. // The lists l and other may be the same. They must not be nil. func (l *List[V]) PushBackList(other *List[V]) { l.lazyInit() for i, e := other.Len(), other.Front(); i > 0; i, e = i-1, e.Next() { l.insertValue(e.Value, l.root.prev) } } // PushFrontList inserts a copy of another list at the front of list l. // The lists l and other may be the same. They must not be nil. func (l *List[V]) PushFrontList(other *List[V]) { l.lazyInit() for i, e := other.Len(), other.Back(); i > 0; i, e = i-1, e.Prev() { l.insertValue(e.Value, &l.root) } } generics-0.2.0/list/list_test.go000066400000000000000000000177671511143273100166440ustar00rootroot00000000000000// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package list import "testing" func checkListLen[V any](t *testing.T, l *List[V], len int) bool { if n := l.Len(); n != len { t.Errorf("l.Len() = %d, want %d", n, len) return false } return true } func checkListPointers[V any](t *testing.T, l *List[V], es []*Element[V]) { root := &l.root if !checkListLen(t, l, len(es)) { return } // zero length lists must be the zero value or properly initialized (sentinel circle) if len(es) == 0 { if l.root.next != nil && l.root.next != root || l.root.prev != nil && l.root.prev != root { t.Errorf("l.root.next = %p, l.root.prev = %p; both should both be nil or %p", l.root.next, l.root.prev, root) } return } // len(es) > 0 // check internal and external prev/next connections for i, e := range es { prev := root Prev := (*Element[V])(nil) if i > 0 { prev = es[i-1] Prev = prev } if p := e.prev; p != prev { t.Errorf("elt[%d](%p).prev = %p, want %p", i, e, p, prev) } if p := e.Prev(); p != Prev { t.Errorf("elt[%d](%p).Prev() = %p, want %p", i, e, p, Prev) } next := root Next := (*Element[V])(nil) if i < len(es)-1 { next = es[i+1] Next = next } if n := e.next; n != next { t.Errorf("elt[%d](%p).next = %p, want %p", i, e, n, next) } if n := e.Next(); n != Next { t.Errorf("elt[%d](%p).Next() = %p, want %p", i, e, n, Next) } } } func TestList(t *testing.T) { l := New[any]() checkListPointers(t, l, []*Element[any]{}) // Single element list e := l.PushFront("a") checkListPointers(t, l, []*Element[any]{e}) l.MoveToFront(e) checkListPointers(t, l, []*Element[any]{e}) l.MoveToBack(e) checkListPointers(t, l, []*Element[any]{e}) l.Remove(e) checkListPointers(t, l, []*Element[any]{}) // Bigger list e2 := l.PushFront(2) e1 := l.PushFront(1) e3 := l.PushBack(3) e4 := l.PushBack("banana") checkListPointers(t, l, []*Element[any]{e1, e2, e3, e4}) l.Remove(e2) checkListPointers(t, l, []*Element[any]{e1, e3, e4}) l.MoveToFront(e3) // move from middle checkListPointers(t, l, []*Element[any]{e3, e1, e4}) l.MoveToFront(e1) l.MoveToBack(e3) // move from middle checkListPointers(t, l, []*Element[any]{e1, e4, e3}) l.MoveToFront(e3) // move from back checkListPointers(t, l, []*Element[any]{e3, e1, e4}) l.MoveToFront(e3) // should be no-op checkListPointers(t, l, []*Element[any]{e3, e1, e4}) l.MoveToBack(e3) // move from front checkListPointers(t, l, []*Element[any]{e1, e4, e3}) l.MoveToBack(e3) // should be no-op checkListPointers(t, l, []*Element[any]{e1, e4, e3}) e2 = l.InsertBefore(2, e1) // insert before front checkListPointers(t, l, []*Element[any]{e2, e1, e4, e3}) l.Remove(e2) e2 = l.InsertBefore(2, e4) // insert before middle checkListPointers(t, l, []*Element[any]{e1, e2, e4, e3}) l.Remove(e2) e2 = l.InsertBefore(2, e3) // insert before back checkListPointers(t, l, []*Element[any]{e1, e4, e2, e3}) l.Remove(e2) e2 = l.InsertAfter(2, e1) // insert after front checkListPointers(t, l, []*Element[any]{e1, e2, e4, e3}) l.Remove(e2) e2 = l.InsertAfter(2, e4) // insert after middle checkListPointers(t, l, []*Element[any]{e1, e4, e2, e3}) l.Remove(e2) e2 = l.InsertAfter(2, e3) // insert after back checkListPointers(t, l, []*Element[any]{e1, e4, e3, e2}) l.Remove(e2) // Check standard iteration. sum := 0 for e := l.Front(); e != nil; e = e.Next() { if i, ok := e.Value.(int); ok { sum += i } } if sum != 4 { t.Errorf("sum over l = %d, want 4", sum) } // Clear all elements by iterating var next *Element[any] for e := l.Front(); e != nil; e = next { next = e.Next() l.Remove(e) } checkListPointers(t, l, []*Element[any]{}) } func checkList(t *testing.T, l *List[int], es []int) { if !checkListLen(t, l, len(es)) { return } i := 0 for e := l.Front(); e != nil; e = e.Next() { le := e.Value if le != es[i] { t.Errorf("elt[%d].Value = %v, want %v", i, le, es[i]) } i++ } } func TestExtending(t *testing.T) { l1 := New[int]() l2 := New[int]() l1.PushBack(1) l1.PushBack(2) l1.PushBack(3) l2.PushBack(4) l2.PushBack(5) l3 := New[int]() l3.PushBackList(l1) checkList(t, l3, []int{1, 2, 3}) l3.PushBackList(l2) checkList(t, l3, []int{1, 2, 3, 4, 5}) l3 = New[int]() l3.PushFrontList(l2) checkList(t, l3, []int{4, 5}) l3.PushFrontList(l1) checkList(t, l3, []int{1, 2, 3, 4, 5}) checkList(t, l1, []int{1, 2, 3}) checkList(t, l2, []int{4, 5}) l3 = New[int]() l3.PushBackList(l1) checkList(t, l3, []int{1, 2, 3}) l3.PushBackList(l3) checkList(t, l3, []int{1, 2, 3, 1, 2, 3}) l3 = New[int]() l3.PushFrontList(l1) checkList(t, l3, []int{1, 2, 3}) l3.PushFrontList(l3) checkList(t, l3, []int{1, 2, 3, 1, 2, 3}) l3 = New[int]() l1.PushBackList(l3) checkList(t, l1, []int{1, 2, 3}) l1.PushFrontList(l3) checkList(t, l1, []int{1, 2, 3}) } func TestRemove(t *testing.T) { l := New[any]() e1 := l.PushBack(1) e2 := l.PushBack(2) checkListPointers(t, l, []*Element[any]{e1, e2}) e := l.Front() l.Remove(e) checkListPointers(t, l, []*Element[any]{e2}) l.Remove(e) checkListPointers(t, l, []*Element[any]{e2}) } func TestIssue4103(t *testing.T) { l1 := New[int]() l1.PushBack(1) l1.PushBack(2) l2 := New[int]() l2.PushBack(3) l2.PushBack(4) e := l1.Front() l2.Remove(e) // l2 should not change because e is not an element of l2 if n := l2.Len(); n != 2 { t.Errorf("l2.Len() = %d, want 2", n) } l1.InsertBefore(8, e) if n := l1.Len(); n != 3 { t.Errorf("l1.Len() = %d, want 3", n) } } func TestIssue6349(t *testing.T) { l := New[int]() l.PushBack(1) l.PushBack(2) e := l.Front() l.Remove(e) if e.Value != 1 { t.Errorf("e.value = %d, want 1", e.Value) } if e.Next() != nil { t.Errorf("e.Next() != nil") } if e.Prev() != nil { t.Errorf("e.Prev() != nil") } } func TestMove(t *testing.T) { l := New[int]() e1 := l.PushBack(1) e2 := l.PushBack(2) e3 := l.PushBack(3) e4 := l.PushBack(4) l.MoveAfter(e3, e3) checkListPointers(t, l, []*Element[int]{e1, e2, e3, e4}) l.MoveBefore(e2, e2) checkListPointers(t, l, []*Element[int]{e1, e2, e3, e4}) l.MoveAfter(e3, e2) checkListPointers(t, l, []*Element[int]{e1, e2, e3, e4}) l.MoveBefore(e2, e3) checkListPointers(t, l, []*Element[int]{e1, e2, e3, e4}) l.MoveBefore(e2, e4) checkListPointers(t, l, []*Element[int]{e1, e3, e2, e4}) e2, e3 = e3, e2 l.MoveBefore(e4, e1) checkListPointers(t, l, []*Element[int]{e4, e1, e2, e3}) e1, e2, e3, e4 = e4, e1, e2, e3 l.MoveAfter(e4, e1) checkListPointers(t, l, []*Element[int]{e1, e4, e2, e3}) e2, e3, e4 = e4, e2, e3 l.MoveAfter(e2, e3) checkListPointers(t, l, []*Element[int]{e1, e3, e2, e4}) } // Test PushFront, PushBack, PushFrontList, PushBackList with uninitialized List func TestZeroList(t *testing.T) { var l1 = new(List[int]) l1.PushFront(1) checkList(t, l1, []int{1}) var l2 = new(List[int]) l2.PushBack(1) checkList(t, l2, []int{1}) var l3 = new(List[int]) l3.PushFrontList(l1) checkList(t, l3, []int{1}) var l4 = new(List[int]) l4.PushBackList(l2) checkList(t, l4, []int{1}) } // Test that a list l is not modified when calling InsertBefore with a mark that is not an element of l. func TestInsertBeforeUnknownMark(t *testing.T) { var l List[int] l.PushBack(1) l.PushBack(2) l.PushBack(3) l.InsertBefore(1, new(Element[int])) checkList(t, &l, []int{1, 2, 3}) } // Test that a list l is not modified when calling InsertAfter with a mark that is not an element of l. func TestInsertAfterUnknownMark(t *testing.T) { var l List[int] l.PushBack(1) l.PushBack(2) l.PushBack(3) l.InsertAfter(1, new(Element[int])) checkList(t, &l, []int{1, 2, 3}) } // Test that a list l is not modified when calling MoveAfter or MoveBefore with a mark that is not an element of l. func TestMoveUnknownMark(t *testing.T) { var l1 List[int] e1 := l1.PushBack(1) var l2 List[int] e2 := l2.PushBack(2) l1.MoveAfter(e1, e2) checkList(t, &l1, []int{1}) checkList(t, &l2, []int{2}) l1.MoveBefore(e1, e2) checkList(t, &l1, []int{1}) checkList(t, &l2, []int{2}) } generics-0.2.0/map.go000066400000000000000000000031521511143273100144130ustar00rootroot00000000000000package generics import ( "golang.org/x/exp/constraints" ) // Deprecated: Use MakeMapIfNil and MapInsert separately. func MakeMapIfNilAndSet[K comparable, V any](pm *map[K]V, k K, v V) (added bool) { MakeMapIfNil(pm) m := *pm _, exists := m[k] added = !exists m[k] = v return } // Does this exist in the maps package? func MakeMap[K comparable, V any, M ~map[K]V](pm *M) { *pm = make(M) } func MakeMapWithCap[K comparable, V any, M ~map[K]V, C constraints.Integer](pm *M, cap C) { *pm = make(M, cap) } func MakeMapIfNil[K comparable, V any, M ~map[K]V](pm *M) { if *pm == nil { MakeMap(pm) } } func MakeMapIfNilWithCap[K comparable, V any, M ~map[K]V, C constraints.Integer](pm *M, cap C) { if *pm == nil { MakeMapWithCap(pm, cap) } } func MapContains[K comparable, V any, M ~map[K]V](m M, k K) bool { _, ok := m[k] return ok } func MapMustGet[K comparable, V any, M ~map[K]V](m M, k K) V { v, ok := m[k] if !ok { panic(k) } return v } // Returns Some of the previous value if there was one. func MapInsert[K comparable, V any, M ~map[K]V](m M, k K, v V) Option[V] { old, ok := m[k] m[k] = v return Option[V]{ Value: old, Ok: ok, } } // Deletes element with the key k. If there is no element with the specified key, panics. delete // only applies to maps, so for now Map is not mentioned in the function name. func MustDelete[K comparable, V any, M ~map[K]V](m M, k K) { _, ok := m[k] if !ok { panic(k) } delete(m, k) } // Panics if the key is already assigned in the map. func MapMustAssignNew[K comparable, V any, M ~map[K]V](m M, k K, v V) { if MapInsert(m, k, v).Ok { panic(k) } } generics-0.2.0/option.go000066400000000000000000000043431511143273100151510ustar00rootroot00000000000000package generics import ( "fmt" ) // Any functions that include types additional to V must be global and are in the option package. type Option[V any] struct { // Value must be zeroed when Ok is false for deterministic comparability. Value V // bool is the smallest type, so putting it at the end increases the chance it can be packed // with Value. Ok bool } func (me Option[V]) UnwrapOrZeroValue() (_ V) { if me.Ok { return me.Value } return } func (me *Option[V]) UnwrapPtr() *V { if !me.Ok { panic("not set") } return &me.Value } func (me Option[V]) Unwrap() V { if !me.Ok { panic("not set") } return me.Value } // Deprecated: Use option.AndThen func (me Option[V]) AndThen(f func(V) Option[V]) Option[V] { if me.Ok { return f(me.Value) } return me } func (me Option[V]) UnwrapOr(or V) V { if me.Ok { return me.Value } else { return or } } func (me *Option[V]) Set(v V) (prev Option[V]) { prev = *me me.Ok = true me.Value = v return } func (me *Option[V]) SetNone() { me.Ok = false me.Value = ZeroValue[V]() } func (me *Option[V]) SetFromTuple(v V, ok bool) { *me = OptionFromTuple(v, ok) } func (me *Option[V]) SetSomeZeroValue() { me.Ok = true me.Value = ZeroValue[V]() } func Some[V any](value V) Option[V] { return Option[V]{Ok: true, Value: value} } func None[V any]() Option[V] { return Option[V]{} } func OptionFromTuple[T any](t T, ok bool) Option[T] { if ok { return Some(t) } else { return None[T]() } } func (me Option[V]) String() string { if me.Ok { return fmt.Sprintf("Some(%v)", me.Value) } else { return "None" } } // Returns an Option that is the left Option if it's Some else the right Option. func (me Option[V]) Or(or Option[V]) Option[V] { if me.Ok { return me } return or } // Converts the option to an option expressed as a pointer (old-school nonsense). func (me Option[V]) ToPtr() *V { if me.Ok { return &me.Value } return nil } func (me Option[V]) AsTuple() (V, bool) { return me.Value, me.Ok } // Yields value for use as iter.Seq such as in range expression. func (me Option[V]) Iter(yield func(V) bool) { if me.Ok { yield(me.Value) } } func (me Option[V]) Filter(f func(V) bool) Option[V] { if me.Ok && !f(me.Value) { me.SetNone() } return me } generics-0.2.0/option/000077500000000000000000000000001511143273100146165ustar00rootroot00000000000000generics-0.2.0/option/option.go000066400000000000000000000007411511143273100164570ustar00rootroot00000000000000package option import ( "github.com/anacrolix/generics" ) func Map[T, U any](f func(from T) (to U), in generics.Option[T]) (out generics.Option[U]) { if in.Ok { out = generics.Some(f(in.Value)) } return } func AndThen[T, U any](in generics.Option[T], f func(in T) (out generics.Option[U])) (out generics.Option[U]) { if in.Ok { out = f(in.Value) } return } func FromPtr[T any](in *T) (_ generics.Option[T]) { if in != nil { return generics.Some(*in) } return } generics-0.2.0/result.go000066400000000000000000000012631511143273100151550ustar00rootroot00000000000000package generics type Result[T any] struct { Ok T Err error } func Err[T any](err error) Result[T] { return Result[T]{ Err: err, } } func ResultFromTuple[T any](t T, err error) Result[T] { return Result[T]{ Ok: t, Err: err, } } func (r Result[T]) AsTuple() (T, error) { return r.Ok, r.Err } func (r Result[T]) Unwrap() T { if r.Err != nil { panic(r.Err) } return r.Ok } func (r Result[T]) ToOption() Option[T] { return Option[T]{ Ok: r.Err == nil, Value: r.Ok, } } func (r *Result[T]) SetOk(ok T) { r.Ok = ok r.Err = nil } func (r *Result[T]) SetErr(err error) { SetZero(&r.Ok) r.Err = err } func (r *Result[T]) IsOk() bool { return r.Err == nil } generics-0.2.0/result/000077500000000000000000000000001511143273100146245ustar00rootroot00000000000000generics-0.2.0/result/result.go000066400000000000000000000004221511143273100164670ustar00rootroot00000000000000package result import ( g "github.com/anacrolix/generics" ) func Ok[T any](ok T) (res g.Result[T]) { res.SetOk(ok) return } // Seems kinda lame since Go can't infer T when returning into place. func Err[T any](err error) (res g.Result[T]) { res.SetErr(err) return } generics-0.2.0/slice.go000066400000000000000000000032471511143273100147420ustar00rootroot00000000000000package generics import ( "golang.org/x/exp/constraints" ) // Pops the last element from the slice and returns it. Panics if the slice is empty, or if the // slice is nil. func SlicePop[T any](slice *[]T) T { lastIndex := len(*slice) - 1 last := (*slice)[lastIndex] *slice = (*slice)[:lastIndex] return last } func MakeSliceWithLength[T any, L constraints.Integer](slice *[]T, length L) { *slice = make([]T, length) } func MakeSliceWithCap[T any, L constraints.Integer](slice *[]T, cap L) { *slice = make([]T, 0, cap) } func Reversed[T any](slice []T) []T { reversed := make([]T, len(slice)) for i := range reversed { reversed[i] = slice[len(slice)-1-i] } return reversed } func Singleton[T any](t T) []T { return []T{t} } // I take it there's no way to do this with a generic return slice element type. func ConvertToSliceOfAny[T any](ts []T) (ret []any) { ret = make([]any, 0, len(ts)) for _, t := range ts { ret = append(ret, t) } return } func ReverseSlice[T any](slice []T) { for i := 0; i < len(slice)/2; i++ { slice[i], slice[len(slice)-1-i] = slice[len(slice)-1-i], slice[i] } } func SliceTake[T any](n int, slice []T) []T { return slice[:Min(n, len(slice))] } func SliceDrop[T any](n int, slice []T) []T { return slice[Min(n, len(slice)):] } func SliceGet[T any, I constraints.Integer](slice []T, index I) (ret Option[T]) { if int(index) < len(slice) { ret = Some(slice[index]) } return } // Surely you should just pass iterator functions around instead. Go sux. func SliceMap[From, To any](froms []From, convert func(From) To) []To { tos := make([]To, 0, len(froms)) for _, from := range froms { tos = append(tos, convert(from)) } return tos } generics-0.2.0/zero-value.go000066400000000000000000000000771511143273100157320ustar00rootroot00000000000000package generics func ZeroValue[T any]() (zero T) { return }