1 module hunt.http.HttpOutputStream;
2 
3 import hunt.http.HttpHeader;
4 import hunt.http.HttpMetaData;
5 
6 import hunt.collection;
7 import hunt.stream;
8 import hunt.Exceptions;
9 import hunt.logging;
10 import std.conv;
11 
12 /** 
13  * 
14  */
15 abstract class HttpOutputStream : OutputStream {
16 
17     protected bool clientMode;
18     protected HttpMetaData metaData;
19     protected bool closed;
20     protected bool committed;
21 
22     this(HttpMetaData metaData, bool clientMode) {
23         this.metaData = metaData;
24         this.clientMode = clientMode;
25     }
26 
27     bool isClosed() {
28         return closed;
29     }
30 
31     bool isCommitted() {
32         return committed;
33     }
34 
35     void setMetaData(HttpMetaData metaData) {
36         assert(!closed && !committed, "Stream closed!");
37         this.metaData = metaData;
38     }
39 
40     override
41     void write(int b) {
42         // byte* ptr = cast(byte*)&b;
43         // write(ptr[0..int.sizeof]);
44 
45         write(cast(byte[]) [cast (byte) b]);
46     }
47 
48     override
49     void write(byte[] array, int offset, int length) {
50         assert(array !is null, "The data must be not null");
51         write(BufferUtils.toBuffer(array, offset, length));
52     }
53 
54     alias write = OutputStream.write;
55 
56     // void writeWithContentLength(Collection!ByteBuffer data) {
57     //     if (closed) {
58     //         return;
59     //     }
60 
61     //     try {
62     //         if (!committed) {
63     //             long contentLength = BufferUtils.remaining(data);
64     //             metaData.getFields().put(HttpHeader.CONTENT_LENGTH, contentLength.to!string);
65     //         }
66     //         foreach (ByteBuffer buf ; data) {
67     //             write(buf);
68     //         }
69     //     } finally {
70     //         close();
71     //     }
72     // }
73 
74     void writeWithContentLength(ByteBuffer[] data) {
75         if (closed) {
76             version(HUNT_DEBUG) warning("Then output stream has been closed.");
77             return;
78         }
79 
80         try {
81             if (!committed) {
82                 long contentLength = BufferUtils.remaining(data);
83                 metaData.getFields().put(HttpHeader.CONTENT_LENGTH, contentLength.to!string);
84             }
85             foreach (ByteBuffer buf ; data) {
86                 write(buf);
87             }
88         } finally {
89             close();
90         }        
91     }
92 
93     void writeWithContentLength(ByteBuffer data) {
94         writeWithContentLength([data]);
95     }
96 
97     abstract void commit() ;
98 
99     abstract void write(ByteBuffer data) ;
100 }