Skip to content

Commit fb21f7c

Browse files
committed
Add offset support in peek-byte.
Add support for peek-byte offset up to 4 bytes, which is needed to implement peek-char.
1 parent 76f6c26 commit fb21f7c

2 files changed

Lines changed: 25 additions & 3 deletions

File tree

langs/outlaw/io.c

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,19 @@ val_t read_byte(void)
1919

2020
val_t peek_byte(void* fake_port, int offset)
2121
{
22-
// offset is ignored for now
23-
char c = getc(in);
22+
char cs[3];
23+
if ((offset < 0) || (offset > 3)) { exit(-1); }
24+
int i;
25+
char c;
26+
for (i = 0; i < offset; i++) {
27+
cs[i] = getc(in);
28+
}
29+
c = getc(in);
2430
ungetc(c, in);
25-
return (c == EOF) ? val_wrap_eof() : val_wrap_int(c);
31+
for (i = 0; i < offset; i++) {
32+
ungetc(cs[offset-i-1], in);
33+
}
34+
return (c == EOF) ? val_wrap_eof() : val_wrap_int((unsigned char)c);
2635
}
2736

2837
val_t write_byte(val_t c)

langs/outlaw/test/test-runner.rkt

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -752,6 +752,19 @@
752752
(cons #\a ""))
753753
(check-equal? (run "ab" '(cons (read-char) (read-char)))
754754
(cons '(#\a . #\b) ""))
755+
(check-equal? (run "a" '(peek-byte (%current-input-port) 0))
756+
(cons 97 ""))
757+
(check-equal? (run "ab" '(cons (peek-byte (%current-input-port) 1) (read-byte)))
758+
(cons (cons 98 97) ""))
759+
(check-equal? (run "abc" '(cons (peek-byte (%current-input-port) 2)
760+
(cons (read-byte) (read-byte))))
761+
(cons (cons 99 (cons 97 98)) ""))
762+
(check-equal? (run "a" '(peek-char))
763+
(cons #\a ""))
764+
(check-equal? (run "ab" '(cons (peek-char) (peek-char)))
765+
(cons '(#\a . #\a) ""))
766+
(check-equal? (run "λ" '(peek-char))
767+
(cons #\λ ""))
755768
(check-equal? (run "" '(write-char #\a))
756769
(cons (void) "a"))
757770
(check-equal? (run "" '(write-char #\newline))

0 commit comments

Comments
 (0)