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