1 //* -*- Mode: C++; tab-width: 8; 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 #ifndef nsCheckSummedOutputStream_h__
7 #define nsCheckSummedOutputStream_h__
8 
9 #include "nsILocalFile.h"
10 #include "nsIFile.h"
11 #include "nsIOutputStream.h"
12 #include "nsICryptoHash.h"
13 #include "nsNetCID.h"
14 #include "nsString.h"
15 #include "nsToolkitCompsCID.h"
16 #include "../../../netwerk/base/nsBufferedStreams.h"
17 #include "prio.h"
18 
19 class nsCheckSummedOutputStream : public nsBufferedOutputStream
20 {
21 public:
22   NS_DECL_ISUPPORTS_INHERITED
23 
24   // Size of MD5 hash in bytes
25   static const uint32_t CHECKSUM_SIZE = 16;
26   static const uint32_t MAX_BUFFER_SIZE = 64 * 1024;
27 
nsCheckSummedOutputStream()28   nsCheckSummedOutputStream() {}
29 
30   NS_IMETHOD Finish() override;
31   NS_IMETHOD Write(const char *buf, uint32_t count, uint32_t *result) override;
32   NS_IMETHOD Init(nsIOutputStream* stream, uint32_t bufferSize) override;
33 
34 protected:
~nsCheckSummedOutputStream()35   virtual ~nsCheckSummedOutputStream() { nsBufferedOutputStream::Close(); }
36 
37   nsCOMPtr<nsICryptoHash> mHash;
38   nsCString mCheckSum;
39 };
40 
41 // returns a file output stream which can be QI'ed to nsIFileOutputStream.
42 inline nsresult
NS_NewCheckSummedOutputStream(nsIOutputStream ** result,nsIFile * file)43 NS_NewCheckSummedOutputStream(nsIOutputStream **result,
44                               nsIFile         *file)
45 {
46     nsCOMPtr<nsIOutputStream> localOutFile;
47     nsresult rv = NS_NewSafeLocalFileOutputStream(getter_AddRefs(localOutFile), file,
48                                                   PR_WRONLY | PR_TRUNCATE | PR_CREATE_FILE);
49     NS_ENSURE_SUCCESS(rv, rv);
50 
51     nsCOMPtr<nsIBufferedOutputStream> out = new nsCheckSummedOutputStream();
52     rv = out->Init(localOutFile, nsCheckSummedOutputStream::CHECKSUM_SIZE);
53     if (NS_SUCCEEDED(rv)) {
54       out.forget(result);
55     }
56     return rv;
57 }
58 
59 #endif
60