pax_global_header00006660000000000000000000000064151337227560014525gustar00rootroot0000000000000052 comment=e2718c40ea244917d635438f225d44151644a24b go-algorithms-0.5.0/000077500000000000000000000000001513372275600143035ustar00rootroot00000000000000go-algorithms-0.5.0/LICENSE000066400000000000000000000027671513372275600153240ustar00rootroot00000000000000 Copyright (c) 2024, go-algorithms (go.bug.st/f) 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: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 3. Neither the name of the copyright holder 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 HOLDER 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. go-algorithms-0.5.0/README.md000066400000000000000000000006771513372275600155740ustar00rootroot00000000000000# go-algorithms [![Go Reference](https://pkg.go.dev/badge/go.bug.st/f.svg)](https://pkg.go.dev/go.bug.st/f) Package f is a golang library implementing some basic algorithms. The canonical import for this library is go.bug.st/f: ```go import "go.bug.st/f" ``` ## License This package is released under the permissive BSD-3-CLAUSE. ## Credits Thanks to all [awesome contributors](https://github.com/bugst/go-algorithms/graphs/contributors). go-algorithms-0.5.0/arguments.go000066400000000000000000000014061513372275600166400ustar00rootroot00000000000000// // This file is part of go-algorithms. // // Copyright 2024 go-algorithms (go.bug.st/f) 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 f import "fmt" // Must should be used to wrap a call to a function returning a value and an error. // Must returns the value if the errors is nil, or panics otherwise. func Must[T any](val T, err error) T { if err != nil { panic(err.Error()) } return val } // NoError panics if the given error is not nil. func NoError(err error) { if err != nil { panic(err.Error()) } } // Assert panics if condition is false. func Assert(condition bool, msg string, args ...any) { if !condition { panic(fmt.Sprintf(msg, args...)) } } go-algorithms-0.5.0/arguments_test.go000066400000000000000000000015001513372275600176720ustar00rootroot00000000000000// // This file is part of go-algorithms. // // Copyright 2024 Cristian Maglie. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // package f_test import ( "fmt" "testing" "github.com/stretchr/testify/assert" f "go.bug.st/f" ) func TestMust(t *testing.T) { t.Run("no error", func(t *testing.T) { assert.Equal(t, 12, f.Must(12, nil)) }) t.Run("error", func(t *testing.T) { want := fmt.Errorf("this is an error") assert.PanicsWithValue(t, want.Error(), func() { f.Must(0, want) }) }) } func TestAssert(t *testing.T) { t.Run("true", func(_ *testing.T) { f.Assert(true, "should not panic") }) t.Run("false", func(t *testing.T) { assert.PanicsWithValue(t, "should panic", func() { f.Assert(false, "should panic") }) }) } go-algorithms-0.5.0/channels.go000066400000000000000000000021021513372275600164200ustar00rootroot00000000000000// // This file is part of go-algorithms. // // Copyright 2024 go-algorithms (go.bug.st/f) 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 f import "sync" // DiscardCh consumes all incoming messages from the given channel until it's closed. func DiscardCh[T any](ch <-chan T) { for range ch { } } // Future is an object that holds a result value. The value may be read and // written asynchronously. type Future[T any] struct { lock sync.Mutex set bool cond *sync.Cond value T } // Send a result in the Future. Threads waiting for result will be unlocked. func (f *Future[T]) Send(value T) { f.lock.Lock() defer f.lock.Unlock() f.set = true f.value = value if f.cond != nil { f.cond.Broadcast() f.cond = nil } } // Await for a result from the Future, blocks until a result is available. func (f *Future[T]) Await() T { f.lock.Lock() defer f.lock.Unlock() for !f.set { if f.cond == nil { f.cond = sync.NewCond(&f.lock) } f.cond.Wait() } return f.value } go-algorithms-0.5.0/channels_test.go000066400000000000000000000014731513372275600174710ustar00rootroot00000000000000// // This file is part of go-algorithms. // // Copyright 2024 go-algorithms (go.bug.st/f) 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 f_test import ( "testing" "time" "github.com/stretchr/testify/require" f "go.bug.st/f" ) func TestFutures(t *testing.T) { { var futureInt f.Future[int] go func() { time.Sleep(100 * time.Millisecond) futureInt.Send(5) }() require.Equal(t, 5, futureInt.Await()) go func() { require.Equal(t, 5, futureInt.Await()) }() go func() { require.Equal(t, 5, futureInt.Await()) }() } { var futureInt f.Future[int] futureInt.Send(5) require.Equal(t, 5, futureInt.Await()) require.Equal(t, 5, futureInt.Await()) require.Equal(t, 5, futureInt.Await()) } } go-algorithms-0.5.0/doc.go000066400000000000000000000006051513372275600154000ustar00rootroot00000000000000// // This file is part of go-algorithms. // // Copyright 2024 go-algorithms (go.bug.st/f) 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 f is a golang library implementing some basic algorithms. The canonical import for this library is go.bug.st/f: import "go.bug.st/f" */ package f go-algorithms-0.5.0/go.mod000066400000000000000000000003351513372275600154120ustar00rootroot00000000000000module go.bug.st/f go 1.22.3 require github.com/stretchr/testify v1.9.0 require ( github.com/davecgh/go-spew v1.1.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) go-algorithms-0.5.0/go.sum000066400000000000000000000015611513372275600154410ustar00rootroot00000000000000github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= go-algorithms-0.5.0/io.go000066400000000000000000000032151513372275600152420ustar00rootroot00000000000000// // This file is part of go-algorithms. // // Copyright 2024 go-algorithms (go.bug.st/f) 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 f import ( "bytes" "io" ) const defaultBufferSize = 1024 type callbackWriter struct { callback func(line string) buffer []byte } // NewCallbackWriter creates a WriterCloser that will buffer input and call the provided callback for each complete line. // The last line (if not ending with a newline) will be processed when Close() is called. func NewCallbackWriter(process func(line string)) io.WriteCloser { return &callbackWriter{ callback: process, buffer: make([]byte, 0, defaultBufferSize), } } // Write implements the io.Writer interface. func (p *callbackWriter) Write(data []byte) (int, error) { l := len(data) for { if len(data) == 0 { return l, nil } idx := bytes.IndexByte(data, '\n') if idx == -1 { // No complete line found, buffer the data p.buffer = append(p.buffer, data...) return l, nil } if len(p.buffer) == 0 { // Fast path: no buffered data, process directly from input p.callback(string(data[:idx])) data = data[idx+1:] continue } // Append up to the newline to the buffer and process p.buffer = append(p.buffer, data[:idx]...) p.callback(string(p.buffer)) // Clear the buffer and continue with remaining data p.buffer = p.buffer[:0] data = data[idx+1:] } } // Close implements the io.Closer interface. func (p *callbackWriter) Close() error { if len(p.buffer) > 0 { p.callback(string(p.buffer)) p.buffer = p.buffer[:0] } return nil } go-algorithms-0.5.0/io_test.go000066400000000000000000000040451513372275600163030ustar00rootroot00000000000000// // This file is part of go-algorithms. // // Copyright 2024 go-algorithms (go.bug.st/f) 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 f import ( "fmt" "testing" "github.com/stretchr/testify/require" ) func TestCallbackWriter(t *testing.T) { t.Run("ProcessLines", func(t *testing.T) { var lines []string w := NewCallbackWriter(func(line string) { lines = append(lines, line) }) require.NotNil(t, w, "NewCallbackWriter returned nil") // Write with two complete lines and one partial chunk1 := []byte("first\nsecond\nthird") n, err := w.Write(chunk1) require.NoError(t, err) require.Equal(t, len(chunk1), n) require.Equal(t, []string{"first", "second"}, lines) n, err = w.Write([]byte("")) require.NoError(t, err) require.Equal(t, 0, n) // Complete the partial and add another full line chunk2 := []byte("\nfourth\n\n") n, err = w.Write(chunk2) require.NoError(t, err) require.Equal(t, len(chunk2), n) // Write a partial line and then close n, err = w.Write([]byte("fifth")) require.NoError(t, err) require.Equal(t, 5, n) require.NoError(t, w.Close()) wants := []string{"first", "second", "third", "fourth", "", "fifth"} require.Equal(t, wants, lines) }) t.Run("BufferGrowth", func(t *testing.T) { w := NewCallbackWriter(func(line string) {}) initialCap := cap(w.(*callbackWriter).buffer) // Ensure initial capacity is already greater than the bigger chunk we are testing require.Greater(t, initialCap, 100) // Run a series of writes to test buffer growth for i := 0; i < initialCap*10; i++ { n, err := w.Write([]byte("12345")) require.NoError(t, err) require.Equal(t, 5, n) n, err = w.Write([]byte("\n12345")) require.NoError(t, err) require.Equal(t, 6, n) n, err = w.Write([]byte("6347856387657823\n12345")) require.NoError(t, err) require.Equal(t, 22, n) } finalCap := cap(w.(*callbackWriter).buffer) fmt.Println(finalCap) require.Equal(t, initialCap, finalCap) }) } go-algorithms-0.5.0/ptr.go000066400000000000000000000007461513372275600154460ustar00rootroot00000000000000// // This file is part of go-algorithms. // // Copyright 2024 Cristian Maglie. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // package f // Ptr returns a pointer to v. func Ptr[T any](v T) *T { return &v } // UnwrapOrDefault returns the ptr value if it is not nil, otherwise returns the zero value. func UnwrapOrDefault[T any](ptr *T) T { if ptr != nil { return *ptr } var zero T return zero } go-algorithms-0.5.0/ptr_test.go000066400000000000000000000013441513372275600165000ustar00rootroot00000000000000// // This file is part of go-algorithms. // // Copyright 2024 Cristian Maglie. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // package f_test import ( "testing" "github.com/stretchr/testify/assert" f "go.bug.st/f" ) func TestPtr(t *testing.T) { t.Run("int", func(t *testing.T) { assert.Equal(t, 12, *f.Ptr(12)) }) t.Run("string", func(t *testing.T) { assert.Equal(t, "hello", *f.Ptr("hello")) }) } func TestUnwrapOrDefault(t *testing.T) { t.Run("not nil", func(t *testing.T) { given := 12 assert.Equal(t, 12, f.UnwrapOrDefault(&given)) }) t.Run("nil", func(t *testing.T) { assert.Equal(t, "", f.UnwrapOrDefault[string](nil)) }) } go-algorithms-0.5.0/slices.go000066400000000000000000000056321513372275600161220ustar00rootroot00000000000000// // This file is part of go-algorithms. // // Copyright 2024 go-algorithms (go.bug.st/f) 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 f import ( "runtime" "sync" "sync/atomic" ) // Filter takes a slice of type []T and a Matcher[T]. It returns a newly // allocated slice containing only those elements of the input slice that // satisfy the matcher. func Filter[T any](values []T, matcher Matcher[T]) []T { var res []T for _, x := range values { if matcher(x) { res = append(res, x) } } return res } // Map applies the Mapper function to each element of the slice and returns // a new slice with the results in the same order. func Map[T, U any](values []T, mapper Mapper[T, U]) []U { res := make([]U, len(values)) for i, x := range values { res[i] = mapper(x) } return res } // ParallelMap applies the Mapper function to each element of the slice and returns // a new slice with the results in the same order. This is executed among multilple // goroutines in parallel. If jobs is specified it will indicate the maximum number // of goroutines to be spawned. func ParallelMap[T, U any](values []T, mapper Mapper[T, U], jobs ...int) []U { res := make([]U, len(values)) var j int if len(jobs) == 0 { j = runtime.NumCPU() } else if len(jobs) == 1 { j = jobs[0] } else { panic("jobs must be a single value") } j = min(j, len(values)) var idx atomic.Int64 idx.Store(-1) var wg sync.WaitGroup wg.Add(j) for count := 0; count < j; count++ { go func() { i := int(idx.Add(1)) for i < len(values) { res[i] = mapper(values[i]) i = int(idx.Add(1)) } wg.Done() }() } wg.Wait() return res } // Reduce applies the Reducer function to all elements of the input values // and returns the result. func Reduce[T any](values []T, reducer Reducer[T], initialValue ...T) T { var result T if len(initialValue) > 1 { panic("initialValue must be a single value") } else if len(initialValue) == 1 { result = initialValue[0] } for _, v := range values { result = reducer(result, v) } return result } // Equals return a Matcher that matches the given value func Equals[T comparable](value T) Matcher[T] { return func(x T) bool { return x == value } } // NotEquals return a Matcher that does not match the given value func NotEquals[T comparable](value T) Matcher[T] { return func(x T) bool { return x != value } } // Uniq return a copy of the input array with all duplicates removed func Uniq[T comparable](in []T) []T { have := map[T]bool{} var out []T for _, v := range in { if have[v] { continue } out = append(out, v) have[v] = true } return out } // Count returns the number of elements in the input array that match the given matcher func Count[T any](in []T, matcher Matcher[T]) int { var count int for _, v := range in { if matcher(v) { count++ } } return count } go-algorithms-0.5.0/slices_test.go000066400000000000000000000056401513372275600171600ustar00rootroot00000000000000// // This file is part of go-algorithms. // // Copyright 2024 go-algorithms (go.bug.st/f) 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 f_test import ( "strings" "testing" "github.com/stretchr/testify/require" f "go.bug.st/f" ) func TestFilter(t *testing.T) { a := []string{"aaa", "bbb", "ccc"} require.Equal(t, []string{"bbb", "ccc"}, f.Filter(a, func(x string) bool { return x > "b" })) b := []int{5, 9, 15, 2, 4, -2} require.Equal(t, []int{5, 9, 15}, f.Filter(b, func(x int) bool { return x > 4 })) } func TestEqualsAndNotEquals(t *testing.T) { require.True(t, f.Equals(int(0))(0)) require.False(t, f.Equals(int(1))(0)) require.True(t, f.Equals("")("")) require.False(t, f.Equals("abc")("")) require.False(t, f.NotEquals(int(0))(0)) require.True(t, f.NotEquals(int(1))(0)) require.False(t, f.NotEquals("")("")) require.True(t, f.NotEquals("abc")("")) } func TestMap(t *testing.T) { value := []string{"hello", " world ", " how are", "you? "} { parts := f.Map(value, strings.TrimSpace) require.Equal(t, 4, len(parts)) require.Equal(t, "hello", parts[0]) require.Equal(t, "world", parts[1]) require.Equal(t, "how are", parts[2]) require.Equal(t, "you?", parts[3]) } { parts := f.ParallelMap(value, strings.TrimSpace) require.Equal(t, 4, len(parts)) require.Equal(t, "hello", parts[0]) require.Equal(t, "world", parts[1]) require.Equal(t, "how are", parts[2]) require.Equal(t, "you?", parts[3]) } } func TestReduce(t *testing.T) { and := func(in ...bool) bool { return f.Reduce(in, func(a, b bool) bool { return a && b }, true) } require.True(t, and()) require.True(t, and(true)) require.False(t, and(false)) require.True(t, and(true, true)) require.False(t, and(true, false)) require.False(t, and(false, true)) require.False(t, and(false, false)) require.False(t, and(true, true, false)) require.False(t, and(false, true, false)) require.False(t, and(false, true, true)) require.True(t, and(true, true, true)) or := func(in ...bool) bool { return f.Reduce(in, func(a, b bool) bool { return a || b }, false) } require.False(t, or()) require.True(t, or(true)) require.False(t, or(false)) require.True(t, or(true, true)) require.True(t, or(true, false)) require.True(t, or(false, true)) require.False(t, or(false, false)) require.True(t, or(true, true, false)) require.True(t, or(false, true, false)) require.False(t, or(false, false, false)) require.True(t, or(true, true, true)) add := func(in ...int) int { return f.Reduce(in, func(a, b int) int { return a + b }) } require.Equal(t, 0, add()) require.Equal(t, 10, add(10)) require.Equal(t, 15, add(10, 2, 3)) } func TestCount(t *testing.T) { a := []string{"aaa", "bbb", "ccc"} require.Equal(t, 1, f.Count(a, f.Equals("bbb"))) require.Equal(t, 0, f.Count(a, f.Equals("ddd"))) require.Equal(t, 3, f.Count(a, f.NotEquals("ddd"))) } go-algorithms-0.5.0/types.go000066400000000000000000000011251513372275600157750ustar00rootroot00000000000000// // This file is part of go-algorithms. // // Copyright 2024 go-algorithms (go.bug.st/f) 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 f // Matcher is a function that tests if a given value matches a certain criteria. type Matcher[T any] func(T) bool // Reducer is a function that combines two values of the same type and return // the combined value. type Reducer[T any] func(T, T) T // Mapper is a function that converts a value of one type to another type. type Mapper[T, U any] func(T) U