File: mptIO.h

package info (click to toggle)
libopenmpt 0.4.3-1+deb10u1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 7,724 kB
  • sloc: cpp: 99,820; sh: 4,503; ansic: 3,449; makefile: 480
file content (1080 lines) | stat: -rw-r--r-- 26,146 bytes parent folder | download
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
/*
 * mptIO.h
 * -------
 * Purpose: Basic functions for reading/writing binary and endian safe data to/from files/streams.
 * Notes  : Some useful functions for reading and writing are still missing.
 * Authors: Joern Heusipp
 *          OpenMPT Devs
 * The OpenMPT source code is released under the BSD license. Read LICENSE for more details.
 */


#pragma once

#include "BuildSettings.h"


#include "../common/Endianness.h"
#include <algorithm>
#include <array>
#include <iosfwd>
#include <limits>
#include <cstring>


OPENMPT_NAMESPACE_BEGIN


namespace mpt {

namespace IO {

typedef int64 Offset;

static constexpr std::size_t BUFFERSIZE_TINY   =    1 * 1024; // on stack usage
static constexpr std::size_t BUFFERSIZE_SMALL  =    4 * 1024; // on heap
static constexpr std::size_t BUFFERSIZE_NORMAL =   64 * 1024; // FILE I/O
static constexpr std::size_t BUFFERSIZE_LARGE  = 1024 * 1024;



// Returns true iff 'off' fits into 'Toff'.
template < typename Toff >
inline bool OffsetFits(IO::Offset off)
{
	return (static_cast<IO::Offset>(mpt::saturate_cast<Toff>(off)) == off);
}



bool IsValid(std::ostream & f);
bool IsValid(std::istream & f);
bool IsValid(std::iostream & f);
IO::Offset TellRead(std::istream & f);
IO::Offset TellWrite(std::ostream & f);
bool SeekBegin(std::ostream & f);
bool SeekBegin(std::istream & f);
bool SeekBegin(std::iostream & f);
bool SeekEnd(std::ostream & f);
bool SeekEnd(std::istream & f);
bool SeekEnd(std::iostream & f);
bool SeekAbsolute(std::ostream & f, IO::Offset pos);
bool SeekAbsolute(std::istream & f, IO::Offset pos);
bool SeekAbsolute(std::iostream & f, IO::Offset pos);
bool SeekRelative(std::ostream & f, IO::Offset off);
bool SeekRelative(std::istream & f, IO::Offset off);
bool SeekRelative(std::iostream & f, IO::Offset off);
IO::Offset ReadRawImpl(std::istream & f, mpt::byte * data, std::size_t size);
bool WriteRawImpl(std::ostream & f, const mpt::byte * data, std::size_t size);
bool IsEof(std::istream & f);
bool Flush(std::ostream & f);



template <typename Tfile> class WriteBuffer;

template <typename Tfile> bool IsValid(WriteBuffer<Tfile> & f) { return IsValid(f.file()); }
template <typename Tfile> IO::Offset TellRead(WriteBuffer<Tfile> & f) { return TellRead(f.file()); }
template <typename Tfile> IO::Offset TellWrite(WriteBuffer<Tfile> & f) { return TellWrite(f.file()); }
template <typename Tfile> bool SeekBegin(WriteBuffer<Tfile> & f) { return SeekBegin(f.file()); }
template <typename Tfile> bool SeekEnd(WriteBuffer<Tfile> & f) { return SeekEnd(f.file()); }
template <typename Tfile> bool SeekAbsolute(WriteBuffer<Tfile> & f, IO::Offset pos) { return SeekAbsolute(f.file(), pos); }
template <typename Tfile> bool SeekRelative(WriteBuffer<Tfile> & f, IO::Offset off) { return SeekRelative(f.file(), off); }
template <typename Tfile> IO::Offset ReadRawImpl(WriteBuffer<Tfile> & f, mpt::byte * data, std::size_t size) { return ReadRawImpl(f.file(), data, size); }
template <typename Tfile> bool WriteRawImpl(WriteBuffer<Tfile> & f, const mpt::byte * data, std::size_t size) { return f.Write(mpt::as_span(data, size)); }
template <typename Tfile> bool IsEof(WriteBuffer<Tfile> & f) { return IsEof(f.file()); }
template <typename Tfile> bool Flush(WriteBuffer<Tfile> & f) { return Flush(f.file()); }





template <typename Tbyte> bool IsValid(std::pair<mpt::span<Tbyte>, IO::Offset> & f)
{
	return (f.second >= 0);
}
template <typename Tbyte> IO::Offset TellRead(std::pair<mpt::span<Tbyte>, IO::Offset> & f)
{
	return f.second;
}
template <typename Tbyte> IO::Offset TellWrite(std::pair<mpt::span<Tbyte>, IO::Offset> & f)
{
	return f.second;
}
template <typename Tbyte> bool SeekBegin(std::pair<mpt::span<Tbyte>, IO::Offset> & f)
{
	f.second = 0;
	return true;
}
template <typename Tbyte> bool SeekEnd(std::pair<mpt::span<Tbyte>, IO::Offset> & f)
{
	f.second = f.first.size();
	return true;
}
template <typename Tbyte> bool SeekAbsolute(std::pair<mpt::span<Tbyte>, IO::Offset> & f, IO::Offset pos)
{
	f.second = pos;
	return true;
}
template <typename Tbyte> bool SeekRelative(std::pair<mpt::span<Tbyte>, IO::Offset> & f, IO::Offset off)
{
	if(f.second < 0)
	{
		return false;
	}
	f.second += off;
	return true;
}
template <typename Tbyte> IO::Offset ReadRawImpl(std::pair<mpt::span<Tbyte>, IO::Offset> & f, mpt::byte * data, std::size_t size)
{
	if(f.second < 0)
	{
		return 0;
	}
	if(f.second >= static_cast<IO::Offset>(f.first.size()))
	{
		return 0;
	}
	std::size_t num = mpt::saturate_cast<std::size_t>(std::min<IO::Offset>(f.first.size() - f.second, size));
	std::copy(mpt::byte_cast<const mpt::byte*>(f.first.data() + f.second), mpt::byte_cast<const mpt::byte*>(f.first.data() + f.second + num), data);
	f.second += num;
	return num;
}
template <typename Tbyte> bool WriteRawImpl(std::pair<mpt::span<Tbyte>, IO::Offset> & f, const mpt::byte * data, std::size_t size)
{
	if(f.second < 0)
	{
		return false;
	}
	if(f.second >= static_cast<IO::Offset>(f.first.size()))
	{
		return false;
	}
	std::size_t num = mpt::saturate_cast<std::size_t>(std::min<IO::Offset>(f.first.size() - f.second, size));
	if(num != size)
	{
		return false;
	}
	std::copy(data, data + num, mpt::byte_cast<mpt::byte*>(f.first.data() + f.second));
	f.second += num;
	return true;
}
template <typename Tbyte> bool IsEof(std::pair<mpt::span<Tbyte>, IO::Offset> & f)
{
	return (f.second >= static_cast<IO::Offset>(f.first.size()));
}
template <typename Tbyte> bool Flush(std::pair<mpt::span<Tbyte>, IO::Offset> & f)
{
	MPT_UNREFERENCED_PARAMTER(f);
	return true;
}



template <typename Tbyte, typename Tfile>
inline IO::Offset ReadRaw(Tfile & f, Tbyte * data, std::size_t size)
{
	return IO::ReadRawImpl(f, mpt::byte_cast<mpt::byte*>(data), size);
}

template <typename Tbyte, typename Tfile>
inline IO::Offset ReadRaw(Tfile & f, mpt::span<Tbyte> data)
{
	return IO::ReadRawImpl(f, mpt::byte_cast<mpt::byte*>(data.data()), data.size());
}

template <typename Tbyte, typename Tfile>
inline bool WriteRaw(Tfile & f, const Tbyte * data, std::size_t size)
{
	return IO::WriteRawImpl(f, mpt::byte_cast<const mpt::byte*>(data), size);
}

template <typename Tbyte, typename Tfile>
inline bool WriteRaw(Tfile & f, mpt::span<Tbyte> data)
{
	return IO::WriteRawImpl(f, mpt::byte_cast<const mpt::byte*>(data.data()), data.size());
}

template <typename Tbinary, typename Tfile>
inline bool Read(Tfile & f, Tbinary & v)
{
	return IO::ReadRaw(f, mpt::as_raw_memory(v)) == mpt::saturate_cast<mpt::IO::Offset>(mpt::as_raw_memory(v).size());
}

template <typename Tbinary, typename Tfile>
inline bool Write(Tfile & f, const Tbinary & v)
{
	return IO::WriteRaw(f, mpt::as_raw_memory(v));
}

template <typename Tbinary, typename Tfile>
inline bool Write(Tfile & f, const std::vector<Tbinary> & v)
{
	STATIC_ASSERT(mpt::is_binary_safe<Tbinary>::value);
	return IO::WriteRaw(f, mpt::as_raw_memory(v));
}

template <typename T, typename Tfile>
inline bool WritePartial(Tfile & f, const T & v, size_t size = sizeof(T))
{
	MPT_ASSERT(size <= sizeof(T));
	return IO::WriteRaw(f, mpt::as_span(mpt::as_raw_memory(v).data(), size));
}

template <typename Tfile>
inline bool ReadByte(Tfile & f, mpt::byte & v)
{
	bool result = false;
	mpt::byte byte = mpt::as_byte(0);
	const IO::Offset readResult = IO::ReadRaw(f, &byte, sizeof(mpt::byte));
	if(readResult < 0)
	{
		result = false;
	} else
	{
		result = (static_cast<uint64>(readResult) == sizeof(mpt::byte));
	}
	v = byte;
	return result;
}

template <typename T, typename Tfile>
inline bool ReadBinaryTruncatedLE(Tfile & f, T & v, std::size_t size)
{
	bool result = false;
	MPT_STATIC_ASSERT(std::numeric_limits<T>::is_integer);
	uint8 bytes[sizeof(T)];
	std::memset(bytes, 0, sizeof(T));
	const IO::Offset readResult = IO::ReadRaw(f, bytes, std::min(size, sizeof(T)));
	if(readResult < 0)
	{
		result = false;
	} else
	{
		result = (static_cast<uint64>(readResult) == std::min(size, sizeof(T)));
	}
	typename mpt::make_le<T>::type val;
	std::memcpy(&val, bytes, sizeof(T));
	v = val;
	return result;
}

template <typename T, typename Tfile>
inline bool ReadIntLE(Tfile & f, T & v)
{
	bool result = false;
	STATIC_ASSERT(std::numeric_limits<T>::is_integer);
	uint8 bytes[sizeof(T)];
	std::memset(bytes, 0, sizeof(T));
	const IO::Offset readResult = IO::ReadRaw(f, bytes, sizeof(T));
	if(readResult < 0)
	{
		result = false;
	} else
	{
		result = (static_cast<uint64>(readResult) == sizeof(T));
	}
	typename mpt::make_le<T>::type val;
	std::memcpy(&val, bytes, sizeof(T));
	v = val;
	return result;
}

template <typename T, typename Tfile>
inline bool ReadIntBE(Tfile & f, T & v)
{
	bool result = false;
	STATIC_ASSERT(std::numeric_limits<T>::is_integer);
	uint8 bytes[sizeof(T)];
	std::memset(bytes, 0, sizeof(T));
	const IO::Offset readResult = IO::ReadRaw(f, bytes, sizeof(T));
	if(readResult < 0)
	{
		result = false;
	} else
	{
		result = (static_cast<uint64>(readResult) == sizeof(T));
	}
	typename mpt::make_be<T>::type val;
	std::memcpy(&val, bytes, sizeof(T));
	v = val;
	return result;
}

template <typename Tfile>
inline bool ReadAdaptiveInt16LE(Tfile & f, uint16 & v)
{
	bool result = true;
	uint8 byte = 0;
	std::size_t additionalBytes = 0;
	v = 0;
	byte = 0;
	if(!IO::ReadIntLE<uint8>(f, byte)) result = false;
	additionalBytes = (byte & 0x01);
	v = byte >> 1;
	for(std::size_t i = 0; i < additionalBytes; ++i)
	{
		byte = 0;
		if(!IO::ReadIntLE<uint8>(f, byte)) result = false;
		v |= (static_cast<uint16>(byte) << (((i+1)*8) - 1));
	}
	return result;
}

template <typename Tfile>
inline bool ReadAdaptiveInt32LE(Tfile & f, uint32 & v)
{
	bool result = true;
	uint8 byte = 0;
	std::size_t additionalBytes = 0;
	v = 0;
	byte = 0;
	if(!IO::ReadIntLE<uint8>(f, byte)) result = false;
	additionalBytes = (byte & 0x03);
	v = byte >> 2;
	for(std::size_t i = 0; i < additionalBytes; ++i)
	{
		byte = 0;
		if(!IO::ReadIntLE<uint8>(f, byte)) result = false;
		v |= (static_cast<uint32>(byte) << (((i+1)*8) - 2));
	}
	return result;
}

template <typename Tfile>
inline bool ReadAdaptiveInt64LE(Tfile & f, uint64 & v)
{
	bool result = true;
	uint8 byte = 0;
	std::size_t additionalBytes = 0;
	v = 0;
	byte = 0;
	if(!IO::ReadIntLE<uint8>(f, byte)) result = false;
	additionalBytes = (1 << (byte & 0x03)) - 1;
	v = byte >> 2;
	for(std::size_t i = 0; i < additionalBytes; ++i)
	{
		byte = 0;
		if(!IO::ReadIntLE<uint8>(f, byte)) result = false;
		v |= (static_cast<uint64>(byte) << (((i+1)*8) - 2));
	}
	return result;
}

template <typename Tsize, typename Tfile>
inline bool ReadSizedStringLE(Tfile & f, std::string & str, Tsize maxSize = std::numeric_limits<Tsize>::max())
{
	STATIC_ASSERT(std::numeric_limits<Tsize>::is_integer);
	str.clear();
	Tsize size = 0;
	if(!mpt::IO::ReadIntLE(f, size))
	{
		return false;
	}
	if(size > maxSize)
	{
		return false;
	}
	for(Tsize i = 0; i != size; ++i)
	{
		char c = '\0';
		if(!mpt::IO::ReadIntLE(f, c))
		{
			return false;
		}
		str.push_back(c);
	}
	return true;
}


template <typename T, typename Tfile>
inline bool WriteIntLE(Tfile & f, const T v)
{
	STATIC_ASSERT(std::numeric_limits<T>::is_integer);
	return IO::Write(f, mpt::as_le(v));
}

template <typename T, typename Tfile>
inline bool WriteIntBE(Tfile & f, const T v)
{
	STATIC_ASSERT(std::numeric_limits<T>::is_integer);
	return IO::Write(f, mpt::as_be(v));
}

template <typename Tfile>
inline bool WriteAdaptiveInt16LE(Tfile & f, const uint16 v, std::size_t fixedSize = 0)
{
	std::size_t minSize = fixedSize;
	std::size_t maxSize = fixedSize;
	MPT_ASSERT(minSize == 0 || minSize == 1 || minSize == 2);
	MPT_ASSERT(maxSize == 0 || maxSize == 1 || maxSize == 2);
	MPT_ASSERT(maxSize == 0 || maxSize >= minSize);
	if(maxSize == 0)
	{
		maxSize = 2;
	}
	if(v < 0x80 && minSize <= 1 && 1 <= maxSize)
	{
		return IO::WriteIntLE<uint8>(f, static_cast<uint8>(v << 1) | 0x00);
	} else if(v < 0x8000 && minSize <= 2 && 2 <= maxSize)
	{
		return IO::WriteIntLE<uint16>(f, static_cast<uint16>(v << 1) | 0x01);
	} else
	{
		MPT_ASSERT_NOTREACHED();
		return false;
	}
}

template <typename Tfile>
inline bool WriteAdaptiveInt32LE(Tfile & f, const uint32 v, std::size_t fixedSize = 0)
{
	std::size_t minSize = fixedSize;
	std::size_t maxSize = fixedSize;
	MPT_ASSERT(minSize == 0 || minSize == 1 || minSize == 2 || minSize == 3 || minSize == 4);
	MPT_ASSERT(maxSize == 0 || maxSize == 1 || maxSize == 2 || maxSize == 3 || maxSize == 4);
	MPT_ASSERT(maxSize == 0 || maxSize >= minSize);
	if(maxSize == 0)
	{
		maxSize = 4;
	}
	if(v < 0x40 && minSize <= 1 && 1 <= maxSize)
	{
		return IO::WriteIntLE<uint8>(f, static_cast<uint8>(v << 2) | 0x00);
	} else if(v < 0x4000 && minSize <= 2 && 2 <= maxSize)
	{
		return IO::WriteIntLE<uint16>(f, static_cast<uint16>(v << 2) | 0x01);
	} else if(v < 0x400000 && minSize <= 3 && 3 <= maxSize)
	{
		uint32 value = static_cast<uint32>(v << 2) | 0x02;
		mpt::byte bytes[3];
		bytes[0] = static_cast<mpt::byte>(value >>  0);
		bytes[1] = static_cast<mpt::byte>(value >>  8);
		bytes[2] = static_cast<mpt::byte>(value >> 16);
		return IO::WriteRaw(f, bytes, 3);
	} else if(v < 0x40000000 && minSize <= 4 && 4 <= maxSize)
	{
		return IO::WriteIntLE<uint32>(f, static_cast<uint32>(v << 2) | 0x03);
	} else
	{
		MPT_ASSERT_NOTREACHED();
		return false;
	}
}

template <typename Tfile>
inline bool WriteAdaptiveInt64LE(Tfile & f, const uint64 v, std::size_t fixedSize = 0)
{
	std::size_t minSize = fixedSize;
	std::size_t maxSize = fixedSize;
	MPT_ASSERT(minSize == 0 || minSize == 1 || minSize == 2 || minSize == 4 || minSize == 8);
	MPT_ASSERT(maxSize == 0 || maxSize == 1 || maxSize == 2 || maxSize == 4 || maxSize == 8);
	MPT_ASSERT(maxSize == 0 || maxSize >= minSize);
	if(maxSize == 0)
	{
		maxSize = 8;
	}
	if(v < 0x40 && minSize <= 1 && 1 <= maxSize)
	{
		return IO::WriteIntLE<uint8>(f, static_cast<uint8>(v << 2) | 0x00);
	} else if(v < 0x4000 && minSize <= 2 && 2 <= maxSize)
	{
		return IO::WriteIntLE<uint16>(f, static_cast<uint16>(v << 2) | 0x01);
	} else if(v < 0x40000000 && minSize <= 4 && 4 <= maxSize)
	{
		return IO::WriteIntLE<uint32>(f, static_cast<uint32>(v << 2) | 0x02);
	} else if(v < 0x4000000000000000ull && minSize <= 8 && 8 <= maxSize)
	{
		return IO::WriteIntLE<uint64>(f, static_cast<uint64>(v << 2) | 0x03);
	} else
	{
		MPT_ASSERT_NOTREACHED();
		return false;
	}
}

// Write a variable-length integer, as found in MIDI files. The number of written bytes is placed in the bytesWritten parameter.
template <typename Tfile, typename T>
bool WriteVarInt(Tfile & f, const T v, size_t *bytesWritten = nullptr)
{
	STATIC_ASSERT(std::numeric_limits<T>::is_integer);
	STATIC_ASSERT(!std::numeric_limits<T>::is_signed);
	mpt::byte out[(sizeof(T) * 8 + 6) / 7];
	size_t numBytes = 0;
	for(uint32 n = (sizeof(T) * 8) / 7; n > 0; n--)
	{
		if(v >= (static_cast<T>(1) << (n * 7u)))
		{
			out[numBytes++] = static_cast<mpt::byte>(((v >> (n * 7u)) & 0x7F) | 0x80);
		}
	}
	out[numBytes++] = static_cast<mpt::byte>(v & 0x7F);
	MPT_ASSERT(numBytes <= mpt::size(out));
	if(bytesWritten != nullptr) *bytesWritten = numBytes;
	return mpt::IO::WriteRaw(f, out, numBytes);
}

template <typename Tsize, typename Tfile>
inline bool WriteSizedStringLE(Tfile & f, const std::string & str)
{
	STATIC_ASSERT(std::numeric_limits<Tsize>::is_integer);
	if(str.size() > std::numeric_limits<Tsize>::max())
	{
		return false;
	}
	Tsize size = static_cast<Tsize>(str.size());
	if(!mpt::IO::WriteIntLE(f, size))
	{
		return false;
	}
	if(!mpt::IO::WriteRaw(f, str.data(), str.size()))
	{
		return false;
	}
	return true;
}

template <typename Tfile>
inline bool WriteText(Tfile &f, const std::string &s)
{
	return mpt::IO::WriteRaw(f, s.data(), s.size());
}

template <typename Tfile>
inline bool WriteTextCRLF(Tfile &f)
{
	return mpt::IO::WriteText(f, "\r\n");
}

template <typename Tfile>
inline bool WriteTextLF(Tfile &f)
{
	return mpt::IO::WriteText(f, "\n");
}

template <typename Tfile>
inline bool WriteTextCRLF(Tfile &f, const std::string &s)
{
	return mpt::IO::WriteText(f, s) && mpt::IO::WriteTextCRLF(f);
}

template <typename Tfile>
inline bool WriteTextLF(Tfile &f, const std::string &s)
{
	return mpt::IO::WriteText(f, s) && mpt::IO::WriteTextLF(f);
}



// WriteBuffer class that avoids calling to the underlying file writing
// functions for every operation, which would involve rather slow un-inlinable
// virtual calls in the iostream and FILE* cases. It is the users responabiliy
// to call HasWriteError() to check for writeback errors at this buffering
// level.

template <typename Tfile>
class WriteBuffer
{
private:
	mpt::byte_span buffer;
	std::size_t size = 0;
	Tfile & f;
	bool writeError = false;
public:
	WriteBuffer(const WriteBuffer &) = delete;
	WriteBuffer & operator=(const WriteBuffer &) = delete;
public:
	inline WriteBuffer(Tfile & f_, mpt::byte_span buffer_)
		: buffer(buffer_)
		, f(f_)
	{
	}
	inline ~WriteBuffer() noexcept(false)
	{
		if(!writeError)
		{
			FlushLocal();
		}
	}
public:
	inline Tfile & file() const
	{
		if(IsDirty())
		{
			FlushLocal();
		}
		return f;
	}
public:
	inline bool HasWriteError() const
	{
		return writeError;
	}
	inline void ClearError()
	{
		writeError = false;
	}
	inline bool IsDirty() const
	{
		return size > 0;
	}
	inline bool IsClean() const
	{
		return size == 0;
	}
	inline bool IsFull() const
	{
		return size == buffer.size();
	}
	inline bool Write(mpt::const_byte_span data)
	{
		bool result = true;
		for(std::size_t i = 0; i < data.size(); ++i)
		{
			buffer[size] = data[i];
			size++;
			if(IsFull())
			{
				FlushLocal();
			}
		}
		return result;
	}
	inline void FlushLocal()
	{
		if(IsClean())
		{
			return;
		}
		try
		{
			if(!mpt::IO::WriteRaw(f, mpt::as_span(buffer.data(), size)))
			{
				writeError = true;
			}
		} catch (const std::exception &)
		{
			writeError = true;
			throw;
		}
		size = 0;
	}
};



} // namespace IO


} // namespace mpt



#if defined(MPT_FILEREADER_STD_ISTREAM)

class IFileDataContainer {
public:
	typedef std::size_t off_t;
protected:
	IFileDataContainer() = default;
public:
	IFileDataContainer(const IFileDataContainer&) = default;
	IFileDataContainer & operator=(const IFileDataContainer&) = default;
	virtual ~IFileDataContainer() = default;
public:
	virtual bool IsValid() const = 0;
	virtual bool HasFastGetLength() const = 0;
	virtual bool HasPinnedView() const = 0;
	virtual const mpt::byte *GetRawData() const = 0;
	virtual off_t GetLength() const = 0;
	virtual off_t Read(mpt::byte *dst, off_t pos, off_t count) const = 0;

	virtual off_t Read(off_t pos, mpt::byte_span dst) const
	{
		return Read(dst.data(), pos, dst.size());
	}

	virtual bool CanRead(off_t pos, off_t length) const
	{
		off_t dataLength = GetLength();
		if((pos == dataLength) && (length == 0))
		{
			return true;
		}
		if(pos >= dataLength)
		{
			return false;
		}
		return length <= dataLength - pos;
	}

	virtual off_t GetReadableLength(off_t pos, off_t length) const
	{
		off_t dataLength = GetLength();
		if(pos >= dataLength)
		{
			return 0;
		}
		return std::min<off_t>(length, dataLength - pos);
	}
};


class FileDataContainerDummy : public IFileDataContainer {
public:
	FileDataContainerDummy() { }
public:
	bool IsValid() const override
	{
		return false;
	}

	bool HasFastGetLength() const override
	{
		return true;
	}

	bool HasPinnedView() const override
	{
		return true;
	}

	const mpt::byte *GetRawData() const override
	{
		return nullptr;
	}

	off_t GetLength() const override
	{
		return 0;
	}
	off_t Read(mpt::byte * /*dst*/, off_t /*pos*/, off_t /*count*/) const override
	{
		return 0;
	}
};


class FileDataContainerWindow : public IFileDataContainer
{
private:
	std::shared_ptr<const IFileDataContainer> data;
	const off_t dataOffset;
	const off_t dataLength;
public:
	FileDataContainerWindow(std::shared_ptr<const IFileDataContainer> src, off_t off, off_t len) : data(src), dataOffset(off), dataLength(len) { }

	bool IsValid() const override
	{
		return data->IsValid();
	}
	bool HasFastGetLength() const override
	{
		return data->HasFastGetLength();
	}
	bool HasPinnedView() const override
	{
		return data->HasPinnedView();
	}
	const mpt::byte *GetRawData() const override
	{
		return data->GetRawData() + dataOffset;
	}
	off_t GetLength() const override
	{
		return dataLength;
	}
	off_t Read(mpt::byte *dst, off_t pos, off_t count) const override
	{
		if(pos >= dataLength)
		{
			return 0;
		}
		return data->Read(dst, dataOffset + pos, std::min(count, dataLength - pos));
	}
	bool CanRead(off_t pos, off_t length) const override
	{
		if((pos == dataLength) && (length == 0))
		{
			return true;
		}
		if(pos >= dataLength)
		{
			return false;
		}
		return (length <= dataLength - pos);
	}
	off_t GetReadableLength(off_t pos, off_t length) const override
	{
		if(pos >= dataLength)
		{
			return 0;
		}
		return std::min(length, dataLength - pos);
	}
};


class FileDataContainerSeekable : public IFileDataContainer {

private:

	off_t streamLength;

	mutable bool cached;
	mutable std::vector<mpt::byte> cache;

protected:

	FileDataContainerSeekable(off_t length);

private:
	
	void CacheStream() const;

public:

	bool IsValid() const override;
	bool HasFastGetLength() const override;
	bool HasPinnedView() const override;
	const mpt::byte *GetRawData() const override;
	off_t GetLength() const override;
	off_t Read(mpt::byte *dst, off_t pos, off_t count) const override;

private:

	virtual off_t InternalRead(mpt::byte *dst, off_t pos, off_t count) const = 0;

};


class FileDataContainerStdStreamSeekable : public FileDataContainerSeekable {

private:

	std::istream *stream;

public:

	FileDataContainerStdStreamSeekable(std::istream *s);

	static bool IsSeekable(std::istream *stream);
	static off_t GetLength(std::istream *stream);

private:

	off_t InternalRead(mpt::byte *dst, off_t pos, off_t count) const override;

};


class FileDataContainerUnseekable : public IFileDataContainer {

private:

	mutable std::vector<mpt::byte> cache;
	mutable std::size_t cachesize;
	mutable bool streamFullyCached;

protected:

	FileDataContainerUnseekable();

private:

	enum : std::size_t {
		QUANTUM_SIZE = mpt::IO::BUFFERSIZE_SMALL,
		BUFFER_SIZE = mpt::IO::BUFFERSIZE_NORMAL
	};

	void EnsureCacheBuffer(std::size_t requiredbuffersize) const;
	void CacheStream() const;
	void CacheStreamUpTo(off_t pos, off_t length) const;

private:

	void ReadCached(mpt::byte *dst, off_t pos, off_t count) const;

public:

	bool IsValid() const override;
	bool HasFastGetLength() const override;
	bool HasPinnedView() const override;
	const mpt::byte *GetRawData() const override;
	off_t GetLength() const override;
	off_t Read(mpt::byte *dst, off_t pos, off_t count) const override;
	bool CanRead(off_t pos, off_t length) const override;
	off_t GetReadableLength(off_t pos, off_t length) const override;

private:

	virtual bool InternalEof() const = 0;
	virtual off_t InternalRead(mpt::byte *dst, off_t count) const = 0;

};


class FileDataContainerStdStream : public FileDataContainerUnseekable {

private:

	std::istream *stream;

public:

	FileDataContainerStdStream(std::istream *s);

private:

	bool InternalEof() const override;
	off_t InternalRead(mpt::byte *dst, off_t count) const override;

};


#if defined(MPT_FILEREADER_CALLBACK_STREAM)


struct CallbackStream
{
	enum : int {
		SeekSet = 0,
		SeekCur = 1,
		SeekEnd = 2
	};
	void *stream;
	std::size_t (*read)( void * stream, void * dst, std::size_t bytes );
	int (*seek)( void * stream, int64 offset, int whence );
	int64 (*tell)( void * stream );
};


class FileDataContainerCallbackStreamSeekable : public FileDataContainerSeekable
{
private:
	CallbackStream stream;
public:
	static bool IsSeekable(CallbackStream stream);
	static off_t GetLength(CallbackStream stream);
	FileDataContainerCallbackStreamSeekable(CallbackStream s);
private:
	off_t InternalRead(mpt::byte *dst, off_t pos, off_t count) const override;
};


class FileDataContainerCallbackStream : public FileDataContainerUnseekable
{
private:
	CallbackStream stream;
	mutable bool eof_reached;
public:
	FileDataContainerCallbackStream(CallbackStream s);
private:
	bool InternalEof() const override;
	off_t InternalRead(mpt::byte *dst, off_t count) const override;
};


#endif // MPT_FILEREADER_CALLBACK_STREAM


#endif


class FileDataContainerMemory
#if defined(MPT_FILEREADER_STD_ISTREAM)
	: public IFileDataContainer
#endif
{

#if defined(MPT_FILEREADER_STD_ISTREAM)
#define MPT_FILEDATACONTAINERMEMORY_OVERRIDE override
#else
#define MPT_FILEDATACONTAINERMEMORY_OVERRIDE
#endif

#if !defined(MPT_FILEREADER_STD_ISTREAM)
public:
	typedef std::size_t off_t;
#endif

private:

	const mpt::byte *streamData;	// Pointer to memory-mapped file
	off_t streamLength;		// Size of memory-mapped file in bytes

public:
	FileDataContainerMemory() : streamData(nullptr), streamLength(0) { }
	FileDataContainerMemory(mpt::const_byte_span data) : streamData(data.data()), streamLength(data.size()) { }

public:

	bool IsValid() const MPT_FILEDATACONTAINERMEMORY_OVERRIDE
	{
		return streamData != nullptr;
	}

	bool HasFastGetLength() const MPT_FILEDATACONTAINERMEMORY_OVERRIDE
	{
		return true;
	}

	bool HasPinnedView() const MPT_FILEDATACONTAINERMEMORY_OVERRIDE
	{
		return true;
	}

	const mpt::byte *GetRawData() const MPT_FILEDATACONTAINERMEMORY_OVERRIDE
	{
		return streamData;
	}

	off_t GetLength() const MPT_FILEDATACONTAINERMEMORY_OVERRIDE
	{
		return streamLength;
	}

	off_t Read(mpt::byte *dst, off_t pos, off_t count) const MPT_FILEDATACONTAINERMEMORY_OVERRIDE
	{
		if(pos >= streamLength)
		{
			return 0;
		}
		off_t avail = std::min<off_t>(streamLength - pos, count);
		std::copy(streamData + pos, streamData + pos + avail, dst);
		return avail;
	}

	off_t Read(off_t pos, mpt::byte_span dst) const MPT_FILEDATACONTAINERMEMORY_OVERRIDE
	{
		return Read(dst.data(), pos, dst.size());
	}

	bool CanRead(off_t pos, off_t length) const MPT_FILEDATACONTAINERMEMORY_OVERRIDE
	{
		if((pos == streamLength) && (length == 0))
		{
			return true;
		}
		if(pos >= streamLength)
		{
			return false;
		}
		return (length <= streamLength - pos);
	}

	off_t GetReadableLength(off_t pos, off_t length) const MPT_FILEDATACONTAINERMEMORY_OVERRIDE
	{
		if(pos >= streamLength)
		{
			return 0;
		}
		return std::min<off_t>(length, streamLength - pos);
	}

};



OPENMPT_NAMESPACE_END