Line data Source code
1 : /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2; -*- */
2 : /* This Source Code Form is subject to the terms of the Mozilla Public
3 : * License, v. 2.0. If a copy of the MPL was not distributed with this
4 : * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
5 :
6 : #ifndef mozilla_devtools_ZeroCopyNSIOutputStream__
7 : #define mozilla_devtools_ZeroCopyNSIOutputStream__
8 :
9 : #include <google/protobuf/io/zero_copy_stream.h>
10 : #include <google/protobuf/stubs/common.h>
11 :
12 : #include "nsCOMPtr.h"
13 : #include "nsIOutputStream.h"
14 :
15 : namespace mozilla {
16 : namespace devtools {
17 :
18 : // A `google::protobuf::io::ZeroCopyOutputStream` implementation that uses an
19 : // `nsIOutputStream` under the covers.
20 : //
21 : // This class will automatically write and flush its data to the
22 : // `nsIOutputStream` in its destructor, but if you care whether that call
23 : // succeeds or fails, then you should call the `flush` method yourself. Errors
24 : // will be logged, however.
25 : class MOZ_STACK_CLASS ZeroCopyNSIOutputStream
26 : : public ::google::protobuf::io::ZeroCopyOutputStream
27 : {
28 : static const int BUFFER_SIZE = 8192;
29 :
30 : // The nsIOutputStream we are streaming to.
31 : nsCOMPtr<nsIOutputStream>& out;
32 :
33 : // The buffer we write data to before passing it to the output stream.
34 : char buffer[BUFFER_SIZE];
35 :
36 : // The status of writing to the underlying output stream.
37 : nsresult result_;
38 :
39 : // The number of bytes in the buffer that have been used thus far.
40 : int amountUsed;
41 :
42 : // Excluding the amount of the buffer currently used (which hasn't been
43 : // written and flushed yet), this is the number of bytes written to the output
44 : // stream.
45 : int64_t writtenCount;
46 :
47 : // Write the internal buffer to the output stream and flush it.
48 : nsresult writeBuffer();
49 :
50 : public:
51 : explicit ZeroCopyNSIOutputStream(nsCOMPtr<nsIOutputStream>& out);
52 :
53 : nsresult flush() { return writeBuffer(); }
54 :
55 : // Return true if writing to the underlying output stream ever failed.
56 0 : bool failed() const { return NS_FAILED(result_); }
57 :
58 0 : nsresult result() const { return result_; }
59 :
60 : // ZeroCopyOutputStream Interface
61 : virtual ~ZeroCopyNSIOutputStream() override;
62 : virtual bool Next(void** data, int* size) override;
63 : virtual void BackUp(int count) override;
64 : virtual ::google::protobuf::int64 ByteCount() const override;
65 : };
66 :
67 : } // namespace devtools
68 : } // namespace mozilla
69 :
70 : #endif // mozilla_devtools_ZeroCopyNSIOutputStream__
|