handle Bytes Index [0] selector and fix case input

This commit is contained in:
Fabio Bozzo
2024-09-13 13:06:49 +02:00
parent e86e45be73
commit 2e17ff8550
2 changed files with 19 additions and 1 deletions

View File

@@ -222,6 +222,24 @@ func resolve(sel Selector, subject ipld.Node, at []string) (ipld.Node, []ipld.No
} else {
cur = basicnode.NewString(string(str[idx]))
}
} else if cur != nil && cur.Kind() == datamodel.Kind_Bytes {
b, err := cur.AsBytes()
if err != nil {
return nil, nil, err
}
idx := seg.Index()
if idx < 0 {
idx = len(b) + idx
}
if idx < 0 || idx >= len(b) {
if seg.Optional() {
cur = nil
} else {
return nil, nil, newResolutionError(fmt.Sprintf("index out of bounds: %d", seg.Index()), at)
}
} else {
cur = basicnode.NewInt(int64(b[idx]))
}
} else if seg.Optional() {
cur = nil
} else {

View File

@@ -37,7 +37,7 @@ func TestSupportedForms(t *testing.T) {
{Name: "Index", Selector: `.[0]`, Input: `[1, 2]`, Output: `1`},
{Name: "Negative Index", Selector: `.[-1]`, Input: `[1, 2]`, Output: `2`},
{Name: "String Index", Selector: `.[0]`, Input: `"Hi"`, Output: `"H"`},
{Name: "Bytes Index", Selector: `.[0]`, Input: `{"/":{"bytes":"AAE"}`, Output: `0`},
{Name: "Bytes Index", Selector: `.[0]`, Input: `{"/":{"bytes":"AAE"}}`, Output: `0`},
{Name: "Array Slice", Selector: `.[0:2]`, Input: `[0, 1, 2]`, Output: `[0, 1]`},
{Name: "Array Slice", Selector: `.[1:]`, Input: `[0, 1, 2]`, Output: `[1, 2]`},
{Name: "Array Slice", Selector: `.[:2]`, Input: `[0, 1, 2]`, Output: `[0, 1]`},