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
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
// TODO: Read->RefreshBuffer-> React to changes from m_nBufActualLen
#include <sal/config.h>
#include <cassert>
#include <cstddef>
#include <memory>
#include <string.h>
#include <o3tl/safeint.hxx>
#include <osl/endian.h>
#include <osl/diagnose.h>
#include <rtl/strbuf.hxx>
#include <rtl/string.hxx>
#include <rtl/ustrbuf.hxx>
#include <sal/log.hxx>
#include <tools/long.hxx>
#include <comphelper/fileformat.h>
#include <comphelper/fileurl.hxx>
static void swapNibbles(unsigned char &c)
{
unsigned char nSwapTmp=c;
nSwapTmp <<= 4;
c >>= 4;
c |= nSwapTmp;
}
#include <tools/debug.hxx>
#include <tools/stream.hxx>
#include <osl/thread.h>
#include <algorithm>
// !!! Do not inline if already the operators <<,>> are inline
template <typename T, std::enable_if_t<std::is_integral_v<T> && sizeof(T) == 2, int> = 0>
static void SwapNumber(T& r)
{ r = OSL_SWAPWORD(r); }
template <typename T, std::enable_if_t<std::is_integral_v<T> && sizeof(T) == 4, int> = 0>
static void SwapNumber(T& r)
{ r = OSL_SWAPDWORD(r); }
template <typename T, std::enable_if_t<std::is_integral_v<T> && sizeof(T) == 8, int> = 0>
static void SwapNumber(T& r)
{
union
{
T n;
sal_uInt32 c[2];
} s;
s.n = r;
std::swap(s.c[0], s.c[1]); // swap the 32 bit words
// swap the bytes in the words
s.c[0] = OSL_SWAPDWORD(s.c[0]);
s.c[1] = OSL_SWAPDWORD(s.c[1]);
r = s.n;
}
#ifdef UNX
static void SwapFloat( float& r )
{
union
{
float f;
sal_uInt32 c;
} s;
s.f = r;
s.c = OSL_SWAPDWORD( s.c );
r = s.f;
}
static void SwapDouble( double& r )
{
if( sizeof(double) != 8 )
{
SAL_WARN( "tools.stream", "Can only swap 8-Byte-doubles" );
}
else
{
union
{
double d;
sal_uInt32 c[2];
} s;
s.d = r;
s.c[0] ^= s.c[1]; // swap 32-bit values in situ
s.c[1] ^= s.c[0];
s.c[0] ^= s.c[1];
s.c[0] = OSL_SWAPDWORD(s.c[0]); // swap dword itself in situ
s.c[1] = OSL_SWAPDWORD(s.c[1]);
r = s.d;
}
}
#endif
//SDO
void SvStream::readNumberWithoutSwap_(void * pDataDest, int nDataSize)
{
if (m_isIoRead && nDataSize <= m_nBufFree)
{
for (int i = 0; i < nDataSize; i++)
static_cast<char*>(pDataDest)[i] = m_pBufPos[i];
m_nBufActualPos += nDataSize;
m_pBufPos += nDataSize;
m_nBufFree -= nDataSize;
}
else
{
ReadBytes( pDataDest, nDataSize );
}
}
void SvStream::writeNumberWithoutSwap_(const void * pDataSrc, int nDataSize)
{
if (m_isIoWrite && nDataSize <= m_nBufFree)
{
for (int i = 0; i < nDataSize; i++)
m_pBufPos[i] = static_cast<const char*>(pDataSrc)[i];
m_nBufFree -= nDataSize;
m_nBufActualPos += nDataSize;
if (m_nBufActualPos > m_nBufActualLen)
m_nBufActualLen = m_nBufActualPos;
m_pBufPos += nDataSize;
m_isDirty = true;
}
else
{
WriteBytes( pDataSrc, nDataSize );
}
}
void SvLockBytes::close()
{
(void)this;
}
// virtual
ErrCode SvLockBytes::ReadAt(sal_uInt64 const , void * , std::size_t ,
std::size_t * ) const
{
OSL_FAIL("SvLockBytes::ReadAt(): Bad stream");
return ERRCODE_NONE;
}
// virtual
ErrCode SvLockBytes::WriteAt(sal_uInt64 const , const void * , std::size_t ,
std::size_t * )
{
OSL_FAIL("SvLockBytes::WriteAt(): Bad stream");
return ERRCODE_NONE;
}
// virtual
ErrCode SvLockBytes::Flush() const
{
OSL_FAIL("SvLockBytes::Flush(): Bad stream");
return ERRCODE_NONE;
}
// virtual
ErrCode SvLockBytes::SetSize(sal_uInt64)
{
OSL_FAIL("SvLockBytes::SetSize(): Bad stream");
return ERRCODE_NONE;
}
ErrCode SvLockBytes::Stat(SvLockBytesStat *) const
{
OSL_FAIL("SvLockBytes::Stat(): Bad stream");
return ERRCODE_NONE;
}
std::size_t SvStream::GetData( void* pData, std::size_t nSize )
{
if( !GetError() )
{
DBG_ASSERT( m_xLockBytes.is(), "pure virtual function" );
std::size_t nRet(0);
m_nError = m_xLockBytes->ReadAt(m_nActPos, pData, nSize, &nRet);
m_nActPos += nRet;
return nRet;
}
else return 0;
}
std::size_t SvStream::PutData( const void* pData, std::size_t nSize )
{
if( !GetError() )
{
DBG_ASSERT( m_xLockBytes.is(), "pure virtual function" );
std::size_t nRet(0);
m_nError = m_xLockBytes->WriteAt(m_nActPos, pData, nSize, &nRet);
m_nActPos += nRet;
return nRet;
}
else return 0;
}
sal_uInt64 SvStream::SeekPos(sal_uInt64 const nPos)
{
// check if a truncated STREAM_SEEK_TO_END was passed
assert(nPos != SAL_MAX_UINT32);
if( !GetError() && nPos == STREAM_SEEK_TO_END )
{
DBG_ASSERT( m_xLockBytes.is(), "pure virtual function" );
SvLockBytesStat aStat;
m_xLockBytes->Stat( &aStat );
m_nActPos = aStat.nSize;
}
else
m_nActPos = nPos;
return m_nActPos;
}
void SvStream::FlushData()
{
if( !GetError() )
{
DBG_ASSERT( m_xLockBytes.is(), "pure virtual function" );
m_nError = m_xLockBytes->Flush();
}
}
void SvStream::SetSize(sal_uInt64 const nSize)
{
DBG_ASSERT( m_xLockBytes.is(), "pure virtual function" );
m_nError = m_xLockBytes->SetSize( nSize );
}
SvStream::SvStream() :
m_nActPos(0)
, m_pBufPos(nullptr)
, m_nBufSize(0)
, m_nBufActualLen(0)
, m_nBufActualPos(0)
, m_nBufFree(0)
, m_isIoRead(false)
, m_isIoWrite(false)
, m_isDirty(false)
, m_isEof(false)
, m_nCompressMode(SvStreamCompressFlags::NONE)
#if defined UNX
, m_eLineDelimiter(LINEEND_LF) // UNIX-Format
#else
, m_eLineDelimiter(LINEEND_CRLF) // DOS-Format
#endif
, m_eStreamCharSet(osl_getThreadTextEncoding())
, m_nCryptMask(0)
, m_nVersion(0)
, m_nBufFilePos(0)
, m_eStreamMode(StreamMode::NONE)
, m_isWritable(true)
{
SetEndian( SvStreamEndian::LITTLE );
ClearError();
}
SvStream::SvStream( SvLockBytes* pLockBytesP ) : SvStream()
{
m_xLockBytes = pLockBytesP;
SetBufferSize( 256 );
}
SvStream::~SvStream()
{
if (m_xLockBytes.is())
Flush();
}
void SvStream::ClearError()
{
m_isEof = false;
m_nError = ERRCODE_NONE;
}
void SvStream::SetError( ErrCode nErrorCode )
{
if (m_nError == ERRCODE_NONE || (m_nError.IsWarning() && nErrorCode.IsError()))
m_nError = nErrorCode;
}
void SvStream::SetEndian( SvStreamEndian nNewFormat )
{
#ifdef OSL_BIGENDIAN
m_isSwap = nNewFormat == SvStreamEndian::LITTLE;
#else
m_isSwap = nNewFormat == SvStreamEndian::BIG;
#endif
}
SvStreamEndian SvStream::GetEndian() const
{
#ifdef OSL_BIGENDIAN
return m_isSwap ? SvStreamEndian::LITTLE : SvStreamEndian::BIG;
#else
return m_isSwap ? SvStreamEndian::BIG : SvStreamEndian::LITTLE;
#endif
}
void SvStream::SetBufferSize( sal_uInt16 nBufferSize )
{
sal_uInt64 const nActualFilePos = Tell();
bool bDontSeek = (m_pRWBuf == nullptr);
if (m_isDirty && m_isWritable) // due to Windows NT: Access denied
FlushBuffer();
if (m_nBufSize)
{
m_pRWBuf.reset();
m_nBufFilePos += m_nBufActualPos;
}
m_pRWBuf = nullptr;
m_nBufActualLen = 0;
m_nBufActualPos = 0;
m_nBufSize = nBufferSize;
if (m_nBufSize)
m_pRWBuf.reset(new sal_uInt8[ m_nBufSize ]);
m_pBufPos = m_pRWBuf.get();
m_isIoRead = m_isIoWrite = false;
if( !bDontSeek )
SeekPos( nActualFilePos );
}
void SvStream::ClearBuffer()
{
m_nBufActualLen = 0;
m_nBufActualPos = 0;
m_nBufFilePos = 0;
m_pBufPos = m_pRWBuf.get();
m_isDirty = false;
m_isIoRead = m_isIoWrite = false;
m_isEof = false;
}
void SvStream::ResetError()
{
ClearError();
}
bool SvStream::ReadByteStringLine( OUString& rStr, rtl_TextEncoding eSrcCharSet,
sal_Int32 nMaxBytesToRead )
{
OString aStr;
bool bRet = ReadLine( aStr, nMaxBytesToRead);
rStr = OStringToOUString(aStr, eSrcCharSet);
return bRet;
}
bool SvStream::ReadLine( OString& rStr, sal_Int32 nMaxBytesToRead )
{
OStringBuffer aBuf(4096);
bool rv = ReadLine(aBuf, nMaxBytesToRead);
rStr = aBuf.makeStringAndClear();
return rv;
}
bool SvStream::ReadLine( OStringBuffer& aBuf, sal_Int32 nMaxBytesToRead )
{
char buf[256+1];
bool bEnd = false;
sal_uInt64 nOldFilePos = Tell();
char c = 0;
std::size_t nTotalLen = 0;
aBuf.setLength(0);
while( !bEnd && !GetError() ) // Don't test for EOF as we
// are reading block-wise!
{
sal_uInt16 nLen = static_cast<sal_uInt16>(ReadBytes(buf, sizeof(buf)-1));
if ( !nLen )
{
if ( aBuf.isEmpty() )
{
// Exit on first block-read error
m_isEof = true;
aBuf.setLength(0);
return false;
}
else
break;
}
sal_uInt16 j, n;
for( j = n = 0; j < nLen ; ++j )
{
c = buf[j];
if ( c == '\n' || c == '\r' )
{
bEnd = true;
break;
}
if ( n < j )
buf[n] = c;
++n;
}
nTotalLen += j;
if (nTotalLen > o3tl::make_unsigned(nMaxBytesToRead))
{
n -= nTotalLen - nMaxBytesToRead;
nTotalLen = nMaxBytesToRead;
bEnd = true;
}
if ( n )
aBuf.append(buf, n);
}
if ( !bEnd && !GetError() && !aBuf.isEmpty() )
bEnd = true;
nOldFilePos += nTotalLen;
if( Tell() > nOldFilePos )
nOldFilePos++;
Seek( nOldFilePos ); // Seek pointer due to BlockRead above
if ( bEnd && (c=='\r' || c=='\n') ) // Special treatment for DOS files
{
char cTemp;
std::size_t nLen = ReadBytes(&cTemp, sizeof(cTemp));
if ( nLen ) {
if( cTemp == c || (cTemp != '\n' && cTemp != '\r') )
Seek( nOldFilePos );
}
}
if ( bEnd )
m_isEof = false;
return bEnd;
}
bool SvStream::ReadUniStringLine( OUString& rStr, sal_Int32 nMaxCodepointsToRead )
{
sal_Unicode buf[256+1];
bool bEnd = false;
sal_uInt64 nOldFilePos = Tell();
sal_Unicode c = 0;
std::size_t nTotalLen = 0;
DBG_ASSERT( sizeof(sal_Unicode) == sizeof(sal_uInt16), "ReadUniStringLine: swapping sizeof(sal_Unicode) not implemented" );
OUStringBuffer aBuf(4096);
while( !bEnd && !GetError() ) // Don't test for EOF as we
// are reading block-wise!
{
sal_uInt16 nLen = static_cast<sal_uInt16>(ReadBytes( buf, sizeof(buf)-sizeof(sal_Unicode)));
nLen /= sizeof(sal_Unicode);
if ( !nLen )
{
if ( aBuf.isEmpty() )
{
// exit on first BlockRead error
m_isEof = true;
rStr.clear();
return false;
}
else
break;
}
sal_uInt16 j, n;
for( j = n = 0; j < nLen ; ++j )
{
if (m_isSwap)
SwapNumber( buf[n] );
c = buf[j];
if ( c == '\n' || c == '\r' )
{
bEnd = true;
break;
}
// erAck 26.02.01: Old behavior was no special treatment of '\0'
// character here, but a following rStr+=c did ignore it. Is this
// really intended? Or should a '\0' better terminate a line?
// The nOldFilePos stuff wasn't correct then anyways.
if ( c )
{
if ( n < j )
buf[n] = c;
++n;
}
}
nTotalLen += j;
if (nTotalLen > o3tl::make_unsigned(nMaxCodepointsToRead))
{
n -= nTotalLen - nMaxCodepointsToRead;
nTotalLen = nMaxCodepointsToRead;
bEnd = true;
}
if ( n )
aBuf.append( buf, n );
}
if ( !bEnd && !GetError() && !aBuf.isEmpty() )
bEnd = true;
nOldFilePos += nTotalLen * sizeof(sal_Unicode);
if( Tell() > nOldFilePos )
nOldFilePos += sizeof(sal_Unicode);
Seek( nOldFilePos ); // seek due to BlockRead above
if ( bEnd && (c=='\r' || c=='\n') ) // special treatment for DOS files
{
sal_Unicode cTemp;
ReadBytes( &cTemp, sizeof(cTemp) );
if (m_isSwap)
SwapNumber( cTemp );
if( cTemp == c || (cTemp != '\n' && cTemp != '\r') )
Seek( nOldFilePos );
}
if ( bEnd )
m_isEof = false;
rStr = aBuf.makeStringAndClear();
return bEnd;
}
bool SvStream::ReadUniOrByteStringLine( OUString& rStr, rtl_TextEncoding eSrcCharSet,
sal_Int32 nMaxCodepointsToRead )
{
if ( eSrcCharSet == RTL_TEXTENCODING_UNICODE )
return ReadUniStringLine( rStr, nMaxCodepointsToRead );
else
return ReadByteStringLine( rStr, eSrcCharSet, nMaxCodepointsToRead );
}
OString read_zeroTerminated_uInt8s_ToOString(SvStream& rStream)
{
OStringBuffer aOutput(256);
char buf[ 256 + 1 ];
bool bEnd = false;
sal_uInt64 nFilePos = rStream.Tell();
while( !bEnd && !rStream.GetError() )
{
std::size_t nLen = rStream.ReadBytes(buf, sizeof(buf)-1);
if (!nLen)
break;
std::size_t nReallyRead = nLen;
const char* pPtr = buf;
while (nLen && *pPtr)
{
++pPtr;
--nLen;
}
bEnd = ( nReallyRead < sizeof(buf)-1 ) // read less than attempted to read
|| ( ( nLen > 0 ) // OR it is inside the block we read
&& ( 0 == *pPtr ) // AND found a string terminator
);
aOutput.append(buf, pPtr - buf);
}
nFilePos += aOutput.getLength();
if (rStream.Tell() > nFilePos)
rStream.Seek(nFilePos+1); // seek due to FileRead above
return aOutput.makeStringAndClear();
}
OUString read_zeroTerminated_uInt8s_ToOUString(SvStream& rStream, rtl_TextEncoding eEnc)
{
return OStringToOUString(
read_zeroTerminated_uInt8s_ToOString(rStream), eEnc);
}
/** Attempt to write a sequence of nUnits 16bit units from an OUString,
returned value is number of bytes written */
static std::size_t write_uInt16s_FromOUString(SvStream& rStrm, std::u16string_view rStr,
std::size_t nUnits)
{
DBG_ASSERT( sizeof(sal_Unicode) == sizeof(sal_uInt16), "write_uInt16s_FromOUString: swapping sizeof(sal_Unicode) not implemented" );
std::size_t nWritten;
if (!rStrm.IsEndianSwap())
nWritten = rStrm.WriteBytes(rStr.data(), nUnits * sizeof(sal_Unicode));
else
{
std::size_t nLen = nUnits;
sal_Unicode aBuf[384];
sal_Unicode* const pTmp = ( nLen > 384 ? new sal_Unicode[nLen] : aBuf);
memcpy( pTmp, rStr.data(), nLen * sizeof(sal_Unicode) );
sal_Unicode* p = pTmp;
const sal_Unicode* const pStop = pTmp + nLen;
while ( p < pStop )
{
SwapNumber( *p );
p++;
}
nWritten = rStrm.WriteBytes( pTmp, nLen * sizeof(sal_Unicode) );
if ( pTmp != aBuf )
delete [] pTmp;
}
return nWritten;
}
bool SvStream::WriteUnicodeOrByteText(std::u16string_view rStr, rtl_TextEncoding eDestCharSet, bool bZero)
{
if ( eDestCharSet == RTL_TEXTENCODING_UNICODE )
{
write_uInt16s_FromOUString(*this, rStr, rStr.size());
if (bZero)
WriteUnicode(0);
}
else
{
OString aStr(OUStringToOString(rStr, eDestCharSet));
WriteBytes(aStr.getStr(), aStr.getLength());
if (bZero)
WriteChar(0);
}
return m_nError == ERRCODE_NONE;
}
bool SvStream::WriteByteStringLine( std::u16string_view rStr, rtl_TextEncoding eDestCharSet )
{
return WriteLine(OUStringToOString(rStr, eDestCharSet));
}
bool SvStream::WriteLine(std::string_view rStr)
{
WriteBytes(rStr.data(), rStr.size());
endl(*this);
return m_nError == ERRCODE_NONE;
}
bool SvStream::WriteUniOrByteChar( sal_Unicode ch, rtl_TextEncoding eDestCharSet )
{
if ( eDestCharSet == RTL_TEXTENCODING_UNICODE )
WriteUnicode(ch);
else
{
OString aStr(&ch, 1, eDestCharSet);
WriteBytes(aStr.getStr(), aStr.getLength());
}
return m_nError == ERRCODE_NONE;
}
void SvStream::StartWritingUnicodeText()
{
m_isSwap = false; // Switch to no endian swapping
// BOM, Byte Order Mark, U+FEFF, see
// http://www.unicode.org/faq/utf_bom.html#BOM
// Upon read: 0xfeff(-257) => no swap; 0xfffe(-2) => swap
WriteUInt16(0xfeff);
}
void SvStream::StartReadingUnicodeText( rtl_TextEncoding eReadBomCharSet )
{
if (!( eReadBomCharSet == RTL_TEXTENCODING_DONTKNOW ||
eReadBomCharSet == RTL_TEXTENCODING_UNICODE ||
eReadBomCharSet == RTL_TEXTENCODING_UTF8))
return; // nothing to read
const sal_uInt64 nOldPos = Tell();
bool bGetBack = true;
unsigned char nFlag(0);
ReadUChar( nFlag );
switch ( nFlag )
{
case 0xfe: // UTF-16BE?
if ( eReadBomCharSet == RTL_TEXTENCODING_DONTKNOW ||
eReadBomCharSet == RTL_TEXTENCODING_UNICODE)
{
ReadUChar(nFlag);
if (nFlag == 0xff)
{
SetEndian(SvStreamEndian::BIG);
bGetBack = false;
}
}
break;
case 0xff: // UTF-16LE?
if ( eReadBomCharSet == RTL_TEXTENCODING_DONTKNOW ||
eReadBomCharSet == RTL_TEXTENCODING_UNICODE)
{
ReadUChar(nFlag);
if (nFlag == 0xfe)
{
SetEndian(SvStreamEndian::LITTLE);
bGetBack = false;
}
}
break;
case 0xef: // UTF-8?
if ( eReadBomCharSet == RTL_TEXTENCODING_DONTKNOW ||
eReadBomCharSet == RTL_TEXTENCODING_UTF8)
{
ReadUChar(nFlag);
if (nFlag == 0xbb)
{
ReadUChar(nFlag);
if (nFlag == 0xbf)
bGetBack = false; // it is UTF-8
}
}
break;
default:
; // nothing
}
if (bGetBack)
Seek(nOldPos); // no BOM, pure data
}
sal_uInt64 SvStream::SeekRel(sal_Int64 const nPos)
{
sal_uInt64 nActualPos = Tell();
if ( nPos >= 0 )
{
if (SAL_MAX_UINT64 - nActualPos > o3tl::make_unsigned(nPos))
nActualPos += nPos;
}
else
{
sal_uInt64 const nAbsPos = static_cast<sal_uInt64>(-nPos);
if ( nActualPos >= nAbsPos )
nActualPos -= nAbsPos;
}
assert((m_pBufPos != nullptr) == bool(m_pRWBuf));
if (m_pRWBuf)
{
m_pBufPos = m_pRWBuf.get() + nActualPos;
}
return Seek( nActualPos );
}
template <typename T> SvStream& SvStream::ReadNumber(T& r)
{
T n = 0;
readNumberWithoutSwap(n);
if (good())
{
if (m_isSwap)
SwapNumber(n);
r = n;
}
return *this;
}
SvStream& SvStream::ReadUInt16(sal_uInt16& r) { return ReadNumber(r); }
SvStream& SvStream::ReadUInt32(sal_uInt32& r) { return ReadNumber(r); }
SvStream& SvStream::ReadUInt64(sal_uInt64& r) { return ReadNumber(r); }
SvStream& SvStream::ReadInt16(sal_Int16& r) { return ReadNumber(r); }
SvStream& SvStream::ReadInt32(sal_Int32& r) { return ReadNumber(r); }
SvStream& SvStream::ReadInt64(sal_Int64& r) { return ReadNumber(r); }
SvStream& SvStream::ReadSChar( signed char& r )
{
if (m_isIoRead && sizeof(signed char) <= m_nBufFree)
{
r = *m_pBufPos;
m_nBufActualPos += sizeof(signed char);
m_pBufPos += sizeof(signed char);
m_nBufFree -= sizeof(signed char);
}
else
ReadBytes( &r, sizeof(signed char) );
return *this;
}
// Special treatment for Chars due to PutBack
SvStream& SvStream::ReadChar( char& r )
{
if (m_isIoRead && sizeof(char) <= m_nBufFree)
{
r = *m_pBufPos;
m_nBufActualPos += sizeof(char);
m_pBufPos += sizeof(char);
m_nBufFree -= sizeof(char);
}
else
ReadBytes( &r, sizeof(char) );
return *this;
}
SvStream& SvStream::ReadUChar( unsigned char& r )
{
if (m_isIoRead && sizeof(char) <= m_nBufFree)
{
r = *m_pBufPos;
m_nBufActualPos += sizeof(char);
m_pBufPos += sizeof(char);
m_nBufFree -= sizeof(char);
}
else
ReadBytes( &r, sizeof(char) );
return *this;
}
SvStream& SvStream::ReadUtf16(sal_Unicode& r) { return ReadNumber(r); }
SvStream& SvStream::ReadCharAsBool( bool& r )
{
if (m_isIoRead && sizeof(char) <= m_nBufFree)
{
SAL_WARN_IF(
*m_pBufPos > 1, "tools.stream", unsigned(*m_pBufPos) << " not 0/1");
r = *m_pBufPos != 0;
m_nBufActualPos += sizeof(char);
m_pBufPos += sizeof(char);
m_nBufFree -= sizeof(char);
}
else
{
unsigned char c;
if (ReadBytes(&c, 1) == 1)
{
SAL_WARN_IF(c > 1, "tools.stream", unsigned(c) << " not 0/1");
r = c != 0;
}
}
return *this;
}
SvStream& SvStream::ReadFloat(float& r)
{
float n = 0;
readNumberWithoutSwap(n);
if (good())
{
#if defined UNX
if (m_isSwap)
SwapFloat(n);
#endif
r = n;
}
return *this;
}
SvStream& SvStream::ReadDouble(double& r)
{
double n = 0;
readNumberWithoutSwap(n);
if (good())
{
#if defined UNX
if (m_isSwap)
SwapDouble(n);
#endif
r = n;
}
return *this;
}
SvStream& SvStream::ReadStream( SvStream& rStream )
{
const sal_uInt32 cBufLen = 0x8000;
std::unique_ptr<char[]> pBuf( new char[ cBufLen ] );
sal_uInt32 nCount;
do {
nCount = ReadBytes( pBuf.get(), cBufLen );
rStream.WriteBytes( pBuf.get(), nCount );
} while( nCount == cBufLen );
return *this;
}
template <typename T> SvStream& SvStream::WriteNumber(T n)
{
if (m_isSwap)
SwapNumber(n);
writeNumberWithoutSwap(n);
return *this;
}
SvStream& SvStream::WriteUInt16(sal_uInt16 v) { return WriteNumber(v); }
SvStream& SvStream::WriteUInt32(sal_uInt32 v) { return WriteNumber(v); }
SvStream& SvStream::WriteUInt64(sal_uInt64 v) { return WriteNumber(v); }
SvStream& SvStream::WriteInt16(sal_Int16 v) { return WriteNumber(v); }
SvStream& SvStream::WriteInt32(sal_Int32 v) { return WriteNumber(v); }
SvStream& SvStream::WriteInt64(sal_Int64 v) { return WriteNumber(v); }
SvStream& SvStream::WriteSChar( signed char v )
{
//SDO
if (m_isIoWrite && sizeof(signed char) <= m_nBufFree)
{
*m_pBufPos = v;
m_pBufPos++; // sizeof(char);
m_nBufActualPos++;
if (m_nBufActualPos > m_nBufActualLen) // Append ?
m_nBufActualLen = m_nBufActualPos;
m_nBufFree--; // = sizeof(char);
m_isDirty = true;
}
else
WriteBytes( &v, sizeof(signed char) );
return *this;
}
// Special treatment for Chars due to PutBack
SvStream& SvStream::WriteChar( char v )
{
//SDO
if (m_isIoWrite && sizeof(char) <= m_nBufFree)
{
*m_pBufPos = v;
m_pBufPos++; // sizeof(char);
m_nBufActualPos++;
if (m_nBufActualPos > m_nBufActualLen) // Append ?
m_nBufActualLen = m_nBufActualPos;
m_nBufFree--; // = sizeof(char);
m_isDirty = true;
}
else
WriteBytes( &v, sizeof(char) );
return *this;
}
SvStream& SvStream::WriteUChar( unsigned char v )
{
//SDO
if (m_isIoWrite && sizeof(char) <= m_nBufFree)
{
*reinterpret_cast<unsigned char*>(m_pBufPos) = v;
m_pBufPos++; // = sizeof(char);
m_nBufActualPos++; // = sizeof(char);
if (m_nBufActualPos > m_nBufActualLen) // Append ?
m_nBufActualLen = m_nBufActualPos;
m_nBufFree--;
m_isDirty = true;
}
else
WriteBytes( &v, sizeof(char) );
return *this;
}
SvStream& SvStream::WriteUInt8( sal_uInt8 v )
{
return WriteUChar(v);
}
SvStream& SvStream::WriteUnicode( sal_Unicode v )
{
return WriteUInt16(v);
}
SvStream& SvStream::WriteFloat( float v )
{
#ifdef UNX
if (m_isSwap)
SwapFloat(v);
#endif
writeNumberWithoutSwap(v);
return *this;
}
SvStream& SvStream::WriteDouble ( double v )
{
#if defined UNX
if (m_isSwap)
SwapDouble(v);
#endif
writeNumberWithoutSwap(v);
return *this;
}
SvStream& SvStream::WriteStream( SvStream& rStream )
{
const sal_uInt32 cBufLen = 0x8000;
std::unique_ptr<char[]> pBuf( new char[ cBufLen ] );
sal_uInt32 nCount;
do {
nCount = rStream.ReadBytes( pBuf.get(), cBufLen );
WriteBytes( pBuf.get(), nCount );
} while( nCount == cBufLen );
return *this;
}
sal_uInt64 SvStream::WriteStream( SvStream& rStream, sal_uInt64 nSize )
{
const sal_uInt32 cBufLen = 0x8000;
std::unique_ptr<char[]> pBuf( new char[ cBufLen ] );
sal_uInt32 nCurBufLen = cBufLen;
sal_uInt32 nCount;
sal_uInt64 nWriteSize = nSize;
do
{
nCurBufLen = std::min<sal_uInt64>(nCurBufLen, nWriteSize);
nCount = rStream.ReadBytes(pBuf.get(), nCurBufLen);
WriteBytes( pBuf.get(), nCount );
nWriteSize -= nCount;
}
while( nWriteSize && nCount == nCurBufLen );
return nSize - nWriteSize;
}
OUString SvStream::ReadUniOrByteString( rtl_TextEncoding eSrcCharSet )
{
// read UTF-16 string directly from stream ?
if (eSrcCharSet == RTL_TEXTENCODING_UNICODE)
return read_uInt32_lenPrefixed_uInt16s_ToOUString(*this);
return read_uInt16_lenPrefixed_uInt8s_ToOUString(*this, eSrcCharSet);
}
SvStream& SvStream::WriteUniOrByteString( std::u16string_view rStr, rtl_TextEncoding eDestCharSet )
{
// write UTF-16 string directly into stream ?
if (eDestCharSet == RTL_TEXTENCODING_UNICODE)
write_uInt32_lenPrefixed_uInt16s_FromOUString(*this, rStr);
else
write_uInt16_lenPrefixed_uInt8s_FromOUString(*this, rStr, eDestCharSet);
return *this;
}
void SvStream::FlushBuffer()
{
if (m_isDirty) // Does stream require a flush?
{
SeekPos(m_nBufFilePos);
if (m_nCryptMask)
CryptAndWriteBuffer(m_pRWBuf.get(), m_nBufActualLen);
else if (PutData(m_pRWBuf.get(), m_nBufActualLen) != m_nBufActualLen)
SetError(SVSTREAM_WRITE_ERROR);
m_isDirty = false;
}
}
std::size_t SvStream::ReadBytes( void* pData, std::size_t nCount )
{
std::size_t nSaveCount = nCount;
if (!m_pRWBuf)
{
nCount = GetData( pData,nCount);
if (m_nCryptMask)
EncryptBuffer(pData, nCount);
m_nBufFilePos += nCount;
}
else
{
// check if block is completely within buffer
m_isIoRead = true;
m_isIoWrite = false;
if (nCount <= o3tl::make_unsigned(m_nBufActualLen - m_nBufActualPos))
{
// => yes
if (nCount != 0)
memcpy(pData, m_pBufPos, nCount);
m_nBufActualPos = m_nBufActualPos + static_cast<sal_uInt16>(nCount);
m_pBufPos += nCount;
m_nBufFree = m_nBufFree - static_cast<sal_uInt16>(nCount);
}
else
{
FlushBuffer();
// Does data block fit into buffer?
if (nCount > m_nBufSize)
{
// => No! Thus read directly
// into target area without using the buffer
m_isIoRead = false;
SeekPos(m_nBufFilePos + m_nBufActualPos);
m_nBufActualLen = 0;
m_pBufPos = m_pRWBuf.get();
nCount = GetData( pData, nCount );
if (m_nCryptMask)
EncryptBuffer(pData, nCount);
m_nBufFilePos += nCount;
m_nBufFilePos += m_nBufActualPos;
m_nBufActualPos = 0;
}
else
{
// => Yes. Fill buffer first, then copy to target area
m_nBufFilePos += m_nBufActualPos;
SeekPos(m_nBufFilePos);
// TODO: Typecast before GetData, sal_uInt16 nCountTmp
std::size_t nCountTmp = GetData( m_pRWBuf.get(), m_nBufSize );
if (m_nCryptMask)
EncryptBuffer(m_pRWBuf.get(), nCountTmp);
m_nBufActualLen = static_cast<sal_uInt16>(nCountTmp);
if( nCount > nCountTmp )
{
nCount = nCountTmp; // trim count back, EOF see below
}
memcpy( pData, m_pRWBuf.get(), nCount );
m_nBufActualPos = static_cast<sal_uInt16>(nCount);
m_pBufPos = m_pRWBuf.get() + nCount;
}
}
}
m_isEof = false;
m_nBufFree = m_nBufActualLen - m_nBufActualPos;
if (nCount != nSaveCount && m_nError != ERRCODE_IO_PENDING)
m_isEof = true;
if (nCount == nSaveCount && m_nError == ERRCODE_IO_PENDING)
m_nError = ERRCODE_NONE;
return nCount;
}
std::size_t SvStream::WriteBytes( const void* pData, std::size_t nCount )
{
if( !nCount )
return 0;
if (!m_isWritable)
{
SetError( ERRCODE_IO_CANTWRITE );
return 0;
}
if (!m_pRWBuf)
{
if (m_nCryptMask)
nCount = CryptAndWriteBuffer( pData, nCount );
else
nCount = PutData( pData, nCount );
m_nBufFilePos += nCount;
return nCount;
}
m_isIoRead = false;
m_isIoWrite = true;
if (nCount <= o3tl::make_unsigned(m_nBufSize - m_nBufActualPos))
{
memcpy( m_pBufPos, pData, nCount );
m_nBufActualPos = m_nBufActualPos + static_cast<sal_uInt16>(nCount);
// Update length if buffer was updated
if (m_nBufActualPos > m_nBufActualLen)
m_nBufActualLen = m_nBufActualPos;
m_pBufPos += nCount;
m_isDirty = true;
}
else
{
FlushBuffer();
// Does data block fit into buffer?
if (nCount > m_nBufSize)
{
m_isIoWrite = false;
m_nBufFilePos += m_nBufActualPos;
m_nBufActualLen = 0;
m_nBufActualPos = 0;
m_pBufPos = m_pRWBuf.get();
SeekPos(m_nBufFilePos);
if (m_nCryptMask)
nCount = CryptAndWriteBuffer( pData, nCount );
else
nCount = PutData( pData, nCount );
m_nBufFilePos += nCount;
}
else
{
// Copy block to buffer
memcpy( m_pRWBuf.get(), pData, nCount );
// Mind the order!
m_nBufFilePos += m_nBufActualPos;
m_nBufActualPos = static_cast<sal_uInt16>(nCount);
m_pBufPos = m_pRWBuf.get() + nCount;
m_nBufActualLen = static_cast<sal_uInt16>(nCount);
m_isDirty = true;
}
}
m_nBufFree = m_nBufSize - m_nBufActualPos;
return nCount;
}
sal_uInt64 SvStream::Seek(sal_uInt64 const nFilePos)
{
m_isIoRead = m_isIoWrite = false;
m_isEof = false;
if (!m_pRWBuf)
{
m_nBufFilePos = SeekPos( nFilePos );
DBG_ASSERT(Tell() == m_nBufFilePos,"Out Of Sync!");
return m_nBufFilePos;
}
// Is seek position within buffer?
if (nFilePos >= m_nBufFilePos && nFilePos <= (m_nBufFilePos + m_nBufActualLen))
{
m_nBufActualPos = static_cast<sal_uInt16>(nFilePos - m_nBufFilePos);
m_pBufPos = m_pRWBuf.get() + m_nBufActualPos;
// Update m_nBufFree to avoid crash upon PutBack
m_nBufFree = m_nBufActualLen - m_nBufActualPos;
}
else
{
FlushBuffer();
m_nBufActualLen = 0;
m_nBufActualPos = 0;
m_pBufPos = m_pRWBuf.get();
m_nBufFilePos = SeekPos( nFilePos );
}
return m_nBufFilePos + m_nBufActualPos;
}
bool checkSeek(SvStream &rSt, sal_uInt64 nOffset)
{
const sal_uInt64 nMaxSeek = rSt.TellEnd();
return (nOffset <= nMaxSeek && rSt.Seek(nOffset) == nOffset);
}
namespace tools
{
bool isEmptyFileUrl(const OUString& rUrl)
{
if (!comphelper::isFileUrl(rUrl))
{
return false;
}
SvFileStream aStream(rUrl, StreamMode::READ);
if (!aStream.IsOpen())
{
return false;
}
return aStream.remainingSize() == 0;
}
}
//STREAM_SEEK_TO_END in some of the Seek backends is special cased to be
//efficient, in others e.g. SotStorageStream it's really horribly slow, and in
//those this should be overridden
sal_uInt64 SvStream::remainingSize()
{
sal_uInt64 const nCurr = Tell();
sal_uInt64 const nEnd = TellEnd();
sal_uInt64 nMaxAvailable = nEnd > nCurr ? (nEnd-nCurr) : 0;
return nMaxAvailable;
}
sal_uInt64 SvStream::TellEnd()
{
FlushBuffer();
sal_uInt64 const nCurr = Tell();
sal_uInt64 const nEnd = Seek(STREAM_SEEK_TO_END);
Seek(nCurr);
return nEnd;
}
void SvStream::Flush()
{
FlushBuffer();
if (m_isWritable)
FlushData();
}
void SvStream::RefreshBuffer()
{
FlushBuffer();
SeekPos(m_nBufFilePos);
m_nBufActualLen = static_cast<sal_uInt16>(GetData( m_pRWBuf.get(), m_nBufSize ));
if (m_nBufActualLen && m_nError == ERRCODE_IO_PENDING)
m_nError = ERRCODE_NONE;
if (m_nCryptMask)
EncryptBuffer(m_pRWBuf.get(), static_cast<std::size_t>(m_nBufActualLen));
m_isIoRead = m_isIoWrite = false;
}
#define CRYPT_BUFSIZE 1024
/// Encrypt and write
std::size_t SvStream::CryptAndWriteBuffer( const void* pStart, std::size_t nLen)
{
unsigned char pTemp[CRYPT_BUFSIZE];
unsigned char const * pDataPtr = static_cast<unsigned char const *>(pStart);
std::size_t nCount = 0;
std::size_t nBufCount;
unsigned char nMask = m_nCryptMask;
do
{
if( nLen >= CRYPT_BUFSIZE )
nBufCount = CRYPT_BUFSIZE;
else
nBufCount = nLen;
nLen -= nBufCount;
memcpy( pTemp, pDataPtr, static_cast<sal_uInt16>(nBufCount) );
// ******** Encrypt ********
for (unsigned char & rn : pTemp)
{
unsigned char aCh = rn;
aCh ^= nMask;
swapNibbles(aCh);
rn = aCh;
}
// *************************
nCount += PutData( pTemp, nBufCount );
pDataPtr += nBufCount;
}
while ( nLen );
return nCount;
}
void SvStream::EncryptBuffer(void* pStart, std::size_t nLen) const
{
unsigned char* pTemp = static_cast<unsigned char*>(pStart);
unsigned char nMask = m_nCryptMask;
for ( std::size_t n=0; n < nLen; n++, pTemp++ )
{
unsigned char aCh = *pTemp;
swapNibbles(aCh);
aCh ^= nMask;
*pTemp = aCh;
}
}
static unsigned char implGetCryptMask(const char* pStr, sal_Int32 nLen, tools::Long nVersion)
{
unsigned char nCryptMask = 0;
if (!nLen)
return nCryptMask;
if( nVersion <= SOFFICE_FILEFORMAT_31 )
{
while( nLen )
{
nCryptMask ^= *pStr;
pStr++;
nLen--;
}
}
else // BugFix #25888#
{
for( sal_Int32 i = 0; i < nLen; i++ ) {
nCryptMask ^= pStr[i];
if( nCryptMask & 0x80 ) {
nCryptMask <<= 1;
nCryptMask++;
}
else
nCryptMask <<= 1;
}
}
if( !nCryptMask )
nCryptMask = 67;
return nCryptMask;
}
void SvStream::SetCryptMaskKey(const OString& rCryptMaskKey)
{
m_aCryptMaskKey = rCryptMaskKey;
m_nCryptMask = implGetCryptMask(m_aCryptMaskKey.getStr(),
m_aCryptMaskKey.getLength(), GetVersion());
}
bool SvStream::SetStreamSize(sal_uInt64 const nSize)
{
#ifdef DBG_UTIL
sal_uInt64 nFPos = Tell();
#endif
sal_uInt16 nBuf = m_nBufSize;
SetBufferSize( 0 );
SetSize( nSize );
if (nSize < m_nBufFilePos)
{
m_nBufFilePos = nSize;
}
SetBufferSize( nBuf );
#ifdef DBG_UTIL
DBG_ASSERT(Tell()==nFPos,"SetStreamSize failed");
#endif
return (m_nError == ERRCODE_NONE);
}
SvStream& endl( SvStream& rStr )
{
LineEnd eDelim = rStr.GetLineDelimiter();
if ( eDelim == LINEEND_CR )
rStr.WriteChar('\r');
else if( eDelim == LINEEND_LF )
rStr.WriteChar('\n');
else
rStr.WriteChar('\r').WriteChar('\n');
return rStr;
}
SvStream& endlu( SvStream& rStrm )
{
switch ( rStrm.GetLineDelimiter() )
{
case LINEEND_CR :
rStrm.WriteUnicode('\r');
break;
case LINEEND_LF :
rStrm.WriteUnicode('\n');
break;
default:
rStrm.WriteUnicode('\r').WriteUnicode('\n');
}
return rStrm;
}
SvStream& endlub( SvStream& rStrm )
{
if ( rStrm.GetStreamCharSet() == RTL_TEXTENCODING_UNICODE )
return endlu( rStrm );
else
return endl( rStrm );
}
SvMemoryStream::SvMemoryStream( void* pBuffer, std::size_t bufSize,
StreamMode eMode )
{
if( eMode & StreamMode::WRITE )
m_isWritable = true;
else
m_isWritable = false;
nEndOfData = bufSize;
bOwnsData = false;
pBuf = static_cast<sal_uInt8 *>(pBuffer);
nResize = 0;
nSize = bufSize;
nPos = 0;
SetBufferSize( 0 );
}
SvMemoryStream::SvMemoryStream( std::size_t nInitSize, std::size_t nResizeOffset )
{
m_isWritable = true;
bOwnsData = true;
nEndOfData = 0;
nResize = nResizeOffset;
nPos = 0;
pBuf = nullptr;
if( nResize != 0 && nResize < 16 )
nResize = 16;
if( nInitSize )
AllocateMemory( nInitSize );
nSize = nInitSize;
SetBufferSize( 64 );
}
SvMemoryStream::~SvMemoryStream()
{
if( pBuf )
{
if( bOwnsData )
FreeMemory();
else
FlushBuffer();
}
}
void SvMemoryStream::SetBuffer( void* pNewBuf, std::size_t nCount,
std::size_t nEOF )
{
SetBufferSize( 0 ); // Init buffering in the base class
Seek( 0 );
if( bOwnsData && pNewBuf != pBuf )
FreeMemory();
pBuf = static_cast<sal_uInt8 *>(pNewBuf);
nPos = 0;
nSize = nCount;
nResize = 0;
bOwnsData = false;
if( nEOF > nCount )
nEOF = nCount;
nEndOfData = nEOF;
ResetError();
}
std::size_t SvMemoryStream::GetData( void* pData, std::size_t nCount )
{
std::size_t nMaxCount = nEndOfData-nPos;
if( nCount > nMaxCount )
nCount = nMaxCount;
if (nCount != 0)
{
memcpy( pData, pBuf+nPos, nCount );
}
nPos += nCount;
return nCount;
}
std::size_t SvMemoryStream::PutData( const void* pData, std::size_t nCount )
{
if( GetError() )
return 0;
std::size_t nMaxCount = nSize-nPos;
// check for overflow
if( nCount > nMaxCount )
{
if( nResize == 0 )
{
// copy as much as possible
nCount = nMaxCount;
SetError( SVSTREAM_OUTOFMEMORY );
}
else
{
tools::Long nNewResize;
if( nSize && nSize > nResize )
nNewResize = nSize;
else
nNewResize = nResize;
if( (nCount-nMaxCount) < nResize )
{
// lacking memory is smaller than nResize,
// resize accordingly
if( !ReAllocateMemory( nNewResize) )
{
nCount = 0;
SetError( SVSTREAM_WRITE_ERROR );
}
}
else
{
// lacking memory is larger than nResize,
// resize by (nCount-nMaxCount) + resize offset
if( !ReAllocateMemory( nCount-nMaxCount+nNewResize ) )
{
nCount = 0;
SetError( SVSTREAM_WRITE_ERROR );
}
}
}
}
assert(pBuf && "Possibly Reallocate failed");
memcpy( pBuf+nPos, pData, nCount);
nPos += nCount;
if( nPos > nEndOfData )
nEndOfData = nPos;
return nCount;
}
sal_uInt64 SvMemoryStream::SeekPos(sal_uInt64 const nNewPos)
{
// nEndOfData: First position in stream not allowed to read from
// nSize: Size of allocated buffer
// check if a truncated STREAM_SEEK_TO_END was passed
assert(nNewPos != SAL_MAX_UINT32);
if( nNewPos < nEndOfData )
nPos = nNewPos;
else if( nNewPos == STREAM_SEEK_TO_END )
nPos = nEndOfData;
else
{
if( nNewPos >= nSize ) // Does buffer need extension?
{
if( nResize ) // Is extension possible?
{
tools::Long nDiff = static_cast<tools::Long>(nNewPos - nSize + 1);
nDiff += static_cast<tools::Long>(nResize);
ReAllocateMemory( nDiff );
nPos = nNewPos;
nEndOfData = nNewPos;
}
else // Extension not possible, set pos to end of data
{
// SetError( SVSTREAM_OUTOFMEMORY );
nPos = nEndOfData;
}
}
else // Expand buffer size
{
nPos = nNewPos;
nEndOfData = nNewPos;
}
}
return nPos;
}
void SvMemoryStream::FlushData()
{
}
void SvMemoryStream::ResetError()
{
SvStream::ClearError();
}
void SvMemoryStream::AllocateMemory( std::size_t nNewSize )
{
pBuf = new sal_uInt8[nNewSize];
}
// (using Bozo algorithm)
bool SvMemoryStream::ReAllocateMemory( tools::Long nDiff )
{
if (!m_isWritable || !bOwnsData)
return false;
bool bRetVal = false;
tools::Long nTemp = static_cast<tools::Long>(nSize);
nTemp += nDiff;
std::size_t nNewSize = static_cast<std::size_t>(nTemp);
if( nNewSize )
{
sal_uInt8* pNewBuf = new sal_uInt8[nNewSize];
bRetVal = true; // Success!
if( nNewSize < nSize ) // Are we shrinking?
{
memcpy( pNewBuf, pBuf, nNewSize );
if( nPos > nNewSize )
nPos = 0;
if( nEndOfData >= nNewSize )
nEndOfData = nNewSize-1;
}
else
{
if (nSize != 0)
{
memcpy( pNewBuf, pBuf, nSize );
}
memset(pNewBuf + nSize, 0x00, nNewSize - nSize);
}
FreeMemory();
pBuf = pNewBuf;
nSize = nNewSize;
}
else
{
bRetVal = true;
FreeMemory();
pBuf = nullptr;
nSize = 0;
nEndOfData = 0;
nPos = 0;
}
return bRetVal;
}
void SvMemoryStream::FreeMemory()
{
assert(bOwnsData);
if (bOwnsData)
{
delete[] pBuf;
pBuf = nullptr;
}
}
void* SvMemoryStream::SwitchBuffer()
{
FlushBuffer();
if( !bOwnsData )
return nullptr;
Seek( STREAM_SEEK_TO_BEGIN );
void* pRetVal = pBuf;
pBuf = nullptr;
nEndOfData = 0;
nResize = 64;
nPos = 0;
ResetError();
std::size_t nInitSize = 512;
AllocateMemory(nInitSize);
nSize = nInitSize;
SetBufferSize( 64 );
return pRetVal;
}
void SvMemoryStream::SetSize(sal_uInt64 const nNewSize)
{
if (!m_isWritable)
{
SetError(SVSTREAM_INVALID_HANDLE);
return;
}
tools::Long nDiff = static_cast<tools::Long>(nNewSize) - static_cast<tools::Long>(nSize);
ReAllocateMemory( nDiff );
}
void SvMemoryStream::MakeReadOnly()
{
FlushBuffer();
m_isWritable = false;
nResize = 0;
SetBufferSize( 0 );
}
// Create an OString of nLen bytes from rStream
// coverity[ +taint_sanitize ]
OString read_uInt8s_ToOString(SvStream& rStrm, std::size_t nLen)
{
rtl_String *pStr = nullptr;
if (nLen)
{
nLen = std::min<std::size_t>(nLen, SAL_MAX_INT32);
//limit allocation to size of file, but + 1 to set eof state
nLen = std::min<sal_uInt64>(nLen, rStrm.remainingSize() + 1);
//alloc a (ref-count 1) rtl_String of the desired length.
//rtl_String's buffer is uninitialized, except for null termination
pStr = rtl_string_alloc(sal::static_int_cast<sal_Int32>(nLen));
SAL_WARN_IF(!pStr, "tools.stream", "allocation failed");
if (pStr)
{
std::size_t nWasRead = rStrm.ReadBytes(pStr->buffer, nLen);
if (nWasRead != nLen)
{
//on (typically unlikely) short read set length to what we could
//read, and null terminate. Excess buffer capacity remains of
//course, could create a (true) replacement OString if it matters.
pStr->length = sal::static_int_cast<sal_Int32>(nWasRead);
pStr->buffer[pStr->length] = 0;
}
}
}
//take ownership of buffer and return, otherwise return empty string
return pStr ? OString(pStr, SAL_NO_ACQUIRE) : OString();
}
// Create an OUString of nLen sal_Unicode code units from rStream
// coverity[ +taint_sanitize ]
OUString read_uInt16s_ToOUString(SvStream& rStrm, std::size_t nLen)
{
rtl_uString *pStr = nullptr;
if (nLen)
{
nLen = std::min<std::size_t>(nLen, SAL_MAX_INT32);
//limit allocation to size of file, but + 1 to set eof state
nLen = o3tl::sanitizing_min<sal_uInt64>(nLen, (rStrm.remainingSize() + 2) / 2);
//alloc a (ref-count 1) rtl_uString of the desired length.
//rtl_String's buffer is uninitialized, except for null termination
pStr = rtl_uString_alloc(sal::static_int_cast<sal_Int32>(nLen));
SAL_WARN_IF(!pStr, "tools.stream", "allocation failed");
if (pStr)
{
std::size_t nWasRead = rStrm.ReadBytes(pStr->buffer, nLen*2)/2;
if (nWasRead != nLen)
{
//on (typically unlikely) short read set length to what we could
//read, and null terminate. Excess buffer capacity remains of
//course, could create a (true) replacement OUString if it matters.
pStr->length = sal::static_int_cast<sal_Int32>(nWasRead);
pStr->buffer[pStr->length] = 0;
}
if (rStrm.IsEndianSwap())
{
for (sal_Int32 i = 0; i < pStr->length; ++i)
pStr->buffer[i] = OSL_SWAPWORD(pStr->buffer[i]);
}
}
}
// take ownership of buffer and return, otherwise return empty string
// coverity[tainted_data] - unhelpful untrusted loop bound
return pStr ? OUString(pStr, SAL_NO_ACQUIRE) : OUString();
}
namespace
{
template <typename T, typename O> T tmpl_convertLineEnd(const T &rIn, LineEnd eLineEnd)
{
// Determine linebreaks and compute length
bool bConvert = false; // Needs conversion
sal_Int32 nStrLen = rIn.getLength();
sal_Int32 nLineEndLen = (eLineEnd == LINEEND_CRLF) ? 2 : 1;
sal_Int32 nLen = 0; // Target length
sal_Int32 i = 0; // Source counter
while (i < nStrLen)
{
// \r or \n causes linebreak
if ( (rIn[i] == '\r') || (rIn[i] == '\n') )
{
nLen = nLen + nLineEndLen;
// If set already, skip expensive test
if ( !bConvert )
{
// Do we need to convert?
if ( ((eLineEnd != LINEEND_LF) && (rIn[i] == '\n')) ||
((eLineEnd == LINEEND_CRLF) && (i+1) < nStrLen && (rIn[i+1] != '\n')) ||
((eLineEnd == LINEEND_LF) &&
((rIn[i] == '\r') || ((i+1) < nStrLen && rIn[i+1] == '\r'))) ||
((eLineEnd == LINEEND_CR) &&
((rIn[i] == '\n') || ((i+1) < nStrLen && rIn[i+1] == '\n'))) )
bConvert = true;
}
// skip char if \r\n or \n\r
if ( (i+1) < nStrLen && ((rIn[i+1] == '\r') || (rIn[i+1] == '\n')) &&
(rIn[i] != rIn[i+1]) )
++i;
}
else
++nLen;
++i;
}
if (!bConvert)
return rIn;
// convert linebreaks, insert string
O aNewData(nLen);
i = 0;
while (i < nStrLen)
{
// \r or \n causes linebreak
if ( (rIn[i] == '\r') || (rIn[i] == '\n') )
{
if ( eLineEnd == LINEEND_CRLF )
{
aNewData.append('\r');
aNewData.append('\n');
}
else
{
if ( eLineEnd == LINEEND_CR )
aNewData.append('\r');
else
aNewData.append('\n');
}
if ( (i+1) < nStrLen && ((rIn[i+1] == '\r') || (rIn[i+1] == '\n')) &&
(rIn[i] != rIn[i+1]) )
++i;
}
else
{
aNewData.append(rIn[i]);
}
++i;
}
return aNewData.makeStringAndClear();
}
}
OString convertLineEnd(const OString &rIn, LineEnd eLineEnd)
{
return tmpl_convertLineEnd<OString, OStringBuffer>(rIn, eLineEnd);
}
OUString convertLineEnd(const OUString &rIn, LineEnd eLineEnd)
{
return tmpl_convertLineEnd<OUString, OUStringBuffer>(rIn, eLineEnd);
}
std::size_t write_uInt32_lenPrefixed_uInt16s_FromOUString(SvStream& rStrm,
std::u16string_view rStr)
{
std::size_t nWritten = 0;
sal_uInt32 nUnits = std::min<std::size_t>(rStr.size(), std::numeric_limits<sal_uInt32>::max());
SAL_WARN_IF(static_cast<std::size_t>(nUnits) != static_cast<std::size_t>(rStr.size()),
"tools.stream",
"string too long for prefix count to fit in output type");
rStrm.WriteUInt32(nUnits);
if (rStrm.good())
{
nWritten += sizeof(sal_uInt32);
nWritten += write_uInt16s_FromOUString(rStrm, rStr, nUnits);
}
return nWritten;
}
std::size_t write_uInt16_lenPrefixed_uInt16s_FromOUString(SvStream& rStrm,
std::u16string_view rStr)
{
std::size_t nWritten = 0;
sal_uInt16 nUnits = std::min<std::size_t>(rStr.size(), std::numeric_limits<sal_uInt16>::max());
SAL_WARN_IF(nUnits != rStr.size(),
"tools.stream",
"string too long for prefix count to fit in output type");
rStrm.WriteUInt16(nUnits);
if (rStrm.good())
{
nWritten += sizeof(nUnits);
nWritten += write_uInt16s_FromOUString(rStrm, rStr, nUnits);
}
return nWritten;
}
std::size_t write_uInt16_lenPrefixed_uInt8s_FromOString(SvStream& rStrm,
std::string_view rStr)
{
std::size_t nWritten = 0;
sal_uInt16 nUnits = std::min<std::size_t>(rStr.size(), std::numeric_limits<sal_uInt16>::max());
SAL_WARN_IF(static_cast<std::size_t>(nUnits) != static_cast<std::size_t>(rStr.size()),
"tools.stream",
"string too long for sal_uInt16 count to fit in output type");
rStrm.WriteUInt16( nUnits );
if (rStrm.good())
{
nWritten += sizeof(sal_uInt16);
nWritten += rStrm.WriteBytes(rStr.data(), nUnits);
}
return nWritten;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|