admin
2020-06-10 a610f2ab6e543d2cb78c1ef212ac6a74ddc067d9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// Copyright © 2017 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
 
using System;
using System.IO;
 
namespace CefSharp.ResponseFilter
{
    /// <summary>
    /// StreamResponseFilter - copies all data from IResponseFilter.Filter
    /// to the provided Stream. The <see cref="Stream"/> must be writable, no data will be copied otherwise.
    /// The StreamResponseFilter will release it's reference (set to null) to the <see cref="Stream"/> when it's Disposed.
    /// </summary>
    public class StreamResponseFilter : IResponseFilter
    {
        private Stream responseStream;
 
        /// <summary>
        /// StreamResponseFilter constructor
        /// </summary>
        /// <param name="stream">a writable stream</param>
        public StreamResponseFilter(Stream stream)
        {
            responseStream = stream;
        }
 
        bool IResponseFilter.InitFilter()
        {
            return responseStream != null && responseStream.CanWrite;
        }
 
        FilterStatus IResponseFilter.Filter(Stream dataIn, out long dataInRead, Stream dataOut, out long dataOutWritten)
        {
            if (dataIn == null)
            {
                dataInRead = 0;
                dataOutWritten = 0;
 
                return FilterStatus.Done;
            }
 
            //Calculate how much data we can read, in some instances dataIn.Length is
            //greater than dataOut.Length
            dataInRead = Math.Min(dataIn.Length, dataOut.Length);
            dataOutWritten = dataInRead;
 
            var readBytes = new byte[dataInRead];
            dataIn.Read(readBytes, 0, readBytes.Length);
            dataOut.Write(readBytes, 0, readBytes.Length);
 
            //Write buffer to the memory stream
            responseStream.Write(readBytes, 0, readBytes.Length);
 
            //If we read less than the total amount avaliable then we need
            //return FilterStatus.NeedMoreData so we can then write the rest
            if (dataInRead < dataIn.Length)
            {
                return FilterStatus.NeedMoreData;
            }
 
            return FilterStatus.Done;
        }
 
        void IDisposable.Dispose()
        {
            responseStream = null;
        }
    }
}