Bug 1874684 - Part 6: Limit day length calculations to safe integers. r=mgaudet
[gecko.git] / dom / quota / StreamUtils.cpp
blobcc6857777290abf16b6c380742b12fa1fa6ebd0b
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 file,
5 * You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #include "StreamUtils.h"
9 #include "mozilla/Result.h"
10 #include "mozilla/dom/quota/Assertions.h"
11 #include "mozilla/dom/quota/QuotaCommon.h"
12 #include "mozilla/dom/quota/ResultExtensions.h"
13 #include "nsCOMPtr.h"
14 #include "nsIFile.h"
15 #include "nsIObjectInputStream.h"
16 #include "nsIObjectOutputStream.h"
17 #include "nsIOutputStream.h"
18 #include "nsIRandomAccessStream.h"
19 #include "nsNetUtil.h"
21 namespace mozilla::dom::quota {
23 Result<nsCOMPtr<nsIOutputStream>, nsresult> GetOutputStream(
24 nsIFile& aFile, FileFlag aFileFlag) {
25 AssertIsOnIOThread();
27 switch (aFileFlag) {
28 case FileFlag::Truncate:
29 QM_TRY_RETURN(NS_NewLocalFileOutputStream(&aFile));
31 case FileFlag::Update: {
32 QM_TRY_INSPECT(const bool& exists,
33 MOZ_TO_RESULT_INVOKE_MEMBER(&aFile, Exists));
35 if (!exists) {
36 return nsCOMPtr<nsIOutputStream>();
39 QM_TRY_INSPECT(const auto& stream,
40 NS_NewLocalFileRandomAccessStream(&aFile));
42 nsCOMPtr<nsIOutputStream> outputStream = do_QueryInterface(stream);
43 QM_TRY(OkIf(outputStream), Err(NS_ERROR_FAILURE));
45 return outputStream;
48 case FileFlag::Append:
49 QM_TRY_RETURN(NS_NewLocalFileOutputStream(
50 &aFile, PR_WRONLY | PR_CREATE_FILE | PR_APPEND));
52 default:
53 MOZ_CRASH("Should never get here!");
57 Result<nsCOMPtr<nsIBinaryOutputStream>, nsresult> GetBinaryOutputStream(
58 nsIFile& aFile, FileFlag aFileFlag) {
59 QM_TRY_UNWRAP(auto outputStream, GetOutputStream(aFile, aFileFlag));
61 QM_TRY(OkIf(outputStream), Err(NS_ERROR_UNEXPECTED));
63 return nsCOMPtr<nsIBinaryOutputStream>(
64 NS_NewObjectOutputStream(outputStream));
67 Result<nsCOMPtr<nsIBinaryInputStream>, nsresult> GetBinaryInputStream(
68 nsIFile& aDirectory, const nsAString& aFilename) {
69 MOZ_ASSERT(!NS_IsMainThread());
71 QM_TRY_INSPECT(const auto& file, MOZ_TO_RESULT_INVOKE_MEMBER_TYPED(
72 nsCOMPtr<nsIFile>, aDirectory, Clone));
74 QM_TRY(MOZ_TO_RESULT(file->Append(aFilename)));
76 QM_TRY_UNWRAP(auto stream, NS_NewLocalFileInputStream(file));
78 QM_TRY_INSPECT(const auto& bufferedStream,
79 NS_NewBufferedInputStream(stream.forget(), 512));
81 QM_TRY(OkIf(bufferedStream), Err(NS_ERROR_FAILURE));
83 return nsCOMPtr<nsIBinaryInputStream>(
84 NS_NewObjectInputStream(bufferedStream));
87 } // namespace mozilla::dom::quota