1 /*
2  * Collie - An asynchronous event-driven network framework using Dlang development
3  *
4  * Copyright (C) 2015-2017  Shanghai Putao Technology Co., Ltd 
5  *
6  * Developer: putao's Dlang team
7  *
8  * Licensed under the Apache-2.0 License.
9  *
10  */
11 module collie.codec.messagetobyteencoder;
12 
13 import collie.channel.handler;
14 import collie.channel;
15 
16 abstract class MessageToByteEncoder(M) : OutboundHandler!(M, ubyte[])
17 {
18     ubyte[] encode(ref M msg);
19 
20     void callBack(ubyte[] data, size_t len);
21 
22     override void write(Context ctx, win msg, OutboundHandlerCallBack cback = null)
23     {
24         auto buf = encode(msg);
25         if (buf.ptr)
26         {
27             ctx.fireWrite(buf, &callBack);
28             if (cback)
29             {
30                 import std.traits;
31 
32                 static if (isArray!M)
33                     cback(msg, msg.length);
34                 else
35                     cback(msg, M.sizeof);
36             }
37         }
38         else
39         {
40             if (cback)
41                 cback(msg, 0);
42         }
43 
44     }
45 }