Compare commits

...

19 Commits

Author SHA1 Message Date
deab986caf v0.0.22 2022-11-30 22:09:54 +01:00
9d9a6f1c6e v0.0.21 2022-11-19 16:58:18 +01:00
06a37f37b7 v0.0.20 2022-11-19 16:26:45 +01:00
b35d6ca0b0 v0.0.19 2022-11-19 13:34:21 +01:00
b643bded8a ArrFirstIndex, ArrLastIndex, ArrMap, ArrSum 2022-11-14 20:42:50 +01:00
93be4f9fdd added more supported GOOS 2022-10-29 15:44:51 +02:00
85b6d17df0 Tests && gomod 2022-10-29 15:34:40 +02:00
c7924cd9ff fix GOOS=windows / GOOS=darwin builds 2022-10-29 15:20:20 +02:00
07712aa08c fix timeext under 32bit compilation 2022-10-29 15:11:08 +02:00
f5243503db Add GeoDistance 2022-10-27 18:57:24 +02:00
21ae9c70d2 Added langext/coords && CompareArr[T] 2022-10-27 18:04:20 +02:00
c223e2f0fa added base62 2022-10-27 17:55:27 +02:00
a694f36f46 add tz params to timeext 2022-10-27 17:50:28 +02:00
e61682b24c Added termext.CleanString 2022-10-27 17:16:39 +02:00
5dc9e98f6b Add langext.ArrFirst / langext.ArrLast 2022-10-27 17:09:48 +02:00
4dd1c08e77 Add langext.BoolCount / langext.Range 2022-10-27 17:06:16 +02:00
c9e459edac Add mathext.Min / mathext.Max 2022-10-27 17:03:30 +02:00
3717eeb515 copy langext & termext from ffsclient 2022-10-27 16:48:26 +02:00
0eaeb5ac4f fix go mod (2) 2022-10-27 16:14:15 +02:00
34 changed files with 1083 additions and 73 deletions

9
Makefile Normal file
View File

@@ -0,0 +1,9 @@
run:
echo "This is a library - can't be run" && false
test:
go test ./...
version:
_data/version.sh

View File

@@ -3,6 +3,6 @@ BFB goext library
A collection of general & useful library methods A collection of general & useful library methods
Every subfolder is a seperate dependency and can be imported individually This should not have any heavy dependencies (gin, mongo, etc) and add missing basic language features...
Potentially needs `export GOPRIVATE="gogs.mikescher.com"` Potentially needs `export GOPRIVATE="gogs.mikescher.com"`

27
_data/version.sh Executable file
View File

@@ -0,0 +1,27 @@
#!/bin/bash
set -o nounset # disallow usage of unset vars ( set -u )
set -o errexit # Exit immediately if a pipeline returns non-zero. ( set -e )
set -o errtrace # Allow the above trap be inherited by all functions in the script. ( set -E )
set -o pipefail # Return value of a pipeline is the value of the last (rightmost) command to exit with a non-zero status
IFS=$'\n\t' # Set $IFS to only newline and tab.
curr_vers=$(git describe --tags --abbrev=0 | sed 's/v//g')
next_ver=$(echo "$curr_vers" | awk -F. -v OFS=. 'NF==1{print ++$NF}; NF>1{if(length($NF+1)>length($NF))$(NF-1)++; $NF=sprintf("%0*d", length($NF), ($NF+1)%(10^length($NF))); print}')
echo ""
echo "> Current Version: ${curr_vers}"
echo "> Next Version: ${next_ver}"
echo ""
git add --verbose .
git commit -a -m "v${next_ver}"
git tag "v${next_ver}"
git push
git push --tags

View File

@@ -1,7 +1,7 @@
package dataext package dataext
import ( import (
"go.mongodb.org/mongo-driver/bson/primitive" "gogs.mikescher.com/BlackForestBytes/goext/langext"
"math/rand" "math/rand"
"strconv" "strconv"
"testing" "testing"
@@ -251,18 +251,21 @@ func randomKey() string {
} }
func randomVal() LRUData { func randomVal() LRUData {
v := primitive.NewObjectID() v, err := langext.NewHexUUID()
if err != nil {
panic(err)
}
return &v return &v
} }
func eq(a LRUData, b LRUData) bool { func eq(a LRUData, b LRUData) bool {
v1, ok1 := a.(*primitive.ObjectID) v1, ok1 := a.(*string)
v2, ok2 := b.(*primitive.ObjectID) v2, ok2 := b.(*string)
if ok1 && ok2 { if ok1 && ok2 {
if v1 == nil || v2 == nil { if v1 == nil || v2 == nil {
return false return false
} }
return v1.Hex() == v2.Hex() return v1 == v2
} }
return false return false

35
dataext/merge.go Normal file
View File

@@ -0,0 +1,35 @@
package dataext
import (
"reflect"
)
func ObjectMerge[T1 any, T2 any](base T1, override T2) T1 {
reflBase := reflect.ValueOf(&base).Elem()
reflOvrd := reflect.ValueOf(&override).Elem()
for i := 0; i < reflBase.NumField(); i++ {
fieldBase := reflBase.Field(i)
fieldOvrd := reflOvrd.Field(i)
if fieldBase.Kind() != reflect.Ptr || fieldOvrd.Kind() != reflect.Ptr {
continue
}
kindBase := fieldBase.Type().Elem().Kind()
kindOvrd := fieldOvrd.Type().Elem().Kind()
if kindBase != kindOvrd {
continue
}
if !fieldOvrd.IsNil() {
fieldBase.Set(fieldOvrd.Elem().Addr())
}
}
return base
}

70
dataext/merge_test.go Normal file
View File

@@ -0,0 +1,70 @@
package dataext
import (
"gogs.mikescher.com/BlackForestBytes/goext/langext"
"testing"
)
func TestObjectMerge(t *testing.T) {
type A struct {
Field1 *int
Field2 *string
Field3 *float64
Field4 *bool
OnlyA int64
DiffType int
}
type B struct {
Field1 *int
Field2 *string
Field3 *float64
Field4 *bool
OnlyB int64
DiffType string
}
valueA := A{
Field1: nil,
Field2: langext.Ptr("99"),
Field3: langext.Ptr(12.2),
Field4: nil,
OnlyA: 1,
DiffType: 2,
}
valueB := B{
Field1: langext.Ptr(12),
Field2: nil,
Field3: langext.Ptr(13.2),
Field4: nil,
OnlyB: 1,
DiffType: "X",
}
valueMerge := ObjectMerge(valueA, valueB)
assertPtrEqual(t, "Field1", valueMerge.Field1, valueB.Field1)
assertPtrEqual(t, "Field2", valueMerge.Field2, valueA.Field2)
assertPtrEqual(t, "Field3", valueMerge.Field3, valueB.Field3)
assertPtrEqual(t, "Field4", valueMerge.Field4, nil)
}
func assertPtrEqual[T1 comparable](t *testing.T, ident string, actual *T1, expected *T1) {
if actual == nil && expected == nil {
return
}
if actual != nil && expected != nil {
if *actual != *expected {
t.Errorf("[%s] values differ: Actual: '%v', Expected: '%v'", ident, *actual, *expected)
} else {
return
}
}
if actual == nil && expected != nil {
t.Errorf("[%s] values differ: Actual: nil, Expected: not-nil", ident)
}
if actual != nil && expected == nil {
t.Errorf("[%s] values differ: Actual: not-nil, Expected: nil", ident)
}
}

7
go.mod
View File

@@ -1,3 +1,8 @@
module blackforestbytes.com/goext module gogs.mikescher.com/BlackForestBytes/goext
go 1.19 go 1.19
require (
golang.org/x/sys v0.1.0
golang.org/x/term v0.1.0
)

4
go.sum Normal file
View File

@@ -0,0 +1,4 @@
golang.org/x/sys v0.1.0 h1:kunALQeHf1/185U1i0GOB/fy1IPRDDpuoOOqRReG57U=
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.1.0 h1:g6Z6vPFA9dYBAF7DWcH6sCcOntplXsDKcliusYijMlw=
golang.org/x/term v0.1.0/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=

View File

@@ -4,6 +4,24 @@ import (
"reflect" "reflect"
) )
func BoolCount(arr ...bool) int {
c := 0
for _, v := range arr {
if v {
c++
}
}
return c
}
func Range[T IntegerConstraint](start T, end T) []T {
r := make([]T, 0, end-start)
for i := start; i < end; i++ {
r = append(r, i)
}
return r
}
func ForceArray[T any](v []T) []T { func ForceArray[T any](v []T) []T {
if v == nil { if v == nil {
return make([]T, 0) return make([]T, 0)
@@ -124,6 +142,46 @@ func ArrAnyErr(arr interface{}, fn func(int) (bool, error)) (bool, error) {
return false, nil return false, nil
} }
func ArrFirst[T comparable](arr []T, comp func(v T) bool) (T, bool) {
for _, v := range arr {
if comp(v) {
return v, true
}
}
return *new(T), false
}
func ArrLast[T comparable](arr []T, comp func(v T) bool) (T, bool) {
found := false
result := *new(T)
for _, v := range arr {
if comp(v) {
found = true
result = v
}
}
return result, found
}
func ArrFirstIndex[T comparable](arr []T, needle T) int {
for i, v := range arr {
if v == needle {
return i
}
}
return -1
}
func ArrLastIndex[T comparable](arr []T, needle T) int {
result := -1
for i, v := range arr {
if v == needle {
result = i
}
}
return result
}
func AddToSet[T comparable](set []T, add T) []T { func AddToSet[T comparable](set []T, add T) []T {
for _, v := range set { for _, v := range set {
if v == add { if v == add {
@@ -132,3 +190,19 @@ func AddToSet[T comparable](set []T, add T) []T {
} }
return append(set, add) return append(set, add)
} }
func ArrMap[T1 any, T2 any](arr []T1, conv func(v T1) T2) []T2 {
r := make([]T2, len(arr))
for i, v := range arr {
r[i] = conv(v)
}
return r
}
func ArrSum[T NumberConstraint](arr []T) T {
var r T = 0
for _, v := range arr {
r += v
}
return r
}

74
langext/base62.go Normal file
View File

@@ -0,0 +1,74 @@
package langext
import (
"crypto/rand"
"errors"
"math"
"math/big"
"strings"
)
var (
base62Base = uint64(62)
base62CharacterSet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
)
func RandBase62(rlen int) string {
bi52 := big.NewInt(int64(len(base62CharacterSet)))
randMax := big.NewInt(math.MaxInt64)
r := ""
for i := 0; i < rlen; i++ {
v, err := rand.Int(rand.Reader, randMax)
if err != nil {
panic(err)
}
r += string(base62CharacterSet[v.Mod(v, bi52).Int64()])
}
return r
}
func EncodeBase62(num uint64) string {
if num == 0 {
return "0"
}
b := make([]byte, 0)
// loop as long the num is bigger than zero
for num > 0 {
r := num % base62Base
num -= r
num /= base62Base
b = append([]byte{base62CharacterSet[int(r)]}, b...)
}
return string(b)
}
func DecodeBase62(str string) (uint64, error) {
if str == "" {
return 0, errors.New("empty string")
}
result := uint64(0)
for _, v := range str {
result *= base62Base
pos := strings.IndexRune(base62CharacterSet, v)
if pos == -1 {
return 0, errors.New("invalid character: " + string(v))
}
result += uint64(pos)
}
return result, nil
}

17
langext/bool.go Normal file
View File

@@ -0,0 +1,17 @@
package langext
func FormatBool(v bool, strTrue string, strFalse string) string {
if v {
return strTrue
} else {
return strFalse
}
}
func Conditional[T any](v bool, resTrue T, resFalse T) T {
if v {
return resTrue
} else {
return resFalse
}
}

View File

@@ -1,6 +1,9 @@
package langext package langext
import "fmt" import (
"errors"
"fmt"
)
func FormatBytesToSI(b uint64) string { func FormatBytesToSI(b uint64) string {
const unit = 1000 const unit = 1000
@@ -14,3 +17,30 @@ func FormatBytesToSI(b uint64) string {
} }
return fmt.Sprintf("%.1f %cB", float64(b)/float64(div), "kMGTPE"[exp]) return fmt.Sprintf("%.1f %cB", float64(b)/float64(div), "kMGTPE"[exp])
} }
func BytesXOR(a []byte, b []byte) ([]byte, error) {
if len(a) != len(b) {
return nil, errors.New("length mismatch")
}
r := make([]byte, len(a))
for i := 0; i < len(a); i++ {
r[i] = a[i] ^ b[i]
}
return r, nil
}
func FormatBytes(b int64) string {
const unit = 1024
if b < unit {
return fmt.Sprintf("%d B", b)
}
div, exp := int64(unit), 0
for n := b / unit; n >= unit; n /= unit {
div *= unit
exp++
}
return fmt.Sprintf("%.1f %ciB", float64(b)/float64(div), "KMGTPE"[exp])
}

View File

@@ -30,3 +30,34 @@ func CompareIntArr(arr1 []int, arr2 []int) bool {
return false return false
} }
func CompareArr[T OrderedConstraint](arr1 []T, arr2 []T) bool {
for i := 0; i < len(arr1) || i < len(arr2); i++ {
if i < len(arr1) && i < len(arr2) {
if arr1[i] < arr2[i] {
return true
} else if arr1[i] > arr2[i] {
return false
} else {
continue
}
}
if i < len(arr1) {
return true
} else { // if i < len(arr2)
return false
}
}
return false
}

21
langext/coords.go Normal file
View File

@@ -0,0 +1,21 @@
package langext
import "math"
func DegToRad(deg float64) float64 {
return deg * (math.Pi / 180.0)
}
func RadToDeg(rad float64) float64 {
return rad / (math.Pi * 180.0)
}
func GeoDistance(lon1 float64, lat1 float64, lon2 float64, lat2 float64) float64 {
var d1 = DegToRad(lat1)
var num1 = DegToRad(lon1)
var d2 = DegToRad(lat2)
var num2 = DegToRad(lon2) - num1
var d3 = math.Pow(math.Sin((d2-d1)/2.0), 2.0) + math.Cos(d1)*math.Cos(d2)*math.Pow(math.Sin(num2/2.0), 2.0)
return 6376500.0 * (2.0 * math.Atan2(math.Sqrt(d3), math.Sqrt(1.0-d3)))
}

33
langext/generics.go Normal file
View File

@@ -0,0 +1,33 @@
package langext
type IntConstraint interface {
int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64
}
type SignedConstraint interface {
~int | ~int8 | ~int16 | ~int32 | ~int64
}
type UnsignedConstraint interface {
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
}
type IntegerConstraint interface {
SignedConstraint | UnsignedConstraint
}
type FloatConstraint interface {
~float32 | ~float64
}
type ComplexConstraint interface {
~complex64 | ~complex128
}
type OrderedConstraint interface {
IntegerConstraint | FloatConstraint | ~string
}
type NumberConstraint interface {
IntegerConstraint | FloatConstraint
}

65
langext/json.go Normal file
View File

@@ -0,0 +1,65 @@
package langext
import (
"bytes"
"encoding/json"
"fmt"
)
type H map[string]any
type A []any
func TryPrettyPrintJson(str string) string {
var prettyJSON bytes.Buffer
if err := json.Indent(&prettyJSON, []byte(str), "", " "); err != nil {
return str
}
return prettyJSON.String()
}
func PrettyPrintJson(str string) (string, bool) {
var prettyJSON bytes.Buffer
if err := json.Indent(&prettyJSON, []byte(str), "", " "); err != nil {
return str, false
}
return prettyJSON.String(), true
}
func PatchJson[JV string | []byte](rawjson JV, key string, value any) (JV, error) {
var err error
var jsonpayload map[string]any
err = json.Unmarshal([]byte(rawjson), &jsonpayload)
if err != nil {
return *new(JV), fmt.Errorf("failed to unmarshal payload: %w", err)
}
jsonpayload[key] = value
newjson, err := json.Marshal(jsonpayload)
if err != nil {
return *new(JV), fmt.Errorf("failed to re-marshal payload: %w", err)
}
return JV(newjson), nil
}
func PatchRemJson[JV string | []byte](rawjson JV, key string) (JV, error) {
var err error
var jsonpayload map[string]any
err = json.Unmarshal([]byte(rawjson), &jsonpayload)
if err != nil {
return *new(JV), fmt.Errorf("failed to unmarshal payload: %w", err)
}
delete(jsonpayload, key)
newjson, err := json.Marshal(jsonpayload)
if err != nil {
return *new(JV), fmt.Errorf("failed to re-marshal payload: %w", err)
}
return JV(newjson), nil
}

9
langext/maps.go Normal file
View File

@@ -0,0 +1,9 @@
package langext
func MapKeyArr[T comparable, V any](v map[T]V) []T {
result := make([]T, 0, len(v))
for k := range v {
result = append(result, k)
}
return result
}

11
langext/os.go Normal file
View File

@@ -0,0 +1,11 @@
package langext
import "os"
func FileExists(filename string) bool {
info, err := os.Stat(filename)
if os.IsNotExist(err) {
return false
}
return !info.IsDir()
}

15
langext/rand.go Normal file
View File

@@ -0,0 +1,15 @@
package langext
import (
"crypto/rand"
"io"
)
func RandBytes(size int) []byte {
b := make([]byte, size)
_, err := io.ReadFull(rand.Reader, b)
if err != nil {
panic(err)
}
return b
}

View File

@@ -61,3 +61,49 @@ func ConvertStringerArray[T fmt.Stringer](inarr []T) []string {
} }
return result return result
} }
func StrRunePadLeft(str string, pad string, padlen int) string {
if pad == "" {
pad = " "
}
if len([]rune(str)) >= padlen {
return str
}
return strings.Repeat(pad, padlen-len([]rune(str)))[0:(padlen-len([]rune(str)))] + str
}
func StrRunePadRight(str string, pad string, padlen int) string {
if pad == "" {
pad = " "
}
if len([]rune(str)) >= padlen {
return str
}
return str + strings.Repeat(pad, padlen-len([]rune(str)))[0:(padlen-len([]rune(str)))]
}
func Indent(str string, pad string) string {
eonl := strings.HasSuffix(str, "\n")
r := ""
for _, v := range strings.Split(str, "\n") {
r += pad + v + "\n"
}
if eonl {
r = r[0 : len(r)-1]
}
return r
}
func NumToStringOpt[V IntConstraint](v *V, fallback string) string {
if v == nil {
return fallback
} else {
return fmt.Sprintf("%d", v)
}
}

134
langext/uuid.go Normal file
View File

@@ -0,0 +1,134 @@
package langext
import (
"crypto/rand"
"encoding/hex"
"io"
"strings"
)
func NewUUID() ([16]byte, error) {
var uuid [16]byte
_, err := io.ReadFull(rand.Reader, uuid[:])
if err != nil {
return [16]byte{}, err
}
uuid[6] = (uuid[6] & 0x0f) | 0x40 // Version 4
uuid[8] = (uuid[8] & 0x3f) | 0x80 // Variant is 10
return uuid, nil
}
func NewHexUUID() (string, error) {
uuid, err := NewUUID()
if err != nil {
return "", err
}
// Result: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
var dst = make([]byte, 36)
hex.Encode(dst, uuid[:4])
dst[8] = '-'
hex.Encode(dst[9:13], uuid[4:6])
dst[13] = '-'
hex.Encode(dst[14:18], uuid[6:8])
dst[18] = '-'
hex.Encode(dst[19:23], uuid[8:10])
dst[23] = '-'
hex.Encode(dst[24:], uuid[10:])
return string(dst), nil
}
func NewUpperHexUUID() (string, error) {
uuid, err := NewUUID()
if err != nil {
return "", err
}
// Result: XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
var dst = make([]byte, 36)
hex.Encode(dst, uuid[:4])
dst[8] = '-'
hex.Encode(dst[9:13], uuid[4:6])
dst[13] = '-'
hex.Encode(dst[14:18], uuid[6:8])
dst[18] = '-'
hex.Encode(dst[19:23], uuid[8:10])
dst[23] = '-'
hex.Encode(dst[24:], uuid[10:])
return strings.ToUpper(string(dst)), nil
}
func NewRawHexUUID() (string, error) {
uuid, err := NewUUID()
if err != nil {
return "", err
}
// Result: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
var dst = make([]byte, 32)
hex.Encode(dst, uuid[:4])
hex.Encode(dst[8:12], uuid[4:6])
hex.Encode(dst[12:16], uuid[6:8])
hex.Encode(dst[16:20], uuid[8:10])
hex.Encode(dst[20:], uuid[10:])
return strings.ToUpper(string(dst)), nil
}
func NewBracesUUID() (string, error) {
uuid, err := NewUUID()
if err != nil {
return "", err
}
// Result: {XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}
var dst = make([]byte, 38)
dst[0] = '{'
hex.Encode(dst, uuid[:5])
dst[9] = '-'
hex.Encode(dst[10:14], uuid[4:6])
dst[14] = '-'
hex.Encode(dst[15:19], uuid[6:8])
dst[19] = '-'
hex.Encode(dst[20:24], uuid[8:10])
dst[24] = '-'
hex.Encode(dst[25:], uuid[10:])
dst[37] = '}'
return strings.ToUpper(string(dst)), nil
}
func NewParensUUID() (string, error) {
uuid, err := NewUUID()
if err != nil {
return "", err
}
// Result: (XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX)
var dst = make([]byte, 38)
dst[0] = '('
hex.Encode(dst, uuid[:5])
dst[9] = '-'
hex.Encode(dst[10:14], uuid[4:6])
dst[14] = '-'
hex.Encode(dst[15:19], uuid[6:8])
dst[19] = '-'
hex.Encode(dst[20:24], uuid[8:10])
dst[24] = '-'
hex.Encode(dst[25:], uuid[10:])
dst[37] = ')'
return strings.ToUpper(string(dst)), nil
}

View File

@@ -1,5 +1,7 @@
package mathext package mathext
import "gogs.mikescher.com/BlackForestBytes/goext/langext"
func AvgFloat64(arr []float64) float64 { func AvgFloat64(arr []float64) float64 {
return SumFloat64(arr) / float64(len(arr)) return SumFloat64(arr) / float64(len(arr))
} }
@@ -11,3 +13,37 @@ func SumFloat64(arr []float64) float64 {
} }
return sum return sum
} }
func Max[T langext.OrderedConstraint](v1 T, v2 T) T {
if v1 > v2 {
return v1
} else {
return v2
}
}
func Min[T langext.OrderedConstraint](v1 T, v2 T) T {
if v1 < v2 {
return v1
} else {
return v2
}
}
func Abs[T langext.NumberConstraint](v T) T {
if v < 0 {
return -v
} else {
return v
}
}
func Clamp[T langext.NumberConstraint](v T, min T, max T) T {
if v < min {
return min
} else if v > max {
return max
} else {
return v
}
}

View File

@@ -1,26 +1,28 @@
package mathext package mathext
func Sum(v []float64) float64 { import "gogs.mikescher.com/BlackForestBytes/goext/langext"
total := float64(0)
func Sum[T langext.NumberConstraint](v []T) T {
total := T(0)
for _, v := range v { for _, v := range v {
total += v total += v
} }
return total return total
} }
func Mean(v []float64) float64 { func Mean[T langext.FloatConstraint](v []T) T {
return Sum(v) / float64(len(v)) return Sum(v) / T(len(v))
} }
func Median(v []float64) float64 { func Median[T langext.FloatConstraint](v []T) T {
if len(v)%2 == 1 { if len(v)%2 == 1 {
return v[len(v)/2] return v[len(v)/2]
} else { } else {
return (v[len(v)/2-1] + v[len(v)/2]) / float64(2) return (v[len(v)/2-1] + v[len(v)/2]) / T(2)
} }
} }
func Min(v []float64) float64 { func ArrMin[T langext.OrderedConstraint](v []T) T {
r := v[0] r := v[0]
for _, val := range v { for _, val := range v {
if val < r { if val < r {
@@ -30,7 +32,7 @@ func Min(v []float64) float64 {
return r return r
} }
func Max(v []float64) float64 { func ArrMax[T langext.OrderedConstraint](v []T) T {
r := v[0] r := v[0]
for _, val := range v { for _, val := range v {
if val > r { if val > r {

61
termext/colors.go Normal file
View File

@@ -0,0 +1,61 @@
package termext
import "strings"
const (
colorReset = "\033[0m"
colorRed = "\033[31m"
colorGreen = "\033[32m"
colorYellow = "\033[33m"
colorBlue = "\033[34m"
colorPurple = "\033[35m"
colorCyan = "\033[36m"
colorGray = "\033[37m"
colorWhite = "\033[97m"
)
func Red(v string) string {
return colorRed + v + colorReset
}
func Green(v string) string {
return colorGreen + v + colorReset
}
func Yellow(v string) string {
return colorYellow + v + colorReset
}
func Blue(v string) string {
return colorBlue + v + colorReset
}
func Purple(v string) string {
return colorPurple + v + colorReset
}
func Cyan(v string) string {
return colorCyan + v + colorReset
}
func Gray(v string) string {
return colorGray + v + colorReset
}
func White(v string) string {
return colorWhite + v + colorReset
}
func CleanString(v string) string {
v = strings.ReplaceAll(v, colorReset, "")
v = strings.ReplaceAll(v, colorRed, "")
v = strings.ReplaceAll(v, colorGreen, "")
v = strings.ReplaceAll(v, colorYellow, "")
v = strings.ReplaceAll(v, colorBlue, "")
v = strings.ReplaceAll(v, colorPurple, "")
v = strings.ReplaceAll(v, colorCyan, "")
v = strings.ReplaceAll(v, colorGray, "")
v = strings.ReplaceAll(v, colorWhite, "")
return v
}

5
termext/osutil_darwin.go Normal file
View File

@@ -0,0 +1,5 @@
package termext
func enableColor() bool {
return true
}

View File

@@ -0,0 +1,5 @@
package termext
func enableColor() bool {
return true
}

5
termext/osutil_linux.go Normal file
View File

@@ -0,0 +1,5 @@
package termext
func enableColor() bool {
return true
}

5
termext/osutil_netbsd.go Normal file
View File

@@ -0,0 +1,5 @@
package termext
func enableColor() bool {
return true
}

View File

@@ -0,0 +1,5 @@
package termext
func enableColor() bool {
return true
}

26
termext/osutil_windows.go Normal file
View File

@@ -0,0 +1,26 @@
package termext
import "golang.org/x/sys/windows"
func enableColor() bool {
handle, err := windows.GetStdHandle(windows.STD_OUTPUT_HANDLE)
if err != nil {
return false
}
var mode uint32
err = windows.GetConsoleMode(handle, &mode)
if err != nil {
return false
}
if mode&windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING != windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING {
mode = mode | windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING
err = windows.SetConsoleMode(handle, mode)
if err != nil {
return false
}
}
return true
}

90
termext/termcolor.go Normal file
View File

@@ -0,0 +1,90 @@
package termext
import (
"golang.org/x/term"
"os"
"regexp"
"strconv"
"strings"
)
// -> partly copied from [ https://github.com/jwalton/go-supportscolor/tree/master ]
func SupportsColors() bool {
if isatty := term.IsTerminal(int(os.Stdout.Fd())); !isatty {
return false
}
termenv := os.Getenv("TERM")
if termenv == "dumb" {
return false
}
if osColorEnabled := enableColor(); !osColorEnabled {
return false
}
if _, ci := os.LookupEnv("CI"); ci {
var ciEnvNames = []string{"TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "BUILDKITE", "DRONE"}
for _, ciEnvName := range ciEnvNames {
_, exists := os.LookupEnv(ciEnvName)
if exists {
return true
}
}
if os.Getenv("CI_NAME") == "codeship" {
return true
}
return false
}
if teamCityVersion, isTeamCity := os.LookupEnv("TEAMCITY_VERSION"); isTeamCity {
versionRegex := regexp.MustCompile(`^(9\.(0*[1-9]\d*)\.|\d{2,}\.)`)
if versionRegex.MatchString(teamCityVersion) {
return true
}
return false
}
if os.Getenv("COLORTERM") == "truecolor" {
return true
}
if termProgram, termProgramPreset := os.LookupEnv("TERM_PROGRAM"); termProgramPreset {
switch termProgram {
case "iTerm.app":
termProgramVersion := strings.Split(os.Getenv("TERM_PROGRAM_VERSION"), ".")
version, err := strconv.ParseInt(termProgramVersion[0], 10, 64)
if err == nil && version >= 3 {
return true
}
return true
case "Apple_Terminal":
return true
default:
// No default
}
}
var term256Regex = regexp.MustCompile("(?i)-256(color)?$")
if term256Regex.MatchString(termenv) {
return true
}
var termBasicRegex = regexp.MustCompile("(?i)^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux")
if termBasicRegex.MatchString(termenv) {
return true
}
if _, colorTerm := os.LookupEnv("COLORTERM"); colorTerm {
return true
}
return false
}

40
termext/termcolor_test.go Normal file
View File

@@ -0,0 +1,40 @@
package termext
import (
"math/rand"
"testing"
)
func init() {
rand.Seed(0)
}
func TestSupportsColors(t *testing.T) {
SupportsColors() // should not error
}
func TestColor(t *testing.T) {
assertEqual(t, Red("test"), "\033[31mtest\u001B[0m")
assertEqual(t, Green("test"), "\033[32mtest\u001B[0m")
assertEqual(t, Yellow("test"), "\033[33mtest\u001B[0m")
assertEqual(t, Blue("test"), "\033[34mtest\u001B[0m")
assertEqual(t, Purple("test"), "\033[35mtest\u001B[0m")
assertEqual(t, Cyan("test"), "\033[36mtest\u001B[0m")
assertEqual(t, Gray("test"), "\033[37mtest\u001B[0m")
assertEqual(t, White("test"), "\033[97mtest\u001B[0m")
assertEqual(t, CleanString(Red("test")), "test")
assertEqual(t, CleanString(Green("test")), "test")
assertEqual(t, CleanString(Yellow("test")), "test")
assertEqual(t, CleanString(Blue("test")), "test")
assertEqual(t, CleanString(Purple("test")), "test")
assertEqual(t, CleanString(Cyan("test")), "test")
assertEqual(t, CleanString(Gray("test")), "test")
assertEqual(t, CleanString(White("test")), "test")
}
func assertEqual(t *testing.T, actual string, expected string) {
if actual != expected {
t.Errorf("values differ: Actual: '%v', Expected: '%v'", actual, expected)
}
}

View File

@@ -1,55 +1,68 @@
package timeext package timeext
import "time" import (
"fmt"
"gogs.mikescher.com/BlackForestBytes/goext/langext"
"time"
)
func FromSeconds(v int) time.Duration { func FromNanoseconds[T langext.NumberConstraint](v T) time.Duration {
return time.Duration(int64(v) * int64(time.Second)) return time.Duration(int64(float64(v) * float64(time.Nanosecond)))
} }
func FromSecondsInt32(v int32) time.Duration { func FromMicroseconds[T langext.NumberConstraint](v T) time.Duration {
return time.Duration(int64(v) * int64(time.Second)) return time.Duration(int64(float64(v) * float64(time.Microsecond)))
} }
func FromSecondsInt64(v int64) time.Duration { func FromMilliseconds[T langext.NumberConstraint](v T) time.Duration {
return time.Duration(v * int64(time.Second)) return time.Duration(int64(float64(v) * float64(time.Millisecond)))
} }
func FromSecondsFloat32(v float32) time.Duration { func FromSeconds[T langext.NumberConstraint](v T) time.Duration {
return time.Duration(int64(v * float32(time.Second))) return time.Duration(int64(float64(v) * float64(time.Second)))
} }
func FromSecondsFloat64(v float64) time.Duration { func FromMinutes[T langext.NumberConstraint](v T) time.Duration {
return time.Duration(int64(v * float64(time.Second))) return time.Duration(int64(float64(v) * float64(time.Minute)))
} }
func FromSecondsFloat(v float64) time.Duration { func FromHours[T langext.NumberConstraint](v T) time.Duration {
return time.Duration(int64(v * float64(time.Second))) return time.Duration(int64(float64(v) * float64(time.Hour)))
} }
func FromMinutes(v int) time.Duration { func FromDays[T langext.NumberConstraint](v T) time.Duration {
return time.Duration(int64(v) * int64(time.Minute)) return time.Duration(int64(float64(v) * float64(24) * float64(time.Hour)))
} }
func FromMinutesFloat(v float64) time.Duration { func FormatNaturalDurationEnglish(iv time.Duration) string {
return time.Duration(int64(v * float64(time.Minute))) if sec := int64(iv.Seconds()); sec < 180 {
if sec == 1 {
return "1 second ago"
} else {
return fmt.Sprintf("%d seconds ago", sec)
}
} }
func FromMinutesFloat64(v float64) time.Duration { if min := int64(iv.Minutes()); min < 180 {
return time.Duration(int64(v * float64(time.Minute))) return fmt.Sprintf("%d minutes ago", min)
} }
func FromHoursFloat64(v float64) time.Duration { if hours := int64(iv.Hours()); hours < 72 {
return time.Duration(int64(v * float64(time.Hour))) return fmt.Sprintf("%d hours ago", hours)
} }
func FromDays(v int) time.Duration { if days := int64(iv.Hours() / 24.0); days < 21 {
return time.Duration(int64(v) * int64(24) * int64(time.Hour)) return fmt.Sprintf("%d days ago", days)
} }
func FromMilliseconds(v int) time.Duration { if weeks := int64(iv.Hours() / 24.0 / 7.0); weeks < 12 {
return time.Duration(int64(v) * int64(time.Millisecond)) return fmt.Sprintf("%d weeks ago", weeks)
} }
func FromMillisecondsFloat(v float64) time.Duration { if months := int64(iv.Hours() / 24.0 / 7.0 / 30); months < 36 {
return time.Duration(int64(v * float64(time.Millisecond))) return fmt.Sprintf("%d months ago", months)
}
years := int64(iv.Hours() / 24.0 / 7.0 / 365)
return fmt.Sprintf("%d years ago", years)
} }

View File

@@ -17,14 +17,14 @@ func init() {
} }
// TimeToDatePart returns a timestamp at the start of the day which contains t (= 00:00:00) // TimeToDatePart returns a timestamp at the start of the day which contains t (= 00:00:00)
func TimeToDatePart(t time.Time) time.Time { func TimeToDatePart(t time.Time, tz *time.Location) time.Time {
t = t.In(TimezoneBerlin) t = t.In(tz)
return time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location()) return time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location())
} }
// TimeToWeekStart returns a timestamp at the start of the week which contains t (= Monday 00:00:00) // TimeToWeekStart returns a timestamp at the start of the week which contains t (= Monday 00:00:00)
func TimeToWeekStart(t time.Time) time.Time { func TimeToWeekStart(t time.Time, tz *time.Location) time.Time {
t = TimeToDatePart(t) t = TimeToDatePart(t, tz)
delta := time.Duration(((int64(t.Weekday()) + 6) % 7) * 24 * int64(time.Hour)) delta := time.Duration(((int64(t.Weekday()) + 6) % 7) * 24 * int64(time.Hour))
t = t.Add(-1 * delta) t = t.Add(-1 * delta)
@@ -33,32 +33,32 @@ func TimeToWeekStart(t time.Time) time.Time {
} }
// TimeToMonthStart returns a timestamp at the start of the month which contains t (= yyyy-MM-00 00:00:00) // TimeToMonthStart returns a timestamp at the start of the month which contains t (= yyyy-MM-00 00:00:00)
func TimeToMonthStart(t time.Time) time.Time { func TimeToMonthStart(t time.Time, tz *time.Location) time.Time {
t = t.In(TimezoneBerlin) t = t.In(tz)
return time.Date(t.Year(), t.Month(), 1, 0, 0, 0, 0, t.Location()) return time.Date(t.Year(), t.Month(), 1, 0, 0, 0, 0, t.Location())
} }
// TimeToMonthEnd returns a timestamp at the end of the month which contains t (= yyyy-MM-31 23:59:59.999999999) // TimeToMonthEnd returns a timestamp at the end of the month which contains t (= yyyy-MM-31 23:59:59.999999999)
func TimeToMonthEnd(t time.Time) time.Time { func TimeToMonthEnd(t time.Time, tz *time.Location) time.Time {
return TimeToMonthStart(t).AddDate(0, 1, 0).Add(-1) return TimeToMonthStart(t, tz).AddDate(0, 1, 0).Add(-1)
} }
// TimeToYearStart returns a timestamp at the start of the year which contains t (= yyyy-01-01 00:00:00) // TimeToYearStart returns a timestamp at the start of the year which contains t (= yyyy-01-01 00:00:00)
func TimeToYearStart(t time.Time) time.Time { func TimeToYearStart(t time.Time, tz *time.Location) time.Time {
t = t.In(TimezoneBerlin) t = t.In(tz)
return time.Date(t.Year(), 1, 1, 0, 0, 0, 0, t.Location()) return time.Date(t.Year(), 1, 1, 0, 0, 0, 0, t.Location())
} }
// TimeToYearEnd returns a timestamp at the end of the month which contains t (= yyyy-12-31 23:59:59.999999999) // TimeToYearEnd returns a timestamp at the end of the month which contains t (= yyyy-12-31 23:59:59.999999999)
func TimeToYearEnd(t time.Time) time.Time { func TimeToYearEnd(t time.Time, tz *time.Location) time.Time {
return TimeToYearStart(t).AddDate(1, 0, 0).Add(-1) return TimeToYearStart(t, tz).AddDate(1, 0, 0).Add(-1)
} }
// IsSameDayIncludingDateBoundaries returns true if t1 and t2 are part of the same day (TZ/Berlin), the boundaries of the day are // IsSameDayIncludingDateBoundaries returns true if t1 and t2 are part of the same day (TZ/Berlin), the boundaries of the day are
// inclusive, this means 2021-09-15T00:00:00 is still part of the day 2021-09-14 // inclusive, this means 2021-09-15T00:00:00 is still part of the day 2021-09-14
func IsSameDayIncludingDateBoundaries(t1 time.Time, t2 time.Time) bool { func IsSameDayIncludingDateBoundaries(t1 time.Time, t2 time.Time, tz *time.Location) bool {
dp1 := TimeToDatePart(t1) dp1 := TimeToDatePart(t1, tz)
dp2 := TimeToDatePart(t2) dp2 := TimeToDatePart(t2, tz)
if dp1.Equal(dp2) { if dp1.Equal(dp2) {
return true return true
@@ -72,9 +72,9 @@ func IsSameDayIncludingDateBoundaries(t1 time.Time, t2 time.Time) bool {
} }
// IsDatePartEqual returns true if a and b have the same date part (`yyyy`, `MM` and `dd`) // IsDatePartEqual returns true if a and b have the same date part (`yyyy`, `MM` and `dd`)
func IsDatePartEqual(a time.Time, b time.Time) bool { func IsDatePartEqual(a time.Time, b time.Time, tz *time.Location) bool {
yy1, mm1, dd1 := a.In(TimezoneBerlin).Date() yy1, mm1, dd1 := a.In(tz).Date()
yy2, mm2, dd2 := b.In(TimezoneBerlin).Date() yy2, mm2, dd2 := b.In(tz).Date()
return yy1 == yy2 && mm1 == mm2 && dd1 == dd2 return yy1 == yy2 && mm1 == mm2 && dd1 == dd2
} }
@@ -82,9 +82,9 @@ func IsDatePartEqual(a time.Time, b time.Time) bool {
// WithTimePart returns a timestamp with the date-part (`yyyy`, `MM`, `dd`) from base // WithTimePart returns a timestamp with the date-part (`yyyy`, `MM`, `dd`) from base
// and the time (`HH`, `mm`, `ss`) from the parameter // and the time (`HH`, `mm`, `ss`) from the parameter
func WithTimePart(base time.Time, hour, minute, second int) time.Time { func WithTimePart(base time.Time, hour, minute, second int) time.Time {
datepart := TimeToDatePart(base) datepart := TimeToDatePart(base, base.Location())
delta := time.Duration(hour*int(time.Hour) + minute*int(time.Minute) + second*int(time.Second)) delta := time.Duration(int64(hour)*int64(time.Hour) + int64(minute)*int64(time.Minute) + int64(second)*int64(time.Second))
return datepart.Add(delta) return datepart.Add(delta)
} }
@@ -92,23 +92,23 @@ func WithTimePart(base time.Time, hour, minute, second int) time.Time {
// CombineDateAndTime returns a timestamp with the date-part (`yyyy`, `MM`, `dd`) from the d parameter // CombineDateAndTime returns a timestamp with the date-part (`yyyy`, `MM`, `dd`) from the d parameter
// and the time (`HH`, `mm`, `ss`) from the t parameter // and the time (`HH`, `mm`, `ss`) from the t parameter
func CombineDateAndTime(d time.Time, t time.Time) time.Time { func CombineDateAndTime(d time.Time, t time.Time) time.Time {
datepart := TimeToDatePart(d) datepart := TimeToDatePart(d, d.Location())
delta := time.Duration(t.Hour()*int(time.Hour) + t.Minute()*int(time.Minute) + t.Second()*int(time.Second) + t.Nanosecond()*int(time.Nanosecond)) delta := time.Duration(int64(t.Hour())*int64(time.Hour) + int64(t.Minute())*int64(time.Minute) + int64(t.Second())*int64(time.Second) + int64(t.Nanosecond())*int64(time.Nanosecond))
return datepart.Add(delta) return datepart.Add(delta)
} }
// IsSunday returns true if t is a sunday (in TZ/Berlin) // IsSunday returns true if t is a sunday (in TZ/Berlin)
func IsSunday(t time.Time) bool { func IsSunday(t time.Time, tz *time.Location) bool {
if t.In(TimezoneBerlin).Weekday() == time.Sunday { if t.In(tz).Weekday() == time.Sunday {
return true return true
} }
return false return false
} }
func DurationFromTime(hours int, minutes int, seconds int) time.Duration { func DurationFromTime(hours int, minutes int, seconds int) time.Duration {
return time.Duration(hours*int(time.Hour) + minutes*int(time.Minute) + seconds*int(time.Second)) return time.Duration(int64(hours)*int64(time.Hour) + int64(minutes)*int64(time.Minute) + int64(seconds)*int64(time.Second))
} }
func Min(a time.Time, b time.Time) time.Time { func Min(a time.Time, b time.Time) time.Time {
@@ -131,3 +131,7 @@ func UnixFloatSeconds(v float64) time.Time {
sec, dec := math.Modf(v) sec, dec := math.Modf(v)
return time.Unix(int64(sec), int64(dec*(1e9))) return time.Unix(int64(sec), int64(dec*(1e9)))
} }
func FloorTime(t time.Time) time.Time {
return time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location())
}