api-io.texi 81 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932
  1. @c -*-texinfo-*-
  2. @c This is part of the GNU Guile Reference Manual.
  3. @c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004, 2007, 2009,
  4. @c 2010, 2011, 2013, 2016, 2019, 2021 Free Software Foundation, Inc.
  5. @c See the file guile.texi for copying conditions.
  6. @node Input and Output
  7. @section Input and Output
  8. @menu
  9. * Ports:: What's a port?
  10. * Binary I/O:: Reading and writing bytes.
  11. * Encoding:: Characters as bytes.
  12. * Textual I/O:: Reading and writing characters.
  13. * Simple Output:: Simple syntactic sugar solution.
  14. * Buffering:: Controlling when data is written to ports.
  15. * Random Access:: Moving around a random access port.
  16. * Line/Delimited:: Read and write lines or delimited text.
  17. * Default Ports:: Defaults for input, output and errors.
  18. * Port Types:: Types of port and how to make them.
  19. * Venerable Port Interfaces:: Procedures from the last millenium.
  20. * Using Ports from C:: Nice interfaces for C.
  21. * I/O Extensions:: Implementing new port types in C.
  22. * Non-Blocking I/O:: How Guile deals with EWOULDBLOCK.
  23. * BOM Handling:: Handling of Unicode byte order marks.
  24. @end menu
  25. @node Ports
  26. @subsection Ports
  27. @cindex Port
  28. Ports are the way that Guile performs input and output. Guile can read
  29. in characters or bytes from an @dfn{input port}, or write them out to an
  30. @dfn{output port}. Some ports support both interfaces.
  31. There are a number of different port types implemented in Guile. File
  32. ports provide input and output over files, as you might imagine. For
  33. example, we might display a string to a file like this:
  34. @example
  35. (let ((port (open-output-file "foo.txt")))
  36. (display "Hello, world!\n" port)
  37. (close-port port))
  38. @end example
  39. There are also string ports, for taking input from a string, or
  40. collecting output to a string; bytevector ports, for doing the same but
  41. using a bytevector as a source or sink of data; and soft ports, for
  42. arranging to call Scheme functions to provide input or handle output.
  43. @xref{Port Types}.
  44. Ports should be @dfn{closed} when they are not needed by calling
  45. @code{close-port} on them, as in the example above. This will make sure
  46. that any pending output is successfully written out to disk, in the case
  47. of a file port, or otherwise to whatever mutable store is backed by the
  48. port. Any error that occurs while writing out that buffered data would
  49. also be raised promptly at the @code{close-port}, and not later when the
  50. port is closed by the garbage collector. @xref{Buffering}, for more on
  51. buffered output.
  52. Closing a port also releases any precious resource the file might have.
  53. Usually in Scheme a programmer doesn't have to clean up after their data
  54. structures (@pxref{Memory Management}), but most systems have strict
  55. limits on how many files can be open, both on a per-process and a
  56. system-wide basis. A program that uses many files should take care not
  57. to hit those limits. The same applies to similar system resources such
  58. as pipes and sockets.
  59. Indeed for these reasons the above example is not the most idiomatic way
  60. to use ports. It is more common to acquire ports via procedures like
  61. @code{call-with-output-file}, which handle the @code{close-port}
  62. automatically:
  63. @example
  64. (call-with-output-file "foo.txt"
  65. (lambda (port)
  66. (display "Hello, world!\n" port)))
  67. @end example
  68. Finally, all ports have associated input and output buffers, as
  69. appropriate. Buffering is a common strategy to limit the overhead of
  70. small reads and writes: without buffering, each character fetched from a
  71. file would involve at least one call into the kernel, and maybe more
  72. depending on the character and the encoding. Instead, Guile will batch
  73. reads and writes into internal buffers. However, sometimes you want to
  74. make output on a port show up immediately. @xref{Buffering}, for more
  75. on interfaces to control port buffering.
  76. @deffn {Scheme Procedure} port? x
  77. @deffnx {C Function} scm_port_p (x)
  78. Return a boolean indicating whether @var{x} is a port.
  79. @end deffn
  80. @rnindex input-port?
  81. @deffn {Scheme Procedure} input-port? x
  82. @deffnx {C Function} scm_input_port_p (x)
  83. Return @code{#t} if @var{x} is an input port, otherwise return
  84. @code{#f}. Any object satisfying this predicate also satisfies
  85. @code{port?}.
  86. @end deffn
  87. @rnindex output-port?
  88. @deffn {Scheme Procedure} output-port? x
  89. @deffnx {C Function} scm_output_port_p (x)
  90. Return @code{#t} if @var{x} is an output port, otherwise return
  91. @code{#f}. Any object satisfying this predicate also satisfies
  92. @code{port?}.
  93. @end deffn
  94. @cindex Closing ports
  95. @cindex Port, close
  96. @deffn {Scheme Procedure} close-port port
  97. @deffnx {C Function} scm_close_port (port)
  98. Close the specified port object. Return @code{#t} if it successfully
  99. closes a port or @code{#f} if it was already closed. An exception may
  100. be raised if an error occurs, for example when flushing buffered output.
  101. @xref{Buffering}, for more on buffered output. @xref{Ports and File
  102. Descriptors, close}, for a procedure which can close file descriptors.
  103. @end deffn
  104. @deffn {Scheme Procedure} port-closed? port
  105. @deffnx {C Function} scm_port_closed_p (port)
  106. Return @code{#t} if @var{port} is closed or @code{#f} if it is
  107. open.
  108. @end deffn
  109. @deffn {Scheme Procedure} call-with-port port proc
  110. Call @var{proc}, passing it @var{port} and closing @var{port} upon exit
  111. of @var{proc}. Return the return values of @var{proc}.
  112. @end deffn
  113. @node Binary I/O
  114. @subsection Binary I/O
  115. Guile's ports are fundamentally binary in nature: at the lowest level,
  116. they work on bytes. This section describes Guile's core binary I/O
  117. operations. @xref{Textual I/O}, for input and output of strings and
  118. characters.
  119. To use these routines, first include the binary I/O module:
  120. @example
  121. (use-modules (ice-9 binary-ports))
  122. @end example
  123. Note that although this module's name suggests that binary ports are
  124. some different kind of port, that's not the case: all ports in Guile are
  125. both binary and textual ports.
  126. @cindex binary input
  127. @deffn {Scheme Procedure} get-u8 port
  128. @deffnx {C Function} scm_get_u8 (port)
  129. Return an octet read from @var{port}, an input port, blocking as
  130. necessary, or the end-of-file object.
  131. @end deffn
  132. @deffn {Scheme Procedure} lookahead-u8 port
  133. @deffnx {C Function} scm_lookahead_u8 (port)
  134. Like @code{get-u8} but does not update @var{port}'s position to point
  135. past the octet.
  136. @end deffn
  137. The end-of-file object is unlike any other kind of object: it's not a
  138. pair, a symbol, or anything else. To check if a value is the
  139. end-of-file object, use the @code{eof-object?} predicate.
  140. @rnindex eof-object?
  141. @cindex End of file object
  142. @deffn {Scheme Procedure} eof-object? x
  143. @deffnx {C Function} scm_eof_object_p (x)
  144. Return @code{#t} if @var{x} is an end-of-file object, or @code{#f}
  145. otherwise.
  146. @end deffn
  147. Note that unlike other procedures in this module, @code{eof-object?} is
  148. defined in the default environment.
  149. @deffn {Scheme Procedure} get-bytevector-n port count
  150. @deffnx {C Function} scm_get_bytevector_n (port, count)
  151. Read @var{count} octets from @var{port}, blocking as necessary and
  152. return a bytevector containing the octets read. If fewer bytes are
  153. available, a bytevector smaller than @var{count} is returned.
  154. @end deffn
  155. @deffn {Scheme Procedure} get-bytevector-n! port bv start count
  156. @deffnx {C Function} scm_get_bytevector_n_x (port, bv, start, count)
  157. Read @var{count} bytes from @var{port} and store them in @var{bv}
  158. starting at index @var{start}. Return either the number of bytes
  159. actually read or the end-of-file object.
  160. @end deffn
  161. @deffn {Scheme Procedure} get-bytevector-some port
  162. @deffnx {C Function} scm_get_bytevector_some (port)
  163. Read from @var{port}, blocking as necessary, until bytes are available
  164. or an end-of-file is reached. Return either the end-of-file object or a
  165. new bytevector containing some of the available bytes (at least one),
  166. and update the port position to point just past these bytes.
  167. @end deffn
  168. @deffn {Scheme Procedure} get-bytevector-some! port bv start count
  169. @deffnx {C Function} scm_get_bytevector_some_x (port, bv, start, count)
  170. Read up to @var{count} bytes from @var{port}, blocking as necessary
  171. until at least one byte is available or an end-of-file is reached.
  172. Store them in @var{bv} starting at index @var{start}. Return the number
  173. of bytes actually read, or an end-of-file object.
  174. @end deffn
  175. @deffn {Scheme Procedure} get-bytevector-all port
  176. @deffnx {C Function} scm_get_bytevector_all (port)
  177. Read from @var{port}, blocking as necessary, until the end-of-file is
  178. reached. Return either a new bytevector containing the data read or the
  179. end-of-file object (if no data were available).
  180. @end deffn
  181. @deffn {Scheme Procedure} unget-bytevector port bv [start [count]]
  182. @deffnx {C Function} scm_unget_bytevector (port, bv, start, count)
  183. Place the contents of @var{bv} in @var{port}, optionally starting at
  184. index @var{start} and limiting to @var{count} octets, so that its bytes
  185. will be read from left-to-right as the next bytes from @var{port} during
  186. subsequent read operations. If called multiple times, the unread bytes
  187. will be read again in last-in first-out order.
  188. @end deffn
  189. @cindex binary output
  190. To perform binary output on a port, use @code{put-u8} or
  191. @code{put-bytevector}.
  192. @deffn {Scheme Procedure} put-u8 port octet
  193. @deffnx {C Function} scm_put_u8 (port, octet)
  194. Write @var{octet}, an integer in the 0--255 range, to @var{port}, a
  195. binary output port.
  196. @end deffn
  197. @deffn {Scheme Procedure} put-bytevector port bv [start [count]]
  198. @deffnx {C Function} scm_put_bytevector (port, bv, start, count)
  199. Write the contents of @var{bv} to @var{port}, optionally starting at
  200. index @var{start} and limiting to @var{count} octets.
  201. @end deffn
  202. @node Encoding
  203. @subsection Encoding
  204. Textual input and output on Guile ports is layered on top of binary
  205. operations. To this end, each port has an associated character encoding
  206. that controls how bytes read from the port are converted to characters,
  207. and how characters written to the port are converted to bytes.
  208. @deffn {Scheme Procedure} port-encoding port
  209. @deffnx {C Function} scm_port_encoding (port)
  210. Returns, as a string, the character encoding that @var{port} uses to
  211. interpret its input and output.
  212. @end deffn
  213. @deffn {Scheme Procedure} set-port-encoding! port enc
  214. @deffnx {C Function} scm_set_port_encoding_x (port, enc)
  215. Sets the character encoding that will be used to interpret I/O to
  216. @var{port}. @var{enc} is a string containing the name of an encoding.
  217. Valid encoding names are those
  218. @url{http://www.iana.org/assignments/character-sets, defined by IANA},
  219. for example @code{"UTF-8"} or @code{"ISO-8859-1"}.
  220. @end deffn
  221. When ports are created, they are assigned an encoding. The usual
  222. process to determine the initial encoding for a port is to take the
  223. value of the @code{%default-port-encoding} fluid.
  224. @defvr {Scheme Variable} %default-port-encoding
  225. A fluid containing name of the encoding to be used by default for newly
  226. created ports (@pxref{Fluids and Dynamic States}). As a special case,
  227. the value @code{#f} is equivalent to @code{"ISO-8859-1"}.
  228. @end defvr
  229. The @code{%default-port-encoding} itself defaults to the encoding
  230. appropriate for the current locale, if @code{setlocale} has been called.
  231. @xref{Locales}, for more on locales and when you might need to call
  232. @code{setlocale} explicitly.
  233. Some port types have other ways of determining their initial locales.
  234. String ports, for example, default to the UTF-8 encoding, in order to be
  235. able to represent all characters regardless of the current locale. File
  236. ports can optionally sniff their file for a @code{coding:} declaration;
  237. @xref{File Ports}. Binary ports might be initialized to the ISO-8859-1
  238. encoding in which each codepoint between 0 and 255 corresponds to a byte
  239. with that value.
  240. Currently, the ports only work with @emph{non-modal} encodings. Most
  241. encodings are non-modal, meaning that the conversion of bytes to a
  242. string doesn't depend on its context: the same byte sequence will always
  243. return the same string. A couple of modal encodings are in common use,
  244. like ISO-2022-JP and ISO-2022-KR, and they are not yet supported.
  245. @cindex port conversion strategy
  246. @cindex conversion strategy, port
  247. @cindex decoding error
  248. @cindex encoding error
  249. Each port also has an associated conversion strategy, which determines
  250. what to do when a Guile character can't be converted to the port's
  251. encoded character representation for output. There are three possible
  252. strategies: to raise an error, to replace the character with a hex
  253. escape, or to replace the character with a substitute character. Port
  254. conversion strategies are also used when decoding characters from an
  255. input port.
  256. @deffn {Scheme Procedure} port-conversion-strategy port
  257. @deffnx {C Function} scm_port_conversion_strategy (port)
  258. Returns the behavior of the port when outputting a character that is not
  259. representable in the port's current encoding.
  260. If @var{port} is @code{#f}, then the current default behavior will be
  261. returned. New ports will have this default behavior when they are
  262. created.
  263. @end deffn
  264. @deffn {Scheme Procedure} set-port-conversion-strategy! port sym
  265. @deffnx {C Function} scm_set_port_conversion_strategy_x (port, sym)
  266. Sets the behavior of Guile when outputting a character that is not
  267. representable in the port's current encoding, or when Guile encounters a
  268. decoding error when trying to read a character. @var{sym} can be either
  269. @code{error}, @code{substitute}, or @code{escape}.
  270. If @var{port} is an open port, the conversion error behavior is set for
  271. that port. If it is @code{#f}, it is set as the default behavior for
  272. any future ports that get created in this thread.
  273. @end deffn
  274. As with port encodings, there is a fluid which determines the initial
  275. conversion strategy for a port.
  276. @deffn {Scheme Variable} %default-port-conversion-strategy
  277. The fluid that defines the conversion strategy for newly created ports,
  278. and also for other conversion routines such as @code{scm_to_stringn},
  279. @code{scm_from_stringn}, @code{string->pointer}, and
  280. @code{pointer->string}.
  281. Its value must be one of the symbols described above, with the same
  282. semantics: @code{error}, @code{substitute}, or @code{escape}.
  283. When Guile starts, its value is @code{substitute}.
  284. Note that @code{(set-port-conversion-strategy! #f @var{sym})} is
  285. equivalent to @code{(fluid-set! %default-port-conversion-strategy
  286. @var{sym})}.
  287. @end deffn
  288. As mentioned above, for an output port there are three possible port
  289. conversion strategies. The @code{error} strategy will throw an error
  290. when a nonconvertible character is encountered. The @code{substitute}
  291. strategy will replace nonconvertible characters with a question mark
  292. (@samp{?}). Finally the @code{escape} strategy will print
  293. nonconvertible characters as a hex escape, using the escaping that is
  294. recognized by Guile's string syntax. Note that if the port's encoding
  295. is a Unicode encoding, like @code{UTF-8}, then encoding errors are
  296. impossible.
  297. For an input port, the @code{error} strategy will cause Guile to throw
  298. an error if it encounters an invalid encoding, such as might happen if
  299. you tried to read @code{ISO-8859-1} as @code{UTF-8}. The error is
  300. thrown before advancing the read position. The @code{substitute}
  301. strategy will replace the bad bytes with a U+FFFD replacement character,
  302. in accordance with Unicode recommendations. When reading from an input
  303. port, the @code{escape} strategy is treated as if it were @code{error}.
  304. @node Textual I/O
  305. @subsection Textual I/O
  306. @cindex textual input
  307. @cindex textual output
  308. This section describes Guile's core textual I/O operations on characters
  309. and strings. @xref{Binary I/O}, for input and output of bytes and
  310. bytevectors. @xref{Encoding}, for more on how characters relate to
  311. bytes. To read general S-expressions from ports, @xref{Scheme Read}.
  312. @xref{Scheme Write}, for interfaces that write generic Scheme datums.
  313. To use these routines, first include the textual I/O module:
  314. @example
  315. (use-modules (ice-9 textual-ports))
  316. @end example
  317. Note that although this module's name suggests that textual ports are
  318. some different kind of port, that's not the case: all ports in Guile are
  319. both binary and textual ports.
  320. @deffn {Scheme Procedure} get-char input-port
  321. Reads from @var{input-port}, blocking as necessary, until a
  322. complete character is available from @var{input-port},
  323. or until an end of file is reached.
  324. If a complete character is available before the next end of file,
  325. @code{get-char} returns that character and updates the input port to
  326. point past the character. If an end of file is reached before any
  327. character is read, @code{get-char} returns the end-of-file object.
  328. @end deffn
  329. @deffn {Scheme Procedure} lookahead-char input-port
  330. The @code{lookahead-char} procedure is like @code{get-char}, but it does
  331. not update @var{input-port} to point past the character.
  332. @end deffn
  333. In the same way that it's possible to "unget" a byte or bytes, it's
  334. possible to "unget" the bytes corresponding to an encoded character.
  335. @deffn {Scheme Procedure} unget-char port char
  336. Place character @var{char} in @var{port} so that it will be read by the
  337. next read operation. If called multiple times, the unread characters
  338. will be read again in last-in first-out order.
  339. @end deffn
  340. @deffn {Scheme Procedure} unget-string port str
  341. Place the string @var{str} in @var{port} so that its characters will
  342. be read from left-to-right as the next characters from @var{port}
  343. during subsequent read operations. If called multiple times, the
  344. unread characters will be read again in last-in first-out order.
  345. @end deffn
  346. Reading in a character at a time can be inefficient. If it's possible
  347. to perform I/O over multiple characters at a time, via strings, that
  348. might be faster.
  349. @deffn {Scheme Procedure} get-string-n input-port count
  350. The @code{get-string-n} procedure reads from @var{input-port}, blocking
  351. as necessary, until @var{count} characters are available, or until an
  352. end of file is reached. @var{count} must be an exact, non-negative
  353. integer, representing the number of characters to be read.
  354. If @var{count} characters are available before end of file,
  355. @code{get-string-n} returns a string consisting of those @var{count}
  356. characters. If fewer characters are available before an end of file, but
  357. one or more characters can be read, @code{get-string-n} returns a string
  358. containing those characters. In either case, the input port is updated
  359. to point just past the characters read. If no characters can be read
  360. before an end of file, the end-of-file object is returned.
  361. @end deffn
  362. @deffn {Scheme Procedure} get-string-n! input-port string start count
  363. The @code{get-string-n!} procedure reads from @var{input-port} in the
  364. same manner as @code{get-string-n}. @var{start} and @var{count} must be
  365. exact, non-negative integer objects, with @var{count} representing the
  366. number of characters to be read. @var{string} must be a string with at
  367. least $@var{start} + @var{count}$ characters.
  368. If @var{count} characters are available before an end of file, they are
  369. written into @var{string} starting at index @var{start}, and @var{count}
  370. is returned. If fewer characters are available before an end of file,
  371. but one or more can be read, those characters are written into
  372. @var{string} starting at index @var{start} and the number of characters
  373. actually read is returned as an exact integer object. If no characters
  374. can be read before an end of file, the end-of-file object is returned.
  375. @end deffn
  376. @deffn {Scheme Procedure} get-string-all input-port
  377. Reads from @var{input-port} until an end of file, decoding characters in
  378. the same manner as @code{get-string-n} and @code{get-string-n!}.
  379. If characters are available before the end of file, a string containing
  380. all the characters decoded from that data are returned. If no character
  381. precedes the end of file, the end-of-file object is returned.
  382. @end deffn
  383. @deffn {Scheme Procedure} get-line input-port
  384. Reads from @var{input-port} up to and including the linefeed
  385. character or end of file, decoding characters in the same manner as
  386. @code{get-string-n} and @code{get-string-n!}.
  387. If a linefeed character is read, a string containing all of the text up
  388. to (but not including) the linefeed character is returned, and the port
  389. is updated to point just past the linefeed character. If an end of file
  390. is encountered before any linefeed character is read, but some
  391. characters have been read and decoded as characters, a string containing
  392. those characters is returned. If an end of file is encountered before
  393. any characters are read, the end-of-file object is returned.
  394. @end deffn
  395. Finally, there are just two core procedures to write characters to a
  396. port.
  397. @deffn {Scheme Procedure} put-char port char
  398. Writes @var{char} to the port. The @code{put-char} procedure returns
  399. an unspecified value.
  400. @end deffn
  401. @deffn {Scheme Procedure} put-string port string
  402. @deffnx {Scheme Procedure} put-string port string start
  403. @deffnx {Scheme Procedure} put-string port string start count
  404. Write the @var{count} characters of @var{string} starting at index
  405. @var{start} to the port.
  406. @var{start} and @var{count} must be non-negative exact integer objects.
  407. @var{string} must have a length of at least @math{@var{start} +
  408. @var{count}}. @var{start} defaults to 0. @var{count} defaults to
  409. @math{@code{(string-length @var{string})} - @var{start}}$.
  410. Calling @code{put-string} is equivalent in all respects to calling
  411. @code{put-char} on the relevant sequence of characters, except that it
  412. will attempt to write multiple characters to the port at a time, even if
  413. the port is unbuffered.
  414. The @code{put-string} procedure returns an unspecified value.
  415. @end deffn
  416. Textual ports have a textual position associated with them: a line and a
  417. column. Reading in characters or writing them out advances the line and
  418. the column appropriately.
  419. @deffn {Scheme Procedure} port-column port
  420. @deffnx {Scheme Procedure} port-line port
  421. @deffnx {C Function} scm_port_column (port)
  422. @deffnx {C Function} scm_port_line (port)
  423. Return the current column number or line number of @var{port}.
  424. @end deffn
  425. Port lines and positions are represented as 0-origin integers, which is
  426. to say that the the first character of the first line is line 0, column
  427. 0. However, when you display a line number, for example in an error
  428. message, we recommend you add 1 to get 1-origin integers. This is
  429. because lines numbers traditionally start with 1, and that is what
  430. non-programmers will find most natural.
  431. @deffn {Scheme Procedure} set-port-column! port column
  432. @deffnx {Scheme Procedure} set-port-line! port line
  433. @deffnx {C Function} scm_set_port_column_x (port, column)
  434. @deffnx {C Function} scm_set_port_line_x (port, line)
  435. Set the current column or line number of @var{port}.
  436. @end deffn
  437. @node Simple Output
  438. @subsection Simple Textual Output
  439. Guile exports a simple formatted output function, @code{simple-format}.
  440. For a more capable formatted output facility, @xref{Formatted Output}.
  441. @deffn {Scheme Procedure} simple-format destination message . args
  442. @deffnx {C Function} scm_simple_format (destination, message, args)
  443. Write @var{message} to @var{destination}, defaulting to the current
  444. output port. @var{message} can contain @code{~A} and @code{~S} escapes.
  445. When printed, the escapes are replaced with corresponding members of
  446. @var{args}: @code{~A} formats using @code{display} and @code{~S} formats
  447. using @code{write}. If @var{destination} is @code{#t}, then use the
  448. current output port, if @var{destination} is @code{#f}, then return a
  449. string containing the formatted text. Does not add a trailing newline.
  450. @end deffn
  451. Somewhat confusingly, Guile binds the @code{format} identifier to
  452. @code{simple-format} at startup. Once @code{(ice-9 format)} loads, it
  453. actually replaces the core @code{format} binding, so depending on
  454. whether you or a module you use has loaded @code{(ice-9 format)}, you
  455. may be using the simple or the more capable version.
  456. @node Buffering
  457. @subsection Buffering
  458. @cindex Port, buffering
  459. Every port has associated input and output buffers. You can think of
  460. ports as being backed by some mutable store, and that store might be far
  461. away. For example, ports backed by file descriptors have to go all the
  462. way to the kernel to read and write their data. To avoid this
  463. round-trip cost, Guile usually reads in data from the mutable store in
  464. chunks, and then services small requests like @code{get-char} out of
  465. that intermediate buffer. Similarly, small writes like
  466. @code{write-char} first go to a buffer, and are sent to the store when
  467. the buffer is full (or when port is flushed). Buffered ports speed up
  468. your program by reducing the number of round-trips to the mutable store,
  469. and they do so in a way that is mostly transparent to the user.
  470. There are two major ways, however, in which buffering affects program
  471. semantics. Building correct, performant programs requires understanding
  472. these situations.
  473. The first case is in random-access read/write ports (@pxref{Random
  474. Access}). These ports, usually backed by a file, logically operate over
  475. the same mutable store when both reading and writing. So, if you read a
  476. character, causing the buffer to fill, then write a character, the bytes
  477. you filled in your read buffer are now invalid. Every time you switch
  478. between reading and writing, Guile has to flush any pending buffer. If
  479. this happens frequently, the cost can be high. In that case you should
  480. reduce the amount that you buffer, in both directions. Similarly, Guile
  481. has to flush buffers before seeking. None of these considerations apply
  482. to sockets, which don't logically read from and write to the same
  483. mutable store, and are not seekable. Note also that sockets are
  484. unbuffered by default. @xref{Network Sockets and Communication}.
  485. The second case is the more pernicious one. If you write data to a
  486. buffered port, it probably doesn't go out to the mutable store directly.
  487. (This ``probably'' introduces some indeterminism in your program: what
  488. goes to the store, and when, depends on how full the buffer is. It is
  489. something that the user needs to explicitly be aware of.) The data is
  490. written to the store later -- when the buffer fills up due to another
  491. write, or when @code{force-output} is called, or when @code{close-port}
  492. is called, or when the program exits, or even when the garbage collector
  493. runs. The salient point is, @emph{the errors are signalled then too}.
  494. Buffered writes defer error detection (and defer the side effects to the
  495. mutable store), perhaps indefinitely if the port type does not need to
  496. be closed at GC.
  497. One common heuristic that works well for textual ports is to flush
  498. output when a newline (@code{\n}) is written. This @dfn{line buffering}
  499. mode is on by default for TTY ports. Most other ports are @dfn{block
  500. buffered}, meaning that once the output buffer reaches the block size,
  501. which depends on the port and its configuration, the output is flushed
  502. as a block, without regard to what is in the block. Likewise reads are
  503. read in at the block size, though if there are fewer bytes available to
  504. read, the buffer may not be entirely filled.
  505. Note that binary reads or writes that are larger than the buffer size go
  506. directly to the mutable store without passing through the buffers. If
  507. your access pattern involves many big reads or writes, buffering might
  508. not matter so much to you.
  509. To control the buffering behavior of a port, use @code{setvbuf}.
  510. @deffn {Scheme Procedure} setvbuf port mode [size]
  511. @deffnx {C Function} scm_setvbuf (port, mode, size)
  512. @cindex port buffering
  513. Set the buffering mode for @var{port}. @var{mode} can be one of the
  514. following symbols:
  515. @table @code
  516. @item none
  517. non-buffered
  518. @item line
  519. line buffered
  520. @item block
  521. block buffered, using a newly allocated buffer of @var{size} bytes.
  522. If @var{size} is omitted, a default size will be used.
  523. @end table
  524. @end deffn
  525. Another way to set the buffering, for file ports, is to open the file
  526. with @code{0} or @code{l} as part of the mode string, for unbuffered or
  527. line-buffered ports, respectively. @xref{File Ports}, for more.
  528. Any buffered output data will be written out when the port is closed.
  529. To make sure to flush it at specific points in your program, use
  530. @code{force-otput}.
  531. @findex fflush
  532. @deffn {Scheme Procedure} force-output [port]
  533. @deffnx {C Function} scm_force_output (port)
  534. Flush the specified output port, or the current output port if
  535. @var{port} is omitted. The current output buffer contents, if any, are
  536. passed to the underlying port implementation.
  537. The return value is unspecified.
  538. @end deffn
  539. @deffn {Scheme Procedure} flush-all-ports
  540. @deffnx {C Function} scm_flush_all_ports ()
  541. Equivalent to calling @code{force-output} on all open output ports. The
  542. return value is unspecified.
  543. @end deffn
  544. Similarly, sometimes you might want to switch from using Guile's ports
  545. to working directly on file descriptors. In that case, for input ports
  546. use @code{drain-input} to get any buffered input from that port.
  547. @deffn {Scheme Procedure} drain-input port
  548. @deffnx {C Function} scm_drain_input (port)
  549. This procedure clears a port's input buffers, similar
  550. to the way that force-output clears the output buffer. The
  551. contents of the buffers are returned as a single string, e.g.,
  552. @lisp
  553. (define p (open-input-file ...))
  554. (drain-input p) => empty string, nothing buffered yet.
  555. (unread-char (read-char p) p)
  556. (drain-input p) => initial chars from p, up to the buffer size.
  557. @end lisp
  558. @end deffn
  559. All of these considerations are very similar to those of streams in the
  560. C library, although Guile's ports are not built on top of C streams.
  561. Still, it is useful to read what other systems do.
  562. @xref{Streams,,,libc,The GNU C Library Reference Manual}, for more
  563. discussion on C streams.
  564. @node Random Access
  565. @subsection Random Access
  566. @cindex Random access, ports
  567. @cindex Port, random access
  568. @deffn {Scheme Procedure} seek fd_port offset whence
  569. @deffnx {C Function} scm_seek (fd_port, offset, whence)
  570. Sets the current position of @var{fd_port} to the integer
  571. @var{offset}. For a file port, @var{offset} is expressed
  572. as a number of bytes; for other types of ports, such as string
  573. ports, @var{offset} is an abstract representation of the
  574. position within the port's data, not necessarily expressed
  575. as a number of bytes. @var{offset} is interpreted according to
  576. the value of @var{whence}.
  577. One of the following variables should be supplied for
  578. @var{whence}:
  579. @defvar SEEK_SET
  580. Seek from the beginning of the file.
  581. @end defvar
  582. @defvar SEEK_CUR
  583. Seek from the current position.
  584. @end defvar
  585. @defvar SEEK_END
  586. Seek from the end of the file.
  587. @end defvar
  588. If @var{fd_port} is a file descriptor, the underlying system
  589. call is @code{lseek}. @var{port} may be a string port.
  590. The value returned is the new position in @var{fd_port}. This means
  591. that the current position of a port can be obtained using:
  592. @lisp
  593. (seek port 0 SEEK_CUR)
  594. @end lisp
  595. @end deffn
  596. @deffn {Scheme Procedure} ftell fd_port
  597. @deffnx {C Function} scm_ftell (fd_port)
  598. Return an integer representing the current position of
  599. @var{fd_port}, measured from the beginning. Equivalent to:
  600. @lisp
  601. (seek port 0 SEEK_CUR)
  602. @end lisp
  603. @end deffn
  604. @findex truncate
  605. @findex ftruncate
  606. @deffn {Scheme Procedure} truncate-file file [length]
  607. @deffnx {C Function} scm_truncate_file (file, length)
  608. Truncate @var{file} to @var{length} bytes. @var{file} can be a
  609. filename string, a port object, or an integer file descriptor. The
  610. return value is unspecified.
  611. For a port or file descriptor @var{length} can be omitted, in which
  612. case the file is truncated at the current position (per @code{ftell}
  613. above).
  614. On most systems a file can be extended by giving a length greater than
  615. the current size, but this is not mandatory in the POSIX standard.
  616. @end deffn
  617. @node Line/Delimited
  618. @subsection Line Oriented and Delimited Text
  619. @cindex Line input/output
  620. @cindex Port, line input/output
  621. The delimited-I/O module can be accessed with:
  622. @lisp
  623. (use-modules (ice-9 rdelim))
  624. @end lisp
  625. It can be used to read or write lines of text, or read text delimited by
  626. a specified set of characters.
  627. @deffn {Scheme Procedure} read-line [port] [handle-delim]
  628. Return a line of text from @var{port} if specified, otherwise from the
  629. value returned by @code{(current-input-port)}. Under Unix, a line of text
  630. is terminated by the first end-of-line character or by end-of-file.
  631. If @var{handle-delim} is specified, it should be one of the following
  632. symbols:
  633. @table @code
  634. @item trim
  635. Discard the terminating delimiter. This is the default, but it will
  636. be impossible to tell whether the read terminated with a delimiter or
  637. end-of-file.
  638. @item concat
  639. Append the terminating delimiter (if any) to the returned string.
  640. @item peek
  641. Push the terminating delimiter (if any) back on to the port.
  642. @item split
  643. Return a pair containing the string read from the port and the
  644. terminating delimiter or end-of-file object.
  645. @end table
  646. @end deffn
  647. @deffn {Scheme Procedure} read-line! buf [port]
  648. Read a line of text into the supplied string @var{buf} and return the
  649. number of characters added to @var{buf}. If @var{buf} is filled, then
  650. @code{#f} is returned. Read from @var{port} if specified, otherwise
  651. from the value returned by @code{(current-input-port)}.
  652. @end deffn
  653. @deffn {Scheme Procedure} read-delimited delims [port] [handle-delim]
  654. Read text until one of the characters in the string @var{delims} is
  655. found or end-of-file is reached. Read from @var{port} if supplied,
  656. otherwise from the value returned by @code{(current-input-port)}.
  657. @var{handle-delim} takes the same values as described for
  658. @code{read-line}.
  659. @end deffn
  660. @c begin (scm-doc-string "rdelim.scm" "read-delimited!")
  661. @deffn {Scheme Procedure} read-delimited! delims buf [port] [handle-delim] [start] [end]
  662. Read text into the supplied string @var{buf}.
  663. If a delimiter was found, return the number of characters written,
  664. except if @var{handle-delim} is @code{split}, in which case the return
  665. value is a pair, as noted above.
  666. As a special case, if @var{port} was already at end-of-stream, the EOF
  667. object is returned. Also, if no characters were written because the
  668. buffer was full, @code{#f} is returned.
  669. It's something of a wacky interface, to be honest.
  670. @end deffn
  671. @deffn {Scheme Procedure} %read-delimited! delims str gobble [port [start [end]]]
  672. @deffnx {C Function} scm_read_delimited_x (delims, str, gobble, port, start, end)
  673. Read characters from @var{port} into @var{str} until one of the
  674. characters in the @var{delims} string is encountered. If
  675. @var{gobble} is true, discard the delimiter character;
  676. otherwise, leave it in the input stream for the next read. If
  677. @var{port} is not specified, use the value of
  678. @code{(current-input-port)}. If @var{start} or @var{end} are
  679. specified, store data only into the substring of @var{str}
  680. bounded by @var{start} and @var{end} (which default to the
  681. beginning and end of the string, respectively).
  682. Return a pair consisting of the delimiter that terminated the
  683. string and the number of characters read. If reading stopped
  684. at the end of file, the delimiter returned is the
  685. @var{eof-object}; if the string was filled without encountering
  686. a delimiter, this value is @code{#f}.
  687. @end deffn
  688. @deffn {Scheme Procedure} %read-line [port]
  689. @deffnx {C Function} scm_read_line (port)
  690. Read a newline-terminated line from @var{port}, allocating storage as
  691. necessary. The newline terminator (if any) is removed from the string,
  692. and a pair consisting of the line and its delimiter is returned. The
  693. delimiter may be either a newline or the @var{eof-object}; if
  694. @code{%read-line} is called at the end of file, it returns the pair
  695. @code{(#<eof> . #<eof>)}.
  696. @end deffn
  697. @node Default Ports
  698. @subsection Default Ports for Input, Output and Errors
  699. @cindex Default ports
  700. @cindex Port, default
  701. @rnindex current-input-port
  702. @deffn {Scheme Procedure} current-input-port
  703. @deffnx {C Function} scm_current_input_port ()
  704. @cindex standard input
  705. Return the current input port. This is the default port used
  706. by many input procedures.
  707. Initially this is the @dfn{standard input} in Unix and C terminology.
  708. When the standard input is a tty the port is unbuffered, otherwise
  709. it's fully buffered.
  710. Unbuffered input is good if an application runs an interactive
  711. subprocess, since any type-ahead input won't go into Guile's buffer
  712. and be unavailable to the subprocess.
  713. Note that Guile buffering is completely separate from the tty ``line
  714. discipline''. In the usual cooked mode on a tty Guile only sees a
  715. line of input once the user presses @key{Return}.
  716. @end deffn
  717. @rnindex current-output-port
  718. @deffn {Scheme Procedure} current-output-port
  719. @deffnx {C Function} scm_current_output_port ()
  720. @cindex standard output
  721. Return the current output port. This is the default port used
  722. by many output procedures.
  723. Initially this is the @dfn{standard output} in Unix and C terminology.
  724. When the standard output is a tty this port is unbuffered, otherwise
  725. it's fully buffered.
  726. Unbuffered output to a tty is good for ensuring progress output or a
  727. prompt is seen. But an application which always prints whole lines
  728. could change to line buffered, or an application with a lot of output
  729. could go fully buffered and perhaps make explicit @code{force-output}
  730. calls (@pxref{Buffering}) at selected points.
  731. @end deffn
  732. @deffn {Scheme Procedure} current-error-port
  733. @deffnx {C Function} scm_current_error_port ()
  734. @cindex standard error output
  735. Return the port to which errors and warnings should be sent.
  736. Initially this is the @dfn{standard error} in Unix and C terminology.
  737. When the standard error is a tty this port is unbuffered, otherwise
  738. it's fully buffered.
  739. @end deffn
  740. @deffn {Scheme Procedure} set-current-input-port port
  741. @deffnx {Scheme Procedure} set-current-output-port port
  742. @deffnx {Scheme Procedure} set-current-error-port port
  743. @deffnx {C Function} scm_set_current_input_port (port)
  744. @deffnx {C Function} scm_set_current_output_port (port)
  745. @deffnx {C Function} scm_set_current_error_port (port)
  746. Change the ports returned by @code{current-input-port},
  747. @code{current-output-port} and @code{current-error-port}, respectively,
  748. so that they use the supplied @var{port} for input or output.
  749. @end deffn
  750. @deffn {Scheme Procedure} with-input-from-port port thunk
  751. @deffnx {Scheme Procedure} with-output-to-port port thunk
  752. @deffnx {Scheme Procedure} with-error-to-port port thunk
  753. Call @var{thunk} in a dynamic environment in which
  754. @code{current-input-port}, @code{current-output-port} or
  755. @code{current-error-port} is rebound to the given @var{port}.
  756. @end deffn
  757. @deftypefn {C Function} void scm_dynwind_current_input_port (SCM port)
  758. @deftypefnx {C Function} void scm_dynwind_current_output_port (SCM port)
  759. @deftypefnx {C Function} void scm_dynwind_current_error_port (SCM port)
  760. These functions must be used inside a pair of calls to
  761. @code{scm_dynwind_begin} and @code{scm_dynwind_end} (@pxref{Dynamic
  762. Wind}). During the dynwind context, the indicated port is set to
  763. @var{port}.
  764. More precisely, the current port is swapped with a `backup' value
  765. whenever the dynwind context is entered or left. The backup value is
  766. initialized with the @var{port} argument.
  767. @end deftypefn
  768. @node Port Types
  769. @subsection Types of Port
  770. @cindex Types of ports
  771. @cindex Port, types
  772. @menu
  773. * File Ports:: Ports on an operating system file.
  774. * Bytevector Ports:: Ports on a bytevector.
  775. * String Ports:: Ports on a Scheme string.
  776. * Custom Ports:: Ports whose implementation you control.
  777. * Soft Ports:: An older version of custom ports.
  778. * Void Ports:: Ports on nothing at all.
  779. @end menu
  780. @node File Ports
  781. @subsubsection File Ports
  782. @cindex File port
  783. @cindex Port, file
  784. The following procedures are used to open file ports.
  785. See also @ref{Ports and File Descriptors, open}, for an interface
  786. to the Unix @code{open} system call.
  787. All file access uses the ``LFS'' large file support functions when
  788. available, so files bigger than 2 Gbytes (@math{2^31} bytes) can be
  789. read and written on a 32-bit system.
  790. Most systems have limits on how many files can be open, so it's
  791. strongly recommended that file ports be closed explicitly when no
  792. longer required (@pxref{Ports}).
  793. @deffn {Scheme Procedure} open-file filename mode @
  794. [#:guess-encoding=#f] [#:encoding=#f]
  795. @deffnx {C Function} scm_open_file_with_encoding @
  796. (filename, mode, guess_encoding, encoding)
  797. @deffnx {C Function} scm_open_file (filename, mode)
  798. Open the file whose name is @var{filename}, and return a port
  799. representing that file. The attributes of the port are
  800. determined by the @var{mode} string. The way in which this is
  801. interpreted is similar to C stdio. The first character must be
  802. one of the following:
  803. @table @samp
  804. @item r
  805. Open an existing file for input.
  806. @item w
  807. Open a file for output, creating it if it doesn't already exist
  808. or removing its contents if it does.
  809. @item a
  810. Open a file for output, creating it if it doesn't already
  811. exist. All writes to the port will go to the end of the file.
  812. The "append mode" can be turned off while the port is in use
  813. @pxref{Ports and File Descriptors, fcntl}
  814. @end table
  815. The following additional characters can be appended:
  816. @table @samp
  817. @item +
  818. Open the port for both input and output. E.g., @code{r+}: open
  819. an existing file for both input and output.
  820. @item 0
  821. Create an "unbuffered" port. In this case input and output
  822. operations are passed directly to the underlying port
  823. implementation without additional buffering. This is likely to
  824. slow down I/O operations. The buffering mode can be changed
  825. while a port is in use (@pxref{Buffering}).
  826. @item l
  827. Add line-buffering to the port. The port output buffer will be
  828. automatically flushed whenever a newline character is written.
  829. @item b
  830. Use binary mode, ensuring that each byte in the file will be read as one
  831. Scheme character.
  832. To provide this property, the file will be opened with the 8-bit
  833. character encoding "ISO-8859-1", ignoring the default port encoding.
  834. @xref{Ports}, for more information on port encodings.
  835. Note that while it is possible to read and write binary data as
  836. characters or strings, it is usually better to treat bytes as octets,
  837. and byte sequences as bytevectors. @xref{Binary I/O}, for more.
  838. This option had another historical meaning, for DOS compatibility: in
  839. the default (textual) mode, DOS reads a CR-LF sequence as one LF byte.
  840. The @code{b} flag prevents this from happening, adding @code{O_BINARY}
  841. to the underlying @code{open} call. Still, the flag is generally useful
  842. because of its port encoding ramifications.
  843. @end table
  844. Unless binary mode is requested, the character encoding of the new port
  845. is determined as follows: First, if @var{guess-encoding} is true, the
  846. @code{file-encoding} procedure is used to guess the encoding of the file
  847. (@pxref{Character Encoding of Source Files}). If @var{guess-encoding}
  848. is false or if @code{file-encoding} fails, @var{encoding} is used unless
  849. it is also false. As a last resort, the default port encoding is used.
  850. @xref{Ports}, for more information on port encodings. It is an error to
  851. pass a non-false @var{guess-encoding} or @var{encoding} if binary mode
  852. is requested.
  853. If a file cannot be opened with the access requested, @code{open-file}
  854. throws an exception.
  855. @end deffn
  856. @rnindex open-input-file
  857. @deffn {Scheme Procedure} open-input-file filename @
  858. [#:guess-encoding=#f] [#:encoding=#f] [#:binary=#f]
  859. Open @var{filename} for input. If @var{binary} is true, open the port
  860. in binary mode, otherwise use text mode. @var{encoding} and
  861. @var{guess-encoding} determine the character encoding as described above
  862. for @code{open-file}. Equivalent to
  863. @lisp
  864. (open-file @var{filename}
  865. (if @var{binary} "rb" "r")
  866. #:guess-encoding @var{guess-encoding}
  867. #:encoding @var{encoding})
  868. @end lisp
  869. @end deffn
  870. @rnindex open-output-file
  871. @deffn {Scheme Procedure} open-output-file filename @
  872. [#:encoding=#f] [#:binary=#f]
  873. Open @var{filename} for output. If @var{binary} is true, open the port
  874. in binary mode, otherwise use text mode. @var{encoding} specifies the
  875. character encoding as described above for @code{open-file}. Equivalent
  876. to
  877. @lisp
  878. (open-file @var{filename}
  879. (if @var{binary} "wb" "w")
  880. #:encoding @var{encoding})
  881. @end lisp
  882. @end deffn
  883. @deffn {Scheme Procedure} call-with-input-file filename proc @
  884. [#:guess-encoding=#f] [#:encoding=#f] [#:binary=#f]
  885. @deffnx {Scheme Procedure} call-with-output-file filename proc @
  886. [#:encoding=#f] [#:binary=#f]
  887. @rnindex call-with-input-file
  888. @rnindex call-with-output-file
  889. Open @var{filename} for input or output, and call @code{(@var{proc}
  890. port)} with the resulting port. Return the value returned by
  891. @var{proc}. @var{filename} is opened as per @code{open-input-file} or
  892. @code{open-output-file} respectively, and an error is signaled if it
  893. cannot be opened.
  894. When @var{proc} returns, the port is closed. If @var{proc} does not
  895. return (e.g.@: if it throws an error), then the port might not be
  896. closed automatically, though it will be garbage collected in the usual
  897. way if not otherwise referenced.
  898. @end deffn
  899. @deffn {Scheme Procedure} with-input-from-file filename thunk @
  900. [#:guess-encoding=#f] [#:encoding=#f] [#:binary=#f]
  901. @deffnx {Scheme Procedure} with-output-to-file filename thunk @
  902. [#:encoding=#f] [#:binary=#f]
  903. @deffnx {Scheme Procedure} with-error-to-file filename thunk @
  904. [#:encoding=#f] [#:binary=#f]
  905. @rnindex with-input-from-file
  906. @rnindex with-output-to-file
  907. Open @var{filename} and call @code{(@var{thunk})} with the new port
  908. setup as respectively the @code{current-input-port},
  909. @code{current-output-port}, or @code{current-error-port}. Return the
  910. value returned by @var{thunk}. @var{filename} is opened as per
  911. @code{open-input-file} or @code{open-output-file} respectively, and an
  912. error is signaled if it cannot be opened.
  913. When @var{thunk} returns, the port is closed and the previous setting
  914. of the respective current port is restored.
  915. The current port setting is managed with @code{dynamic-wind}, so the
  916. previous value is restored no matter how @var{thunk} exits (eg.@: an
  917. exception), and if @var{thunk} is re-entered (via a captured
  918. continuation) then it's set again to the @var{filename} port.
  919. The port is closed when @var{thunk} returns normally, but not when
  920. exited via an exception or new continuation. This ensures it's still
  921. ready for use if @var{thunk} is re-entered by a captured continuation.
  922. Of course the port is always garbage collected and closed in the usual
  923. way when no longer referenced anywhere.
  924. @end deffn
  925. @deffn {Scheme Procedure} port-mode port
  926. @deffnx {C Function} scm_port_mode (port)
  927. Return the port modes associated with the open port @var{port}.
  928. These will not necessarily be identical to the modes used when
  929. the port was opened, since modes such as "append" which are
  930. used only during port creation are not retained.
  931. @end deffn
  932. @deffn {Scheme Procedure} port-filename port
  933. @deffnx {C Function} scm_port_filename (port)
  934. Return the filename associated with @var{port}, or @code{#f} if no
  935. filename is associated with the port.
  936. @var{port} must be open; @code{port-filename} cannot be used once the
  937. port is closed.
  938. @end deffn
  939. @deffn {Scheme Procedure} set-port-filename! port filename
  940. @deffnx {C Function} scm_set_port_filename_x (port, filename)
  941. Change the filename associated with @var{port}, using the current input
  942. port if none is specified. Note that this does not change the port's
  943. source of data, but only the value that is returned by
  944. @code{port-filename} and reported in diagnostic output.
  945. @end deffn
  946. @deffn {Scheme Procedure} file-port? obj
  947. @deffnx {C Function} scm_file_port_p (obj)
  948. Determine whether @var{obj} is a port that is related to a file.
  949. @end deffn
  950. @node Bytevector Ports
  951. @subsubsection Bytevector Ports
  952. @deffn {Scheme Procedure} open-bytevector-input-port bv [transcoder]
  953. @deffnx {C Function} scm_open_bytevector_input_port (bv, transcoder)
  954. Return an input port whose contents are drawn from bytevector @var{bv}
  955. (@pxref{Bytevectors}).
  956. @c FIXME: Update description when implemented.
  957. The @var{transcoder} argument is currently not supported.
  958. @end deffn
  959. @deffn {Scheme Procedure} open-bytevector-output-port [transcoder]
  960. @deffnx {C Function} scm_open_bytevector_output_port (transcoder)
  961. Return two values: a binary output port and a procedure. The latter
  962. should be called with zero arguments to obtain a bytevector containing
  963. the data accumulated by the port, as illustrated below.
  964. @lisp
  965. (call-with-values
  966. (lambda ()
  967. (open-bytevector-output-port))
  968. (lambda (port get-bytevector)
  969. (display "hello" port)
  970. (get-bytevector)))
  971. @result{} #vu8(104 101 108 108 111)
  972. @end lisp
  973. @c FIXME: Update description when implemented.
  974. The @var{transcoder} argument is currently not supported.
  975. @end deffn
  976. @deffn {Scheme Procedure} call-with-output-bytevector proc
  977. Call the one-argument procedure @var{proc} with a newly created
  978. bytevector output port. When the function returns, the bytevector
  979. composed of the characters written into the port is returned.
  980. @var{proc} should not close the port.
  981. @end deffn
  982. @deffn {Scheme Procedure} call-with-input-bytevector bytevector proc
  983. Call the one-argument procedure @var{proc} with a newly created input
  984. port from which @var{bytevector}'s contents may be read. The values
  985. yielded by the @var{proc} is returned.
  986. @end deffn
  987. @node String Ports
  988. @subsubsection String Ports
  989. @cindex String port
  990. @cindex Port, string
  991. @deffn {Scheme Procedure} call-with-output-string proc
  992. @deffnx {C Function} scm_call_with_output_string (proc)
  993. Calls the one-argument procedure @var{proc} with a newly created output
  994. port. When the function returns, the string composed of the characters
  995. written into the port is returned. @var{proc} should not close the port.
  996. @end deffn
  997. @deffn {Scheme Procedure} call-with-input-string string proc
  998. @deffnx {C Function} scm_call_with_input_string (string, proc)
  999. Calls the one-argument procedure @var{proc} with a newly
  1000. created input port from which @var{string}'s contents may be
  1001. read. The value yielded by the @var{proc} is returned.
  1002. @end deffn
  1003. @deffn {Scheme Procedure} with-output-to-string thunk
  1004. Calls the zero-argument procedure @var{thunk} with the current output
  1005. port set temporarily to a new string port. It returns a string
  1006. composed of the characters written to the current output.
  1007. @end deffn
  1008. @deffn {Scheme Procedure} with-input-from-string string thunk
  1009. Calls the zero-argument procedure @var{thunk} with the current input
  1010. port set temporarily to a string port opened on the specified
  1011. @var{string}. The value yielded by @var{thunk} is returned.
  1012. @end deffn
  1013. @deffn {Scheme Procedure} open-input-string str
  1014. @deffnx {C Function} scm_open_input_string (str)
  1015. Take a string and return an input port that delivers characters
  1016. from the string. The port can be closed by
  1017. @code{close-input-port}, though its storage will be reclaimed
  1018. by the garbage collector if it becomes inaccessible.
  1019. @end deffn
  1020. @deffn {Scheme Procedure} open-output-string
  1021. @deffnx {C Function} scm_open_output_string ()
  1022. Return an output port that will accumulate characters for
  1023. retrieval by @code{get-output-string}. The port can be closed
  1024. by the procedure @code{close-output-port}, though its storage
  1025. will be reclaimed by the garbage collector if it becomes
  1026. inaccessible.
  1027. @end deffn
  1028. @deffn {Scheme Procedure} get-output-string port
  1029. @deffnx {C Function} scm_get_output_string (port)
  1030. Given an output port created by @code{open-output-string},
  1031. return a string consisting of the characters that have been
  1032. output to the port so far.
  1033. @code{get-output-string} must be used before closing @var{port}, once
  1034. closed the string cannot be obtained.
  1035. @end deffn
  1036. With string ports, the port-encoding is treated differently than other
  1037. types of ports. When string ports are created, they do not inherit a
  1038. character encoding from the current locale. They are given a
  1039. default locale that allows them to handle all valid string characters.
  1040. Typically one should not modify a string port's character encoding
  1041. away from its default. @xref{Encoding}.
  1042. @node Custom Ports
  1043. @subsubsection Custom Ports
  1044. Custom ports allow the user to provide input and handle output via
  1045. user-supplied procedures. Guile currently only provides custom binary
  1046. ports, not textual ports; for custom textual ports, @xref{Soft Ports}.
  1047. We should add the R6RS custom textual port interfaces though.
  1048. Contributions are appreciated.
  1049. @cindex custom binary input ports
  1050. @deffn {Scheme Procedure} make-custom-binary-input-port id read! get-position set-position! close
  1051. Return a new custom binary input port@footnote{This is similar in spirit
  1052. to Guile's @dfn{soft ports} (@pxref{Soft Ports}).} named @var{id} (a
  1053. string) whose input is drained by invoking @var{read!} and passing it a
  1054. bytevector, an index where bytes should be written, and the number of
  1055. bytes to read. The @code{read!} procedure must return an integer
  1056. indicating the number of bytes read, or @code{0} to indicate the
  1057. end-of-file.
  1058. Optionally, if @var{get-position} is not @code{#f}, it must be a thunk
  1059. that will be called when @code{port-position} is invoked on the custom
  1060. binary port and should return an integer indicating the position within
  1061. the underlying data stream; if @var{get-position} was not supplied, the
  1062. returned port does not support @code{port-position}.
  1063. Likewise, if @var{set-position!} is not @code{#f}, it should be a
  1064. one-argument procedure. When @code{set-port-position!} is invoked on the
  1065. custom binary input port, @var{set-position!} is passed an integer
  1066. indicating the position of the next byte is to read.
  1067. Finally, if @var{close} is not @code{#f}, it must be a thunk. It is
  1068. invoked when the custom binary input port is closed.
  1069. The returned port is fully buffered by default, but its buffering mode
  1070. can be changed using @code{setvbuf} (@pxref{Buffering}).
  1071. Using a custom binary input port, the @code{open-bytevector-input-port}
  1072. procedure (@pxref{Bytevector Ports}) could be implemented as follows:
  1073. @lisp
  1074. (define (open-bytevector-input-port source)
  1075. (define position 0)
  1076. (define length (bytevector-length source))
  1077. (define (read! bv start count)
  1078. (let ((count (min count (- length position))))
  1079. (bytevector-copy! source position
  1080. bv start count)
  1081. (set! position (+ position count))
  1082. count))
  1083. (define (get-position) position)
  1084. (define (set-position! new-position)
  1085. (set! position new-position))
  1086. (make-custom-binary-input-port "the port" read!
  1087. get-position set-position!
  1088. #f))
  1089. (read (open-bytevector-input-port (string->utf8 "hello")))
  1090. @result{} hello
  1091. @end lisp
  1092. @end deffn
  1093. @cindex custom binary output ports
  1094. @deffn {Scheme Procedure} make-custom-binary-output-port id write! get-position set-position! close
  1095. Return a new custom binary output port named @var{id} (a string) whose
  1096. output is sunk by invoking @var{write!} and passing it a bytevector, an
  1097. index where bytes should be read from this bytevector, and the number of
  1098. bytes to be ``written''. The @code{write!} procedure must return an
  1099. integer indicating the number of bytes actually written; when it is
  1100. passed @code{0} as the number of bytes to write, it should behave as
  1101. though an end-of-file was sent to the byte sink.
  1102. The other arguments are as for @code{make-custom-binary-input-port}.
  1103. @end deffn
  1104. @cindex custom binary input/output ports
  1105. @deffn {Scheme Procedure} make-custom-binary-input/output-port id read! write! get-position set-position! close
  1106. Return a new custom binary input/output port named @var{id} (a string).
  1107. The various arguments are the same as for The other arguments are as for
  1108. @code{make-custom-binary-input-port} and
  1109. @code{make-custom-binary-output-port}. If buffering is enabled on the
  1110. port, as is the case by default, input will be buffered in both
  1111. directions; @xref{Buffering}. If the @var{set-position!} function is
  1112. provided and not @code{#f}, then the port will also be marked as
  1113. random-access, causing the buffer to be flushed between reads and
  1114. writes.
  1115. @end deffn
  1116. @node Soft Ports
  1117. @subsubsection Soft Ports
  1118. @cindex Soft port
  1119. @cindex Port, soft
  1120. A @dfn{soft port} is a port based on a vector of procedures capable of
  1121. accepting or delivering characters. It allows emulation of I/O ports.
  1122. @deffn {Scheme Procedure} make-soft-port pv modes
  1123. Return a port capable of receiving or delivering characters as
  1124. specified by the @var{modes} string (@pxref{File Ports,
  1125. open-file}). @var{pv} must be a vector of length 5 or 6. Its
  1126. components are as follows:
  1127. @enumerate 0
  1128. @item
  1129. procedure accepting one character for output
  1130. @item
  1131. procedure accepting a string for output
  1132. @item
  1133. thunk for flushing output
  1134. @item
  1135. thunk for getting one character
  1136. @item
  1137. thunk for closing port (not by garbage collection)
  1138. @item
  1139. (if present and not @code{#f}) thunk for computing the number of
  1140. characters that can be read from the port without blocking.
  1141. @end enumerate
  1142. For an output-only port only elements 0, 1, 2, and 4 need be
  1143. procedures. For an input-only port only elements 3 and 4 need
  1144. be procedures. Thunks 2 and 4 can instead be @code{#f} if
  1145. there is no useful operation for them to perform.
  1146. If thunk 3 returns @code{#f} or an @code{eof-object}
  1147. (@pxref{Input, eof-object?, ,r5rs, The Revised^5 Report on
  1148. Scheme}) it indicates that the port has reached end-of-file.
  1149. For example:
  1150. @lisp
  1151. (define stdout (current-output-port))
  1152. (define p (make-soft-port
  1153. (vector
  1154. (lambda (c) (write c stdout))
  1155. (lambda (s) (display s stdout))
  1156. (lambda () (display "." stdout))
  1157. (lambda () (char-upcase (read-char)))
  1158. (lambda () (display "@@" stdout)))
  1159. "rw"))
  1160. (write p p) @result{} #<input-output: soft 8081e20>
  1161. @end lisp
  1162. @end deffn
  1163. @node Void Ports
  1164. @subsubsection Void Ports
  1165. @cindex Void port
  1166. @cindex Port, void
  1167. This kind of port causes any data to be discarded when written to, and
  1168. always returns the end-of-file object when read from.
  1169. @deffn {Scheme Procedure} %make-void-port mode
  1170. @deffnx {C Function} scm_sys_make_void_port (mode)
  1171. Create and return a new void port. A void port acts like
  1172. @file{/dev/null}. The @var{mode} argument
  1173. specifies the input/output modes for this port: see the
  1174. documentation for @code{open-file} in @ref{File Ports}.
  1175. @end deffn
  1176. @node Venerable Port Interfaces
  1177. @subsection Venerable Port Interfaces
  1178. Over the 25 years or so that Guile has been around, its port system has
  1179. evolved, adding many useful features. At the same time there have been
  1180. four major Scheme standards released in those 25 years, which also
  1181. evolve the common Scheme understanding of what a port interface should
  1182. be. Alas, it would be too much to ask for all of these evolutionary
  1183. branches to be consistent. Some of Guile's original interfaces don't
  1184. mesh with the later Scheme standards, and yet Guile can't just drop old
  1185. interfaces. Sadly as well, the R6RS and R7RS standards both part from a
  1186. base of R5RS, but end up in different and somewhat incompatible designs.
  1187. Guile's approach is to pick a set of port primitives that make sense
  1188. together. We document that set of primitives, design our internal
  1189. interfaces around them, and recommend them to users. As the R6RS I/O
  1190. system is the most capable standard that Scheme has yet produced in this
  1191. domain, we mostly recommend that; @code{(ice-9 binary-ports)} and
  1192. @code{(ice-9 textual-ports)} are wholly modelled on @code{(rnrs io
  1193. ports)}. Guile does not wholly copy R6RS, however; @xref{R6RS
  1194. Incompatibilities}.
  1195. At the same time, we have many venerable port interfaces, lore handed
  1196. down to us from our hacker ancestors. Most of these interfaces even
  1197. predate the expectation that Scheme should have modules, so they are
  1198. present in the default environment. In Guile we support them as well
  1199. and we have no plans to remove them, but again we don't recommend them
  1200. for new users.
  1201. @rnindex char-ready?
  1202. @deffn {Scheme Procedure} char-ready? [port]
  1203. Return @code{#t} if a character is ready on input @var{port}
  1204. and return @code{#f} otherwise. If @code{char-ready?} returns
  1205. @code{#t} then the next @code{read-char} operation on
  1206. @var{port} is guaranteed not to hang. If @var{port} is a file
  1207. port at end of file then @code{char-ready?} returns @code{#t}.
  1208. @code{char-ready?} exists to make it possible for a
  1209. program to accept characters from interactive ports without
  1210. getting stuck waiting for input. Any input editors associated
  1211. with such ports must make sure that characters whose existence
  1212. has been asserted by @code{char-ready?} cannot be rubbed out.
  1213. If @code{char-ready?} were to return @code{#f} at end of file,
  1214. a port at end of file would be indistinguishable from an
  1215. interactive port that has no ready characters.
  1216. Note that @code{char-ready?} only works reliably for terminals and
  1217. sockets with one-byte encodings. Under the hood it will return
  1218. @code{#t} if the port has any input buffered, or if the file descriptor
  1219. that backs the port polls as readable, indicating that Guile can fetch
  1220. more bytes from the kernel. However being able to fetch one byte
  1221. doesn't mean that a full character is available; @xref{Encoding}. Also,
  1222. on many systems it's possible for a file descriptor to poll as readable,
  1223. but then block when it comes time to read bytes. Note also that on
  1224. Linux kernels, all file ports backed by files always poll as readable.
  1225. For non-file ports, this procedure always returns @code{#t}, except for
  1226. soft ports, which have a @code{char-ready?} handler. @xref{Soft Ports}.
  1227. In short, this is a legacy procedure whose semantics are hard to
  1228. provide. However it is a useful check to see if any input is buffered.
  1229. @xref{Non-Blocking I/O}.
  1230. @end deffn
  1231. @rnindex read-char
  1232. @deffn {Scheme Procedure} read-char [port]
  1233. The same as @code{get-char}, except that @var{port} defaults to the
  1234. current input port. @xref{Textual I/O}.
  1235. @end deffn
  1236. @rnindex peek-char
  1237. @deffn {Scheme Procedure} peek-char [port]
  1238. The same as @code{lookahead-char}, except that @var{port} defaults to
  1239. the current input port. @xref{Textual I/O}.
  1240. @end deffn
  1241. @deffn {Scheme Procedure} unread-char cobj [port]
  1242. The same as @code{unget-char}, except that @var{port} defaults to the
  1243. current input port, and the arguments are swapped. @xref{Textual I/O}.
  1244. @end deffn
  1245. @deffn {Scheme Procedure} unread-string str port
  1246. @deffnx {C Function} scm_unread_string (str, port)
  1247. The same as @code{unget-string}, except that @var{port} defaults to the
  1248. current input port, and the arguments are swapped. @xref{Textual I/O}.
  1249. @end deffn
  1250. @rnindex newline
  1251. @deffn {Scheme Procedure} newline [port]
  1252. Send a newline to @var{port}. If @var{port} is omitted, send to the
  1253. current output port. Equivalent to @code{(put-char port #\newline)}.
  1254. @end deffn
  1255. @rnindex write-char
  1256. @deffn {Scheme Procedure} write-char chr [port]
  1257. The same as @code{put-char}, except that @var{port} defaults to the
  1258. current input port, and the arguments are swapped. @xref{Textual I/O}.
  1259. @end deffn
  1260. @node Using Ports from C
  1261. @subsection Using Ports from C
  1262. Guile's C interfaces provides some niceties for sending and receiving
  1263. bytes and characters in a way that works better with C.
  1264. @deftypefn {C Function} size_t scm_c_read (SCM port, void *buffer, size_t size)
  1265. Read up to @var{size} bytes from @var{port} and store them in
  1266. @var{buffer}. The return value is the number of bytes actually read,
  1267. which can be less than @var{size} if end-of-file has been reached.
  1268. Note that as this is a binary input procedure, this function does not
  1269. update @code{port-line} and @code{port-column} (@pxref{Textual I/O}).
  1270. @end deftypefn
  1271. @deftypefn {C Function} void scm_c_write (SCM port, const void *buffer, size_t size)
  1272. Write @var{size} bytes at @var{buffer} to @var{port}.
  1273. Note that as this is a binary output procedure, this function does not
  1274. update @code{port-line} and @code{port-column} (@pxref{Textual I/O}).
  1275. @end deftypefn
  1276. @deftypefn {C Function} size_t scm_c_read_bytes (SCM port, SCM bv, size_t start, size_t count)
  1277. @deftypefnx {C Function} void scm_c_write_bytes (SCM port, SCM bv, size_t start, size_t count)
  1278. Like @code{scm_c_read} and @code{scm_c_write}, but reading into or
  1279. writing from the bytevector @var{bv}. @var{count} indicates the byte
  1280. index at which to start in the bytevector, and the read or write will
  1281. continue for @var{count} bytes.
  1282. @end deftypefn
  1283. @deftypefn {C Function} void scm_unget_bytes (const unsigned char *buf, size_t len, SCM port)
  1284. @deftypefnx {C Function} void scm_unget_byte (int c, SCM port)
  1285. @deftypefnx {C Function} void scm_ungetc (scm_t_wchar c, SCM port)
  1286. Like @code{unget-bytevector}, @code{unget-byte}, and @code{unget-char},
  1287. respectively. @xref{Textual I/O}.
  1288. @end deftypefn
  1289. @deftypefn {C Function} void scm_c_put_latin1_chars (SCM port, const scm_t_uint8 *buf, size_t len)
  1290. @deftypefnx {C Function} void scm_c_put_utf32_chars (SCM port, const scm_t_uint32 *buf, size_t len);
  1291. Write a string to @var{port}. In the first case, the
  1292. @code{scm_t_uint8*} buffer is a string in the latin-1 encoding. In the
  1293. second, the @code{scm_t_uint32*} buffer is a string in the UTF-32
  1294. encoding. These routines will update the port's line and column.
  1295. @end deftypefn
  1296. @node I/O Extensions
  1297. @subsection Implementing New Port Types in C
  1298. This section describes how to implement a new port type in C. Although
  1299. ports support many operations, as a data structure they present an
  1300. opaque interface to the user. To the port implementor, you have two
  1301. pieces of information to work with: the port type, and the port's
  1302. ``stream''. The port type is an opaque pointer allocated when defining
  1303. your port type. It is your key into the port API, and it helps you
  1304. identify which ports are actually yours. The ``stream'' is a pointer
  1305. you control, and which you set when you create a port. Get a stream
  1306. from a port using the @code{SCM_STREAM} macro. Note that your port
  1307. methods are only ever called with ports of your type.
  1308. A port type is created by calling @code{scm_make_port_type}. Once you
  1309. have your port type, you can create ports with @code{scm_c_make_port},
  1310. or @code{scm_c_make_port_with_encoding}.
  1311. @deftypefun scm_t_port_type* scm_make_port_type (char *name, size_t (*read) (SCM port, SCM dst, size_t start, size_t count), size_t (*write) (SCM port, SCM src, size_t start, size_t count))
  1312. Define a new port type. The @var{name}, @var{read} and @var{write}
  1313. parameters are initial values for those port type fields, as described
  1314. below. The other fields are initialized with default values and can be
  1315. changed later.
  1316. @end deftypefun
  1317. @deftypefun SCM scm_c_make_port_with_encoding (scm_t_port_type *type, unsigned long mode_bits, SCM encoding, SCM conversion_strategy, scm_t_bits stream)
  1318. @deftypefunx SCM scm_c_make_port (scm_t_port_type *type, unsigned long mode_bits, scm_t_bits stream)
  1319. Make a port with the given @var{type}. The @var{stream} indicates the
  1320. private data associated with the port, which your port implementation
  1321. may later retrieve with @code{SCM_STREAM}. The mode bits should include
  1322. one or more of the flags @code{SCM_RDNG} or @code{SCM_WRTNG}, indicating
  1323. that the port is an input and/or an output port, respectively. The mode
  1324. bits may also include @code{SCM_BUF0} or @code{SCM_BUFLINE}, indicating
  1325. that the port should be unbuffered or line-buffered, respectively. The
  1326. default is that the port will be block-buffered. @xref{Buffering}.
  1327. As you would imagine, @var{encoding} and @var{conversion_strategy}
  1328. specify the port's initial textual encoding and conversion strategy.
  1329. Both are symbols. @code{scm_c_make_port} is the same as
  1330. @code{scm_c_make_port_with_encoding}, except it uses the default port
  1331. encoding and conversion strategy.
  1332. @end deftypefun
  1333. The port type has a number of associate procedures and properties which
  1334. collectively implement the port's behavior. Creating a new port type
  1335. mostly involves writing these procedures.
  1336. @table @code
  1337. @item name
  1338. A pointer to a NUL terminated string: the name of the port type. This
  1339. property is initialized via the first argument to
  1340. @code{scm_make_port_type}.
  1341. @item read
  1342. A port's @code{read} implementation fills read buffers. It should copy
  1343. bytes to the supplied bytevector @code{dst}, starting at offset
  1344. @code{start} and continuing for @code{count} bytes, returning the number
  1345. of bytes read.
  1346. @item write
  1347. A port's @code{write} implementation flushes write buffers to the
  1348. mutable store.
  1349. It should write out bytes from the supplied bytevector @code{src},
  1350. starting at offset @code{start} and continuing for @code{count} bytes,
  1351. and return the number of bytes that were written.
  1352. @item read_wait_fd
  1353. @itemx write_wait_fd
  1354. If a port's @code{read} or @code{write} function returns @code{(size_t)
  1355. -1}, that indicates that reading or writing would block. In that case
  1356. to preserve the illusion of a blocking read or write operation, Guile's
  1357. C port run-time will @code{poll} on the file descriptor returned by
  1358. either the port's @code{read_wait_fd} or @code{write_wait_fd} function.
  1359. Set using
  1360. @deftypefun void scm_set_port_read_wait_fd (scm_t_port_type *type, int (*wait_fd) (SCM port))
  1361. @deftypefunx void scm_set_port_write_wait_fd (scm_t_port_type *type, int (*wait_fd) (SCM port))
  1362. @end deftypefun
  1363. Only a port type which implements the @code{read_wait_fd} or
  1364. @code{write_wait_fd} port methods can usefully return @code{(size_t) -1}
  1365. from a read or write function. @xref{Non-Blocking I/O}, for more on
  1366. non-blocking I/O in Guile.
  1367. @item print
  1368. Called when @code{write} is called on the port, to print a port
  1369. description. For example, for a file port it may produce something
  1370. like: @code{#<input: /etc/passwd 3>}. Set using
  1371. @deftypefun void scm_set_port_print (scm_t_port_type *type, int (*print) (SCM port, SCM dest_port, scm_print_state *pstate))
  1372. The first argument @var{port} is the port being printed, the second
  1373. argument @var{dest_port} is where its description should go.
  1374. @end deftypefun
  1375. @item close
  1376. Called when the port is closed. It should free any resources used by
  1377. the port. Set using
  1378. @deftypefun void scm_set_port_close (scm_t_port_type *type, void (*close) (SCM port))
  1379. @end deftypefun
  1380. By default, ports that are garbage collected just go away without
  1381. closing. If your port type needs to release some external resource like
  1382. a file descriptor, or needs to make sure that its internal buffers are
  1383. flushed even if the port is collected while it was open, then mark the
  1384. port type as needing a close on GC.
  1385. @deftypefun void scm_set_port_needs_close_on_gc (scm_t_port_type *type, int needs_close_p)
  1386. @end deftypefun
  1387. @item seek
  1388. Set the current position of the port. Guile will flush read and/or
  1389. write buffers before seeking, as appropriate.
  1390. @deftypefun void scm_set_port_seek (scm_t_port_type *type, scm_t_off (*seek) (SCM port, scm_t_off offset, int whence))
  1391. @end deftypefun
  1392. @item truncate
  1393. Truncate the port data to be specified length. Guile will flush buffers
  1394. before hand, as appropriate. Set using
  1395. @deftypefun void scm_set_port_truncate (scm_t_port_type *type, void (*truncate) (SCM port, scm_t_off length))
  1396. @end deftypefun
  1397. @item random_access_p
  1398. Determine whether this port is a random-access port.
  1399. @cindex random access
  1400. Seeking on a random-access port with buffered input, or switching to
  1401. writing after reading, will cause the buffered input to be discarded and
  1402. Guile will seek the port back the buffered number of bytes. Likewise
  1403. seeking on a random-access port with buffered output, or switching to
  1404. reading after writing, will flush pending bytes with a call to the
  1405. @code{write} procedure. @xref{Buffering}.
  1406. Indicate to Guile that your port needs this behavior by returning a
  1407. nonzero value from your @code{random_access_p} function. The default
  1408. implementation of this function returns nonzero if the port type
  1409. supplies a seek implementation.
  1410. @deftypefun void scm_set_port_random_access_p (scm_t_port_type *type, int (*random_access_p) (SCM port));
  1411. @end deftypefun
  1412. @item get_natural_buffer_sizes
  1413. Guile will internally attach buffers to ports. An input port always has
  1414. a read buffer and an output port always has a write buffer.
  1415. @xref{Buffering}. A port buffer consists of a bytevector, along with
  1416. some cursors into that bytevector denoting where to get and put data.
  1417. Port implementations generally don't have to be concerned with
  1418. buffering: a port type's @code{read} or @code{write} function will
  1419. receive the buffer's bytevector as an argument, along with an offset and
  1420. a length into that bytevector, and should then either fill or empty that
  1421. bytevector. However in some cases, port implementations may be able to
  1422. provide an appropriate default buffer size to Guile.
  1423. @deftypefun void scm_set_port_get_natural_buffer_sizes @
  1424. (scm_t_port_type *type, void (*get_natural_buffer_sizes) (SCM, size_t *read_buf_size, size_t *write_buf_size))
  1425. Fill in @var{read_buf_size} and @var{write_buf_size} with an appropriate buffer size for this port, if one is known.
  1426. @end deftypefun
  1427. File ports implement a @code{get_natural_buffer_sizes} to let the
  1428. operating system inform Guile about the appropriate buffer sizes for the
  1429. particular file opened by the port.
  1430. @end table
  1431. Note that calls to all of these methods can proceed in parallel and
  1432. concurrently and from any thread up until the point that the port is
  1433. closed. The call to @code{close} will happen when no other method is
  1434. running, and no method will be called after the @code{close} method is
  1435. called. If your port implementation needs mutual exclusion to prevent
  1436. concurrency, it is responsible for locking appropriately.
  1437. @node Non-Blocking I/O
  1438. @subsection Non-Blocking I/O
  1439. Most ports in Guile are @dfn{blocking}: when you try to read a character
  1440. from a port, Guile will block on the read until a character is ready, or
  1441. end-of-stream is detected. Likewise whenever Guile goes to write
  1442. (possibly buffered) data to an output port, Guile will block until all
  1443. the data is written.
  1444. Interacting with ports in blocking mode is very convenient: you can
  1445. write straightforward, sequential algorithms whose code flow reflects
  1446. the flow of data. However, blocking I/O has two main limitations.
  1447. The first is that it's easy to get into a situation where code is
  1448. waiting on data. Time spent waiting on data when code could be doing
  1449. something else is wasteful and prevents your program from reaching its
  1450. peak throughput. If you implement a web server that sequentially
  1451. handles requests from clients, it's very easy for the server to end up
  1452. waiting on a client to finish its HTTP request, or waiting on it to
  1453. consume the response. The end result is that you are able to serve
  1454. fewer requests per second than you'd like to serve.
  1455. The second limitation is related: a blocking parser over user-controlled
  1456. input is a denial-of-service vulnerability. Indeed the so-called ``slow
  1457. loris'' attack of the early 2010s was just that: an attack on common web
  1458. servers that drip-fed HTTP requests, one character at a time. All it
  1459. took was a handful of slow loris connections to occupy an entire web
  1460. server.
  1461. In Guile we would like to preserve the ability to write straightforward
  1462. blocking networking processes of all kinds, but under the hood to allow
  1463. those processes to suspend their requests if they would block.
  1464. To do this, the first piece is to allow Guile ports to declare
  1465. themselves as being nonblocking. This is currently supported only for
  1466. file ports, which also includes sockets, terminals, or any other port
  1467. that is backed by a file descriptor. To do that, we use an arcane UNIX
  1468. incantation:
  1469. @example
  1470. (let ((flags (fcntl socket F_GETFL)))
  1471. (fcntl socket F_SETFL (logior O_NONBLOCK flags)))
  1472. @end example
  1473. Now the file descriptor is open in non-blocking mode. If Guile tries to
  1474. read or write from this file and the read or write returns a result
  1475. indicating that more data can only be had by doing a blocking read or
  1476. write, Guile will block by polling on the socket's @code{read-wait-fd}
  1477. or @code{write-wait-fd}, to preserve the illusion of a blocking read or
  1478. write. @xref{I/O Extensions} for more on those internal interfaces.
  1479. So far we have just reproduced the status quo: the file descriptor is
  1480. non-blocking, but the operations on the port do block. To go farther,
  1481. it would be nice if we could suspend the ``thread'' using delimited
  1482. continuations, and only resume the thread once the file descriptor is
  1483. readable or writable. (@xref{Prompts}).
  1484. But here we run into a difficulty. The ports code is implemented in C,
  1485. which means that although we can suspend the computation to some outer
  1486. prompt, we can't resume it because Guile can't resume delimited
  1487. continuations that capture the C stack.
  1488. To overcome this difficulty we have created a compatible but entirely
  1489. parallel implementation of port operations. To use this implementation,
  1490. do the following:
  1491. @example
  1492. (use-modules (ice-9 suspendable-ports))
  1493. (install-suspendable-ports!)
  1494. @end example
  1495. This will replace the core I/O primitives like @code{get-char} and
  1496. @code{put-bytevector} with new versions that are exactly the same as the
  1497. ones in the standard library, but with two differences. One is that
  1498. when a read or a write would block, the suspendable port operations call
  1499. out the value of the @code{current-read-waiter} or
  1500. @code{current-write-waiter} parameter, as appropriate.
  1501. @xref{Parameters}. The default read and write waiters do the same thing
  1502. that the C read and write waiters do, which is to poll. User code can
  1503. parameterize the waiters, though, enabling the computation to suspend
  1504. and allow the program to process other I/O operations. Because the new
  1505. suspendable ports implementation is written in Scheme, that suspended
  1506. computation can resume again later when it is able to make progress.
  1507. Success!
  1508. The other main difference is that because the new ports implementation
  1509. is written in Scheme, it is slower than C, currently by a factor of 3 or
  1510. 4, though it depends on many factors. For this reason we have to keep
  1511. the C implementations as the default ones. One day when Guile's
  1512. compiler is better, we can close this gap and have only one port
  1513. operation implementation again.
  1514. Note that Guile does not currently include an implementation of the
  1515. facility to suspend the current thread and schedule other threads in the
  1516. meantime. Before adding such a thing, we want to make sure that we're
  1517. providing the right primitives that can be used to build schedulers and
  1518. other user-space concurrency patterns, and that the patterns that we
  1519. settle on are the right patterns. In the meantime, have a look at 8sync
  1520. (@url{https://gnu.org/software/8sync}) for a prototype of an
  1521. asynchronous I/O and concurrency facility.
  1522. @deffn {Scheme Procedure} install-suspendable-ports!
  1523. Replace the core ports implementation with suspendable ports, as
  1524. described above. This will mutate the values of the bindings like
  1525. @code{get-char}, @code{put-u8}, and so on in place.
  1526. @end deffn
  1527. @deffn {Scheme Procedure} uninstall-suspendable-ports!
  1528. Restore the original core ports implementation, un-doing the effect of
  1529. @code{install-suspendable-ports!}.
  1530. @end deffn
  1531. @deffn {Scheme Parameter} current-read-waiter
  1532. @deffnx {Scheme Parameter} current-write-waiter
  1533. Parameters whose values are procedures of one argument, called when a
  1534. suspendable port operation would block on a port while reading or
  1535. writing, respectively. The default values of these parameters do a
  1536. blocking @code{poll} on the port's file descriptor. The procedures are
  1537. passed the port in question as their one argument.
  1538. @end deffn
  1539. @node BOM Handling
  1540. @subsection Handling of Unicode Byte Order Marks
  1541. @cindex BOM
  1542. @cindex byte order mark
  1543. This section documents the finer points of Guile's handling of Unicode
  1544. byte order marks (BOMs). A byte order mark (U+FEFF) is typically found
  1545. at the start of a UTF-16 or UTF-32 stream, to allow readers to reliably
  1546. determine the byte order. Occasionally, a BOM is found at the start of
  1547. a UTF-8 stream, but this is much less common and not generally
  1548. recommended.
  1549. Guile attempts to handle BOMs automatically, and in accordance with the
  1550. recommendations of the Unicode Standard, when the port encoding is set
  1551. to @code{UTF-8}, @code{UTF-16}, or @code{UTF-32}. In brief, Guile
  1552. automatically writes a BOM at the start of a UTF-16 or UTF-32 stream,
  1553. and automatically consumes one from the start of a UTF-8, UTF-16, or
  1554. UTF-32 stream.
  1555. As specified in the Unicode Standard, a BOM is only handled specially at
  1556. the start of a stream, and only if the port encoding is set to
  1557. @code{UTF-8}, @code{UTF-16} or @code{UTF-32}. If the port encoding is
  1558. set to @code{UTF-16BE}, @code{UTF-16LE}, @code{UTF-32BE}, or
  1559. @code{UTF-32LE}, then BOMs are @emph{not} handled specially, and none of
  1560. the special handling described in this section applies.
  1561. @itemize @bullet
  1562. @item
  1563. To ensure that Guile will properly detect the byte order of a UTF-16 or
  1564. UTF-32 stream, you must perform a textual read before any writes, seeks,
  1565. or binary I/O. Guile will not attempt to read a BOM unless a read is
  1566. explicitly requested at the start of the stream.
  1567. @item
  1568. If a textual write is performed before the first read, then an arbitrary
  1569. byte order will be chosen. Currently, big endian is the default on all
  1570. platforms, but that may change in the future. If you wish to explicitly
  1571. control the byte order of an output stream, set the port encoding to
  1572. @code{UTF-16BE}, @code{UTF-16LE}, @code{UTF-32BE}, or @code{UTF-32LE},
  1573. and explicitly write a BOM (@code{#\xFEFF}) if desired.
  1574. @item
  1575. If @code{set-port-encoding!} is called in the middle of a stream, Guile
  1576. treats this as a new logical ``start of stream'' for purposes of BOM
  1577. handling, and will forget about any BOMs that had previously been seen.
  1578. Therefore, it may choose a different byte order than had been used
  1579. previously. This is intended to support multiple logical text streams
  1580. embedded within a larger binary stream.
  1581. @item
  1582. Binary I/O operations are not guaranteed to update Guile's notion of
  1583. whether the port is at the ``start of the stream'', nor are they
  1584. guaranteed to produce or consume BOMs.
  1585. @item
  1586. For ports that support seeking (e.g. normal files), the input and output
  1587. streams are considered linked: if the user reads first, then a BOM will
  1588. be consumed (if appropriate), but later writes will @emph{not} produce a
  1589. BOM. Similarly, if the user writes first, then later reads will
  1590. @emph{not} consume a BOM.
  1591. @item
  1592. For ports that are not random access (e.g. pipes, sockets, and
  1593. terminals), the input and output streams are considered
  1594. @emph{independent} for purposes of BOM handling: the first read will
  1595. consume a BOM (if appropriate), and the first write will @emph{also}
  1596. produce a BOM (if appropriate). However, the input and output streams
  1597. will always use the same byte order.
  1598. @item
  1599. Seeks to the beginning of a file will set the ``start of stream'' flags.
  1600. Therefore, a subsequent textual read or write will consume or produce a
  1601. BOM. However, unlike @code{set-port-encoding!}, if a byte order had
  1602. already been chosen for the port, it will remain in effect after a seek,
  1603. and cannot be changed by the presence of a BOM. Seeks anywhere other
  1604. than the beginning of a file clear the ``start of stream'' flags.
  1605. @end itemize
  1606. @c Local Variables:
  1607. @c TeX-master: "guile.texi"
  1608. @c End: