Version 0 of ReadChar

Updated 2010-01-20 07:51:06 by pmarin

pmarin. ReadChar is an implementation of the classic getc and putbak functions
For more info see the page 255 of Software Tools by Kernighan and Plauger
The code is part of Muddy Scheme

package require TclOO
package require struct::stack

oo::class create ReadChar {

        constructor {{chan stdin}} {
                my variable ch 
                my variable buf
                set ch $chan
                set buf [struct::stack]
        }
        
        method getc {} {
                my variable ch
                my variable buf
                if  {[$buf size]} {
                        return [$buf pop]
                } else {
                        if {![eof $ch]} {
                                return [read $ch 1] 
                        } else {
                                return "eof"        
                        }
                }
        }
        
        method eof {} {
                my variable ch
                my variable buf
                if { ![$buf size] && [eof $ch] } {
                        return 1 
                } else {
                        return 0 
                }
        }
        
        method peek {} {
                my variable ch 
                my variable buf

                if  {[$buf size]} {
                        return [$buf peek]
                } else {
                        if {![eof $ch]} {
                                set c [read $ch 1]
                                $buf push $c 
                                return $c
                        } else {
                                return "eof"        
                        }
                }

        }

        method putbak str {
                my variable buf
                if { [string length $str] > 0 } {
                        if { [string length $str] == 1 } {
                                $buf push $str
                        } else {
                                foreach i [split [string reverse $str] {}] {
                                        $buf push $i        
                                }
                        }
                }
        }

        destructor  {
                my variable ch 
                my variable buf
                $buf destroy
                close $ch
        }
}

Coments

It is rare that It is not already implemented in the core libraries... Am I missing something?