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 : #include "mozilla/devtools/ZeroCopyNSIOutputStream.h"
7 :
8 : #include "mozilla/DebugOnly.h"
9 : #include "mozilla/Unused.h"
10 :
11 : namespace mozilla {
12 : namespace devtools {
13 :
14 0 : ZeroCopyNSIOutputStream::ZeroCopyNSIOutputStream(nsCOMPtr<nsIOutputStream>& out)
15 : : out(out)
16 : , result_(NS_OK)
17 : , amountUsed(0)
18 0 : , writtenCount(0)
19 : {
20 0 : DebugOnly<bool> nonBlocking = false;
21 0 : MOZ_ASSERT(out->IsNonBlocking(&nonBlocking) == NS_OK);
22 0 : MOZ_ASSERT(!nonBlocking);
23 0 : }
24 :
25 0 : ZeroCopyNSIOutputStream::~ZeroCopyNSIOutputStream()
26 : {
27 0 : if (!failed())
28 0 : Unused << NS_WARN_IF(NS_FAILED(writeBuffer()));
29 0 : }
30 :
31 : nsresult
32 0 : ZeroCopyNSIOutputStream::writeBuffer()
33 : {
34 0 : if (failed())
35 0 : return result_;
36 :
37 0 : if (amountUsed == 0)
38 0 : return NS_OK;
39 :
40 0 : int32_t amountWritten = 0;
41 0 : while (amountWritten < amountUsed) {
42 0 : uint32_t justWritten = 0;
43 :
44 0 : result_ = out->Write(buffer + amountWritten,
45 0 : amountUsed - amountWritten,
46 0 : &justWritten);
47 0 : if (NS_WARN_IF(NS_FAILED(result_)))
48 0 : return result_;
49 :
50 0 : amountWritten += justWritten;
51 : }
52 :
53 0 : writtenCount += amountUsed;
54 0 : amountUsed = 0;
55 0 : return NS_OK;
56 : }
57 :
58 : // ZeroCopyOutputStream Interface
59 :
60 : bool
61 0 : ZeroCopyNSIOutputStream::Next(void** data, int* size)
62 : {
63 0 : MOZ_ASSERT(data != nullptr);
64 0 : MOZ_ASSERT(size != nullptr);
65 :
66 0 : if (failed())
67 0 : return false;
68 :
69 0 : if (amountUsed == BUFFER_SIZE) {
70 0 : if (NS_FAILED(writeBuffer()))
71 0 : return false;
72 : }
73 :
74 0 : *data = buffer + amountUsed;
75 0 : *size = BUFFER_SIZE - amountUsed;
76 0 : amountUsed = BUFFER_SIZE;
77 0 : return true;
78 : }
79 :
80 : void
81 0 : ZeroCopyNSIOutputStream::BackUp(int count)
82 : {
83 0 : MOZ_ASSERT(count >= 0,
84 : "Cannot back up a negative amount of bytes.");
85 0 : MOZ_ASSERT(amountUsed == BUFFER_SIZE,
86 : "Can only call BackUp directly after calling Next.");
87 0 : MOZ_ASSERT(count <= amountUsed,
88 : "Can't back up further than we've given out.");
89 :
90 0 : amountUsed -= count;
91 0 : }
92 :
93 : ::google::protobuf::int64
94 0 : ZeroCopyNSIOutputStream::ByteCount() const
95 : {
96 0 : return writtenCount + amountUsed;
97 : }
98 :
99 : } // namespace devtools
100 : } // namespace mozilla
|