shithub: mc

Download patch

ref: 218e5bd8256e190fb0b71f4178dc107a7b7bfc74
parent: 469769a5581ce0909cc3bec7fc59d8e71b9fe58b
author: Ori Bernstein <[email protected]>
date: Wed Dec 25 17:58:39 EST 2013

Make peeking handle EOF correctly.

--- a/bio.myr
+++ b/bio.myr
@@ -45,8 +45,8 @@
 	generic getle	: (f : file# -> std.option(@a::(tctest,tcnum,tcint)))
 
 	/* peeking */
-	const peekb	: (f : file# -> byte)
-	const peekc	: (f : file# -> char)
+	const peekb	: (f : file# -> std.option(byte))
+	const peekc	: (f : file# -> std.option(char))
 
 	/* delimited read; returns freshly allocated buffer. */
 	const readln	: (f : file#	-> std.option(byte[:]))
@@ -250,7 +250,10 @@
 	var b
 	var len
 
-	b = peekb(f)
+	if !ensureread(f, 1)
+		-> false
+	;;
+	b = f.rbuf[f.rstart]
 	if b & 0x80 == 0	/* 0b0xxx_xxxx */
 		len = 1
 	elif b & 0xe0 == 0xc0	/* 0b110x_xxxx */
@@ -333,16 +336,20 @@
 
 /* peeks a single byte from an input stream */
 const peekb = {f
-	ensureread(f, 1)
-	-> f.rbuf[f.rstart]
+	if !ensureread(f, 1)
+		-> `std.None
+	else
+		-> `std.Some f.rbuf[f.rstart]
+	;;
 }
 
 /* peeks a single character from a utf8 encoded input stream */
 const peekc = {f
 	if !ensurecodepoint(f)
-		-> -1
+		-> `std.None
+	else
+		-> `std.Some std.decode(f.rbuf[f.rstart:f.rend])
 	;;
-	-> std.decode(f.rbuf[f.rstart:f.rend])
 }
 
 /*
--- a/test/bio-peek.myr
+++ b/test/bio-peek.myr
@@ -11,17 +11,35 @@
 	| `std.None:	std.fatal(1, "Unable to open data file")
 	;;
 	
-	std.assert(bio.peekb(f) == 0x30, "wrong byte value read from datafile")
-	std.assert(bio.peekc(f) == '0', "wrong char value read from datafile")
+	std.assert(peekb(f) == 0x30, "wrong byte value read from datafile")
+	std.assert(peekc(f) == '0', "wrong char value read from datafile")
 
 	bio.read(f, buf[:4])	/* skip ahead 4 bytes */
-	std.assert(bio.peekb(f) == 0x34, "wrong byte value read from datafile")
-	std.assert(bio.peekc(f) == '4', "wrong char value read from datafile")
+	std.assert(peekb(f) == 0x34, "wrong byte value read from datafile")
+	std.assert(peekc(f) == '4', "wrong char value read from datafile")
 
 	bio.read(f, buf[:])	/* skip ahead 64k */
-	std.assert(bio.peekb(f) == 0x30, "wrong byte value read from datafile")
-	std.assert(bio.peekc(f) == '0', "wrong char value read from datafile")
+	std.assert(peekb(f) == 0x30, "wrong byte value read from datafile")
+	std.assert(peekc(f) == '0', "wrong char value read from datafile")
 
 	bio.close(f);
 	std.put("Succeded peeeking values\n")
+}
+
+const peekc = {f
+	match bio.peekc(f)
+	| `std.Some c:	-> c
+	| `std.None:
+		std.put("eof")
+		-> -1
+	;;
+}
+
+const peekb = {f
+	match bio.peekb(f)
+	| `std.Some b:	-> b
+	| `std.None:
+		std.put("eof")
+		-> -1
+	;;
 }