nsCheckSummedOutputStream.h 1.9 KB

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