*** empty log message ***
[bpt/guile.git] / libguile / fports.c
CommitLineData
3d7f708f 1/* Copyright (C) 1995,1996,1997,1998,1999,2000,2001, 2002 Free Software Foundation, Inc.
0f2d19dd
JB
2 *
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2, or (at your option)
6 * any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License
14 * along with this software; see the file COPYING. If not, write to
82892bed
JB
15 * the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
16 * Boston, MA 02111-1307 USA
0f2d19dd
JB
17 *
18 * As a special exception, the Free Software Foundation gives permission
19 * for additional uses of the text contained in its release of GUILE.
20 *
21 * The exception is that, if you link the GUILE library with other files
22 * to produce an executable, this does not by itself cause the
23 * resulting executable to be covered by the GNU General Public License.
24 * Your use of that executable is in no way restricted on account of
25 * linking the GUILE library code into it.
26 *
27 * This exception does not however invalidate any other reasons why
28 * the executable file might be covered by the GNU General Public License.
29 *
30 * This exception applies only to the code released by the
31 * Free Software Foundation under the name GUILE. If you copy
32 * code from other Free Software Foundation releases into a copy of
33 * GUILE, as the General Public License permits, the exception does
34 * not apply to the code that you add in this way. To avoid misleading
35 * anyone as to the status of such modified files, you must delete
36 * this exception notice from them.
37 *
38 * If you write modifications of your own for GUILE, it is your choice
39 * whether to permit this exception to apply to your modifications.
82892bed 40 * If you do not wish that, delete this exception notice. */
1bbd0b84 41
1bbd0b84 42
0f2d19dd 43\f
85286595
RB
44#if HAVE_CONFIG_H
45# include <config.h>
46#endif
0f2d19dd
JB
47
48#include <stdio.h>
cb63cf9e 49#include <fcntl.h>
a0599745
MD
50#include "libguile/_scm.h"
51#include "libguile/strings.h"
a0599745 52#include "libguile/validate.h"
6b72ac1d
GH
53#include "libguile/gc.h"
54
a0599745 55#include "libguile/fports.h"
95b88819
GH
56
57#ifdef HAVE_STRING_H
58#include <string.h>
59#endif
0f2d19dd
JB
60#ifdef HAVE_UNISTD_H
61#include <unistd.h>
62#else
1be6b49c 63size_t fwrite ();
0f2d19dd 64#endif
b8b17bfd
MV
65#ifdef HAVE_IO_H
66#include <io.h>
67#endif
f47a5239 68#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
cb63cf9e
JB
69#include <sys/stat.h>
70#endif
0f2d19dd 71
cb63cf9e 72#include <errno.h>
e145dd02 73
a0599745 74#include "libguile/iselect.h"
edb810bb
SJ
75
76/* Some defines for Windows (native port, not Cygwin). */
82893676
MG
77#ifdef __MINGW32__
78# include <sys/stat.h>
79# include <winsock2.h>
80# define ftruncate(fd, size) chsize (fd, size)
81#endif /* __MINGW32__ */
cb63cf9e 82
a98bddfd 83
92c2555f 84scm_t_bits scm_tc16_fport;
a98bddfd
DH
85
86
19b27fa2 87/* default buffer size, used if the O/S won't supply a value. */
1be6b49c 88static const size_t default_buffer_size = 1024;
19b27fa2 89
cb63cf9e
JB
90/* create FPORT buffer with specified sizes (or -1 to use default size or
91 0 for no buffer. */
92static void
c014a02e 93scm_fport_buffer_add (SCM port, long read_size, int write_size)
c6c79933 94#define FUNC_NAME "scm_fport_buffer_add"
e145dd02 95{
92c2555f 96 scm_t_port *pt = SCM_PTAB_ENTRY (port);
e145dd02 97
cb63cf9e
JB
98 if (read_size == -1 || write_size == -1)
99 {
1be6b49c 100 size_t default_size;
f47a5239 101#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
cb63cf9e 102 struct stat st;
b8b17bfd 103 scm_t_fport *fp = SCM_FSTREAM (port);
cb63cf9e 104
19b27fa2
GH
105 default_size = (fstat (fp->fdes, &st) == -1) ? default_buffer_size
106 : st.st_blksize;
cb63cf9e 107#else
19b27fa2 108 default_size = default_buffer_size;
cb63cf9e
JB
109#endif
110 if (read_size == -1)
111 read_size = default_size;
112 if (write_size == -1)
113 write_size = default_size;
114 }
0f2d19dd 115
f5f2dcff 116 if (SCM_INPUT_PORT_P (port) && read_size > 0)
cb63cf9e 117 {
4c9419ac 118 pt->read_buf = scm_gc_malloc (read_size, "port buffer");
cb63cf9e
JB
119 pt->read_pos = pt->read_end = pt->read_buf;
120 pt->read_buf_size = read_size;
121 }
122 else
123 {
840ae05d 124 pt->read_pos = pt->read_buf = pt->read_end = &pt->shortbuf;
cb63cf9e
JB
125 pt->read_buf_size = 1;
126 }
1717856b 127
f5f2dcff 128 if (SCM_OUTPUT_PORT_P (port) && write_size > 0)
cb63cf9e 129 {
4c9419ac 130 pt->write_buf = scm_gc_malloc (write_size, "port buffer");
cb63cf9e
JB
131 pt->write_pos = pt->write_buf;
132 pt->write_buf_size = write_size;
133 }
134 else
135 {
136 pt->write_buf = pt->write_pos = &pt->shortbuf;
137 pt->write_buf_size = 1;
138 }
139
140 pt->write_end = pt->write_buf + pt->write_buf_size;
141 if (read_size > 0 || write_size > 0)
54778cd3 142 SCM_SET_CELL_WORD_0 (port, SCM_CELL_WORD_0 (port) & ~SCM_BUF0);
cb63cf9e 143 else
54778cd3 144 SCM_SET_CELL_WORD_0 (port, SCM_CELL_WORD_0 (port) | SCM_BUF0);
7a6f1ffa 145}
c6c79933 146#undef FUNC_NAME
7a6f1ffa 147
a1ec6916 148SCM_DEFINE (scm_setvbuf, "setvbuf", 2, 1, 0,
1bbd0b84 149 (SCM port, SCM mode, SCM size),
fc0d72d4
MD
150 "Set the buffering mode for @var{port}. @var{mode} can be:\n"
151 "@table @code\n"
152 "@item _IONBF\n"
153 "non-buffered\n"
154 "@item _IOLBF\n"
155 "line buffered\n"
156 "@item _IOFBF\n"
157 "block buffered, using a newly allocated buffer of @var{size} bytes.\n"
158 "If @var{size} is omitted, a default size will be used.\n"
2c1ae20e 159 "@end table")
1bbd0b84 160#define FUNC_NAME s_scm_setvbuf
7a6f1ffa 161{
1be6b49c 162 int cmode;
c014a02e 163 long csize;
92c2555f 164 scm_t_port *pt;
7a6f1ffa 165
78446828
MV
166 port = SCM_COERCE_OUTPORT (port);
167
3b3b36dd
GB
168 SCM_VALIDATE_OPFPORT (1,port);
169 SCM_VALIDATE_INUM_COPY (2,mode,cmode);
d3639214 170 if (cmode != _IONBF && cmode != _IOFBF && cmode != _IOLBF)
1bbd0b84 171 scm_out_of_range (FUNC_NAME, mode);
d3639214
GH
172
173 if (cmode == _IOLBF)
174 {
54778cd3 175 SCM_SET_CELL_WORD_0 (port, SCM_CELL_WORD_0 (port) | SCM_BUFLINE);
d3639214
GH
176 cmode = _IOFBF;
177 }
178 else
179 {
54778cd3 180 SCM_SET_CELL_WORD_0 (port, SCM_CELL_WORD_0 (port) ^ SCM_BUFLINE);
d3639214
GH
181 }
182
7a6f1ffa 183 if (SCM_UNBNDP (size))
cb63cf9e
JB
184 {
185 if (cmode == _IOFBF)
186 csize = -1;
187 else
188 csize = 0;
189 }
7a6f1ffa
GH
190 else
191 {
3b3b36dd 192 SCM_VALIDATE_INUM_COPY (3,size,csize);
cb63cf9e 193 if (csize < 0 || (cmode == _IONBF && csize > 0))
1bbd0b84 194 scm_out_of_range (FUNC_NAME, size);
7a6f1ffa 195 }
d3639214 196
cb63cf9e 197 pt = SCM_PTAB_ENTRY (port);
7a6f1ffa 198
4c9419ac
MV
199 /* silently discards buffered and put-back chars. */
200 if (pt->read_buf == pt->putback_buf)
201 {
202 pt->read_buf = pt->saved_read_buf;
203 pt->read_pos = pt->saved_read_pos;
204 pt->read_end = pt->saved_read_end;
205 pt->read_buf_size = pt->saved_read_buf_size;
206 }
cb63cf9e 207 if (pt->read_buf != &pt->shortbuf)
4c9419ac 208 scm_gc_free (pt->read_buf, pt->read_buf_size, "port buffer");
cb63cf9e 209 if (pt->write_buf != &pt->shortbuf)
4c9419ac 210 scm_gc_free (pt->write_buf, pt->write_buf_size, "port buffer");
7a6f1ffa 211
cb63cf9e
JB
212 scm_fport_buffer_add (port, csize, csize);
213 return SCM_UNSPECIFIED;
0f2d19dd 214}
1bbd0b84 215#undef FUNC_NAME
0f2d19dd 216
eadd48de 217/* Move ports with the specified file descriptor to new descriptors,
387d418c 218 * resetting the revealed count to 0.
0f2d19dd 219 */
1717856b 220
eadd48de 221void
6e8d25a6 222scm_evict_ports (int fd)
0f2d19dd 223{
c014a02e 224 long i;
0f2d19dd 225
67329a9e 226 for (i = 0; i < scm_i_port_table_size; i++)
eadd48de 227 {
67329a9e 228 SCM port = scm_i_port_table[i]->port;
cb63cf9e
JB
229
230 if (SCM_FPORTP (port))
eadd48de 231 {
92c2555f 232 scm_t_fport *fp = SCM_FSTREAM (port);
cb63cf9e
JB
233
234 if (fp->fdes == fd)
235 {
236 fp->fdes = dup (fd);
237 if (fp->fdes == -1)
238 scm_syserror ("scm_evict_ports");
239 scm_set_port_revealed_x (port, SCM_MAKINUM (0));
240 }
eadd48de
GH
241 }
242 }
243}
0f2d19dd 244
efa40607
DH
245
246SCM_DEFINE (scm_file_port_p, "file-port?", 1, 0, 0,
247 (SCM obj),
2069af38 248 "Determine whether @var{obj} is a port that is related to a file.")
efa40607
DH
249#define FUNC_NAME s_scm_file_port_p
250{
251 return SCM_BOOL (SCM_FPORTP (obj));
252}
253#undef FUNC_NAME
254
255
0f2d19dd
JB
256/* scm_open_file
257 * Return a new port open on a given file.
258 *
259 * The mode string must match the pattern: [rwa+]** which
260 * is interpreted in the usual unix way.
261 *
262 * Return the new port.
263 */
3b3b36dd 264SCM_DEFINE (scm_open_file, "open-file", 2, 0, 0,
1e6808ea
MG
265 (SCM filename, SCM mode),
266 "Open the file whose name is @var{filename}, and return a port\n"
fc0d72d4 267 "representing that file. The attributes of the port are\n"
1e6808ea
MG
268 "determined by the @var{mode} string. The way in which this is\n"
269 "interpreted is similar to C stdio. The first character must be\n"
270 "one of the following:\n"
fc0d72d4
MD
271 "@table @samp\n"
272 "@item r\n"
273 "Open an existing file for input.\n"
274 "@item w\n"
275 "Open a file for output, creating it if it doesn't already exist\n"
276 "or removing its contents if it does.\n"
277 "@item a\n"
1e6808ea
MG
278 "Open a file for output, creating it if it doesn't already\n"
279 "exist. All writes to the port will go to the end of the file.\n"
fc0d72d4
MD
280 "The \"append mode\" can be turned off while the port is in use\n"
281 "@pxref{Ports and File Descriptors, fcntl}\n"
1e6808ea
MG
282 "@end table\n"
283 "The following additional characters can be appended:\n"
fc0d72d4
MD
284 "@table @samp\n"
285 "@item +\n"
286 "Open the port for both input and output. E.g., @code{r+}: open\n"
287 "an existing file for both input and output.\n"
288 "@item 0\n"
1e6808ea
MG
289 "Create an \"unbuffered\" port. In this case input and output\n"
290 "operations are passed directly to the underlying port\n"
291 "implementation without additional buffering. This is likely to\n"
292 "slow down I/O operations. The buffering mode can be changed\n"
293 "while a port is in use @pxref{Ports and File Descriptors,\n"
294 "setvbuf}\n"
fc0d72d4
MD
295 "@item l\n"
296 "Add line-buffering to the port. The port output buffer will be\n"
297 "automatically flushed whenever a newline character is written.\n"
1e6808ea
MG
298 "@end table\n"
299 "In theory we could create read/write ports which were buffered\n"
300 "in one direction only. However this isn't included in the\n"
301 "current interfaces. If a file cannot be opened with the access\n"
302 "requested, @code{open-file} throws an exception.")
1bbd0b84 303#define FUNC_NAME s_scm_open_file
0f2d19dd 304{
19639113 305 SCM port;
cb63cf9e
JB
306 int fdes;
307 int flags = 0;
19639113 308 char *file;
1e6808ea 309 char *md;
cb63cf9e 310 char *ptr;
19639113 311
a6d9e5ab 312 SCM_VALIDATE_STRING (1, filename);
1e6808ea 313 SCM_VALIDATE_STRING (2, mode);
19639113 314
a6d9e5ab 315 file = SCM_STRING_CHARS (filename);
1e6808ea 316 md = SCM_STRING_CHARS (mode);
19639113 317
1e6808ea 318 switch (*md)
0f2d19dd 319 {
cb63cf9e
JB
320 case 'r':
321 flags |= O_RDONLY;
322 break;
323 case 'w':
324 flags |= O_WRONLY | O_CREAT | O_TRUNC;
325 break;
326 case 'a':
327 flags |= O_WRONLY | O_CREAT | O_APPEND;
328 break;
329 default:
1e6808ea 330 scm_out_of_range (FUNC_NAME, mode);
0f2d19dd 331 }
1e6808ea 332 ptr = md + 1;
cb63cf9e 333 while (*ptr != '\0')
e145dd02 334 {
cb63cf9e
JB
335 switch (*ptr)
336 {
337 case '+':
338 flags = (flags & ~(O_RDONLY | O_WRONLY)) | O_RDWR;
339 break;
9f561420
GH
340 case 'b':
341#if defined (O_BINARY)
342 flags |= O_BINARY;
343#endif
344 break;
cb63cf9e 345 case '0': /* unbuffered: handled later. */
d3639214 346 case 'l': /* line buffered: handled during output. */
cb63cf9e
JB
347 break;
348 default:
1e6808ea 349 scm_out_of_range (FUNC_NAME, mode);
cb63cf9e
JB
350 }
351 ptr++;
e145dd02 352 }
cb63cf9e
JB
353 SCM_SYSCALL (fdes = open (file, flags, 0666));
354 if (fdes == -1)
e145dd02 355 {
cb63cf9e
JB
356 int en = errno;
357
5d2d2ffc 358 SCM_SYSERROR_MSG ("~A: ~S",
cb63cf9e 359 scm_cons (scm_makfrom0str (strerror (en)),
5d2d2ffc 360 scm_cons (filename, SCM_EOL)), en);
0f2d19dd 361 }
1e6808ea 362 port = scm_fdes_to_port (fdes, md, filename);
0f2d19dd
JB
363 return port;
364}
1bbd0b84 365#undef FUNC_NAME
0f2d19dd 366
e145dd02 367\f
82893676
MG
368#ifdef __MINGW32__
369/*
370 * Try getting the appropiate file flags for a given file descriptor
371 * under Windows. This incorporates some fancy operations because Windows
372 * differentiates between file, pipe and socket descriptors.
373 */
374#ifndef O_ACCMODE
375# define O_ACCMODE 0x0003
376#endif
377
378static int getflags (int fdes)
379{
380 int flags = 0;
381 struct stat buf;
382 int error, optlen = sizeof (int);
383
384 /* Is this a socket ? */
385 if (getsockopt (fdes, SOL_SOCKET, SO_ERROR, (void *) &error, &optlen) >= 0)
386 flags = O_RDWR;
387 /* Maybe a regular file ? */
388 else if (fstat (fdes, &buf) < 0)
389 flags = -1;
390 else
391 {
392 /* Or an anonymous pipe handle ? */
b8b17bfd 393 if (buf.st_mode & _S_IFIFO)
8f99e3f3
SJ
394 flags = PeekNamedPipe ((HANDLE) _get_osfhandle (fdes), NULL, 0,
395 NULL, NULL, NULL) ? O_RDONLY : O_WRONLY;
82893676 396 /* stdin ? */
b8b17bfd 397 else if (fdes == fileno (stdin) && isatty (fdes))
82893676
MG
398 flags = O_RDONLY;
399 /* stdout / stderr ? */
b8b17bfd
MV
400 else if ((fdes == fileno (stdout) || fdes == fileno (stderr)) &&
401 isatty (fdes))
82893676
MG
402 flags = O_WRONLY;
403 else
404 flags = buf.st_mode;
405 }
406 return flags;
407}
408#endif /* __MINGW32__ */
409
cb63cf9e 410/* Building Guile ports from a file descriptor. */
e145dd02 411
cb63cf9e 412/* Build a Scheme port from an open file descriptor `fdes'.
a089567e
JB
413 MODE indicates whether FILE is open for reading or writing; it uses
414 the same notation as open-file's second argument.
19b27fa2
GH
415 NAME is a string to be used as the port's filename.
416*/
a089567e 417SCM
cb63cf9e 418scm_fdes_to_port (int fdes, char *mode, SCM name)
19b27fa2 419#define FUNC_NAME "scm_fdes_to_port"
a089567e
JB
420{
421 long mode_bits = scm_mode_bits (mode);
422 SCM port;
92c2555f 423 scm_t_port *pt;
19b27fa2
GH
424 int flags;
425
426 /* test that fdes is valid. */
82893676
MG
427#ifdef __MINGW32__
428 flags = getflags (fdes);
429#else
19b27fa2 430 flags = fcntl (fdes, F_GETFL, 0);
82893676 431#endif
19b27fa2
GH
432 if (flags == -1)
433 SCM_SYSERROR;
434 flags &= O_ACCMODE;
435 if (flags != O_RDWR
436 && ((flags != O_WRONLY && (mode_bits & SCM_WRTNG))
437 || (flags != O_RDONLY && (mode_bits & SCM_RDNG))))
438 {
439 SCM_MISC_ERROR ("requested file mode not available on fdes", SCM_EOL);
440 }
a089567e 441
a089567e 442 SCM_DEFER_INTS;
da220f27
HWN
443
444 port = scm_new_port_table_entry (scm_tc16_fport);
445 SCM_SET_CELL_TYPE(port, scm_tc16_fport | mode_bits);
446 pt = SCM_PTAB_ENTRY(port);
a089567e 447 {
92c2555f 448 scm_t_fport *fp
4c9419ac 449 = (scm_t_fport *) scm_gc_malloc (sizeof (scm_t_fport), "file port");
c6c79933 450
cb63cf9e 451 fp->fdes = fdes;
0de97b83 452 pt->rw_random = SCM_FDES_RANDOM_P (fdes);
cb63cf9e
JB
453 SCM_SETSTREAM (port, fp);
454 if (mode_bits & SCM_BUF0)
455 scm_fport_buffer_add (port, 0, 0);
456 else
457 scm_fport_buffer_add (port, -1, -1);
a089567e 458 }
b24b5e13 459 SCM_SET_FILENAME (port, name);
a089567e 460 SCM_ALLOW_INTS;
e145dd02
JB
461 return port;
462}
19b27fa2 463#undef FUNC_NAME
e145dd02 464
affc96b5 465/* Return a lower bound on the number of bytes available for input. */
cb63cf9e 466static int
affc96b5 467fport_input_waiting (SCM port)
e145dd02 468{
cb63cf9e
JB
469 int fdes = SCM_FSTREAM (port)->fdes;
470
471#ifdef HAVE_SELECT
472 struct timeval timeout;
473 SELECT_TYPE read_set;
474 SELECT_TYPE write_set;
475 SELECT_TYPE except_set;
476
477 FD_ZERO (&read_set);
478 FD_ZERO (&write_set);
479 FD_ZERO (&except_set);
480
481 FD_SET (fdes, &read_set);
482
483 timeout.tv_sec = 0;
484 timeout.tv_usec = 0;
485
486 if (select (SELECT_SET_SIZE,
487 &read_set, &write_set, &except_set, &timeout)
488 < 0)
affc96b5
GH
489 scm_syserror ("fport_input_waiting");
490 return FD_ISSET (fdes, &read_set) ? 1 : 0;
cb63cf9e
JB
491#elif defined (FIONREAD)
492 int remir;
493 ioctl(fdes, FIONREAD, &remir);
494 return remir;
495#else
affc96b5 496 scm_misc_error ("fport_input_waiting",
cb63cf9e
JB
497 "Not fully implemented on this platform",
498 SCM_EOL);
499#endif
a089567e
JB
500}
501
cb63cf9e 502\f
0f2d19dd 503static int
e81d98ec 504fport_print (SCM exp, SCM port, scm_print_state *pstate SCM_UNUSED)
0f2d19dd 505{
b3ec3c64
MD
506 scm_puts ("#<", port);
507 scm_print_port_mode (exp, port);
508 if (SCM_OPFPORTP (exp))
0f2d19dd 509 {
b3ec3c64 510 int fdes;
b24b5e13
DH
511 SCM name = SCM_FILENAME (exp);
512 if (SCM_STRINGP (name) || SCM_SYMBOLP (name))
513 scm_display (name, port);
514 else
515 scm_puts (SCM_PTOBNAME (SCM_PTOBNUM (exp)), port);
b3ec3c64
MD
516 scm_putc (' ', port);
517 fdes = (SCM_FSTREAM (exp))->fdes;
518
82893676 519#ifdef HAVE_TTYNAME
b3ec3c64
MD
520 if (isatty (fdes))
521 scm_puts (ttyname (fdes), port);
522 else
82893676 523#endif /* HAVE_TTYNAME */
b3ec3c64 524 scm_intprint (fdes, 10, port);
0f2d19dd
JB
525 }
526 else
527 {
b3ec3c64
MD
528 scm_puts (SCM_PTOBNAME (SCM_PTOBNUM (exp)), port);
529 scm_putc (' ', port);
63bcad19 530 scm_intprint ((scm_t_bits) SCM_PTAB_ENTRY (exp), 16, port);
0f2d19dd 531 }
b3ec3c64
MD
532 scm_putc ('>', port);
533 return 1;
0f2d19dd
JB
534}
535
cb63cf9e
JB
536/* thread-local block for input on fport's fdes. */
537static void
538fport_wait_for_input (SCM port)
3cb988bd 539{
cb63cf9e 540 int fdes = SCM_FSTREAM (port)->fdes;
3cb988bd 541
affc96b5 542 if (!fport_input_waiting (port))
8122b543 543 {
cb63cf9e
JB
544 int n;
545 SELECT_TYPE readfds;
546 int flags = fcntl (fdes, F_GETFL);
547
548 if (flags == -1)
549 scm_syserror ("scm_fdes_wait_for_input");
550 if (!(flags & O_NONBLOCK))
551 do
552 {
553 FD_ZERO (&readfds);
554 FD_SET (fdes, &readfds);
555 n = scm_internal_select (fdes + 1, &readfds, NULL, NULL, NULL);
556 }
557 while (n == -1 && errno == EINTR);
8122b543 558 }
3cb988bd 559}
0f2d19dd 560
affc96b5 561static void fport_flush (SCM port);
0f2d19dd 562
c2da2648
GH
563/* fill a port's read-buffer with a single read. returns the first
564 char or EOF if end of file. */
0f2d19dd 565static int
affc96b5 566fport_fill_input (SCM port)
0f2d19dd 567{
c014a02e 568 long count;
92c2555f
MV
569 scm_t_port *pt = SCM_PTAB_ENTRY (port);
570 scm_t_fport *fp = SCM_FSTREAM (port);
cb63cf9e 571
cb63cf9e 572 fport_wait_for_input (port);
cb63cf9e
JB
573 SCM_SYSCALL (count = read (fp->fdes, pt->read_buf, pt->read_buf_size));
574 if (count == -1)
affc96b5 575 scm_syserror ("fport_fill_input");
cb63cf9e
JB
576 if (count == 0)
577 return EOF;
578 else
579 {
5c070ca7 580 pt->read_pos = pt->read_buf;
cb63cf9e 581 pt->read_end = pt->read_buf + count;
5c070ca7 582 return *pt->read_buf;
cb63cf9e 583 }
0f2d19dd
JB
584}
585
cb63cf9e 586static off_t
affc96b5 587fport_seek (SCM port, off_t offset, int whence)
0f2d19dd 588{
92c2555f
MV
589 scm_t_port *pt = SCM_PTAB_ENTRY (port);
590 scm_t_fport *fp = SCM_FSTREAM (port);
7dcb364d
GH
591 off_t rv;
592 off_t result;
593
594 if (pt->rw_active == SCM_PORT_WRITE)
595 {
596 if (offset != 0 || whence != SEEK_CUR)
597 {
598 fport_flush (port);
599 result = rv = lseek (fp->fdes, offset, whence);
600 }
601 else
602 {
603 /* read current position without disturbing the buffer. */
604 rv = lseek (fp->fdes, offset, whence);
605 result = rv + (pt->write_pos - pt->write_buf);
606 }
607 }
608 else if (pt->rw_active == SCM_PORT_READ)
609 {
610 if (offset != 0 || whence != SEEK_CUR)
611 {
612 /* could expand to avoid a second seek. */
613 scm_end_input (port);
614 result = rv = lseek (fp->fdes, offset, whence);
615 }
616 else
617 {
618 /* read current position without disturbing the buffer
619 (particularly the unread-char buffer). */
620 rv = lseek (fp->fdes, offset, whence);
621 result = rv - (pt->read_end - pt->read_pos);
622
623 if (pt->read_buf == pt->putback_buf)
624 result -= pt->saved_read_end - pt->saved_read_pos;
625 }
626 }
627 else /* SCM_PORT_NEITHER */
628 {
629 result = rv = lseek (fp->fdes, offset, whence);
630 }
cb8dfa3f 631
7dcb364d 632 if (rv == -1)
affc96b5 633 scm_syserror ("fport_seek");
7dcb364d 634
cb8dfa3f 635 return result;
0f2d19dd
JB
636}
637
840ae05d 638static void
affc96b5 639fport_truncate (SCM port, off_t length)
840ae05d 640{
92c2555f 641 scm_t_fport *fp = SCM_FSTREAM (port);
840ae05d
JB
642
643 if (ftruncate (fp->fdes, length) == -1)
644 scm_syserror ("ftruncate");
645}
646
0c6d2191
GH
647/* helper for fport_write: try to write data, using multiple system
648 calls if required. */
649#define FUNC_NAME "write_all"
650static void write_all (SCM port, const void *data, size_t remaining)
651{
652 int fdes = SCM_FSTREAM (port)->fdes;
653
654 while (remaining > 0)
655 {
82893676 656 size_t done;
0c6d2191
GH
657
658 SCM_SYSCALL (done = write (fdes, data, remaining));
659
660 if (done == -1)
661 SCM_SYSERROR;
662 remaining -= done;
663 data = ((const char *) data) + done;
664 }
665}
666#undef FUNC_NAME
667
31703ab8 668static void
8aa011a1 669fport_write (SCM port, const void *data, size_t size)
31703ab8 670{
0c6d2191 671 /* this procedure tries to minimize the number of writes/flushes. */
92c2555f 672 scm_t_port *pt = SCM_PTAB_ENTRY (port);
31703ab8 673
0c6d2191
GH
674 if (pt->write_buf == &pt->shortbuf
675 || (pt->write_pos == pt->write_buf && size >= pt->write_buf_size))
31703ab8 676 {
0c6d2191
GH
677 /* "unbuffered" port, or
678 port with empty buffer and data won't fit in buffer. */
679 write_all (port, data, size);
680 return;
31703ab8 681 }
d3639214 682
0c6d2191
GH
683 {
684 off_t space = pt->write_end - pt->write_pos;
685
686 if (size <= space)
687 {
688 /* data fits in buffer. */
689 memcpy (pt->write_pos, data, size);
690 pt->write_pos += size;
691 if (pt->write_pos == pt->write_end)
692 {
affc96b5 693 fport_flush (port);
0c6d2191
GH
694 /* we can skip the line-buffering check if nothing's buffered. */
695 return;
696 }
697 }
698 else
699 {
700 memcpy (pt->write_pos, data, space);
701 pt->write_pos = pt->write_end;
702 fport_flush (port);
703 {
704 const void *ptr = ((const char *) data) + space;
705 size_t remaining = size - space;
706
707 if (size >= pt->write_buf_size)
708 {
709 write_all (port, ptr, remaining);
710 return;
711 }
712 else
713 {
714 memcpy (pt->write_pos, ptr, remaining);
715 pt->write_pos += remaining;
716 }
31703ab8 717 }
0c6d2191 718 }
31703ab8 719
0c6d2191
GH
720 /* handle line buffering. */
721 if ((SCM_CELL_WORD_0 (port) & SCM_BUFLINE) && memchr (data, '\n', size))
722 fport_flush (port);
723 }
31703ab8
GH
724}
725
726/* becomes 1 when process is exiting: normal exception handling won't
727 work by this time. */
04a98cff 728extern int scm_i_terminating;
0f2d19dd 729
cb63cf9e 730static void
affc96b5 731fport_flush (SCM port)
0f2d19dd 732{
92c2555f
MV
733 scm_t_port *pt = SCM_PTAB_ENTRY (port);
734 scm_t_fport *fp = SCM_FSTREAM (port);
6f760c1d 735 unsigned char *ptr = pt->write_buf;
c014a02e
ML
736 long init_size = pt->write_pos - pt->write_buf;
737 long remaining = init_size;
0f2d19dd 738
cb63cf9e
JB
739 while (remaining > 0)
740 {
c014a02e 741 long count;
cb63cf9e
JB
742
743 SCM_SYSCALL (count = write (fp->fdes, ptr, remaining));
744 if (count < 0)
745 {
746 /* error. assume nothing was written this call, but
747 fix up the buffer for any previous successful writes. */
c014a02e 748 long done = init_size - remaining;
cb63cf9e
JB
749
750 if (done > 0)
751 {
752 int i;
753
754 for (i = 0; i < remaining; i++)
755 {
756 *(pt->write_buf + i) = *(pt->write_buf + done + i);
757 }
758 pt->write_pos = pt->write_buf + remaining;
759 }
04a98cff 760 if (scm_i_terminating)
cb63cf9e
JB
761 {
762 const char *msg = "Error: could not flush file-descriptor ";
763 char buf[11];
764
765 write (2, msg, strlen (msg));
766 sprintf (buf, "%d\n", fp->fdes);
767 write (2, buf, strlen (buf));
768
769 count = remaining;
770 }
6b72ac1d
GH
771 else if (scm_gc_running_p)
772 {
773 /* silently ignore the error. scm_error would abort if we
774 called it now. */
775 count = remaining;
776 }
777 else
778 scm_syserror ("fport_flush");
cb63cf9e
JB
779 }
780 ptr += count;
781 remaining -= count;
782 }
783 pt->write_pos = pt->write_buf;
61e452ba 784 pt->rw_active = SCM_PORT_NEITHER;
840ae05d
JB
785}
786
283a1a0e 787/* clear the read buffer and adjust the file position for unread bytes. */
840ae05d 788static void
affc96b5 789fport_end_input (SCM port, int offset)
840ae05d 790{
92c2555f
MV
791 scm_t_fport *fp = SCM_FSTREAM (port);
792 scm_t_port *pt = SCM_PTAB_ENTRY (port);
283a1a0e
GH
793
794 offset += pt->read_end - pt->read_pos;
840ae05d 795
840ae05d
JB
796 if (offset > 0)
797 {
798 pt->read_pos = pt->read_end;
799 /* will throw error if unread-char used at beginning of file
800 then attempting to write. seems correct. */
801 if (lseek (fp->fdes, -offset, SEEK_CUR) == -1)
affc96b5 802 scm_syserror ("fport_end_input");
840ae05d 803 }
61e452ba 804 pt->rw_active = SCM_PORT_NEITHER;
8f29fbd0
JB
805}
806
6a2c4c81 807static int
affc96b5 808fport_close (SCM port)
6a2c4c81 809{
92c2555f
MV
810 scm_t_fport *fp = SCM_FSTREAM (port);
811 scm_t_port *pt = SCM_PTAB_ENTRY (port);
cb63cf9e 812 int rv;
840ae05d 813
affc96b5 814 fport_flush (port);
cb63cf9e
JB
815 SCM_SYSCALL (rv = close (fp->fdes));
816 if (rv == -1 && errno != EBADF)
6b72ac1d
GH
817 {
818 if (scm_gc_running_p)
819 /* silently ignore the error. scm_error would abort if we
820 called it now. */
821 ;
822 else
823 scm_syserror ("fport_close");
824 }
6c951427
GH
825 if (pt->read_buf == pt->putback_buf)
826 pt->read_buf = pt->saved_read_buf;
cb63cf9e 827 if (pt->read_buf != &pt->shortbuf)
4c9419ac 828 scm_gc_free (pt->read_buf, pt->read_buf_size, "port buffer");
cb63cf9e 829 if (pt->write_buf != &pt->shortbuf)
4c9419ac
MV
830 scm_gc_free (pt->write_buf, pt->write_buf_size, "port buffer");
831 scm_gc_free (fp, sizeof (*fp), "file port");
cb63cf9e 832 return rv;
6a2c4c81
JB
833}
834
1be6b49c 835static size_t
affc96b5 836fport_free (SCM port)
b3ec3c64 837{
affc96b5 838 fport_close (port);
b3ec3c64
MD
839 return 0;
840}
841
92c2555f 842static scm_t_bits
b3ec3c64
MD
843scm_make_fptob ()
844{
92c2555f 845 scm_t_bits tc = scm_make_port_type ("file", fport_fill_input, fport_write);
a98bddfd 846
affc96b5 847 scm_set_port_free (tc, fport_free);
e841c3e0 848 scm_set_port_print (tc, fport_print);
affc96b5
GH
849 scm_set_port_flush (tc, fport_flush);
850 scm_set_port_end_input (tc, fport_end_input);
851 scm_set_port_close (tc, fport_close);
852 scm_set_port_seek (tc, fport_seek);
853 scm_set_port_truncate (tc, fport_truncate);
854 scm_set_port_input_waiting (tc, fport_input_waiting);
a98bddfd
DH
855
856 return tc;
b3ec3c64 857}
0f2d19dd 858
0f2d19dd
JB
859void
860scm_init_fports ()
0f2d19dd 861{
a98bddfd
DH
862 scm_tc16_fport = scm_make_fptob ();
863
86d31dfe
MV
864 scm_c_define ("_IOFBF", SCM_MAKINUM (_IOFBF));
865 scm_c_define ("_IOLBF", SCM_MAKINUM (_IOLBF));
866 scm_c_define ("_IONBF", SCM_MAKINUM (_IONBF));
a98bddfd 867
a98bddfd 868#include "libguile/fports.x"
0f2d19dd 869}
89e00824
ML
870
871/*
872 Local Variables:
873 c-file-style: "gnu"
874 End:
875*/