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