]> Repositorios git - scryer-prolog.git/commitdiff
ADDED: read_n_chars/3, reading N characters from a stream.
authorMarkus Triska <[email protected]>
Thu, 4 Nov 2021 17:36:27 +0000 (18:36 +0100)
committerMarkus Triska <[email protected]>
Thu, 4 Nov 2021 17:36:27 +0000 (18:36 +0100)
src/lib/charsio.pl

index d186eaf49ca74d07c1a24abe1ada39c9ab2180a3..5a71ce1bd218801aadb5b247f7c34373edd77c65 100644 (file)
@@ -1,6 +1,7 @@
 :- module(charsio, [char_type/2,
                     chars_utf8bytes/2,
                     get_single_char/1,
+                    read_n_chars/3,
                     read_line_to_chars/3,
                     read_term_from_chars/2,
                     write_term_to_chars/3,
@@ -199,6 +200,29 @@ read_line_to_chars(Stream, Cs0, Cs) :-
             )
         ).
 
+/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+   Read N characters from Stream.
+
+   If N is a variable, read until EOF, unifying N with the number of
+   characters read.
+- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
+
+read_n_chars(Stream, N, Cs) :-
+        can_be(integer, N),
+        (   var(N) ->
+            read_to_eof(Stream, Cs),
+            length(Cs, N)
+        ;   N >= 0,
+            '$get_n_chars'(Stream, N, Cs)
+        ).
+
+read_to_eof(Stream, Cs) :-
+        '$get_n_chars'(Stream, 512, Cs0),
+        (   Cs0 == [] -> Cs = []
+        ;   partial_string(Cs0, Cs, Rest),
+            read_to_eof(Stream, Rest)
+        ).
+
 /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    Relation between a list of characters Cs and its Base64 encoding Bs,
    also a list of characters.