xpcom/io/nsStreamUtils.cpp

changeset 0
6474c204b198
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/xpcom/io/nsStreamUtils.cpp	Wed Dec 31 06:09:35 2014 +0100
     1.3 @@ -0,0 +1,815 @@
     1.4 +/* vim:set ts=4 sw=4 sts=4 et cin: */
     1.5 +/* This Source Code Form is subject to the terms of the Mozilla Public
     1.6 + * License, v. 2.0. If a copy of the MPL was not distributed with this
     1.7 + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
     1.8 +
     1.9 +#include "mozilla/Mutex.h"
    1.10 +#include "mozilla/Attributes.h"
    1.11 +#include "nsStreamUtils.h"
    1.12 +#include "nsAutoPtr.h"
    1.13 +#include "nsCOMPtr.h"
    1.14 +#include "nsIPipe.h"
    1.15 +#include "nsIEventTarget.h"
    1.16 +#include "nsIRunnable.h"
    1.17 +#include "nsISafeOutputStream.h"
    1.18 +#include "nsString.h"
    1.19 +#include "nsIAsyncInputStream.h"
    1.20 +#include "nsIAsyncOutputStream.h"
    1.21 +#include "nsIBufferedStreams.h"
    1.22 +
    1.23 +using namespace mozilla;
    1.24 +
    1.25 +//-----------------------------------------------------------------------------
    1.26 +
    1.27 +class nsInputStreamReadyEvent MOZ_FINAL : public nsIRunnable
    1.28 +                                        , public nsIInputStreamCallback
    1.29 +{
    1.30 +public:
    1.31 +    NS_DECL_THREADSAFE_ISUPPORTS
    1.32 +
    1.33 +    nsInputStreamReadyEvent(nsIInputStreamCallback *callback,
    1.34 +                            nsIEventTarget *target)
    1.35 +        : mCallback(callback)
    1.36 +        , mTarget(target)
    1.37 +    {
    1.38 +    }
    1.39 +
    1.40 +private:
    1.41 +    ~nsInputStreamReadyEvent()
    1.42 +    {
    1.43 +        if (!mCallback)
    1.44 +            return;
    1.45 +        //
    1.46 +        // whoa!!  looks like we never posted this event.  take care to
    1.47 +        // release mCallback on the correct thread.  if mTarget lives on the
    1.48 +        // calling thread, then we are ok.  otherwise, we have to try to 
    1.49 +        // proxy the Release over the right thread.  if that thread is dead,
    1.50 +        // then there's nothing we can do... better to leak than crash.
    1.51 +        //
    1.52 +        bool val;
    1.53 +        nsresult rv = mTarget->IsOnCurrentThread(&val);
    1.54 +        if (NS_FAILED(rv) || !val) {
    1.55 +            nsCOMPtr<nsIInputStreamCallback> event =
    1.56 +                NS_NewInputStreamReadyEvent(mCallback, mTarget);
    1.57 +            mCallback = nullptr;
    1.58 +            if (event) {
    1.59 +                rv = event->OnInputStreamReady(nullptr);
    1.60 +                if (NS_FAILED(rv)) {
    1.61 +                    NS_NOTREACHED("leaking stream event");
    1.62 +                    nsISupports *sup = event;
    1.63 +                    NS_ADDREF(sup);
    1.64 +                }
    1.65 +            }
    1.66 +        }
    1.67 +    }
    1.68 +
    1.69 +public:
    1.70 +    NS_IMETHOD OnInputStreamReady(nsIAsyncInputStream *stream)
    1.71 +    {
    1.72 +        mStream = stream;
    1.73 +
    1.74 +        nsresult rv =
    1.75 +            mTarget->Dispatch(this, NS_DISPATCH_NORMAL);
    1.76 +        if (NS_FAILED(rv)) {
    1.77 +            NS_WARNING("Dispatch failed");
    1.78 +            return NS_ERROR_FAILURE;
    1.79 +        }
    1.80 +
    1.81 +        return NS_OK;
    1.82 +    }
    1.83 +
    1.84 +    NS_IMETHOD Run()
    1.85 +    {
    1.86 +        if (mCallback) {
    1.87 +            if (mStream)
    1.88 +                mCallback->OnInputStreamReady(mStream);
    1.89 +            mCallback = nullptr;
    1.90 +        }
    1.91 +        return NS_OK;
    1.92 +    }
    1.93 +
    1.94 +private:
    1.95 +    nsCOMPtr<nsIAsyncInputStream>    mStream;
    1.96 +    nsCOMPtr<nsIInputStreamCallback> mCallback;
    1.97 +    nsCOMPtr<nsIEventTarget>         mTarget;
    1.98 +};
    1.99 +
   1.100 +NS_IMPL_ISUPPORTS(nsInputStreamReadyEvent, nsIRunnable,
   1.101 +                  nsIInputStreamCallback)
   1.102 +
   1.103 +//-----------------------------------------------------------------------------
   1.104 +
   1.105 +class nsOutputStreamReadyEvent MOZ_FINAL : public nsIRunnable
   1.106 +                                         , public nsIOutputStreamCallback
   1.107 +{
   1.108 +public:
   1.109 +    NS_DECL_THREADSAFE_ISUPPORTS
   1.110 +
   1.111 +    nsOutputStreamReadyEvent(nsIOutputStreamCallback *callback,
   1.112 +                             nsIEventTarget *target)
   1.113 +        : mCallback(callback)
   1.114 +        , mTarget(target)
   1.115 +    {
   1.116 +    }
   1.117 +
   1.118 +private:
   1.119 +    ~nsOutputStreamReadyEvent()
   1.120 +    {
   1.121 +        if (!mCallback)
   1.122 +            return;
   1.123 +        //
   1.124 +        // whoa!!  looks like we never posted this event.  take care to
   1.125 +        // release mCallback on the correct thread.  if mTarget lives on the
   1.126 +        // calling thread, then we are ok.  otherwise, we have to try to 
   1.127 +        // proxy the Release over the right thread.  if that thread is dead,
   1.128 +        // then there's nothing we can do... better to leak than crash.
   1.129 +        //
   1.130 +        bool val;
   1.131 +        nsresult rv = mTarget->IsOnCurrentThread(&val);
   1.132 +        if (NS_FAILED(rv) || !val) {
   1.133 +            nsCOMPtr<nsIOutputStreamCallback> event =
   1.134 +                NS_NewOutputStreamReadyEvent(mCallback, mTarget);
   1.135 +            mCallback = nullptr;
   1.136 +            if (event) {
   1.137 +                rv = event->OnOutputStreamReady(nullptr);
   1.138 +                if (NS_FAILED(rv)) {
   1.139 +                    NS_NOTREACHED("leaking stream event");
   1.140 +                    nsISupports *sup = event;
   1.141 +                    NS_ADDREF(sup);
   1.142 +                }
   1.143 +            }
   1.144 +        }
   1.145 +    }
   1.146 +
   1.147 +public:
   1.148 +    NS_IMETHOD OnOutputStreamReady(nsIAsyncOutputStream *stream)
   1.149 +    {
   1.150 +        mStream = stream;
   1.151 +
   1.152 +        nsresult rv =
   1.153 +            mTarget->Dispatch(this, NS_DISPATCH_NORMAL);
   1.154 +        if (NS_FAILED(rv)) {
   1.155 +            NS_WARNING("PostEvent failed");
   1.156 +            return NS_ERROR_FAILURE;
   1.157 +        }
   1.158 +
   1.159 +        return NS_OK;
   1.160 +    }
   1.161 +
   1.162 +    NS_IMETHOD Run()
   1.163 +    {
   1.164 +        if (mCallback) {
   1.165 +            if (mStream)
   1.166 +                mCallback->OnOutputStreamReady(mStream);
   1.167 +            mCallback = nullptr;
   1.168 +        }
   1.169 +        return NS_OK;
   1.170 +    }
   1.171 +
   1.172 +private:
   1.173 +    nsCOMPtr<nsIAsyncOutputStream>    mStream;
   1.174 +    nsCOMPtr<nsIOutputStreamCallback> mCallback;
   1.175 +    nsCOMPtr<nsIEventTarget>          mTarget;
   1.176 +};
   1.177 +
   1.178 +NS_IMPL_ISUPPORTS(nsOutputStreamReadyEvent, nsIRunnable,
   1.179 +                  nsIOutputStreamCallback)
   1.180 +
   1.181 +//-----------------------------------------------------------------------------
   1.182 +
   1.183 +already_AddRefed<nsIInputStreamCallback>
   1.184 +NS_NewInputStreamReadyEvent(nsIInputStreamCallback *callback,
   1.185 +                            nsIEventTarget *target)
   1.186 +{
   1.187 +    NS_ASSERTION(callback, "null callback");
   1.188 +    NS_ASSERTION(target, "null target");
   1.189 +    nsRefPtr<nsInputStreamReadyEvent> ev =
   1.190 +        new nsInputStreamReadyEvent(callback, target);
   1.191 +    return ev.forget();
   1.192 +}
   1.193 +
   1.194 +already_AddRefed<nsIOutputStreamCallback>
   1.195 +NS_NewOutputStreamReadyEvent(nsIOutputStreamCallback *callback,
   1.196 +                             nsIEventTarget *target)
   1.197 +{
   1.198 +    NS_ASSERTION(callback, "null callback");
   1.199 +    NS_ASSERTION(target, "null target");
   1.200 +    nsRefPtr<nsOutputStreamReadyEvent> ev =
   1.201 +        new nsOutputStreamReadyEvent(callback, target);
   1.202 +    return ev.forget();
   1.203 +}
   1.204 +
   1.205 +//-----------------------------------------------------------------------------
   1.206 +// NS_AsyncCopy implementation
   1.207 +
   1.208 +// abstract stream copier...
   1.209 +class nsAStreamCopier : public nsIInputStreamCallback
   1.210 +                      , public nsIOutputStreamCallback
   1.211 +                      , public nsIRunnable
   1.212 +{
   1.213 +public:
   1.214 +    NS_DECL_THREADSAFE_ISUPPORTS
   1.215 +
   1.216 +    nsAStreamCopier()
   1.217 +        : mLock("nsAStreamCopier.mLock")
   1.218 +        , mCallback(nullptr)
   1.219 +        , mProgressCallback(nullptr)
   1.220 +        , mClosure(nullptr)
   1.221 +        , mChunkSize(0)
   1.222 +        , mEventInProcess(false)
   1.223 +        , mEventIsPending(false)
   1.224 +        , mCloseSource(true)
   1.225 +        , mCloseSink(true)
   1.226 +        , mCanceled(false)
   1.227 +        , mCancelStatus(NS_OK)
   1.228 +    {
   1.229 +    }
   1.230 +
   1.231 +    // virtual since subclasses call superclass Release()
   1.232 +    virtual ~nsAStreamCopier()
   1.233 +    {
   1.234 +    }
   1.235 +
   1.236 +    // kick off the async copy...
   1.237 +    nsresult Start(nsIInputStream *source,
   1.238 +                   nsIOutputStream *sink,
   1.239 +                   nsIEventTarget *target,
   1.240 +                   nsAsyncCopyCallbackFun callback,
   1.241 +                   void *closure,
   1.242 +                   uint32_t chunksize,
   1.243 +                   bool closeSource,
   1.244 +                   bool closeSink,
   1.245 +                   nsAsyncCopyProgressFun progressCallback)
   1.246 +    {
   1.247 +        mSource = source;
   1.248 +        mSink = sink;
   1.249 +        mTarget = target;
   1.250 +        mCallback = callback;
   1.251 +        mClosure = closure;
   1.252 +        mChunkSize = chunksize;
   1.253 +        mCloseSource = closeSource;
   1.254 +        mCloseSink = closeSink;
   1.255 +        mProgressCallback = progressCallback;
   1.256 +
   1.257 +        mAsyncSource = do_QueryInterface(mSource);
   1.258 +        mAsyncSink = do_QueryInterface(mSink);
   1.259 +
   1.260 +        return PostContinuationEvent();
   1.261 +    }
   1.262 +
   1.263 +    // implemented by subclasses, returns number of bytes copied and
   1.264 +    // sets source and sink condition before returning.
   1.265 +    virtual uint32_t DoCopy(nsresult *sourceCondition, nsresult *sinkCondition) = 0;
   1.266 +
   1.267 +    void Process()
   1.268 +    {
   1.269 +        if (!mSource || !mSink)
   1.270 +            return;
   1.271 +
   1.272 +        nsresult sourceCondition, sinkCondition;
   1.273 +        nsresult cancelStatus;
   1.274 +        bool canceled;
   1.275 +        {
   1.276 +            MutexAutoLock lock(mLock);
   1.277 +            canceled = mCanceled;
   1.278 +            cancelStatus = mCancelStatus;
   1.279 +        }
   1.280 +
   1.281 +        // Copy data from the source to the sink until we hit failure or have
   1.282 +        // copied all the data.
   1.283 +        for (;;) {
   1.284 +            // Note: copyFailed will be true if the source or the sink have
   1.285 +            //       reported an error, or if we failed to write any bytes
   1.286 +            //       because we have consumed all of our data.
   1.287 +            bool copyFailed = false;
   1.288 +            if (!canceled) {
   1.289 +                uint32_t n = DoCopy(&sourceCondition, &sinkCondition);
   1.290 +                if (n > 0 && mProgressCallback) {
   1.291 +                    mProgressCallback(mClosure, n);
   1.292 +                }
   1.293 +                copyFailed = NS_FAILED(sourceCondition) ||
   1.294 +                             NS_FAILED(sinkCondition) || n == 0;
   1.295 +
   1.296 +                MutexAutoLock lock(mLock);
   1.297 +                canceled = mCanceled;
   1.298 +                cancelStatus = mCancelStatus;
   1.299 +            }
   1.300 +            if (copyFailed && !canceled) {
   1.301 +                if (sourceCondition == NS_BASE_STREAM_WOULD_BLOCK && mAsyncSource) {
   1.302 +                    // need to wait for more data from source.  while waiting for
   1.303 +                    // more source data, be sure to observe failures on output end.
   1.304 +                    mAsyncSource->AsyncWait(this, 0, 0, nullptr);
   1.305 +
   1.306 +                    if (mAsyncSink)
   1.307 +                        mAsyncSink->AsyncWait(this,
   1.308 +                                              nsIAsyncOutputStream::WAIT_CLOSURE_ONLY,
   1.309 +                                              0, nullptr);
   1.310 +                    break;
   1.311 +                }
   1.312 +                else if (sinkCondition == NS_BASE_STREAM_WOULD_BLOCK && mAsyncSink) {
   1.313 +                    // need to wait for more room in the sink.  while waiting for
   1.314 +                    // more room in the sink, be sure to observer failures on the
   1.315 +                    // input end.
   1.316 +                    mAsyncSink->AsyncWait(this, 0, 0, nullptr);
   1.317 +
   1.318 +                    if (mAsyncSource)
   1.319 +                        mAsyncSource->AsyncWait(this,
   1.320 +                                                nsIAsyncInputStream::WAIT_CLOSURE_ONLY,
   1.321 +                                                0, nullptr);
   1.322 +                    break;
   1.323 +                }
   1.324 +            }
   1.325 +            if (copyFailed || canceled) {
   1.326 +                if (mCloseSource) {
   1.327 +                    // close source
   1.328 +                    if (mAsyncSource)
   1.329 +                        mAsyncSource->CloseWithStatus(canceled ? cancelStatus :
   1.330 +                                                                 sinkCondition);
   1.331 +                    else
   1.332 +                        mSource->Close();
   1.333 +                }
   1.334 +                mAsyncSource = nullptr;
   1.335 +                mSource = nullptr;
   1.336 +
   1.337 +                if (mCloseSink) {
   1.338 +                    // close sink
   1.339 +                    if (mAsyncSink)
   1.340 +                        mAsyncSink->CloseWithStatus(canceled ? cancelStatus :
   1.341 +                                                               sourceCondition);
   1.342 +                    else {
   1.343 +                        // If we have an nsISafeOutputStream, and our
   1.344 +                        // sourceCondition and sinkCondition are not set to a
   1.345 +                        // failure state, finish writing.
   1.346 +                        nsCOMPtr<nsISafeOutputStream> sostream =
   1.347 +                            do_QueryInterface(mSink);
   1.348 +                        if (sostream && NS_SUCCEEDED(sourceCondition) &&
   1.349 +                            NS_SUCCEEDED(sinkCondition))
   1.350 +                            sostream->Finish();
   1.351 +                        else
   1.352 +                            mSink->Close();
   1.353 +                    }
   1.354 +                }
   1.355 +                mAsyncSink = nullptr;
   1.356 +                mSink = nullptr;
   1.357 +
   1.358 +                // notify state complete...
   1.359 +                if (mCallback) {
   1.360 +                    nsresult status;
   1.361 +                    if (!canceled) {
   1.362 +                        status = sourceCondition;
   1.363 +                        if (NS_SUCCEEDED(status))
   1.364 +                            status = sinkCondition;
   1.365 +                        if (status == NS_BASE_STREAM_CLOSED)
   1.366 +                            status = NS_OK;
   1.367 +                    } else {
   1.368 +                        status = cancelStatus; 
   1.369 +                    }
   1.370 +                    mCallback(mClosure, status);
   1.371 +                }
   1.372 +                break;
   1.373 +            }
   1.374 +        }
   1.375 +    }
   1.376 +
   1.377 +    nsresult Cancel(nsresult aReason)
   1.378 +    {
   1.379 +        MutexAutoLock lock(mLock);
   1.380 +        if (mCanceled)
   1.381 +            return NS_ERROR_FAILURE;
   1.382 +
   1.383 +        if (NS_SUCCEEDED(aReason)) {
   1.384 +            NS_WARNING("cancel with non-failure status code");
   1.385 +            aReason = NS_BASE_STREAM_CLOSED;
   1.386 +        }
   1.387 +
   1.388 +        mCanceled = true;
   1.389 +        mCancelStatus = aReason;
   1.390 +        return NS_OK;
   1.391 +    }
   1.392 +
   1.393 +    NS_IMETHOD OnInputStreamReady(nsIAsyncInputStream *source)
   1.394 +    {
   1.395 +        PostContinuationEvent();
   1.396 +        return NS_OK;
   1.397 +    }
   1.398 +
   1.399 +    NS_IMETHOD OnOutputStreamReady(nsIAsyncOutputStream *sink)
   1.400 +    {
   1.401 +        PostContinuationEvent();
   1.402 +        return NS_OK;
   1.403 +    }
   1.404 +
   1.405 +    // continuation event handler
   1.406 +    NS_IMETHOD Run()
   1.407 +    {
   1.408 +        Process();
   1.409 +
   1.410 +        // clear "in process" flag and post any pending continuation event
   1.411 +        MutexAutoLock lock(mLock);
   1.412 +        mEventInProcess = false;
   1.413 +        if (mEventIsPending) {
   1.414 +            mEventIsPending = false;
   1.415 +            PostContinuationEvent_Locked();
   1.416 +        }
   1.417 +
   1.418 +        return NS_OK;
   1.419 +    }
   1.420 +
   1.421 +    nsresult PostContinuationEvent()
   1.422 +    {
   1.423 +        // we cannot post a continuation event if there is currently
   1.424 +        // an event in process.  doing so could result in Process being
   1.425 +        // run simultaneously on multiple threads, so we mark the event
   1.426 +        // as pending, and if an event is already in process then we 
   1.427 +        // just let that existing event take care of posting the real
   1.428 +        // continuation event.
   1.429 +
   1.430 +        MutexAutoLock lock(mLock);
   1.431 +        return PostContinuationEvent_Locked();
   1.432 +    }
   1.433 +
   1.434 +    nsresult PostContinuationEvent_Locked()
   1.435 +    {
   1.436 +        nsresult rv = NS_OK;
   1.437 +        if (mEventInProcess)
   1.438 +            mEventIsPending = true;
   1.439 +        else {
   1.440 +            rv = mTarget->Dispatch(this, NS_DISPATCH_NORMAL);
   1.441 +            if (NS_SUCCEEDED(rv))
   1.442 +                mEventInProcess = true;
   1.443 +            else
   1.444 +                NS_WARNING("unable to post continuation event");
   1.445 +        }
   1.446 +        return rv;
   1.447 +    }
   1.448 +
   1.449 +protected:
   1.450 +    nsCOMPtr<nsIInputStream>       mSource;
   1.451 +    nsCOMPtr<nsIOutputStream>      mSink;
   1.452 +    nsCOMPtr<nsIAsyncInputStream>  mAsyncSource;
   1.453 +    nsCOMPtr<nsIAsyncOutputStream> mAsyncSink;
   1.454 +    nsCOMPtr<nsIEventTarget>       mTarget;
   1.455 +    Mutex                          mLock;
   1.456 +    nsAsyncCopyCallbackFun         mCallback;
   1.457 +    nsAsyncCopyProgressFun         mProgressCallback;
   1.458 +    void                          *mClosure;
   1.459 +    uint32_t                       mChunkSize;
   1.460 +    bool                           mEventInProcess;
   1.461 +    bool                           mEventIsPending;
   1.462 +    bool                           mCloseSource;
   1.463 +    bool                           mCloseSink;
   1.464 +    bool                           mCanceled;
   1.465 +    nsresult                       mCancelStatus;
   1.466 +};
   1.467 +
   1.468 +NS_IMPL_ISUPPORTS(nsAStreamCopier,
   1.469 +                  nsIInputStreamCallback,
   1.470 +                  nsIOutputStreamCallback,
   1.471 +                  nsIRunnable)
   1.472 +
   1.473 +class nsStreamCopierIB MOZ_FINAL : public nsAStreamCopier
   1.474 +{
   1.475 +public:
   1.476 +    nsStreamCopierIB() : nsAStreamCopier() {}
   1.477 +    virtual ~nsStreamCopierIB() {}
   1.478 +
   1.479 +    struct ReadSegmentsState {
   1.480 +        nsIOutputStream *mSink;
   1.481 +        nsresult         mSinkCondition;
   1.482 +    };
   1.483 +
   1.484 +    static NS_METHOD ConsumeInputBuffer(nsIInputStream *inStr,
   1.485 +                                        void *closure,
   1.486 +                                        const char *buffer,
   1.487 +                                        uint32_t offset,
   1.488 +                                        uint32_t count,
   1.489 +                                        uint32_t *countWritten)
   1.490 +    {
   1.491 +        ReadSegmentsState *state = (ReadSegmentsState *) closure;
   1.492 +
   1.493 +        nsresult rv = state->mSink->Write(buffer, count, countWritten);
   1.494 +        if (NS_FAILED(rv))
   1.495 +            state->mSinkCondition = rv;
   1.496 +        else if (*countWritten == 0)
   1.497 +            state->mSinkCondition = NS_BASE_STREAM_CLOSED;
   1.498 +
   1.499 +        return state->mSinkCondition;
   1.500 +    }
   1.501 +
   1.502 +    uint32_t DoCopy(nsresult *sourceCondition, nsresult *sinkCondition)
   1.503 +    {
   1.504 +        ReadSegmentsState state;
   1.505 +        state.mSink = mSink;
   1.506 +        state.mSinkCondition = NS_OK;
   1.507 +
   1.508 +        uint32_t n;
   1.509 +        *sourceCondition =
   1.510 +            mSource->ReadSegments(ConsumeInputBuffer, &state, mChunkSize, &n);
   1.511 +        *sinkCondition = state.mSinkCondition;
   1.512 +        return n;
   1.513 +    }
   1.514 +};
   1.515 +
   1.516 +class nsStreamCopierOB MOZ_FINAL : public nsAStreamCopier
   1.517 +{
   1.518 +public:
   1.519 +    nsStreamCopierOB() : nsAStreamCopier() {}
   1.520 +    virtual ~nsStreamCopierOB() {}
   1.521 +
   1.522 +    struct WriteSegmentsState {
   1.523 +        nsIInputStream *mSource;
   1.524 +        nsresult        mSourceCondition;
   1.525 +    };
   1.526 +
   1.527 +    static NS_METHOD FillOutputBuffer(nsIOutputStream *outStr,
   1.528 +                                      void *closure,
   1.529 +                                      char *buffer,
   1.530 +                                      uint32_t offset,
   1.531 +                                      uint32_t count,
   1.532 +                                      uint32_t *countRead)
   1.533 +    {
   1.534 +        WriteSegmentsState *state = (WriteSegmentsState *) closure;
   1.535 +
   1.536 +        nsresult rv = state->mSource->Read(buffer, count, countRead);
   1.537 +        if (NS_FAILED(rv))
   1.538 +            state->mSourceCondition = rv;
   1.539 +        else if (*countRead == 0)
   1.540 +            state->mSourceCondition = NS_BASE_STREAM_CLOSED;
   1.541 +
   1.542 +        return state->mSourceCondition;
   1.543 +    }
   1.544 +
   1.545 +    uint32_t DoCopy(nsresult *sourceCondition, nsresult *sinkCondition)
   1.546 +    {
   1.547 +        WriteSegmentsState state;
   1.548 +        state.mSource = mSource;
   1.549 +        state.mSourceCondition = NS_OK;
   1.550 +
   1.551 +        uint32_t n;
   1.552 +        *sinkCondition =
   1.553 +            mSink->WriteSegments(FillOutputBuffer, &state, mChunkSize, &n);
   1.554 +        *sourceCondition = state.mSourceCondition;
   1.555 +        return n;
   1.556 +    }
   1.557 +};
   1.558 +
   1.559 +//-----------------------------------------------------------------------------
   1.560 +
   1.561 +nsresult
   1.562 +NS_AsyncCopy(nsIInputStream         *source,
   1.563 +             nsIOutputStream        *sink,
   1.564 +             nsIEventTarget         *target,
   1.565 +             nsAsyncCopyMode         mode,
   1.566 +             uint32_t                chunkSize,
   1.567 +             nsAsyncCopyCallbackFun  callback,
   1.568 +             void                   *closure,
   1.569 +             bool                    closeSource,
   1.570 +             bool                    closeSink,
   1.571 +             nsISupports           **aCopierCtx,
   1.572 +             nsAsyncCopyProgressFun  progressCallback)
   1.573 +{
   1.574 +    NS_ASSERTION(target, "non-null target required");
   1.575 +
   1.576 +    nsresult rv;
   1.577 +    nsAStreamCopier *copier;
   1.578 +
   1.579 +    if (mode == NS_ASYNCCOPY_VIA_READSEGMENTS)
   1.580 +        copier = new nsStreamCopierIB();
   1.581 +    else
   1.582 +        copier = new nsStreamCopierOB();
   1.583 +
   1.584 +    if (!copier)
   1.585 +        return NS_ERROR_OUT_OF_MEMORY;
   1.586 +
   1.587 +    // Start() takes an owning ref to the copier...
   1.588 +    NS_ADDREF(copier);
   1.589 +    rv = copier->Start(source, sink, target, callback, closure, chunkSize,
   1.590 +                       closeSource, closeSink, progressCallback);
   1.591 +
   1.592 +    if (aCopierCtx) {
   1.593 +        *aCopierCtx = static_cast<nsISupports*>(
   1.594 +                      static_cast<nsIRunnable*>(copier));
   1.595 +        NS_ADDREF(*aCopierCtx);
   1.596 +    }
   1.597 +    NS_RELEASE(copier);
   1.598 +
   1.599 +    return rv;
   1.600 +}
   1.601 +
   1.602 +//-----------------------------------------------------------------------------
   1.603 +
   1.604 +nsresult
   1.605 +NS_CancelAsyncCopy(nsISupports *aCopierCtx, nsresult aReason)
   1.606 +{
   1.607 +  nsAStreamCopier *copier = static_cast<nsAStreamCopier *>(
   1.608 +                            static_cast<nsIRunnable *>(aCopierCtx));
   1.609 +  return copier->Cancel(aReason);
   1.610 +}
   1.611 +
   1.612 +//-----------------------------------------------------------------------------
   1.613 +
   1.614 +nsresult
   1.615 +NS_ConsumeStream(nsIInputStream *stream, uint32_t maxCount, nsACString &result)
   1.616 +{
   1.617 +    nsresult rv = NS_OK;
   1.618 +    result.Truncate();
   1.619 +
   1.620 +    while (maxCount) {
   1.621 +        uint64_t avail64;
   1.622 +        rv = stream->Available(&avail64);
   1.623 +        if (NS_FAILED(rv)) {
   1.624 +            if (rv == NS_BASE_STREAM_CLOSED)
   1.625 +                rv = NS_OK;
   1.626 +            break;
   1.627 +        }
   1.628 +        if (avail64 == 0)
   1.629 +            break;
   1.630 +
   1.631 +        uint32_t avail = (uint32_t)XPCOM_MIN<uint64_t>(avail64, maxCount);
   1.632 +
   1.633 +        // resize result buffer
   1.634 +        uint32_t length = result.Length();
   1.635 +        if (avail > UINT32_MAX - length)
   1.636 +            return NS_ERROR_FILE_TOO_BIG;
   1.637 +        
   1.638 +        result.SetLength(length + avail);
   1.639 +        if (result.Length() != (length + avail))
   1.640 +            return NS_ERROR_OUT_OF_MEMORY;
   1.641 +        char *buf = result.BeginWriting() + length;
   1.642 +        
   1.643 +        uint32_t n;
   1.644 +        rv = stream->Read(buf, avail, &n);
   1.645 +        if (NS_FAILED(rv))
   1.646 +            break;
   1.647 +        if (n != avail)
   1.648 +            result.SetLength(length + n);
   1.649 +        if (n == 0)
   1.650 +            break;
   1.651 +        maxCount -= n;
   1.652 +    }
   1.653 +
   1.654 +    return rv;
   1.655 +}
   1.656 +
   1.657 +//-----------------------------------------------------------------------------
   1.658 +
   1.659 +static NS_METHOD
   1.660 +TestInputStream(nsIInputStream *inStr,
   1.661 +                void *closure,
   1.662 +                const char *buffer,
   1.663 +                uint32_t offset,
   1.664 +                uint32_t count,
   1.665 +                uint32_t *countWritten)
   1.666 +{
   1.667 +    bool *result = static_cast<bool *>(closure);
   1.668 +    *result = true;
   1.669 +    return NS_ERROR_ABORT;  // don't call me anymore
   1.670 +}
   1.671 +
   1.672 +bool
   1.673 +NS_InputStreamIsBuffered(nsIInputStream *stream)
   1.674 +{
   1.675 +    nsCOMPtr<nsIBufferedInputStream> bufferedIn = do_QueryInterface(stream);
   1.676 +    if (bufferedIn) {
   1.677 +        return true;
   1.678 +    }
   1.679 +
   1.680 +    bool result = false;
   1.681 +    uint32_t n;
   1.682 +    nsresult rv = stream->ReadSegments(TestInputStream,
   1.683 +                                       &result, 1, &n);
   1.684 +    return result || NS_SUCCEEDED(rv);
   1.685 +}
   1.686 +
   1.687 +static NS_METHOD
   1.688 +TestOutputStream(nsIOutputStream *outStr,
   1.689 +                 void *closure,
   1.690 +                 char *buffer,
   1.691 +                 uint32_t offset,
   1.692 +                 uint32_t count,
   1.693 +                 uint32_t *countRead)
   1.694 +{
   1.695 +    bool *result = static_cast<bool *>(closure);
   1.696 +    *result = true;
   1.697 +    return NS_ERROR_ABORT;  // don't call me anymore
   1.698 +}
   1.699 +
   1.700 +bool
   1.701 +NS_OutputStreamIsBuffered(nsIOutputStream *stream)
   1.702 +{
   1.703 +    nsCOMPtr<nsIBufferedOutputStream> bufferedOut = do_QueryInterface(stream);
   1.704 +    if (bufferedOut) {
   1.705 +        return true;
   1.706 +    }
   1.707 +
   1.708 +    bool result = false;
   1.709 +    uint32_t n;
   1.710 +    stream->WriteSegments(TestOutputStream, &result, 1, &n);
   1.711 +    return result;
   1.712 +}
   1.713 +
   1.714 +//-----------------------------------------------------------------------------
   1.715 +
   1.716 +NS_METHOD
   1.717 +NS_CopySegmentToStream(nsIInputStream *inStr,
   1.718 +                       void *closure,
   1.719 +                       const char *buffer,
   1.720 +                       uint32_t offset,
   1.721 +                       uint32_t count,
   1.722 +                       uint32_t *countWritten)
   1.723 +{
   1.724 +    nsIOutputStream *outStr = static_cast<nsIOutputStream *>(closure);
   1.725 +    *countWritten = 0;
   1.726 +    while (count) {
   1.727 +        uint32_t n;
   1.728 +        nsresult rv = outStr->Write(buffer, count, &n);
   1.729 +        if (NS_FAILED(rv))
   1.730 +            return rv;
   1.731 +        buffer += n;
   1.732 +        count -= n;
   1.733 +        *countWritten += n;
   1.734 +    }
   1.735 +    return NS_OK;
   1.736 +}
   1.737 +
   1.738 +NS_METHOD
   1.739 +NS_CopySegmentToBuffer(nsIInputStream *inStr,
   1.740 +                       void *closure,
   1.741 +                       const char *buffer,
   1.742 +                       uint32_t offset,
   1.743 +                       uint32_t count,
   1.744 +                       uint32_t *countWritten)
   1.745 +{
   1.746 +    char *toBuf = static_cast<char *>(closure);
   1.747 +    memcpy(&toBuf[offset], buffer, count);
   1.748 +    *countWritten = count;
   1.749 +    return NS_OK;
   1.750 +}
   1.751 +
   1.752 +NS_METHOD
   1.753 +NS_CopySegmentToBuffer(nsIOutputStream *outStr,
   1.754 +                       void *closure,
   1.755 +                       char *buffer,
   1.756 +                       uint32_t offset,
   1.757 +                       uint32_t count,
   1.758 +                       uint32_t *countRead)
   1.759 +{
   1.760 +    const char* fromBuf = static_cast<const char*>(closure);
   1.761 +    memcpy(buffer, &fromBuf[offset], count);
   1.762 +    *countRead = count;
   1.763 +    return NS_OK;
   1.764 +}
   1.765 +
   1.766 +NS_METHOD
   1.767 +NS_DiscardSegment(nsIInputStream *inStr,
   1.768 +                  void *closure,
   1.769 +                  const char *buffer,
   1.770 +                  uint32_t offset,
   1.771 +                  uint32_t count,
   1.772 +                  uint32_t *countWritten)
   1.773 +{
   1.774 +    *countWritten = count;
   1.775 +    return NS_OK;
   1.776 +}
   1.777 +
   1.778 +//-----------------------------------------------------------------------------
   1.779 +
   1.780 +NS_METHOD
   1.781 +NS_WriteSegmentThunk(nsIInputStream *inStr,
   1.782 +                     void *closure,
   1.783 +                     const char *buffer,
   1.784 +                     uint32_t offset,
   1.785 +                     uint32_t count,
   1.786 +                     uint32_t *countWritten)
   1.787 +{
   1.788 +    nsWriteSegmentThunk *thunk = static_cast<nsWriteSegmentThunk *>(closure);
   1.789 +    return thunk->mFun(thunk->mStream, thunk->mClosure, buffer, offset, count,
   1.790 +                       countWritten);
   1.791 +}
   1.792 +
   1.793 +NS_METHOD
   1.794 +NS_FillArray(FallibleTArray<char>& aDest, nsIInputStream *aInput,
   1.795 +             uint32_t aKeep, uint32_t *aNewBytes)
   1.796 +{
   1.797 +  MOZ_ASSERT(aInput, "null stream");
   1.798 +  MOZ_ASSERT(aKeep <= aDest.Length(), "illegal keep count");
   1.799 +
   1.800 +  char* aBuffer = aDest.Elements();
   1.801 +  int64_t keepOffset = int64_t(aDest.Length()) - aKeep;
   1.802 +  if (0 != aKeep && keepOffset > 0) {
   1.803 +    memmove(aBuffer, aBuffer + keepOffset, aKeep);
   1.804 +  }
   1.805 +
   1.806 +  nsresult rv =
   1.807 +    aInput->Read(aBuffer + aKeep, aDest.Capacity() - aKeep, aNewBytes);
   1.808 +  if (NS_FAILED(rv)) {
   1.809 +    *aNewBytes = 0;
   1.810 +  }
   1.811 +  // NOTE: we rely on the fact that the new slots are NOT initialized by
   1.812 +  // SetLengthAndRetainStorage here, see nsTArrayElementTraits::Construct()
   1.813 +  // in nsTArray.h:
   1.814 +  aDest.SetLengthAndRetainStorage(aKeep + *aNewBytes);
   1.815 +
   1.816 +  MOZ_ASSERT(aDest.Length() <= aDest.Capacity(), "buffer overflow");
   1.817 +  return rv;
   1.818 +}

mercurial