Skip to content

Commit

Permalink
strings: Add At command returning the n-th rune
Browse files Browse the repository at this point in the history
  • Loading branch information
Catya3 committed Jun 12, 2024
1 parent 1e19f2e commit 9fe09e0
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 0 deletions.
1 change: 1 addition & 0 deletions internal/runtime/funcs/registry.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ func CreatorRegistry() map[string]runtime.FuncCreator {
"time_sleep": timeSleep{},

// strings
"string_at": stringAt{},
"join": stringJoin{},
"split": stringSplit{},
"string_sort": listSortString{},
Expand Down
71 changes: 71 additions & 0 deletions internal/runtime/funcs/string_at.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
package funcs

import (
"context"
"errors"

"github.com/nevalang/neva/internal/runtime"
"golang.org/x/exp/utf8string"
)

var errIndexOutOfBounds = errors.New("index out of bounds")

Check failure on line 11 in internal/runtime/funcs/string_at.go

View workflow job for this annotation

GitHub Actions / build_and_test

errIndexOutOfBounds redeclared in this block

type stringAt struct{}

func (stringAt) Create(io runtime.FuncIO, _ runtime.Msg) (func(context.Context), error) {
dataIn, err := io.In.Port("data")
if err != nil {
return nil, err
}

idxIn, err := io.In.Port("idx")
if err != nil {
return nil, err
}

resOut, err := io.Out.Port("res")
if err != nil {
return nil, err
}

errOut, err := io.Out.Port("err")
if err != nil {
return nil, err
}

return func(ctx context.Context) {
for {
var data *utf8string.String
var idx int64

select {
case <-ctx.Done():
return
case msg := <-dataIn:
data = utf8string.NewString(msg.Str())
}

select {
case <-ctx.Done():
return
case msg := <-idxIn:
idx = msg.Int()
}

if idx < 0 || idx >= int64(data.RuneCount()) {
select {
case <-ctx.Done():
return
case errOut <- errorFromString(errIndexOutOfBounds.Error()):
continue
}
}

select {
case <-ctx.Done():
return
case resOut <- runtime.NewStrMsg(string(data.At(int(idx)))):
}
}
}, nil
}

0 comments on commit 9fe09e0

Please sign in to comment.