Skip to content

Commit

Permalink
Fix slice string format with min and max int
Browse files Browse the repository at this point in the history
Suppress the min and max when set with a negative step. Prevents
aggressive display of large numbers not specified by the user.
  • Loading branch information
theory committed Dec 13, 2024
1 parent 63ccd9f commit 8e6b916
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 2 deletions.
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,15 @@ All notable changes to this project will be documented in this file. It uses the
[Semantic Versioning]: https://semver.org/spec/v2.0.0.html
"Semantic Versioning 2.0.0"

## [v0.2.1 ] — Unreleased

### 🪲 Bug Fixes

* Fixed the formatting of slice strings to omit min and max integers when
not specified and using a negative step.

[v0.2.1]: https://github.com/theory/jsonpath/compare/v0.2.0...v0.2.1

## [v0.2.0] — 2024-11-13

### ⚡ Improvements
Expand Down
4 changes: 2 additions & 2 deletions spec/selector.go
Original file line number Diff line number Diff line change
Expand Up @@ -194,11 +194,11 @@ func Slice(args ...any) SliceSelector {

// writeTo writes a string representation of s to buf.
func (s SliceSelector) writeTo(buf *strings.Builder) {
if s.start != 0 {
if s.start != 0 && (s.step >= 0 || s.start != math.MaxInt) {
buf.WriteString(strconv.FormatInt(int64(s.start), 10))
}
buf.WriteByte(':')
if s.end != math.MaxInt {
if s.end != math.MaxInt && (s.step >= 0 || s.end != math.MinInt) {
buf.WriteString(strconv.FormatInt(int64(s.end), 10))
}
if s.step != 1 {
Expand Down
46 changes: 46 additions & 0 deletions spec/selector_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package spec

import (
"fmt"
"math"
"strings"
"testing"
Expand Down Expand Up @@ -127,6 +128,51 @@ func TestSelectorString(t *testing.T) {
tok: Slice(nil, nil, 3),
str: "::3",
},
{
name: "slice_neg_step",
tok: Slice(nil, nil, -1),
str: "::-1",
},
{
name: "slice_max_start",
tok: Slice(math.MaxInt),
str: fmt.Sprintf("%v:", math.MaxInt),
},
{
name: "slice_max_start_neg_step",
tok: Slice(math.MaxInt, nil, -1),
str: "::-1",
},
{
name: "slice_min_start",
tok: Slice(math.MinInt),
str: fmt.Sprintf("%v:", math.MinInt),
},
{
name: "slice_min_start_neg_step",
tok: Slice(math.MinInt, nil, -1),
str: fmt.Sprintf("%v::-1", math.MinInt),
},
{
name: "slice_max_end",
tok: Slice(0, math.MaxInt),
str: ":",
},
{
name: "slice_max_end_neg_step",
tok: Slice(0, math.MaxInt, -1),
str: "::-1",
},
{
name: "slice_min_end",
tok: Slice(0, math.MinInt),
str: fmt.Sprintf(":%v", math.MinInt),
},
{
name: "slice_min_end_neg_step",
tok: Slice(0, math.MinInt, -1),
str: "::-1",
},
{
name: "wildcard",
tok: Wildcard,
Expand Down

0 comments on commit 8e6b916

Please sign in to comment.