Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Release v0.0.10 #266

Merged
merged 7 commits into from
Nov 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/go.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ jobs:
with:
go-version: 1.20.0


- name: Build
run: go build -v ./...

Expand Down
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,5 @@

.idea
.vscode
**/.DS_Store
**/.DS_Store
**/*.so
8 changes: 6 additions & 2 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,9 @@

run:
go: '1.20'
skip-dirs:
- .idea
issues:
exclude-dirs:
- .idea
linters-settings:
errcheck:
ignore: ''
32 changes: 32 additions & 0 deletions condition.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Copyright 2021 ecodeclub
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package ekit

// IfThenElse 根据条件返回对应的泛型结果
// 注意避免结果的空指针问题
func IfThenElse[T any](condition bool, trueValue, falseValue T) T {
if condition {
return trueValue
}
return falseValue
}

// IfThenElseFunc 根据条件执行对应的函数并返回泛型结果
func IfThenElseFunc[T any](condition bool, trueFunc, falseFunc func() (T, error)) (T, error) {
if condition {
return trueFunc()
}
return falseFunc()
}
65 changes: 65 additions & 0 deletions condition_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
// Copyright 2021 ecodeclub
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package ekit

import (
"errors"
"fmt"
"testing"

"github.com/stretchr/testify/assert"
)

func TestIfThenElse(t *testing.T) {
i := 7
i = IfThenElse(false, i, 0)
assert.Equal(t, i, 0)
}

func ExampleIfThenElse() {
result := IfThenElse(true, "yes", "no")
fmt.Println(result)

// Output:
// yes
}

func TestIfThenElseFunc(t *testing.T) {
resp, err := IfThenElseFunc(true, func() (int, error) {
return 0, nil
}, func() (int, error) {
return 1, errors.New("some error")
})
assert.NoError(t, err)
assert.Equal(t, resp, 0)
}

func ExampleIfThenElseFunc() {
code, err := IfThenElseFunc(false, func() (code int, err error) {
// do something when condition is true
// ...
return 0, nil
}, func() (code int, err error) {
// do something when condition is false
// ...
return 1, errors.New("some error when execute func2")
})
fmt.Println(code)
fmt.Println(err)

// Output:
// 1
// some error when execute func2
}
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ go 1.20
require (
github.com/DATA-DOG/go-sqlmock v1.5.0
github.com/mattn/go-sqlite3 v1.14.15
github.com/pkg/errors v0.9.1
github.com/stretchr/testify v1.8.4
golang.org/x/exp v0.0.0-20231006140011-7918f672742d
golang.org/x/sync v0.4.0
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/mattn/go-sqlite3 v1.14.15 h1:vfoHhTN1af61xCRSWzFIWzx2YskyMTwHLrExkBOjvxI=
github.com/mattn/go-sqlite3 v1.14.15/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg=
github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
Expand Down
4 changes: 4 additions & 0 deletions internal/errs/error.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,7 @@ func NewErrInvalidIntervalValue(interval time.Duration) error {
func NewErrInvalidMaxIntervalValue(maxInterval, initialInterval time.Duration) error {
return fmt.Errorf("ekit: 最大重试间隔的时间 [%d] 应大于等于初始重试的间隔时间 [%d] ", maxInterval, initialInterval)
}

func NewErrRetryExhausted(lastErr error) error {
return fmt.Errorf("ekit: 超过最大重试次数,业务返回的最后一个 error %w", lastErr)
}
File renamed without changes.
148 changes: 148 additions & 0 deletions list/copy_on_write_array_list.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
// Copyright 2021 ecodeclub
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package list

import (
"sync"

"github.com/ecodeclub/ekit/internal/errs"
"github.com/ecodeclub/ekit/internal/slice"
)

var (
_ List[any] = &CopyOnWriteArrayList[any]{}
)

// CopyOnWriteArrayList 基于切片的简单封装 写时加锁,读不加锁,适合于读多写少场景
type CopyOnWriteArrayList[T any] struct {
vals []T
mutex *sync.Mutex
}

// NewCopyOnWriteArrayList
func NewCopyOnWriteArrayList[T any]() *CopyOnWriteArrayList[T] {
m := &sync.Mutex{}
return &CopyOnWriteArrayList[T]{
vals: make([]T, 0),
mutex: m,
}
}

// NewCopyOnWriteArrayListOf 直接使用 ts,会执行复制
func NewCopyOnWriteArrayListOf[T any](ts []T) *CopyOnWriteArrayList[T] {
items := make([]T, len(ts))
copy(items, ts)
m := &sync.Mutex{}
return &CopyOnWriteArrayList[T]{
vals: items,
mutex: m,
}
}

func (a *CopyOnWriteArrayList[T]) Get(index int) (t T, e error) {
l := a.Len()
if index < 0 || index >= l {
return t, errs.NewErrIndexOutOfRange(l, index)
}
return a.vals[index], e
}

// Append 往CopyOnWriteArrayList里追加数据
func (a *CopyOnWriteArrayList[T]) Append(ts ...T) error {
a.mutex.Lock()
defer a.mutex.Unlock()
n := len(a.vals)
newItems := make([]T, n, n+len(ts))
copy(newItems, a.vals)
newItems = append(newItems, ts...)
a.vals = newItems
return nil
}

// Add 在CopyOnWriteArrayList下标为index的位置插入一个元素
// 当index等于CopyOnWriteArrayList长度等同于append
func (a *CopyOnWriteArrayList[T]) Add(index int, t T) (err error) {
a.mutex.Lock()
defer a.mutex.Unlock()
n := len(a.vals)
newItems := make([]T, n, n+1)
copy(newItems, a.vals)
newItems, err = slice.Add(newItems, t, index)
a.vals = newItems
return
}

// Set 设置CopyOnWriteArrayList里index位置的值为t
func (a *CopyOnWriteArrayList[T]) Set(index int, t T) error {
a.mutex.Lock()
defer a.mutex.Unlock()
n := len(a.vals)
if index >= n || index < 0 {
return errs.NewErrIndexOutOfRange(n, index)
}
newItems := make([]T, n)
copy(newItems, a.vals)
newItems[index] = t
a.vals = newItems
return nil
}

// 这里不涉及缩容,每次都是当前内容长度申请的数组容量
func (a *CopyOnWriteArrayList[T]) Delete(index int) (T, error) {
a.mutex.Lock()
defer a.mutex.Unlock()
var ret T
n := len(a.vals)
if index >= n || index < 0 {
return ret, errs.NewErrIndexOutOfRange(n, index)
}
newItems := make([]T, len(a.vals)-1)
item := 0
for i, v := range a.vals {
if i == index {
ret = v
continue
}
newItems[item] = v
item++
}
a.vals = newItems
return ret, nil
}

func (a *CopyOnWriteArrayList[T]) Len() int {
return len(a.vals)
}

func (a *CopyOnWriteArrayList[T]) Cap() int {
return cap(a.vals)
}

func (a *CopyOnWriteArrayList[T]) Range(fn func(index int, t T) error) error {
for key, value := range a.vals {
e := fn(key, value)
if e != nil {
return e
}
}
return nil
}

func (a *CopyOnWriteArrayList[T]) AsSlice() []T {
a.mutex.Lock()
defer a.mutex.Unlock()
res := make([]T, len(a.vals))
copy(res, a.vals)
return res
}
Loading
Loading