Julia: modify Base.peek to return a Char and export it

Created on 23 Apr 2016  路  7Comments  路  Source: JuliaLang/julia

The peek function is very useful and an efficient alternative to marking and resetting a stream when all you need to do is get a single character. The current peek returns a byte, however, which leads to errors when people assume that they can compare that byte to a character and check for a character (only works for UTF-8 streams and ASCII characters). This was a significant annoyance in implementing https://github.com/JuliaLang/julia/pull/16024. This is technically not breaking since Base.peek isn't exported. Most code that uses it will actually continue to work.

Hacktoberfest good first issue help wanted

Most helpful comment

Actually, even better: we can support generic peek(io, T) implemented with mark, read and reset but with more efficient methods when T is UInt8 or Char.

All 7 comments

we should make this match the read API, so:

read(io, UInt8)
read(io, Char)

peek(io, UInt8)
peek(io, Char)

The mark/reset API is good but it's very high overhead for just looking at a single character, which requires only a fixed amount of lookahead. The fact that we _still_ use peek in a lot of places in Base indicates that peek is necessary and should work correctly, rather than continue to exist and be broken and non-public.

This could probably be closed just by renaming peekchar to peek and renaming peek to peekbyte. Since both are unexported, we could potentially just do the rename.

Or we could just do what @quinnj recommends and make peek match read.

Actually, even better: we can support generic peek(io, T) implemented with mark, read and reset but with more efficient methods when T is UInt8 or Char.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

tkoolen picture tkoolen  路  3Comments

dpsanders picture dpsanders  路  3Comments

felixrehren picture felixrehren  路  3Comments

wilburtownsend picture wilburtownsend  路  3Comments

yurivish picture yurivish  路  3Comments