Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: Slurping a file (was: more spllitting travails)



On Sun, Jan 14, 2024 at 2:34 AM Roman Perepelitsa
<roman.perepelitsa@xxxxxxxxx> wrote:
>
> On Sat, Jan 13, 2024 at 9:02 PM Bart Schaefer <schaefer@xxxxxxxxxxxxxxxx> wrote:
> >
> >   IFS= read -rd '' file_content <file
>
> In addition to being unable to read files with nul bytes, this
> solution suffers from additional drawbacks:
>
> - It's impossible to distinguish EOF from I/O error.

Pretty sure you can do that by examining $ERRNO on nonzero status?

> - It's slow when reading from non-file file descriptors.
> - It's slower than the optimized sysread-based slurp (see below) for
> larger files.

I'm curious whether
  setopt nomultibyte
  read -u 0 -k 8192 ...
is actually that much slower in a slurp-like loop.

> Here's a version with linear time complexity:
>
>     function slurp() {
>       emulate -L zsh -o no_multibyte
>       zmodload zsh/system || return
>       local -a content
>       local -i i
>       while true; do
>         sysread 'content[++i]' && continue

Another thought:  Use -c count option to get number of bytes read and
-s $size option to specify buffer size.  If (( $count == $size )) then
double $size for the next read.

>         (( $? == 5 )) || return
>         break
>       done
>       typeset -g REPLY=${(j::)content}

Why the typeset here?  Just assign?

>     }




Messages sorted by: Reverse Date, Date, Thread, Author