api-io.texi 82 KB

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