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