1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
3 * This file is part of the LibreOffice project.
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
10 #ifndef INCLUDED_SAX_SOURCE_TOOLS_CACHEDOUTPUTSTREAM_HXX
11 #define INCLUDED_SAX_SOURCE_TOOLS_CACHEDOUTPUTSTREAM_HXX
13 #include <sal/types.h>
15 #include <com/sun/star/io/XOutputStream.hpp>
16 #include <com/sun/star/uno/Sequence.hxx>
21 namespace sax_fastparser
{
26 virtual ~ForMergeBase() {}
27 virtual void append( const css::uno::Sequence
<sal_Int8
>& rWhat
) = 0;
30 class CachedOutputStream
32 /// When buffer hits this size, it's written to mxOutputStream
33 static const sal_Int32 mnMaximumSize
= 0x100000; // 1Mbyte
35 /// ForMerge structure is used for sorting elements in Writer
36 std::shared_ptr
< ForMergeBase
> mpForMerge
;
37 const css::uno::Sequence
<sal_Int8
> mpCache
;
38 /// Output stream, usually writing data into files.
39 css::uno::Reference
< css::io::XOutputStream
> mxOutputStream
;
41 sal_Int32 mnCacheWrittenSize
;
42 bool mbWriteToOutStream
;
45 CachedOutputStream() : mpCache(mnMaximumSize
)
47 , mnCacheWrittenSize(0)
48 , mbWriteToOutStream(true)
51 const css::uno::Reference
< css::io::XOutputStream
>& getOutputStream() const
53 return mxOutputStream
;
56 void setOutputStream( const css::uno::Reference
< css::io::XOutputStream
>& xOutputStream
)
58 mxOutputStream
= xOutputStream
;
61 void setOutput(const std::shared_ptr
<ForMergeBase
>& pForMerge
)
64 mbWriteToOutStream
= false;
65 mpForMerge
= pForMerge
;
68 void resetOutputToStream()
71 mbWriteToOutStream
= true;
75 /// cache string and if limit is hit, flush
76 void writeBytes( const sal_Int8
* pStr
, sal_Int32 nLen
)
78 // Write when the buffer gets big enough
79 if (mnCacheWrittenSize
+ nLen
> mnMaximumSize
)
83 // Writer does some elements sorting, so it can accumulate
84 // pretty big strings in FastSaxSerializer::ForMerge.
85 // In that case, just flush data and write immediately.
86 if (nLen
> mnMaximumSize
)
88 if (mbWriteToOutStream
)
89 mxOutputStream
->writeBytes( css::uno::Sequence
<sal_Int8
>(pStr
, nLen
) );
91 mpForMerge
->append( css::uno::Sequence
<sal_Int8
>(pStr
, nLen
) );
96 memcpy(pSeq
->elements
+ mnCacheWrittenSize
, pStr
, nLen
);
97 mnCacheWrittenSize
+= nLen
;
100 /// immediately write buffer into mxOutputStream and clear
103 // resize the Sequence to written size
104 pSeq
->nElements
= mnCacheWrittenSize
;
105 if (mbWriteToOutStream
)
106 mxOutputStream
->writeBytes( mpCache
);
108 mpForMerge
->append( mpCache
);
109 // and next time write to the beginning
110 mnCacheWrittenSize
= 0;
118 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */