diff options
Diffstat (limited to 'lib')
49 files changed, 163 insertions, 264 deletions
diff --git a/lib/ascii/set.go b/lib/ascii/set.go index 6e867287..1c813db9 100644 --- a/lib/ascii/set.go +++ b/lib/ascii/set.go @@ -106,8 +106,8 @@ func (as *Set) Equal(as2 Set) bool { // the set in any other way. func (as *Set) Visit(do func(n byte) (skip bool)) (aborted bool) { var currentChar byte - for i := uint(0); i < 4; i++ { - for j := uint(0); j < 32; j++ { + for i := range uint(4) { + for j := range uint(32) { if (as[i] & (1 << j)) != 0 { if do(currentChar) { return true diff --git a/lib/ascii/set_benchmark_test.go b/lib/ascii/set_benchmark_test.go index 53194daa..030ef82d 100644 --- a/lib/ascii/set_benchmark_test.go +++ b/lib/ascii/set_benchmark_test.go @@ -22,7 +22,7 @@ const N int = 10 // if populate is true, fill each set with every 2nd ASCII character func setupSets(populate bool) []Set { sets := []Set{} - for i := 0; i < N; i++ { + for range N { var as Set if populate { for c := 0; c < utf8.RuneSelf; c += 2 { @@ -41,7 +41,7 @@ func setupSets(populate bool) []Set { // if populate is true, fill each set with every 2nd ASCII character func setupMapSets(populate bool) []map[byte]struct{} { sets := []map[byte]struct{}{} - for i := 0; i < N; i++ { + for range N { as := make(map[byte]struct{}) if populate { for c := 0; c < utf8.RuneSelf; c += 2 { @@ -73,7 +73,7 @@ func BenchmarkSet(b *testing.B) { b.ResetTimer() for i := 0; i < b.N; i++ { for _, as := range sets { - for c := byte(0); c < utf8.RuneSelf; c++ { + for c := range byte(utf8.RuneSelf) { exists = as.Contains(c) } } @@ -85,7 +85,7 @@ func BenchmarkSet(b *testing.B) { b.ResetTimer() for i := 0; i < b.N; i++ { for _, as := range sets { - for c := byte(0); c < utf8.RuneSelf; c++ { + for c := range byte(utf8.RuneSelf) { as.Remove(c) } } @@ -97,7 +97,7 @@ func BenchmarkSet(b *testing.B) { b.ResetTimer() for i := 0; i < b.N; i++ { for _, as := range sets { - for c := byte(0); c < utf8.RuneSelf; c++ { + for range byte(utf8.RuneSelf) { size = as.Size() } } @@ -139,7 +139,7 @@ func BenchmarkMapSet(b *testing.B) { b.ResetTimer() for i := 0; i < b.N; i++ { for _, as := range sets { - for c := byte(0); c < utf8.RuneSelf; c++ { + for c := range byte(utf8.RuneSelf) { _, exists = as[c] } } @@ -151,7 +151,7 @@ func BenchmarkMapSet(b *testing.B) { b.ResetTimer() for i := 0; i < b.N; i++ { for _, as := range sets { - for c := byte(0); c < utf8.RuneSelf; c++ { + for c := range byte(utf8.RuneSelf) { delete(as, c) } } @@ -163,7 +163,7 @@ func BenchmarkMapSet(b *testing.B) { b.ResetTimer() for i := 0; i < b.N; i++ { for _, as := range sets { - for c := byte(0); c < utf8.RuneSelf; c++ { + for range byte(utf8.RuneSelf) { size = len(as) } } diff --git a/lib/bytes/bytes.go b/lib/bytes/bytes.go index f0f55555..b79fd7cb 100644 --- a/lib/bytes/bytes.go +++ b/lib/bytes/bytes.go @@ -342,14 +342,8 @@ func SkipAfterToken(text, token []byte, startAt int, checkEsc bool) (int, bool) func SnippetByIndexes(s []byte, indexes []int, sniplen int) (snippets [][]byte) { var start, end int for _, idx := range indexes { - start = idx - sniplen - if start < 0 { - start = 0 - } - end = idx + sniplen - if end > len(s) { - end = len(s) - } + start = max(idx-sniplen, 0) + end = min(idx+sniplen, len(s)) snippets = append(snippets, s[start:end]) } diff --git a/lib/contact/google/address.go b/lib/contact/google/address.go index 563ae101..457a4aed 100644 --- a/lib/contact/google/address.go +++ b/lib/contact/google/address.go @@ -6,11 +6,11 @@ package google // Address format. type Address struct { Rel string `json:"rel,omitempty"` - Full GD `json:"gd$formattedAddress,omitempty"` - POBox GD `json:"gd$pobox,omitempty"` - Street GD `json:"gd$street,omitempty"` - City GD `json:"gd$city,omitempty"` - StateOrProv GD `json:"gd$region,omitempty"` - PostalCode GD `json:"gd$postcode,omitempty"` - Country GD `json:"gd$country,omitempty"` + Full GD `json:"gd$formattedAddress"` + POBox GD `json:"gd$pobox"` + Street GD `json:"gd$street"` + City GD `json:"gd$city"` + StateOrProv GD `json:"gd$region"` + PostalCode GD `json:"gd$postcode"` + Country GD `json:"gd$country"` } diff --git a/lib/contact/google/author.go b/lib/contact/google/author.go index 65ae94a6..b6a19c83 100644 --- a/lib/contact/google/author.go +++ b/lib/contact/google/author.go @@ -5,6 +5,6 @@ package google // Author define Google contacts author. type Author struct { - Name GD `json:"name,omitempty"` - Email GD `json:"email,omitempty"` + Name GD `json:"name"` + Email GD `json:"email"` } diff --git a/lib/contact/google/contact.go b/lib/contact/google/contact.go index 111643c9..5d27ed32 100644 --- a/lib/contact/google/contact.go +++ b/lib/contact/google/contact.go @@ -21,8 +21,8 @@ type Contact struct { // Title GD `json:"title,omitempty"` // Links []Link `json:"link,omitempty"` - Name Name `json:"gd$name,omitempty"` - Birthday Birthday `json:"gContact$birthday,omitempty"` + Name Name `json:"gd$name"` + Birthday Birthday `json:"gContact$birthday"` Orgs []Org `json:"gd$organization,omitempty"` Emails []Email `json:"gd$email,omitempty"` Phones []Phone `json:"gd$phoneNumber,omitempty"` diff --git a/lib/contact/google/event.go b/lib/contact/google/event.go index a84cedc3..ce4bf51f 100644 --- a/lib/contact/google/event.go +++ b/lib/contact/google/event.go @@ -6,5 +6,5 @@ package google // Event format. type Event struct { Rel string `json:"rel,omitempty"` - When EventTime `json:"gd$when,omitempty"` + When EventTime `json:"gd$when"` } diff --git a/lib/contact/google/feed.go b/lib/contact/google/feed.go index fbbc3584..aa3716a6 100644 --- a/lib/contact/google/feed.go +++ b/lib/contact/google/feed.go @@ -25,6 +25,6 @@ type Feed struct { // StartIndex GD `json:"openSearch$startIndex,omitempty"` // ItemsPerPage GD `json:"openSearch$itemsPerPage,omitempty"` - TotalResult GD `json:"openSearch$totalResults,omitempty"` + TotalResult GD `json:"openSearch$totalResults"` Contacts []Contact `json:"entry,omitempty"` } diff --git a/lib/contact/google/name.go b/lib/contact/google/name.go index cf78025b..1ab2fcd7 100644 --- a/lib/contact/google/name.go +++ b/lib/contact/google/name.go @@ -5,10 +5,10 @@ package google // Name define Google contact name format. type Name struct { - Prefix GD `json:"gd$namePrefix,omitempty"` - First GD `json:"gd$givenName,omitempty"` - Middle GD `json:"gd$additionalName,omitempty"` - Last GD `json:"gd$familyName,omitempty"` - Suffix GD `json:"gd$nameSuffix,omitempty"` - Full GD `json:"gd$fullName,omitempty"` + Prefix GD `json:"gd$namePrefix"` + First GD `json:"gd$givenName"` + Middle GD `json:"gd$additionalName"` + Last GD `json:"gd$familyName"` + Suffix GD `json:"gd$nameSuffix"` + Full GD `json:"gd$fullName"` } diff --git a/lib/contact/google/org.go b/lib/contact/google/org.go index c2cb8b1f..5cc9683e 100644 --- a/lib/contact/google/org.go +++ b/lib/contact/google/org.go @@ -6,6 +6,6 @@ package google // Org as organisation. type Org struct { Type string `json:"rel,omitempty"` - Name GD `json:"gd$orgName,omitempty"` - JobTitle GD `json:"gd$orgTitle,omitempty"` + Name GD `json:"gd$orgName"` + JobTitle GD `json:"gd$orgTitle"` } diff --git a/lib/contact/google/root.go b/lib/contact/google/root.go index e5cbff53..922f945e 100644 --- a/lib/contact/google/root.go +++ b/lib/contact/google/root.go @@ -7,5 +7,5 @@ package google type Root struct { Version string `json:"version,omitempty"` Encoding string `json:"encoding,omitempty"` - Feed Feed `json:"feed,omitempty"` + Feed Feed `json:"feed"` } diff --git a/lib/contact/microsoft/contact.go b/lib/contact/microsoft/contact.go index cb36594b..ea81168d 100644 --- a/lib/contact/microsoft/contact.go +++ b/lib/contact/microsoft/contact.go @@ -53,9 +53,9 @@ type Contact struct { SpouseName string `json:"spouseName,omitempty"` PersonalNotes string `json:"personalNotes,omitempty"` - HomeAddress Address `json:"homeAddress,omitempty"` - BusinessAddress Address `json:"businessAddress,omitempty"` - OtherAddress Address `json:"otherAddress,omitempty"` + HomeAddress Address `json:"homeAddress"` + BusinessAddress Address `json:"businessAddress"` + OtherAddress Address `json:"otherAddress"` IMAddresses []string `json:"imAddresses,omitempty"` HomePhones []string `json:"homePhones,omitempty"` diff --git a/lib/dns/idpool.go b/lib/dns/idpool.go index 1f6b8147..53226fbc 100644 --- a/lib/dns/idpool.go +++ b/lib/dns/idpool.go @@ -7,22 +7,22 @@ import ( "sync/atomic" ) -var idPool uint32 +var idPool atomic.Uint32 // getNextID increment and return ID. func getNextID() uint16 { - atomic.AddUint32(&idPool, 1) - var id = atomic.LoadUint32(&idPool) + idPool.Add(1) + var id = idPool.Load() return uint16(id) } // getID return the current ID value in pool. func getID() uint16 { - var id = atomic.LoadUint32(&idPool) + var id = idPool.Load() return uint16(id) } func resetIDPool() { - atomic.StoreUint32(&idPool, 0) + idPool.Store(0) } diff --git a/lib/dns/udp_client_pool_test.go b/lib/dns/udp_client_pool_test.go index 88e52d75..a841708c 100644 --- a/lib/dns/udp_client_pool_test.go +++ b/lib/dns/udp_client_pool_test.go @@ -57,8 +57,7 @@ func TestNewUDPClientPool(t *testing.T) { qname = "kilabit.info" for range 10 { - wg.Add(1) - go func() { + wg.Go(func() { var ( cl = clPool.Get() q = MessageQuestion{ @@ -71,8 +70,7 @@ func TestNewUDPClientPool(t *testing.T) { if err != nil { t.Log("Lookup error: ", err.Error()) } - wg.Done() - }() + }) } wg.Wait() } diff --git a/lib/dsv/reader.go b/lib/dsv/reader.go index 4bde7060..891b97b9 100644 --- a/lib/dsv/reader.go +++ b/lib/dsv/reader.go @@ -523,7 +523,7 @@ func (reader *Reader) IsEqual(other *Reader) bool { return false } - for a := 0; a < l; a++ { + for a := range l { if !reader.InputMetadata[a].IsEqual(&other.InputMetadata[a]) { return false } diff --git a/lib/email/dkim/keyflag.go b/lib/email/dkim/keyflag.go index 6e950a6f..d1cb74eb 100644 --- a/lib/email/dkim/keyflag.go +++ b/lib/email/dkim/keyflag.go @@ -6,6 +6,7 @@ package dkim import ( "bytes" + "slices" ) // KeyFlag define a type of key flag in DKIM key record. @@ -46,10 +47,8 @@ func unpackKeyFlags(in []byte) (out []KeyFlag) { } func insertKeyFlag(flags *[]KeyFlag, key KeyFlag) { - for _, v := range *flags { - if v == key { - return - } + if slices.Contains(*flags, key) { + return } *flags = append(*flags, key) } diff --git a/lib/email/dkim/signature.go b/lib/email/dkim/signature.go index 3a8aeeff..278a4e17 100644 --- a/lib/email/dkim/signature.go +++ b/lib/email/dkim/signature.go @@ -489,9 +489,9 @@ func (sig *Signature) set(t *tag) (err error) { // setQueryMethods parse list of query methods and set Signature.QueryMethod // based on first match. func (sig *Signature) setQueryMethods(v []byte) { - methods := bytes.Split(v, sepColon) + methods := bytes.SplitSeq(v, sepColon) - for _, m := range methods { + for m := range methods { var qtype, qopt []byte kv := bytes.Split(m, sepSlash) diff --git a/lib/http/form.go b/lib/http/form.go index e746b403..cfc77b1b 100644 --- a/lib/http/form.go +++ b/lib/http/form.go @@ -34,7 +34,7 @@ func MarshalForm(in any) (out url.Values, err error) { x int ) - if inKind == reflect.Ptr { + if inKind == reflect.Pointer { inType = inType.Elem() inKind = inType.Kind() } @@ -166,7 +166,7 @@ func UnmarshalForm(in url.Values, out any) (err error) { hasTag bool ) - if rkind != reflect.Ptr { + if rkind != reflect.Pointer { return fmt.Errorf("%s: expecting *T got %T", logp, out) } @@ -177,7 +177,7 @@ func UnmarshalForm(in url.Values, out any) (err error) { vout = vout.Elem() rtype = rtype.Elem() rkind = rtype.Kind() - if rkind == reflect.Ptr { + if rkind == reflect.Pointer { rtype = rtype.Elem() rkind = rtype.Kind() if rkind != reflect.Struct { @@ -232,7 +232,7 @@ func UnmarshalForm(in url.Values, out any) (err error) { rtype = fval.Type() rkind = fval.Kind() - if rkind == reflect.Ptr { + if rkind == reflect.Pointer { // F *T rtype = rtype.Elem() // T <= *T rkind = rtype.Kind() diff --git a/lib/http/range_example_test.go b/lib/http/range_example_test.go index 0f53b9b7..80c6e15f 100644 --- a/lib/http/range_example_test.go +++ b/lib/http/range_example_test.go @@ -106,27 +106,25 @@ func ExampleParseRange() { // bytes=0-9,10-19,-20 } -func ptrInt64(v int64) *int64 { return &v } - func ExampleRange_Add() { var listpos = []struct { start *int64 end *int64 }{ - {ptrInt64(0), ptrInt64(9)}, // OK. - {ptrInt64(0), ptrInt64(5)}, // Overlap with [0,9]. - {ptrInt64(9), ptrInt64(19)}, // Overlap with [0,9]. + {new(int64(0)), new(int64(9))}, // OK. + {new(int64(0)), new(int64(5))}, // Overlap with [0,9]. + {new(int64(9)), new(int64(19))}, // Overlap with [0,9]. - {ptrInt64(10), ptrInt64(19)}, // OK. - {ptrInt64(19), ptrInt64(20)}, // Overlap with [10,19]. - {ptrInt64(20), ptrInt64(19)}, // End less than start. + {new(int64(10)), new(int64(19))}, // OK. + {new(int64(19)), new(int64(20))}, // Overlap with [10,19]. + {new(int64(20)), new(int64(19))}, // End less than start. - {nil, ptrInt64(10)}, // OK. - {nil, ptrInt64(20)}, // Overlap with [nil,10]. + {nil, new(int64(10))}, // OK. + {nil, new(int64(20))}, // Overlap with [nil,10]. - {ptrInt64(20), nil}, // Overlap with [nil,10]. - {ptrInt64(30), ptrInt64(40)}, // Overlap with [20,nil]. - {ptrInt64(30), nil}, // Overlap with [20,nil]. + {new(int64(20)), nil}, // Overlap with [nil,10]. + {new(int64(30)), new(int64(40))}, // Overlap with [20,nil]. + {new(int64(30)), nil}, // Overlap with [20,nil]. } var r = libhttp.NewRange(``) @@ -153,7 +151,7 @@ func ExampleRange_Positions() { var r = libhttp.NewRange(``) fmt.Println(r.Positions()) // Empty positions. - r.Add(ptrInt64(10), ptrInt64(20)) + r.Add(new(int64(10)), new(int64(20))) fmt.Println(r.Positions()) // Output: // [] @@ -165,7 +163,7 @@ func ExampleRange_String() { fmt.Println(r.String()) // Empty range will return empty string. - r.Add(ptrInt64(0), ptrInt64(9)) + r.Add(new(int64(0)), new(int64(9))) fmt.Println(r.String()) // Output: // diff --git a/lib/http/range_position_test.go b/lib/http/range_position_test.go index 8fc2afd4..83f08358 100644 --- a/lib/http/range_position_test.go +++ b/lib/http/range_position_test.go @@ -54,14 +54,12 @@ func TestParseContentRange(t *testing.T) { } } -func ptrInt64(v int64) *int64 { return &v } - func TestRangePositionContentRange(t *testing.T) { var ( unit = AcceptRangesBytes pos = RangePosition{ - start: ptrInt64(10), - end: ptrInt64(20), + start: new(int64(10)), + end: new(int64(20)), } ) diff --git a/lib/ini/common_test.go b/lib/ini/common_test.go index c41de518..64190ce5 100644 --- a/lib/ini/common_test.go +++ b/lib/ini/common_test.go @@ -105,14 +105,13 @@ func TestParseTag_fromStruct(t *testing.T) { {`a`, `b ": c`, `d`, ``}, } - adt ADT vtype reflect.Type field reflect.StructField tag string got []string ) - vtype = reflect.TypeOf(adt) + vtype = reflect.TypeFor[ADT]() for x := range vtype.NumField() { field = vtype.Field(x) diff --git a/lib/ini/ini.go b/lib/ini/ini.go index a75ac0d2..419018d0 100644 --- a/lib/ini/ini.go +++ b/lib/ini/ini.go @@ -114,7 +114,7 @@ func Marshal(v any) (b []byte, err error) { rvalue := reflect.ValueOf(v) kind := rtipe.Kind() - for kind == reflect.Ptr { + for kind == reflect.Pointer { rtipe = rtipe.Elem() rvalue = rvalue.Elem() kind = rtipe.Kind() @@ -194,7 +194,7 @@ func (in *Ini) marshalStruct( } key = strings.ToLower(key) - for kind == reflect.Ptr { + for kind == reflect.Pointer { ftype = ftype.Elem() kind = ftype.Kind() fvalue = fvalue.Elem() @@ -209,7 +209,7 @@ func (in *Ini) marshalStruct( case reflect.Array, reflect.Slice: for xx := 0; xx < fvalue.Len(); xx++ { item := fvalue.Index(xx) - for item.Kind() == reflect.Ptr { + for item.Kind() == reflect.Pointer { item = item.Elem() } switch item.Kind() { @@ -255,7 +255,7 @@ func (in *Ini) marshalStruct( for _, key = range keys { mapValue = amap[key] valueType = reflect.TypeOf(mapValue.Interface()) - for valueType.Kind() == reflect.Ptr { + for valueType.Kind() == reflect.Pointer { valueType = valueType.Elem() mapValue = mapValue.Elem() } @@ -267,8 +267,8 @@ func (in *Ini) marshalStruct( } } - case reflect.Ptr: - for ftype.Kind() == reflect.Ptr { + case reflect.Pointer: + for ftype.Kind() == reflect.Pointer { ftype = ftype.Elem() fvalue = fvalue.Elem() } @@ -328,7 +328,7 @@ func (in *Ini) Unmarshal(v any) (err error) { rvalue := reflect.ValueOf(v) kind := rtipe.Kind() - for kind != reflect.Ptr { + for kind != reflect.Pointer { return fmt.Errorf("ini: Unmarshal: expecting pointer to struct, got %v", kind) } diff --git a/lib/ini/ini_unmarshal.go b/lib/ini/ini_unmarshal.go index aed1548e..b999c36c 100644 --- a/lib/ini/ini_unmarshal.go +++ b/lib/ini/ini_unmarshal.go @@ -46,8 +46,8 @@ func (in *Ini) unmarshal(tagField *tagStructField) { case reflect.Map: unmarshalToMap(sec, sfield.ftype, sfield.fval) - case reflect.Ptr: - for sfield.fkind == reflect.Ptr { + case reflect.Pointer: + for sfield.fkind == reflect.Pointer { sfield.ftype = sfield.ftype.Elem() sfield.fkind = sfield.ftype.Kind() } @@ -72,9 +72,9 @@ func (in *Ini) unmarshal(tagField *tagStructField) { newSlice := reflect.Append(sfield.fval, newStruct.Elem()) sfield.fval.Set(newSlice) - case reflect.Ptr: + case reflect.Pointer: // V []*T - for sliceElem.Kind() == reflect.Ptr { + for sliceElem.Kind() == reflect.Pointer { sliceElem = sliceElem.Elem() } @@ -127,7 +127,7 @@ func unmarshalToMap(sec *Section, rtype reflect.Type, rval reflect.Value) bool { } else { amap = rval } - for elKind == reflect.Ptr { + for elKind == reflect.Pointer { elType = elType.Elem() elKind = elType.Kind() isPtr = true diff --git a/lib/ini/struct_field.go b/lib/ini/struct_field.go index 0b4a1222..e31ed176 100644 --- a/lib/ini/struct_field.go +++ b/lib/ini/struct_field.go @@ -37,8 +37,8 @@ func (sfield *structField) set(val string) bool { return true } - case reflect.Ptr: - for sfield.fkind == reflect.Ptr { + case reflect.Pointer: + for sfield.fkind == reflect.Pointer { sfield.ftype = sfield.ftype.Elem() sfield.fkind = sfield.ftype.Kind() } @@ -96,8 +96,8 @@ func (sfield *structField) append(val string) (slice reflect.Value, ok bool) { slice = reflect.Append(slice, reflect.ValueOf(t)) } - case reflect.Ptr: - for ftype.Kind() == reflect.Ptr { + case reflect.Pointer: + for ftype.Kind() == reflect.Pointer { ftype = ftype.Elem() } diff --git a/lib/ini/tag_struct_field.go b/lib/ini/tag_struct_field.go index 672d5c97..8a6b42e0 100644 --- a/lib/ini/tag_struct_field.go +++ b/lib/ini/tag_struct_field.go @@ -53,7 +53,7 @@ func unpackTagStructField(rtype reflect.Type, rval reflect.Value) (out *tagStruc out.v[key] = sf } - case reflect.Ptr: + case reflect.Pointer: if fval.IsNil() { continue } diff --git a/lib/memfs/memfs_test.go b/lib/memfs/memfs_test.go index 86d2cc26..dab393eb 100644 --- a/lib/memfs/memfs_test.go +++ b/lib/memfs/memfs_test.go @@ -12,6 +12,7 @@ import ( "log" "os" "path/filepath" + "slices" "testing" "time" @@ -393,13 +394,7 @@ func TestMemFS_Get(t *testing.T) { continue } - found := false - for _, expCT := range c.expContentType { - if expCT == got.ContentType { - found = true - break - } - } + found := slices.Contains(c.expContentType, got.ContentType) if !found { t.Errorf("expecting one of the Content-Type %v, got %s", c.expContentType, got.ContentType) diff --git a/lib/mining/classifier/cart/cart.go b/lib/mining/classifier/cart/cart.go index d72fb929..6de005cf 100644 --- a/lib/mining/classifier/cart/cart.go +++ b/lib/mining/classifier/cart/cart.go @@ -357,7 +357,7 @@ func (runtime *Runtime) ClassifySet(data tabula.ClasetInterface) (e error) { nrow := data.GetNRow() targetAttr := data.GetClassColumn() - for i := 0; i < nrow; i++ { + for i := range nrow { class := runtime.Classify(data.GetRow(i)) _ = targetAttr.Records[i].SetValue(class, tabula.TString) diff --git a/lib/mining/classifier/cm.go b/lib/mining/classifier/cm.go index 48cf37b8..7358b92e 100644 --- a/lib/mining/classifier/cm.go +++ b/lib/mining/classifier/cm.go @@ -77,7 +77,7 @@ func (cm *CM) ComputeStrings(valueSpace, targets, predictions []string) { cm.computeClassError() } -// ComputeNumeric will calculate confusion matrix using targets and predictions +// ComputeNumeric calculates confusion matrix using targets and predictions // values. func (cm *CM) ComputeNumeric(vs, actuals, predictions []int64) { cm.initByNumeric(vs) @@ -141,16 +141,13 @@ func (cm *CM) countTargetPrediction(target, predict string, return } -// countNumeric will count and return number of `pred` in predictions where -// actuals value is `act`. +// countNumeric returns count of `pred` in predictions where actuals value is +// `act`. func (cm *CM) countNumeric(act, pred int64, actuals, predictions []int64) ( cnt int64, ) { // Find minimum length to mitigate out-of-range loop. - minlen := len(actuals) - if len(predictions) < minlen { - minlen = len(predictions) - } + minlen := min(len(predictions), len(actuals)) for x := range minlen { if actuals[x] != act { diff --git a/lib/mining/classifier/stats_interface.go b/lib/mining/classifier/stats_interface.go index 38599d23..6d5c4baa 100644 --- a/lib/mining/classifier/stats_interface.go +++ b/lib/mining/classifier/stats_interface.go @@ -50,10 +50,7 @@ func ComputeAccuracies(tp, fp, tn, fn []int64) (accuracies []float64) { // and `end` timestamps. func ComputeElapsedTimes(start, end []int64) (elaps []int64) { // Get minimum length. - minlen := len(start) - if len(end) < minlen { - minlen = len(end) - } + minlen := min(len(end), len(start)) for x := range minlen { elaps = append(elaps, end[x]-start[x]) diff --git a/lib/mining/knn/knn.go b/lib/mining/knn/knn.go index 977e6dc6..71c60cc9 100644 --- a/lib/mining/knn/knn.go +++ b/lib/mining/knn/knn.go @@ -80,10 +80,7 @@ func (in *Runtime) FindNeighbors(samples *tabula.Rows, instance *tabula.Row) ( } // Make sure number of neighbors is greater than request. - minK := in.AllNeighbors.Len() - if minK > in.K { - minK = in.K - } + minK := min(in.AllNeighbors.Len(), in.K) kneighbors = in.AllNeighbors.SelectRange(0, minK) diff --git a/lib/numbers/int.go b/lib/numbers/int.go index e6fa450c..dd0185d4 100644 --- a/lib/numbers/int.go +++ b/lib/numbers/int.go @@ -7,6 +7,7 @@ import ( "crypto/rand" "log" "math/big" + "slices" ) // IntCreateSeq will create and return sequence of integer from `min` to @@ -50,13 +51,7 @@ func IntPickRandPositive(maxVal int, dup bool, pickedListID, exsListID []int) (i idx = int(randv.Int64()) // Check in exclude indices. - excluded = false - for _, v := range exsListID { - if idx == v { - excluded = true - break - } - } + excluded = slices.Contains(exsListID, idx) if excluded { continue } @@ -67,13 +62,7 @@ func IntPickRandPositive(maxVal int, dup bool, pickedListID, exsListID []int) (i } // Check if its already picked. - picked = false - for _, v := range pickedListID { - if idx == v { - picked = true - break - } - } + picked = slices.Contains(pickedListID, idx) if picked { // Get another random idx again. diff --git a/lib/reflect/example_test.go b/lib/reflect/example_test.go index 69970fea..a2a4befa 100644 --- a/lib/reflect/example_test.go +++ b/lib/reflect/example_test.go @@ -453,7 +453,6 @@ func ExampleTag() { } var ( - t T vtype reflect.Type field reflect.StructField val string @@ -461,10 +460,10 @@ func ExampleTag() { hasTag bool ) - vtype = reflect.TypeOf(t) + vtype = reflect.TypeFor[T]() - for x := range vtype.NumField() { - field = vtype.Field(x) + for field0 := range vtype.Fields() { + field = field0 val, opts, hasTag = libreflect.Tag(field, "atag") fmt.Println(val, opts, hasTag) } diff --git a/lib/reflect/reflect.go b/lib/reflect/reflect.go index 2b344329..86d65628 100644 --- a/lib/reflect/reflect.go +++ b/lib/reflect/reflect.go @@ -68,7 +68,7 @@ func IsNil(v any) bool { kind == reflect.Func || kind == reflect.Interface || kind == reflect.Map || - kind == reflect.Ptr || + kind == reflect.Pointer || kind == reflect.Slice { return val.IsNil() } @@ -104,7 +104,7 @@ func Marshal(obj any) (out []byte, err error) { ok bool ) - if objKind == reflect.Ptr && objValue.IsNil() { + if objKind == reflect.Pointer && objValue.IsNil() { return nil, nil } @@ -167,7 +167,7 @@ func Set(obj reflect.Value, val string) (err error) { objValue reflect.Value ) - if objKind != reflect.Ptr { + if objKind != reflect.Pointer { // Variable passed value (V T). return fmt.Errorf("%s: object %T is not setable", logp, obj.Interface()) } @@ -177,7 +177,7 @@ func Set(obj reflect.Value, val string) (err error) { objType = objType.Elem() objKind = objType.Kind() - if objKind == reflect.Ptr { + if objKind == reflect.Pointer { // Variable is passed as **T. if obj.IsNil() { objType = objType.Elem() @@ -246,11 +246,11 @@ func setSlice(slice reflect.Value, val string) (sliceOut reflect.Value, err erro sliceType = sliceType.Elem() // T = []T sliceKind = sliceType.Kind() - if sliceKind == reflect.Ptr { + if sliceKind == reflect.Pointer { sliceType = sliceType.Elem() sliceKind = sliceType.Kind() - if sliceKind == reflect.Ptr { + if sliceKind == reflect.Pointer { elValue = reflect.New(sliceType) // var t = new(*T) sliceType = sliceType.Elem() // *T <= **T ptrValue = reflect.New(sliceType) // var pt = new(T) @@ -288,7 +288,7 @@ func setValue(obj reflect.Value, val string) (err error) { v any ) - for objKind == reflect.Ptr { + for objKind == reflect.Pointer { objType = objType.Elem() objKind = objType.Kind() } @@ -442,7 +442,7 @@ func Unmarshal(obj reflect.Value, val []byte) (ok bool, err error) { methodName string ) - if objKind != reflect.Ptr { + if objKind != reflect.Pointer { // Variable passed as is (V T). return false, nil } @@ -452,7 +452,7 @@ func Unmarshal(obj reflect.Value, val []byte) (ok bool, err error) { objType = objType.Elem() objKind = objType.Kind() - if objKind == reflect.Ptr { + if objKind == reflect.Pointer { // Variable is passed as **T. if obj.IsNil() { objType = objType.Elem() @@ -677,7 +677,7 @@ func doEqual(v1, v2 reflect.Value) (err error) { case reflect.Map: return doEqualMap(v1, v2) - case reflect.Ptr: + case reflect.Pointer: if v1.IsNil() && v2.IsNil() { return nil } @@ -769,7 +769,7 @@ func doEqualMap(v1, v2 reflect.Value) (err error) { // fields has equal value. // The type of both struct is already equal when this function called. func doEqualStruct(v1, v2 reflect.Value) (err error) { - var equalerType = reflect.TypeOf((*Equaler)(nil)).Elem() + var equalerType = reflect.TypeFor[Equaler]() if v1.Type().Implements(equalerType) { var m1 = v1.MethodByName(`Equal`) var callIn = []reflect.Value{v2.Addr()} diff --git a/lib/smtp/smtp.go b/lib/smtp/smtp.go index f7121280..4a91079a 100644 --- a/lib/smtp/smtp.go +++ b/lib/smtp/smtp.go @@ -7,6 +7,7 @@ package smtp import ( "bytes" "errors" + "slices" "git.sr.ht/~shulhan/pakakeh.go/lib/ascii" ) @@ -207,12 +208,9 @@ func parseLocalDomain(data []byte, allow []byte) (out []byte) { continue } found = false - for _, c := range allow { - if c == data[x] { - out = append(out, data[x]) - found = true - break - } + if slices.Contains(allow, data[x]) { + out = append(out, data[x]) + found = true } if found { continue diff --git a/lib/ssh/sftp/file_attrs.go b/lib/ssh/sftp/file_attrs.go index a4a8995d..db37637a 100644 --- a/lib/ssh/sftp/file_attrs.go +++ b/lib/ssh/sftp/file_attrs.go @@ -112,7 +112,7 @@ func unpackFileAttrs(payload []byte) (fa *FileAttrs, length int) { length += 4 fa.exts = make(extensions, n) - for x := uint32(0); x < n; x++ { + for range n { size := binary.BigEndian.Uint32(payload[:4]) payload = payload[4:] length += 4 diff --git a/lib/ssh/sftp/packet.go b/lib/ssh/sftp/packet.go index 8fa95c9e..c699d922 100644 --- a/lib/ssh/sftp/packet.go +++ b/lib/ssh/sftp/packet.go @@ -129,7 +129,7 @@ func unpackPacket(payload []byte) (pac *packet, err error) { ) n := binary.BigEndian.Uint32(payload) payload = payload[4:] - for x := uint32(0); x < n; x++ { + for range n { node := &dirEntry{} v = binary.BigEndian.Uint32(payload) diff --git a/lib/tabula/column.go b/lib/tabula/column.go index b89acffc..1e84e150 100644 --- a/lib/tabula/column.go +++ b/lib/tabula/column.go @@ -235,10 +235,7 @@ func (col *Column) SetValues(values []string) { } // pick the least length - minlen := reclen - if vallen < reclen { - minlen = vallen - } + minlen := min(vallen, reclen) for x := range minlen { _ = col.Records[x].SetValue(values[x], col.Type) diff --git a/lib/tabula/columns.go b/lib/tabula/columns.go index 6a79e341..16c3ac32 100644 --- a/lib/tabula/columns.go +++ b/lib/tabula/columns.go @@ -5,6 +5,8 @@ package tabula import ( + "slices" + libbytes "git.sr.ht/~shulhan/pakakeh.go/lib/bytes" libnumbers "git.sr.ht/~shulhan/pakakeh.go/lib/numbers" ) @@ -29,11 +31,7 @@ func (cols *Columns) Reset() { func (cols *Columns) SetTypes(types []int) { typeslen := len(types) colslen := len(*cols) - minlen := typeslen - - if colslen < minlen { - minlen = colslen - } + minlen := min(colslen, typeslen) for x := range minlen { (*cols)[x].Type = types[x] @@ -72,13 +70,7 @@ func (cols *Columns) RandomPick(n int, dup bool, excludeIdx []int) ( // select unpicked columns using picked index. for cid := range *cols { // check if column index has been picked up - isPicked := false - for _, idx := range pickedIdx { - if cid == idx { - isPicked = true - break - } - } + isPicked := slices.Contains(pickedIdx, cid) if !isPicked { unpicked = append(unpicked, (*cols)[cid]) unpickedIdx = append(unpickedIdx, cid) diff --git a/lib/tabula/columns_test.go b/lib/tabula/columns_test.go index f70a6aca..a1dfb0d5 100644 --- a/lib/tabula/columns_test.go +++ b/lib/tabula/columns_test.go @@ -27,7 +27,7 @@ func TestRandomPickColumns(t *testing.T) { dup := false ncols := 6 excludeIdx := []int{3} - for i := 0; i < 5; i++ { + for range 5 { picked, unpicked, _, _ := dataset.Columns.RandomPick(ncols, dup, excludeIdx) diff --git a/lib/tabula/dataset.go b/lib/tabula/dataset.go index 3fee622b..c54e2236 100644 --- a/lib/tabula/dataset.go +++ b/lib/tabula/dataset.go @@ -213,10 +213,7 @@ func (dataset *Dataset) SetColumnsName(names []string) { } // find minimum length - minlen := collen - if nameslen < collen { - minlen = nameslen - } + minlen := min(nameslen, collen) for x := range minlen { dataset.Columns[x].Name = names[x] @@ -364,11 +361,7 @@ func (dataset *Dataset) TransposeToColumns() { } // use the least length - minlen := len(*dataset.GetRow(0)) - - if minlen > ncol { - minlen = ncol - } + minlen := min(len(*dataset.GetRow(0)), ncol) switch orgmode { case DatasetModeRows, DatasetNoMode: @@ -407,7 +400,7 @@ func (dataset *Dataset) TransposeToRows() { rowlen := math.MinInt32 flen := len(dataset.Columns) - for f := 0; f < flen; f++ { + for f := range flen { l := dataset.Columns[f].Len() if l > rowlen { @@ -421,7 +414,7 @@ func (dataset *Dataset) TransposeToRows() { for r := 0; r < rowlen; r++ { row := make(Row, flen) - for f := 0; f < flen; f++ { + for f := range flen { if dataset.Columns[f].Len() > r { row[f] = dataset.Columns[f].Records[r] } else { @@ -526,7 +519,7 @@ func (dataset *Dataset) FillRowsWithColumn(colIdx int, col Column) { for ; y < nrow; y++ { row := make(Row, ncol) - for z := 0; z < ncol; z++ { + for z := range ncol { if z == colIdx { row[colIdx] = col.Records[y] } else { @@ -591,18 +584,15 @@ func (dataset *Dataset) PushColumnToRows(col Column) { // If no existing rows in dataset, initialize the rows slice. dataset.Rows = make(Rows, colsize) - for nrow = 0; nrow < colsize; nrow++ { + for nrow = range colsize { row := make(Row, 0) dataset.Rows[nrow] = &row } + nrow++ } // Pick the minimum length between column or current row length. - minrow := nrow - - if colsize < nrow { - minrow = colsize - } + minrow := min(colsize, nrow) // Push each record in column to each rows var row *Row diff --git a/lib/tabula/datasetinterface.go b/lib/tabula/datasetinterface.go index d695fbc2..77cb8904 100644 --- a/lib/tabula/datasetinterface.go +++ b/lib/tabula/datasetinterface.go @@ -7,6 +7,7 @@ package tabula import ( "encoding/json" "os" + "slices" ) // DatasetInterface is the interface for working with DSV data. @@ -191,12 +192,9 @@ func SplitRowsByCategorical(di DatasetInterface, colidx int, splitVal []string) for _, row := range *di.GetRows() { found := false - for _, val := range splitVal { - if (*row)[colidx].String() == val { - splitIn.PushRow(row) - found = true - break - } + if slices.Contains(splitVal, (*row)[colidx].String()) { + splitIn.PushRow(row) + found = true } if !found { splitEx.PushRow(row) diff --git a/lib/tabula/rows.go b/lib/tabula/rows.go index ccba310c..e9c40207 100644 --- a/lib/tabula/rows.go +++ b/lib/tabula/rows.go @@ -9,6 +9,7 @@ import ( "fmt" "log" "math/big" + "slices" ) // Rows represent slice of Row. @@ -141,13 +142,7 @@ func (rows *Rows) RandomPick(n int, duplicate bool) ( } // check if its already picked - isPicked := false - for _, pastIdx := range pickedIdx { - if idx == pastIdx { - isPicked = true - break - } - } + isPicked := slices.Contains(pickedIdx, idx) // get another random idx again if isPicked { continue @@ -166,13 +161,7 @@ func (rows *Rows) RandomPick(n int, duplicate bool) ( // select unpicked rows using picked index. for rid := range *rows { // check if row index has been picked up - isPicked := false - for _, idx := range pickedIdx { - if rid == idx { - isPicked = true - break - } - } + isPicked := slices.Contains(pickedIdx, rid) if !isPicked { unpicked.PushBack((*rows)[rid]) unpickedIdx = append(unpickedIdx, rid) diff --git a/lib/tabula/rows_test.go b/lib/tabula/rows_test.go index 82ddc517..af6552f1 100644 --- a/lib/tabula/rows_test.go +++ b/lib/tabula/rows_test.go @@ -112,7 +112,7 @@ func TestRandomPick(t *testing.T) { } // random pick with duplicate - for i := 0; i < 5; i++ { + for range 5 { picked, unpicked, pickedIdx, unpickedIdx := rows.RandomPick(6, true) @@ -130,7 +130,7 @@ func TestRandomPick(t *testing.T) { } // random pick without duplication - for i := 0; i < 5; i++ { + for range 5 { picked, unpicked, pickedIdx, unpickedIdx := rows.RandomPick(3, false) diff --git a/lib/tabula/tabula_test.go b/lib/tabula/tabula_test.go index 26f0d34f..a4e105b8 100644 --- a/lib/tabula/tabula_test.go +++ b/lib/tabula/tabula_test.go @@ -39,7 +39,7 @@ func initRows() (rows Rows, e error) { l := len(rowsData[i]) row := make(Row, 0) - for j := 0; j < l; j++ { + for j := range l { rec, e := NewRecordBy(rowsData[i][j], testColTypes[j]) diff --git a/lib/test/data.go b/lib/test/data.go index accbc94b..a995ed20 100644 --- a/lib/test/data.go +++ b/lib/test/data.go @@ -320,20 +320,20 @@ func (data *Data) parse(content []byte) (err error) { func (data *Data) parseFlag(content []byte) { var ( - idx = bytes.IndexByte(content, ':') - bkey []byte - bval []byte + before, after, ok = bytes.Cut(content, []byte{':'}) + bkey []byte + bval []byte ) - if idx < 0 { + if !ok { return } - bkey = bytes.TrimSpace(content[:idx]) + bkey = bytes.TrimSpace(before) if len(bkey) == 0 { return } - bval = bytes.TrimSpace(content[idx+1:]) + bval = bytes.TrimSpace(after) data.Flag[string(bkey)] = string(bval) } diff --git a/lib/text/chunk.go b/lib/text/chunk.go index a904f2bd..10d37936 100644 --- a/lib/text/chunk.go +++ b/lib/text/chunk.go @@ -8,6 +8,7 @@ import ( "bytes" "fmt" "strconv" + "strings" ) // Chunk represent subset of line, contain starting position and slice of @@ -20,15 +21,15 @@ type Chunk struct { // JoinChunks all chunk's values using `sep` as separator and return it as // string. func JoinChunks(chunks []Chunk, sep string) string { - var out string + var out strings.Builder for x := range len(chunks) { if x > 0 { - out += sep + out.WriteString(sep) } - out += string(chunks[x].V) + out.WriteString(string(chunks[x].V)) } - return out + return out.String() } // MarshalJSON encode the Chunk into JSON value. diff --git a/lib/text/diff/diffinterface.go b/lib/text/diff/diffinterface.go index 015e636a..0f8df1b2 100644 --- a/lib/text/diff/diffinterface.go +++ b/lib/text/diff/diffinterface.go @@ -152,10 +152,7 @@ func BytesRatio(old, newline []byte, minTokenLen int) (ratio float32, m int, max oldlen = len(old) // Get minimal token to search in the newline left over. - minlen = minTokenLen - if oldlen < minlen { - minlen = oldlen - } + minlen = min(oldlen, minTokenLen) // Search old token in newline, chunk by chunk. x = 0 @@ -181,10 +178,7 @@ func BytesRatio(old, newline []byte, minTokenLen int) (ratio float32, m int, max oldlen = len(old) newlen = len(newline) - minlen = oldlen - if newlen < minlen { - minlen = newlen - } + minlen = min(newlen, oldlen) x, y = 0, 0 // start again from beginning... @@ -264,11 +258,7 @@ func Bytes(old, new []byte, atx, aty int) (adds, dels text.Chunks) { newlen := len(new) minlen := 0 - if oldlen < newlen { - minlen = oldlen - } else { - minlen = newlen - } + minlen = min(oldlen, newlen) // Find the position of unmatched byte from the beginning. x, y := 0, 0 @@ -326,19 +316,13 @@ func Bytes(old, new []byte, atx, aty int) (adds, dels text.Chunks) { newleftlen := len(newleft) // Get minimal token to search in the new left over. - minlen = DefMatchLen - if oldleftlen < DefMatchLen { - minlen = oldleftlen - } + minlen = min(oldleftlen, DefMatchLen) xtoken := oldleft[:minlen] xaty := inbytes.TokenFind(newleft, xtoken, 0) // Get miniminal token to search in the old left over. - minlen = DefMatchLen - if newleftlen < DefMatchLen { - minlen = newleftlen - } + minlen = min(newleftlen, DefMatchLen) ytoken := newleft[:minlen] yatx := inbytes.TokenFind(oldleft, ytoken, 0) @@ -411,10 +395,7 @@ func searchForward(atx, aty int, x, y *int, oldleft, newleft *[]byte) ( oldleftlen := len(*oldleft) newleftlen := len(*newleft) - minlen := DefMatchLen - if oldleftlen < minlen { - minlen = oldleftlen - } + minlen := min(oldleftlen, DefMatchLen) // Loop through old line to find matching token xaty := -1 @@ -428,10 +409,7 @@ func searchForward(atx, aty int, x, y *int, oldleft, newleft *[]byte) ( } } - minlen = DefMatchLen - if newleftlen < minlen { - minlen = newleftlen - } + minlen = min(newleftlen, DefMatchLen) yatx := -1 yy := 1 diff --git a/lib/websocket/funcs.go b/lib/websocket/funcs.go index 293213a1..85c83eed 100644 --- a/lib/websocket/funcs.go +++ b/lib/websocket/funcs.go @@ -100,11 +100,7 @@ func Send(fd int, packet []byte, timeout time.Duration) (err error) { } for len(packet) > 0 { - if len(packet) < maxBuffer { - max = len(packet) - } else { - max = maxBuffer - } + max = min(len(packet), maxBuffer) n, err = unix.Write(fd, packet[:max]) if err != nil { diff --git a/lib/xmlrpc/value.go b/lib/xmlrpc/value.go index 13537c75..35470440 100644 --- a/lib/xmlrpc/value.go +++ b/lib/xmlrpc/value.go @@ -105,7 +105,7 @@ func NewValue(in any) (out *Value) { } } - case reflect.Interface, reflect.Ptr: + case reflect.Interface, reflect.Pointer: return NewValue(refv.Elem()) case reflect.Invalid, reflect.Complex64, reflect.Complex128, |
