1 /*
2  * Hunt - A refined core library for D programming language.
3  *
4  * Copyright (C) 2018-2019 HuntLabs
5  *
6  * Website: https://www.huntlabs.net/
7  *
8  * Licensed under the Apache-2.0 License.
9  *
10  */
11 
12 module hunt.io.channel.Common;
13 
14 import hunt.io.IoError;
15 import hunt.io.ByteBuffer;
16 import hunt.io.SimpleQueue;
17 import hunt.util.TaskPool;
18 import hunt.Functions;
19 import hunt.system.Memory;
20 
21 import core.atomic;
22 import std.socket;
23 
24 
25 alias DataReceivedHandler = void delegate(ByteBuffer buffer);
26 alias AcceptHandler = void delegate(Socket socket);
27 alias ErrorEventHandler = Action1!(IoError);
28 
29 alias ConnectionHandler = void delegate(bool isSucceeded);
30 alias UdpDataHandler = void delegate(const(ubyte)[] data, Address addr);
31 
32 @property TaskPool workerPool() @trusted {
33     import std.concurrency : initOnce;
34 
35     __gshared TaskPool pool;
36     return initOnce!pool({
37         return new TaskPool(defaultPoolThreads, true);
38     }());
39 }
40 
41 // __gshared bool useWorkerThread = false;
42 
43 private shared uint _defaultPoolThreads = 0;
44 
45 /**
46 These properties get and set the number of worker threads in the `TaskPool`
47 instance returned by `taskPool`.  The default value is `totalCPUs` - 1.
48 Calling the setter after the first call to `taskPool` does not changes
49 number of worker threads in the instance returned by `taskPool`.
50 */
51 @property uint defaultPoolThreads() @trusted {
52     const local = atomicLoad(_defaultPoolThreads);
53     return local < uint.max ? local : totalCPUs - 1;
54 }
55 
56 /// Ditto
57 @property void defaultPoolThreads(uint newVal) @trusted {
58     atomicStore(_defaultPoolThreads, newVal);
59 }
60 
61 
62 /**
63 */
64 interface Channel {
65 
66 }
67 
68 
69 
70 enum ChannelType : ubyte {
71     Accept = 0,
72     TCP,
73     UDP,
74     Timer,
75     Event,
76     File,
77     None
78 }
79 
80 enum ChannelFlag : ushort {
81     None = 0,
82     Read,
83     Write,
84 
85     OneShot = 8,
86     ETMode = 16
87 }
88 
89 final class UdpDataObject {
90     Address addr;
91     ubyte[] data;
92 }
93 
94 final class BaseTypeObject(T) {
95     T data;
96 }
97 
98 
99 
100 version (HUNT_IO_WORKERPOOL) {
101     alias WritingBufferQueue = MagedNonBlockingQueue!ByteBuffer;
102 } else {
103     alias WritingBufferQueue = SimpleQueue!ByteBuffer;
104 }
105 
106 // alias WritingBufferQueue = MagedNonBlockingQueue!ByteBuffer;
107 // alias WritingBufferQueue = SimpleQueue!ByteBuffer;
108 // alias WritingBufferQueue = MagedBlockingQueue!ByteBuffer;
109 
110 /**
111 */
112 Address createAddress(AddressFamily family = AddressFamily.INET,
113         ushort port = InternetAddress.PORT_ANY) {
114     if (family == AddressFamily.INET6) {
115         // addr = new Internet6Address(port); // bug on windows
116         return new Internet6Address("::", port);
117     } else
118         return new InternetAddress(port);
119 }