janet-lang / spork

Various Janet utility modules - the official "Contrib" library.
MIT License
117 stars 35 forks source link

Extra call to string in receiver function returned by make-recv? #163

Closed sogaiu closed 4 months ago

sogaiu commented 8 months ago

The make-recv function in msg.janet creates and returns a receiver function. The receiver function is created such that, as part of its last form, calls unpack:

  (fn receiver []
    (buffer/clear buf)
    (if-not (:chunk stream 4 buf) (break))
    (def [b0 b1 b2 b3] buf)
    (def len (+ b0 (* b1 0x100) (* b2 0x10000) (* b3 0x1000000)))
    (buffer/clear buf)
    (if-not (:chunk stream len buf) (break))
    (unpack (string buf)))

make-recv takes an optional argument unpack, which if unspecified, defaults to the function string:

(defn make-recv
  "Get a function that, when invoked, gets the next message from a readable stream.
  Provide an optional unpack function that will parse the received buffer."
  [stream &opt unpack]
  (def buf @"")
  (default unpack string)

It seems that, if make-recv doesn't receive an explicit argument for unpack, unpack would have its default value of string and thus the last form of the receiver function would end up being:

(string (string buf))

Is the inner call to string necessary?

Perhaps it's ok for the last form to be instead:

(unpack buf)

Or is it important that unpack not be passed the buffer?