1 /* fileio.c -- does standard I/O
2 
3   (c) 1998-2007 (W3C) MIT, ERCIM, Keio University
4   See tidyp.h for the copyright notice.
5 
6   Default implementations of Tidy input sources
7   and output sinks based on standard C FILE*.
8 
9 */
10 
11 #include <stdio.h>
12 
13 #include "forward.h"
14 #include "fileio.h"
15 #include "tidyp.h"
16 
17 typedef struct _fp_input_source
18 {
19     FILE*        fp;
20     TidyBuffer   unget;
21 } FileSource;
22 
filesrc_getByte(void * sourceData)23 static int TIDY_CALL filesrc_getByte( void* sourceData )
24 {
25   FileSource* fin = (FileSource*) sourceData;
26   int bv;
27   if ( fin->unget.size > 0 )
28     bv = tidyBufPopByte( &fin->unget );
29   else
30     bv = fgetc( fin->fp );
31   return bv;
32 }
33 
filesrc_eof(void * sourceData)34 static Bool TIDY_CALL filesrc_eof( void* sourceData )
35 {
36   FileSource* fin = (FileSource*) sourceData;
37   Bool isEOF = ( fin->unget.size == 0 );
38   if ( isEOF )
39     isEOF = feof( fin->fp ) != 0;
40   return isEOF;
41 }
42 
filesrc_ungetByte(void * sourceData,byte bv)43 static void TIDY_CALL filesrc_ungetByte( void* sourceData, byte bv )
44 {
45   FileSource* fin = (FileSource*) sourceData;
46   tidyBufPutByte( &fin->unget, bv );
47 }
48 
49 #if SUPPORT_POSIX_MAPPED_FILES
50 #define initFileSource initStdIOFileSource
51 #define freeFileSource freeStdIOFileSource
52 #endif
TY_(initFileSource)53 int TY_(initFileSource)( TidyAllocator *allocator, TidyInputSource* inp, FILE* fp )
54 {
55   FileSource* fin = NULL;
56 
57   fin = (FileSource*) TidyAlloc( allocator, sizeof(FileSource) );
58   if ( !fin )
59       return -1;
60   TidyClearMemory( fin, sizeof(FileSource) );
61   fin->unget.allocator = allocator;
62   fin->fp = fp;
63 
64   inp->getByte    = filesrc_getByte;
65   inp->eof        = filesrc_eof;
66   inp->ungetByte  = filesrc_ungetByte;
67   inp->sourceData = fin;
68 
69   return 0;
70 }
71 
TY_(freeFileSource)72 void TY_(freeFileSource)( TidyInputSource* inp, Bool closeIt )
73 {
74     FileSource* fin = (FileSource*) inp->sourceData;
75     if ( closeIt && fin && fin->fp )
76       fclose( fin->fp );
77     tidyBufFree( &fin->unget );
78     TidyFree( fin->unget.allocator, fin );
79 }
80 
TY_(filesink_putByte)81 void TIDY_CALL TY_(filesink_putByte)( void* sinkData, byte bv )
82 {
83   FILE* fout = (FILE*) sinkData;
84   fputc( bv, fout );
85 }
86 
TY_(initFileSink)87 void TY_(initFileSink)( TidyOutputSink* outp, FILE* fp )
88 {
89   outp->putByte  = TY_(filesink_putByte);
90   outp->sinkData = fp;
91 }
92 
93 /*
94  * local variables:
95  * mode: c
96  * indent-tabs-mode: nil
97  * c-basic-offset: 4
98  * eval: (c-set-offset 'substatement-open 0)
99  * end:
100  */
101