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 #include "nsGZFileWriter.h"
19 nsGZFileWriter::nsGZFileWriter(Operation aMode
)
20 : mMode(aMode
), mInitialized(false), mFinished(false), mGZFile(nullptr) {}
22 nsGZFileWriter::~nsGZFileWriter() {
23 if (mInitialized
&& !mFinished
) {
28 nsresult
nsGZFileWriter::Init(nsIFile
* aFile
) {
29 if (NS_WARN_IF(mInitialized
) || NS_WARN_IF(mFinished
)) {
30 return NS_ERROR_FAILURE
;
33 // Get a FILE out of our nsIFile. Convert that into a file descriptor which
34 // gzip can own. Then close our FILE, leaving only gzip's fd open.
37 nsresult rv
= aFile
->OpenANSIFileDesc(mMode
== Create
? "wb" : "ab", &file
);
38 if (NS_WARN_IF(NS_FAILED(rv
))) {
41 return InitANSIFileDesc(file
);
44 nsresult
nsGZFileWriter::InitANSIFileDesc(FILE* aFile
) {
45 if (NS_WARN_IF(mInitialized
) || NS_WARN_IF(mFinished
)) {
46 return NS_ERROR_FAILURE
;
49 mGZFile
= gzdopen(dup(fileno(aFile
)), mMode
== Create
? "wb" : "ab");
52 // gzdopen returns nullptr on error.
53 if (NS_WARN_IF(!mGZFile
)) {
54 return NS_ERROR_FAILURE
;
62 nsresult
nsGZFileWriter::Write(const nsACString
& aStr
) {
63 if (NS_WARN_IF(!mInitialized
) || NS_WARN_IF(mFinished
)) {
64 return NS_ERROR_FAILURE
;
67 // gzwrite uses a return value of 0 to indicate failure. Otherwise, it
68 // returns the number of uncompressed bytes written. To ensure we can
69 // distinguish between success and failure, don't call gzwrite when we have 0
75 // gzwrite never does a short write -- that is, the return value should
76 // always be either 0 or aStr.Length(), and we shouldn't have to call it
77 // multiple times in order to get it to read the whole buffer.
78 int rv
= gzwrite(mGZFile
, aStr
.BeginReading(), aStr
.Length());
79 if (NS_WARN_IF(rv
!= static_cast<int>(aStr
.Length()))) {
80 return NS_ERROR_FAILURE
;
86 nsresult
nsGZFileWriter::Finish() {
87 if (NS_WARN_IF(!mInitialized
) || NS_WARN_IF(mFinished
)) {
88 return NS_ERROR_FAILURE
;
94 // Ignore errors from gzclose; it's not like there's anything we can do about