1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #ifndef mozilla_FixedBufferOutputStream_h
8 #define mozilla_FixedBufferOutputStream_h
11 #include "mozilla/fallible.h"
12 #include "mozilla/Mutex.h"
13 #include "mozilla/Span.h"
14 #include "mozilla/UniquePtr.h"
15 #include "nsIOutputStream.h"
16 #include "nsStringFwd.h"
23 class StreamBufferSink
;
25 // An output stream so you can read your potentially-async input stream into
26 // a contiguous buffer using NS_AsyncCopy. Back when streams were more
27 // synchronous and people didn't know blocking I/O was bad, if you wanted to
28 // read a stream into a flat buffer, you could use NS_ReadInputStreamToString
29 // or NS_ReadInputStreamToBuffer. But those don't work with async streams.
30 // This can be used to replace hand-rolled Read/AsyncWait() loops. Because you
31 // specify the expected size up front, the buffer is pre-allocated so wasteful
32 // reallocations can be avoided.
33 class FixedBufferOutputStream final
: public nsIOutputStream
{
34 template <typename T
, typename
... Args
>
35 friend RefPtr
<T
> MakeRefPtr(Args
&&... aArgs
);
38 // Factory method to get a FixedBufferOutputStream by allocating a char buffer
39 // with the given length.
40 static RefPtr
<FixedBufferOutputStream
> Create(size_t aLength
);
42 // Factory method to get a FixedBufferOutputStream by allocating a char buffer
43 // with the given length, fallible version.
44 static RefPtr
<FixedBufferOutputStream
> Create(size_t aLength
,
45 const mozilla::fallible_t
&);
47 // Factory method to get a FixedBufferOutputStream from a preallocated char
48 // buffer. The output stream doesn't take ownership of the char buffer, so the
49 // char buffer must outlive the output stream (to avoid a use-after-free).
50 static RefPtr
<FixedBufferOutputStream
> Create(mozilla::Span
<char> aBuffer
);
52 // Factory method to get a FixedBufferOutputStream from an arbitrary
54 static RefPtr
<FixedBufferOutputStream
> Create(
55 UniquePtr
<StreamBufferSink
>&& aSink
);
57 nsDependentCSubstring
WrittenData();
59 NS_DECL_THREADSAFE_ISUPPORTS
60 NS_DECL_NSIOUTPUTSTREAM
63 explicit FixedBufferOutputStream(UniquePtr
<StreamBufferSink
>&& aSink
);
65 ~FixedBufferOutputStream() = default;
67 const UniquePtr
<StreamBufferSink
> mSink
;
71 size_t mOffset
MOZ_GUARDED_BY(mMutex
);
72 bool mWriting
MOZ_GUARDED_BY(mMutex
);
73 bool mClosed
MOZ_GUARDED_BY(mMutex
);
76 } // namespace mozilla
78 #endif // mozilla_FixedBufferOutputStream_h