Source code

Revision control

Other Tools

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/. */
5
6
#include "MemoryDownloader.h"
7
8
#include "mozilla/Assertions.h"
9
#include "nsIInputStream.h"
10
11
namespace mozilla {
12
namespace net {
13
14
NS_IMPL_ISUPPORTS(MemoryDownloader, nsIStreamListener, nsIRequestObserver)
15
16
MemoryDownloader::MemoryDownloader(IObserver* aObserver)
17
: mObserver(aObserver), mStatus(NS_ERROR_NOT_INITIALIZED) {}
18
19
NS_IMETHODIMP
20
MemoryDownloader::OnStartRequest(nsIRequest* aRequest) {
21
MOZ_ASSERT(!mData);
22
mData.reset(new FallibleTArray<uint8_t>());
23
mStatus = NS_OK;
24
return NS_OK;
25
}
26
27
NS_IMETHODIMP
28
MemoryDownloader::OnStopRequest(nsIRequest* aRequest, nsresult aStatus) {
29
MOZ_ASSERT_IF(NS_FAILED(mStatus), NS_FAILED(aStatus));
30
MOZ_ASSERT(!mData == NS_FAILED(mStatus));
31
Data data;
32
data.swap(mData);
33
RefPtr<IObserver> observer;
34
observer.swap(mObserver);
35
observer->OnDownloadComplete(this, aRequest, nullptr, aStatus,
36
std::move(data));
37
return NS_OK;
38
}
39
40
nsresult MemoryDownloader::ConsumeData(nsIInputStream* aIn, void* aClosure,
41
const char* aFromRawSegment,
42
uint32_t aToOffset, uint32_t aCount,
43
uint32_t* aWriteCount) {
44
MemoryDownloader* self = static_cast<MemoryDownloader*>(aClosure);
45
if (!self->mData->AppendElements(aFromRawSegment, aCount, fallible)) {
46
// The error returned by ConsumeData isn't propagated to the
47
// return of ReadSegments, so it has to be passed as state.
48
self->mStatus = NS_ERROR_OUT_OF_MEMORY;
49
return NS_ERROR_OUT_OF_MEMORY;
50
}
51
*aWriteCount = aCount;
52
return NS_OK;
53
}
54
55
NS_IMETHODIMP
56
MemoryDownloader::OnDataAvailable(nsIRequest* aRequest, nsIInputStream* aInStr,
57
uint64_t aSourceOffset, uint32_t aCount) {
58
uint32_t n;
59
MOZ_ASSERT(mData);
60
nsresult rv = aInStr->ReadSegments(ConsumeData, this, aCount, &n);
61
if (NS_SUCCEEDED(mStatus) && NS_FAILED(rv)) {
62
mStatus = rv;
63
}
64
if (NS_WARN_IF(NS_FAILED(mStatus))) {
65
mData.reset(nullptr);
66
return mStatus;
67
}
68
return NS_OK;
69
}
70
71
} // namespace net
72
} // namespace mozilla