Line data Source code
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 0 : NS_IMPL_ISUPPORTS(MemoryDownloader,
15 : nsIStreamListener,
16 : nsIRequestObserver)
17 :
18 0 : MemoryDownloader::MemoryDownloader(IObserver* aObserver)
19 0 : : mObserver(aObserver)
20 : {
21 0 : }
22 :
23 0 : MemoryDownloader::~MemoryDownloader()
24 : {
25 0 : }
26 :
27 : NS_IMETHODIMP
28 0 : MemoryDownloader::OnStartRequest(nsIRequest* aRequest, nsISupports* aCtxt)
29 : {
30 0 : MOZ_ASSERT(!mData);
31 0 : mData.reset(new FallibleTArray<uint8_t>());
32 0 : mStatus = NS_OK;
33 0 : return NS_OK;
34 : }
35 :
36 : NS_IMETHODIMP
37 0 : MemoryDownloader::OnStopRequest(nsIRequest* aRequest,
38 : nsISupports* aCtxt,
39 : nsresult aStatus)
40 : {
41 0 : MOZ_ASSERT_IF(NS_FAILED(mStatus), NS_FAILED(aStatus));
42 0 : MOZ_ASSERT(!mData == NS_FAILED(mStatus));
43 0 : Data data;
44 0 : data.swap(mData);
45 0 : RefPtr<IObserver> observer;
46 0 : observer.swap(mObserver);
47 0 : observer->OnDownloadComplete(this, aRequest, aCtxt, aStatus,
48 0 : mozilla::Move(data));
49 0 : return NS_OK;
50 : }
51 :
52 : nsresult
53 0 : MemoryDownloader::ConsumeData(nsIInputStream* aIn,
54 : void* aClosure,
55 : const char* aFromRawSegment,
56 : uint32_t aToOffset,
57 : uint32_t aCount,
58 : uint32_t* aWriteCount)
59 : {
60 0 : MemoryDownloader* self = static_cast<MemoryDownloader*>(aClosure);
61 0 : if (!self->mData->AppendElements(aFromRawSegment, aCount, fallible)) {
62 : // The error returned by ConsumeData isn't propagated to the
63 : // return of ReadSegments, so it has to be passed as state.
64 0 : self->mStatus = NS_ERROR_OUT_OF_MEMORY;
65 0 : return NS_ERROR_OUT_OF_MEMORY;
66 : }
67 0 : *aWriteCount = aCount;
68 0 : return NS_OK;
69 : }
70 :
71 : NS_IMETHODIMP
72 0 : MemoryDownloader::OnDataAvailable(nsIRequest* aRequest,
73 : nsISupports* aCtxt,
74 : nsIInputStream* aInStr,
75 : uint64_t aSourceOffset,
76 : uint32_t aCount)
77 : {
78 : uint32_t n;
79 0 : MOZ_ASSERT(mData);
80 0 : nsresult rv = aInStr->ReadSegments(ConsumeData, this, aCount, &n);
81 0 : if (NS_SUCCEEDED(mStatus) && NS_FAILED(rv)) {
82 0 : mStatus = rv;
83 : }
84 0 : if (NS_WARN_IF(NS_FAILED(mStatus))) {
85 0 : mData.reset(nullptr);
86 0 : return mStatus;
87 : }
88 0 : return NS_OK;
89 : }
90 :
91 : } // namespace net
92 : } // namespace mozilla
|