api-io.texi 80 KB

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