1 /* -*- Mode: C++; 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/. */
6 #include "MemoryDownloader.h"
8 #include "mozilla/Assertions.h"
9 #include "nsIInputStream.h"
14 NS_IMPL_ISUPPORTS(MemoryDownloader
, nsIStreamListener
, nsIRequestObserver
)
16 MemoryDownloader::MemoryDownloader(IObserver
* aObserver
)
17 : mObserver(aObserver
), mStatus(NS_ERROR_NOT_INITIALIZED
) {}
20 MemoryDownloader::OnStartRequest(nsIRequest
* aRequest
) {
22 mData
.reset(new FallibleTArray
<uint8_t>());
28 MemoryDownloader::OnStopRequest(nsIRequest
* aRequest
, nsresult aStatus
) {
29 MOZ_ASSERT_IF(NS_FAILED(mStatus
), NS_FAILED(aStatus
));
30 MOZ_ASSERT(!mData
== NS_FAILED(mStatus
));
33 RefPtr
<IObserver
> observer
;
34 observer
.swap(mObserver
);
35 observer
->OnDownloadComplete(this, aRequest
, aStatus
, std::move(data
));
39 nsresult
MemoryDownloader::ConsumeData(nsIInputStream
* aIn
, void* aClosure
,
40 const char* aFromRawSegment
,
41 uint32_t aToOffset
, uint32_t aCount
,
42 uint32_t* aWriteCount
) {
43 MemoryDownloader
* self
= static_cast<MemoryDownloader
*>(aClosure
);
44 if (!self
->mData
->AppendElements(aFromRawSegment
, aCount
, fallible
)) {
45 // The error returned by ConsumeData isn't propagated to the
46 // return of ReadSegments, so it has to be passed as state.
47 self
->mStatus
= NS_ERROR_OUT_OF_MEMORY
;
48 return NS_ERROR_OUT_OF_MEMORY
;
50 *aWriteCount
= aCount
;
55 MemoryDownloader::OnDataAvailable(nsIRequest
* aRequest
, nsIInputStream
* aInStr
,
56 uint64_t aSourceOffset
, uint32_t aCount
) {
59 nsresult rv
= aInStr
->ReadSegments(ConsumeData
, this, aCount
, &n
);
60 if (NS_SUCCEEDED(mStatus
) && NS_FAILED(rv
)) {
63 if (NS_WARN_IF(NS_FAILED(mStatus
))) {
71 } // namespace mozilla