pax_global_header00006660000000000000000000000064143100300570014503gustar00rootroot0000000000000052 comment=33475637bf32db88de882a7704de9fc5e2d31f15 golang-github-maruel-natural-1.1.0/000077500000000000000000000000001431003005700171605ustar00rootroot00000000000000golang-github-maruel-natural-1.1.0/.github/000077500000000000000000000000001431003005700205205ustar00rootroot00000000000000golang-github-maruel-natural-1.1.0/.github/workflows/000077500000000000000000000000001431003005700225555ustar00rootroot00000000000000golang-github-maruel-natural-1.1.0/.github/workflows/test.yml000066400000000000000000000164441431003005700242700ustar00rootroot00000000000000# Copyright 2022 Marc-Antoine Ruel. All rights reserved. # Use of this source code is governed under the Apache License, Version 2.0 # that can be found in the LICENSE file. # References: # https://developer.github.com/webhooks/event-payloads/ # https://github.com/actions/cache # https://github.com/actions/checkout # https://github.com/actions/setup-go # https://help.github.com/en/actions/configuring-and-managing-workflows/authenticating-with-the-github_token#using-the-github_token-in-a-workflow # https://help.github.com/en/actions/reference/context-and-expression-syntax-for-github-actions/ # https://help.github.com/en/actions/reference/workflow-syntax-for-github-actions on: [push, pull_request] name: Run tests jobs: test_all: continue-on-error: true defaults: run: shell: bash strategy: fail-fast: false matrix: os: [ubuntu-latest, macos-latest, windows-latest] # Do not forget to bump every 6 months! gover: ["1.18"] runs-on: "${{matrix.os}}" name: "go${{matrix.gover}}.x on ${{matrix.os}}" steps: - uses: actions/setup-go@v3 with: go-version: "~${{matrix.gover}}.0" # Checkout and print debugging information. - name: Turn off git core.autocrlf run: git config --global core.autocrlf false - uses: actions/checkout@v3 - name: "Debug" run: | echo HOME = $HOME echo GITHUB_WORKSPACE = $GITHUB_WORKSPACE echo PATH = $PATH echo "" echo $ ls -l $HOME/go/bin ls -la $HOME/go/bin - name: 'Cache: ~/go' uses: actions/cache@v2 with: path: ~/go key: "${{runner.os}}-gopkg-${{hashFiles('go.sum', '.github/workflows/*.yml')}}" # Fetch the tools before checking out, so they don't modify go.mod/go.sum. - name: 'go install necessary tools' run: | go install -v github.com/gordonklaus/ineffassign@latest go install -v github.com/securego/gosec/cmd/gosec@latest go install -v golang.org/x/tools/go/analysis/passes/shadow/cmd/shadow@latest go install -v honnef.co/go/tools/cmd/staticcheck@latest - name: 'go install necessary tools (ubuntu)' if: always() && matrix.os == 'ubuntu-latest' run: | go install -v github.com/client9/misspell/cmd/misspell@latest go install -v github.com/google/addlicense@latest # Now run proper checks. - name: 'Check: go vet' if: always() run: go vet ./... - name: 'Check: go vet shadow; shadowed variables' run: | SHADOW_TOOL="$(which shadow)" if [ -f "${SHADOW_TOOL}.exe" ]; then SHADOW_TOOL="${SHADOW_TOOL}.exe" fi go vet -vettool=$SHADOW_TOOL ./... - name: 'Check: inefficient variable assignment' if: always() run: ineffassign ./... - name: 'Check: staticcheck' if: always() run: staticcheck -checks inherit,-SA1019 ./... # Still broken on go1.18. :( #- name: 'Check: gosec (only G104)' # run: gosec -include=G104 -fmt=golint -quiet ./... # The following checks are not dependent on the OS or go build tags. Only # run them on ubuntu-latest since it's the fastest one. - name: 'Check: no executable was committed (ubuntu)' if: always() && matrix.os == 'ubuntu-latest' run: | if find . -path ./.git -prune -o -type f -executable -print | grep -e . ; then echo 'Do not commit executables' false fi - name: 'Check: gofmt; code is well formatted (ubuntu)' if: always() && matrix.os == 'ubuntu-latest' run: | FILES=$(gofmt -s -l .) if ! test -z "$FILES"; then echo 'Please run `gofmt -s -w` on the following files:' >> _gofmt.txt echo "" >> _gofmt.txt for FILE in ${FILES}; do echo "- ${FILE}" >> _gofmt.txt done cat _gofmt.txt echo "## ⚠ gofmt Failed" >> _comments.txt echo "" >> _comments.txt cat _gofmt.txt >> _comments.txt echo "" >> _comments.txt false fi - name: 'Check: addlicense; all sources have a license header (ubuntu)' if: always() && matrix.os == 'ubuntu-latest' run: addlicense -check . - name: "Check: misspelling; code doesn't contain misspelling (ubuntu)" if: always() && matrix.os == 'ubuntu-latest' run: | ERR=$(misspell .) if ! test -z "$ERR"; then echo "$ERR" echo "## ⚠ misspell Failed" >> _comments.txt echo "" >> _comments.txt echo "$ERR" >> _comments.txt echo "" >> _comments.txt false fi # Run tests last since it's potentially the slowest step. - name: 'Check: go test -cover' run: go test -timeout=40s -covermode=count -coverprofile coverage.txt ./... # Don't send code coverage if anything failed to reduce spam. - uses: codecov/codecov-action@v2 - name: 'Cleanup' run: rm coverage.txt # Don't run go test -race if anything failed, to speed up the results. - name: 'Check: go test -race' run: go test -timeout=60s -race ./... - name: 'Check: go test -bench .' run: go test -timeout=40s -bench . -benchtime=100ms -cpu=1 ./... - name: 'Check: CGO_ENABLED=0 go test -short' run: CGO_ENABLED=0 go test -timeout=40s -short ./... - name: "Check: tree is clean" run: | # Nothing should have changed in the tree up to that point and no # unsuspected file was created. TOUCHED=$(git status --porcelain --ignored) if ! test -z "$TOUCHED"; then echo "Oops, something touched these files, please cleanup:" echo "$TOUCHED" git diff false fi - name: "Check: go generate doesn't modify files" run: | go generate ./... # Also test for untracked files. TOUCHED=$(git status --porcelain --ignored) if ! test -z "$TOUCHED"; then echo "go generate created these files, please fix:" echo "$TOUCHED" false fi - name: "Check: go mod tidy doesn't modify files" run: | go mod tidy TOUCHED=$(git status --porcelain --ignored) if ! test -z "$TOUCHED"; then echo "go mod tidy was not clean, please update:" git diff false fi - name: 'Send comments' if: failure() && github.event_name == 'pull_request' run: | if [ -f _comments.txt ]; then URL=$(cat ${GITHUB_EVENT_PATH} | jq -r .pull_request.comments_url) echo "Sending $(cat _comments.txt|wc -l) lines of comments to ${URL}" PAYLOAD=$(echo '{}' | jq --arg body "$(cat _comments.txt)" '.body = $body') curl -sS --request POST \ --header "Authorization: Bearer ${{secrets.GITHUB_TOKEN}}" \ --header "Content-Type: application/json" \ --data "${PAYLOAD}" "${URL}" > /dev/null fi test_short: continue-on-error: true strategy: fail-fast: false matrix: os: [ubuntu-latest] gover: ['1.11.13'] runs-on: "${{matrix.os}}" name: "go${{matrix.gover}} on ${{matrix.os}} (quick)" steps: - uses: actions/setup-go@v3 with: go-version: "${{matrix.gover}}" - uses: actions/checkout@v3 - name: 'Check: go test' run: go test -timeout=40s ./... golang-github-maruel-natural-1.1.0/LICENSE000066400000000000000000000261231431003005700201710ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2018 Marc-Antoine Ruel 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. golang-github-maruel-natural-1.1.0/README.md000066400000000000000000000032511431003005700204400ustar00rootroot00000000000000# natural Yet another natural sort, with 100% test coverage and a benchmark. It **does not allocate memory**, doesn't depend on package `sort` and hence doesn't depend on `reflect`. It is optimized for speed. [![Go Reference](https://pkg.go.dev/badge/github.com/maruel/natural.svg)](https://pkg.go.dev/github.com/maruel/natural) [![codecov](https://codecov.io/gh/maruel/natural/branch/main/graph/badge.svg?token=iQg8Y62BBg)](https://codecov.io/gh/maruel/natural) ## Benchmarks On Go 1.18.3. ``` $ go test -bench=. -cpu 1 goos: linux goarch: amd64 pkg: github.com/maruel/natural cpu: Intel(R) Core(TM) i7-10700 CPU @ 2.90GHz BenchmarkLessDigitsTwoGroupsNative 331287298 3.597 ns/op 0 B/op 0 allocs/op BenchmarkLessDigitsTwoGroups 32479050 36.55 ns/op 0 B/op 0 allocs/op BenchmarkLessStringOnly 157775884 7.603 ns/op 0 B/op 0 allocs/op BenchmarkLessDigitsOnly 69210796 17.52 ns/op 0 B/op 0 allocs/op BenchmarkLess10Blocks 6331066 190.8 ns/op 0 B/op 0 allocs/op ``` On a Raspberry Pi 3: ``` $ go test -bench=. -cpu 1 goos: linux goarch: arm pkg: github.com/maruel/natural BenchmarkLessDigitsTwoGroupsNative 14181789 86.57 ns/op 0 B/op 0 allocs/op BenchmarkLessDigitsTwoGroups 1600195 748.9 ns/op 0 B/op 0 allocs/op BenchmarkLessStringOnly 8286034 142.3 ns/op 0 B/op 0 allocs/op BenchmarkLessDigitsOnly 3653055 331.4 ns/op 0 B/op 0 allocs/op BenchmarkLess10Blocks 310687 3838 ns/op 0 B/op 0 allocs/op ``` Coverage: ``` $ go test -cover PASS coverage: 100.0% of statements ok github.com/maruel/natural 0.012s ``` golang-github-maruel-natural-1.1.0/example_test.go000066400000000000000000000007241431003005700222040ustar00rootroot00000000000000// Copyright 2018 Marc-Antoine Ruel. All rights reserved. // Use of this source code is governed under the Apache License, Version 2.0 // that can be found in the LICENSE file. package natural_test import ( "fmt" "sort" "strings" "github.com/maruel/natural" ) func Example() { items := []string{ "gpio10", "gpio1", "gpio20", } sort.Sort(natural.StringSlice(items)) fmt.Println(strings.Join(items, "\n")) // Output: // gpio1 // gpio10 // gpio20 } golang-github-maruel-natural-1.1.0/go.mod000066400000000000000000000000521431003005700202630ustar00rootroot00000000000000module github.com/maruel/natural go 1.11 golang-github-maruel-natural-1.1.0/natsort.go000066400000000000000000000042111431003005700211770ustar00rootroot00000000000000// Copyright 2018 Marc-Antoine Ruel. All rights reserved. // Use of this source code is governed under the Apache License, Version 2.0 // that can be found in the LICENSE file. // Package natural defines a natural "less" to compare two strings while // interpreting natural numbers. // // This is occasionally nicknamed 'natsort'. // // It does so with no memory allocation. package natural import ( "strconv" ) // Less does a 'natural' comparison on the two strings. // // It treats digits as decimal numbers, so that Less("10", "2") return true. // // This function does no memory allocation. func Less(a, b string) bool { for { if p := commonPrefix(a, b); p != 0 { a = a[p:] b = b[p:] } if len(a) == 0 { return len(b) != 0 } if ia := digits(a); ia > 0 { if ib := digits(b); ib > 0 { // Both sides have digits. an, aerr := strconv.ParseUint(a[:ia], 10, 64) bn, berr := strconv.ParseUint(b[:ib], 10, 64) if aerr == nil && berr == nil { if an != bn { return an < bn } // Semantically the same digits, e.g. "00" == "0", "01" == "1". In // this case, only continue processing if there's trailing data on // both sides, otherwise do lexical comparison. if ia != len(a) && ib != len(b) { a = a[ia:] b = b[ib:] continue } } } } return a < b } } // StringSlice attaches the methods of Interface to []string, sorting in // increasing order using natural order. type StringSlice []string func (p StringSlice) Len() int { return len(p) } func (p StringSlice) Less(i, j int) bool { return Less(p[i], p[j]) } func (p StringSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } // // commonPrefix returns the common prefix except for digits. func commonPrefix(a, b string) int { m := len(a) if n := len(b); n < m { m = n } if m == 0 { return 0 } _ = a[m-1] _ = b[m-1] for i := 0; i < m; i++ { ca := a[i] cb := b[i] if (ca >= '0' && ca <= '9') || (cb >= '0' && cb <= '9') || ca != cb { return i } } return m } func digits(s string) int { for i := 0; i < len(s); i++ { c := s[i] if c < '0' || c > '9' { return i } } return len(s) } golang-github-maruel-natural-1.1.0/natsort_test.go000066400000000000000000000045431431003005700222460ustar00rootroot00000000000000// Copyright 2018 Marc-Antoine Ruel. All rights reserved. // Use of this source code is governed under the Apache License, Version 2.0 // that can be found in the LICENSE file. package natural import ( "testing" ) func TestLessLess(t *testing.T) { data := [][2]string{ {"", "a"}, {"a", "b"}, {"a", "aa"}, {"a0", "a1"}, {"a0", "a00"}, {"a00", "a01"}, {"a01", "a2"}, {"a01x", "a2x"}, // Only the last number matters. {"a0b00", "a00b1"}, {"a0b00", "a00b01"}, {"a00b0", "a0b00"}, {"a00b00", "a0b01"}, {"a00b00", "a0b1"}, } for _, l := range data { if !Less(l[0], l[1]) { t.Fatalf("Less(%q, %q) returned false", l[0], l[1]) } } } func TestLessNot(t *testing.T) { data := [][2]string{ {"a", ""}, {"a", "a"}, {"aa", "a"}, {"b", "a"}, {"a01", "a00"}, {"a01", "a01"}, {"a1", "a1"}, {"a2", "a01"}, {"a2x", "a01x"}, {"a00b00", "a0b0"}, {"a00b01", "a0b00"}, {"a00b00", "a0b00"}, } for _, l := range data { if Less(l[0], l[1]) { t.Fatalf("Less(%q, %q) returned true", l[0], l[1]) } } } // BenchmarkLessDigitsTwoGroupsNative benchmarks calling a function that just // does a < b without taking into account the digits, using the same string as // BenchmarkLessDigitsTwoGroups. func BenchmarkLessDigitsTwoGroupsNative(b *testing.B) { b.ReportAllocs() for i := 0; i < b.N; i++ { if less("a01a2", "a01a01") { b.Fatal("unexpected result") } } } //go:noinline func less(a, b string) bool { return a < b } // BenchmarkLessDigitsTwoGroups compares "a01a2" and "a01a01". func BenchmarkLessDigitsTwoGroups(b *testing.B) { b.ReportAllocs() for i := 0; i < b.N; i++ { if Less("a01a2", "a01a01") { b.Fatal("unexpected result") } } } // BenchmarkLessStringOnly doesn't contain digits. func BenchmarkLessStringOnly(b *testing.B) { b.ReportAllocs() for i := 0; i < b.N; i++ { if Less("abcd", "abc") { b.Fatal("unexpected result") } } } // BenchmarkLessDigitsOnly contains only digits. func BenchmarkLessDigitsOnly(b *testing.B) { b.ReportAllocs() for i := 0; i < b.N; i++ { if Less("10", "2") { b.Fatal("unexpected result") } } } // BenchmarkLess10Blocks benchmark a mix of 10 strings and digits. func BenchmarkLess10Blocks(b *testing.B) { b.ReportAllocs() for i := 0; i < b.N; i++ { if Less("a01a01a01a01a01a01a01a01a01a2", "a01a01a01a01a01a01a01a01a01a01") { b.Fatal("unexpected result") } } }