Skip to content

Commit

Permalink
Add joker.io/read function.
Browse files Browse the repository at this point in the history
  • Loading branch information
candid82 committed Jul 3, 2024
1 parent 4f0c27f commit 4c8821c
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 0 deletions.
7 changes: 7 additions & 0 deletions std/io.joke
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,10 @@
{:added "1.0"
:go "close(f)"}
[^Object f])

(defn ^String read
"Reads up to n bytes from IOReader r and returns a string of the read bytes.
May return a shorter (or blank) string if EOF is encountered."
{:added "1.3.6"
:go "read(r, n)"}
^String [^IOReader r ^Int n])
18 changes: 18 additions & 0 deletions std/io/a_io.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,24 @@ func __pipe_(_args []Object) Object {
return NIL
}

var __read__P ProcFn = __read_
var read_ Proc = Proc{Fn: __read__P, Name: "read_", Package: "std/io"}

func __read_(_args []Object) Object {
_c := len(_args)
switch {
case _c == 2:
r := ExtractIOReader(_args, 0)
n := ExtractInt(_args, 1)
_res := read(r, n)
return MakeString(_res)

default:
PanicArity(_c)
}
return NIL
}

func Init() {

InternsOrThunks()
Expand Down
6 changes: 6 additions & 0 deletions std/io/a_io_slow_init.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,10 @@ func InternsOrThunks() {
with code expecting an IOWriter.
Returns a vector [reader, writer].`, "1.0"))

ioNamespace.InternVar("read", read_,
MakeMeta(
NewListFrom(NewVectorFrom(MakeSymbol("r"), MakeSymbol("n"))),
`Reads up to n bytes from IOReader r and returns a string of the read bytes.
May return a shorter (or blank) string if EOF is encountered.`, "1.3.6").Plus(MakeKeyword("tag"), String{S: "String"}))

}
9 changes: 9 additions & 0 deletions std/io/io_native.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,12 @@ func close(f Object) Nil {
}
panic(RT.NewError("Object is not closable: " + f.ToString(false)))
}

func read(r io.Reader, n int) string {
buf := make([]byte, n)
cnt, err := r.Read(buf)
if err != io.EOF {
PanicOnErr(err)
}
return string(buf[:cnt])
}

0 comments on commit 4c8821c

Please sign in to comment.