Bug 1893155 - Part 1: Make Calendar{WeekOfYear,YearOfWeek} return undefined. r=spider...
[gecko.git] / xpcom / base / nsGZFileWriter.cpp
blob2d8e14e9442cdd118b1a1b07d7993a0afaba0608
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"
8 #include "nsIFile.h"
9 #include "nsString.h"
10 #include "zlib.h"
12 #ifdef XP_WIN
13 # include <io.h>
14 # define _dup dup
15 #else
16 # include <unistd.h>
17 #endif
19 nsGZFileWriter::nsGZFileWriter(Operation aMode)
20 : mMode(aMode), mInitialized(false), mFinished(false), mGZFile(nullptr) {}
22 nsGZFileWriter::~nsGZFileWriter() {
23 if (mInitialized && !mFinished) {
24 Finish();
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.
36 FILE* file;
37 nsresult rv = aFile->OpenANSIFileDesc(mMode == Create ? "wb" : "ab", &file);
38 if (NS_WARN_IF(NS_FAILED(rv))) {
39 return 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");
50 fclose(aFile);
52 // gzdopen returns nullptr on error.
53 if (NS_WARN_IF(!mGZFile)) {
54 return NS_ERROR_FAILURE;
57 mInitialized = true;
59 return NS_OK;
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
70 // bytes to write.
71 if (aStr.IsEmpty()) {
72 return NS_OK;
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;
83 return NS_OK;
86 nsresult nsGZFileWriter::Finish() {
87 if (NS_WARN_IF(!mInitialized) || NS_WARN_IF(mFinished)) {
88 return NS_ERROR_FAILURE;
91 mFinished = true;
92 gzclose(mGZFile);
94 // Ignore errors from gzclose; it's not like there's anything we can do about
95 // it, at this point!
96 return NS_OK;