[project @ 1998-11-26 09:17:22 by sof]
[ghc-hetmet.git] / ghc / lib / std / cbits / filePutc.lc
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1994
3 %
4 \subsection[filePut.lc]{hPutChar Runtime Support}
5
6 \begin{code}
7
8 #include "rtsdefs.h"
9 #include "stgio.h"
10 #include "error.h"
11
12 #define TERMINATE_LINE(x)   ((x) == '\n')
13
14 StgInt
15 filePutc(ptr, c)
16 StgForeignObj ptr;
17 StgChar c;
18 {
19     IOFileObject* fo = (IOFileObject*)ptr;
20     int rc = 0;
21
22     /* What filePutc needs to do:
23
24          - if there's no buffering => write it out.
25          - if the buffer is line-buffered
26                 write out buffer (+char), iff buffer would be full afterwards ||
27                                               new char is the newline character
28                 add to buffer , otherwise
29          - if the buffer is fully-buffered
30                write out buffer (+char), iff adding char fills up buffer.
31                add char to buffer, otherwise.
32
33      In the cases where a file is buffered, the invariant is that operations
34      that fill up a buffer also flushes them. A consequence of this here, is 
35      that we're guaranteed to be passed a buffer with space for (at least)
36      the one char we're adding.
37
38      Supporting RW objects adds yet another twist, since we have to make
39      sure that if such objects have been read from just previously, we
40      flush(i.e., empty) the buffer first. (We could be smarter about this,
41      but aren't!)
42
43     */
44
45     if ( FILEOBJ_READABLE(fo) && FILEOBJ_JUST_READ(fo) ) {
46         rc = flushReadBuffer(ptr);
47         if (rc<0) return rc;
48     }
49
50     fo->flags = (fo->flags & ~FILEOBJ_RW_READ) | FILEOBJ_RW_WRITE;
51               
52    /* check whether we can just add it to the buffer.. */
53     if ( FILEOBJ_UNBUFFERED(fo) ) {
54         ; 
55     } else {
56         /* We're buffered, add it to the pack */
57        ((char*)fo->buf)[fo->bufWPtr] = (char)c;
58        fo->bufWPtr++;
59       /* If the buffer filled up as a result, *or*
60          the added character terminated a line
61             => flush.
62       */
63       if ( FILEOBJ_BUFFER_FULL(fo) || 
64            (FILEOBJ_LINEBUFFERED(fo) && TERMINATE_LINE(c)) ) {
65         rc = writeBuffer(ptr, fo->bufWPtr);
66         /* Undo the write if we're blocking..*/
67         if (rc == FILEOBJ_BLOCKED_WRITE ) fo->bufWPtr--;
68       }
69       return rc;
70     }
71
72     if ( fo->flags & FILEOBJ_NONBLOCKING_IO && inputReady(ptr,0) != 1 )
73       return FILEOBJ_BLOCKED_WRITE;
74
75     /* Unbuffered, write the character directly. */
76     while ((rc = write(fo->fd, &c, 1)) == 0 && errno == EINTR) ;
77
78     if (rc == 0) {
79         cvtErrno();
80         stdErrno();
81         return -1;
82     }
83     return 0;
84
85 }
86
87 \end{code}