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