File: stream.cc

package info (click to toggle)
ht 2.1.0%2Brepack1-3
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 5,796 kB
  • ctags: 15,915
  • sloc: cpp: 88,932; ansic: 12,693; sh: 4,081; lex: 226; makefile: 184; yacc: 128
file content (1657 lines) | stat: -rw-r--r-- 30,918 bytes parent folder | download | duplicates (8)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
/*
 *	HT Editor
 *	stream.cc
 *
 *	Copyright (C) 1999-2002 Stefan Weyergraf (stefan@weyergraf.de)
 *
 *	This program is free software; you can redistribute it and/or modify
 *	it under the terms of the GNU General Public License version 2 as
 *	published by the Free Software Foundation.
 *
 *	This program is distributed in the hope that it will be useful,
 *	but WITHOUT ANY WARRANTY; without even the implied warranty of
 *	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *	GNU General Public License for more details.
 *
 *	You should have received a copy of the GNU General Public License
 *	along with this program; if not, write to the Free Software
 *	Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include <cerrno>
#include <climits>
#include <new>
#include <cstring>
#include <cstdio>
#include <cstdlib>

#include <fcntl.h>
#include <sys/stat.h>	/* for mode definitions */
#include <sys/types.h>	/* for mode definitions */
#include <unistd.h>

#include "htdebug.h"
#include "except.h"
#include "snprintf.h"
#include "stream.h"
#include "strtools.h"
#include "tools.h"

/*
 *	Listener
 */
#if 0
class Listener: public Object {
public:
	StreamEventListener *listener;
	StreamEvent notify_mask;

	Listener(StreamEventListener *l, StreamEvent nmask)
	{
		listener = l;
		notify_mask = nmask;
	}

/* extends Object */
	virtual int compareTo(const Object *obj) const
	{
		return ((Listener*)obj)->listener == listener ? 0 : 1;
	}
};
#endif
/*
 *	Stream
 */

#define STREAM_COPYBUF_SIZE	(64*1024)

Stream::Stream()
{
	mAccessMode = IOAM_NULL;
//	mListeners = NULL;
}

/*
Stream::~Stream()
{
//	delete mListeners;
}
*/

/*
void Stream::addEventListener(StreamEventListener *l, StreamEvent mask)
{
	if (!mListeners) mListeners = new Array(true);
	*mListeners += new Listener(l, mask);
}
*/
void Stream::checkAccess(IOAccessMode mask)
{
	if ((mAccessMode & mask) != mask) throw IOException(EACCES);
}

/**
 *	Copy (whole) stream to another (i.e. copy until EOF)
 *	@param stream Stream to copy this Stream to
 *	@returns number of bytes copied
 */
FileOfs Stream::copyAllTo(Stream *stream)
{
	byte *buf = new byte[STREAM_COPYBUF_SIZE];
	FileOfs result = 0;
	uint r, t;
	do {
		uint k = STREAM_COPYBUF_SIZE;
		r = read(buf, k);
		assert(r <= k);
		t = stream->write(buf, r);
		assert(t <= r);
		result += t;
		if (t != k) break;
	} while (t);
	delete[] buf;
	return result;
}

/**
 *	Copy (partial) stream to another
 *	@param stream Stream to copy this Stream to
 *	@param count maximum number of bytes to copy
 *	@returns number of bytes copied
 */
FileOfs Stream::copyTo(Stream *stream, FileOfs count)
{
	byte *buf = new byte[STREAM_COPYBUF_SIZE];
	FileOfs result = 0;
	while (count) {
		uint k = STREAM_COPYBUF_SIZE;
		if (k > count) k = count;
		uint r = read(buf, k);
		assert(r <= k);
		uint t = stream->write(buf, r);
		assert(t <= r);
		count -= t;
		result += t;
		if (t != k) break;
	}
	delete[] buf;
	return result;
}

/**
 *	Get access-mode
 */
IOAccessMode Stream::getAccessMode() const
{
	return mAccessMode;
}

/**
 *	Get descriptive name
 */
String &Stream::getDesc(String &result) const
{
	result = "";
	return result;
}
/*
void Stream::notifyListeners(StreamEvent event,...)
{
	if (!mListeners) return;
	foreach(Listener, l, *mListeners,
		if (l->notify_mask & event) {
			va_list ap;
			va_start(ap, event);
			l->listener->handleEvent(event, ap);
			va_end(ap);
		}
	);
}
*/
/**
 *	Set access-mode
 */
int	Stream::setAccessMode(IOAccessMode mode)
{
	mAccessMode = mode;
	return 0;
}

/**
 *	Set access-mode, throw IOException if unsuccessful
 */
void	Stream::setAccessModex(IOAccessMode mode)
{
	int e = setAccessMode(mode);
	if (e) throw IOException(e);
}

/**
 *	Read from stream.
 *	Read up to <i>size</i> bytes from stream into <i>buf</i>.
 *	If less than <i>size</i> bytes are read, the exact number is
 *	returned and a (temporary) end-of-file (EOF) is encountered.
 *
 *	@param buf pointer to bytes to read
 *	@param size number of bytes to read
 *	@returns number of bytes read
 *	@throws IOException
 */
uint	Stream::read(void *buf, uint size)
{
	return 0;
}

/**
 *	Exact read from stream.
 *	Read exactly <i>size</i> bytes from stream into <i>buf</i>.
 *	If less than <i>size</i> bytes are read, IOException is thrown.
 *
 *	@param buf pointer to bytes to read
 *	@param size number of bytes to read
 *	@throws IOException
 */
//#include "snprintf.h" 
void	Stream::readx(void *buf, uint size)
{
//	File *f = dynamic_cast<File*>(this);
//	FileOfs t = f ? f->tell() : 0;
	if (read(buf, size) != size) {
//		FileOfs sz = f ? f->getSize() : mkfofs(0);
//		ht_printf("readx failed, ofs = 0x%qx, size = %d (file size 0x%qx)\n", &t, size, &sz);
		throw EOFException();
	}	    
}
/*
void Stream::removeEventListener(StreamEventListener *l)
{
	Listener t(l, SEV_NULL);
	bool b = (*mListeners -= &t);
	assert(b);
}
*/
/**
 *	Write to stream.
 *	Write up to <i>size</i> bytes from <i>buf</i> into stream.
 *	If less than <i>size</i> bytes are written, the exact number is
 *	returned and a (temporary) end-of-file (EOF) is encountered.
 *
 *	@param buf pointer to bytes to write
 *	@param size number of bytes to write
 *	@returns number of bytes written
 *	@throws IOException
 */
uint	Stream::write(const void *buf, uint size)
{
	return 0;
}

/**
 *	Exact write to stream.
 *	Write exactly <i>size</i> bytes from <i>buf</i> into stream.
 *	If less than <i>size</i> bytes are written, IOException is thrown.
 *
 *	@param buf pointer to bytes to write
 *	@param size number of bytes to write
 *	@throws IOException
 */
void	Stream::writex(const void *buf, uint size)
{
	if (write(buf, size) != size) throw EOFException();
}


// FIXME: more dynamical solution appreciated
#define REASONABLE_STRING_LIMIT	1024
 
char *Stream::readstrz()
{
	/* get string size */
	char buf[REASONABLE_STRING_LIMIT];
	int z = 0;
	while (1) {
		readx(buf+z, 1);
		z++;
		if (z >= REASONABLE_STRING_LIMIT) {
			z = REASONABLE_STRING_LIMIT;
			break;
		}
		if (buf[z-1] == 0) break;
	}
	if (!z) return NULL;
	char *str = ht_malloc(z);
	if (!str) throw std::bad_alloc();
	memcpy(str, buf, z-1);
	str[z-1] = 0;
	return str;
}

bool Stream::readStringz(String &s)
{
	String r;
	try {
		while (1) {
			char c;
			readx(&c, 1);
			if (!c) break;
			r.appendChar(c);
		}
		s.grab(r);
		return true;
	} catch (const EOFException &) {
		return false;
	}
}

void Stream::writestrz(const char *str)
{
	if (str) {
		writex(str, strlen(str)+1);
	} else {
		byte n = 0;
		writex(&n, 1);
	}
}

char *Stream::readstrp()
{
	uint8 l;
	readx(&l, 1);
	char *str = ht_malloc(l+1);
	if (!str) throw std::bad_alloc();
	try {
		readx(str, l);
	} catch (...) {
		free(str);
		throw;
	}
	str[l] = 0;
	return str;
}

char *Stream::readstrl()
{
	uint32 l = 0;
	for (int i=0; i<4; i++) {
		uint8 b;
		readx(&b, 1);
		l <<= 7;
		l |= b & 0x7f;
		if (!(b & 0x80)) break;
	}
	char *str = ht_malloc(l+1);
	if (!str) throw std::bad_alloc();	
	try {
		readx(str, l);
	} catch (...) {
		free(str);
		throw;
	}
	str[l] = 0;
	return str;
}

void Stream::writestrl(const char *str)
{
	uint8 b;
	uint32 len = strlen(str);
	if (!len) {
		b = 0;
		writex(&b, 1);
		return;
	}
	int i = 4;
	uint32 a = 0xfe000000;
	while (!(len & a)) {
		a >>= 7;
		i--;
	}
	len <<= (4-i)*7;
	while (i--) {
		a = i ? 0x80 : 0;
		b = ((len & 0xfe000000) >> (3 * 7)) | a;
		len <<= 7;
		writex(&b, 1);
		return;
	}
}

void Stream::writestrp(const char *str)
{
	unsigned char l = str ? strlen(str) : 0;
	writex(&l, 1);
	writex(str, l);
}

char *Stream::readstrw()
{
	short t;
	byte lbuf[2];
	readx(lbuf, 2);
	int l = lbuf[0] | lbuf[1] << 8;
	char *a = ht_malloc(l+1);
	if (!a) throw std::bad_alloc();
	for (int i=0; i < l; i++) {
		// FIXME: this looks wrong
		readx(&t, 2);
		a[i] = (char)t;
	}
	a[l] = 0;
	return a;
}

void Stream::writestrw(const char *str)
{
	/* FIXME: someone implement me ? */
	throw NotImplementedException(HERE);
}
/*
 *   StreamLayer
 */

StreamLayer::StreamLayer(Stream *s, bool own) : Stream()
{
	mStream = s;
	mOwnStream = own;
}

StreamLayer::~StreamLayer()
{
	if (mOwnStream) delete mStream;
}

IOAccessMode StreamLayer::getAccessMode() const
{
	return mStream->getAccessMode();
}

String &StreamLayer::getDesc(String &result) const
{
	return mStream->getDesc(result);
}

int StreamLayer::setAccessMode(IOAccessMode mode)
{
	return mStream->setAccessMode(mode);
}

uint StreamLayer::read(void *buf, uint size)
{
	return mStream->read(buf, size);
}

uint StreamLayer::write(const void *buf, uint size)
{
	return mStream->write(buf, size);
}

Stream *StreamLayer::getLayered() const
{
	return mStream;
}

void StreamLayer::setLayered(Stream *newLayered, bool ownNewLayered)
{
	mStream = newLayered;
	mOwnStream = ownNewLayered;
}

/*
 *	ObjectStream
 */
ObjectStream::ObjectStream(Stream *s, bool own_s) : StreamLayer(s, own_s)
{
}

void ObjectStream::putCommentf(const char *comment_format, ...)
{
	char buf[1024];
	va_list arg;
	va_start(arg, comment_format);
	ht_vsnprintf(buf, sizeof buf, comment_format, arg);
	va_end(arg);
	putComment(buf);
}

/**
 *	A object-stream-layer.
 */
ObjectStreamLayer::ObjectStreamLayer(ObjectStream *aObjStream, bool own_ostream)
: ObjectStream(aObjStream, own_ostream)
{
	mObjStream = aObjStream;
}

void ObjectStreamLayer::getBinary(void *buf, uint size, const char *desc)
{
	return mObjStream->getBinary(buf, size, desc);
}

bool ObjectStreamLayer::getBool(const char *desc)
{
	return mObjStream->getBool(desc);
}

uint64 ObjectStreamLayer::getInt(uint size, const char *desc)
{
	return mObjStream->getInt(size, desc);
}

Object *ObjectStreamLayer::getObjectInternal(const char *name, ObjectID id)
{
	return mObjStream->getObjectInternal(name, id);
}

char *ObjectStreamLayer::getString(const char *desc)
{
	return mObjStream->getString(desc);
}

byte *ObjectStreamLayer::getLenString(int &len, const char *desc)
{
	return mObjStream->getLenString(len, desc);
}

void ObjectStreamLayer::putBinary(const void *mem, uint size, const char *desc)
{
	return mObjStream->putBinary(mem, size, desc);
}

void ObjectStreamLayer::putBool(bool b, const char *desc)
{
	return mObjStream->putBool(b, desc);
}

void ObjectStreamLayer::putComment(const char *comment)
{
	return mObjStream->putComment(comment);
}

void ObjectStreamLayer::putInt(uint64 i, uint size, const char *desc, uint int_fmt_hint)
{
	return mObjStream->putInt(i, size, desc, int_fmt_hint);
}

void ObjectStreamLayer::putObject(const Object *object, const char *name, ObjectID id)
{
	return mObjStream->putObject(object, name, id);
}

void ObjectStreamLayer::putSeparator()
{
	return mObjStream->putSeparator();
}

void ObjectStreamLayer::putString(const char *string, const char *desc)
{
	return mObjStream->putString(string, desc);
}

void ObjectStreamLayer::putLenString(const byte *string, int len, const char *desc)
{
	return mObjStream->putLenString(string, len, desc);
}

/*
 *	A File
 */
File::File()
{
	mcount = 0;
}

#define FILE_TRANSFER_BUFSIZE 4*1024
/**
 *	Low-level control function.
 *	@param cmd file control command number
 *	@returns 0 on success, POSIX.1 I/O error code on error
 */
int File::cntl(uint cmd, ...)
{
	va_list vargs;
	va_start(vargs, cmd);
	int ret = vcntl(cmd, vargs);
	va_end(vargs);
	return ret;
}

void File::move(FileOfs src, FileOfs dest, FileOfs size)
{
	if (dest < src) {
		char tbuf[FILE_TRANSFER_BUFSIZE];
		while (size != 0) {
			FileOfs k = size;
			if (k > sizeof tbuf) k = sizeof tbuf;
			seek(src);
			readx(tbuf, k);
			seek(dest);
			writex(tbuf, k);
			src += k;
			dest += k;
			size -= k;
		}
	} else if (dest > src) {
		src += size;
		dest += size;
		char tbuf[FILE_TRANSFER_BUFSIZE];
		while (size != 0) {
			FileOfs k = size;
			if (k > sizeof tbuf) k = sizeof tbuf;
			src -= k;
			dest -= k;
			seek(src);
			readx(tbuf, k);
			seek(dest);
			writex(tbuf, k);
			size -= k;
		}
	}
}

/**
 *	Cut out bytes from file.
 *	Cut out <i>size</i> bytes starting at current file pointer, ending at
 *	current file pointer + <i>size</i>. Does not modify the current file pointer.
 *
 *	@param size number of bytes to delete
 *	@throws IOException
 */
void File::cut(FileOfs size)
{
	FileOfs t = tell();
	FileOfs o = t+size;
	if (o > getSize()) throw IOException(EINVAL);
	FileOfs s = getSize()-o;
	move(o, t, s);
	truncate(getSize()-size);
	seek(t);
}

/**
 *	Extend file.
 *	Extend file to new size <i>newsize</i>.
 *	The current file pointer is undefined (but valid) after this operation.
 *
 *	@param newsize new extended file size
 *	@throws IOException
 */
void File::extend(FileOfs newsize)
{
	if (getSize() > newsize) throw IOException(EINVAL);
	if (getSize() == newsize) return;

	FileOfs save_ofs = tell();
	int e = 0;

	IOAccessMode oldmode = getAccessMode();
	if (!(oldmode & IOAM_WRITE)) {
		int f = setAccessMode(oldmode | IOAM_WRITE);
		if (f) throw IOException(f);
	}

	FileOfs s = getSize();
	char buf[FILE_TRANSFER_BUFSIZE];
	memset(buf, 0, sizeof buf);
	newsize -= s;
	seek(s);
	while (newsize != 0) {
		uint k = MIN(sizeof buf, newsize);
		uint l = write(buf, k);
		if (l != k) {
			e = EIO;
			break;
		}
		newsize -= l;
	}

	if (!(oldmode & IOAM_WRITE)) {
		int f = setAccessMode(oldmode);
		if (f) e = f;
	}
	if (e) throw IOException(e);
	seek(save_ofs);
}

/**
 *	Get filename.
 *
 *	@param result String that receives the filename
 *	@returns its argument
 */
String &File::getFilename(String &result) const
{
	result = "";
	return result;
}

/**
 *	Get file size.
 *
 *	@returns file size
 */
FileOfs File::getSize() const
{
	return 0;
}

#define FILE_INSERT_BUFSIZE 4*1024
/**
 *	Insert bytes into file.
 *	Insert <i>size</i> bytes from <i>buf</i> at the current file pointer
 *	into the file and extend file accordingly.
 *
 *	@param buf pointer to buffer that holds at least <i>size</i> bytes
 *	@param size number of bytes to insert
 *	@throws IOException
 */
void File::insert(const void *buf, FileOfs size)
{
	FileOfs t = tell();
	FileOfs s = getSize()-t;
	extend(getSize()+size);
	move(t, t+size, s);
	seek(t);
	writex(buf, size);
}

/**
 *	Get file status in a portable way.
 *	@param s structure that receives the file status
 */
void File::pstat(pstat_t &s) const
{
	s.caps = 0;
}

/**
 *	Set current file pointer.
 *	@param offset new value for current file pointer
 */
void File::seek(FileOfs offset)
{
	throw NotImplementedException(HERE);
}

/**
 *	Get current file pointer.
 *	@returns current file pointer
 */
FileOfs File::tell() const
{
	return 0;
}

/**
 *	Truncate file.
 *	Truncate file to new size <i>newsize</i>.
 *	The current file pointer is undefined (but valid) after this operation.
 *
 *	@param newsize new truncated file size
 *	@throws IOException
 */
void File::truncate(FileOfs newsize)
{
	if (getSize() < newsize) throw IOException(EINVAL);
	if (getSize() == newsize) return;

	throw NotImplementedException(HERE);
}

/**
 *	Vararg wrapper for cntl()
 */
int File::vcntl(uint cmd, va_list vargs)
{
	switch (cmd) {
		case FCNTL_GET_MOD_COUNT: {	// int &mcount
			int *mc = va_arg(vargs, int *);
			*mc = mcount;
			return 0;
		}
	}
	return ENOSYS;
}

char *File::fgetstrz()
{
	FileOfs o = tell();
	/* get string size */
	char buf[64];
	int s, z = 0;
	bool found = false;
	while (!found) {
		s = read(buf, 64);
		for (int i=0; i < s; i++) {
			z++;
			if (buf[i] == 0) {
				found = true;
				break;
			}
		}
		if (s < 64) {
			break;
		}
	}
	if (s == 0) return ht_strdup("");
	/* read string */
	char *str = ht_malloc(z);
	if (!str) throw std::bad_alloc();
	seek(o);
	readx(str, z);
	str[z-1] = 0;
	return str;
}

/*
 *	FileLayer
 */
FileLayer::FileLayer(File *f, bool own_f) : File()
{
	mFile = f;
	mOwnFile = own_f;
}

FileLayer::~FileLayer()
{
	if (mOwnFile) delete mFile;
}

void FileLayer::cut(FileOfs size)
{
	return mFile->cut(size);
}

void FileLayer::extend(FileOfs newsize)
{
	return mFile->extend(newsize);
}

IOAccessMode FileLayer::getAccessMode() const
{
	return mFile->getAccessMode();
}

String &FileLayer::getDesc(String &result) const
{
	return mFile->getDesc(result);
}

String &FileLayer::getFilename(String &result) const
{
	return mFile->getFilename(result);
}

FileOfs FileLayer::getSize() const
{
	return mFile->getSize();
}

void FileLayer::insert(const void *buf, FileOfs size)
{
	return mFile->insert(buf, size);
}

void FileLayer::pstat(pstat_t &s) const
{
	return mFile->pstat(s);
}

uint FileLayer::read(void *buf, uint size)
{
	return mFile->read(buf, size);
}

void FileLayer::seek(FileOfs offset)
{
	return mFile->seek(offset);
}

int FileLayer::setAccessMode(IOAccessMode mode)
{
	return mFile->setAccessMode(mode);
}

File *FileLayer::getLayered() const
{
	return mFile;
}

void FileLayer::setLayered(File *newLayered, bool ownNewLayered)
{
	mFile = newLayered;
	mOwnFile = ownNewLayered;
}

FileOfs FileLayer::tell() const
{
	return mFile->tell();
}

void FileLayer::truncate(FileOfs newsize)
{
	return mFile->truncate(newsize);
}

int FileLayer::vcntl(uint cmd, va_list vargs)
{
	return mFile->vcntl(cmd, vargs);
}

uint FileLayer::write(const void *buf, uint size)
{
	return mFile->write(buf, size);
}

/*
 *	LocalFileFD
 */

/**
 *	create open file
 */
LocalFileFD::LocalFileFD(const String &aFilename, IOAccessMode am, FileOpenMode om)
 : File(), mFilename(aFilename)
{
	mOpenMode = om;
	fd = -1;
	own_fd = false;
	int e = setAccessMode(am);
	if (e) throw IOException(e);
	mOpenMode = FOM_EXISTS;
}

/**
 *	map a file descriptor [fd]
 */
LocalFileFD::LocalFileFD(int f, bool own_f, IOAccessMode am)
 : File()
{
	mFilename = NULL;
	fd = f;
	own_fd = own_f;
	offset = 0;
	int e = File::setAccessMode(am);
	if (e) throw IOException(e);
}

LocalFileFD::~LocalFileFD()
{
	if (own_fd && (fd>=0)) ::close(fd);
}

String &LocalFileFD::getDesc(String &result) const
{
	result = mFilename;
	return result;
}

String &LocalFileFD::getFilename(String &result) const
{
	result = mFilename;
	return result;
}

FileOfs LocalFileFD::getSize() const
{
	FileOfs t = tell();
	off_t r = ::lseek(fd, 0, SEEK_END);
	if (r == (off_t)-1) return 0;	// hm...
	::lseek(fd, t, SEEK_SET);
	return r;
}

uint LocalFileFD::read(void *buf, uint size)
{
	if (!(getAccessMode() & IOAM_READ)) throw IOException(EACCES);
	errno = 0;
	uint r = ::read(fd, buf, size);
	int e = errno;
	if (e) {
		::lseek(fd, 0, SEEK_SET);
		offset = 0;
		if (e != EAGAIN) throw IOException(e);
		return 0;
	} else {
		offset += r;
		return r;
	}		
}

void LocalFileFD::seek(FileOfs o)
{
	off_t r = ::lseek(fd, o, SEEK_SET);
	if (r == (off_t)-1) throw IOException(errno);
	offset = r;
	if (offset != o) throw IOException(EIO);
}

int LocalFileFD::setAccessMode(IOAccessMode am)
{
	IOAccessMode orig_access_mode = getAccessMode();
	int e = setAccessModeInternal(am);
	if (e && setAccessModeInternal(orig_access_mode))
		throw IOException(e);
	return e;
}

int LocalFileFD::setAccessModeInternal(IOAccessMode am)
{
//RETRY:
	if (getAccessMode() == am) return 0;
	if (fd >= 0) {
		// must own fd to change its access mode cause we can't
		// reopen a fd. right?
		if (!own_fd) throw NotImplementedException(HERE);
		// FIXME: race condition here, how to reopen a fd atomically?
		close(fd);
		fd = -1;
	}
	File::setAccessMode(IOAM_NULL);

	int mode = 0;

	if ((am & IOAM_READ) && (am & IOAM_WRITE)) mode = O_RDWR;
	else if (am & IOAM_READ) mode = O_RDONLY;
	else if (am & IOAM_WRITE) mode = O_WRONLY;

//	mode |= O_BINARY;

	switch (mOpenMode) {
	case FOM_APPEND:
		mode |= O_APPEND;
		break;
	case FOM_CREATE:
		mode |= O_CREAT | O_TRUNC;
		break;
	case FOM_EXISTS:
		;
	}

	int e = 0;
	if (am != IOAM_NULL) {
		pstat_t s;
		fd = ::open(mFilename.contentChar(), mode);
		if (fd < 0) e = errno;
		if (!e) {
			own_fd = true;
			e = sys_pstat_fd(s, fd);
			if (!e) {
				if (HT_S_ISDIR(s.mode)) {
					e = EISDIR;
				} else if (!HT_S_ISREG(s.mode) && !HT_S_ISBLK(s.mode)) {
					e = EINVAL;
				}
			}
		}
	}
	return e ? e : File::setAccessMode(am);
}

FileOfs LocalFileFD::tell() const
{
	return offset;
}

void LocalFileFD::truncate(FileOfs newsize)
{
	errno = 0;
	int e = sys_truncate_fd(fd, newsize);
	if (errno) e = errno;
	if (e) throw IOException(e);
}

int LocalFileFD::vcntl(uint cmd, va_list vargs)
{
	switch (cmd) {
		case FCNTL_FLUSH_STAT: {
			IOAccessMode m = getAccessMode();
			int e, f;
			e = setAccessMode(IOAM_NULL);
			f = setAccessMode(m);
			return e ? e : f;
		}
		case FCNTL_GET_FD: {	// (int &fd)
			int *pfd = va_arg(vargs, int*);
			*pfd = fd;
			return 0;
		}
	}
	return File::vcntl(cmd, vargs);
}

uint LocalFileFD::write(const void *buf, uint size)
{
	if (!(getAccessMode() & IOAM_WRITE)) throw IOException(EACCES);
	errno = 0;
	uint r = ::write(fd, buf, size);
	int e = errno;
	if (e) {
		::lseek(fd, 0, SEEK_SET);
		offset = 0;
		if (e != EAGAIN) throw IOException(e);
		return 0;
	} else {
		offset += r;
		return r;
	}		
}

/*
 *	StdIoFile
 */

/**
 *	create open file
 */
LocalFile::LocalFile(const String &aFilename, IOAccessMode am, FileOpenMode om)
 : File(), mFilename(aFilename)
{
	mOpenMode = om;
	file = NULL;
	own_file = false;
	offset = 0;
	int e = LocalFile::setAccessMode(am);
	if (e) throw IOException(e);
	mOpenMode = FOM_EXISTS;
}

/**
 *	map a file stream [FILE*]
 */
LocalFile::LocalFile(SYS_FILE *f, bool own_f, IOAccessMode am)
 : File()
{
	file = f;
	own_file = own_f;
	File::setAccessMode(am);
}

LocalFile::~LocalFile()
{
	if (own_file && file) sys_fclose(file);
}

String &LocalFile::getDesc(String &result) const
{
	result = mFilename;
	return result;
}

String &LocalFile::getFilename(String &result) const
{
	result = mFilename;
	return result;
}

FileOfs LocalFile::getSize() const
{
	FileOfs t = tell();
	sys_fseek(file, 0, SYS_SEEK_END);
	FileOfs r = sys_ftell(file);
	sys_fseek(file, t, SYS_SEEK_SET);
	return r;
}

void LocalFile::pstat(pstat_t &s) const
{
	sys_pstat_file(s, file);
}

uint LocalFile::read(void *buf, uint size)
{
	if (!(getAccessMode() & IOAM_READ)) throw IOException(EACCES);
	errno = 0;
	uint r = sys_fread(file, (byte*)buf, size);
	if (errno) throw IOException(errno);
	offset += r;
	return r;
}

void LocalFile::seek(FileOfs o)
{
	int e = sys_fseek(file, o, SYS_SEEK_SET);
	if (e) throw IOException(e);
	offset = o;
}

int LocalFile::setAccessMode(IOAccessMode am)
{
	IOAccessMode orig_access_mode = getAccessMode();
	int e = setAccessModeInternal(am);
	if (e && setAccessModeInternal(orig_access_mode))
		throw IOException(e);
	return e;
}

int LocalFile::setAccessModeInternal(IOAccessMode am)
{
//RETRY:
	if (getAccessMode() == am) return 0;

	int e = 0;
	if (am != IOAM_NULL) {
		pstat_t s;
		if (file) {
			file = sys_freopen(mFilename.contentChar(), mOpenMode, am, file);
			if (!file) setAccessMode(IOAM_NULL);
		} else {
			file = sys_fopen(mFilename.contentChar(), mOpenMode, am);
		}
		if (!file) e = errno;
		if (!e) {
			own_file = true;
			e = sys_pstat_file(s, file);
			if (!e) {
				if (HT_S_ISDIR(s.mode)) {
					e = EISDIR;
				} else if (!HT_S_ISREG(s.mode) && !HT_S_ISBLK(s.mode)) {
					e = EINVAL;
				}
			}
		}
	} else {
		if (file) {
			sys_fclose(file);
			file = NULL;
		}
	}
	return e ? e : File::setAccessMode(am);
}

FileOfs LocalFile::tell() const
{
	return offset;
}

void LocalFile::truncate(FileOfs newsize)
{
	errno = 0;

	IOAccessMode old_am = getAccessMode();
	int e;
	e = setAccessMode(IOAM_NULL);
	if (!e) {
		e = sys_truncate(mFilename.contentChar(), newsize);
		if (errno) e = errno;
	}
	if (!e) e = setAccessMode(old_am);
	if (e) throw IOException(e);
}

int LocalFile::vcntl(uint cmd, va_list vargs)
{
	switch (cmd) {
	case FCNTL_FLUSH_STAT: {
		IOAccessMode m = getAccessMode();
		int e, f;
		e = setAccessMode(IOAM_NULL);
		f = setAccessMode(m);
		return e ? e : f;
	}
	case FCNTL_GET_FD: 	// (int &fd)
/*		if (file) {
			int *pfd = va_arg(vargs, int*);
			*pfd = fileno(file);
			return 0;
		}*/
		// FIXME:
		assert(0);
		break;
	}
	return File::vcntl(cmd, vargs);
}

uint LocalFile::write(const void *buf, uint size)
{
	if (!(getAccessMode() & IOAM_WRITE)) throw IOException(EACCES);
	errno = 0;
	uint r = sys_fwrite(file, (byte*)buf, size);
	if (errno) throw IOException(errno);
	offset += r;
	return r;
}

/*
 *	TempFile
 */
TempFile::TempFile(uint am) : LocalFile(tmpfile(), true, am)
{
}

String &TempFile::getDesc(String &result) const
{
	result = "temporary file";
	return result;
}

void TempFile::pstat(pstat_t &s) const
{
	s.caps = pstat_size;
	s.size = getSize();
}

/*
 *	MemMapFile
 */
MemMapFile::MemMapFile(void *b, uint s, FileOfs ofs) : ConstMemMapFile(b, s, ofs)
{
}

uint MemMapFile::write(const void *b, uint size)
{
	if (pos > this->size) return 0;	// or throw exception?
	if (pos+size > this->size) size = this->size - pos;
	memcpy(((byte*)buf) + pos, b, size);
	pos += size;
	return size;
}

/*
 *	ConstMemMapFile
 */
ConstMemMapFile::ConstMemMapFile(const void *b, uint s, FileOfs o)
: File()
{
	buf = b;
	pos = 0;
	size = s;
	ofs = o;
}

String &ConstMemMapFile::getDesc(String &result) const
{
	result = "ConstMemMapFile";
	return result;
}

FileOfs ConstMemMapFile::getSize() const
{
	return size;
}

uint ConstMemMapFile::read(void *b, uint size)
{
	if (pos > this->size) return 0;
	if (pos+size > this->size) size = this->size - pos;
	memcpy(b, (const byte*)buf+pos, size);
	pos += size;
	return size;
}

void ConstMemMapFile::seek(FileOfs offset)
{
	pos = offset - ofs;
}

FileOfs ConstMemMapFile::tell() const
{
	return pos + ofs;
}

/*
 *	NullFile
 */
NullFile::NullFile() : File()
{
}

void NullFile::extend(FileOfs newsize)
{
	if (newsize != 0) throw IOException(EINVAL);
}

String &NullFile::getDesc(String &result) const
{
	result = "null device";
	return result;
}

FileOfs NullFile::getSize() const
{
	return 0;
}

void NullFile::pstat(pstat_t &s) const
{
	s.caps = pstat_size;
	s.size = getSize();
}

uint NullFile::read(void *buf, uint size)
{
	return 0;
}

void NullFile::seek(FileOfs offset)
{
	if (offset != 0) throw IOException(EINVAL);
}

int NullFile::setAccessMode(IOAccessMode am)
{
	return (am == getAccessMode()) ? 0 : EACCES;
}

FileOfs NullFile::tell() const
{
	return 0;
}

void NullFile::truncate(FileOfs newsize)
{
	if (newsize != 0) throw IOException(EINVAL);
}

uint NullFile::write(const void *buf, uint size)
{
	return 0;
}

/*
 *	MemoryFile
 */
#define MEMORYFILE_GROW_FACTOR_NUM		4
#define MEMORYFILE_GROW_FACTOR_DENOM		3
#define MEMORYFILE_MIN_BUFSIZE			32

MemoryFile::MemoryFile(FileOfs o, uint size, IOAccessMode mode) : File()
{
	ofs = o;
	dsize = size;
	buf = NULL;
	ibufsize = size;
	if (ibufsize < MEMORYFILE_MIN_BUFSIZE) ibufsize = MEMORYFILE_MIN_BUFSIZE;
	resizeBuf(ibufsize);
	memset(buf, 0, dsize);
	mcount = 0;

	pos = 0;
	int e = setAccessMode(mode);
	if (e) throw IOException(e);
}

MemoryFile::~MemoryFile()
{
	free(buf);
}

byte *MemoryFile::getBufPtr() const
{
	return buf;
}

void MemoryFile::extend(FileOfs newsize)
{
	// MemoryFiles may not be > 2G
	if (newsize > 0x7fffffff) throw IOException(EINVAL);
	if (newsize < getSize()) throw IOException(EINVAL);
	if (newsize == getSize()) return;
	while (bufsize<newsize) extendBuf();
	memset(buf+dsize, 0, newsize-dsize);
	dsize = newsize;
	mcount++;
}

void MemoryFile::extendBuf()
{
	resizeBuf(extendBufSize(bufsize));
}

uint MemoryFile::extendBufSize(uint bufsize)
{
	return bufsize * MEMORYFILE_GROW_FACTOR_NUM / MEMORYFILE_GROW_FACTOR_DENOM;
}

IOAccessMode MemoryFile::getAccessMode() const
{
	return Stream::getAccessMode();
}

String &MemoryFile::getDesc(String &result) const
{
	result = "MemoryFile";
	return result;
}

FileOfs MemoryFile::getSize() const
{
	return dsize;
}

void MemoryFile::pstat(pstat_t &s) const
{
	s.caps = pstat_size;
	s.size = getSize();
}

uint MemoryFile::read(void *b, uint size)
{
	if (pos+size > dsize) {
		if (pos >= dsize) return 0;
		size = dsize-pos;
	}
	memcpy(b, buf+pos, size);
	pos += size;
	return size;
}

void MemoryFile::resizeBuf(uint newsize)
{
	bufsize = newsize;

	assert(dsize <= bufsize);

	buf = (byte*)realloc(buf, bufsize ? bufsize : 1);
	if (!buf) throw std::bad_alloc();
}

void MemoryFile::seek(FileOfs o)
{
	if (o<ofs) throw IOException(EINVAL);
	pos = o-ofs;
}

int MemoryFile::setAccessMode(IOAccessMode mode)
{
	int e = Stream::setAccessMode(mode);
	if (e) return e;
	seek(ofs);
	return 0;
}

uint MemoryFile::shrinkBufSize(uint bufsize)
{
	return bufsize * MEMORYFILE_GROW_FACTOR_DENOM / MEMORYFILE_GROW_FACTOR_NUM;
}

void MemoryFile::shrinkBuf()
{
	resizeBuf(shrinkBufSize(bufsize));
}

FileOfs MemoryFile::tell() const
{
	return pos+ofs;
}

void MemoryFile::truncate(FileOfs newsize)
{
	dsize = newsize;

	uint s = ibufsize;
	while (s<dsize) s = extendBufSize(s);
	
	resizeBuf(s);
	mcount++;
}

uint MemoryFile::write(const void *b, uint size)
{
	while (pos+size >= bufsize) extendBuf();
	memcpy(((byte*)buf) + pos, b, size);
	pos += size;
	if (pos > dsize) dsize = pos;
	mcount++;
	return size;
}

/*
 *	A file layer, representing a cropped version of a file
 */
CroppedFile::CroppedFile(File *file, bool own_file, FileOfs aCropStart, FileOfs aCropSize)
: FileLayer(file, own_file)
{
	mCropStart = aCropStart;
	mHasCropSize = true;
	mCropSize = aCropSize;
	seek(0);
}

CroppedFile::CroppedFile(File *file, bool own_file, FileOfs aCropStart)
: FileLayer(file, own_file)
{
	mCropStart = aCropStart;
	mHasCropSize = false;
	seek(0);
}

void CroppedFile::extend(FileOfs newsize)
{
	throw IOException(ENOSYS);
}

String &CroppedFile::getDesc(String &result) const
{
	String s;
	if (mHasCropSize) {
		result.assignFormat("[->%qx,%qx] of %y", mCropStart, mCropSize, &FileLayer::getDesc(s));
	} else {
		result.assignFormat("[->%qx,...] of %y", mCropStart, &FileLayer::getDesc(s));
	}
	return result;
}

FileOfs	CroppedFile::getSize() const
{
	FileOfs lsize = FileLayer::getSize();
	if (lsize < mCropStart) return 0;
	lsize -= mCropStart;
	if (mHasCropSize) {
		if (lsize > mCropSize) lsize = mCropSize;
	}
	return lsize;
}

void CroppedFile::pstat(pstat_t &s) const
{
	FileLayer::pstat(s);
	if (s.caps & pstat_size) {
		s.size = getSize();
	}
}

uint CroppedFile::read(void *buf, uint size)
{
	FileOfs offset = FileLayer::tell();
	if (offset<mCropStart) return 0;
	if (mHasCropSize) {
		if (offset >= mCropStart+mCropSize) return 0;
		if (offset+size >= mCropStart+mCropSize) size = mCropStart+mCropSize-offset;
	}
	return FileLayer::read(buf, size);
}

void CroppedFile::seek(FileOfs offset)
{
/*	if (mHasCropSize) {
...
		if (offset>mCropStart) throw IOException(EIO);
	}*/
	FileLayer::seek(offset+mCropStart);
}

FileOfs CroppedFile::tell() const
{
	FileOfs offset = FileLayer::tell();
	if (offset < mCropStart) throw IOException(EIO);
	return offset - mCropStart;
}

void CroppedFile::truncate(FileOfs newsize)
{
	// not implemented because not considered safe
	throw IOException(ENOSYS);
}

uint CroppedFile::write(const void *buf, uint size)
{
	FileOfs offset = FileLayer::tell();
	if (offset<mCropStart) return 0;
	if (mHasCropSize) {
		if (offset >= mCropStart+mCropSize) return 0;
		if (offset+size >= mCropStart+mCropSize) size = mCropStart+mCropSize-offset;
	}
	return FileLayer::write(buf, size);
}