Print the faulty object upon invalid-keyword errors.
[bpt/guile.git] / libguile / ports.c
CommitLineData
e4598559
MW
1/* Copyright (C) 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2006,
2 * 2007, 2008, 2009, 2010, 2011, 2012, 2013 Free Software Foundation, Inc.
f4bc4e59 3 *
73be1d9e 4 * This library is free software; you can redistribute it and/or
53befeb7
NJ
5 * modify it under the terms of the GNU Lesser General Public License
6 * as published by the Free Software Foundation; either version 3 of
7 * the License, or (at your option) any later version.
0f2d19dd 8 *
53befeb7
NJ
9 * This library is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
73be1d9e
MV
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
0f2d19dd 13 *
73be1d9e
MV
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
53befeb7
NJ
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
17 * 02110-1301 USA
73be1d9e 18 */
1bbd0b84 19
1bbd0b84 20
0f2d19dd 21\f
d68fee48
JB
22/* Headers. */
23
2b829bbb
KR
24#define _LARGEFILE64_SOURCE /* ask for stat64 etc */
25
dbb605f5 26#ifdef HAVE_CONFIG_H
bd515f37
RB
27# include <config.h>
28#endif
29
0f2d19dd 30#include <stdio.h>
e6e2e95a 31#include <errno.h>
8ab3d8a0 32#include <fcntl.h> /* for chsize on mingw */
b5cb4464 33#include <assert.h>
f4bc4e59 34#include <iconv.h>
889975e5
MG
35#include <uniconv.h>
36#include <unistr.h>
37#include <striconveh.h>
96965a6e 38#include <c-strcase.h>
e6e2e95a 39
fca43887
LC
40#include <assert.h>
41
a0599745 42#include "libguile/_scm.h"
4e047c3e 43#include "libguile/async.h"
8269ba5b 44#include "libguile/deprecation.h"
f0942910 45#include "libguile/eval.h"
8ab3d8a0 46#include "libguile/fports.h" /* direct access for seek and truncate */
9511876f 47#include "libguile/goops.h"
a0599745
MD
48#include "libguile/smob.h"
49#include "libguile/chars.h"
185e369a 50#include "libguile/dynwind.h"
0f2d19dd 51
a0599745 52#include "libguile/keywords.h"
5dbc6c06 53#include "libguile/hashtab.h"
a0599745
MD
54#include "libguile/root.h"
55#include "libguile/strings.h"
b42170a4 56#include "libguile/mallocs.h"
a0599745
MD
57#include "libguile/validate.h"
58#include "libguile/ports.h"
e4598559 59#include "libguile/ports-internal.h"
3a5fb14d 60#include "libguile/vectors.h"
5dbc6c06 61#include "libguile/weaks.h"
9de87eea 62#include "libguile/fluids.h"
889975e5 63#include "libguile/eq.h"
0f2d19dd 64
bd9e24b3
GH
65#ifdef HAVE_STRING_H
66#include <string.h>
67#endif
68
ec65f5da
MV
69#ifdef HAVE_IO_H
70#include <io.h>
71#endif
72
0f2d19dd
JB
73#ifdef HAVE_UNISTD_H
74#include <unistd.h>
75#endif
76
95b88819
GH
77#ifdef HAVE_SYS_IOCTL_H
78#include <sys/ioctl.h>
79#endif
d68fee48 80
8ab3d8a0
KR
81/* Mingw (version 3.4.5, circa 2006) has ftruncate as an alias for chsize
82 already, but have this code here in case that wasn't so in past versions,
83 or perhaps to help other minimal DOS environments.
84
85 gnulib ftruncate.c has code using fcntl F_CHSIZE and F_FREESP, which
86 might be possibilities if we've got other systems without ftruncate. */
87
56a3dcd4 88#if defined HAVE_CHSIZE && ! defined HAVE_FTRUNCATE
82893676 89#define ftruncate(fd, size) chsize (fd, size)
8ab3d8a0
KR
90#undef HAVE_FTRUNCATE
91#define HAVE_FTRUNCATE 1
82893676
MG
92#endif
93
0f2d19dd 94\f
d68fee48 95/* The port kind table --- a dynamically resized array of port types. */
0f2d19dd
JB
96
97
98/* scm_ptobs scm_numptob
5dbc6c06 99 * implement a dynamically resized array of ptob records.
0f2d19dd
JB
100 * Indexes into this table are used when generating type
101 * tags for smobjects (if you know a tag you can get an index and conversely).
102 */
dd3a26f3
AW
103scm_t_ptob_descriptor *scm_ptobs = NULL;
104long scm_numptob = 0;
0f2d19dd 105
ee149d03 106/* GC marker for a port with stream of SCM type. */
0f2d19dd 107SCM
a284e297 108scm_markstream (SCM ptr)
0f2d19dd
JB
109{
110 int openp;
f9a64404 111 openp = SCM_CELL_WORD_0 (ptr) & SCM_OPN;
0f2d19dd 112 if (openp)
74a16888 113 return SCM_PACK (SCM_STREAM (ptr));
0f2d19dd
JB
114 else
115 return SCM_BOOL_F;
116}
117
f12733c9 118/*
f12733c9 119 * We choose to use an interface similar to the smob interface with
affc96b5 120 * fill_input and write as standard fields, passed to the port
f12733c9
MD
121 * type constructor, and optional fields set by setters.
122 */
123
70df8af6 124static void
e81d98ec 125flush_port_default (SCM port SCM_UNUSED)
70df8af6
GH
126{
127}
128
129static void
e81d98ec 130end_input_default (SCM port SCM_UNUSED, int offset SCM_UNUSED)
70df8af6
GH
131{
132}
0f2d19dd 133
92c2555f 134scm_t_bits
f12733c9 135scm_make_port_type (char *name,
affc96b5 136 int (*fill_input) (SCM port),
8aa011a1 137 void (*write) (SCM port, const void *data, size_t size))
0f2d19dd
JB
138{
139 char *tmp;
0953b549 140 if (SCM_I_MAX_PORT_TYPE_COUNT - 1 <= scm_numptob)
0f2d19dd 141 goto ptoberr;
9de87eea 142 SCM_CRITICAL_SECTION_START;
fca43887
LC
143 tmp = (char *) scm_gc_realloc ((char *) scm_ptobs,
144 scm_numptob * sizeof (scm_t_ptob_descriptor),
145 (1 + scm_numptob)
146 * sizeof (scm_t_ptob_descriptor),
147 "port-type");
0f2d19dd
JB
148 if (tmp)
149 {
92c2555f 150 scm_ptobs = (scm_t_ptob_descriptor *) tmp;
affc96b5 151
f12733c9
MD
152 scm_ptobs[scm_numptob].name = name;
153 scm_ptobs[scm_numptob].mark = 0;
3051344b 154 scm_ptobs[scm_numptob].free = NULL;
f12733c9
MD
155 scm_ptobs[scm_numptob].print = scm_port_print;
156 scm_ptobs[scm_numptob].equalp = 0;
affc96b5
GH
157 scm_ptobs[scm_numptob].close = 0;
158
159 scm_ptobs[scm_numptob].write = write;
70df8af6 160 scm_ptobs[scm_numptob].flush = flush_port_default;
affc96b5 161
70df8af6 162 scm_ptobs[scm_numptob].end_input = end_input_default;
affc96b5
GH
163 scm_ptobs[scm_numptob].fill_input = fill_input;
164 scm_ptobs[scm_numptob].input_waiting = 0;
165
f12733c9 166 scm_ptobs[scm_numptob].seek = 0;
affc96b5
GH
167 scm_ptobs[scm_numptob].truncate = 0;
168
0f2d19dd
JB
169 scm_numptob++;
170 }
9de87eea 171 SCM_CRITICAL_SECTION_END;
0f2d19dd 172 if (!tmp)
2500356c
DH
173 {
174 ptoberr:
175 scm_memory_error ("scm_make_port_type");
176 }
f12733c9 177 /* Make a class object if Goops is present */
63385df2 178 if (SCM_UNPACK (scm_port_class[0]) != 0)
f12733c9 179 scm_make_port_classes (scm_numptob - 1, SCM_PTOBNAME (scm_numptob - 1));
0f2d19dd
JB
180 return scm_tc7_port + (scm_numptob - 1) * 256;
181}
182
f12733c9 183void
23f2b9a3 184scm_set_port_mark (scm_t_bits tc, SCM (*mark) (SCM))
f12733c9
MD
185{
186 scm_ptobs[SCM_TC2PTOBNUM (tc)].mark = mark;
187}
188
189void
23f2b9a3 190scm_set_port_free (scm_t_bits tc, size_t (*free) (SCM))
f12733c9
MD
191{
192 scm_ptobs[SCM_TC2PTOBNUM (tc)].free = free;
193}
194
195void
23f2b9a3 196scm_set_port_print (scm_t_bits tc, int (*print) (SCM exp, SCM port,
f12733c9
MD
197 scm_print_state *pstate))
198{
199 scm_ptobs[SCM_TC2PTOBNUM (tc)].print = print;
200}
201
202void
23f2b9a3 203scm_set_port_equalp (scm_t_bits tc, SCM (*equalp) (SCM, SCM))
f12733c9
MD
204{
205 scm_ptobs[SCM_TC2PTOBNUM (tc)].equalp = equalp;
206}
207
31703ab8 208void
23f2b9a3 209scm_set_port_flush (scm_t_bits tc, void (*flush) (SCM port))
31703ab8 210{
affc96b5 211 scm_ptobs[SCM_TC2PTOBNUM (tc)].flush = flush;
31703ab8
GH
212}
213
f12733c9 214void
23f2b9a3 215scm_set_port_end_input (scm_t_bits tc, void (*end_input) (SCM port, int offset))
f12733c9 216{
affc96b5 217 scm_ptobs[SCM_TC2PTOBNUM (tc)].end_input = end_input;
f12733c9
MD
218}
219
220void
23f2b9a3 221scm_set_port_close (scm_t_bits tc, int (*close) (SCM))
f12733c9 222{
affc96b5 223 scm_ptobs[SCM_TC2PTOBNUM (tc)].close = close;
f12733c9
MD
224}
225
226void
f1ce9199
LC
227scm_set_port_seek (scm_t_bits tc,
228 scm_t_off (*seek) (SCM, scm_t_off, int))
f12733c9
MD
229{
230 scm_ptobs[SCM_TC2PTOBNUM (tc)].seek = seek;
231}
232
233void
f1ce9199 234scm_set_port_truncate (scm_t_bits tc, void (*truncate) (SCM, scm_t_off))
f12733c9 235{
affc96b5 236 scm_ptobs[SCM_TC2PTOBNUM (tc)].truncate = truncate;
f12733c9
MD
237}
238
239void
23f2b9a3 240scm_set_port_input_waiting (scm_t_bits tc, int (*input_waiting) (SCM))
f12733c9 241{
affc96b5 242 scm_ptobs[SCM_TC2PTOBNUM (tc)].input_waiting = input_waiting;
f12733c9
MD
243}
244
45c0878b
MW
245static void
246scm_i_set_pending_eof (SCM port)
247{
248 SCM_PORT_GET_INTERNAL (port)->pending_eof = 1;
249}
250
251static void
252scm_i_clear_pending_eof (SCM port)
253{
254 SCM_PORT_GET_INTERNAL (port)->pending_eof = 0;
255}
256
05d7f762
MW
257SCM
258scm_i_port_alist (SCM port)
259{
260 return SCM_PORT_GET_INTERNAL (port)->alist;
261}
262
263void
264scm_i_set_port_alist_x (SCM port, SCM alist)
265{
266 SCM_PORT_GET_INTERNAL (port)->alist = alist;
267}
268
0f2d19dd 269\f
0f2d19dd 270
3b3b36dd 271SCM_DEFINE (scm_char_ready_p, "char-ready?", 0, 1, 0,
1e6808ea
MG
272 (SCM port),
273 "Return @code{#t} if a character is ready on input @var{port}\n"
274 "and return @code{#f} otherwise. If @code{char-ready?} returns\n"
275 "@code{#t} then the next @code{read-char} operation on\n"
276 "@var{port} is guaranteed not to hang. If @var{port} is a file\n"
277 "port at end of file then @code{char-ready?} returns @code{#t}.\n"
c2dfff19
KR
278 "\n"
279 "@code{char-ready?} exists to make it possible for a\n"
1e6808ea
MG
280 "program to accept characters from interactive ports without\n"
281 "getting stuck waiting for input. Any input editors associated\n"
282 "with such ports must make sure that characters whose existence\n"
283 "has been asserted by @code{char-ready?} cannot be rubbed out.\n"
284 "If @code{char-ready?} were to return @code{#f} at end of file,\n"
285 "a port at end of file would be indistinguishable from an\n"
c2dfff19 286 "interactive port that has no ready characters.")
1bbd0b84 287#define FUNC_NAME s_scm_char_ready_p
0f2d19dd 288{
92c2555f 289 scm_t_port *pt;
6c951427 290
0f2d19dd 291 if (SCM_UNBNDP (port))
9de87eea 292 port = scm_current_input_port ();
b2456dd4
AW
293 /* It's possible to close the current input port, so validate even in
294 this case. */
295 SCM_VALIDATE_OPINPORT (1, port);
d68fee48 296
ae4c4016
JB
297 pt = SCM_PTAB_ENTRY (port);
298
6c951427
GH
299 /* if the current read buffer is filled, or the
300 last pushed-back char has been read and the saved buffer is
301 filled, result is true. */
302 if (pt->read_pos < pt->read_end
303 || (pt->read_buf == pt->putback_buf
304 && pt->saved_read_pos < pt->saved_read_end))
0f2d19dd 305 return SCM_BOOL_T;
ee149d03
JB
306 else
307 {
92c2555f 308 scm_t_ptob_descriptor *ptob = &scm_ptobs[SCM_PTOBNUM (port)];
ee149d03 309
affc96b5 310 if (ptob->input_waiting)
7888309b 311 return scm_from_bool(ptob->input_waiting (port));
ee149d03 312 else
6c951427 313 return SCM_BOOL_T;
ee149d03 314 }
0f2d19dd 315}
1bbd0b84 316#undef FUNC_NAME
0f2d19dd 317
e8b21eec
LC
318/* Move up to READ_LEN bytes from PORT's putback and/or read buffers
319 into memory starting at DEST. Return the number of bytes moved.
320 PORT's line/column numbers are left unchanged. */
321size_t
322scm_take_from_input_buffers (SCM port, char *dest, size_t read_len)
c2da2648 323{
92c2555f 324 scm_t_port *pt = SCM_PTAB_ENTRY (port);
e8b21eec 325 size_t bytes_read = 0;
c2da2648
GH
326 size_t from_buf = min (pt->read_end - pt->read_pos, read_len);
327
328 if (from_buf > 0)
329 {
330 memcpy (dest, pt->read_pos, from_buf);
331 pt->read_pos += from_buf;
e8b21eec 332 bytes_read += from_buf;
c2da2648
GH
333 read_len -= from_buf;
334 dest += from_buf;
335 }
336
337 /* if putback was active, try the real input buffer too. */
338 if (pt->read_buf == pt->putback_buf)
339 {
340 from_buf = min (pt->saved_read_end - pt->saved_read_pos, read_len);
341 if (from_buf > 0)
342 {
343 memcpy (dest, pt->saved_read_pos, from_buf);
344 pt->saved_read_pos += from_buf;
e8b21eec 345 bytes_read += from_buf;
c2da2648
GH
346 }
347 }
e8b21eec
LC
348
349 return bytes_read;
c2da2648
GH
350}
351
6c951427 352/* Clear a port's read buffers, returning the contents. */
a1ec6916 353SCM_DEFINE (scm_drain_input, "drain-input", 1, 0, 0,
1bbd0b84 354 (SCM port),
4a151b3d
GH
355 "This procedure clears a port's input buffers, similar\n"
356 "to the way that force-output clears the output buffer. The\n"
357 "contents of the buffers are returned as a single string, e.g.,\n"
358 "\n"
359 "@lisp\n"
360 "(define p (open-input-file ...))\n"
361 "(drain-input p) => empty string, nothing buffered yet.\n"
362 "(unread-char (read-char p) p)\n"
363 "(drain-input p) => initial chars from p, up to the buffer size.\n"
364 "@end lisp\n\n"
365 "Draining the buffers may be useful for cleanly finishing\n"
366 "buffered I/O so that the file descriptor can be used directly\n"
367 "for further input.")
1bbd0b84 368#define FUNC_NAME s_scm_drain_input
ee149d03 369{
840ae05d 370 SCM result;
3a5fb14d 371 char *data;
28a6e1b0 372 scm_t_port *pt;
c014a02e 373 long count;
ee149d03 374
34d19ef6 375 SCM_VALIDATE_OPINPORT (1, port);
28a6e1b0 376 pt = SCM_PTAB_ENTRY (port);
840ae05d 377
6c951427
GH
378 count = pt->read_end - pt->read_pos;
379 if (pt->read_buf == pt->putback_buf)
380 count += pt->saved_read_end - pt->saved_read_pos;
840ae05d 381
67a72dc1
AW
382 if (count)
383 {
190d4b0d 384 result = scm_i_make_string (count, &data, 0);
67a72dc1
AW
385 scm_take_from_input_buffers (port, data, count);
386 }
387 else
388 result = scm_nullstr;
389
840ae05d 390 return result;
ee149d03 391}
1bbd0b84 392#undef FUNC_NAME
0f2d19dd
JB
393
394\f
d68fee48 395/* Standard ports --- current input, output, error, and more(!). */
0f2d19dd 396
34297700
AW
397static SCM cur_inport_fluid = SCM_BOOL_F;
398static SCM cur_outport_fluid = SCM_BOOL_F;
399static SCM cur_errport_fluid = SCM_BOOL_F;
400static SCM cur_loadport_fluid = SCM_BOOL_F;
9de87eea 401
3b3b36dd 402SCM_DEFINE (scm_current_input_port, "current-input-port", 0, 0, 0,
e1546b65
MG
403 (),
404 "Return the current input port. This is the default port used\n"
405 "by many input procedures. Initially, @code{current-input-port}\n"
406 "returns the @dfn{standard input} in Unix and C terminology.")
1bbd0b84 407#define FUNC_NAME s_scm_current_input_port
0f2d19dd 408{
34297700 409 if (scm_is_true (cur_inport_fluid))
889975e5
MG
410 return scm_fluid_ref (cur_inport_fluid);
411 else
412 return SCM_BOOL_F;
0f2d19dd 413}
1bbd0b84 414#undef FUNC_NAME
0f2d19dd 415
3b3b36dd 416SCM_DEFINE (scm_current_output_port, "current-output-port", 0, 0, 0,
e1546b65
MG
417 (),
418 "Return the current output port. This is the default port used\n"
9401323e 419 "by many output procedures. Initially,\n"
e1546b65
MG
420 "@code{current-output-port} returns the @dfn{standard output} in\n"
421 "Unix and C terminology.")
1bbd0b84 422#define FUNC_NAME s_scm_current_output_port
0f2d19dd 423{
34297700 424 if (scm_is_true (cur_outport_fluid))
889975e5
MG
425 return scm_fluid_ref (cur_outport_fluid);
426 else
427 return SCM_BOOL_F;
0f2d19dd 428}
1bbd0b84 429#undef FUNC_NAME
0f2d19dd 430
3b3b36dd 431SCM_DEFINE (scm_current_error_port, "current-error-port", 0, 0, 0,
1bbd0b84 432 (),
b380b885
MD
433 "Return the port to which errors and warnings should be sent (the\n"
434 "@dfn{standard error} in Unix and C terminology).")
1bbd0b84 435#define FUNC_NAME s_scm_current_error_port
0f2d19dd 436{
34297700 437 if (scm_is_true (cur_errport_fluid))
889975e5
MG
438 return scm_fluid_ref (cur_errport_fluid);
439 else
440 return SCM_BOOL_F;
0f2d19dd 441}
1bbd0b84 442#undef FUNC_NAME
0f2d19dd 443
3972de76
AW
444SCM
445scm_current_warning_port (void)
446{
f57ea23a
MW
447 static SCM cwp_var = SCM_UNDEFINED;
448 static scm_i_pthread_mutex_t cwp_var_mutex
449 = SCM_I_PTHREAD_MUTEX_INITIALIZER;
450
451 scm_i_scm_pthread_mutex_lock (&cwp_var_mutex);
452 if (SCM_UNBNDP (cwp_var))
453 cwp_var = scm_c_private_variable ("guile", "current-warning-port");
454 scm_i_pthread_mutex_unlock (&cwp_var_mutex);
3972de76
AW
455
456 return scm_call_0 (scm_variable_ref (cwp_var));
457}
458
3b3b36dd 459SCM_DEFINE (scm_current_load_port, "current-load-port", 0, 0, 0,
e1546b65 460 (),
b450f070 461 "Return the current-load-port.\n"
e1546b65 462 "The load port is used internally by @code{primitive-load}.")
1bbd0b84 463#define FUNC_NAME s_scm_current_load_port
31614d8e 464{
9de87eea 465 return scm_fluid_ref (cur_loadport_fluid);
31614d8e 466}
1bbd0b84 467#undef FUNC_NAME
31614d8e 468
3b3b36dd 469SCM_DEFINE (scm_set_current_input_port, "set-current-input-port", 1, 0, 0,
1bbd0b84 470 (SCM port),
8f85c0c6
NJ
471 "@deffnx {Scheme Procedure} set-current-output-port port\n"
472 "@deffnx {Scheme Procedure} set-current-error-port port\n"
b380b885
MD
473 "Change the ports returned by @code{current-input-port},\n"
474 "@code{current-output-port} and @code{current-error-port}, respectively,\n"
475 "so that they use the supplied @var{port} for input or output.")
1bbd0b84 476#define FUNC_NAME s_scm_set_current_input_port
0f2d19dd 477{
9de87eea 478 SCM oinp = scm_fluid_ref (cur_inport_fluid);
34d19ef6 479 SCM_VALIDATE_OPINPORT (1, port);
9de87eea 480 scm_fluid_set_x (cur_inport_fluid, port);
0f2d19dd
JB
481 return oinp;
482}
1bbd0b84 483#undef FUNC_NAME
0f2d19dd
JB
484
485
3b3b36dd 486SCM_DEFINE (scm_set_current_output_port, "set-current-output-port", 1, 0, 0,
e1546b65
MG
487 (SCM port),
488 "Set the current default output port to @var{port}.")
1bbd0b84 489#define FUNC_NAME s_scm_set_current_output_port
0f2d19dd 490{
9de87eea 491 SCM ooutp = scm_fluid_ref (cur_outport_fluid);
78446828 492 port = SCM_COERCE_OUTPORT (port);
34d19ef6 493 SCM_VALIDATE_OPOUTPORT (1, port);
9de87eea 494 scm_fluid_set_x (cur_outport_fluid, port);
0f2d19dd
JB
495 return ooutp;
496}
1bbd0b84 497#undef FUNC_NAME
0f2d19dd
JB
498
499
3b3b36dd 500SCM_DEFINE (scm_set_current_error_port, "set-current-error-port", 1, 0, 0,
e1546b65
MG
501 (SCM port),
502 "Set the current default error port to @var{port}.")
1bbd0b84 503#define FUNC_NAME s_scm_set_current_error_port
0f2d19dd 504{
9de87eea 505 SCM oerrp = scm_fluid_ref (cur_errport_fluid);
78446828 506 port = SCM_COERCE_OUTPORT (port);
34d19ef6 507 SCM_VALIDATE_OPOUTPORT (1, port);
9de87eea 508 scm_fluid_set_x (cur_errport_fluid, port);
0f2d19dd
JB
509 return oerrp;
510}
1bbd0b84 511#undef FUNC_NAME
0f2d19dd 512
3972de76
AW
513
514SCM
515scm_set_current_warning_port (SCM port)
516{
517 static SCM cwp_var = SCM_BOOL_F;
518
519 if (scm_is_false (cwp_var))
520 cwp_var = scm_c_private_lookup ("guile", "current-warning-port");
521
522 return scm_call_1 (scm_variable_ref (cwp_var), port);
523}
524
525
185e369a 526void
661ae7ab 527scm_dynwind_current_input_port (SCM port)
9de87eea 528#define FUNC_NAME NULL
185e369a 529{
9de87eea 530 SCM_VALIDATE_OPINPORT (1, port);
661ae7ab 531 scm_dynwind_fluid (cur_inport_fluid, port);
185e369a 532}
9de87eea 533#undef FUNC_NAME
185e369a
MV
534
535void
661ae7ab 536scm_dynwind_current_output_port (SCM port)
9de87eea 537#define FUNC_NAME NULL
185e369a 538{
9de87eea
MV
539 port = SCM_COERCE_OUTPORT (port);
540 SCM_VALIDATE_OPOUTPORT (1, port);
661ae7ab 541 scm_dynwind_fluid (cur_outport_fluid, port);
185e369a 542}
9de87eea 543#undef FUNC_NAME
185e369a
MV
544
545void
661ae7ab 546scm_dynwind_current_error_port (SCM port)
9de87eea
MV
547#define FUNC_NAME NULL
548{
549 port = SCM_COERCE_OUTPORT (port);
550 SCM_VALIDATE_OPOUTPORT (1, port);
661ae7ab 551 scm_dynwind_fluid (cur_errport_fluid, port);
9de87eea
MV
552}
553#undef FUNC_NAME
554
555void
661ae7ab 556scm_i_dynwind_current_load_port (SCM port)
185e369a 557{
661ae7ab 558 scm_dynwind_fluid (cur_loadport_fluid, port);
185e369a
MV
559}
560
0f2d19dd 561\f
840ae05d 562/* The port table --- an array of pointers to ports. */
0f2d19dd 563
5dbc6c06
HWN
564/*
565 We need a global registry of ports to flush them all at exit, and to
05d7f762 566 get all the ports matching a file descriptor.
5dbc6c06
HWN
567 */
568SCM scm_i_port_weak_hash;
0f2d19dd 569
9de87eea 570scm_i_pthread_mutex_t scm_i_port_table_mutex = SCM_I_PTHREAD_MUTEX_INITIALIZER;
b9ad392e 571
651a0735
LC
572\f
573/* Port finalization. */
574
1cc91f1b 575
6922d92f 576static void finalize_port (void *, void *);
651a0735 577
f4bc4e59 578/* Register a finalizer for PORT. */
651a0735
LC
579static SCM_C_INLINE_KEYWORD void
580register_finalizer_for_port (SCM port)
581{
337edc59
MW
582 /* Register a finalizer for PORT so that its
583 type's `free' function gets called. */
75ba64d6 584 scm_i_set_finalizer (SCM2PTR (port), finalize_port, NULL);
651a0735
LC
585}
586
587/* Finalize the object (a port) pointed to by PTR. */
588static void
6922d92f 589finalize_port (void *ptr, void *data)
651a0735
LC
590{
591 long port_type;
592 SCM port = PTR2SCM (ptr);
593
594 if (!SCM_PORTP (port))
595 abort ();
596
597 if (SCM_OPENP (port))
598 {
599 if (SCM_REVEALED (port) > 0)
600 /* Keep "revealed" ports alive and re-register a finalizer. */
601 register_finalizer_for_port (port);
602 else
603 {
604 port_type = SCM_TC2PTOBNUM (SCM_CELL_TYPE (port));
605 if (port_type >= scm_numptob)
606 abort ();
607
608 if (scm_ptobs[port_type].free)
609 /* Yes, I really do mean `.free' rather than `.close'. `.close'
610 is for explicit `close-port' by user. */
611 scm_ptobs[port_type].free (port);
612
613 SCM_SETSTREAM (port, 0);
614 SCM_CLR_PORT_OPEN_FLAG (port);
651a0735
LC
615
616 scm_gc_ports_collected++;
617 }
618 }
619}
620
621
622
623\f
624
625/* This function is not and should not be thread safe. */
da220f27
HWN
626SCM
627scm_new_port_table_entry (scm_t_bits tag)
402788a9 628#define FUNC_NAME "scm_new_port_table_entry"
0f2d19dd 629{
85835e59
HWN
630 /*
631 We initialize the cell to empty, this is in case scm_gc_calloc
632 triggers GC ; we don't want the GC to scan a half-finished Z.
633 */
634
67329a9e 635 SCM z = scm_cons (SCM_EOL, SCM_EOL);
e4598559
MW
636 scm_t_port *entry = scm_gc_typed_calloc (scm_t_port);
637 scm_t_port_internal *pti = scm_gc_typed_calloc (scm_t_port_internal);
337edc59 638 const char *encoding;
5f16b897 639
840ae05d 640 entry->file_name = SCM_BOOL_F;
61e452ba 641 entry->rw_active = SCM_PORT_NEITHER;
5dbc6c06 642 entry->port = z;
9d9c66ba 643
889975e5
MG
644 /* Initialize this port with the thread's current default
645 encoding. */
337edc59 646 encoding = scm_i_default_port_encoding ();
b22e94db 647 entry->ilseq_handler = scm_i_default_port_conversion_handler ();
337edc59 648 entry->encoding = encoding ? scm_gc_strdup (encoding, "port") : NULL;
96965a6e 649 if (encoding && c_strcasecmp (encoding, "UTF-8") == 0)
337edc59
MW
650 pti->encoding_mode = SCM_PORT_ENCODING_MODE_UTF8;
651 else
652 pti->encoding_mode = SCM_PORT_ENCODING_MODE_ICONV;
653 pti->iconv_descriptors = NULL;
5f16b897 654
cdd3d6c9
MW
655 pti->at_stream_start_for_bom_read = 1;
656 pti->at_stream_start_for_bom_write = 1;
657
e4598559
MW
658 /* XXX These fields are not what they seem. They have been
659 repurposed, but cannot safely be renamed in 2.0 without breaking
660 ABI compatibility. This will be cleaned up in 2.2. */
661 entry->input_cd = pti; /* XXX pointer to the internal port structure */
662 entry->output_cd = NULL; /* XXX unused */
663
45c0878b 664 pti->pending_eof = 0;
05d7f762
MW
665 pti->alist = SCM_EOL;
666
5dbc6c06
HWN
667 SCM_SET_CELL_TYPE (z, tag);
668 SCM_SETPTAB_ENTRY (z, entry);
840ae05d 669
05d7f762 670 scm_hashq_set_x (scm_i_port_weak_hash, z, SCM_BOOL_F);
651a0735
LC
671
672 /* For each new port, register a finalizer so that it port type's free
673 function can be invoked eventually. */
674 register_finalizer_for_port (z);
675
da220f27 676 return z;
0f2d19dd 677}
c6c79933 678#undef FUNC_NAME
0f2d19dd 679
67329a9e 680#if SCM_ENABLE_DEPRECATED==1
8269ba5b 681scm_t_port *
67329a9e
HWN
682scm_add_to_port_table (SCM port)
683{
8269ba5b
AW
684 SCM z;
685 scm_t_port * pt;
67329a9e 686
8269ba5b
AW
687 scm_c_issue_deprecation_warning ("scm_add_to_port_table is deprecated.");
688
689 scm_i_pthread_mutex_lock (&scm_i_port_table_mutex);
690 z = scm_new_port_table_entry (scm_tc7_port);
691 pt = SCM_PTAB_ENTRY(z);
67329a9e 692 pt->port = port;
5dbc6c06
HWN
693 SCM_SETCAR (z, SCM_EOL);
694 SCM_SETCDR (z, SCM_EOL);
85835e59 695 SCM_SETPTAB_ENTRY (port, pt);
8269ba5b
AW
696 scm_i_pthread_mutex_unlock (&scm_i_port_table_mutex);
697
67329a9e
HWN
698 return pt;
699}
700#endif
701
702
6c951427 703/* Remove a port from the table and destroy it. */
b9ad392e 704
337edc59
MW
705static void close_iconv_descriptors (scm_t_iconv_descriptors *id);
706
8269ba5b 707static void
5dbc6c06
HWN
708scm_i_remove_port (SCM port)
709#define FUNC_NAME "scm_remove_port"
0f2d19dd 710{
8269ba5b 711 scm_t_port *p;
e4598559 712 scm_t_port_internal *pti;
682d78d0 713
8269ba5b 714 scm_i_scm_pthread_mutex_lock (&scm_i_port_table_mutex);
682d78d0 715
8269ba5b 716 p = SCM_PTAB_ENTRY (port);
e4598559 717 pti = SCM_PORT_GET_INTERNAL (port);
8269ba5b 718 scm_port_non_buffer (p);
682d78d0
LC
719 p->putback_buf = NULL;
720 p->putback_buf_size = 0;
3e05fc04 721
337edc59 722 if (pti->iconv_descriptors)
3e05fc04 723 {
337edc59
MW
724 close_iconv_descriptors (pti->iconv_descriptors);
725 pti->iconv_descriptors = NULL;
3e05fc04
AW
726 }
727
0f2d19dd 728 SCM_SETPTAB_ENTRY (port, 0);
8269ba5b 729
5dbc6c06 730 scm_hashq_remove_x (scm_i_port_weak_hash, port);
8269ba5b
AW
731
732 scm_i_pthread_mutex_unlock (&scm_i_port_table_mutex);
0f2d19dd 733}
db4b4ca6
DH
734#undef FUNC_NAME
735
0f2d19dd 736
b450f070 737/* Functions for debugging. */
5dbc6c06 738#ifdef GUILE_DEBUG
3b3b36dd 739SCM_DEFINE (scm_pt_size, "pt-size", 0, 0, 0,
b450f070 740 (),
1e6808ea 741 "Return the number of ports in the port table. @code{pt-size}\n"
5352393c 742 "is only included in @code{--enable-guile-debug} builds.")
1bbd0b84 743#define FUNC_NAME s_scm_pt_size
0f2d19dd 744{
5dbc6c06 745 return scm_from_int (SCM_HASHTABLE_N_ITEMS (scm_i_port_weak_hash));
0f2d19dd 746}
1bbd0b84 747#undef FUNC_NAME
0f2d19dd
JB
748#endif
749
70df8af6 750void
92c2555f 751scm_port_non_buffer (scm_t_port *pt)
70df8af6
GH
752{
753 pt->read_pos = pt->read_buf = pt->read_end = &pt->shortbuf;
754 pt->write_buf = pt->write_pos = &pt->shortbuf;
755 pt->read_buf_size = pt->write_buf_size = 1;
756 pt->write_end = pt->write_buf + pt->write_buf_size;
757}
0f2d19dd 758
d68fee48
JB
759\f
760/* Revealed counts --- an oddity inherited from SCSH. */
761
8b13c6b3
GH
762/* Find a port in the table and return its revealed count.
763 Also used by the garbage collector.
0f2d19dd 764 */
1cc91f1b 765
0f2d19dd 766int
a284e297 767scm_revealed_count (SCM port)
0f2d19dd
JB
768{
769 return SCM_REVEALED(port);
770}
771
772
773
774/* Return the revealed count for a port. */
775
3b3b36dd 776SCM_DEFINE (scm_port_revealed, "port-revealed", 1, 0, 0,
1bbd0b84 777 (SCM port),
1e6808ea 778 "Return the revealed count for @var{port}.")
1bbd0b84 779#define FUNC_NAME s_scm_port_revealed
0f2d19dd 780{
78446828 781 port = SCM_COERCE_OUTPORT (port);
34d19ef6 782 SCM_VALIDATE_OPENPORT (1, port);
e11e83f3 783 return scm_from_int (scm_revealed_count (port));
0f2d19dd 784}
1bbd0b84 785#undef FUNC_NAME
0f2d19dd
JB
786
787/* Set the revealed count for a port. */
3b3b36dd 788SCM_DEFINE (scm_set_port_revealed_x, "set-port-revealed!", 2, 0, 0,
1bbd0b84 789 (SCM port, SCM rcount),
b450f070 790 "Sets the revealed count for a port to a given value.\n"
b380b885 791 "The return value is unspecified.")
1bbd0b84 792#define FUNC_NAME s_scm_set_port_revealed_x
0f2d19dd 793{
78446828 794 port = SCM_COERCE_OUTPORT (port);
34d19ef6 795 SCM_VALIDATE_OPENPORT (1, port);
a55c2b68 796 SCM_REVEALED (port) = scm_to_int (rcount);
8b13c6b3 797 return SCM_UNSPECIFIED;
0f2d19dd 798}
1bbd0b84 799#undef FUNC_NAME
0f2d19dd 800
d68fee48
JB
801
802\f
803/* Retrieving a port's mode. */
804
eadd48de
GH
805/* Return the flags that characterize a port based on the mode
806 * string used to open a file for that port.
807 *
808 * See PORT FLAGS in scm.h
809 */
810
3a5fb14d 811static long
889975e5 812scm_i_mode_bits_n (SCM modes)
3a5fb14d
MV
813{
814 return (SCM_OPN
889975e5
MG
815 | (scm_i_string_contains_char (modes, 'r')
816 || scm_i_string_contains_char (modes, '+') ? SCM_RDNG : 0)
817 | (scm_i_string_contains_char (modes, 'w')
818 || scm_i_string_contains_char (modes, 'a')
819 || scm_i_string_contains_char (modes, '+') ? SCM_WRTNG : 0)
820 | (scm_i_string_contains_char (modes, '0') ? SCM_BUF0 : 0)
821 | (scm_i_string_contains_char (modes, 'l') ? SCM_BUFLINE : 0));
3a5fb14d
MV
822}
823
eadd48de 824long
a284e297 825scm_mode_bits (char *modes)
eadd48de 826{
889975e5 827 return scm_i_mode_bits (scm_from_locale_string (modes));
eadd48de
GH
828}
829
d617ee18
MV
830long
831scm_i_mode_bits (SCM modes)
832{
833 long bits;
834
835 if (!scm_is_string (modes))
836 scm_wrong_type_arg_msg (NULL, 0, modes, "string");
837
889975e5 838 bits = scm_i_mode_bits_n (modes);
d617ee18
MV
839 scm_remember_upto_here_1 (modes);
840 return bits;
841}
eadd48de
GH
842
843/* Return the mode flags from an open port.
844 * Some modes such as "append" are only used when opening
845 * a file and are not returned here. */
846
3b3b36dd 847SCM_DEFINE (scm_port_mode, "port-mode", 1, 0, 0,
1bbd0b84 848 (SCM port),
1e6808ea
MG
849 "Return the port modes associated with the open port @var{port}.\n"
850 "These will not necessarily be identical to the modes used when\n"
851 "the port was opened, since modes such as \"append\" which are\n"
852 "used only during port creation are not retained.")
1bbd0b84 853#define FUNC_NAME s_scm_port_mode
eadd48de 854{
26a3038d 855 char modes[4];
eadd48de 856 modes[0] = '\0';
78446828
MV
857
858 port = SCM_COERCE_OUTPORT (port);
34d19ef6 859 SCM_VALIDATE_OPPORT (1, port);
f9a64404
DH
860 if (SCM_CELL_WORD_0 (port) & SCM_RDNG) {
861 if (SCM_CELL_WORD_0 (port) & SCM_WRTNG)
eadd48de
GH
862 strcpy (modes, "r+");
863 else
864 strcpy (modes, "r");
865 }
f9a64404 866 else if (SCM_CELL_WORD_0 (port) & SCM_WRTNG)
eadd48de 867 strcpy (modes, "w");
f9a64404 868 if (SCM_CELL_WORD_0 (port) & SCM_BUF0)
eadd48de 869 strcat (modes, "0");
3a5fb14d 870 return scm_from_locale_string (modes);
eadd48de 871}
1bbd0b84 872#undef FUNC_NAME
eadd48de
GH
873
874
d68fee48
JB
875\f
876/* Closing ports. */
877
0f2d19dd
JB
878/* scm_close_port
879 * Call the close operation on a port object.
eadd48de 880 * see also scm_close.
0f2d19dd 881 */
3b3b36dd 882SCM_DEFINE (scm_close_port, "close-port", 1, 0, 0,
1bbd0b84 883 (SCM port),
1e6808ea
MG
884 "Close the specified port object. Return @code{#t} if it\n"
885 "successfully closes a port or @code{#f} if it was already\n"
886 "closed. An exception may be raised if an error occurs, for\n"
887 "example when flushing buffered output. See also @ref{Ports and\n"
888 "File Descriptors, close}, for a procedure which can close file\n"
889 "descriptors.")
1bbd0b84 890#define FUNC_NAME s_scm_close_port
0f2d19dd 891{
1be6b49c 892 size_t i;
eadd48de
GH
893 int rv;
894
78446828
MV
895 port = SCM_COERCE_OUTPORT (port);
896
7a754ca6 897 SCM_VALIDATE_PORT (1, port);
0f2d19dd 898 if (SCM_CLOSEDP (port))
eadd48de 899 return SCM_BOOL_F;
0f2d19dd 900 i = SCM_PTOBNUM (port);
affc96b5
GH
901 if (scm_ptobs[i].close)
902 rv = (scm_ptobs[i].close) (port);
eadd48de
GH
903 else
904 rv = 0;
5dbc6c06 905 scm_i_remove_port (port);
22a52da1 906 SCM_CLR_PORT_OPEN_FLAG (port);
7888309b 907 return scm_from_bool (rv >= 0);
7a754ca6
MD
908}
909#undef FUNC_NAME
910
911SCM_DEFINE (scm_close_input_port, "close-input-port", 1, 0, 0,
912 (SCM port),
913 "Close the specified input port object. The routine has no effect if\n"
914 "the file has already been closed. An exception may be raised if an\n"
915 "error occurs. The value returned is unspecified.\n\n"
916 "See also @ref{Ports and File Descriptors, close}, for a procedure\n"
917 "which can close file descriptors.")
918#define FUNC_NAME s_scm_close_input_port
919{
920 SCM_VALIDATE_INPUT_PORT (1, port);
921 scm_close_port (port);
922 return SCM_UNSPECIFIED;
923}
924#undef FUNC_NAME
925
926SCM_DEFINE (scm_close_output_port, "close-output-port", 1, 0, 0,
927 (SCM port),
928 "Close the specified output port object. The routine has no effect if\n"
929 "the file has already been closed. An exception may be raised if an\n"
930 "error occurs. The value returned is unspecified.\n\n"
931 "See also @ref{Ports and File Descriptors, close}, for a procedure\n"
932 "which can close file descriptors.")
933#define FUNC_NAME s_scm_close_output_port
934{
935 port = SCM_COERCE_OUTPORT (port);
936 SCM_VALIDATE_OUTPUT_PORT (1, port);
937 scm_close_port (port);
938 return SCM_UNSPECIFIED;
0f2d19dd 939}
1bbd0b84 940#undef FUNC_NAME
0f2d19dd 941
5dbc6c06 942static SCM
b7b4aef9 943collect_keys (void *unused, SCM key, SCM value, SCM result)
5dbc6c06 944{
b7b4aef9 945 return scm_cons (key, result);
5dbc6c06
HWN
946}
947
c536b4b3
MV
948void
949scm_c_port_for_each (void (*proc)(void *data, SCM p), void *data)
c2ca4493 950{
fdfe6305
MV
951 SCM ports;
952
b7b4aef9
AW
953 /* Copy out the port table as a list so that we get strong references
954 to all the values. */
5dbc6c06 955 scm_i_pthread_mutex_lock (&scm_i_port_table_mutex);
b7b4aef9
AW
956 ports = scm_internal_hash_fold (collect_keys, NULL,
957 SCM_EOL, scm_i_port_weak_hash);
9de87eea 958 scm_i_pthread_mutex_unlock (&scm_i_port_table_mutex);
3a5fb14d 959
b7b4aef9
AW
960 for (; scm_is_pair (ports); ports = scm_cdr (ports))
961 {
962 SCM p = scm_car (ports);
963 if (SCM_PORTP (p))
964 proc (data, p);
965 }
c536b4b3 966}
fdfe6305 967
c536b4b3
MV
968SCM_DEFINE (scm_port_for_each, "port-for-each", 1, 0, 0,
969 (SCM proc),
970 "Apply @var{proc} to each port in the Guile port table\n"
971 "in turn. The return value is unspecified. More specifically,\n"
972 "@var{proc} is applied exactly once to every port that exists\n"
b7e64f8b
BT
973 "in the system at the time @code{port-for-each} is invoked.\n"
974 "Changes to the port table while @code{port-for-each} is running\n"
975 "have no effect as far as @code{port-for-each} is concerned.")
c536b4b3
MV
976#define FUNC_NAME s_scm_port_for_each
977{
1b3daef0
AW
978 SCM ports;
979
c536b4b3
MV
980 SCM_VALIDATE_PROC (1, proc);
981
1b3daef0
AW
982 /* Copy out the port table as a list so that we get strong references
983 to all the values. */
984 scm_i_pthread_mutex_lock (&scm_i_port_table_mutex);
985 ports = scm_internal_hash_fold (collect_keys, NULL,
986 SCM_EOL, scm_i_port_weak_hash);
987 scm_i_pthread_mutex_unlock (&scm_i_port_table_mutex);
988
989 for (; scm_is_pair (ports); ports = scm_cdr (ports))
990 if (SCM_PORTP (SCM_CAR (ports)))
991 scm_call_1 (proc, SCM_CAR (ports));
992
c2ca4493
GH
993 return SCM_UNSPECIFIED;
994}
995#undef FUNC_NAME
996
c536b4b3 997
d68fee48
JB
998\f
999/* Utter miscellany. Gosh, we should clean this up some time. */
1000
3b3b36dd 1001SCM_DEFINE (scm_input_port_p, "input-port?", 1, 0, 0,
1bbd0b84 1002 (SCM x),
1e6808ea
MG
1003 "Return @code{#t} if @var{x} is an input port, otherwise return\n"
1004 "@code{#f}. Any object satisfying this predicate also satisfies\n"
1005 "@code{port?}.")
1bbd0b84 1006#define FUNC_NAME s_scm_input_port_p
0f2d19dd 1007{
7888309b 1008 return scm_from_bool (SCM_INPUT_PORT_P (x));
0f2d19dd 1009}
1bbd0b84 1010#undef FUNC_NAME
0f2d19dd 1011
3b3b36dd 1012SCM_DEFINE (scm_output_port_p, "output-port?", 1, 0, 0,
1bbd0b84 1013 (SCM x),
1e6808ea
MG
1014 "Return @code{#t} if @var{x} is an output port, otherwise return\n"
1015 "@code{#f}. Any object satisfying this predicate also satisfies\n"
1016 "@code{port?}.")
1bbd0b84 1017#define FUNC_NAME s_scm_output_port_p
0f2d19dd 1018{
82893676 1019 x = SCM_COERCE_OUTPORT (x);
7888309b 1020 return scm_from_bool (SCM_OUTPUT_PORT_P (x));
0f2d19dd 1021}
1bbd0b84 1022#undef FUNC_NAME
0f2d19dd 1023
eb5c0a2a
GH
1024SCM_DEFINE (scm_port_p, "port?", 1, 0, 0,
1025 (SCM x),
1e6808ea 1026 "Return a boolean indicating whether @var{x} is a port.\n"
5352393c
MG
1027 "Equivalent to @code{(or (input-port? @var{x}) (output-port?\n"
1028 "@var{x}))}.")
eb5c0a2a
GH
1029#define FUNC_NAME s_scm_port_p
1030{
7888309b 1031 return scm_from_bool (SCM_PORTP (x));
eb5c0a2a
GH
1032}
1033#undef FUNC_NAME
1034
3b3b36dd 1035SCM_DEFINE (scm_port_closed_p, "port-closed?", 1, 0, 0,
1bbd0b84 1036 (SCM port),
1e6808ea
MG
1037 "Return @code{#t} if @var{port} is closed or @code{#f} if it is\n"
1038 "open.")
1bbd0b84 1039#define FUNC_NAME s_scm_port_closed_p
60d0643d 1040{
34d19ef6 1041 SCM_VALIDATE_PORT (1, port);
7888309b 1042 return scm_from_bool (!SCM_OPPORTP (port));
60d0643d 1043}
1bbd0b84 1044#undef FUNC_NAME
0f2d19dd 1045
3b3b36dd 1046SCM_DEFINE (scm_eof_object_p, "eof-object?", 1, 0, 0,
1bbd0b84 1047 (SCM x),
1e6808ea
MG
1048 "Return @code{#t} if @var{x} is an end-of-file object; otherwise\n"
1049 "return @code{#f}.")
1bbd0b84 1050#define FUNC_NAME s_scm_eof_object_p
0f2d19dd 1051{
7888309b 1052 return scm_from_bool(SCM_EOF_OBJECT_P (x));
0f2d19dd 1053}
1bbd0b84 1054#undef FUNC_NAME
0f2d19dd 1055
3b3b36dd 1056SCM_DEFINE (scm_force_output, "force-output", 0, 1, 0,
1bbd0b84 1057 (SCM port),
b380b885 1058 "Flush the specified output port, or the current output port if @var{port}\n"
9401323e 1059 "is omitted. The current output buffer contents are passed to the\n"
b380b885
MD
1060 "underlying port implementation (e.g., in the case of fports, the\n"
1061 "data will be written to the file and the output buffer will be cleared.)\n"
1062 "It has no effect on an unbuffered port.\n\n"
1063 "The return value is unspecified.")
1bbd0b84 1064#define FUNC_NAME s_scm_force_output
0f2d19dd
JB
1065{
1066 if (SCM_UNBNDP (port))
9de87eea 1067 port = scm_current_output_port ();
0f2d19dd 1068 else
78446828
MV
1069 {
1070 port = SCM_COERCE_OUTPORT (port);
34d19ef6 1071 SCM_VALIDATE_OPOUTPORT (1, port);
78446828 1072 }
affc96b5 1073 scm_flush (port);
ee149d03 1074 return SCM_UNSPECIFIED;
0f2d19dd 1075}
1bbd0b84 1076#undef FUNC_NAME
0f2d19dd 1077
5dbc6c06
HWN
1078
1079static void
61d3568b 1080flush_output_port (void *closure, SCM port)
5dbc6c06 1081{
5dbc6c06
HWN
1082 if (SCM_OPOUTPORTP (port))
1083 scm_flush (port);
1084}
1085
a1ec6916 1086SCM_DEFINE (scm_flush_all_ports, "flush-all-ports", 0, 0, 0,
1bbd0b84 1087 (),
b380b885
MD
1088 "Equivalent to calling @code{force-output} on\n"
1089 "all open output ports. The return value is unspecified.")
1bbd0b84 1090#define FUNC_NAME s_scm_flush_all_ports
89ea5b7c 1091{
5dbc6c06 1092 scm_c_port_for_each (&flush_output_port, NULL);
89ea5b7c
GH
1093 return SCM_UNSPECIFIED;
1094}
1bbd0b84 1095#undef FUNC_NAME
0f2d19dd 1096
3b3b36dd 1097SCM_DEFINE (scm_read_char, "read-char", 0, 1, 0,
1bbd0b84 1098 (SCM port),
1e6808ea
MG
1099 "Return the next character available from @var{port}, updating\n"
1100 "@var{port} to point to the following character. If no more\n"
c62da8f8
LC
1101 "characters are available, the end-of-file object is returned.\n"
1102 "\n"
1103 "When @var{port}'s data cannot be decoded according to its\n"
1104 "character encoding, a @code{decoding-error} is raised and\n"
1105 "@var{port} points past the erroneous byte sequence.\n")
1bbd0b84 1106#define FUNC_NAME s_scm_read_char
0f2d19dd 1107{
889975e5 1108 scm_t_wchar c;
0f2d19dd 1109 if (SCM_UNBNDP (port))
9de87eea 1110 port = scm_current_input_port ();
34d19ef6 1111 SCM_VALIDATE_OPINPORT (1, port);
b7f3516f 1112 c = scm_getc (port);
0f2d19dd
JB
1113 if (EOF == c)
1114 return SCM_EOF_VAL;
7866a09b 1115 return SCM_MAKE_CHAR (c);
0f2d19dd 1116}
1bbd0b84 1117#undef FUNC_NAME
0f2d19dd 1118
f4bc4e59
LC
1119/* Update the line and column number of PORT after consumption of C. */
1120static inline void
1121update_port_lf (scm_t_wchar c, SCM port)
1122{
1123 switch (c)
1124 {
1125 case '\a':
7b292a9d 1126 case EOF:
f4bc4e59
LC
1127 break;
1128 case '\b':
1129 SCM_DECCOL (port);
1130 break;
1131 case '\n':
1132 SCM_INCLINE (port);
1133 break;
1134 case '\r':
1135 SCM_ZEROCOL (port);
1136 break;
1137 case '\t':
1138 SCM_TABCOL (port);
1139 break;
1140 default:
1141 SCM_INCCOL (port);
1142 break;
1143 }
1144}
1145
889975e5
MG
1146#define SCM_MBCHAR_BUF_SIZE (4)
1147
f4bc4e59
LC
1148/* Convert the SIZE-byte UTF-8 sequence in UTF8_BUF to a codepoint.
1149 UTF8_BUF is assumed to contain a valid UTF-8 sequence. */
1150static scm_t_wchar
1151utf8_to_codepoint (const scm_t_uint8 *utf8_buf, size_t size)
1152{
1153 scm_t_wchar codepoint;
1154
1155 if (utf8_buf[0] <= 0x7f)
1156 {
1157 assert (size == 1);
1158 codepoint = utf8_buf[0];
1159 }
1160 else if ((utf8_buf[0] & 0xe0) == 0xc0)
1161 {
1162 assert (size == 2);
1163 codepoint = ((scm_t_wchar) utf8_buf[0] & 0x1f) << 6UL
1164 | (utf8_buf[1] & 0x3f);
1165 }
1166 else if ((utf8_buf[0] & 0xf0) == 0xe0)
1167 {
1168 assert (size == 3);
1169 codepoint = ((scm_t_wchar) utf8_buf[0] & 0x0f) << 12UL
1170 | ((scm_t_wchar) utf8_buf[1] & 0x3f) << 6UL
1171 | (utf8_buf[2] & 0x3f);
1172 }
1173 else
1174 {
1175 assert (size == 4);
1176 codepoint = ((scm_t_wchar) utf8_buf[0] & 0x07) << 18UL
1177 | ((scm_t_wchar) utf8_buf[1] & 0x3f) << 12UL
1178 | ((scm_t_wchar) utf8_buf[2] & 0x3f) << 6UL
1179 | (utf8_buf[3] & 0x3f);
1180 }
1181
1182 return codepoint;
1183}
1184
7b292a9d
LC
1185/* Read a UTF-8 sequence from PORT. On success, return 0 and set
1186 *CODEPOINT to the codepoint that was read, fill BUF with its UTF-8
1187 representation, and set *LEN to the length in bytes. Return
1188 `EILSEQ' on error. */
c62da8f8 1189static int
7b292a9d
LC
1190get_utf8_codepoint (SCM port, scm_t_wchar *codepoint,
1191 scm_t_uint8 buf[SCM_MBCHAR_BUF_SIZE], size_t *len)
889975e5 1192{
7b292a9d
LC
1193#define ASSERT_NOT_EOF(b) \
1194 if (SCM_UNLIKELY ((b) == EOF)) \
1195 goto invalid_seq
7be1705d
LC
1196#define CONSUME_PEEKED_BYTE() \
1197 pt->read_pos++
7b292a9d
LC
1198
1199 int byte;
7be1705d 1200 scm_t_port *pt;
7b292a9d
LC
1201
1202 *len = 0;
7be1705d 1203 pt = SCM_PTAB_ENTRY (port);
7b292a9d
LC
1204
1205 byte = scm_get_byte_or_eof (port);
1206 if (byte == EOF)
1207 {
1208 *codepoint = EOF;
1209 return 0;
1210 }
1211
1212 buf[0] = (scm_t_uint8) byte;
1213 *len = 1;
1214
1215 if (buf[0] <= 0x7f)
1216 /* 1-byte form. */
1217 *codepoint = buf[0];
1218 else if (buf[0] >= 0xc2 && buf[0] <= 0xdf)
1219 {
1220 /* 2-byte form. */
7be1705d 1221 byte = scm_peek_byte_or_eof (port);
7b292a9d
LC
1222 ASSERT_NOT_EOF (byte);
1223
7b292a9d
LC
1224 if (SCM_UNLIKELY ((byte & 0xc0) != 0x80))
1225 goto invalid_seq;
1226
7be1705d
LC
1227 CONSUME_PEEKED_BYTE ();
1228 buf[1] = (scm_t_uint8) byte;
1229 *len = 2;
1230
7b292a9d
LC
1231 *codepoint = ((scm_t_wchar) buf[0] & 0x1f) << 6UL
1232 | (buf[1] & 0x3f);
1233 }
1234 else if ((buf[0] & 0xf0) == 0xe0)
1235 {
1236 /* 3-byte form. */
7be1705d
LC
1237 byte = scm_peek_byte_or_eof (port);
1238 ASSERT_NOT_EOF (byte);
7b292a9d
LC
1239
1240 if (SCM_UNLIKELY ((byte & 0xc0) != 0x80
1241 || (buf[0] == 0xe0 && byte < 0xa0)
1242 || (buf[0] == 0xed && byte > 0x9f)))
7be1705d 1243 goto invalid_seq;
7b292a9d 1244
7be1705d
LC
1245 CONSUME_PEEKED_BYTE ();
1246 buf[1] = (scm_t_uint8) byte;
1247 *len = 2;
7b292a9d 1248
7be1705d 1249 byte = scm_peek_byte_or_eof (port);
7b292a9d
LC
1250 ASSERT_NOT_EOF (byte);
1251
7b292a9d
LC
1252 if (SCM_UNLIKELY ((byte & 0xc0) != 0x80))
1253 goto invalid_seq;
1254
7be1705d
LC
1255 CONSUME_PEEKED_BYTE ();
1256 buf[2] = (scm_t_uint8) byte;
1257 *len = 3;
1258
7b292a9d
LC
1259 *codepoint = ((scm_t_wchar) buf[0] & 0x0f) << 12UL
1260 | ((scm_t_wchar) buf[1] & 0x3f) << 6UL
1261 | (buf[2] & 0x3f);
1262 }
1263 else if (buf[0] >= 0xf0 && buf[0] <= 0xf4)
1264 {
1265 /* 4-byte form. */
7be1705d 1266 byte = scm_peek_byte_or_eof (port);
7b292a9d
LC
1267 ASSERT_NOT_EOF (byte);
1268
7b292a9d
LC
1269 if (SCM_UNLIKELY (((byte & 0xc0) != 0x80)
1270 || (buf[0] == 0xf0 && byte < 0x90)
1271 || (buf[0] == 0xf4 && byte > 0x8f)))
7be1705d 1272 goto invalid_seq;
7b292a9d 1273
7be1705d
LC
1274 CONSUME_PEEKED_BYTE ();
1275 buf[1] = (scm_t_uint8) byte;
1276 *len = 2;
1277
1278 byte = scm_peek_byte_or_eof (port);
7b292a9d
LC
1279 ASSERT_NOT_EOF (byte);
1280
7be1705d
LC
1281 if (SCM_UNLIKELY ((byte & 0xc0) != 0x80))
1282 goto invalid_seq;
1283
1284 CONSUME_PEEKED_BYTE ();
7b292a9d
LC
1285 buf[2] = (scm_t_uint8) byte;
1286 *len = 3;
1287
7be1705d 1288 byte = scm_peek_byte_or_eof (port);
7b292a9d
LC
1289 ASSERT_NOT_EOF (byte);
1290
7b292a9d
LC
1291 if (SCM_UNLIKELY ((byte & 0xc0) != 0x80))
1292 goto invalid_seq;
1293
7be1705d
LC
1294 CONSUME_PEEKED_BYTE ();
1295 buf[3] = (scm_t_uint8) byte;
1296 *len = 4;
1297
7b292a9d
LC
1298 *codepoint = ((scm_t_wchar) buf[0] & 0x07) << 18UL
1299 | ((scm_t_wchar) buf[1] & 0x3f) << 12UL
1300 | ((scm_t_wchar) buf[2] & 0x3f) << 6UL
1301 | (buf[3] & 0x3f);
1302 }
1303 else
1304 goto invalid_seq;
1305
1306 return 0;
1307
1308 invalid_seq:
7be1705d
LC
1309 /* Here we could choose the consume the faulty byte when it's not a
1310 valid starting byte, but it's not a requirement. What Section 3.9
1311 of Unicode 6.0.0 mandates, though, is to not consume a byte that
1312 would otherwise be a valid starting byte. */
1313
7b292a9d
LC
1314 return EILSEQ;
1315
7be1705d 1316#undef CONSUME_PEEKED_BYTE
7b292a9d
LC
1317#undef ASSERT_NOT_EOF
1318}
1319
1320/* Likewise, read a byte sequence from PORT, passing it through its
1321 input conversion descriptor. */
1322static int
1323get_iconv_codepoint (SCM port, scm_t_wchar *codepoint,
1324 char buf[SCM_MBCHAR_BUF_SIZE], size_t *len)
1325{
cdd3d6c9 1326 scm_t_iconv_descriptors *id;
f4bc4e59 1327 scm_t_uint8 utf8_buf[SCM_MBCHAR_BUF_SIZE];
1ee237d9 1328 size_t input_size = 0;
889975e5 1329
cdd3d6c9
MW
1330 id = scm_i_port_iconv_descriptors (port, SCM_PORT_READ);
1331
1ee237d9 1332 for (;;)
63479112 1333 {
1ee237d9
MW
1334 int byte_read;
1335 char *input, *output;
f4bc4e59 1336 size_t input_left, output_left, done;
889975e5 1337
f4bc4e59 1338 byte_read = scm_get_byte_or_eof (port);
1ee237d9 1339 if (SCM_UNLIKELY (byte_read == EOF))
889975e5 1340 {
1ee237d9
MW
1341 if (SCM_LIKELY (input_size == 0))
1342 {
1343 *codepoint = (scm_t_wchar) EOF;
1344 *len = input_size;
1345 return 0;
1346 }
1347 else
45c0878b
MW
1348 {
1349 /* EOF found in the middle of a multibyte character. */
1350 scm_i_set_pending_eof (port);
1351 return EILSEQ;
1352 }
889975e5
MG
1353 }
1354
1ee237d9 1355 buf[input_size++] = byte_read;
889975e5 1356
f4bc4e59 1357 input = buf;
1ee237d9
MW
1358 input_left = input_size;
1359 output = (char *) utf8_buf;
f4bc4e59 1360 output_left = sizeof (utf8_buf);
889975e5 1361
337edc59 1362 done = iconv (id->input_cd, &input, &input_left, &output, &output_left);
1ee237d9 1363
f4bc4e59 1364 if (done == (size_t) -1)
889975e5 1365 {
1ee237d9
MW
1366 int err = errno;
1367 if (SCM_LIKELY (err == EINVAL))
1368 /* The input byte sequence did not form a complete
1369 character. Read another byte and try again. */
1370 continue;
1371 else
1372 return err;
889975e5 1373 }
f4bc4e59 1374 else
1ee237d9
MW
1375 {
1376 size_t output_size = sizeof (utf8_buf) - output_left;
1377 if (SCM_LIKELY (output_size > 0))
1378 {
1379 /* iconv generated output. Convert the UTF8_BUF sequence
1380 to a Unicode code point. */
1381 *codepoint = utf8_to_codepoint (utf8_buf, output_size);
1382 *len = input_size;
1383 return 0;
1384 }
1385 else
1386 {
1387 /* iconv consumed some bytes without producing any output.
1388 Most likely this means that a Unicode byte-order mark
1389 (BOM) was consumed, which should not be included in the
1390 returned buf. Shift any remaining bytes to the beginning
1391 of buf, and continue the loop. */
1392 memmove (buf, input, input_left);
1393 input_size = input_left;
1394 continue;
1395 }
1396 }
7b292a9d 1397 }
7b292a9d 1398}
c62da8f8 1399
7b292a9d
LC
1400/* Read a codepoint from PORT and return it in *CODEPOINT. Fill BUF
1401 with the byte representation of the codepoint in PORT's encoding, and
1402 set *LEN to the length in bytes of that representation. Return 0 on
1403 success and an errno value on error. */
1404static int
1405get_codepoint (SCM port, scm_t_wchar *codepoint,
1406 char buf[SCM_MBCHAR_BUF_SIZE], size_t *len)
1407{
1408 int err;
1409 scm_t_port *pt = SCM_PTAB_ENTRY (port);
e4598559 1410 scm_t_port_internal *pti = SCM_PORT_GET_INTERNAL (port);
7b292a9d 1411
337edc59 1412 if (pti->encoding_mode == SCM_PORT_ENCODING_MODE_UTF8)
7b292a9d 1413 err = get_utf8_codepoint (port, codepoint, (scm_t_uint8 *) buf, len);
cc540d0b 1414 else
7b292a9d
LC
1415 err = get_iconv_codepoint (port, codepoint, buf, len);
1416
1417 if (SCM_LIKELY (err == 0))
cdd3d6c9
MW
1418 {
1419 if (SCM_UNLIKELY (pti->at_stream_start_for_bom_read))
1420 {
1421 /* Record that we're no longer at stream start. */
1422 pti->at_stream_start_for_bom_read = 0;
1423 if (pt->rw_random)
1424 pti->at_stream_start_for_bom_write = 0;
1425
1426 /* If we just read a BOM in an encoding that recognizes them,
1427 then silently consume it and read another code point. */
1428 if (SCM_UNLIKELY
1429 (*codepoint == SCM_UNICODE_BOM
1430 && (pti->encoding_mode == SCM_PORT_ENCODING_MODE_UTF8
96965a6e
MW
1431 || c_strcasecmp (pt->encoding, "UTF-16") == 0
1432 || c_strcasecmp (pt->encoding, "UTF-32") == 0)))
cdd3d6c9
MW
1433 return get_codepoint (port, codepoint, buf, len);
1434 }
1435 update_port_lf (*codepoint, port);
1436 }
7b292a9d 1437 else if (pt->ilseq_handler == SCM_ICONVEH_QUESTION_MARK)
a42d7971 1438 {
7b292a9d
LC
1439 *codepoint = '?';
1440 err = 0;
a42d7971
LC
1441 update_port_lf (*codepoint, port);
1442 }
889975e5 1443
c62da8f8 1444 return err;
889975e5
MG
1445}
1446
fd5eec2b
LC
1447/* Read a codepoint from PORT and return it. */
1448scm_t_wchar
1449scm_getc (SCM port)
c62da8f8 1450#define FUNC_NAME "scm_getc"
fd5eec2b 1451{
c62da8f8 1452 int err;
fd5eec2b 1453 size_t len;
c62da8f8 1454 scm_t_wchar codepoint;
fd5eec2b
LC
1455 char buf[SCM_MBCHAR_BUF_SIZE];
1456
c62da8f8
LC
1457 err = get_codepoint (port, &codepoint, buf, &len);
1458 if (SCM_UNLIKELY (err != 0))
1459 /* At this point PORT should point past the invalid encoding, as per
1460 R6RS-lib Section 8.2.4. */
1461 scm_decoding_error (FUNC_NAME, err, "input decoding error", port);
1462
1463 return codepoint;
fd5eec2b 1464}
c62da8f8 1465#undef FUNC_NAME
889975e5 1466
5c070ca7 1467/* this should only be called when the read buffer is empty. it
affc96b5 1468 tries to refill the read buffer. it returns the first char from
5c070ca7 1469 the port, which is either EOF or *(pt->read_pos). */
187fa0b9
MW
1470static int
1471scm_i_fill_input (SCM port)
6c951427 1472{
92c2555f 1473 scm_t_port *pt = SCM_PTAB_ENTRY (port);
45c0878b 1474 scm_t_port_internal *pti = SCM_PORT_GET_INTERNAL (port);
283a1a0e 1475
b5cb4464
NJ
1476 assert (pt->read_pos == pt->read_end);
1477
45c0878b
MW
1478 if (pti->pending_eof)
1479 {
1480 pti->pending_eof = 0;
1481 return EOF;
1482 }
1483
6c951427
GH
1484 if (pt->read_buf == pt->putback_buf)
1485 {
1486 /* finished reading put-back chars. */
1487 pt->read_buf = pt->saved_read_buf;
1488 pt->read_pos = pt->saved_read_pos;
1489 pt->read_end = pt->saved_read_end;
1490 pt->read_buf_size = pt->saved_read_buf_size;
1491 if (pt->read_pos < pt->read_end)
5c070ca7 1492 return *(pt->read_pos);
6c951427 1493 }
affc96b5 1494 return scm_ptobs[SCM_PTOBNUM (port)].fill_input (port);
6c951427
GH
1495}
1496
187fa0b9
MW
1497int
1498scm_fill_input (SCM port)
1499{
1500 return scm_i_fill_input (port);
1501}
1502
8a2b5965
MW
1503/* Slow-path fallback for 'scm_get_byte_or_eof' in inline.h */
1504int
e00793d7 1505scm_slow_get_byte_or_eof (SCM port)
8a2b5965
MW
1506{
1507 scm_t_port *pt = SCM_PTAB_ENTRY (port);
1508
1509 if (pt->rw_active == SCM_PORT_WRITE)
1510 scm_flush (port);
1511
1512 if (pt->rw_random)
1513 pt->rw_active = SCM_PORT_READ;
1514
1515 if (pt->read_pos >= pt->read_end)
1516 {
1517 if (SCM_UNLIKELY (scm_i_fill_input (port) == EOF))
1518 return EOF;
1519 }
1520
1521 return *pt->read_pos++;
1522}
1523
1524/* Slow-path fallback for 'scm_peek_byte_or_eof' in inline.h */
1525int
e00793d7 1526scm_slow_peek_byte_or_eof (SCM port)
8a2b5965
MW
1527{
1528 scm_t_port *pt = SCM_PTAB_ENTRY (port);
1529
1530 if (pt->rw_active == SCM_PORT_WRITE)
1531 scm_flush (port);
1532
1533 if (pt->rw_random)
1534 pt->rw_active = SCM_PORT_READ;
1535
1536 if (pt->read_pos >= pt->read_end)
1537 {
1538 if (SCM_UNLIKELY (scm_i_fill_input (port) == EOF))
45c0878b
MW
1539 {
1540 scm_i_set_pending_eof (port);
1541 return EOF;
1542 }
8a2b5965
MW
1543 }
1544
1545 return *pt->read_pos;
1546}
1547
3cb988bd 1548
6fe692e9
MD
1549/* scm_lfwrite
1550 *
53802ea8
MV
1551 * This function differs from scm_c_write; it updates port line and
1552 * column. */
6fe692e9 1553
9c44cd45 1554void
1be6b49c 1555scm_lfwrite (const char *ptr, size_t size, SCM port)
ee149d03 1556{
92c2555f
MV
1557 scm_t_port *pt = SCM_PTAB_ENTRY (port);
1558 scm_t_ptob_descriptor *ptob = &scm_ptobs[SCM_PTOBNUM (port)];
3e2043c4 1559
840ae05d 1560 if (pt->rw_active == SCM_PORT_READ)
affc96b5 1561 scm_end_input (port);
283a1a0e 1562
31703ab8 1563 ptob->write (port, ptr, size);
840ae05d 1564
9c44cd45
MG
1565 for (; size; ptr++, size--)
1566 update_port_lf ((scm_t_wchar) (unsigned char) *ptr, port);
1567
1568 if (pt->rw_random)
1569 pt->rw_active = SCM_PORT_WRITE;
1570}
1571
4325620f 1572/* Write STR to PORT from START inclusive to END exclusive. */
9c44cd45
MG
1573void
1574scm_lfwrite_substr (SCM str, size_t start, size_t end, SCM port)
1575{
9c44cd45 1576 scm_t_port *pt = SCM_PTAB_ENTRY (port);
9c44cd45
MG
1577
1578 if (pt->rw_active == SCM_PORT_READ)
1579 scm_end_input (port);
1580
4325620f
LC
1581 if (end == (size_t) -1)
1582 end = scm_i_string_length (str);
9c44cd45 1583
b908768a 1584 scm_i_display_substring (str, start, end, port);
53802ea8 1585
840ae05d
JB
1586 if (pt->rw_random)
1587 pt->rw_active = SCM_PORT_WRITE;
ee149d03 1588}
3cb988bd 1589
6fe692e9
MD
1590/* scm_c_read
1591 *
1592 * Used by an application to read arbitrary number of bytes from an
1593 * SCM port. Same semantics as libc read, except that scm_c_read only
1594 * returns less than SIZE bytes if at end-of-file.
1595 *
1596 * Warning: Doesn't update port line and column counts! */
1597
b5cb4464
NJ
1598/* This structure, and the following swap_buffer function, are used
1599 for temporarily swapping a port's own read buffer, and the buffer
1600 that the caller of scm_c_read provides. */
1601struct port_and_swap_buffer
1602{
1603 scm_t_port *pt;
1604 unsigned char *buffer;
1605 size_t size;
1606};
1607
1608static void
1609swap_buffer (void *data)
1610{
1611 struct port_and_swap_buffer *psb = (struct port_and_swap_buffer *) data;
1612 unsigned char *old_buf = psb->pt->read_buf;
1613 size_t old_size = psb->pt->read_buf_size;
1614
1615 /* Make the port use (buffer, size) from the struct. */
1616 psb->pt->read_pos = psb->pt->read_buf = psb->pt->read_end = psb->buffer;
1617 psb->pt->read_buf_size = psb->size;
1618
1619 /* Save the port's old (buffer, size) in the struct. */
1620 psb->buffer = old_buf;
1621 psb->size = old_size;
1622}
1623
1be6b49c
ML
1624size_t
1625scm_c_read (SCM port, void *buffer, size_t size)
693758d5 1626#define FUNC_NAME "scm_c_read"
6fe692e9 1627{
693758d5 1628 scm_t_port *pt;
1be6b49c 1629 size_t n_read = 0, n_available;
b5cb4464 1630 struct port_and_swap_buffer psb;
6fe692e9 1631
693758d5
LC
1632 SCM_VALIDATE_OPINPORT (1, port);
1633
1634 pt = SCM_PTAB_ENTRY (port);
6fe692e9
MD
1635 if (pt->rw_active == SCM_PORT_WRITE)
1636 scm_ptobs[SCM_PTOBNUM (port)].flush (port);
1637
1638 if (pt->rw_random)
1639 pt->rw_active = SCM_PORT_READ;
1640
b5cb4464
NJ
1641 /* Take bytes first from the port's read buffer. */
1642 if (pt->read_pos < pt->read_end)
6fe692e9 1643 {
b5cb4464 1644 n_available = min (size, pt->read_end - pt->read_pos);
6fe692e9 1645 memcpy (buffer, pt->read_pos, n_available);
910d1e40 1646 buffer = (char *) buffer + n_available;
6fe692e9
MD
1647 pt->read_pos += n_available;
1648 n_read += n_available;
6fe692e9 1649 size -= n_available;
6fe692e9
MD
1650 }
1651
b5cb4464
NJ
1652 /* Avoid the scm_dynwind_* costs if we now have enough data. */
1653 if (size == 0)
1654 return n_read;
1655
187fa0b9
MW
1656 /* Now we will call scm_i_fill_input repeatedly until we have read the
1657 requested number of bytes. (Note that a single scm_i_fill_input
b5cb4464 1658 call does not guarantee to fill the whole of the port's read
6d227556 1659 buffer.) */
75192345 1660 if (pt->read_buf_size <= 1 && pt->encoding == NULL)
b5cb4464 1661 {
6d227556
NJ
1662 /* The port that we are reading from is unbuffered - i.e. does
1663 not have its own persistent buffer - but we have a buffer,
1664 provided by our caller, that is the right size for the data
187fa0b9 1665 that is wanted. For the following scm_i_fill_input calls,
6d227556
NJ
1666 therefore, we use the buffer in hand as the port's read
1667 buffer.
1668
1669 We need to make sure that the port's normal (1 byte) buffer
187fa0b9 1670 is reinstated in case one of the scm_i_fill_input () calls
6d227556 1671 throws an exception; we use the scm_dynwind_* API to achieve
75192345
MG
1672 that.
1673
1674 A consequence of this optimization is that the fill_input
1675 functions can't unget characters. That'll push data to the
1676 pushback buffer instead of this psb buffer. */
1677#if SCM_DEBUG == 1
1678 unsigned char *pback = pt->putback_buf;
1679#endif
6d227556
NJ
1680 psb.pt = pt;
1681 psb.buffer = buffer;
1682 psb.size = size;
1683 scm_dynwind_begin (SCM_F_DYNWIND_REWINDABLE);
1684 scm_dynwind_rewind_handler (swap_buffer, &psb, SCM_F_WIND_EXPLICITLY);
1685 scm_dynwind_unwind_handler (swap_buffer, &psb, SCM_F_WIND_EXPLICITLY);
1686
187fa0b9 1687 /* Call scm_i_fill_input until we have all the bytes that we need,
6d227556 1688 or we hit EOF. */
187fa0b9 1689 while (pt->read_buf_size && (scm_i_fill_input (port) != EOF))
6d227556
NJ
1690 {
1691 pt->read_buf_size -= (pt->read_end - pt->read_pos);
1692 pt->read_pos = pt->read_buf = pt->read_end;
1693 }
75192345
MG
1694#if SCM_DEBUG == 1
1695 if (pback != pt->putback_buf
1696 || pt->read_buf - (unsigned char *) buffer < 0)
1697 scm_misc_error (FUNC_NAME,
1698 "scm_c_read must not call a fill function that pushes "
1699 "back characters onto an unbuffered port", SCM_EOL);
1700#endif
6d227556 1701 n_read += pt->read_buf - (unsigned char *) buffer;
75192345 1702
6d227556
NJ
1703 /* Reinstate the port's normal buffer. */
1704 scm_dynwind_end ();
1705 }
1706 else
1707 {
1708 /* The port has its own buffer. It is important that we use it,
1709 even if it happens to be smaller than our caller's buffer, so
1710 that a custom port implementation's entry points (in
1711 particular, fill_input) can rely on the buffer always being
1712 the same as they first set up. */
187fa0b9 1713 while (size && (scm_i_fill_input (port) != EOF))
6d227556
NJ
1714 {
1715 n_available = min (size, pt->read_end - pt->read_pos);
1716 memcpy (buffer, pt->read_pos, n_available);
1717 buffer = (char *) buffer + n_available;
1718 pt->read_pos += n_available;
1719 n_read += n_available;
1720 size -= n_available;
1721 }
1722 }
6fe692e9 1723
b5cb4464 1724 return n_read;
6fe692e9 1725}
693758d5 1726#undef FUNC_NAME
6fe692e9
MD
1727
1728/* scm_c_write
1729 *
1730 * Used by an application to write arbitrary number of bytes to an SCM
1731 * port. Similar semantics as libc write. However, unlike libc
1732 * write, scm_c_write writes the requested number of bytes and has no
1733 * return value.
1734 *
1735 * Warning: Doesn't update port line and column counts!
1736 */
1737
693758d5 1738void
1be6b49c 1739scm_c_write (SCM port, const void *ptr, size_t size)
693758d5 1740#define FUNC_NAME "scm_c_write"
6fe692e9 1741{
693758d5
LC
1742 scm_t_port *pt;
1743 scm_t_ptob_descriptor *ptob;
1744
1745 SCM_VALIDATE_OPOUTPORT (1, port);
1746
1747 pt = SCM_PTAB_ENTRY (port);
1748 ptob = &scm_ptobs[SCM_PTOBNUM (port)];
6fe692e9
MD
1749
1750 if (pt->rw_active == SCM_PORT_READ)
1751 scm_end_input (port);
1752
1753 ptob->write (port, ptr, size);
1754
1755 if (pt->rw_random)
1756 pt->rw_active = SCM_PORT_WRITE;
1757}
693758d5 1758#undef FUNC_NAME
3cb988bd 1759
fca43887 1760void
a284e297 1761scm_flush (SCM port)
ee149d03 1762{
c014a02e 1763 long i = SCM_PTOBNUM (port);
7f2a6c38 1764 assert (i >= 0);
affc96b5 1765 (scm_ptobs[i].flush) (port);
ee149d03
JB
1766}
1767
283a1a0e 1768void
a284e297 1769scm_end_input (SCM port)
283a1a0e 1770{
c014a02e 1771 long offset;
92c2555f 1772 scm_t_port *pt = SCM_PTAB_ENTRY (port);
283a1a0e 1773
45c0878b 1774 scm_i_clear_pending_eof (port);
283a1a0e
GH
1775 if (pt->read_buf == pt->putback_buf)
1776 {
1777 offset = pt->read_end - pt->read_pos;
1778 pt->read_buf = pt->saved_read_buf;
1779 pt->read_pos = pt->saved_read_pos;
1780 pt->read_end = pt->saved_read_end;
1781 pt->read_buf_size = pt->saved_read_buf_size;
1782 }
1783 else
1784 offset = 0;
1785
affc96b5 1786 scm_ptobs[SCM_PTOBNUM (port)].end_input (port, offset);
283a1a0e
GH
1787}
1788
ee149d03
JB
1789\f
1790
1791
7f6c3f8f
MW
1792static void
1793scm_i_unget_bytes (const unsigned char *buf, size_t len, SCM port)
1794#define FUNC_NAME "scm_unget_bytes"
ee149d03 1795{
92c2555f 1796 scm_t_port *pt = SCM_PTAB_ENTRY (port);
7f6c3f8f 1797 size_t old_len, new_len;
840ae05d 1798
45c0878b 1799 scm_i_clear_pending_eof (port);
6c951427 1800
7f6c3f8f 1801 if (pt->read_buf != pt->putback_buf)
6c951427
GH
1802 /* switch to the put-back buffer. */
1803 {
1804 if (pt->putback_buf == NULL)
1805 {
7f6c3f8f
MW
1806 pt->putback_buf_size = (len > SCM_INITIAL_PUTBACK_BUF_SIZE
1807 ? len : SCM_INITIAL_PUTBACK_BUF_SIZE);
c357d546 1808 pt->putback_buf
92d8fd32 1809 = (unsigned char *) scm_gc_malloc_pointerless
7f6c3f8f 1810 (pt->putback_buf_size, "putback buffer");
6c951427
GH
1811 }
1812
1813 pt->saved_read_buf = pt->read_buf;
1814 pt->saved_read_pos = pt->read_pos;
1815 pt->saved_read_end = pt->read_end;
1816 pt->saved_read_buf_size = pt->read_buf_size;
1817
7f6c3f8f
MW
1818 /* Put read_pos at the end of the buffer, so that ungets will not
1819 have to shift the buffer contents each time. */
1820 pt->read_buf = pt->putback_buf;
1821 pt->read_pos = pt->read_end = pt->putback_buf + pt->putback_buf_size;
6c951427
GH
1822 pt->read_buf_size = pt->putback_buf_size;
1823 }
1824
7f6c3f8f
MW
1825 old_len = pt->read_end - pt->read_pos;
1826 new_len = old_len + len;
1827
1828 if (new_len > pt->read_buf_size)
1829 /* The putback buffer needs to be enlarged. */
1830 {
1831 size_t new_buf_size;
1832 unsigned char *new_buf, *new_end, *new_pos;
1833
1834 new_buf_size = pt->read_buf_size * 2;
1835 if (new_buf_size < new_len)
1836 new_buf_size = new_len;
1837
1838 new_buf = (unsigned char *)
1839 scm_gc_malloc_pointerless (new_buf_size, "putback buffer");
1840
1841 /* Put the bytes at the end of the buffer, so that future
1842 ungets won't need to shift the buffer. */
1843 new_end = new_buf + new_buf_size;
1844 new_pos = new_end - old_len;
1845 memcpy (new_pos, pt->read_pos, old_len);
1846
1847 pt->read_buf = pt->putback_buf = new_buf;
1848 pt->read_pos = new_pos;
1849 pt->read_end = new_end;
1850 pt->read_buf_size = pt->putback_buf_size = new_buf_size;
1851 }
1852 else if (pt->read_buf + len < pt->read_pos)
1853 /* If needed, shift the existing buffer contents up.
1854 This should not happen unless some external code
1855 manipulates the putback buffer pointers. */
1856 {
1857 unsigned char *new_end = pt->read_buf + pt->read_buf_size;
1858 unsigned char *new_pos = new_end - old_len;
1859
1860 memmove (new_pos, pt->read_pos, old_len);
1861 pt->read_pos = new_pos;
1862 pt->read_end = new_end;
1863 }
1864
1865 /* Move read_pos back and copy the bytes there. */
1866 pt->read_pos -= len;
1867 memcpy (pt->read_buf + (pt->read_pos - pt->read_buf), buf, len);
1868
1869 if (pt->rw_active == SCM_PORT_WRITE)
1870 scm_flush (port);
ee149d03 1871
840ae05d
JB
1872 if (pt->rw_random)
1873 pt->rw_active = SCM_PORT_READ;
889975e5
MG
1874}
1875#undef FUNC_NAME
1876
7f6c3f8f
MW
1877void
1878scm_unget_bytes (const unsigned char *buf, size_t len, SCM port)
1879{
1880 scm_i_unget_bytes (buf, len, port);
1881}
1882
1883void
1884scm_unget_byte (int c, SCM port)
1885{
1886 unsigned char byte;
1887
1888 byte = c;
1889 scm_i_unget_bytes (&byte, 1, port);
1890}
1891
63479112 1892void
889975e5
MG
1893scm_ungetc (scm_t_wchar c, SCM port)
1894#define FUNC_NAME "scm_ungetc"
1895{
1896 scm_t_port *pt = SCM_PTAB_ENTRY (port);
63479112
LC
1897 char *result;
1898 char result_buf[10];
1899 const char *encoding;
889975e5 1900 size_t len;
889975e5 1901
63479112
LC
1902 if (pt->encoding != NULL)
1903 encoding = pt->encoding;
1904 else
1905 encoding = "ISO-8859-1";
1906
1907 len = sizeof (result_buf);
1908 result = u32_conv_to_encoding (encoding,
1909 (enum iconv_ilseq_handler) pt->ilseq_handler,
1910 (uint32_t *) &c, 1, NULL,
1911 result_buf, &len);
1912
1913 if (SCM_UNLIKELY (result == NULL || len == 0))
6851d3be
LC
1914 scm_encoding_error (FUNC_NAME, errno,
1915 "conversion to port encoding failed",
1916 SCM_BOOL_F, SCM_MAKE_CHAR (c));
63479112 1917
7f6c3f8f 1918 scm_i_unget_bytes ((unsigned char *) result, len, port);
63479112
LC
1919
1920 if (SCM_UNLIKELY (result != result_buf))
1921 free (result);
840ae05d 1922
ee149d03
JB
1923 if (c == '\n')
1924 {
1925 /* What should col be in this case?
1926 * We'll leave it at -1.
1927 */
1928 SCM_LINUM (port) -= 1;
1929 }
1930 else
1931 SCM_COL(port) -= 1;
1932}
c6c79933 1933#undef FUNC_NAME
ee149d03
JB
1934
1935
1936void
70d63753 1937scm_ungets (const char *s, int n, SCM port)
ee149d03
JB
1938{
1939 /* This is simple minded and inefficient, but unreading strings is
1940 * probably not a common operation, and remember that line and
1941 * column numbers have to be handled...
1942 *
1943 * Please feel free to write an optimized version!
1944 */
1945 while (n--)
1946 scm_ungetc (s[n], port);
1947}
1948
1949
3b3b36dd 1950SCM_DEFINE (scm_peek_char, "peek-char", 0, 1, 0,
1bbd0b84 1951 (SCM port),
1e6808ea
MG
1952 "Return the next character available from @var{port},\n"
1953 "@emph{without} updating @var{port} to point to the following\n"
1954 "character. If no more characters are available, the\n"
c2dfff19
KR
1955 "end-of-file object is returned.\n"
1956 "\n"
1957 "The value returned by\n"
1e6808ea
MG
1958 "a call to @code{peek-char} is the same as the value that would\n"
1959 "have been returned by a call to @code{read-char} on the same\n"
1960 "port. The only difference is that the very next call to\n"
1961 "@code{read-char} or @code{peek-char} on that @var{port} will\n"
1962 "return the value returned by the preceding call to\n"
1963 "@code{peek-char}. In particular, a call to @code{peek-char} on\n"
1964 "an interactive port will hang waiting for input whenever a call\n"
c62da8f8
LC
1965 "to @code{read-char} would have hung.\n"
1966 "\n"
1967 "As for @code{read-char}, a @code{decoding-error} may be raised\n"
1968 "if such a situation occurs. However, unlike with @code{read-char},\n"
1969 "@var{port} still points at the beginning of the erroneous byte\n"
1970 "sequence when the error is raised.\n")
1bbd0b84 1971#define FUNC_NAME s_scm_peek_char
ee149d03 1972{
c62da8f8 1973 int err;
fd5eec2b
LC
1974 SCM result;
1975 scm_t_wchar c;
1976 char bytes[SCM_MBCHAR_BUF_SIZE];
7f6c3f8f 1977 long column, line;
fd5eec2b
LC
1978 size_t len;
1979
ee149d03 1980 if (SCM_UNBNDP (port))
9de87eea 1981 port = scm_current_input_port ();
b2456dd4 1982 SCM_VALIDATE_OPINPORT (1, port);
fd5eec2b
LC
1983
1984 column = SCM_COL (port);
1985 line = SCM_LINUM (port);
1986
c62da8f8 1987 err = get_codepoint (port, &c, bytes, &len);
fd5eec2b 1988
7f6c3f8f 1989 scm_i_unget_bytes ((unsigned char *) bytes, len, port);
fd5eec2b 1990
c62da8f8
LC
1991 SCM_COL (port) = column;
1992 SCM_LINUM (port) = line;
fd5eec2b 1993
c62da8f8
LC
1994 if (SCM_UNLIKELY (err != 0))
1995 {
1996 scm_decoding_error (FUNC_NAME, err, "input decoding error", port);
1997
1998 /* Shouldn't happen since `catch' always aborts to prompt. */
1999 result = SCM_BOOL_F;
fd5eec2b 2000 }
c62da8f8 2001 else if (c == EOF)
45c0878b
MW
2002 {
2003 scm_i_set_pending_eof (port);
2004 result = SCM_EOF_VAL;
2005 }
c62da8f8
LC
2006 else
2007 result = SCM_MAKE_CHAR (c);
fd5eec2b
LC
2008
2009 return result;
3cb988bd 2010}
1bbd0b84 2011#undef FUNC_NAME
3cb988bd 2012
1be4270a 2013SCM_DEFINE (scm_unread_char, "unread-char", 1, 1, 0,
1bbd0b84 2014 (SCM cobj, SCM port),
b7e64f8b
BT
2015 "Place character @var{cobj} in @var{port} so that it will be\n"
2016 "read by the next read operation. If called multiple times, the\n"
2017 "unread characters will be read again in last-in first-out\n"
2018 "order. If @var{port} is not supplied, the current input port\n"
2019 "is used.")
1bbd0b84 2020#define FUNC_NAME s_scm_unread_char
0f2d19dd
JB
2021{
2022 int c;
2023
34d19ef6 2024 SCM_VALIDATE_CHAR (1, cobj);
0f2d19dd 2025 if (SCM_UNBNDP (port))
9de87eea 2026 port = scm_current_input_port ();
b2456dd4 2027 SCM_VALIDATE_OPINPORT (2, port);
0f2d19dd 2028
7866a09b 2029 c = SCM_CHAR (cobj);
0f2d19dd 2030
b7f3516f 2031 scm_ungetc (c, port);
0f2d19dd
JB
2032 return cobj;
2033}
1bbd0b84 2034#undef FUNC_NAME
0f2d19dd 2035
a1ec6916 2036SCM_DEFINE (scm_unread_string, "unread-string", 2, 0, 0,
1bbd0b84 2037 (SCM str, SCM port),
b380b885
MD
2038 "Place the string @var{str} in @var{port} so that its characters will be\n"
2039 "read in subsequent read operations. If called multiple times, the\n"
2040 "unread characters will be read again in last-in first-out order. If\n"
2041 "@var{port} is not supplied, the current-input-port is used.")
1bbd0b84 2042#define FUNC_NAME s_scm_unread_string
ee1e7e13 2043{
889975e5 2044 int n;
34d19ef6 2045 SCM_VALIDATE_STRING (1, str);
ee1e7e13 2046 if (SCM_UNBNDP (port))
9de87eea 2047 port = scm_current_input_port ();
b2456dd4 2048 SCM_VALIDATE_OPINPORT (2, port);
ee1e7e13 2049
889975e5
MG
2050 n = scm_i_string_length (str);
2051
2052 while (n--)
2053 scm_ungetc (scm_i_string_ref (str, n), port);
ee1e7e13
MD
2054
2055 return str;
2056}
1bbd0b84 2057#undef FUNC_NAME
ee1e7e13 2058
a1ec6916 2059SCM_DEFINE (scm_seek, "seek", 3, 0, 0,
1e6808ea 2060 (SCM fd_port, SCM offset, SCM whence),
b7e64f8b 2061 "Sets the current position of @var{fd_port} to the integer\n"
1e6808ea
MG
2062 "@var{offset}, which is interpreted according to the value of\n"
2063 "@var{whence}.\n"
2064 "\n"
2065 "One of the following variables should be supplied for\n"
2066 "@var{whence}:\n"
b380b885
MD
2067 "@defvar SEEK_SET\n"
2068 "Seek from the beginning of the file.\n"
2069 "@end defvar\n"
2070 "@defvar SEEK_CUR\n"
2071 "Seek from the current position.\n"
2072 "@end defvar\n"
2073 "@defvar SEEK_END\n"
2074 "Seek from the end of the file.\n"
1e6808ea 2075 "@end defvar\n"
b7e64f8b 2076 "If @var{fd_port} is a file descriptor, the underlying system\n"
1e6808ea
MG
2077 "call is @code{lseek}. @var{port} may be a string port.\n"
2078 "\n"
2079 "The value returned is the new position in the file. This means\n"
2080 "that the current position of a port can be obtained using:\n"
2081 "@lisp\n"
b380b885 2082 "(seek port 0 SEEK_CUR)\n"
1e6808ea 2083 "@end lisp")
1bbd0b84 2084#define FUNC_NAME s_scm_seek
840ae05d 2085{
840ae05d
JB
2086 int how;
2087
1e6808ea 2088 fd_port = SCM_COERCE_OUTPORT (fd_port);
840ae05d 2089
a55c2b68 2090 how = scm_to_int (whence);
840ae05d 2091 if (how != SEEK_SET && how != SEEK_CUR && how != SEEK_END)
1bbd0b84 2092 SCM_OUT_OF_RANGE (3, whence);
23f2b9a3 2093
0a94eb00 2094 if (SCM_OPPORTP (fd_port))
840ae05d 2095 {
cdd3d6c9 2096 scm_t_port_internal *pti = SCM_PORT_GET_INTERNAL (fd_port);
92c2555f 2097 scm_t_ptob_descriptor *ptob = scm_ptobs + SCM_PTOBNUM (fd_port);
f1ce9199
LC
2098 off_t_or_off64_t off = scm_to_off_t_or_off64_t (offset);
2099 off_t_or_off64_t rv;
840ae05d
JB
2100
2101 if (!ptob->seek)
1bbd0b84 2102 SCM_MISC_ERROR ("port is not seekable",
1e6808ea 2103 scm_cons (fd_port, SCM_EOL));
840ae05d 2104 else
cdd3d6c9
MW
2105 rv = ptob->seek (fd_port, off, how);
2106
2107 /* Set stream-start flags according to new position. */
2108 pti->at_stream_start_for_bom_read = (rv == 0);
2109 pti->at_stream_start_for_bom_write = (rv == 0);
2110
2111 scm_i_clear_pending_eof (fd_port);
2112
f1ce9199 2113 return scm_from_off_t_or_off64_t (rv);
840ae05d
JB
2114 }
2115 else /* file descriptor?. */
2116 {
23f2b9a3
KR
2117 off_t_or_off64_t off = scm_to_off_t_or_off64_t (offset);
2118 off_t_or_off64_t rv;
2119 rv = lseek_or_lseek64 (scm_to_int (fd_port), off, how);
840ae05d 2120 if (rv == -1)
1bbd0b84 2121 SCM_SYSERROR;
23f2b9a3 2122 return scm_from_off_t_or_off64_t (rv);
840ae05d 2123 }
840ae05d 2124}
1bbd0b84 2125#undef FUNC_NAME
840ae05d 2126
8ab3d8a0
KR
2127#ifndef O_BINARY
2128#define O_BINARY 0
2129#endif
2130
2131/* Mingw has ftruncate(), perhaps implemented above using chsize, but
2132 doesn't have the filename version truncate(), hence this code. */
2133#if HAVE_FTRUNCATE && ! HAVE_TRUNCATE
2134static int
2135truncate (const char *file, off_t length)
82893676 2136{
8ab3d8a0
KR
2137 int ret, fdes;
2138
2139 fdes = open (file, O_BINARY | O_WRONLY);
2140 if (fdes == -1)
2141 return -1;
2142
2143 ret = ftruncate (fdes, length);
2144 if (ret == -1)
82893676 2145 {
8ab3d8a0 2146 int save_errno = errno;
82893676 2147 close (fdes);
8ab3d8a0
KR
2148 errno = save_errno;
2149 return -1;
82893676 2150 }
8ab3d8a0
KR
2151
2152 return close (fdes);
82893676 2153}
8ab3d8a0 2154#endif /* HAVE_FTRUNCATE && ! HAVE_TRUNCATE */
82893676 2155
a1ec6916 2156SCM_DEFINE (scm_truncate_file, "truncate-file", 1, 1, 0,
1bbd0b84 2157 (SCM object, SCM length),
b7e64f8b
BT
2158 "Truncate file @var{object} to @var{length} bytes. @var{object}\n"
2159 "can be a filename string, a port object, or an integer file\n"
2160 "descriptor.\n"
8ab3d8a0
KR
2161 "The return value is unspecified.\n"
2162 "\n"
2163 "For a port or file descriptor @var{length} can be omitted, in\n"
2164 "which case the file is truncated at the current position (per\n"
2165 "@code{ftell} above).\n"
2166 "\n"
2167 "On most systems a file can be extended by giving a length\n"
2168 "greater than the current size, but this is not mandatory in the\n"
2169 "POSIX standard.")
1bbd0b84 2170#define FUNC_NAME s_scm_truncate_file
840ae05d 2171{
69bc9ff3 2172 int rv;
69bc9ff3 2173
2b829bbb
KR
2174 /* "object" can be a port, fdes or filename.
2175
2176 Negative "length" makes no sense, but it's left to truncate() or
2177 ftruncate() to give back an error for that (normally EINVAL).
2178 */
840ae05d 2179
840ae05d
JB
2180 if (SCM_UNBNDP (length))
2181 {
69bc9ff3 2182 /* must supply length if object is a filename. */
7f9994d9 2183 if (scm_is_string (object))
34d19ef6 2184 SCM_MISC_ERROR("must supply length if OBJECT is a filename", SCM_EOL);
69bc9ff3 2185
e11e83f3 2186 length = scm_seek (object, SCM_INUM0, scm_from_int (SEEK_CUR));
840ae05d 2187 }
3fe6190f 2188
69bc9ff3 2189 object = SCM_COERCE_OUTPORT (object);
e11e83f3 2190 if (scm_is_integer (object))
69bc9ff3 2191 {
23f2b9a3
KR
2192 off_t_or_off64_t c_length = scm_to_off_t_or_off64_t (length);
2193 SCM_SYSCALL (rv = ftruncate_or_ftruncate64 (scm_to_int (object),
2194 c_length));
69bc9ff3 2195 }
0c95b57d 2196 else if (SCM_OPOUTPORTP (object))
69bc9ff3 2197 {
f1ce9199 2198 off_t_or_off64_t c_length = scm_to_off_t_or_off64_t (length);
92c2555f
MV
2199 scm_t_port *pt = SCM_PTAB_ENTRY (object);
2200 scm_t_ptob_descriptor *ptob = scm_ptobs + SCM_PTOBNUM (object);
45c0878b 2201
affc96b5 2202 if (!ptob->truncate)
1bbd0b84 2203 SCM_MISC_ERROR ("port is not truncatable", SCM_EOL);
45c0878b
MW
2204
2205 scm_i_clear_pending_eof (object);
69bc9ff3 2206 if (pt->rw_active == SCM_PORT_READ)
affc96b5 2207 scm_end_input (object);
69bc9ff3 2208 else if (pt->rw_active == SCM_PORT_WRITE)
affc96b5 2209 ptob->flush (object);
45c0878b 2210
affc96b5 2211 ptob->truncate (object, c_length);
69bc9ff3
GH
2212 rv = 0;
2213 }
2214 else
2215 {
2b829bbb 2216 off_t_or_off64_t c_length = scm_to_off_t_or_off64_t (length);
7f9994d9
MV
2217 char *str = scm_to_locale_string (object);
2218 int eno;
2b829bbb 2219 SCM_SYSCALL (rv = truncate_or_truncate64 (str, c_length));
7f9994d9
MV
2220 eno = errno;
2221 free (str);
2222 errno = eno;
69bc9ff3
GH
2223 }
2224 if (rv == -1)
1bbd0b84 2225 SCM_SYSERROR;
840ae05d
JB
2226 return SCM_UNSPECIFIED;
2227}
1bbd0b84 2228#undef FUNC_NAME
840ae05d 2229
a1ec6916 2230SCM_DEFINE (scm_port_line, "port-line", 1, 0, 0,
1bbd0b84 2231 (SCM port),
a150979d
KR
2232 "Return the current line number for @var{port}.\n"
2233 "\n"
2234 "The first line of a file is 0. But you might want to add 1\n"
2235 "when printing line numbers, since starting from 1 is\n"
2236 "traditional in error messages, and likely to be more natural to\n"
2237 "non-programmers.")
1bbd0b84 2238#define FUNC_NAME s_scm_port_line
0f2d19dd 2239{
78446828 2240 port = SCM_COERCE_OUTPORT (port);
34d19ef6 2241 SCM_VALIDATE_OPENPORT (1, port);
651f2cd2 2242 return scm_from_long (SCM_LINUM (port));
0f2d19dd 2243}
1bbd0b84 2244#undef FUNC_NAME
0f2d19dd 2245
a1ec6916 2246SCM_DEFINE (scm_set_port_line_x, "set-port-line!", 2, 0, 0,
1bbd0b84 2247 (SCM port, SCM line),
a150979d
KR
2248 "Set the current line number for @var{port} to @var{line}. The\n"
2249 "first line of a file is 0.")
1bbd0b84 2250#define FUNC_NAME s_scm_set_port_line_x
d043d8c2 2251{
360fc44c 2252 port = SCM_COERCE_OUTPORT (port);
34d19ef6 2253 SCM_VALIDATE_OPENPORT (1, port);
651f2cd2 2254 SCM_PTAB_ENTRY (port)->line_number = scm_to_long (line);
564478fd 2255 return SCM_UNSPECIFIED;
d043d8c2 2256}
1bbd0b84 2257#undef FUNC_NAME
d043d8c2 2258
a1ec6916 2259SCM_DEFINE (scm_port_column, "port-column", 1, 0, 0,
1bbd0b84 2260 (SCM port),
a150979d
KR
2261 "Return the current column number of @var{port}.\n"
2262 "If the number is\n"
b380b885
MD
2263 "unknown, the result is #f. Otherwise, the result is a 0-origin integer\n"
2264 "- i.e. the first character of the first line is line 0, column 0.\n"
2265 "(However, when you display a file position, for example in an error\n"
650a1cf9 2266 "message, we recommend you add 1 to get 1-origin integers. This is\n"
b380b885
MD
2267 "because lines and column numbers traditionally start with 1, and that is\n"
2268 "what non-programmers will find most natural.)")
1bbd0b84 2269#define FUNC_NAME s_scm_port_column
0f2d19dd 2270{
78446828 2271 port = SCM_COERCE_OUTPORT (port);
34d19ef6 2272 SCM_VALIDATE_OPENPORT (1, port);
e11e83f3 2273 return scm_from_int (SCM_COL (port));
0f2d19dd 2274}
1bbd0b84 2275#undef FUNC_NAME
0f2d19dd 2276
a1ec6916 2277SCM_DEFINE (scm_set_port_column_x, "set-port-column!", 2, 0, 0,
1bbd0b84 2278 (SCM port, SCM column),
a150979d
KR
2279 "Set the current column of @var{port}. Before reading the first\n"
2280 "character on a line the column should be 0.")
1bbd0b84 2281#define FUNC_NAME s_scm_set_port_column_x
d043d8c2 2282{
360fc44c 2283 port = SCM_COERCE_OUTPORT (port);
34d19ef6 2284 SCM_VALIDATE_OPENPORT (1, port);
a55c2b68 2285 SCM_PTAB_ENTRY (port)->column_number = scm_to_int (column);
564478fd 2286 return SCM_UNSPECIFIED;
d043d8c2 2287}
1bbd0b84 2288#undef FUNC_NAME
d043d8c2 2289
a1ec6916 2290SCM_DEFINE (scm_port_filename, "port-filename", 1, 0, 0,
1bbd0b84 2291 (SCM port),
ac012a27
AW
2292 "Return the filename associated with @var{port}, or @code{#f}\n"
2293 "if no filename is associated with the port.")
1bbd0b84 2294#define FUNC_NAME s_scm_port_filename
0f2d19dd 2295{
78446828 2296 port = SCM_COERCE_OUTPORT (port);
34d19ef6 2297 SCM_VALIDATE_OPENPORT (1, port);
b24b5e13 2298 return SCM_FILENAME (port);
0f2d19dd 2299}
1bbd0b84 2300#undef FUNC_NAME
0f2d19dd 2301
a1ec6916 2302SCM_DEFINE (scm_set_port_filename_x, "set-port-filename!", 2, 0, 0,
1bbd0b84 2303 (SCM port, SCM filename),
b380b885
MD
2304 "Change the filename associated with @var{port}, using the current input\n"
2305 "port if none is specified. Note that this does not change the port's\n"
2306 "source of data, but only the value that is returned by\n"
2307 "@code{port-filename} and reported in diagnostic output.")
1bbd0b84 2308#define FUNC_NAME s_scm_set_port_filename_x
d14af9f2 2309{
360fc44c 2310 port = SCM_COERCE_OUTPORT (port);
34d19ef6 2311 SCM_VALIDATE_OPENPORT (1, port);
360fc44c 2312 /* We allow the user to set the filename to whatever he likes. */
b24b5e13
DH
2313 SCM_SET_FILENAME (port, filename);
2314 return SCM_UNSPECIFIED;
d14af9f2 2315}
1bbd0b84 2316#undef FUNC_NAME
d14af9f2 2317
d6a6989e
LC
2318/* A fluid specifying the default encoding for newly created ports. If it is
2319 a string, that is the encoding. If it is #f, it is in the "native"
2320 (Latin-1) encoding. */
2321SCM_VARIABLE (default_port_encoding_var, "%default-port-encoding");
2322
889975e5
MG
2323static int scm_port_encoding_init = 0;
2324
9d9c66ba
LC
2325/* Use ENCODING as the default encoding for future ports. */
2326void
2327scm_i_set_default_port_encoding (const char *encoding)
2328{
2329 if (!scm_port_encoding_init
2330 || !scm_is_fluid (SCM_VARIABLE_REF (default_port_encoding_var)))
2331 scm_misc_error (NULL, "tried to set port encoding fluid before it is initialized",
2332 SCM_EOL);
2333
2334 if (encoding == NULL
96965a6e
MW
2335 || c_strcasecmp (encoding, "ASCII") == 0
2336 || c_strcasecmp (encoding, "ANSI_X3.4-1968") == 0
2337 || c_strcasecmp (encoding, "ISO-8859-1") == 0)
9d9c66ba
LC
2338 scm_fluid_set_x (SCM_VARIABLE_REF (default_port_encoding_var), SCM_BOOL_F);
2339 else
2340 scm_fluid_set_x (SCM_VARIABLE_REF (default_port_encoding_var),
2341 scm_from_locale_string (encoding));
2342}
2343
2344/* Return the name of the default encoding for newly created ports; a
2345 return value of NULL means "ISO-8859-1". */
889975e5 2346const char *
9d9c66ba 2347scm_i_default_port_encoding (void)
889975e5 2348{
9d9c66ba
LC
2349 if (!scm_port_encoding_init)
2350 return NULL;
2351 else if (!scm_is_fluid (SCM_VARIABLE_REF (default_port_encoding_var)))
2352 return NULL;
2353 else
889975e5 2354 {
9d9c66ba
LC
2355 SCM encoding;
2356
2357 encoding = scm_fluid_ref (SCM_VARIABLE_REF (default_port_encoding_var));
2358 if (!scm_is_string (encoding))
889975e5
MG
2359 return NULL;
2360 else
9d9c66ba 2361 return scm_i_string_chars (encoding);
889975e5
MG
2362 }
2363}
2364
cdd3d6c9
MW
2365/* If the next LEN bytes from PORT are equal to those in BYTES, then
2366 return 1, else return 0. Leave the port position unchanged. */
2367static int
2368looking_at_bytes (SCM port, const unsigned char *bytes, int len)
2369{
2370 scm_t_port *pt = SCM_PTAB_ENTRY (port);
cdd3d6c9
MW
2371 int i = 0;
2372
2373 while (i < len && scm_peek_byte_or_eof (port) == bytes[i])
2374 {
2375 pt->read_pos++;
2376 i++;
2377 }
7f6c3f8f
MW
2378 scm_i_unget_bytes (bytes, i, port);
2379 return (i == len);
cdd3d6c9
MW
2380}
2381
2382static const unsigned char scm_utf8_bom[3] = {0xEF, 0xBB, 0xBF};
2383static const unsigned char scm_utf16be_bom[2] = {0xFE, 0xFF};
2384static const unsigned char scm_utf16le_bom[2] = {0xFF, 0xFE};
2385static const unsigned char scm_utf32be_bom[4] = {0x00, 0x00, 0xFE, 0xFF};
2386static const unsigned char scm_utf32le_bom[4] = {0xFF, 0xFE, 0x00, 0x00};
2387
2388/* Decide what byte order to use for a UTF-16 port. Return "UTF-16BE"
2389 or "UTF-16LE". MODE must be either SCM_PORT_READ or SCM_PORT_WRITE,
2390 and specifies which operation is about to be done. The MODE
2391 determines how we will decide the byte order. We deliberately avoid
2392 reading from the port unless the user is about to do so. If the user
2393 is about to read, then we look for a BOM, and if present, we use it
2394 to determine the byte order. Otherwise we choose big endian, as
2395 recommended by the Unicode Standard. Note that the BOM (if any) is
2396 not consumed here. */
2397static const char *
2398decide_utf16_encoding (SCM port, scm_t_port_rw_active mode)
2399{
2400 if (mode == SCM_PORT_READ
2401 && SCM_PORT_GET_INTERNAL (port)->at_stream_start_for_bom_read
2402 && looking_at_bytes (port, scm_utf16le_bom, sizeof scm_utf16le_bom))
2403 return "UTF-16LE";
2404 else
2405 return "UTF-16BE";
2406}
2407
2408/* Decide what byte order to use for a UTF-32 port. Return "UTF-32BE"
2409 or "UTF-32LE". See the comment above 'decide_utf16_encoding' for
2410 details. */
2411static const char *
2412decide_utf32_encoding (SCM port, scm_t_port_rw_active mode)
2413{
2414 if (mode == SCM_PORT_READ
2415 && SCM_PORT_GET_INTERNAL (port)->at_stream_start_for_bom_read
2416 && looking_at_bytes (port, scm_utf32le_bom, sizeof scm_utf32le_bom))
2417 return "UTF-32LE";
2418 else
2419 return "UTF-32BE";
2420}
2421
337edc59 2422static void
1fa89aaf 2423finalize_iconv_descriptors (void *ptr, void *data)
337edc59
MW
2424{
2425 close_iconv_descriptors (ptr);
2426}
2427
2428static scm_t_iconv_descriptors *
2429open_iconv_descriptors (const char *encoding, int reading, int writing)
2430{
2431 scm_t_iconv_descriptors *id;
2432 iconv_t input_cd, output_cd;
2433
2434 input_cd = (iconv_t) -1;
2435 output_cd = (iconv_t) -1;
2436 if (reading)
2437 {
2438 /* Open an input iconv conversion descriptor, from ENCODING
2439 to UTF-8. We choose UTF-8, not UTF-32, because iconv
2440 implementations can typically convert from anything to
2441 UTF-8, but not to UTF-32 (see
2442 <http://lists.gnu.org/archive/html/bug-libunistring/2010-09/msg00007.html>). */
2443
2444 /* Assume opening an iconv descriptor causes about 16 KB of
2445 allocation. */
2446 scm_gc_register_allocation (16 * 1024);
2447
2448 input_cd = iconv_open ("UTF-8", encoding);
2449 if (input_cd == (iconv_t) -1)
2450 goto invalid_encoding;
2451 }
2452
2453 if (writing)
2454 {
2455 /* Assume opening an iconv descriptor causes about 16 KB of
2456 allocation. */
2457 scm_gc_register_allocation (16 * 1024);
2458
2459 output_cd = iconv_open (encoding, "UTF-8");
2460 if (output_cd == (iconv_t) -1)
2461 {
2462 if (input_cd != (iconv_t) -1)
2463 iconv_close (input_cd);
2464 goto invalid_encoding;
2465 }
2466 }
2467
2468 id = scm_gc_malloc_pointerless (sizeof (*id), "iconv descriptors");
2469 id->input_cd = input_cd;
2470 id->output_cd = output_cd;
2471
2472 /* Register a finalizer to close the descriptors. */
2473 scm_i_set_finalizer (id, finalize_iconv_descriptors, NULL);
2474
2475 return id;
2476
2477 invalid_encoding:
2478 {
2479 SCM err;
2480 err = scm_from_locale_string (encoding);
2481 scm_misc_error ("open_iconv_descriptors",
2482 "invalid or unknown character encoding ~s",
2483 scm_list_1 (err));
2484 }
2485}
2486
2487static void
2488close_iconv_descriptors (scm_t_iconv_descriptors *id)
2489{
2490 if (id->input_cd != (iconv_t) -1)
2491 iconv_close (id->input_cd);
2492 if (id->output_cd != (iconv_t) -1)
2493 iconv_close (id->output_cd);
2494 id->input_cd = (void *) -1;
2495 id->output_cd = (void *) -1;
2496}
2497
cdd3d6c9
MW
2498/* Return the iconv_descriptors, initializing them if necessary. MODE
2499 must be either SCM_PORT_READ or SCM_PORT_WRITE, and specifies which
2500 operation is about to be done. We deliberately avoid reading from
2501 the port unless the user was about to do so. */
337edc59 2502scm_t_iconv_descriptors *
cdd3d6c9 2503scm_i_port_iconv_descriptors (SCM port, scm_t_port_rw_active mode)
337edc59 2504{
cdd3d6c9 2505 scm_t_port_internal *pti = SCM_PORT_GET_INTERNAL (port);
337edc59
MW
2506
2507 assert (pti->encoding_mode == SCM_PORT_ENCODING_MODE_ICONV);
2508
2509 if (!pti->iconv_descriptors)
2510 {
cdd3d6c9
MW
2511 scm_t_port *pt = SCM_PTAB_ENTRY (port);
2512 const char *precise_encoding;
2513
337edc59
MW
2514 if (!pt->encoding)
2515 pt->encoding = "ISO-8859-1";
cdd3d6c9
MW
2516
2517 /* If the specified encoding is UTF-16 or UTF-32, then make
2518 that more precise by deciding what byte order to use. */
96965a6e 2519 if (c_strcasecmp (pt->encoding, "UTF-16") == 0)
cdd3d6c9 2520 precise_encoding = decide_utf16_encoding (port, mode);
96965a6e 2521 else if (c_strcasecmp (pt->encoding, "UTF-32") == 0)
cdd3d6c9
MW
2522 precise_encoding = decide_utf32_encoding (port, mode);
2523 else
2524 precise_encoding = pt->encoding;
2525
337edc59 2526 pti->iconv_descriptors =
cdd3d6c9 2527 open_iconv_descriptors (precise_encoding,
337edc59
MW
2528 SCM_INPUT_PORT_P (port),
2529 SCM_OUTPUT_PORT_P (port));
2530 }
2531
2532 return pti->iconv_descriptors;
2533}
2534
889975e5 2535void
064c27c4 2536scm_i_set_port_encoding_x (SCM port, const char *encoding)
889975e5 2537{
889975e5 2538 scm_t_port *pt;
e4598559 2539 scm_t_port_internal *pti;
337edc59 2540 scm_t_iconv_descriptors *prev;
f4bc4e59 2541
9d9c66ba
LC
2542 /* Set the character encoding for this port. */
2543 pt = SCM_PTAB_ENTRY (port);
e4598559 2544 pti = SCM_PORT_GET_INTERNAL (port);
337edc59 2545 prev = pti->iconv_descriptors;
f4bc4e59 2546
cdd3d6c9
MW
2547 /* In order to handle cases where the encoding changes mid-stream
2548 (e.g. within an HTTP stream, or within a file that is composed of
2549 segments with different encodings), we consider this to be "stream
2550 start" for purposes of BOM handling, regardless of our actual file
2551 position. */
2552 pti->at_stream_start_for_bom_read = 1;
2553 pti->at_stream_start_for_bom_write = 1;
2554
9d9c66ba
LC
2555 if (encoding == NULL)
2556 encoding = "ISO-8859-1";
f4bc4e59 2557
7b292a9d
LC
2558 /* If ENCODING is UTF-8, then no conversion descriptor is opened
2559 because we do I/O ourselves. This saves 100+ KiB for each
2560 descriptor. */
cdd3d6c9 2561 pt->encoding = scm_gc_strdup (encoding, "port");
96965a6e 2562 if (c_strcasecmp (encoding, "UTF-8") == 0)
cdd3d6c9 2563 pti->encoding_mode = SCM_PORT_ENCODING_MODE_UTF8;
337edc59 2564 else
cdd3d6c9 2565 pti->encoding_mode = SCM_PORT_ENCODING_MODE_ICONV;
f4bc4e59 2566
cdd3d6c9 2567 pti->iconv_descriptors = NULL;
337edc59
MW
2568 if (prev)
2569 close_iconv_descriptors (prev);
889975e5
MG
2570}
2571
2572SCM_DEFINE (scm_port_encoding, "port-encoding", 1, 0, 0,
2573 (SCM port),
2574 "Returns, as a string, the character encoding that @var{port}\n"
2575 "uses to interpret its input and output.\n")
2576#define FUNC_NAME s_scm_port_encoding
2577{
2578 scm_t_port *pt;
2579 const char *enc;
2580
2581 SCM_VALIDATE_PORT (1, port);
2582
2583 pt = SCM_PTAB_ENTRY (port);
9d9c66ba 2584 enc = pt->encoding;
889975e5
MG
2585 if (enc)
2586 return scm_from_locale_string (pt->encoding);
2587 else
0af34a3f 2588 return SCM_BOOL_F;
889975e5
MG
2589}
2590#undef FUNC_NAME
d6a6989e 2591
889975e5
MG
2592SCM_DEFINE (scm_set_port_encoding_x, "set-port-encoding!", 2, 0, 0,
2593 (SCM port, SCM enc),
2594 "Sets the character encoding that will be used to interpret all\n"
2595 "port I/O. New ports are created with the encoding\n"
2596 "appropriate for the current locale if @code{setlocale} has \n"
2597 "been called or ISO-8859-1 otherwise\n"
2598 "and this procedure can be used to modify that encoding.\n")
889975e5
MG
2599#define FUNC_NAME s_scm_set_port_encoding_x
2600{
2601 char *enc_str;
889975e5
MG
2602
2603 SCM_VALIDATE_PORT (1, port);
2604 SCM_VALIDATE_STRING (2, enc);
2605
2606 enc_str = scm_to_locale_string (enc);
da288f50 2607 scm_i_set_port_encoding_x (port, enc_str);
3e05fc04 2608 free (enc_str);
da288f50 2609
889975e5
MG
2610 return SCM_UNSPECIFIED;
2611}
2612#undef FUNC_NAME
2613
2614
b22e94db
LC
2615/* A fluid specifying the default conversion handler for newly created
2616 ports. Its value should be one of the symbols below. */
2617SCM_VARIABLE (default_conversion_strategy_var,
2618 "%default-port-conversion-strategy");
2619
2620/* Whether the above fluid is initialized. */
889975e5
MG
2621static int scm_conversion_strategy_init = 0;
2622
b22e94db
LC
2623/* The possible conversion strategies. */
2624SCM_SYMBOL (sym_error, "error");
2625SCM_SYMBOL (sym_substitute, "substitute");
2626SCM_SYMBOL (sym_escape, "escape");
2627
2628/* Return the default failed encoding conversion policy for new created
2629 ports. */
889975e5 2630scm_t_string_failed_conversion_handler
b22e94db 2631scm_i_default_port_conversion_handler (void)
889975e5 2632{
b22e94db
LC
2633 scm_t_string_failed_conversion_handler handler;
2634
2635 if (!scm_conversion_strategy_init
2636 || !scm_is_fluid (SCM_VARIABLE_REF (default_conversion_strategy_var)))
2637 handler = SCM_FAILED_CONVERSION_QUESTION_MARK;
889975e5
MG
2638 else
2639 {
b22e94db
LC
2640 SCM fluid, value;
2641
2642 fluid = SCM_VARIABLE_REF (default_conversion_strategy_var);
2643 value = scm_fluid_ref (fluid);
2644
2645 if (scm_is_eq (sym_substitute, value))
2646 handler = SCM_FAILED_CONVERSION_QUESTION_MARK;
2647 else if (scm_is_eq (sym_escape, value))
2648 handler = SCM_FAILED_CONVERSION_ESCAPE_SEQUENCE;
2649 else
2650 /* Default to 'error also when the fluid's value is not one of
2651 the valid symbols. */
2652 handler = SCM_FAILED_CONVERSION_ERROR;
889975e5 2653 }
b22e94db
LC
2654
2655 return handler;
889975e5
MG
2656}
2657
b22e94db 2658/* Use HANDLER as the default conversion strategy for future ports. */
889975e5 2659void
b22e94db
LC
2660scm_i_set_default_port_conversion_handler (scm_t_string_failed_conversion_handler
2661 handler)
889975e5
MG
2662{
2663 SCM strategy;
b22e94db
LC
2664
2665 if (!scm_conversion_strategy_init
2666 || !scm_is_fluid (SCM_VARIABLE_REF (default_conversion_strategy_var)))
2667 scm_misc_error (NULL, "tried to set conversion strategy fluid before it is initialized",
2668 SCM_EOL);
2669
2670 switch (handler)
889975e5 2671 {
b22e94db
LC
2672 case SCM_FAILED_CONVERSION_ERROR:
2673 strategy = sym_error;
2674 break;
2675
2676 case SCM_FAILED_CONVERSION_ESCAPE_SEQUENCE:
2677 strategy = sym_escape;
2678 break;
2679
2680 case SCM_FAILED_CONVERSION_QUESTION_MARK:
2681 strategy = sym_substitute;
2682 break;
2683
2684 default:
2685 abort ();
889975e5 2686 }
b22e94db
LC
2687
2688 scm_fluid_set_x (SCM_VARIABLE_REF (default_conversion_strategy_var),
2689 strategy);
889975e5
MG
2690}
2691
2692SCM_DEFINE (scm_port_conversion_strategy, "port-conversion-strategy",
2693 1, 0, 0, (SCM port),
2694 "Returns the behavior of the port when handling a character that\n"
2695 "is not representable in the port's current encoding.\n"
2696 "It returns the symbol @code{error} if unrepresentable characters\n"
2697 "should cause exceptions, @code{substitute} if the port should\n"
2698 "try to replace unrepresentable characters with question marks or\n"
2699 "approximate characters, or @code{escape} if unrepresentable\n"
2700 "characters should be converted to string escapes.\n"
2701 "\n"
2702 "If @var{port} is @code{#f}, then the current default behavior\n"
2703 "will be returned. New ports will have this default behavior\n"
2704 "when they are created.\n")
2705#define FUNC_NAME s_scm_port_conversion_strategy
2706{
2707 scm_t_string_failed_conversion_handler h;
2708
b22e94db
LC
2709 if (scm_is_false (port))
2710 h = scm_i_default_port_conversion_handler ();
2711 else
889975e5 2712 {
b22e94db
LC
2713 scm_t_port *pt;
2714
889975e5 2715 SCM_VALIDATE_OPPORT (1, port);
b22e94db
LC
2716 pt = SCM_PTAB_ENTRY (port);
2717
2718 h = pt->ilseq_handler;
889975e5
MG
2719 }
2720
889975e5 2721 if (h == SCM_FAILED_CONVERSION_ERROR)
4a655e50 2722 return scm_from_latin1_symbol ("error");
889975e5 2723 else if (h == SCM_FAILED_CONVERSION_QUESTION_MARK)
4a655e50 2724 return scm_from_latin1_symbol ("substitute");
889975e5 2725 else if (h == SCM_FAILED_CONVERSION_ESCAPE_SEQUENCE)
4a655e50 2726 return scm_from_latin1_symbol ("escape");
889975e5
MG
2727 else
2728 abort ();
2729
2730 /* Never gets here. */
2731 return SCM_UNDEFINED;
2732}
2733#undef FUNC_NAME
2734
2735SCM_DEFINE (scm_set_port_conversion_strategy_x, "set-port-conversion-strategy!",
2736 2, 0, 0,
2737 (SCM port, SCM sym),
2738 "Sets the behavior of the interpreter when outputting a character\n"
2739 "that is not representable in the port's current encoding.\n"
2740 "@var{sym} can be either @code{'error}, @code{'substitute}, or\n"
2741 "@code{'escape}. If it is @code{'error}, an error will be thrown\n"
2742 "when an unconvertible character is encountered. If it is\n"
2743 "@code{'substitute}, then unconvertible characters will \n"
2744 "be replaced with approximate characters, or with question marks\n"
2745 "if no approximately correct character is available.\n"
2746 "If it is @code{'escape},\n"
2747 "it will appear as a hex escape when output.\n"
2748 "\n"
2749 "If @var{port} is an open port, the conversion error behavior\n"
2750 "is set for that port. If it is @code{#f}, it is set as the\n"
2751 "default behavior for any future ports that get created in\n"
2752 "this thread.\n")
2753#define FUNC_NAME s_scm_set_port_conversion_strategy_x
2754{
b22e94db 2755 scm_t_string_failed_conversion_handler handler;
889975e5 2756
b22e94db
LC
2757 if (scm_is_eq (sym, sym_error))
2758 handler = SCM_FAILED_CONVERSION_ERROR;
2759 else if (scm_is_eq (sym, sym_substitute))
2760 handler = SCM_FAILED_CONVERSION_QUESTION_MARK;
2761 else if (scm_is_eq (sym, sym_escape))
2762 handler = SCM_FAILED_CONVERSION_ESCAPE_SEQUENCE;
2763 else
2764 SCM_MISC_ERROR ("unknown conversion strategy ~s", scm_list_1 (sym));
889975e5 2765
b22e94db
LC
2766 if (scm_is_false (port))
2767 scm_i_set_default_port_conversion_handler (handler);
2768 else
889975e5 2769 {
b22e94db
LC
2770 SCM_VALIDATE_OPPORT (1, port);
2771 SCM_PTAB_ENTRY (port)->ilseq_handler = handler;
889975e5
MG
2772 }
2773
889975e5
MG
2774 return SCM_UNSPECIFIED;
2775}
2776#undef FUNC_NAME
2777
2778
2779
f12733c9
MD
2780void
2781scm_print_port_mode (SCM exp, SCM port)
2782{
2783 scm_puts (SCM_CLOSEDP (exp)
2784 ? "closed: "
f9a64404
DH
2785 : (SCM_RDNG & SCM_CELL_WORD_0 (exp)
2786 ? (SCM_WRTNG & SCM_CELL_WORD_0 (exp)
f12733c9
MD
2787 ? "input-output: "
2788 : "input: ")
f9a64404 2789 : (SCM_WRTNG & SCM_CELL_WORD_0 (exp)
f12733c9
MD
2790 ? "output: "
2791 : "bogus: ")),
2792 port);
2793}
1cc91f1b 2794
f12733c9 2795int
e81d98ec 2796scm_port_print (SCM exp, SCM port, scm_print_state *pstate SCM_UNUSED)
0f2d19dd 2797{
f12733c9
MD
2798 char *type = SCM_PTOBNAME (SCM_PTOBNUM (exp));
2799 if (!type)
2800 type = "port";
b7f3516f 2801 scm_puts ("#<", port);
f12733c9 2802 scm_print_port_mode (exp, port);
b7f3516f
TT
2803 scm_puts (type, port);
2804 scm_putc (' ', port);
0345e278 2805 scm_uintprint (SCM_CELL_WORD_1 (exp), 16, port);
b7f3516f 2806 scm_putc ('>', port);
f12733c9 2807 return 1;
0f2d19dd
JB
2808}
2809
0f2d19dd 2810\f
ee149d03 2811
d68fee48 2812/* Void ports. */
0f2d19dd 2813
92c2555f 2814scm_t_bits scm_tc16_void_port = 0;
0f2d19dd 2815
e81d98ec 2816static int fill_input_void_port (SCM port SCM_UNUSED)
283a1a0e 2817{
70df8af6 2818 return EOF;
283a1a0e
GH
2819}
2820
31703ab8 2821static void
e81d98ec
DH
2822write_void_port (SCM port SCM_UNUSED,
2823 const void *data SCM_UNUSED,
2824 size_t size SCM_UNUSED)
31703ab8
GH
2825{
2826}
2827
d617ee18
MV
2828static SCM
2829scm_i_void_port (long mode_bits)
0f2d19dd 2830{
9de87eea 2831 scm_i_scm_pthread_mutex_lock (&scm_i_port_table_mutex);
402788a9 2832 {
da220f27
HWN
2833 SCM answer = scm_new_port_table_entry (scm_tc16_void_port);
2834 scm_t_port * pt = SCM_PTAB_ENTRY(answer);
2835
402788a9 2836 scm_port_non_buffer (pt);
402788a9
HWN
2837
2838 SCM_SETSTREAM (answer, 0);
2839 SCM_SET_CELL_TYPE (answer, scm_tc16_void_port | mode_bits);
9de87eea 2840 scm_i_pthread_mutex_unlock (&scm_i_port_table_mutex);
402788a9
HWN
2841 return answer;
2842 }
0f2d19dd
JB
2843}
2844
d617ee18
MV
2845SCM
2846scm_void_port (char *mode_str)
2847{
2848 return scm_i_void_port (scm_mode_bits (mode_str));
2849}
2850
a1ec6916 2851SCM_DEFINE (scm_sys_make_void_port, "%make-void-port", 1, 0, 0,
1bbd0b84 2852 (SCM mode),
70df8af6 2853 "Create and return a new void port. A void port acts like\n"
bb2c02f2 2854 "@file{/dev/null}. The @var{mode} argument\n"
70df8af6 2855 "specifies the input/output modes for this port: see the\n"
b380b885 2856 "documentation for @code{open-file} in @ref{File Ports}.")
1bbd0b84 2857#define FUNC_NAME s_scm_sys_make_void_port
0f2d19dd 2858{
d617ee18 2859 return scm_i_void_port (scm_i_mode_bits (mode));
0f2d19dd 2860}
1bbd0b84 2861#undef FUNC_NAME
0f2d19dd 2862
0f2d19dd 2863\f
89545eba 2864/* Initialization. */
1cc91f1b 2865
0f2d19dd
JB
2866void
2867scm_init_ports ()
0f2d19dd 2868{
840ae05d 2869 /* lseek() symbols. */
e11e83f3
MV
2870 scm_c_define ("SEEK_SET", scm_from_int (SEEK_SET));
2871 scm_c_define ("SEEK_CUR", scm_from_int (SEEK_CUR));
2872 scm_c_define ("SEEK_END", scm_from_int (SEEK_END));
840ae05d 2873
70df8af6
GH
2874 scm_tc16_void_port = scm_make_port_type ("void", fill_input_void_port,
2875 write_void_port);
9de87eea 2876
f39448c5
AW
2877 cur_inport_fluid = scm_make_fluid ();
2878 cur_outport_fluid = scm_make_fluid ();
2879 cur_errport_fluid = scm_make_fluid ();
2880 cur_loadport_fluid = scm_make_fluid ();
9de87eea 2881
f39448c5 2882 scm_i_port_weak_hash = scm_make_weak_key_hash_table (SCM_I_MAKINUM(31));
d6a6989e 2883
a0599745 2884#include "libguile/ports.x"
889975e5 2885
d6a6989e 2886 /* Use Latin-1 as the default port encoding. */
c81c2ad3
AW
2887 SCM_VARIABLE_SET (default_port_encoding_var,
2888 scm_make_fluid_with_default (SCM_BOOL_F));
889975e5 2889 scm_port_encoding_init = 1;
d6a6989e 2890
b22e94db
LC
2891 SCM_VARIABLE_SET (default_conversion_strategy_var,
2892 scm_make_fluid_with_default (sym_substitute));
889975e5 2893 scm_conversion_strategy_init = 1;
b22e94db 2894
9670f238
AW
2895 /* These bindings are used when boot-9 turns `current-input-port' et
2896 al into parameters. They are then removed from the guile module. */
2897 scm_c_define ("%current-input-port-fluid", cur_inport_fluid);
2898 scm_c_define ("%current-output-port-fluid", cur_outport_fluid);
2899 scm_c_define ("%current-error-port-fluid", cur_errport_fluid);
0f2d19dd 2900}
89e00824
ML
2901
2902/*
2903 Local Variables:
2904 c-file-style: "gnu"
2905 End:
2906*/