/core/io/streams/c/c.factor

http://github.com/abeaumont/factor · Factor · 87 lines · 61 code · 24 blank · 2 comment · 7 complexity · 0017d1542ca1f5a8d5c88701f996a5af MD5 · raw file

  1. ! Copyright (C) 2004, 2010 Slava Pestov.
  2. ! See http://factorcode.org/license.txt for BSD license.
  3. USING: accessors alien alien.strings byte-arrays destructors io
  4. io.backend io.encodings.utf8 io.files kernel kernel.private
  5. make math sequences threads.private ;
  6. IN: io.streams.c
  7. TUPLE: c-stream < disposable handle ;
  8. : new-c-stream ( handle class -- c-stream )
  9. new-disposable swap >>handle ; inline
  10. M: c-stream dispose* handle>> fclose ;
  11. TUPLE: c-writer < c-stream ;
  12. INSTANCE: c-writer output-stream
  13. INSTANCE: c-writer file-writer
  14. : <c-writer> ( handle -- stream ) c-writer new-c-stream ;
  15. M: c-writer stream-write1 dup check-disposed handle>> fputc ;
  16. M: c-writer stream-write
  17. dup check-disposed
  18. [ [ >c-ptr ] [ byte-length ] bi ] [ handle>> ] bi* fwrite ;
  19. M: c-writer stream-flush dup check-disposed handle>> fflush ;
  20. TUPLE: c-reader < c-stream ;
  21. INSTANCE: c-reader input-stream
  22. INSTANCE: c-reader file-reader
  23. : <c-reader> ( handle -- stream ) c-reader new-c-stream ;
  24. M: c-reader stream-read-unsafe dup check-disposed handle>> fread-unsafe ;
  25. M: c-reader stream-read1 dup check-disposed handle>> fgetc ;
  26. : read-until-loop ( stream delim -- ch )
  27. over stream-read1 dup [
  28. dup pick member-eq? [ 2nip ] [ , read-until-loop ] if
  29. ] [
  30. 2nip
  31. ] if ; inline recursive
  32. M: c-reader stream-read-until
  33. dup check-disposed
  34. [ swap read-until-loop ] B{ } make swap
  35. over empty? over not and [ 2drop f f ] when ;
  36. M: c-io-backend init-io ;
  37. : stdin-handle ( -- alien ) OBJ-STDIN special-object ;
  38. : stdout-handle ( -- alien ) OBJ-STDOUT special-object ;
  39. : stderr-handle ( -- alien ) OBJ-STDERR special-object ;
  40. : init-c-stdio ( -- )
  41. stdin-handle <c-reader>
  42. stdout-handle <c-writer>
  43. stderr-handle <c-writer>
  44. set-stdio ;
  45. M: c-io-backend init-stdio init-c-stdio ;
  46. M: c-io-backend io-multiplex
  47. dup 0 = [ drop ] [ 60 60 * 1000 * 1000 * or (sleep) ] if ;
  48. : fopen ( path mode -- alien )
  49. [ utf8 string>alien ] bi@ (fopen) ;
  50. M: c-io-backend (file-reader)
  51. "rb" fopen <c-reader> ;
  52. M: c-io-backend (file-writer)
  53. "wb" fopen <c-writer> ;
  54. M: c-io-backend (file-appender)
  55. "ab" fopen <c-writer> ;
  56. : show ( msg -- )
  57. #! A word which directly calls primitives. It is used to
  58. #! print stuff from contexts where the I/O system would
  59. #! otherwise not work (tools.deploy.shaker, the I/O
  60. #! multiplexer thread).
  61. "\n" append >byte-array dup length
  62. stdout-handle fwrite
  63. stdout-handle fflush ;