Browse Source

import from nxrighthere

Matt Coburn 6 years ago
commit
5c2dc352a8

+ 31 - 0
ENet-CSharp.nuspec

@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="utf-8"?>
+<package xmlns="http://schemas.microsoft.com/packaging/2011/08/nuspec.xsd">
+  <metadata>
+    <id>ENet-CSharp</id>
+    <version>2.2.1</version>
+    <title>ENet-CSharp</title>
+    <authors>Stanislav Denisov</authors>
+    <owners>nxrighthere</owners>
+    <requireLicenseAcceptance>false</requireLicenseAcceptance>
+    <license type="file">license\license.txt</license>
+    <projectUrl>https://github.com/nxrighthere/ENet-CSharp</projectUrl>
+    <description>Reliable UDP networking library extended for the .NET environment</description>
+    <summary></summary>
+    <releaseNotes></releaseNotes>
+    <copyright>(c) 2019 Stanislav Denisov</copyright>
+    <tags>networking udp protocol ipv4 ipv6 gamedev</tags>
+  </metadata>
+  <files>
+    <file src="build\ENet-CSharp.targets" target="build\ENet-CSharp.targets" />
+    <file src="lib\net35\ENet-CSharp.dll" target="lib\net35\ENet-CSharp.dll" />
+    <file src="lib\netcoreapp2.0\ENet-CSharp.dll" target="lib\netcoreapp2.0\ENet-CSharp.dll" />
+    <file src="lib\netcoreapp2.0\enet.dll" target="lib\netcoreapp2.0\enet.dll" />
+    <file src="lib\netcoreapp2.0\enet.dylib" target="lib\netcoreapp2.0\enet.dylib" />
+    <file src="lib\netcoreapp2.0\libenet.so" target="lib\netcoreapp2.0\libenet.so" />
+    <file src="lib\netstandard2.0\ENet-CSharp.dll" target="lib\netstandard2.0\ENet-CSharp.dll" />
+    <file src="lib\enet.dll" target="lib\enet.dll" />
+    <file src="lib\enet.dylib" target="lib\enet.dylib" />
+    <file src="lib\libenet.so" target="lib\libenet.so" />
+    <file src="license\license.txt" target="license\license.txt" />
+  </files>
+</package>

+ 21 - 0
LICENSE

@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2018 Stanislav Denisov ([email protected])
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.

+ 414 - 0
README.md

@@ -0,0 +1,414 @@
+<p align="center"> 
+  <img src="https://i.imgur.com/CxkUxTs.png" alt="alt logo">
+</p>
+
+[![GitHub release](https://img.shields.io/github/release/nxrighthere/ENet-CSharp.svg)](https://github.com/nxrighthere/ENet-CSharp/releases) [![PayPal](https://drive.google.com/uc?id=1OQrtNBVJehNVxgPf6T6yX1wIysz1ElLR)](https://www.paypal.me/nxrighthere) [![Bountysource](https://drive.google.com/uc?id=19QRobscL8Ir2RL489IbVjcw3fULfWS_Q)](https://salt.bountysource.com/checkout/amount?team=nxrighthere) [![Coinbase](https://drive.google.com/uc?id=1LckuF-IAod6xmO9yF-jhTjq1m-4f7cgF)](https://commerce.coinbase.com/checkout/03e11816-b6fc-4e14-b974-29a1d0886697)
+
+This project is based on collaborative work with [@inlife](https://github.com/inlife) and inherited all features of the custom [fork](https://github.com/zpl-c/enet) where the native library was heavily modified. You can find the most notable changes [here](https://github.com/nxrighthere/ENet-CSharp/issues/22#issuecomment-432982154). This version is extended, optimized, and involves new features that were not available before to boost the development process and run safely in the managed .NET environment with the highest possible performance.
+
+Although the project is called ENet-CSharp, this is not just a C# wrapper for the native C library, but an independent fork which is incompatible with any other ENet implementation including the original one since 2.0 version. Programmers who are using C/C++ languages can utilize this fork as well in any projects.
+
+Features:
+
+- Lightweight and straightforward
+- Low resource consumption
+- Dual-stack IPv4/IPv6 support
+- Connection management
+- Sequencing
+- Channels
+- Reliability
+- Fragmentation and reassembly
+- Compression
+- Aggregation
+- Adaptability
+- Portability
+
+Please, read [common mistakes](https://github.com/nxrighthere/ENet-CSharp/issues/45) during integration and check [this](https://github.com/nxrighthere/ENet-CSharp/issues?q=is%3Aissue+is%3Aclosed) section before opening a new issue.
+
+Building
+--------
+To build the native library appropriate software is required:
+
+For desktop platforms [CMake](https://cmake.org/download/) with GNU Make or Visual Studio.
+
+For mobile platforms [NDK](https://developer.android.com/ndk/downloads/) for Android and [Xcode](https://developer.apple.com/xcode/) for iOS. Make sure that all compiled libraries are assigned to appropriate platforms and CPU architectures.
+
+Define `ENET_LZ4` to build the library with support for an optional packet-level compression.
+
+A managed assembly can be built using any available compiling platform that supports C# 3.0 or higher.
+
+Compiled libraries
+--------
+You can grab compiled libraries from the [release](https://github.com/nxrighthere/ENet-CSharp/releases) section or from [NuGet](https://www.nuget.org/packages/ENet-CSharp):
+
+`ENet-CSharp` contains compiled assembly with native libraries for the .NET environment (.NET Standard 2.0).
+
+`ENet-Unity` contains script with native libraries for the Unity.
+
+These packages are provided only for traditional platforms: Windows, Linux, and MacOS (x64).
+
+Usage
+--------
+Before starting to work, the library should be initialized using `ENet.Library.Initialize();` function.
+
+After the work is done, deinitialize the library using `ENet.Library.Deinitialize();` function.
+
+### .NET environment
+##### Start a new server:
+```c#
+using (Host server = new Host()) {
+	Address address = new Address();
+
+	address.Port = port;
+	server.Create(address, maxClients);
+
+	Event netEvent;
+
+	while (!Console.KeyAvailable) {
+		bool polled = false;
+
+		while (!polled) {
+			if (server.CheckEvents(out netEvent) <= 0) {
+				if (server.Service(15, out netEvent) <= 0)
+					break;
+
+				polled = true;
+			}
+
+			switch (netEvent.Type) {
+				case EventType.None:
+					break;
+
+				case EventType.Connect:
+					Console.WriteLine("Client connected - ID: " + netEvent.Peer.ID + ", IP: " + netEvent.Peer.IP);
+					break;
+
+				case EventType.Disconnect:
+					Console.WriteLine("Client disconnected - ID: " + netEvent.Peer.ID + ", IP: " + netEvent.Peer.IP);
+					break;
+
+				case EventType.Timeout:
+					Console.WriteLine("Client timeout - ID: " + netEvent.Peer.ID + ", IP: " + netEvent.Peer.IP);
+					break;
+
+				case EventType.Receive:
+					Console.WriteLine("Packet received from - ID: " + netEvent.Peer.ID + ", IP: " + netEvent.Peer.IP + ", Channel ID: " + netEvent.ChannelID + ", Data length: " + netEvent.Packet.Length);
+					netEvent.Packet.Dispose();
+					break;
+			}
+		}
+	}
+
+	server.Flush();
+}
+```
+
+##### Start a new client:
+```c#
+using (Host client = new Host()) {
+	Address address = new Address();
+
+	address.SetHost(ip);
+	address.Port = port;
+	client.Create();
+
+	Peer peer = client.Connect(address);
+
+	Event netEvent;
+
+	while (!Console.KeyAvailable) {
+		bool polled = false;
+
+		while (!polled) {
+			if (client.CheckEvents(out netEvent) <= 0) {
+				if (client.Service(15, out netEvent) <= 0)
+					break;
+
+				polled = true;
+			}
+
+			switch (netEvent.Type) {
+				case EventType.None:
+					break;
+
+				case EventType.Connect:
+					Console.WriteLine("Client connected to server - ID: " + peer.ID);
+					break;
+
+				case EventType.Disconnect:
+					Console.WriteLine("Client disconnected from server");
+					break;
+
+				case EventType.Timeout:
+					Console.WriteLine("Client connection timeout");
+					break;
+
+				case EventType.Receive:
+					Console.WriteLine("Packet received from server - Channel ID: " + netEvent.ChannelID + ", Data length: " + netEvent.Packet.Length);
+					netEvent.Packet.Dispose();
+					break;
+			}
+		}
+	}
+
+	client.Flush();
+}
+```
+
+##### Create and send a new packet:
+```csharp
+Packet packet = default(Packet);
+byte[] data = new byte[64];
+
+packet.Create(data);
+peer.Send(channelID, ref packet);
+```
+
+##### Copy payload from a packet:
+```csharp
+byte[] buffer = new byte[1024];
+
+netEvent.Packet.CopyTo(buffer);
+```
+
+##### Integrate with a custom memory allocator:
+```csharp
+AllocCallback OnMemoryAllocate = (size) => {
+	return Marshal.AllocHGlobal(size);
+};
+
+FreeCallback OnMemoryFree = (memory) => {
+	Marshal.FreeHGlobal(memory);
+};
+
+NoMemoryCallback OnNoMemory = () => {
+	throw new OutOfMemoryException();
+};
+
+Callbacks callbacks = new Callbacks(OnMemoryAllocate, OnMemoryFree, OnNoMemory);
+
+if (ENet.Library.Initialize(callbacks))
+	Console.WriteLine("ENet successfully initialized using a custom memory allocator");
+```
+
+### Unity
+Usage is almost the same as in the .NET environment, except that the console functions must be replaced with functions provided by Unity. If the `Host.Service()` will be called in a game loop, then make sure that the timeout parameter set to 0 which means non-blocking. Also, keep Unity run in background by enabling the appropriate option in the player settings.
+
+Multi-threading
+--------
+### Strategy
+The best-known strategy is to use ENet in an independent I/O thread and utilize [inter-thread messaging](http://www.1024cores.net/home/lock-free-algorithms/queues) techniques for transferring data across threads/tasks without any locks/mutexes. Non-blocking queues like [Ring Buffer](https://www.slideshare.net/trishagee/introduction-to-the-disruptor) was designed for such purposes. High-level abstractions and logic can be parallelized [using workers](https://forum.unity.com/threads/showcase-enet-unity-ecs-5000-real-time-player-simulation.605656/), then communicate with I/O thread and enqueue/dequeue messages to send/receive data across the network.
+
+### Functionality
+In general, ENet is not thread-safe, but some of its functions can be used safely if the user is careful enough:
+
+`Packet` structure and its functions are safe until a packet is only moving across threads by value and a custom memory allocator is not used.
+
+`Peer.ID` as soon as a pointer to a peer was obtained from the native side, the ID will be cached in `Peer` structure for further actions with objects that assigned to that ID. `Peer` structure can be moved across threads by value, but its functions  are not thread-safe because data in memory may change by the service in another thread.
+
+`Library.Time` utilizes atomic primitives internally for managing local monotonic time.
+
+API reference
+--------
+### Enumerations
+#### PacketFlags
+Definitions of a flags for `Peer.Send()` function:
+
+`PacketFlags.None` unreliable sequenced, delivery of packet is not guaranteed.
+
+`PacketFlags.Reliable` reliable sequenced, a packet must be received by the target peer and resend attempts should be made until the packet is delivered.
+
+`PacketFlags.Unsequenced` a packet will not be sequenced with other packets and may be delivered out of order.
+
+`PacketFlags.NoAllocate` a packet will not allocate data, and the user must supply it instead.
+
+`PacketFlags.UnreliableFragment` a packet will be unreliably fragmented if it exceeds the MTU. By default packets larger than MTU fragmented reliably.
+
+#### EventType
+Definitions of event types for `Event.Type` property:
+
+`EventType.None` no event occurred within the specified time limit.
+
+`EventType.Connect` a connection request initiated by `Peer.Connect()` function has completed. `Event.Peer` returns a peer which successfully connected. `Event.Data` returns user-supplied data describing the connection or 0 if none is available.
+
+`EventType.Disconnect` a peer has disconnected. This event is generated on a successful completion of a disconnect initiated by `Peer.Disconnect`. `Event.Peer` returns a peer which disconnected. `Event.Data` returns user-supplied data describing the disconnection or 0 if none is available.
+
+`EventType.Receive` a packet has been received from a peer. `Event.Peer` returns a peer which sent the packet. `Event.ChannelID` specifies the channel number upon which the packet was received. `Event.Packet` returns a packet that was received, and this packet must be destroyed using `Event.Packet.Dispose()` function after use.
+
+`EventType.Timeout` a peer has timed out. This event occurs if a peer has timed out or if a connection request initialized by `Peer.Connect` has timed out. `Event.Peer` returns a peer which timed out.
+
+#### PeerState
+Definitions of peer states for `Peer.State` property:
+
+`PeerState.Uninitialized` a peer not initialized.
+
+`PeerState.Disconnected` a peer disconnected or timed out.
+
+`PeerState.Connecting` a peer connection in-progress.
+
+`PeerState.Connected` a peer successfully connected.
+
+`PeerState.Disconnecting` a peer disconnection in-progress.
+
+`PeerState.Zombie` a peer not properly disconnected.
+
+### Delegates
+#### Memory callbacks
+Provides per application events.
+
+`AllocCallback(IntPtr size)` notifies when a memory is requested for allocation. Expects pointer to the newly allocated memory.
+
+`FreeCallback(IntPtr memory)` notifies when the memory can be freed.
+
+`NoMemoryCallback()` notifies when memory is not enough.
+
+#### Packet callbacks
+Provides per packet events.
+
+`PacketFreeCallback(Packet packet)` notifies when a packet is being destroyed.
+
+### Structures
+#### Address
+Contains marshalled structure with host data and port number.
+
+`Address.Port` set or get a port number.
+
+`Address.GetHost()` attempts to do a reverse lookup from the address. Returns a string with a resolved name or an IP address.
+
+`Address.SetHost(string hostName)` set host name or an IP address (IPv4/IPv6). Should be used for binding to a network interface or for connection to a foreign host. Returns true on success or false on failure.
+
+#### Event
+Contains marshalled structure with the event type, managed pointer to the peer, channel ID, user-supplied data, and managed pointer to the packet.
+
+`Event.Type` returns a type of the event.
+
+`Event.Peer` returns a peer that generated a connect, disconnect, receive or a timeout event.
+
+`Event.ChannelID` returns a channel ID on the peer that generated the event, if appropriate.
+
+`Event.Data` returns user-supplied data, if appropriate.
+
+`Event.Packet` returns a packet associated with the event, if appropriate.
+
+#### Packet
+Contains a managed pointer to the packet.
+
+`Packet.Dispose()` destroys the packet. Should be called only when the packet was obtained from `EventType.Receive` event.
+
+`Packet.IsSet` returns a state of the managed pointer.
+
+`Packet.Data` returns a managed pointer to the packet data.
+
+`Packet.Length` returns a length of payload in the packet.
+
+`Packet.HasReferences` checks references to the packet.
+
+`Packet.SetFreeCallback(PacketFreeCallback callback)` set callback to notify the programmer when an appropriate packet is being destroyed. Pointer `IntPtr` to a callback can be used instead of a reference to a delegate.
+
+`Packet.Create(byte[] data, int offset, int length, PacketFlags flags)` creates a packet that may be sent to a peer. The offset, length and packet flags parameters are optional. Multiple flags can be specified at once. Pointer `IntPtr` to a native buffer can be used instead of a reference to a byte array.
+
+`Packet.CopyTo(byte[] destination)` copies payload from the packet to the destination array.
+
+#### Peer
+Contains a managed pointer to the peer and cached ID.
+
+`Peer.IsSet` returns a state of the managed pointer.
+
+`Peer.ID` returns a peer ID.
+
+`Peer.IP` returns an IP address in a printable form.
+
+`Peer.Port` returns a port number.
+
+`Peer.MTU` returns an MTU.
+
+`Peer.State` returns a peer state described in the `PeerState` enumeration.
+
+`Peer.RoundTripTime` returns a round trip time in milliseconds.
+
+`Peer.LastSendTime` returns a last packet send time in milliseconds.
+
+`Peer.LastReceiveTime` returns a last packet receive time in milliseconds.
+
+`Peer.PacketsSent` returns a total number of packets sent during the connection.
+
+`Peer.PacketsLost` returns a total number of lost packets during the connection.
+
+`Peer.BytesSent` returns a total number of bytes sent during the connection.
+
+`Peer.BytesReceived` returns a total number of bytes received during the connection.
+
+`Peer.Data` set or get the user-supplied data. Should be used with an explicit cast to appropriate data type.
+
+`Peer.ConfigureThrottle(uint interval, uint acceleration, uint deceleration)` configures throttle parameter for a peer. Unreliable packets are dropped by ENet in response to the varying conditions of the connection to the peer. The throttle represents a probability that an unreliable packet should not be dropped and thus sent by ENet to the peer. The lowest mean round trip time from the sending of a reliable packet to the receipt of its acknowledgment is measured over an amount of time specified by the interval parameter in milliseconds. If a measured round trip time happens to be significantly less than the mean round trip time measured over the interval, then the throttle probability is increased to allow more traffic by an amount specified in the acceleration parameter, which is a ratio to the `Library.throttleScale` constant. If a measured round trip time happens to be significantly greater than the mean round trip time measured over the interval, then the throttle probability is decreased to limit traffic by an amount specified in the deceleration parameter, which is a ratio to the `Library.throttleScale` constant. When the throttle has a value of `Library.throttleScale`, no unreliable packets are dropped by ENet, and so 100% of all unreliable packets will be sent. When the throttle has a value of 0, all unreliable packets are dropped by ENet, and so 0% of all unreliable packets will be sent. Intermediate values for the throttle represent intermediate probabilities between 0% and 100% of unreliable packets being sent. The bandwidth limits of the local and foreign hosts are taken into account to determine a sensible limit for the throttle probability above which it should not raise even in the best of conditions.
+
+`Peer.Send(byte channelID, ref Packet packet)` queues a packet to be sent. Returns true on success or false on failure.
+
+`Peer.Ping()` sends a ping request to a peer. ENet automatically pings all connected peers at regular intervals, however, this function may be called to ensure more frequent ping requests.
+
+`Peer.PingInterval(uint interval)` sets an interval at which pings will be sent to a peer. Pings are used both to monitor the liveness of the connection and also to dynamically adjust the throttle during periods of low traffic so that the throttle has reasonable responsiveness during traffic spikes.
+
+`Peer.Timeout(uint timeoutLimit, uint timeoutMinimum, uint timeoutMaximum)` sets a timeout parameters for a peer. The timeout parameters control how and when a peer will timeout from a failure to acknowledge reliable traffic. Timeout values used in the semi-linear mechanism, where if a reliable packet is not acknowledged within an average round trip time plus a variance tolerance until timeout reaches a set limit. If the timeout is thus at this limit and reliable packets have been sent but not acknowledged within a certain minimum time period, the peer will be disconnected. Alternatively, if reliable packets have been sent but not acknowledged for a certain maximum time period, the peer will be disconnected regardless of the current timeout limit value.
+
+`Peer.Disconnect(uint data)` request a disconnection from a peer.
+
+`Peer.DisconnectNow(uint data)` force an immediate disconnection from a peer.
+
+`Peer.DisconnectLater(uint data)` request a disconnection from a peer, but only after all queued outgoing packets are sent.
+
+`Peer.Reset()` forcefully disconnects a peer. The foreign host represented by the peer is not notified of the disconnection and will timeout on its connection to the local host.
+
+### Classes
+#### Host
+Contains a managed pointer to the host.
+
+`Host.Dispose()` destroys the host.
+
+`Host.IsSet` returns a state of the managed pointer.
+
+`Host.PeersCount` returns a number of connected peers.
+
+`Host.PacketsSent` returns a total number of packets sent during the session.
+
+`Host.PacketsReceived` returns a total number of packets received during the session.
+
+`Host.BytesSent` returns a total number of bytes sent during the session.
+
+`Host.BytesReceived` returns a total number of bytes received during the session.
+
+`Host.Create(Address? address, int peerLimit, int channelLimit, uint incomingBandwidth, uint outgoingBandwidth)` creates a host for communicating with peers. The bandwidth parameters determine the window size of a connection which limits the number of reliable packets that may be in transit at any given time. ENet will strategically drop packets on specific sides of a connection between hosts to ensure the host's bandwidth is not overwhelmed. All the parameters are optional except the address and peer limit in cases where the function is used to create a host which will listen for incoming connections.
+
+`Host.EnableCompression()` enables packet-level compression.
+
+`Host.PreventConnections(bool state)` prevents access to the host for new incoming connections. This function makes the host completely invisible from outside, any peer that attempts to connect to it will be timed out.
+
+`Host.Broadcast(byte channelID, ref Packet packet, Peer[] peers)` queues a packet to be sent to a range of peers or to all peers associated with the host if the optional peers parameter is not used. Any zeroed `Peer` structure in an array will be excluded from the broadcast.
+
+`Host.CheckEvents(out Event @event)` checks for any queued events on the host and dispatches one if available. Returns > 0 if an event was dispatched, 0 if no events are available, < 0 on failure.
+
+`Host.Connect(Address address, int channelLimit, uint data)` initiates a connection to a foreign host. Returns a peer representing the foreign host on success or throws an exception on failure. The peer returned will not have completed the connection until `Host.Service()` notifies of an `EventType.Connect` event. The channel limit and user-supplied data parameters are optional.
+
+`Host.Service(int timeout, out Event @event)` waits for events on the specified host and shuttles packets between the host and its peers. ENet uses a polled event model to notify the user of significant events. ENet hosts are polled for events with this function, where an optional timeout value in milliseconds may be specified to control how long ENet will poll. If a timeout of 0 is specified, this function will return immediately if there are no events to dispatch. Otherwise, it will return 1 if an event was dispatched within the specified timeout. This function should be regularly called to ensure packets are sent and received, otherwise, traffic spikes will occur leading to increased latency. The timeout parameter set to 0 means non-blocking which required for cases where the function is called in a game loop.
+
+`Host.SetBandwidthLimit(uint incomingBandwidth, uint outgoingBandwidth)` adjusts the bandwidth limits of a host in bytes per second.
+
+`Host.SetChannelLimit(int channelLimit)` limits the maximum allowed channels of future incoming connections. 
+
+`Host.Flush()` sends any queued packets on the specified host to its designated peers. 
+
+#### Library
+Contains constant fields.
+
+`Library.maxChannelCount` the maximum possible number of channels.
+
+`Library.maxPeers` the maximum possible number of peers.
+
+`Library.maxPacketSize` the maximum size of a packet.
+
+`Library.version` the current version of the native library.
+
+`Library.Initialize(Callbacks inits)` initializes the native library. Callbacks parameter is optional and should be used only with a custom memory allocator. Should be called before starting the work. Returns true on success or false on failure.
+
+`Library.Deinitialize()` deinitializes the native library. Should be called after the work is done.
+
+`Library.Time` returns a current local monotonic time in milliseconds. It never reset while the application remains alive.

+ 21 - 0
Source/Managed/ENet-CSharp.csproj

@@ -0,0 +1,21 @@
+<Project Sdk="Microsoft.NET.Sdk">
+
+  <PropertyGroup>
+    <OutputType>Library</OutputType>
+    <TargetFrameworks>netstandard2.0;netcoreapp2.0</TargetFrameworks>
+    <RootNamespace>ENet</RootNamespace>
+  </PropertyGroup>
+
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
+    <Optimize>false</Optimize>
+    <CheckForOverflowUnderflow>True</CheckForOverflowUnderflow>
+    <LangVersion>3</LangVersion>
+  </PropertyGroup>
+
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
+    <Optimize>true</Optimize>
+    <CheckForOverflowUnderflow>True</CheckForOverflowUnderflow>
+    <LangVersion>3</LangVersion>
+  </PropertyGroup>
+
+</Project>

+ 1030 - 0
Source/Managed/ENet.cs

@@ -0,0 +1,1030 @@
+/*
+ *  Managed C# wrapper for an extended version of ENet
+ *  Copyright (c) 2013 James Bellinger
+ *  Copyright (c) 2016 Nate Shoffner
+ *  Copyright (c) 2018 Stanislav Denisov
+ *
+ *  Permission is hereby granted, free of charge, to any person obtaining a copy
+ *  of this software and associated documentation files (the "Software"), to deal
+ *  in the Software without restriction, including without limitation the rights
+ *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ *  copies of the Software, and to permit persons to whom the Software is
+ *  furnished to do so, subject to the following conditions:
+ *
+ *  The above copyright notice and this permission notice shall be included in all
+ *  copies or substantial portions of the Software.
+ *
+ *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ *  SOFTWARE.
+ */
+
+using System;
+using System.Runtime.InteropServices;
+using System.Security;
+using System.Text;
+
+namespace ENet {
+	[Flags]
+	public enum PacketFlags {
+		None = 0,
+		Reliable = 1 << 0,
+		Unsequenced = 1 << 1,
+		NoAllocate = 1 << 2,
+		UnreliableFragment = 1 << 3
+	}
+
+	public enum EventType {
+		None = 0,
+		Connect = 1,
+		Disconnect = 2,
+		Receive = 3,
+		Timeout = 4
+	}
+
+	public enum PeerState {
+		Uninitialized = -1,
+		Disconnected = 0,
+		Connecting = 1,
+		AcknowledgingConnect = 2,
+		ConnectionPending = 3,
+		ConnectionSucceeded = 4,
+		Connected = 5,
+		DisconnectLater = 6,
+		Disconnecting = 7,
+		AcknowledgingDisconnect = 8,
+		Zombie = 9
+	}
+
+	[StructLayout(LayoutKind.Sequential)]
+	public struct ENetAddress {
+		[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
+		public byte[] host;
+		public ushort port;
+		public ushort scope;
+	}
+
+	[StructLayout(LayoutKind.Sequential)]
+	public struct ENetEvent {
+		public EventType type;
+		public IntPtr peer;
+		public byte channelID;
+		public uint data;
+		public IntPtr packet;
+	}
+
+	[StructLayout(LayoutKind.Sequential)]
+	public struct ENetCallbacks {
+		public AllocCallback malloc;
+		public FreeCallback free;
+		public NoMemoryCallback noMemory;
+	}
+
+	public delegate IntPtr AllocCallback(IntPtr size);
+	public delegate void FreeCallback(IntPtr memory);
+	public delegate void NoMemoryCallback();
+	public delegate void PacketFreeCallback(Packet packet);
+
+	internal static class ArrayPool {
+		[ThreadStatic]
+		private static byte[] byteBuffer;
+		[ThreadStatic]
+		private static IntPtr[] pointerBuffer;
+
+		public static byte[] GetByteBuffer() {
+			if (byteBuffer == null)
+				byteBuffer = new byte[64];
+
+			return byteBuffer;
+		}
+
+		public static IntPtr[] GetPointerBuffer() {
+			if (pointerBuffer == null)
+				pointerBuffer = new IntPtr[Library.maxPeers];
+
+			return pointerBuffer;
+		}
+	}
+
+	public struct Address {
+		private ENetAddress nativeAddress;
+
+		internal ENetAddress NativeData {
+			get {
+				return nativeAddress;
+			}
+
+			set {
+				nativeAddress = value;
+			}
+		}
+
+		public Address(ENetAddress address) {
+			nativeAddress = address;
+		}
+
+		public ushort Port {
+			get {
+				return nativeAddress.port;
+			}
+
+			set {
+				nativeAddress.port = value;
+			}
+		}
+
+		public string GetHost() {
+			StringBuilder hostName = new StringBuilder(1024);
+
+			if (Native.enet_address_get_host(nativeAddress, hostName, (IntPtr)hostName.Capacity) != 0)
+				return String.Empty;
+
+			return hostName.ToString();
+		}
+
+		public bool SetHost(string hostName) {
+			if (hostName == null)
+				throw new ArgumentNullException("hostName");
+
+			return Native.enet_address_set_host(ref nativeAddress, hostName) == 0;
+		}
+	}
+
+	public struct Event {
+		private ENetEvent nativeEvent;
+
+		internal ENetEvent NativeData {
+			get {
+				return nativeEvent;
+			}
+
+			set {
+				nativeEvent = value;
+			}
+		}
+
+		public Event(ENetEvent @event) {
+			nativeEvent = @event;
+		}
+
+		public EventType Type {
+			get {
+				return nativeEvent.type;
+			}
+		}
+
+		public Peer Peer {
+			get {
+				return new Peer(nativeEvent.peer);
+			}
+		}
+
+		public byte ChannelID {
+			get {
+				return nativeEvent.channelID;
+			}
+		}
+
+		public uint Data {
+			get {
+				return nativeEvent.data;
+			}
+		}
+
+		public Packet Packet {
+			get {
+				return new Packet(nativeEvent.packet);
+			}
+		}
+	}
+
+	public class Callbacks {
+		private ENetCallbacks nativeCallbacks;
+
+		internal ENetCallbacks NativeData {
+			get {
+				return nativeCallbacks;
+			}
+
+			set {
+				nativeCallbacks = value;
+			}
+		}
+
+		public Callbacks(AllocCallback allocCallback, FreeCallback freeCallback, NoMemoryCallback noMemoryCallback) {
+			nativeCallbacks.malloc = allocCallback;
+			nativeCallbacks.free = freeCallback;
+			nativeCallbacks.noMemory = noMemoryCallback;
+		}
+	}
+
+	public struct Packet : IDisposable {
+		private IntPtr nativePacket;
+
+		internal IntPtr NativeData {
+			get {
+				return nativePacket;
+			}
+
+			set {
+				nativePacket = value;
+			}
+		}
+
+		public Packet(IntPtr packet) {
+			nativePacket = packet;
+		}
+
+		public void Dispose() {
+			if (nativePacket != IntPtr.Zero) {
+				Native.enet_packet_dispose(nativePacket);
+				nativePacket = IntPtr.Zero;
+			}
+		}
+
+		public bool IsSet {
+			get {
+				return nativePacket != IntPtr.Zero;
+			}
+		}
+
+		public IntPtr Data {
+			get {
+				CheckCreated();
+
+				return Native.enet_packet_get_data(nativePacket);
+			}
+		}
+
+		public int Length {
+			get {
+				CheckCreated();
+
+				return Native.enet_packet_get_length(nativePacket);
+			}
+		}
+
+		public bool HasReferences {
+			get {
+				CheckCreated();
+
+				return Native.enet_packet_check_references(nativePacket) != 0;
+			}
+		}
+
+		internal void CheckCreated() {
+			if (nativePacket == IntPtr.Zero)
+				throw new InvalidOperationException("Packet not created");
+		}
+
+		public void SetFreeCallback(IntPtr callback) {
+			CheckCreated();
+
+			Native.enet_packet_set_free_callback(nativePacket, callback);
+		}
+
+		public void SetFreeCallback(PacketFreeCallback callback) {
+			CheckCreated();
+
+			Native.enet_packet_set_free_callback(nativePacket, Marshal.GetFunctionPointerForDelegate(callback));
+		}
+
+		public void Create(byte[] data) {
+			if (data == null)
+				throw new ArgumentNullException("data");
+
+			Create(data, data.Length);
+		}
+
+		public void Create(byte[] data, int length) {
+			Create(data, length, PacketFlags.None);
+		}
+
+		public void Create(byte[] data, PacketFlags flags) {
+			Create(data, data.Length, flags);
+		}
+
+		public void Create(byte[] data, int length, PacketFlags flags) {
+			if (data == null)
+				throw new ArgumentNullException("data");
+
+			if (length < 0 || length > data.Length)
+				throw new ArgumentOutOfRangeException();
+
+			nativePacket = Native.enet_packet_create(data, (IntPtr)length, flags);
+		}
+
+		public void Create(IntPtr data, int length, PacketFlags flags) {
+			if (data == IntPtr.Zero)
+				throw new ArgumentNullException("data");
+
+			if (length < 0)
+				throw new ArgumentOutOfRangeException();
+
+			nativePacket = Native.enet_packet_create(data, (IntPtr)length, flags);
+		}
+
+		public void Create(byte[] data, int offset, int length, PacketFlags flags) {
+			if (data == null)
+				throw new ArgumentNullException("data");
+
+			if (offset < 0 || length < 0 || length > data.Length)
+				throw new ArgumentOutOfRangeException();
+
+			nativePacket = Native.enet_packet_create_offset(data, (IntPtr)length, (IntPtr)offset, flags);
+		}
+
+		public void Create(IntPtr data, int offset, int length, PacketFlags flags) {
+			if (data == IntPtr.Zero)
+				throw new ArgumentNullException("data");
+
+			if (offset < 0 || length < 0)
+				throw new ArgumentOutOfRangeException();
+
+			nativePacket = Native.enet_packet_create_offset(data, (IntPtr)length, (IntPtr)offset, flags);
+		}
+
+		public void CopyTo(byte[] destination) {
+			if (destination == null)
+				throw new ArgumentNullException("destination");
+
+			Marshal.Copy(Data, destination, 0, Length);
+		}
+	}
+
+	public class Host : IDisposable {
+		private IntPtr nativeHost;
+
+		internal IntPtr NativeData {
+			get {
+				return nativeHost;
+			}
+
+			set {
+				nativeHost = value;
+			}
+		}
+
+		public void Dispose() {
+			Dispose(true);
+			GC.SuppressFinalize(this);
+		}
+
+		protected virtual void Dispose(bool disposing) {
+			if (nativeHost != IntPtr.Zero) {
+				Native.enet_host_destroy(nativeHost);
+				nativeHost = IntPtr.Zero;
+			}
+		}
+
+		~Host() {
+			Dispose(false);
+		}
+
+		public bool IsSet {
+			get {
+				return nativeHost != IntPtr.Zero;
+			}
+		}
+
+		public uint PeersCount {
+			get {
+				CheckCreated();
+
+				return Native.enet_host_get_peers_count(nativeHost);
+			}
+		}
+
+		public uint PacketsSent {
+			get {
+				CheckCreated();
+
+				return Native.enet_host_get_packets_sent(nativeHost);
+			}
+		}
+
+		public uint PacketsReceived {
+			get {
+				CheckCreated();
+
+				return Native.enet_host_get_packets_received(nativeHost);
+			}
+		}
+
+		public uint BytesSent {
+			get {
+				CheckCreated();
+
+				return Native.enet_host_get_bytes_sent(nativeHost);
+			}
+		}
+
+		public uint BytesReceived {
+			get {
+				CheckCreated();
+
+				return Native.enet_host_get_bytes_received(nativeHost);
+			}
+		}
+
+		internal void CheckCreated() {
+			if (nativeHost == IntPtr.Zero)
+				throw new InvalidOperationException("Host not created");
+		}
+
+		private void CheckChannelLimit(int channelLimit) {
+			if (channelLimit < 0 || channelLimit > Library.maxChannelCount)
+				throw new ArgumentOutOfRangeException("channelLimit");
+		}
+
+		public void Create() {
+			Create(null, 1, 0);
+		}
+
+		public void Create(Address? address, int peerLimit) {
+			Create(address, peerLimit, 0);
+		}
+
+		public void Create(Address? address, int peerLimit, int channelLimit) {
+			Create(address, peerLimit, channelLimit, 0, 0);
+		}
+
+		public void Create(int peerLimit, int channelLimit) {
+			Create(null, peerLimit, channelLimit, 0, 0);
+		}
+
+		public void Create(int peerLimit, int channelLimit, uint incomingBandwidth, uint outgoingBandwidth) {
+			Create(null, peerLimit, channelLimit, incomingBandwidth, outgoingBandwidth);
+		}
+
+		public void Create(Address? address, int peerLimit, int channelLimit, uint incomingBandwidth, uint outgoingBandwidth) {
+			if (nativeHost != IntPtr.Zero)
+				throw new InvalidOperationException("Host already created");
+
+			if (peerLimit < 0 || peerLimit > Library.maxPeers)
+				throw new ArgumentOutOfRangeException("peerLimit");
+
+			CheckChannelLimit(channelLimit);
+
+			if (address != null) {
+				var nativeAddress = address.Value.NativeData;
+
+				nativeHost = Native.enet_host_create(ref nativeAddress, (IntPtr)peerLimit, (IntPtr)channelLimit, incomingBandwidth, outgoingBandwidth);
+			} else {
+				nativeHost = Native.enet_host_create(IntPtr.Zero, (IntPtr)peerLimit, (IntPtr)channelLimit, incomingBandwidth, outgoingBandwidth);
+			}
+
+			if (nativeHost == IntPtr.Zero)
+				throw new InvalidOperationException("Host creation call failed");
+		}
+
+		public void EnableCompression() {
+			CheckCreated();
+
+			Native.enet_host_enable_compression(nativeHost);
+		}
+
+		public void PreventConnections(bool state) {
+			CheckCreated();
+
+			Native.enet_host_prevent_connections(nativeHost, (byte)(state ? 1 : 0));
+		}
+
+		public void Broadcast(byte channelID, ref Packet packet) {
+			CheckCreated();
+
+			packet.CheckCreated();
+			Native.enet_host_broadcast(nativeHost, channelID, packet.NativeData);
+			packet.NativeData = IntPtr.Zero;
+		}
+
+		public void Broadcast(byte channelID, ref Packet packet, Peer[] peers) {
+			CheckCreated();
+
+			packet.CheckCreated();
+
+			if (peers.Length > 0) {
+				IntPtr[] nativePeers = ArrayPool.GetPointerBuffer();
+				int nativeCount = 0;
+
+				for (int i = 0; i < peers.Length; i++) {
+					if (peers[i].NativeData != IntPtr.Zero) {
+						nativePeers[nativeCount] = peers[i].NativeData;
+						nativeCount++;
+					}
+				}
+
+				Native.enet_host_broadcast_selective(nativeHost, channelID, packet.NativeData, nativePeers, (IntPtr)nativeCount);
+			}
+
+			packet.NativeData = IntPtr.Zero;
+		}
+
+		public int CheckEvents(out Event @event) {
+			CheckCreated();
+
+			ENetEvent nativeEvent;
+
+			var result = Native.enet_host_check_events(nativeHost, out nativeEvent);
+
+			if (result <= 0) {
+				@event = new Event();
+
+				return result;
+			}
+
+			@event = new Event(nativeEvent);
+
+			return result;
+		}
+
+		public Peer Connect(Address address) {
+			return Connect(address, 0, 0);
+		}
+
+		public Peer Connect(Address address, int channelLimit) {
+			return Connect(address, channelLimit, 0);
+		}
+
+		public Peer Connect(Address address, int channelLimit, uint data) {
+			CheckCreated();
+			CheckChannelLimit(channelLimit);
+
+			var nativeAddress = address.NativeData;
+			var peer = new Peer(Native.enet_host_connect(nativeHost, ref nativeAddress, (IntPtr)channelLimit, data));
+
+			if (peer.NativeData == IntPtr.Zero)
+				throw new InvalidOperationException("Host connect call failed");
+
+			return peer;
+		}
+
+		public int Service(int timeout, out Event @event) {
+			if (timeout < 0)
+				throw new ArgumentOutOfRangeException("timeout");
+
+			CheckCreated();
+
+			ENetEvent nativeEvent;
+
+			var result = Native.enet_host_service(nativeHost, out nativeEvent, (uint)timeout);
+
+			if (result <= 0) {
+				@event = new Event();
+
+				return result;
+			}
+
+			@event = new Event(nativeEvent);
+
+			return result;
+		}
+
+		public void SetBandwidthLimit(uint incomingBandwidth, uint outgoingBandwidth) {
+			CheckCreated();
+
+			Native.enet_host_bandwidth_limit(nativeHost, incomingBandwidth, outgoingBandwidth);
+		}
+
+		public void SetChannelLimit(int channelLimit) {
+			CheckCreated();
+			CheckChannelLimit(channelLimit);
+
+			Native.enet_host_channel_limit(nativeHost, (IntPtr)channelLimit);
+		}
+
+		public void Flush() {
+			CheckCreated();
+
+			Native.enet_host_flush(nativeHost);
+		}
+	}
+
+	public struct Peer {
+		private IntPtr nativePeer;
+		private uint nativeID;
+
+		internal IntPtr NativeData {
+			get {
+				return nativePeer;
+			}
+
+			set {
+				nativePeer = value;
+			}
+		}
+
+		public Peer(IntPtr peer) {
+			nativePeer = peer;
+			nativeID = nativePeer != IntPtr.Zero ? Native.enet_peer_get_id(nativePeer) : 0;
+		}
+
+		public bool IsSet {
+			get {
+				return nativePeer != IntPtr.Zero;
+			}
+		}
+
+		public uint ID {
+			get {
+				return nativeID;
+			}
+		}
+
+		public string IP {
+			get {
+				CheckCreated();
+
+				byte[] ip = ArrayPool.GetByteBuffer();
+
+				if (Native.enet_peer_get_ip(nativePeer, ip, (IntPtr)ip.Length) == 0) {
+					if (Encoding.ASCII.GetString(ip).Remove(7) != "::ffff:")
+						return Encoding.ASCII.GetString(ip, 0, ip.StringLength());
+					else
+						return Encoding.ASCII.GetString(ip, 0, ip.StringLength()).Substring(7);
+				} else {
+					return String.Empty;
+				}
+			}
+		}
+
+		public ushort Port {
+			get {
+				CheckCreated();
+
+				return Native.enet_peer_get_port(nativePeer);
+			}
+		}
+
+		public uint MTU {
+			get {
+				CheckCreated();
+
+				return Native.enet_peer_get_mtu(nativePeer);
+			}
+		}
+
+		public PeerState State {
+			get {
+				return nativePeer == IntPtr.Zero ? PeerState.Uninitialized : Native.enet_peer_get_state(nativePeer);
+			}
+		}
+
+		public uint RoundTripTime {
+			get {
+				CheckCreated();
+
+				return Native.enet_peer_get_rtt(nativePeer);
+			}
+		}
+
+		public uint LastSendTime {
+			get {
+				CheckCreated();
+
+				return Native.enet_peer_get_lastsendtime(nativePeer);
+			}
+		}
+
+		public uint LastReceiveTime {
+			get {
+				CheckCreated();
+
+				return Native.enet_peer_get_lastreceivetime(nativePeer);
+			}
+		}
+
+		public ulong PacketsSent {
+			get {
+				CheckCreated();
+
+				return Native.enet_peer_get_packets_sent(nativePeer);
+			}
+		}
+
+		public ulong PacketsLost {
+			get {
+				CheckCreated();
+
+				return Native.enet_peer_get_packets_lost(nativePeer);
+			}
+		}
+
+		public ulong BytesSent {
+			get {
+				CheckCreated();
+
+				return Native.enet_peer_get_bytes_sent(nativePeer);
+			}
+		}
+
+		public ulong BytesReceived {
+			get {
+				CheckCreated();
+
+				return Native.enet_peer_get_bytes_received(nativePeer);
+			}
+		}
+
+		public IntPtr Data {
+			get {
+				CheckCreated();
+
+				return Native.enet_peer_get_data(nativePeer);
+			}
+
+			set {
+				CheckCreated();
+
+				Native.enet_peer_set_data(nativePeer, value);
+			}
+		}
+
+		internal void CheckCreated() {
+			if (nativePeer == IntPtr.Zero)
+				throw new InvalidOperationException("Peer not created");
+		}
+
+		public void ConfigureThrottle(uint interval, uint acceleration, uint deceleration) {
+			CheckCreated();
+
+			Native.enet_peer_throttle_configure(nativePeer, interval, acceleration, deceleration);
+		}
+
+		public bool Send(byte channelID, ref Packet packet) {
+			CheckCreated();
+
+			packet.CheckCreated();
+
+			return Native.enet_peer_send(nativePeer, channelID, packet.NativeData) == 0;
+		}
+
+		public void Ping() {
+			CheckCreated();
+
+			Native.enet_peer_ping(nativePeer);
+		}
+
+		public void PingInterval(uint interval) {
+			CheckCreated();
+
+			Native.enet_peer_ping_interval(nativePeer, interval);
+		}
+
+		public void Timeout(uint timeoutLimit, uint timeoutMinimum, uint timeoutMaximum) {
+			CheckCreated();
+
+			Native.enet_peer_timeout(nativePeer, timeoutLimit, timeoutMinimum, timeoutMaximum);
+		}
+
+		public void Disconnect(uint data) {
+			CheckCreated();
+
+			Native.enet_peer_disconnect(nativePeer, data);
+		}
+
+		public void DisconnectNow(uint data) {
+			CheckCreated();
+
+			Native.enet_peer_disconnect_now(nativePeer, data);
+		}
+
+		public void DisconnectLater(uint data) {
+			CheckCreated();
+
+			Native.enet_peer_disconnect_later(nativePeer, data);
+		}
+
+		public void Reset() {
+			CheckCreated();
+
+			Native.enet_peer_reset(nativePeer);
+		}
+	}
+
+	public static class Extensions {
+		public static int StringLength(this byte[] data) {
+			if (data == null)
+				throw new ArgumentNullException("data");
+
+			int i;
+
+			for (i = 0; i < data.Length && data[i] != 0; i++);
+
+			return i;
+		}
+	}
+
+	public static class Library {
+		public const uint maxChannelCount = 0xFF;
+		public const uint maxPeers = 0xFFF;
+		public const uint maxPacketSize = 32 * 1024 * 1024;
+		public const uint throttleScale = 32;
+		public const uint throttleAcceleration = 2;
+		public const uint throttleDeceleration = 2;
+		public const uint throttleInterval = 5000;
+		public const uint timeoutLimit = 32;
+		public const uint timeoutMinimum = 5000;
+		public const uint timeoutMaximum = 30000;
+		public const uint version = (2 << 16) | (2 << 8) | (1);
+
+		public static bool Initialize() {
+			return Native.enet_initialize() == 0;
+		}
+
+		public static bool Initialize(Callbacks inits) {
+			return Native.enet_initialize_with_callbacks(version, inits.NativeData) == 0;
+		}
+
+		public static void Deinitialize() {
+			Native.enet_deinitialize();
+		}
+
+		public static uint Time {
+			get {
+				return Native.enet_time_get();
+			}
+		}
+	}
+
+	[SuppressUnmanagedCodeSecurity]
+	internal static class Native {
+		#if __IOS__ || UNITY_IOS && !UNITY_EDITOR
+			private const string nativeLibrary = "__Internal";
+		#else
+			private const string nativeLibrary = "enet";
+		#endif
+
+		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern int enet_initialize();
+
+		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern int enet_initialize_with_callbacks(uint version, ENetCallbacks inits);
+
+		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern void enet_deinitialize();
+
+		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern uint enet_time_get();
+
+		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern int enet_address_get_host(ENetAddress address, StringBuilder hostName, IntPtr nameLength);
+
+		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern int enet_address_set_host(ref ENetAddress address, string hostName);
+
+		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern IntPtr enet_packet_create(byte[] data, IntPtr dataLength, PacketFlags flags);
+
+		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern IntPtr enet_packet_create(IntPtr data, IntPtr dataLength, PacketFlags flags);
+
+		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern IntPtr enet_packet_create_offset(byte[] data, IntPtr dataLength, IntPtr dataOffset, PacketFlags flags);
+
+		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern IntPtr enet_packet_create_offset(IntPtr data, IntPtr dataLength, IntPtr dataOffset, PacketFlags flags);
+
+		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern int enet_packet_check_references(IntPtr packet);
+
+		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern IntPtr enet_packet_get_data(IntPtr packet);
+
+		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern int enet_packet_get_length(IntPtr packet);
+
+		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern void enet_packet_set_free_callback(IntPtr packet, IntPtr callback);
+
+		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern void enet_packet_dispose(IntPtr packet);
+
+		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern IntPtr enet_host_create(ref ENetAddress address, IntPtr peerLimit, IntPtr channelLimit, uint incomingBandwidth, uint outgoingBandwidth);
+
+		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern IntPtr enet_host_create(IntPtr address, IntPtr peerLimit, IntPtr channelLimit, uint incomingBandwidth, uint outgoingBandwidth);
+
+		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern IntPtr enet_host_connect(IntPtr host, ref ENetAddress address, IntPtr channelCount, uint data);
+
+		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern void enet_host_broadcast(IntPtr host, byte channelID, IntPtr packet);
+
+		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern void enet_host_broadcast_selective(IntPtr host, byte channelID, IntPtr packet, IntPtr[] peers, IntPtr peersLength);
+
+		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern int enet_host_service(IntPtr host, out ENetEvent @event, uint timeout);
+
+		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern int enet_host_check_events(IntPtr host, out ENetEvent @event);
+
+		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern void enet_host_channel_limit(IntPtr host, IntPtr channelLimit);
+
+		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern void enet_host_bandwidth_limit(IntPtr host, uint incomingBandwidth, uint outgoingBandwidth);
+
+		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern uint enet_host_get_peers_count(IntPtr host);
+
+		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern uint enet_host_get_packets_sent(IntPtr host);
+
+		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern uint enet_host_get_packets_received(IntPtr host);
+
+		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern uint enet_host_get_bytes_sent(IntPtr host);
+
+		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern uint enet_host_get_bytes_received(IntPtr host);
+
+		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern void enet_host_flush(IntPtr host);
+
+		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern void enet_host_destroy(IntPtr host);
+
+		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern void enet_host_enable_compression(IntPtr host);
+
+		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern void enet_host_prevent_connections(IntPtr host, byte state);
+
+		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern void enet_peer_throttle_configure(IntPtr peer, uint interval, uint acceleration, uint deceleration);
+
+		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern uint enet_peer_get_id(IntPtr peer);
+
+		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern int enet_peer_get_ip(IntPtr peer, byte[] ip, IntPtr ipLength);
+
+		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern ushort enet_peer_get_port(IntPtr peer);
+
+		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern uint enet_peer_get_mtu(IntPtr peer);
+
+		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern PeerState enet_peer_get_state(IntPtr peer);
+
+		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern uint enet_peer_get_rtt(IntPtr peer);
+
+		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern uint enet_peer_get_lastsendtime(IntPtr peer);
+
+		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern uint enet_peer_get_lastreceivetime(IntPtr peer);
+
+		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern ulong enet_peer_get_packets_sent(IntPtr peer);
+
+		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern ulong enet_peer_get_packets_lost(IntPtr peer);
+
+		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern ulong enet_peer_get_bytes_sent(IntPtr peer);
+
+		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern ulong enet_peer_get_bytes_received(IntPtr peer);
+
+		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern IntPtr enet_peer_get_data(IntPtr peer);
+
+		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern void enet_peer_set_data(IntPtr peer, IntPtr data);
+
+		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern int enet_peer_send(IntPtr peer, byte channelID, IntPtr packet);
+
+		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern void enet_peer_ping(IntPtr peer);
+
+		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern void enet_peer_ping_interval(IntPtr peer, uint pingInterval);
+
+		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern void enet_peer_timeout(IntPtr peer, uint timeoutLimit, uint timeoutMinimum, uint timeoutMaximum);
+
+		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern void enet_peer_disconnect(IntPtr peer, uint data);
+
+		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern void enet_peer_disconnect_now(IntPtr peer, uint data);
+
+		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern void enet_peer_disconnect_later(IntPtr peer, uint data);
+
+		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
+		internal static extern void enet_peer_reset(IntPtr peer);
+	}
+}

+ 35 - 0
Source/Native/CMakeLists.txt

@@ -0,0 +1,35 @@
+cmake_minimum_required(VERSION 2.6)
+project(enet C)
+
+set(ENET_STATIC "0" CACHE BOOL "Create a static library")
+set(ENET_SHARED "0" CACHE BOOL "Create a shared library")
+set(ENET_LZ4 "0" CACHE BOOL "Add support for an optional packet-level compression")
+
+if (MSVC)
+	add_definitions(-W3)
+else()
+	add_definitions(-Wno-error)
+endif()
+
+include_directories(${PROJECT_SOURCE_DIR})
+
+if (ENET_LZ4)
+    add_definitions(-DENET_LZ4)
+    set(SOURCES lz4/lz4.c)
+endif()
+
+if (ENET_STATIC)
+    add_library(enet_static STATIC enet.c ${SOURCES})
+
+    if (WIN32)
+        target_link_libraries(enet_static winmm ws2_32)
+    endif()
+endif()
+
+if (ENET_SHARED)
+    add_library(enet SHARED enet.c ${SOURCES})
+
+    if (WIN32)
+        target_link_libraries(enet winmm ws2_32)
+    endif()
+endif()

+ 27 - 0
Source/Native/enet.c

@@ -0,0 +1,27 @@
+/*
+ *  ENet reliable UDP networking library 
+ *  Copyright (c) 2018 Lee Salzman, Vladyslav Hrytsenko, Dominik Madarász, Stanislav Denisov
+ *
+ *  Permission is hereby granted, free of charge, to any person obtaining a copy
+ *  of this software and associated documentation files (the "Software"), to deal
+ *  in the Software without restriction, including without limitation the rights
+ *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ *  copies of the Software, and to permit persons to whom the Software is
+ *  furnished to do so, subject to the following conditions:
+ *
+ *  The above copyright notice and this permission notice shall be included in all
+ *  copies or substantial portions of the Software.
+ *
+ *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ *  SOFTWARE.
+ */
+
+#define _WINSOCK_DEPRECATED_NO_WARNINGS
+#define ENET_IMPLEMENTATION
+#define ENET_DLL
+#include "enet.h"

+ 5056 - 0
Source/Native/enet.h

@@ -0,0 +1,5056 @@
+/*
+ *  ENet reliable UDP networking library
+ *  Copyright (c) 2018 Lee Salzman, Vladyslav Hrytsenko, Dominik Madarász, Stanislav Denisov
+ *
+ *  Permission is hereby granted, free of charge, to any person obtaining a copy
+ *  of this software and associated documentation files (the "Software"), to deal
+ *  in the Software without restriction, including without limitation the rights
+ *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ *  copies of the Software, and to permit persons to whom the Software is
+ *  furnished to do so, subject to the following conditions:
+ *
+ *  The above copyright notice and this permission notice shall be included in all
+ *  copies or substantial portions of the Software.
+ *
+ *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ *  SOFTWARE.
+ */
+
+#ifndef ENET_H
+#define ENET_H
+
+#include <stdlib.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <time.h>
+
+#ifdef ENET_LZ4
+	#include "lz4/lz4.h"
+#endif
+
+#define ENET_VERSION_MAJOR 2
+#define ENET_VERSION_MINOR 2
+#define ENET_VERSION_PATCH 1
+#define ENET_VERSION_CREATE(major, minor, patch) (((major) << 16) | ((minor) << 8) | (patch))
+#define ENET_VERSION_GET_MAJOR(version) (((version) >> 16) & 0xFF)
+#define ENET_VERSION_GET_MINOR(version) (((version) >> 8) & 0xFF)
+#define ENET_VERSION_GET_PATCH(version) ((version) & 0xFF)
+#define ENET_VERSION ENET_VERSION_CREATE(ENET_VERSION_MAJOR, ENET_VERSION_MINOR, ENET_VERSION_PATCH)
+
+#define ENET_TIME_OVERFLOW 86400000
+#define ENET_TIME_LESS(a, b) ((a) - (b) >= ENET_TIME_OVERFLOW)
+#define ENET_TIME_GREATER(a, b) ((b) - (a) >= ENET_TIME_OVERFLOW)
+#define ENET_TIME_LESS_EQUAL(a, b) (!ENET_TIME_GREATER(a, b))
+#define ENET_TIME_GREATER_EQUAL(a, b) (!ENET_TIME_LESS(a, b))
+#define ENET_TIME_DIFFERENCE(a, b) ((a) - (b) >= ENET_TIME_OVERFLOW ? (b) - (a) : (a) - (b))
+
+#define ENET_MAX(x, y) ((x) > (y) ? (x) : (y))
+#define ENET_MIN(x, y) ((x) < (y) ? (x) : (y))
+
+#define ENET_SRTT_INITIAL 1.0
+#define ENET_SRTT_PARA_G  0.125
+
+// =======================================================================//
+// !
+// ! System differences
+// !
+// =======================================================================//
+
+#ifdef _WIN32
+	#ifdef __MINGW32__
+		#include "mingw/inet_ntop.c"
+		#include "mingw/inet_pton.c"
+	#endif
+
+	#if defined(_MSC_VER) && defined(ENET_IMPLEMENTATION)
+		#pragma warning(disable: 4018) /* signed/unsigned mismatch */
+		#pragma warning(disable: 4146) /* unary minus operator applied to unsigned type */
+		#pragma warning(disable: 4244) /* 64bit to 32bit int */
+		#pragma warning(disable: 4267) /* size_t to int conversion */
+	#endif
+
+	#ifndef ENET_NO_PRAGMA_LINK
+		#pragma comment(lib, "ws2_32.lib")
+		#pragma comment(lib, "winmm.lib")
+	#endif
+
+	#if _MSC_VER >= 1910
+		/* It looks like there were changes as of Visual Studio 2017 and there are no 32/64 bit
+		versions of _InterlockedExchange[operation], only InterlockedExchange[operation]
+		(without leading underscore), so we have to distinguish between compiler versions */
+		#define NOT_UNDERSCORED_INTERLOCKED_EXCHANGE
+	#endif
+
+	#ifdef __GNUC__
+		#if (_WIN32_WINNT < 0x0501)
+			#undef _WIN32_WINNT
+			#define _WIN32_WINNT 0x0501
+		#endif
+	#endif
+
+	#include <winsock2.h>
+	#include <ws2tcpip.h>
+	#include <mmsystem.h>
+	#include <intrin.h>
+
+	#if defined(_WIN32) && defined(_MSC_VER)
+		#if _MSC_VER < 1900
+			typedef struct timespec {
+				long tv_sec;
+				long tv_nsec;
+			};
+		#endif
+		#define CLOCK_MONOTONIC 0
+	#endif
+
+	typedef SOCKET ENetSocket;
+
+	#define ENET_SOCKET_NULL INVALID_SOCKET
+
+	typedef struct {
+		size_t dataLength;
+		void* data;
+	} ENetBuffer;
+
+	#define ENET_CALLBACK __cdecl
+
+	#ifdef ENET_DLL
+		#ifdef ENET_IMPLEMENTATION
+			#define ENET_API __declspec(dllexport)
+		#else
+			#define ENET_API __declspec(dllimport)
+		#endif
+	#else
+		#define ENET_API extern
+	#endif
+#else
+	#include <sys/types.h>
+	#include <sys/ioctl.h>
+	#include <sys/time.h>
+	#include <sys/socket.h>
+	#include <poll.h>
+	#include <arpa/inet.h>
+	#include <netinet/in.h>
+	#include <netinet/tcp.h>
+	#include <netdb.h>
+	#include <unistd.h>
+	#include <string.h>
+	#include <errno.h>
+	#include <fcntl.h>
+
+	#ifdef __APPLE__
+		#include <mach/clock.h>
+		#include <mach/mach.h>
+		#include <Availability.h>
+	#endif
+
+	#ifndef MSG_NOSIGNAL
+		#define MSG_NOSIGNAL 0
+	#endif
+
+	#ifdef MSG_MAXIOVLEN
+		#define ENET_BUFFER_MAXIMUM MSG_MAXIOVLEN
+	#endif
+
+	typedef int ENetSocket;
+
+	#define ENET_SOCKET_NULL -1
+
+	typedef struct {
+		void* data;
+		size_t dataLength;
+	} ENetBuffer;
+
+	#define ENET_CALLBACK
+	#define ENET_API extern
+#endif
+
+#ifndef ENET_BUFFER_MAXIMUM
+	#define ENET_BUFFER_MAXIMUM (1 + 2 * ENET_PROTOCOL_MAXIMUM_PACKET_COMMANDS)
+#endif
+
+#define ENET_HOST_ANY       in6addr_any
+#define ENET_PORT_ANY       0
+#define ENET_HOST_BROADCAST 0xFFFFFFFFU
+
+#define ENET_HOST_TO_NET_16(value) (htons(value))
+#define ENET_HOST_TO_NET_32(value) (htonl(value))
+#define ENET_NET_TO_HOST_16(value) (ntohs(value))
+#define ENET_NET_TO_HOST_32(value) (ntohl(value))
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+// =======================================================================//
+// !
+// ! Basic stuff
+// !
+// =======================================================================//
+
+	typedef uint8_t enet_uint8;
+	typedef uint16_t enet_uint16;
+	typedef uint32_t enet_uint32;
+	typedef uint64_t enet_uint64;
+
+	typedef enet_uint32 ENetVersion;
+
+	typedef fd_set ENetSocketSet;
+
+	typedef struct _ENetCallbacks {
+		void*(ENET_CALLBACK *malloc)(size_t size);
+		void(ENET_CALLBACK *free)(void* memory);
+		void(ENET_CALLBACK *noMemory)(void);
+	} ENetCallbacks;
+
+	extern void* enet_malloc(size_t);
+	extern void enet_free(void*);
+
+// =======================================================================//
+// !
+// ! List
+// !
+// =======================================================================//
+
+	typedef struct _ENetListNode {
+		struct _ENetListNode* next;
+		struct _ENetListNode* previous;
+	} ENetListNode;
+
+	typedef ENetListNode* ENetListIterator;
+
+	typedef struct _ENetList {
+		ENetListNode sentinel;
+	} ENetList;
+
+	extern ENetListIterator enet_list_insert(ENetListIterator, void*);
+	extern ENetListIterator enet_list_move(ENetListIterator, void*, void*);
+
+	extern void* enet_list_remove(ENetListIterator);
+	extern void enet_list_clear(ENetList*);
+	extern size_t enet_list_size(ENetList*);
+
+	#define enet_list_begin(list) ((list)->sentinel.next)
+	#define enet_list_end(list) (&(list)->sentinel)
+	#define enet_list_empty(list) (enet_list_begin(list) == enet_list_end(list))
+	#define enet_list_next(iterator) ((iterator)->next)
+	#define enet_list_previous(iterator) ((iterator)->previous)
+	#define enet_list_front(list) ((void*)(list)->sentinel.next)
+	#define enet_list_back(list) ((void*)(list)->sentinel.previous)
+
+// =======================================================================//
+// !
+// ! Protocol
+// !
+// =======================================================================//
+
+	enum {
+		ENET_PROTOCOL_MINIMUM_MTU             = 576,
+		ENET_PROTOCOL_MAXIMUM_MTU             = 4096,
+		ENET_PROTOCOL_MAXIMUM_PACKET_COMMANDS = 32,
+		ENET_PROTOCOL_MINIMUM_WINDOW_SIZE     = 4096,
+		ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE     = 65536,
+		ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT   = 1,
+		ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT   = 255,
+		ENET_PROTOCOL_MAXIMUM_PEER_ID         = 0xFFF,
+		ENET_PROTOCOL_MAXIMUM_FRAGMENT_COUNT  = 1024 * 1024
+	};
+
+	typedef enum _ENetProtocolCommand {
+		ENET_PROTOCOL_COMMAND_NONE                     = 0,
+		ENET_PROTOCOL_COMMAND_ACKNOWLEDGE              = 1,
+		ENET_PROTOCOL_COMMAND_CONNECT                  = 2,
+		ENET_PROTOCOL_COMMAND_VERIFY_CONNECT           = 3,
+		ENET_PROTOCOL_COMMAND_DISCONNECT               = 4,
+		ENET_PROTOCOL_COMMAND_PING                     = 5,
+		ENET_PROTOCOL_COMMAND_SEND_RELIABLE            = 6,
+		ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE          = 7,
+		ENET_PROTOCOL_COMMAND_SEND_FRAGMENT            = 8,
+		ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED         = 9,
+		ENET_PROTOCOL_COMMAND_BANDWIDTH_LIMIT          = 10,
+		ENET_PROTOCOL_COMMAND_THROTTLE_CONFIGURE       = 11,
+		ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE_FRAGMENT = 12,
+		ENET_PROTOCOL_COMMAND_COUNT                    = 13,
+		ENET_PROTOCOL_COMMAND_MASK                     = 0x0F
+	} ENetProtocolCommand;
+
+	typedef enum _ENetProtocolFlag {
+		ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE = (1 << 7),
+		ENET_PROTOCOL_COMMAND_FLAG_UNSEQUENCED = (1 << 6),
+		ENET_PROTOCOL_HEADER_FLAG_SENT_TIME    = (1 << 14),
+		ENET_PROTOCOL_HEADER_FLAG_COMPRESSED   = (1 << 15),
+		ENET_PROTOCOL_HEADER_FLAG_MASK         = ENET_PROTOCOL_HEADER_FLAG_SENT_TIME | ENET_PROTOCOL_HEADER_FLAG_COMPRESSED,
+		ENET_PROTOCOL_HEADER_SESSION_MASK      = (3 << 12),
+		ENET_PROTOCOL_HEADER_SESSION_SHIFT     = 12
+	} ENetProtocolFlag;
+
+	#ifdef _MSC_VER
+		#pragma pack(push, 1)
+		#define ENET_PACKED
+	#elif defined(__GNUC__) || defined(__clang__)
+		#define ENET_PACKED __attribute__ ((packed))
+	#else
+		#define ENET_PACKED
+	#endif
+
+	typedef struct _ENetProtocolHeader {
+		enet_uint16 peerID;
+		enet_uint16 sentTime;
+	} ENET_PACKED ENetProtocolHeader;
+
+	typedef struct _ENetProtocolCommandHeader {
+		enet_uint8 command;
+		enet_uint8 channelID;
+		enet_uint16 reliableSequenceNumber;
+	} ENET_PACKED ENetProtocolCommandHeader;
+
+	typedef struct _ENetProtocolAcknowledge {
+		ENetProtocolCommandHeader header;
+		enet_uint16 receivedReliableSequenceNumber;
+		enet_uint16 receivedSentTime;
+	} ENET_PACKED ENetProtocolAcknowledge;
+
+	typedef struct _ENetProtocolConnect {
+		ENetProtocolCommandHeader header;
+		enet_uint16 outgoingPeerID;
+		enet_uint8 incomingSessionID;
+		enet_uint8 outgoingSessionID;
+		enet_uint32 mtu;
+		enet_uint32 windowSize;
+		enet_uint32 channelCount;
+		enet_uint32 incomingBandwidth;
+		enet_uint32 outgoingBandwidth;
+		enet_uint32 packetThrottleInterval;
+		enet_uint32 packetThrottleAcceleration;
+		enet_uint32 packetThrottleDeceleration;
+		enet_uint32 connectID;
+		enet_uint32 data;
+	} ENET_PACKED ENetProtocolConnect;
+
+	typedef struct _ENetProtocolVerifyConnect {
+		ENetProtocolCommandHeader header;
+		enet_uint16 outgoingPeerID;
+		enet_uint8 incomingSessionID;
+		enet_uint8 outgoingSessionID;
+		enet_uint32 mtu;
+		enet_uint32 windowSize;
+		enet_uint32 channelCount;
+		enet_uint32 incomingBandwidth;
+		enet_uint32 outgoingBandwidth;
+		enet_uint32 packetThrottleInterval;
+		enet_uint32 packetThrottleAcceleration;
+		enet_uint32 packetThrottleDeceleration;
+		enet_uint32 connectID;
+	} ENET_PACKED ENetProtocolVerifyConnect;
+
+	typedef struct _ENetProtocolBandwidthLimit {
+		ENetProtocolCommandHeader header;
+		enet_uint32 incomingBandwidth;
+		enet_uint32 outgoingBandwidth;
+	} ENET_PACKED ENetProtocolBandwidthLimit;
+
+	typedef struct _ENetProtocolThrottleConfigure {
+		ENetProtocolCommandHeader header;
+		enet_uint32 packetThrottleInterval;
+		enet_uint32 packetThrottleAcceleration;
+		enet_uint32 packetThrottleDeceleration;
+	} ENET_PACKED ENetProtocolThrottleConfigure;
+
+	typedef struct _ENetProtocolDisconnect {
+		ENetProtocolCommandHeader header;
+		enet_uint32 data;
+	} ENET_PACKED ENetProtocolDisconnect;
+
+	typedef struct _ENetProtocolPing {
+		ENetProtocolCommandHeader header;
+	} ENET_PACKED ENetProtocolPing;
+
+	typedef struct _ENetProtocolSendReliable {
+		ENetProtocolCommandHeader header;
+		enet_uint16 dataLength;
+	} ENET_PACKED ENetProtocolSendReliable;
+
+	typedef struct _ENetProtocolSendUnreliable {
+		ENetProtocolCommandHeader header;
+		enet_uint16 unreliableSequenceNumber;
+		enet_uint16 dataLength;
+	} ENET_PACKED ENetProtocolSendUnreliable;
+
+	typedef struct _ENetProtocolSendUnsequenced {
+		ENetProtocolCommandHeader header;
+		enet_uint16 unsequencedGroup;
+		enet_uint16 dataLength;
+	} ENET_PACKED ENetProtocolSendUnsequenced;
+
+	typedef struct _ENetProtocolSendFragment {
+		ENetProtocolCommandHeader header;
+		enet_uint16 startSequenceNumber;
+		enet_uint16 dataLength;
+		enet_uint32 fragmentCount;
+		enet_uint32 fragmentNumber;
+		enet_uint32 totalLength;
+		enet_uint32 fragmentOffset;
+	} ENET_PACKED ENetProtocolSendFragment;
+
+	typedef union _ENetProtocol {
+		ENetProtocolCommandHeader header;
+		ENetProtocolAcknowledge acknowledge;
+		ENetProtocolConnect connect;
+		ENetProtocolVerifyConnect verifyConnect;
+		ENetProtocolDisconnect disconnect;
+		ENetProtocolPing ping;
+		ENetProtocolSendReliable sendReliable;
+		ENetProtocolSendUnreliable sendUnreliable;
+		ENetProtocolSendUnsequenced sendUnsequenced;
+		ENetProtocolSendFragment sendFragment;
+		ENetProtocolBandwidthLimit bandwidthLimit;
+		ENetProtocolThrottleConfigure throttleConfigure;
+	} ENET_PACKED ENetProtocol;
+
+	#ifdef _MSC_VER
+		#pragma pack(pop)
+	#endif
+
+// =======================================================================//
+// !
+// ! General ENet structs/enums
+// !
+// =======================================================================//
+
+	typedef enum _ENetSocketType {
+		ENET_SOCKET_TYPE_STREAM   = 1,
+		ENET_SOCKET_TYPE_DATAGRAM = 2
+	} ENetSocketType;
+
+	typedef enum _ENetSocketWait {
+		ENET_SOCKET_WAIT_NONE      = 0,
+		ENET_SOCKET_WAIT_SEND      = (1 << 0),
+		ENET_SOCKET_WAIT_RECEIVE   = (1 << 1),
+		ENET_SOCKET_WAIT_INTERRUPT = (1 << 2)
+	} ENetSocketWait;
+
+	typedef enum _ENetSocketOption {
+		ENET_SOCKOPT_NONBLOCK    = 1,
+		ENET_SOCKOPT_BROADCAST   = 2,
+		ENET_SOCKOPT_RCVBUF      = 3,
+		ENET_SOCKOPT_SNDBUF      = 4,
+		ENET_SOCKOPT_REUSEADDR   = 5,
+		ENET_SOCKOPT_RCVTIMEO    = 6,
+		ENET_SOCKOPT_SNDTIMEO    = 7,
+		ENET_SOCKOPT_ERROR       = 8,
+		ENET_SOCKOPT_NODELAY     = 9,
+		ENET_SOCKOPT_IPV6_V6ONLY = 10
+	} ENetSocketOption;
+
+	typedef enum _ENetSocketShutdown {
+		ENET_SOCKET_SHUTDOWN_READ       = 0,
+		ENET_SOCKET_SHUTDOWN_WRITE      = 1,
+		ENET_SOCKET_SHUTDOWN_READ_WRITE = 2
+	} ENetSocketShutdown;
+
+	typedef struct _ENetAddress {
+		struct in6_addr host;
+		enet_uint16 port;
+		enet_uint16 scope;
+	} ENetAddress;
+
+	#define in6_equal(in6_addr_a, in6_addr_b) (memcmp(&in6_addr_a, &in6_addr_b, sizeof(struct in6_addr)) == 0)
+
+	typedef enum _ENetPacketFlag {
+		ENET_PACKET_FLAG_RELIABLE            = (1 << 0),
+		ENET_PACKET_FLAG_UNSEQUENCED         = (1 << 1),
+		ENET_PACKET_FLAG_NO_ALLOCATE         = (1 << 2),
+		ENET_PACKET_FLAG_UNRELIABLE_FRAGMENT = (1 << 3),
+		ENET_PACKET_FLAG_SENT                = (1 << 8)
+	} ENetPacketFlag;
+
+	typedef void (ENET_CALLBACK *ENetPacketFreeCallback)(void*);
+
+	typedef struct _ENetPacket {
+		enet_uint32 flags;
+		enet_uint32 dataLength;
+		enet_uint8* data;
+		ENetPacketFreeCallback freeCallback;
+		enet_uint32 referenceCount;
+	} ENetPacket;
+
+	typedef struct _ENetAcknowledgement {
+		ENetListNode acknowledgementList;
+		enet_uint32 sentTime;
+		ENetProtocol command;
+	} ENetAcknowledgement;
+
+	typedef struct _ENetOutgoingCommand {
+		ENetListNode outgoingCommandList;
+		enet_uint16 reliableSequenceNumber;
+		enet_uint16 unreliableSequenceNumber;
+		enet_uint32 sentTime;
+		enet_uint32 roundTripTimeout;
+		enet_uint32 roundTripTimeoutLimit;
+		enet_uint32 fragmentOffset;
+		enet_uint16 fragmentLength;
+		enet_uint16 sendAttempts;
+		ENetProtocol command;
+		ENetPacket* packet;
+	} ENetOutgoingCommand;
+
+	typedef struct _ENetIncomingCommand {
+		ENetListNode incomingCommandList;
+		enet_uint16 reliableSequenceNumber;
+		enet_uint16 unreliableSequenceNumber;
+		ENetProtocol command;
+		enet_uint32 fragmentCount;
+		enet_uint32 fragmentsRemaining;
+		enet_uint32* fragments;
+		ENetPacket* packet;
+	} ENetIncomingCommand;
+
+	typedef enum _ENetPeerState {
+		ENET_PEER_STATE_DISCONNECTED             = 0,
+		ENET_PEER_STATE_CONNECTING               = 1,
+		ENET_PEER_STATE_ACKNOWLEDGING_CONNECT    = 2,
+		ENET_PEER_STATE_CONNECTION_PENDING       = 3,
+		ENET_PEER_STATE_CONNECTION_SUCCEEDED     = 4,
+		ENET_PEER_STATE_CONNECTED                = 5,
+		ENET_PEER_STATE_DISCONNECT_LATER         = 6,
+		ENET_PEER_STATE_DISCONNECTING            = 7,
+		ENET_PEER_STATE_ACKNOWLEDGING_DISCONNECT = 8,
+		ENET_PEER_STATE_ZOMBIE                   = 9
+	} ENetPeerState;
+
+	enum {
+		ENET_HOST_RECEIVE_BUFFER_SIZE          = 256 * 1024,
+		ENET_HOST_SEND_BUFFER_SIZE             = 256 * 1024,
+		ENET_HOST_BANDWIDTH_THROTTLE_INTERVAL  = 1000,
+		ENET_HOST_DEFAULT_MTU                  = 1400,
+		ENET_HOST_DEFAULT_MAXIMUM_PACKET_SIZE  = 32 * 1024 * 1024,
+		ENET_HOST_DEFAULT_MAXIMUM_WAITING_DATA = 32 * 1024 * 1024,
+		ENET_PEER_DEFAULT_ROUND_TRIP_TIME      = 500,
+		ENET_PEER_DEFAULT_PACKET_THROTTLE      = 32,
+		ENET_PEER_PACKET_THROTTLE_SCALE        = 32,
+		ENET_PEER_PACKET_THROTTLE_COUNTER      = 7,
+		ENET_PEER_PACKET_THROTTLE_ACCELERATION = 2,
+		ENET_PEER_PACKET_THROTTLE_DECELERATION = 2,
+		ENET_PEER_PACKET_THROTTLE_INTERVAL     = 5000,
+		ENET_PEER_PACKET_LOSS_SCALE            = (1 << 16),
+		ENET_PEER_PACKET_LOSS_INTERVAL         = 10000,
+		ENET_PEER_WINDOW_SIZE_SCALE            = 64 * 1024,
+		ENET_PEER_TIMEOUT_LIMIT                = 32,
+		ENET_PEER_TIMEOUT_MINIMUM              = 5000,
+		ENET_PEER_TIMEOUT_MAXIMUM              = 30000,
+		ENET_PEER_PING_INTERVAL                = 500,
+		ENET_PEER_UNSEQUENCED_WINDOWS          = 64,
+		ENET_PEER_UNSEQUENCED_WINDOW_SIZE      = 1024,
+		ENET_PEER_FREE_UNSEQUENCED_WINDOWS     = 32,
+		ENET_PEER_RELIABLE_WINDOWS             = 16,
+		ENET_PEER_RELIABLE_WINDOW_SIZE         = 0x1000,
+		ENET_PEER_FREE_RELIABLE_WINDOWS        = 8
+	};
+
+	typedef struct _ENetChannel {
+		enet_uint16 outgoingReliableSequenceNumber;
+		enet_uint16 outgoingUnreliableSequenceNumber;
+		enet_uint16 usedReliableWindows;
+		enet_uint16 reliableWindows[ENET_PEER_RELIABLE_WINDOWS];
+		enet_uint16 incomingReliableSequenceNumber;
+		enet_uint16 incomingUnreliableSequenceNumber;
+		ENetList incomingReliableCommands;
+		ENetList incomingUnreliableCommands;
+	} ENetChannel;
+
+	typedef struct _ENetPeer {
+		ENetListNode dispatchList;
+		struct _ENetHost* host;
+		enet_uint16 outgoingPeerID;
+		enet_uint16 incomingPeerID;
+		enet_uint32 connectID;
+		enet_uint8 outgoingSessionID;
+		enet_uint8 incomingSessionID;
+		ENetAddress address;
+		void* data;
+		ENetPeerState state;
+		ENetChannel* channels;
+		size_t channelCount;
+		enet_uint32 incomingBandwidth;
+		enet_uint32 outgoingBandwidth;
+		enet_uint32 incomingBandwidthThrottleEpoch;
+		enet_uint32 outgoingBandwidthThrottleEpoch;
+		enet_uint32 incomingDataTotal;
+		enet_uint64 totalDataReceived;
+		enet_uint32 outgoingDataTotal;
+		enet_uint64 totalDataSent;
+		enet_uint32 lastSendTime;
+		enet_uint32 lastReceiveTime;
+		enet_uint32 nextTimeout;
+		enet_uint32 earliestTimeout;
+		enet_uint32 packetLossEpoch;
+		enet_uint32 packetsSent;
+		enet_uint64 totalPacketsSent;
+		enet_uint32 packetsLost;
+		enet_uint64 totalPacketsLost;
+		enet_uint32 packetLoss;
+		enet_uint32 packetLossVariance;
+		enet_uint32 packetThrottle;
+		enet_uint32 packetThrottleLimit;
+		enet_uint32 packetThrottleCounter;
+		enet_uint32 packetThrottleEpoch;
+		enet_uint32 packetThrottleAcceleration;
+		enet_uint32 packetThrottleDeceleration;
+		enet_uint32 packetThrottleInterval;
+		enet_uint32 pingInterval;
+		enet_uint32 timeoutLimit;
+		enet_uint32 timeoutMinimum;
+		enet_uint32 timeoutMaximum;
+		enet_uint32 smoothedRoundTripTime;
+		enet_uint32 lastRoundTripTime;
+		enet_uint32 lowestRoundTripTime;
+		enet_uint32 lastRoundTripTimeVariance;
+		enet_uint32 highestRoundTripTimeVariance;
+		enet_uint32 roundTripTime;
+		enet_uint32 roundTripTimeVariance;
+		enet_uint32 mtu;
+		enet_uint32 windowSize;
+		enet_uint32 reliableDataInTransit;
+		enet_uint16 outgoingReliableSequenceNumber;
+		ENetList acknowledgements;
+		ENetList sentReliableCommands;
+		ENetList sentUnreliableCommands;
+		ENetList outgoingReliableCommands;
+		ENetList outgoingUnreliableCommands;
+		ENetList dispatchedCommands;
+		int needsDispatch;
+		enet_uint16 incomingUnsequencedGroup;
+		enet_uint16 outgoingUnsequencedGroup;
+		enet_uint32 unsequencedWindow[ENET_PEER_UNSEQUENCED_WINDOW_SIZE / 32];
+		enet_uint32 eventData;
+		size_t totalWaitingData;
+	} ENetPeer;
+
+	typedef enet_uint32 (ENET_CALLBACK *ENetChecksumCallback)(const ENetBuffer* buffers, size_t bufferCount);
+
+	typedef int (ENET_CALLBACK *ENetInterceptCallback)(struct _ENetHost* host, void* event);
+
+	typedef struct _ENetHost {
+		ENetSocket socket;
+		ENetAddress address;
+		enet_uint32 incomingBandwidth;
+		enet_uint32 outgoingBandwidth;
+		enet_uint32 bandwidthThrottleEpoch;
+		enet_uint32 mtu;
+		enet_uint32 randomSeed;
+		int recalculateBandwidthLimits;
+		enet_uint8 preventConnections;
+		ENetPeer* peers;
+		size_t peerCount;
+		size_t channelLimit;
+		enet_uint32 serviceTime;
+		ENetList dispatchQueue;
+		int continueSending;
+		size_t packetSize;
+		enet_uint16 headerFlags;
+		enet_uint32 totalSentData;
+		enet_uint32 totalSentPackets;
+		enet_uint32 totalReceivedData;
+		enet_uint32 totalReceivedPackets;
+		ENetProtocol commands[ENET_PROTOCOL_MAXIMUM_PACKET_COMMANDS];
+		size_t commandCount;
+		ENetBuffer buffers[ENET_BUFFER_MAXIMUM];
+		size_t bufferCount;
+		enet_uint8 compression;
+		char* compressionBuffer;
+		size_t compressionBufferSize;
+		ENetChecksumCallback checksumCallback;
+		enet_uint8 packetData[2][ENET_PROTOCOL_MAXIMUM_MTU];
+		ENetAddress receivedAddress;
+		enet_uint8* receivedData;
+		size_t receivedDataLength;
+		ENetInterceptCallback interceptCallback;
+		size_t connectedPeers;
+		size_t bandwidthLimitedPeers;
+		size_t duplicatePeers;
+		size_t maximumPacketSize;
+		size_t maximumWaitingData;
+	} ENetHost;
+
+	typedef enum _ENetEventType {
+		ENET_EVENT_TYPE_NONE               = 0,
+		ENET_EVENT_TYPE_CONNECT            = 1,
+		ENET_EVENT_TYPE_DISCONNECT         = 2,
+		ENET_EVENT_TYPE_RECEIVE            = 3,
+		ENET_EVENT_TYPE_DISCONNECT_TIMEOUT = 4
+	} ENetEventType;
+
+	typedef struct _ENetEvent {
+		ENetEventType type;
+		ENetPeer* peer;
+		enet_uint8 channelID;
+		enet_uint32 data;
+		ENetPacket* packet;
+	} ENetEvent;
+
+// =======================================================================//
+// !
+// ! Public API
+// !
+// =======================================================================//
+
+	ENET_API int enet_initialize(void);
+	ENET_API int enet_initialize_with_callbacks(ENetVersion, const ENetCallbacks*);
+	ENET_API void enet_deinitialize(void);
+	ENET_API ENetVersion enet_linked_version(void);
+	ENET_API enet_uint32 enet_time_get(void);
+
+	ENET_API ENetSocket enet_socket_create(ENetSocketType);
+	ENET_API int enet_socket_bind(ENetSocket, const ENetAddress*);
+	ENET_API int enet_socket_get_address(ENetSocket, ENetAddress*);
+	ENET_API int enet_socket_listen(ENetSocket, int);
+	ENET_API ENetSocket enet_socket_accept(ENetSocket, ENetAddress*);
+	ENET_API int enet_socket_connect(ENetSocket, const ENetAddress*);
+	ENET_API int enet_socket_send(ENetSocket, const ENetAddress*, const ENetBuffer*, size_t);
+	ENET_API int enet_socket_receive(ENetSocket, ENetAddress*, ENetBuffer*, size_t);
+	ENET_API int enet_socket_wait(ENetSocket, enet_uint32*, enet_uint64);
+	ENET_API int enet_socket_set_option(ENetSocket, ENetSocketOption, int);
+	ENET_API int enet_socket_get_option(ENetSocket, ENetSocketOption, int*);
+	ENET_API int enet_socket_shutdown(ENetSocket, ENetSocketShutdown);
+	ENET_API void enet_socket_destroy(ENetSocket);
+	ENET_API int enet_socket_set_select(ENetSocket, ENetSocketSet*, ENetSocketSet*, enet_uint32);
+
+	ENET_API int enet_address_set_host_ip(ENetAddress*, const char*);
+	ENET_API int enet_address_set_host(ENetAddress*, const char*);
+	ENET_API int enet_address_get_host_ip(const ENetAddress*, char*, size_t);
+	ENET_API int enet_address_get_host(const ENetAddress*, char*, size_t);
+
+	ENET_API ENetPacket* enet_packet_create(const void*, size_t, enet_uint32);
+	ENET_API ENetPacket* enet_packet_create_offset(const void*, size_t, size_t, enet_uint32);
+	ENET_API void enet_packet_destroy(ENetPacket*);
+
+	ENET_API enet_uint32 enet_crc32(const ENetBuffer*, size_t);
+
+	ENET_API ENetHost* enet_host_create(const ENetAddress*, size_t, size_t, enet_uint32, enet_uint32);
+	ENET_API void enet_host_destroy(ENetHost*);
+	ENET_API void enet_host_enable_compression(ENetHost*);
+	ENET_API void enet_host_prevent_connections(ENetHost*, enet_uint8);
+	ENET_API ENetPeer* enet_host_connect(ENetHost*, const ENetAddress*, size_t, enet_uint32);
+	ENET_API int enet_host_check_events(ENetHost*, ENetEvent*);
+	ENET_API int enet_host_service(ENetHost*, ENetEvent*, enet_uint32);
+	ENET_API void enet_host_flush(ENetHost*);
+	ENET_API void enet_host_broadcast(ENetHost*, enet_uint8, ENetPacket*);
+	ENET_API void enet_host_broadcast_selective(ENetHost*, enet_uint8, ENetPacket*, ENetPeer**, size_t);
+	ENET_API void enet_host_channel_limit(ENetHost*, size_t);
+	ENET_API void enet_host_bandwidth_limit(ENetHost*, enet_uint32, enet_uint32);
+
+	ENET_API int enet_peer_send(ENetPeer*, enet_uint8, ENetPacket*);
+	ENET_API ENetPacket* enet_peer_receive(ENetPeer*, enet_uint8* channelID);
+	ENET_API void enet_peer_ping(ENetPeer*);
+	ENET_API void enet_peer_ping_interval(ENetPeer*, enet_uint32);
+	ENET_API void enet_peer_timeout(ENetPeer*, enet_uint32, enet_uint32, enet_uint32);
+	ENET_API void enet_peer_reset(ENetPeer*);
+	ENET_API void enet_peer_disconnect(ENetPeer*, enet_uint32);
+	ENET_API void enet_peer_disconnect_now(ENetPeer*, enet_uint32);
+	ENET_API void enet_peer_disconnect_later(ENetPeer*, enet_uint32);
+	ENET_API void enet_peer_throttle_configure(ENetPeer*, enet_uint32, enet_uint32, enet_uint32);
+
+	/* Extended API for easier binding in other programming languages */
+	ENET_API void* enet_packet_get_data(const ENetPacket*);
+	ENET_API int enet_packet_get_length(const ENetPacket*);
+	ENET_API void enet_packet_set_free_callback(ENetPacket*, const void*);
+	ENET_API int enet_packet_check_references(const ENetPacket*);
+	ENET_API void enet_packet_dispose(ENetPacket*);
+
+	ENET_API enet_uint32 enet_host_get_peers_count(const ENetHost*);
+	ENET_API enet_uint32 enet_host_get_packets_sent(const ENetHost*);
+	ENET_API enet_uint32 enet_host_get_packets_received(const ENetHost*);
+	ENET_API enet_uint32 enet_host_get_bytes_sent(const ENetHost*);
+	ENET_API enet_uint32 enet_host_get_bytes_received(const ENetHost*);
+
+	ENET_API enet_uint32 enet_peer_get_id(const ENetPeer*);
+	ENET_API int enet_peer_get_ip(const ENetPeer*, char* ip, size_t ipLength);
+	ENET_API enet_uint16 enet_peer_get_port(const ENetPeer*);
+	ENET_API enet_uint32 enet_peer_get_mtu(const ENetPeer*);
+	ENET_API ENetPeerState enet_peer_get_state(const ENetPeer*);
+	ENET_API enet_uint32 enet_peer_get_rtt(const ENetPeer*);
+	ENET_API enet_uint32 enet_peer_get_lastsendtime(const ENetPeer*);
+	ENET_API enet_uint32 enet_peer_get_lastreceivetime(const ENetPeer*);
+	ENET_API enet_uint64 enet_peer_get_packets_sent(const ENetPeer*);
+	ENET_API enet_uint64 enet_peer_get_packets_lost(const ENetPeer*);
+	ENET_API enet_uint64 enet_peer_get_bytes_sent(const ENetPeer*);
+	ENET_API enet_uint64 enet_peer_get_bytes_received(const ENetPeer*);
+	ENET_API void* enet_peer_get_data(const ENetPeer*);
+	ENET_API void enet_peer_set_data(ENetPeer*, const void*);
+
+// =======================================================================//
+// !
+// ! Private API
+// !
+// =======================================================================//
+
+	extern void enet_host_bandwidth_throttle(ENetHost*);
+	extern enet_uint64 enet_host_random_seed(void);
+
+	extern int enet_peer_throttle(ENetPeer*, enet_uint32);
+	extern void enet_peer_reset_queues(ENetPeer*);
+	extern void enet_peer_setup_outgoing_command(ENetPeer*, ENetOutgoingCommand*);
+	extern ENetOutgoingCommand* enet_peer_queue_outgoing_command(ENetPeer*, const ENetProtocol*, ENetPacket*, enet_uint32, enet_uint16);
+	extern ENetIncomingCommand* enet_peer_queue_incoming_command(ENetPeer*, const ENetProtocol*, const void*, size_t, enet_uint32, enet_uint32);
+	extern ENetAcknowledgement* enet_peer_queue_acknowledgement(ENetPeer*, const ENetProtocol*, enet_uint16);
+	extern void enet_peer_dispatch_incoming_unreliable_commands(ENetPeer*, ENetChannel*);
+	extern void enet_peer_dispatch_incoming_reliable_commands(ENetPeer*, ENetChannel*);
+	extern void enet_peer_on_connect(ENetPeer*);
+	extern void enet_peer_on_disconnect(ENetPeer*);
+
+	extern size_t enet_protocol_command_size(enet_uint8);
+
+#ifdef __cplusplus
+}
+#endif
+
+#if defined(ENET_IMPLEMENTATION) && !defined(ENET_IMPLEMENTATION_DONE)
+#define ENET_IMPLEMENTATION_DONE 1
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+// =======================================================================//
+// !
+// ! Atomics
+// !
+// =======================================================================//
+
+#ifdef _MSC_VER
+	#define ENET_AT_CASSERT_PRED(predicate) sizeof(char[2 * !!(predicate) - 1])
+	#define ENET_IS_SUPPORTED_ATOMIC(size) ENET_AT_CASSERT_PRED(size == 1 || size == 2 || size == 4 || size == 8)
+	#define ENET_ATOMIC_SIZEOF(variable) (ENET_IS_SUPPORTED_ATOMIC(sizeof(*(variable))), sizeof(*(variable)))
+
+	__inline int64_t enet_at_atomic_read(char* ptr, size_t size) {
+		switch (size) {
+			case 1:
+				return _InterlockedExchangeAdd8((volatile char*)ptr, 0);
+
+			case 2:
+				return _InterlockedExchangeAdd16((volatile SHORT*)ptr, 0);
+
+			case 4:
+				#ifdef NOT_UNDERSCORED_INTERLOCKED_EXCHANGE
+					return InterlockedExchangeAdd((volatile LONG*)ptr, 0);
+				#else
+					return _InterlockedExchangeAdd((volatile LONG*)ptr, 0);
+				#endif
+
+			case 8:
+				#ifdef NOT_UNDERSCORED_INTERLOCKED_EXCHANGE
+					return InterlockedExchangeAdd64((volatile LONGLONG*)ptr, 0);
+				#else
+					return _InterlockedExchangeAdd64((volatile LONGLONG*)ptr, 0);
+				#endif
+
+			default:
+				return 0x0;
+		}
+	}
+
+	__inline int64_t enet_at_atomic_write(char* ptr, int64_t value, size_t size) {
+		switch (size) {
+			case 1:
+				return _InterlockedExchange8((volatile char*)ptr, (char)value);
+
+			case 2:
+				return _InterlockedExchange16((volatile SHORT*)ptr, (SHORT)value);
+
+			case 4:
+				#ifdef NOT_UNDERSCORED_INTERLOCKED_EXCHANGE
+					return InterlockedExchange((volatile LONG*)ptr, (LONG)value);
+				#else
+					return _InterlockedExchange((volatile LONG*)ptr, (LONG)value);
+				#endif
+
+			case 8:
+				#ifdef NOT_UNDERSCORED_INTERLOCKED_EXCHANGE
+					return InterlockedExchange64((volatile LONGLONG*)ptr, (LONGLONG)value);
+				#else
+					return _InterlockedExchange64((volatile LONGLONG*)ptr, (LONGLONG)value);
+				#endif
+
+			default:
+				return 0x0;
+		}
+	}
+
+	__inline int64_t enet_at_atomic_cas(char* ptr, int64_t new_val, int64_t old_val, size_t size) {
+		switch (size) {
+			case 1:
+				return _InterlockedCompareExchange8((volatile char*)ptr, (char)new_val, (char)old_val);
+
+			case 2:
+				return _InterlockedCompareExchange16((volatile SHORT*)ptr, (SHORT)new_val, (SHORT)old_val);
+
+			case 4:
+				#ifdef NOT_UNDERSCORED_INTERLOCKED_EXCHANGE
+					return InterlockedCompareExchange((volatile LONG*)ptr, (LONG)new_val, (LONG)old_val);
+				#else
+					return _InterlockedCompareExchange((volatile LONG*)ptr, (LONG)new_val, (LONG)old_val);
+				#endif
+
+			case 8:
+				#ifdef NOT_UNDERSCORED_INTERLOCKED_EXCHANGE
+					return InterlockedCompareExchange64((volatile LONGLONG*)ptr, (LONGLONG)new_val, (LONGLONG)old_val);
+				#else
+					return _InterlockedCompareExchange64((volatile LONGLONG*)ptr, (LONGLONG)new_val, (LONGLONG)old_val);
+				#endif
+
+			default:
+				return 0x0;
+		}
+	}
+
+	__inline int64_t enet_at_atomic_inc(char* ptr, int64_t delta, size_t data_size) {
+		switch (data_size) {
+			case 1:
+				return _InterlockedExchangeAdd8((volatile char*)ptr, (char)delta);
+
+			case 2:
+				return _InterlockedExchangeAdd16((volatile SHORT*)ptr, (SHORT)delta);
+
+			case 4:
+				#ifdef NOT_UNDERSCORED_INTERLOCKED_EXCHANGE
+					return InterlockedExchangeAdd((volatile LONG*)ptr, (LONG)delta);
+				#else
+					return _InterlockedExchangeAdd((volatile LONG*)ptr, (LONG)delta);
+				#endif
+
+			case 8:
+				#ifdef NOT_UNDERSCORED_INTERLOCKED_EXCHANGE
+					return InterlockedExchangeAdd64((volatile LONGLONG*)ptr, (LONGLONG)delta);
+				#else
+					return _InterlockedExchangeAdd64((volatile LONGLONG*)ptr, (LONGLONG)delta);
+				#endif
+
+			default:
+				return 0x0;
+		}
+	}
+
+	#define ENET_ATOMIC_READ(variable) enet_at_atomic_read((char*)(variable), ENET_ATOMIC_SIZEOF(variable))
+	#define ENET_ATOMIC_WRITE(variable, new_val) enet_at_atomic_write((char*)(variable), (int64_t)(new_val), ENET_ATOMIC_SIZEOF(variable))
+	#define ENET_ATOMIC_CAS(variable, old_value, new_val) enet_at_atomic_cas((char*)(variable), (int64_t)(new_val), (int64_t)(old_value), ENET_ATOMIC_SIZEOF(variable))
+	#define ENET_ATOMIC_INC(variable) enet_at_atomic_inc((char*)(variable), 1, ENET_ATOMIC_SIZEOF(variable))
+	#define ENET_ATOMIC_DEC(variable) enet_at_atomic_inc((char*)(variable), -1, ENET_ATOMIC_SIZEOF(variable))
+	#define ENET_ATOMIC_INC_BY(variable, delta) enet_at_atomic_inc((char*)(variable), (delta), ENET_ATOMIC_SIZEOF(variable))
+	#define ENET_ATOMIC_DEC_BY(variable, delta) enet_at_atomic_inc((char*)(variable), -(delta), ENET_ATOMIC_SIZEOF(variable))
+#elif defined(__GNUC__) || defined(__clang__)
+	#if defined(__clang__) || (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7))
+		#define AT_HAVE_ATOMICS
+	#endif
+
+	/* We want to use __atomic built-ins if possible because the __sync primitives are
+	deprecated, because the __atomic build-ins allow us to use ENET_ATOMIC_WRITE on
+	uninitialized memory without running into undefined behavior, and because the
+	__atomic versions generate more efficient code since we don't need to rely on
+	CAS when we don't actually want it.
+
+	Note that we use acquire-release memory order (like mutexes do). We could use
+	sequentially consistent memory order but that has lower performance and is
+	almost always unneeded. */
+	#ifdef AT_HAVE_ATOMICS
+		#define ENET_ATOMIC_READ(ptr) __atomic_load_n((ptr), __ATOMIC_ACQUIRE)
+		#define ENET_ATOMIC_WRITE(ptr, value) __atomic_store_n((ptr), (value), __ATOMIC_RELEASE)
+
+		#ifndef typeof
+			#define typeof __typeof__
+		#endif
+
+		/* clang_analyzer doesn't know that CAS writes to memory so it complains about
+		potentially lost data. Replace the code with the equivalent non-sync code. */
+		#ifdef __clang_analyzer__
+			#define ENET_ATOMIC_CAS(ptr, old_value, new_value)                                                                   \
+				({                                                                                                               \
+					typeof(*(ptr)) ENET_ATOMIC_CAS_old_actual_ = (*(ptr));                                                       \
+					if (ATOMIC_CAS_old_actual_ == (old_value))                                                                   \
+						*(ptr) = new_value;                                                                                      \
+					ENET_ATOMIC_CAS_old_actual_;                                                                                 \
+				})
+			#else
+			/* Could use __auto_type instead of typeof but that shouldn't work in C++.
+			The ({ }) syntax is a GCC extension called statement expression. It lets
+			us return a value out of the macro.
+
+			TODO We should return bool here instead of the old value to avoid the ABA
+			problem. */
+			#define ENET_ATOMIC_CAS(ptr, old_value, new_value)                                                                   \
+				({                                                                                                               \
+					typeof(*(ptr)) ENET_ATOMIC_CAS_expected_ = (old_value);                                                      \
+					__atomic_compare_exchange_n((ptr), &ENET_ATOMIC_CAS_expected_, (new_value), false,                           \
+					__ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE);                                                                         \
+					ENET_ATOMIC_CAS_expected_;                                                                                   \
+				})
+			#endif
+
+			#define ENET_ATOMIC_INC(ptr) __atomic_fetch_add((ptr), 1, __ATOMIC_ACQ_REL)
+			#define ENET_ATOMIC_DEC(ptr) __atomic_fetch_sub((ptr), 1, __ATOMIC_ACQ_REL)
+			#define ENET_ATOMIC_INC_BY(ptr, delta) __atomic_fetch_add((ptr), (delta), __ATOMIC_ACQ_REL)
+			#define ENET_ATOMIC_DEC_BY(ptr, delta) __atomic_fetch_sub((ptr), (delta), __ATOMIC_ACQ_REL)
+		#else
+			#define ENET_ATOMIC_READ(variable) __sync_fetch_and_add(variable, 0)
+			#define ENET_ATOMIC_WRITE(variable, new_val) (void)__sync_val_compare_and_swap((variable), *(variable), (new_val))
+			#define ENET_ATOMIC_CAS(variable, old_value, new_val) __sync_val_compare_and_swap((variable), (old_value), (new_val))
+			#define ENET_ATOMIC_INC(variable) __sync_fetch_and_add((variable), 1)
+			#define ENET_ATOMIC_DEC(variable) __sync_fetch_and_sub((variable), 1)
+			#define ENET_ATOMIC_INC_BY(variable, delta) __sync_fetch_and_add((variable), (delta), 1)
+			#define ENET_ATOMIC_DEC_BY(variable, delta) __sync_fetch_and_sub((variable), (delta), 1)
+		#endif
+	#undef AT_HAVE_ATOMICS
+#endif
+
+// =======================================================================//
+// !
+// ! Globals
+// !
+// =======================================================================//
+
+	ENetVersion enet_linked_version(void) {
+		return ENET_VERSION;
+	}
+
+// =======================================================================//
+// !
+// ! Callbacks
+// !
+// =======================================================================//
+
+	static ENetCallbacks callbacks = { malloc, free, abort };
+
+	int enet_initialize_with_callbacks(ENetVersion version, const ENetCallbacks* inits) {
+		if (version < ENET_VERSION_CREATE(1, 3, 0))
+			return -1;
+
+		if (inits->malloc != NULL || inits->free != NULL) {
+			if (inits->malloc == NULL || inits->free == NULL)
+				return -1;
+
+			callbacks.malloc = inits->malloc;
+			callbacks.free   = inits->free;
+		}
+
+		if (inits->noMemory != NULL)
+			callbacks.noMemory = inits->noMemory;
+
+		return enet_initialize();
+	}
+
+	void* enet_malloc(size_t size) {
+		void* memory = callbacks.malloc(size);
+
+		if (memory == NULL)
+			callbacks.noMemory();
+
+		return memory;
+	}
+
+	void enet_free(void* memory) {
+		callbacks.free(memory);
+	}
+
+// =======================================================================//
+// !
+// ! List
+// !
+// =======================================================================//
+
+	void enet_list_clear(ENetList* list) {
+		list->sentinel.next     = &list->sentinel;
+		list->sentinel.previous = &list->sentinel;
+	}
+
+	ENetListIterator enet_list_insert(ENetListIterator position, void* data) {
+		ENetListIterator result = (ENetListIterator)data;
+		result->previous        = position->previous;
+		result->next            = position;
+		result->previous->next  = result;
+		position->previous      = result;
+
+		return result;
+	}
+
+	void* enet_list_remove(ENetListIterator position) {
+		position->previous->next = position->next;
+		position->next->previous = position->previous;
+
+		return position;
+	}
+
+	ENetListIterator enet_list_move(ENetListIterator position, void* dataFirst, void* dataLast) {
+		ENetListIterator first = (ENetListIterator)dataFirst;
+		ENetListIterator last  = (ENetListIterator)dataLast;
+		first->previous->next  = last->next;
+		last->next->previous   = first->previous;
+		first->previous        = position->previous;
+		last->next             = position;
+		first->previous->next  = first;
+		position->previous     = last;
+
+		return first;
+	}
+
+	size_t enet_list_size(ENetList* list) {
+		size_t size = 0;
+		ENetListIterator position;
+
+		for (position = enet_list_begin(list); position != enet_list_end(list); position = enet_list_next(position)) {
+			++size;
+		}
+
+		return size;
+	}
+
+// =======================================================================//
+// !
+// ! Packet
+// !
+// =======================================================================//
+
+	ENetPacket* enet_packet_create(const void* data, size_t dataLength, enet_uint32 flags) {
+		ENetPacket* packet;
+
+		if (flags & ENET_PACKET_FLAG_NO_ALLOCATE) {
+			packet = (ENetPacket*)enet_malloc(sizeof(ENetPacket));
+
+			if (packet == NULL)
+				return NULL;
+
+			packet->data = (enet_uint8*)data;
+		} else {
+			packet = (ENetPacket*)enet_malloc(sizeof(ENetPacket) + dataLength);
+
+			if (packet == NULL)
+				return NULL;
+
+			packet->data = (enet_uint8*)packet + sizeof(ENetPacket);
+
+			if (data != NULL)
+				memcpy(packet->data, data, dataLength);
+		}
+
+		packet->referenceCount = 0;
+		packet->flags          = flags;
+		packet->dataLength     = dataLength;
+		packet->freeCallback   = NULL;
+
+		return packet;
+	}
+
+	ENetPacket* enet_packet_create_offset(const void* data, size_t dataLength, size_t dataOffset, enet_uint32 flags) {
+		ENetPacket* packet;
+
+		if (flags & ENET_PACKET_FLAG_NO_ALLOCATE) {
+			packet = (ENetPacket*)enet_malloc(sizeof(ENetPacket));
+
+			if (packet == NULL)
+				return NULL;
+
+			packet->data = (enet_uint8*)data;
+		} else {
+			packet = (ENetPacket*)enet_malloc(sizeof(ENetPacket) + dataLength - dataOffset);
+
+			if (packet == NULL)
+				return NULL;
+
+			packet->data = (enet_uint8*)packet + sizeof(ENetPacket);
+
+			if (data != NULL)
+				memcpy(packet->data, (char*)data + dataOffset, dataLength - dataOffset);
+		}
+
+		packet->referenceCount = 0;
+		packet->flags          = flags;
+		packet->dataLength     = dataLength - dataOffset;
+		packet->freeCallback   = NULL;
+
+		return packet;
+	}
+
+	void enet_packet_destroy(ENetPacket* packet) {
+		if (packet == NULL)
+			return;
+
+		if (packet->freeCallback != NULL)
+			(*packet->freeCallback)((void*)packet);
+
+		enet_free(packet);
+	}
+
+	static int initializedCRC32 = 0;
+	static enet_uint32 crcTable[256];
+
+	static enet_uint32 reflect_crc(int val, int bits) {
+		int result = 0, bit;
+
+		for (bit = 0; bit < bits; bit++) {
+			if (val & 1)
+				result |= 1 << (bits - 1 - bit);
+
+			val >>= 1;
+		}
+
+		return result;
+	}
+
+	static void initialize_crc32(void) {
+		int byte;
+
+		for (byte = 0; byte < 256; ++byte) {
+			enet_uint32 crc = reflect_crc(byte, 8) << 24;
+			int offset;
+
+			for (offset = 0; offset < 8; ++offset) {
+				if (crc & 0x80000000)
+					crc = (crc << 1) ^ 0x04c11db7;
+				else
+					crc <<= 1;
+			}
+
+			crcTable[byte] = reflect_crc(crc, 32);
+		}
+
+		initializedCRC32 = 1;
+	}
+
+	enet_uint32 enet_crc32(const ENetBuffer* buffers, size_t bufferCount) {
+		enet_uint32 crc = 0xFFFFFFFF;
+
+		if (!initializedCRC32)
+			initialize_crc32();
+
+		while (bufferCount-- > 0) {
+			const enet_uint8* data = (const enet_uint8*)buffers->data;
+			const enet_uint8* dataEnd = &data[buffers->dataLength];
+
+			while (data < dataEnd) {
+				crc = (crc >> 8) ^ crcTable[(crc & 0xFF)^* data++];
+			}
+
+			++buffers;
+		}
+
+		return ENET_HOST_TO_NET_32(~crc);
+	}
+
+// =======================================================================//
+// !
+// ! Protocol
+// !
+// =======================================================================//
+
+	static size_t commandSizes[ENET_PROTOCOL_COMMAND_COUNT] = {
+		0,
+		sizeof(ENetProtocolAcknowledge),
+		sizeof(ENetProtocolConnect),
+		sizeof(ENetProtocolVerifyConnect),
+		sizeof(ENetProtocolDisconnect),
+		sizeof(ENetProtocolPing),
+		sizeof(ENetProtocolSendReliable),
+		sizeof(ENetProtocolSendUnreliable),
+		sizeof(ENetProtocolSendFragment),
+		sizeof(ENetProtocolSendUnsequenced),
+		sizeof(ENetProtocolBandwidthLimit),
+		sizeof(ENetProtocolThrottleConfigure),
+		sizeof(ENetProtocolSendFragment)
+	};
+
+	size_t enet_protocol_command_size(enet_uint8 commandNumber) {
+		return commandSizes[commandNumber & ENET_PROTOCOL_COMMAND_MASK];
+	}
+
+	static void enet_protocol_change_state(ENetHost* host, ENetPeer* peer, ENetPeerState state) {
+		if (state == ENET_PEER_STATE_CONNECTED || state == ENET_PEER_STATE_DISCONNECT_LATER)
+			enet_peer_on_connect(peer);
+		else
+			enet_peer_on_disconnect(peer);
+
+		peer->state = state;
+	}
+
+	static void enet_protocol_dispatch_state(ENetHost* host, ENetPeer* peer, ENetPeerState state) {
+		enet_protocol_change_state(host, peer, state);
+
+		if (!peer->needsDispatch) {
+			enet_list_insert(enet_list_end(&host->dispatchQueue), &peer->dispatchList);
+
+			peer->needsDispatch = 1;
+		}
+	}
+
+	static int enet_protocol_dispatch_incoming_commands(ENetHost* host, ENetEvent* event) {
+		while (!enet_list_empty(&host->dispatchQueue)) {
+			ENetPeer* peer = (ENetPeer*)enet_list_remove(enet_list_begin(&host->dispatchQueue));
+			peer->needsDispatch = 0;
+
+			switch (peer->state) {
+				case ENET_PEER_STATE_CONNECTION_PENDING:
+				case ENET_PEER_STATE_CONNECTION_SUCCEEDED:
+					enet_protocol_change_state(host, peer, ENET_PEER_STATE_CONNECTED);
+
+					event->type = ENET_EVENT_TYPE_CONNECT;
+					event->peer = peer;
+					event->data = peer->eventData;
+
+					return 1;
+
+				case ENET_PEER_STATE_ZOMBIE:
+					host->recalculateBandwidthLimits = 1;
+					event->type = ENET_EVENT_TYPE_DISCONNECT;
+					event->peer = peer;
+					event->data = peer->eventData;
+
+					enet_peer_reset(peer);
+
+					return 1;
+
+				case ENET_PEER_STATE_CONNECTED:
+					if (enet_list_empty(&peer->dispatchedCommands))
+						continue;
+
+					event->packet = enet_peer_receive(peer, &event->channelID);
+
+					if (event->packet == NULL)
+						continue;
+
+					event->type = ENET_EVENT_TYPE_RECEIVE;
+					event->peer = peer;
+
+					if (!enet_list_empty(&peer->dispatchedCommands)) {
+						peer->needsDispatch = 1;
+
+						enet_list_insert(enet_list_end(&host->dispatchQueue), &peer->dispatchList);
+					}
+
+					return 1;
+
+				default:
+					break;
+			}
+		}
+
+		return 0;
+	}
+
+	static void enet_protocol_notify_connect(ENetHost* host, ENetPeer* peer, ENetEvent* event) {
+		host->recalculateBandwidthLimits = 1;
+
+		if (event != NULL) {
+			enet_protocol_change_state(host, peer, ENET_PEER_STATE_CONNECTED);
+
+			peer->totalDataSent     = 0;
+			peer->totalDataReceived = 0;
+			peer->totalPacketsSent  = 0;
+			peer->totalPacketsLost  = 0;
+			event->type = ENET_EVENT_TYPE_CONNECT;
+			event->peer = peer;
+			event->data = peer->eventData;
+		} else {
+			enet_protocol_dispatch_state(host, peer, peer->state == ENET_PEER_STATE_CONNECTING ? ENET_PEER_STATE_CONNECTION_SUCCEEDED : ENET_PEER_STATE_CONNECTION_PENDING);
+		}
+	}
+
+	static void enet_protocol_notify_disconnect(ENetHost* host, ENetPeer* peer, ENetEvent* event) {
+		if (peer->state >= ENET_PEER_STATE_CONNECTION_PENDING)
+			host->recalculateBandwidthLimits = 1;
+
+		if (peer->state != ENET_PEER_STATE_CONNECTING && peer->state < ENET_PEER_STATE_CONNECTION_SUCCEEDED) {
+			enet_peer_reset(peer);
+		} else if (event != NULL) {
+			event->type = ENET_EVENT_TYPE_DISCONNECT;
+			event->peer = peer;
+			event->data = 0;
+
+			enet_peer_reset(peer);
+		} else {
+			peer->eventData = 0;
+
+			enet_protocol_dispatch_state(host, peer, ENET_PEER_STATE_ZOMBIE);
+		}
+	}
+
+	static void enet_protocol_notify_disconnect_timeout(ENetHost* host, ENetPeer* peer, ENetEvent* event) {
+		if (peer->state >= ENET_PEER_STATE_CONNECTION_PENDING)
+			host->recalculateBandwidthLimits = 1;
+
+		if (peer->state != ENET_PEER_STATE_CONNECTING && peer->state < ENET_PEER_STATE_CONNECTION_SUCCEEDED) {
+			enet_peer_reset(peer);
+		} else if (event != NULL) {
+			event->type = ENET_EVENT_TYPE_DISCONNECT_TIMEOUT;
+			event->peer = peer;
+			event->data = 0;
+
+			enet_peer_reset(peer);
+		} else {
+			peer->eventData = 0;
+
+			enet_protocol_dispatch_state(host, peer, ENET_PEER_STATE_ZOMBIE);
+		}
+	}
+
+	static void enet_protocol_remove_sent_unreliable_commands(ENetPeer* peer) {
+		ENetOutgoingCommand* outgoingCommand;
+
+		if (enet_list_empty(&peer->sentUnreliableCommands))
+			return;
+
+		do {
+			outgoingCommand = (ENetOutgoingCommand*)enet_list_front(&peer->sentUnreliableCommands);
+
+			enet_list_remove(&outgoingCommand->outgoingCommandList);
+
+			if (outgoingCommand->packet != NULL) {
+				--outgoingCommand->packet->referenceCount;
+
+				if (outgoingCommand->packet->referenceCount == 0) {
+					outgoingCommand->packet->flags |= ENET_PACKET_FLAG_SENT;
+
+					enet_packet_destroy(outgoingCommand->packet);
+				}
+			}
+
+			enet_free(outgoingCommand);
+		}
+
+		while (!enet_list_empty(&peer->sentUnreliableCommands));
+
+		if (peer->state == ENET_PEER_STATE_DISCONNECT_LATER && enet_list_empty(&peer->outgoingReliableCommands) && enet_list_empty(&peer->outgoingUnreliableCommands) && enet_list_empty(&peer->sentReliableCommands))
+			enet_peer_disconnect(peer, peer->eventData);
+	}
+
+	static ENetProtocolCommand enet_protocol_remove_sent_reliable_command(ENetPeer* peer, enet_uint16 reliableSequenceNumber, enet_uint8 channelID) {
+		ENetOutgoingCommand* outgoingCommand = NULL;
+		ENetListIterator currentCommand;
+		ENetProtocolCommand commandNumber;
+
+		int wasSent = 1;
+
+		for (currentCommand = enet_list_begin(&peer->sentReliableCommands); currentCommand != enet_list_end(&peer->sentReliableCommands); currentCommand = enet_list_next(currentCommand)) {
+			outgoingCommand = (ENetOutgoingCommand*)currentCommand;
+
+			if (outgoingCommand->reliableSequenceNumber == reliableSequenceNumber && outgoingCommand->command.header.channelID == channelID)
+				break;
+		}
+
+		if (currentCommand == enet_list_end(&peer->sentReliableCommands)) {
+			for (currentCommand = enet_list_begin(&peer->outgoingReliableCommands); currentCommand != enet_list_end(&peer->outgoingReliableCommands); currentCommand = enet_list_next(currentCommand)) {
+				outgoingCommand = (ENetOutgoingCommand*)currentCommand;
+
+				if (outgoingCommand->sendAttempts < 1)
+					return ENET_PROTOCOL_COMMAND_NONE;
+
+				if (outgoingCommand->reliableSequenceNumber == reliableSequenceNumber && outgoingCommand->command.header.channelID == channelID)
+					break;
+			}
+
+			if (currentCommand == enet_list_end(&peer->outgoingReliableCommands))
+				return ENET_PROTOCOL_COMMAND_NONE;
+
+			wasSent = 0;
+		}
+
+		if (outgoingCommand == NULL)
+			return ENET_PROTOCOL_COMMAND_NONE;
+
+		if (channelID < peer->channelCount) {
+			ENetChannel* channel       = &peer->channels[channelID];
+			enet_uint16 reliableWindow = reliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
+
+			if (channel->reliableWindows[reliableWindow] > 0) {
+				--channel->reliableWindows[reliableWindow];
+
+				if (!channel->reliableWindows[reliableWindow])
+					channel->usedReliableWindows &= ~(1 << reliableWindow);
+			}
+		}
+
+		commandNumber = (ENetProtocolCommand)(outgoingCommand->command.header.command & ENET_PROTOCOL_COMMAND_MASK);
+
+		enet_list_remove(&outgoingCommand->outgoingCommandList);
+
+		if (outgoingCommand->packet != NULL) {
+			if (wasSent)
+				peer->reliableDataInTransit -= outgoingCommand->fragmentLength;
+
+			--outgoingCommand->packet->referenceCount;
+
+			if (outgoingCommand->packet->referenceCount == 0) {
+				outgoingCommand->packet->flags |= ENET_PACKET_FLAG_SENT;
+
+				enet_packet_destroy(outgoingCommand->packet);
+			}
+		}
+
+		enet_free(outgoingCommand);
+
+		if (enet_list_empty(&peer->sentReliableCommands))
+			return commandNumber;
+
+		outgoingCommand = (ENetOutgoingCommand*)enet_list_front(&peer->sentReliableCommands);
+		peer->nextTimeout = outgoingCommand->sentTime + outgoingCommand->roundTripTimeout;
+
+		return commandNumber;
+	}
+
+	static ENetPeer* enet_protocol_handle_connect(ENetHost* host, ENetProtocolHeader* header, ENetProtocol* command) {
+		enet_uint8 incomingSessionID, outgoingSessionID;
+		enet_uint32 mtu, windowSize;
+		ENetChannel* channel;
+		size_t channelCount, duplicatePeers = 0;
+		ENetPeer* currentPeer, *peer = NULL;
+		ENetProtocol verifyCommand;
+		channelCount = ENET_NET_TO_HOST_32(command->connect.channelCount);
+
+		if (channelCount < ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT || channelCount > ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT)
+			return NULL;
+
+		for (currentPeer = host->peers; currentPeer < &host->peers[host->peerCount]; ++currentPeer) {
+			if (currentPeer->state == ENET_PEER_STATE_DISCONNECTED) {
+				if (peer == NULL)
+					peer = currentPeer;
+			} else if (currentPeer->state != ENET_PEER_STATE_CONNECTING && in6_equal(currentPeer->address.host, host->receivedAddress.host)) {
+				if (currentPeer->address.port == host->receivedAddress.port && currentPeer->connectID == command->connect.connectID)
+					return NULL;
+
+				++duplicatePeers;
+			}
+		}
+
+		if (peer == NULL || duplicatePeers >= host->duplicatePeers)
+			return NULL;
+
+		if (channelCount > host->channelLimit)
+			channelCount = host->channelLimit;
+
+		peer->channels = (ENetChannel*)enet_malloc(channelCount * sizeof(ENetChannel));
+
+		if (peer->channels == NULL)
+			return NULL;
+
+		peer->channelCount               = channelCount;
+		peer->state                      = ENET_PEER_STATE_ACKNOWLEDGING_CONNECT;
+		peer->connectID                  = command->connect.connectID;
+		peer->address                    = host->receivedAddress;
+		peer->outgoingPeerID             = ENET_NET_TO_HOST_16(command->connect.outgoingPeerID);
+		peer->incomingBandwidth          = ENET_NET_TO_HOST_32(command->connect.incomingBandwidth);
+		peer->outgoingBandwidth          = ENET_NET_TO_HOST_32(command->connect.outgoingBandwidth);
+		peer->packetThrottleInterval     = ENET_NET_TO_HOST_32(command->connect.packetThrottleInterval);
+		peer->packetThrottleAcceleration = ENET_NET_TO_HOST_32(command->connect.packetThrottleAcceleration);
+		peer->packetThrottleDeceleration = ENET_NET_TO_HOST_32(command->connect.packetThrottleDeceleration);
+		peer->eventData                  = ENET_NET_TO_HOST_32(command->connect.data);
+		incomingSessionID = command->connect.incomingSessionID == 0xFF ? peer->outgoingSessionID : command->connect.incomingSessionID;
+		incomingSessionID = (incomingSessionID + 1) & (ENET_PROTOCOL_HEADER_SESSION_MASK >> ENET_PROTOCOL_HEADER_SESSION_SHIFT);
+
+		if (incomingSessionID == peer->outgoingSessionID)
+			incomingSessionID = (incomingSessionID + 1) & (ENET_PROTOCOL_HEADER_SESSION_MASK >> ENET_PROTOCOL_HEADER_SESSION_SHIFT);
+
+		peer->outgoingSessionID = incomingSessionID;
+		outgoingSessionID = command->connect.outgoingSessionID == 0xFF ? peer->incomingSessionID : command->connect.outgoingSessionID;
+		outgoingSessionID = (outgoingSessionID + 1) & (ENET_PROTOCOL_HEADER_SESSION_MASK >> ENET_PROTOCOL_HEADER_SESSION_SHIFT);
+
+		if (outgoingSessionID == peer->incomingSessionID)
+			outgoingSessionID = (outgoingSessionID + 1) & (ENET_PROTOCOL_HEADER_SESSION_MASK >> ENET_PROTOCOL_HEADER_SESSION_SHIFT);
+
+		peer->incomingSessionID = outgoingSessionID;
+
+		for (channel = peer->channels; channel < &peer->channels[channelCount]; ++channel) {
+			channel->outgoingReliableSequenceNumber   = 0;
+			channel->outgoingUnreliableSequenceNumber = 0;
+			channel->incomingReliableSequenceNumber   = 0;
+			channel->incomingUnreliableSequenceNumber = 0;
+
+			enet_list_clear(&channel->incomingReliableCommands);
+			enet_list_clear(&channel->incomingUnreliableCommands);
+
+			channel->usedReliableWindows = 0;
+
+			memset(channel->reliableWindows, 0, sizeof(channel->reliableWindows));
+		}
+
+		mtu = ENET_NET_TO_HOST_32(command->connect.mtu);
+
+		if (mtu < ENET_PROTOCOL_MINIMUM_MTU)
+			mtu = ENET_PROTOCOL_MINIMUM_MTU;
+		else if (mtu > ENET_PROTOCOL_MAXIMUM_MTU)
+			mtu = ENET_PROTOCOL_MAXIMUM_MTU;
+
+		peer->mtu = mtu;
+
+		if (host->outgoingBandwidth == 0 && peer->incomingBandwidth == 0)
+			peer->windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
+		else if (host->outgoingBandwidth == 0 || peer->incomingBandwidth == 0)
+			peer->windowSize = (ENET_MAX(host->outgoingBandwidth, peer->incomingBandwidth) / ENET_PEER_WINDOW_SIZE_SCALE) * ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
+		else
+			peer->windowSize = (ENET_MIN(host->outgoingBandwidth, peer->incomingBandwidth) / ENET_PEER_WINDOW_SIZE_SCALE) * ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
+
+		if (peer->windowSize < ENET_PROTOCOL_MINIMUM_WINDOW_SIZE)
+			peer->windowSize = ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
+		else if (peer->windowSize > ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE)
+			peer->windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
+
+		if (host->incomingBandwidth == 0)
+			windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
+		else
+			windowSize = (host->incomingBandwidth / ENET_PEER_WINDOW_SIZE_SCALE) * ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
+
+		if (windowSize > ENET_NET_TO_HOST_32(command->connect.windowSize))
+			windowSize = ENET_NET_TO_HOST_32(command->connect.windowSize);
+
+		if (windowSize < ENET_PROTOCOL_MINIMUM_WINDOW_SIZE)
+			windowSize = ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
+		else if (windowSize > ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE)
+			windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
+
+		verifyCommand.header.command                           = ENET_PROTOCOL_COMMAND_VERIFY_CONNECT | ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE;
+		verifyCommand.header.channelID                         = 0xFF;
+		verifyCommand.verifyConnect.outgoingPeerID             = ENET_HOST_TO_NET_16(peer->incomingPeerID);
+		verifyCommand.verifyConnect.incomingSessionID          = incomingSessionID;
+		verifyCommand.verifyConnect.outgoingSessionID          = outgoingSessionID;
+		verifyCommand.verifyConnect.mtu                        = ENET_HOST_TO_NET_32(peer->mtu);
+		verifyCommand.verifyConnect.windowSize                 = ENET_HOST_TO_NET_32(windowSize);
+		verifyCommand.verifyConnect.channelCount               = ENET_HOST_TO_NET_32(channelCount);
+		verifyCommand.verifyConnect.incomingBandwidth          = ENET_HOST_TO_NET_32(host->incomingBandwidth);
+		verifyCommand.verifyConnect.outgoingBandwidth          = ENET_HOST_TO_NET_32(host->outgoingBandwidth);
+		verifyCommand.verifyConnect.packetThrottleInterval     = ENET_HOST_TO_NET_32(peer->packetThrottleInterval);
+		verifyCommand.verifyConnect.packetThrottleAcceleration = ENET_HOST_TO_NET_32(peer->packetThrottleAcceleration);
+		verifyCommand.verifyConnect.packetThrottleDeceleration = ENET_HOST_TO_NET_32(peer->packetThrottleDeceleration);
+		verifyCommand.verifyConnect.connectID                  = peer->connectID;
+
+		enet_peer_queue_outgoing_command(peer, &verifyCommand, NULL, 0, 0);
+
+		return peer;
+	}
+
+	static int enet_protocol_handle_send_reliable(ENetHost* host, ENetPeer* peer, const ENetProtocol* command, enet_uint8** currentData) {
+		size_t dataLength;
+
+		if (command->header.channelID >= peer->channelCount || (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER))
+			return -1;
+
+		dataLength    = ENET_NET_TO_HOST_16(command->sendReliable.dataLength);
+		*currentData += dataLength;
+
+		if (dataLength > host->maximumPacketSize || *currentData < host->receivedData || *currentData > &host->receivedData[host->receivedDataLength])
+			return -1;
+
+		if (enet_peer_queue_incoming_command(peer, command, (const enet_uint8*)command + sizeof(ENetProtocolSendReliable), dataLength, ENET_PACKET_FLAG_RELIABLE, 0) == NULL)
+			return -1;
+
+		return 0;
+	}
+
+	static int enet_protocol_handle_send_unsequenced(ENetHost* host, ENetPeer* peer, const ENetProtocol* command, enet_uint8** currentData) {
+		enet_uint32 unsequencedGroup, index;
+		size_t dataLength;
+
+		if (command->header.channelID >= peer->channelCount || (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER))
+			return -1;
+
+		dataLength    = ENET_NET_TO_HOST_16(command->sendUnsequenced.dataLength);
+		*currentData += dataLength;
+
+		if (dataLength > host->maximumPacketSize || *currentData < host->receivedData || *currentData > &host->receivedData[host->receivedDataLength])
+			return -1;
+
+		unsequencedGroup = ENET_NET_TO_HOST_16(command->sendUnsequenced.unsequencedGroup);
+		index = unsequencedGroup % ENET_PEER_UNSEQUENCED_WINDOW_SIZE;
+
+		if (unsequencedGroup < peer->incomingUnsequencedGroup)
+			unsequencedGroup += 0x10000;
+
+		if (unsequencedGroup >= (enet_uint32)peer->incomingUnsequencedGroup + ENET_PEER_FREE_UNSEQUENCED_WINDOWS * ENET_PEER_UNSEQUENCED_WINDOW_SIZE)
+			return 0;
+
+		unsequencedGroup &= 0xFFFF;
+
+		if (unsequencedGroup - index != peer->incomingUnsequencedGroup) {
+			peer->incomingUnsequencedGroup = unsequencedGroup - index;
+
+			memset(peer->unsequencedWindow, 0, sizeof(peer->unsequencedWindow));
+		} else if (peer->unsequencedWindow[index / 32] & (1 << (index % 32))) {
+			return 0;
+		}
+		
+		if (enet_peer_queue_incoming_command(peer, command, (const enet_uint8*)command + sizeof(ENetProtocolSendUnsequenced), dataLength, ENET_PACKET_FLAG_UNSEQUENCED, 0) == NULL)
+			return -1;
+
+		peer->unsequencedWindow[index / 32] |= 1 << (index % 32);
+
+		return 0;
+	}
+
+	static int enet_protocol_handle_send_unreliable(ENetHost* host, ENetPeer* peer, const ENetProtocol* command, enet_uint8** currentData) {
+		size_t dataLength;
+
+		if (command->header.channelID >= peer->channelCount || (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER))
+			return -1;
+
+		dataLength    = ENET_NET_TO_HOST_16(command->sendUnreliable.dataLength);
+		*currentData += dataLength;
+
+		if (dataLength > host->maximumPacketSize || *currentData < host->receivedData || *currentData > &host->receivedData[host->receivedDataLength])
+			return -1;
+
+		if (enet_peer_queue_incoming_command(peer, command, (const enet_uint8*)command + sizeof(ENetProtocolSendUnreliable), dataLength, 0, 0) == NULL)
+			return -1;
+
+		return 0;
+	}
+
+	static int enet_protocol_handle_send_fragment(ENetHost* host, ENetPeer* peer, const ENetProtocol* command, enet_uint8** currentData) {
+		enet_uint32 fragmentNumber, fragmentCount, fragmentOffset, fragmentLength, startSequenceNumber, totalLength;
+		ENetChannel* channel;
+		enet_uint16 startWindow, currentWindow;
+		ENetListIterator currentCommand;
+		ENetIncomingCommand* startCommand = NULL;
+
+		if (command->header.channelID >= peer->channelCount || (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER))
+			return -1;
+
+		fragmentLength = ENET_NET_TO_HOST_16(command->sendFragment.dataLength);
+		*currentData  += fragmentLength;
+
+		if (fragmentLength > host->maximumPacketSize || *currentData < host->receivedData || *currentData > &host->receivedData[host->receivedDataLength])
+			return -1;
+
+		channel = &peer->channels[command->header.channelID];
+		startSequenceNumber = ENET_NET_TO_HOST_16(command->sendFragment.startSequenceNumber);
+		startWindow         = startSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
+		currentWindow       = channel->incomingReliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
+
+		if (startSequenceNumber < channel->incomingReliableSequenceNumber)
+			startWindow += ENET_PEER_RELIABLE_WINDOWS;
+
+		if (startWindow < currentWindow || startWindow >= currentWindow + ENET_PEER_FREE_RELIABLE_WINDOWS - 1)
+			return 0;
+
+		fragmentNumber = ENET_NET_TO_HOST_32(command->sendFragment.fragmentNumber);
+		fragmentCount  = ENET_NET_TO_HOST_32(command->sendFragment.fragmentCount);
+		fragmentOffset = ENET_NET_TO_HOST_32(command->sendFragment.fragmentOffset);
+		totalLength    = ENET_NET_TO_HOST_32(command->sendFragment.totalLength);
+
+		if (fragmentCount > ENET_PROTOCOL_MAXIMUM_FRAGMENT_COUNT || fragmentNumber >= fragmentCount || totalLength > host->maximumPacketSize || fragmentOffset >= totalLength || fragmentLength > totalLength - fragmentOffset)
+			return -1;
+
+		for (currentCommand = enet_list_previous(enet_list_end(&channel->incomingReliableCommands)); currentCommand != enet_list_end(&channel->incomingReliableCommands); currentCommand = enet_list_previous(currentCommand)) {
+			ENetIncomingCommand* incomingCommand = (ENetIncomingCommand*)currentCommand;
+
+			if (startSequenceNumber >= channel->incomingReliableSequenceNumber) {
+				if (incomingCommand->reliableSequenceNumber < channel->incomingReliableSequenceNumber)
+					continue;
+			} else if (incomingCommand->reliableSequenceNumber >= channel->incomingReliableSequenceNumber) {
+				break;
+			}
+
+			if (incomingCommand->reliableSequenceNumber <= startSequenceNumber) {
+				if (incomingCommand->reliableSequenceNumber < startSequenceNumber)
+					break;
+
+				if ((incomingCommand->command.header.command & ENET_PROTOCOL_COMMAND_MASK) != ENET_PROTOCOL_COMMAND_SEND_FRAGMENT || totalLength != incomingCommand->packet->dataLength || fragmentCount != incomingCommand->fragmentCount)
+					return -1;
+
+				startCommand = incomingCommand;
+
+				break;
+			}
+		}
+
+		if (startCommand == NULL) {
+			ENetProtocol hostCommand = *command;
+			hostCommand.header.reliableSequenceNumber = startSequenceNumber;
+			startCommand = enet_peer_queue_incoming_command(peer, &hostCommand, NULL, totalLength, ENET_PACKET_FLAG_RELIABLE, fragmentCount);
+
+			if (startCommand == NULL)
+				return -1;
+		}
+
+		if ((startCommand->fragments[fragmentNumber / 32] & (1 << (fragmentNumber % 32))) == 0) {
+			--startCommand->fragmentsRemaining;
+			startCommand->fragments[fragmentNumber / 32] |= (1 << (fragmentNumber % 32));
+
+			if (fragmentOffset + fragmentLength > startCommand->packet->dataLength)
+				fragmentLength = startCommand->packet->dataLength - fragmentOffset;
+
+			memcpy(startCommand->packet->data + fragmentOffset, (enet_uint8*)command + sizeof(ENetProtocolSendFragment), fragmentLength);
+
+			if (startCommand->fragmentsRemaining <= 0)
+				enet_peer_dispatch_incoming_reliable_commands(peer, channel);
+		}
+
+		return 0;
+	}
+
+	static int enet_protocol_handle_send_unreliable_fragment(ENetHost* host, ENetPeer* peer, const ENetProtocol* command, enet_uint8** currentData) {
+		enet_uint32 fragmentNumber, fragmentCount, fragmentOffset, fragmentLength, reliableSequenceNumber, startSequenceNumber, totalLength;
+		enet_uint16 reliableWindow, currentWindow;
+		ENetChannel* channel;
+		ENetListIterator currentCommand;
+		ENetIncomingCommand* startCommand = NULL;
+
+		if (command->header.channelID >= peer->channelCount || (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER))
+			return -1;
+
+		fragmentLength = ENET_NET_TO_HOST_16(command->sendFragment.dataLength);
+		*currentData  += fragmentLength;
+
+		if (fragmentLength > host->maximumPacketSize || *currentData < host->receivedData || *currentData > &host->receivedData[host->receivedDataLength])
+			return -1;
+
+		channel = &peer->channels[command->header.channelID];
+		reliableSequenceNumber = command->header.reliableSequenceNumber;
+		startSequenceNumber    = ENET_NET_TO_HOST_16(command->sendFragment.startSequenceNumber);
+		reliableWindow = reliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
+		currentWindow  = channel->incomingReliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
+
+		if (reliableSequenceNumber < channel->incomingReliableSequenceNumber)
+			reliableWindow += ENET_PEER_RELIABLE_WINDOWS;
+
+		if (reliableWindow < currentWindow || reliableWindow >= currentWindow + ENET_PEER_FREE_RELIABLE_WINDOWS - 1)
+			return 0;
+
+		if (reliableSequenceNumber == channel->incomingReliableSequenceNumber && startSequenceNumber <= channel->incomingUnreliableSequenceNumber)
+			return 0;
+
+		fragmentNumber = ENET_NET_TO_HOST_32(command->sendFragment.fragmentNumber);
+		fragmentCount  = ENET_NET_TO_HOST_32(command->sendFragment.fragmentCount);
+		fragmentOffset = ENET_NET_TO_HOST_32(command->sendFragment.fragmentOffset);
+		totalLength    = ENET_NET_TO_HOST_32(command->sendFragment.totalLength);
+
+		if (fragmentCount > ENET_PROTOCOL_MAXIMUM_FRAGMENT_COUNT || fragmentNumber >= fragmentCount || totalLength > host->maximumPacketSize || fragmentOffset >= totalLength || fragmentLength > totalLength - fragmentOffset)
+			return -1;
+
+			for (currentCommand = enet_list_previous(enet_list_end(&channel->incomingUnreliableCommands)); currentCommand != enet_list_end(&channel->incomingUnreliableCommands); currentCommand = enet_list_previous(currentCommand)) {
+				ENetIncomingCommand* incomingCommand = (ENetIncomingCommand*)currentCommand;
+
+				if (reliableSequenceNumber >= channel->incomingReliableSequenceNumber) {
+					if (incomingCommand->reliableSequenceNumber < channel->incomingReliableSequenceNumber)
+						continue;
+				} else if (incomingCommand->reliableSequenceNumber >= channel->incomingReliableSequenceNumber) {
+					break;
+				}
+
+				if (incomingCommand->reliableSequenceNumber < reliableSequenceNumber)
+					break;
+
+				if (incomingCommand->reliableSequenceNumber > reliableSequenceNumber)
+					continue;
+
+				if (incomingCommand->unreliableSequenceNumber <= startSequenceNumber) {
+					if (incomingCommand->unreliableSequenceNumber < startSequenceNumber)
+						break;
+
+					if ((incomingCommand->command.header.command & ENET_PROTOCOL_COMMAND_MASK) != ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE_FRAGMENT || totalLength != incomingCommand->packet->dataLength || fragmentCount != incomingCommand->fragmentCount)
+						return -1;
+
+					startCommand = incomingCommand;
+
+					break;
+				}
+			}
+
+			if (startCommand == NULL) {
+				startCommand = enet_peer_queue_incoming_command(peer, command, NULL, totalLength,
+				ENET_PACKET_FLAG_UNRELIABLE_FRAGMENT, fragmentCount);
+
+				if (startCommand == NULL)
+					return -1;
+			}
+
+			if ((startCommand->fragments[fragmentNumber / 32] & (1 << (fragmentNumber % 32))) == 0) {
+				--startCommand->fragmentsRemaining;
+				startCommand->fragments[fragmentNumber / 32] |= (1 << (fragmentNumber % 32));
+
+				if (fragmentOffset + fragmentLength > startCommand->packet->dataLength)
+					fragmentLength = startCommand->packet->dataLength - fragmentOffset;
+
+				memcpy(startCommand->packet->data + fragmentOffset, (enet_uint8*)command + sizeof(ENetProtocolSendFragment), fragmentLength);
+
+				if (startCommand->fragmentsRemaining <= 0)
+					enet_peer_dispatch_incoming_unreliable_commands(peer, channel);
+			}
+
+			return 0;
+		}
+
+		static int enet_protocol_handle_ping(ENetHost* host, ENetPeer* peer, const ENetProtocol* command) {
+			if (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER)
+				return -1;
+
+			return 0;
+		}
+
+	static int enet_protocol_handle_bandwidth_limit(ENetHost* host, ENetPeer* peer, const ENetProtocol* command) {
+		if (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER)
+			return -1;
+
+		if (peer->incomingBandwidth != 0)
+			--host->bandwidthLimitedPeers;
+
+		peer->incomingBandwidth = ENET_NET_TO_HOST_32(command->bandwidthLimit.incomingBandwidth);
+		peer->outgoingBandwidth = ENET_NET_TO_HOST_32(command->bandwidthLimit.outgoingBandwidth);
+
+		if (peer->incomingBandwidth != 0)
+			++host->bandwidthLimitedPeers;
+
+		if (peer->incomingBandwidth == 0 && host->outgoingBandwidth == 0)
+			peer->windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
+		else if (peer->incomingBandwidth == 0 || host->outgoingBandwidth == 0)
+			peer->windowSize = (ENET_MAX(peer->incomingBandwidth, host->outgoingBandwidth) / ENET_PEER_WINDOW_SIZE_SCALE) * ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
+		else
+			peer->windowSize = (ENET_MIN(peer->incomingBandwidth, host->outgoingBandwidth) / ENET_PEER_WINDOW_SIZE_SCALE) * ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
+
+		if (peer->windowSize < ENET_PROTOCOL_MINIMUM_WINDOW_SIZE)
+			peer->windowSize = ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
+		else if (peer->windowSize > ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE)
+			peer->windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
+
+		return 0;
+	}
+
+	static int enet_protocol_handle_throttle_configure(ENetHost* host, ENetPeer* peer, const ENetProtocol* command) {
+		if (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER)
+			return -1;
+
+		peer->packetThrottleInterval     = ENET_NET_TO_HOST_32(command->throttleConfigure.packetThrottleInterval);
+		peer->packetThrottleAcceleration = ENET_NET_TO_HOST_32(command->throttleConfigure.packetThrottleAcceleration);
+		peer->packetThrottleDeceleration = ENET_NET_TO_HOST_32(command->throttleConfigure.packetThrottleDeceleration);
+
+		return 0;
+	}
+
+	static int enet_protocol_handle_disconnect(ENetHost* host, ENetPeer* peer, const ENetProtocol* command) {
+		if (peer->state == ENET_PEER_STATE_DISCONNECTED || peer->state == ENET_PEER_STATE_ZOMBIE || peer->state == ENET_PEER_STATE_ACKNOWLEDGING_DISCONNECT)
+			return 0;
+
+		enet_peer_reset_queues(peer);
+
+		if (peer->state == ENET_PEER_STATE_CONNECTION_SUCCEEDED || peer->state == ENET_PEER_STATE_DISCONNECTING || peer->state == ENET_PEER_STATE_CONNECTING) {
+			enet_protocol_dispatch_state(host, peer, ENET_PEER_STATE_ZOMBIE);
+		} else if (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER) {
+			if (peer->state == ENET_PEER_STATE_CONNECTION_PENDING)
+				host->recalculateBandwidthLimits = 1;
+
+			enet_peer_reset(peer);
+		} else if (command->header.command & ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE) {
+			enet_protocol_change_state(host, peer, ENET_PEER_STATE_ACKNOWLEDGING_DISCONNECT);
+		} else {
+			enet_protocol_dispatch_state(host, peer, ENET_PEER_STATE_ZOMBIE);
+		}
+
+		if (peer->state != ENET_PEER_STATE_DISCONNECTED)
+			peer->eventData = ENET_NET_TO_HOST_32(command->disconnect.data);
+
+		return 0;
+	}
+
+	static int enet_protocol_handle_acknowledge(ENetHost* host, ENetEvent* event, ENetPeer* peer, const ENetProtocol* command) {
+		enet_uint32 roundTripTime, receivedSentTime, receivedReliableSequenceNumber;
+		ENetProtocolCommand commandNumber;
+
+		if (peer->state == ENET_PEER_STATE_DISCONNECTED || peer->state == ENET_PEER_STATE_ZOMBIE)
+			return 0;
+
+		receivedSentTime  = ENET_NET_TO_HOST_16(command->acknowledge.receivedSentTime);
+		receivedSentTime |= host->serviceTime & 0xFFFF0000;
+
+		if ((receivedSentTime & 0x8000) > (host->serviceTime & 0x8000))
+			receivedSentTime -= 0x10000;
+
+		if (ENET_TIME_LESS(host->serviceTime, receivedSentTime))
+			return 0;
+
+		peer->lastReceiveTime = host->serviceTime;
+		peer->earliestTimeout = 0;
+		roundTripTime = ENET_TIME_DIFFERENCE(host->serviceTime, receivedSentTime);
+
+		if (roundTripTime == 0)
+			roundTripTime = 1;
+
+		if (peer->smoothedRoundTripTime == 0)
+			peer->smoothedRoundTripTime = (enet_uint32)((1 - ENET_SRTT_PARA_G) * ENET_SRTT_INITIAL + ENET_SRTT_PARA_G * roundTripTime);
+		else
+			peer->smoothedRoundTripTime = (enet_uint32)((1 - ENET_SRTT_PARA_G) * peer->smoothedRoundTripTime + ENET_SRTT_PARA_G * roundTripTime);
+
+		enet_peer_throttle(peer, peer->smoothedRoundTripTime);
+
+		peer->roundTripTimeVariance -= peer->roundTripTimeVariance / 4;
+
+		if (peer->smoothedRoundTripTime >= peer->roundTripTime) {
+			peer->roundTripTime         += (peer->smoothedRoundTripTime - peer->roundTripTime) / 8;
+			peer->roundTripTimeVariance += (peer->smoothedRoundTripTime - peer->roundTripTime) / 4;
+		} else {
+			peer->roundTripTime         -= (peer->roundTripTime - peer->smoothedRoundTripTime) / 8;
+			peer->roundTripTimeVariance += (peer->roundTripTime - peer->smoothedRoundTripTime) / 4;
+		}
+
+		if (peer->roundTripTime < peer->lowestRoundTripTime)
+			peer->lowestRoundTripTime = peer->roundTripTime;
+
+		if (peer->roundTripTimeVariance > peer->highestRoundTripTimeVariance)
+			peer->highestRoundTripTimeVariance = peer->roundTripTimeVariance;
+
+		if (peer->packetThrottleEpoch == 0 ||
+			ENET_TIME_DIFFERENCE(host->serviceTime, peer->packetThrottleEpoch) >= peer->packetThrottleInterval) {
+
+			peer->lastRoundTripTime            = peer->lowestRoundTripTime;
+			peer->lastRoundTripTimeVariance    = peer->highestRoundTripTimeVariance;
+			peer->lowestRoundTripTime          = peer->roundTripTime;
+			peer->highestRoundTripTimeVariance = peer->roundTripTimeVariance;
+			peer->packetThrottleEpoch          = host->serviceTime;
+		}
+
+		receivedReliableSequenceNumber = ENET_NET_TO_HOST_16(command->acknowledge.receivedReliableSequenceNumber);
+		commandNumber = enet_protocol_remove_sent_reliable_command(peer, receivedReliableSequenceNumber, command->header.channelID);
+
+		switch (peer->state) {
+			case ENET_PEER_STATE_ACKNOWLEDGING_CONNECT:
+				if (commandNumber != ENET_PROTOCOL_COMMAND_VERIFY_CONNECT)
+					return -1;
+
+				enet_protocol_notify_connect(host, peer, event);
+
+				break;
+
+			case ENET_PEER_STATE_DISCONNECTING:
+				if (commandNumber != ENET_PROTOCOL_COMMAND_DISCONNECT)
+					return -1;
+
+				enet_protocol_notify_disconnect(host, peer, event);
+
+				break;
+
+			case ENET_PEER_STATE_DISCONNECT_LATER:
+				if (enet_list_empty(&peer->outgoingReliableCommands) && enet_list_empty(&peer->outgoingUnreliableCommands) && enet_list_empty(&peer->sentReliableCommands))
+					enet_peer_disconnect(peer, peer->eventData);
+
+				break;
+
+			default:
+				break;
+		}
+
+		return 0;
+	}
+
+	static int enet_protocol_handle_verify_connect(ENetHost* host, ENetEvent* event, ENetPeer* peer, const ENetProtocol* command) {
+		enet_uint32 mtu, windowSize;
+		size_t channelCount;
+
+		if (peer->state != ENET_PEER_STATE_CONNECTING)
+			return 0;
+
+		channelCount = ENET_NET_TO_HOST_32(command->verifyConnect.channelCount);
+
+		if (channelCount < ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT || channelCount > ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT || ENET_NET_TO_HOST_32(command->verifyConnect.packetThrottleInterval) != peer->packetThrottleInterval || ENET_NET_TO_HOST_32(command->verifyConnect.packetThrottleAcceleration) != peer->packetThrottleAcceleration || ENET_NET_TO_HOST_32(command->verifyConnect.packetThrottleDeceleration) != peer->packetThrottleDeceleration || command->verifyConnect.connectID != peer->connectID) {
+			peer->eventData = 0;
+
+			enet_protocol_dispatch_state(host, peer, ENET_PEER_STATE_ZOMBIE);
+
+			return -1;
+		}
+
+		enet_protocol_remove_sent_reliable_command(peer, 1, 0xFF);
+
+		if (channelCount < peer->channelCount)
+			peer->channelCount = channelCount;
+
+		peer->outgoingPeerID    = ENET_NET_TO_HOST_16(command->verifyConnect.outgoingPeerID);
+		peer->incomingSessionID = command->verifyConnect.incomingSessionID;
+		peer->outgoingSessionID = command->verifyConnect.outgoingSessionID;
+		mtu = ENET_NET_TO_HOST_32(command->verifyConnect.mtu);
+
+		if (mtu < ENET_PROTOCOL_MINIMUM_MTU)
+			mtu = ENET_PROTOCOL_MINIMUM_MTU;
+		else if (mtu > ENET_PROTOCOL_MAXIMUM_MTU)
+			mtu = ENET_PROTOCOL_MAXIMUM_MTU;
+
+		if (mtu < peer->mtu)
+			peer->mtu = mtu;
+
+		windowSize = ENET_NET_TO_HOST_32(command->verifyConnect.windowSize);
+
+		if (windowSize < ENET_PROTOCOL_MINIMUM_WINDOW_SIZE)
+			windowSize = ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
+
+		if (windowSize > ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE)
+			windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
+
+		if (windowSize < peer->windowSize)
+			peer->windowSize = windowSize;
+
+		peer->incomingBandwidth = ENET_NET_TO_HOST_32(command->verifyConnect.incomingBandwidth);
+		peer->outgoingBandwidth = ENET_NET_TO_HOST_32(command->verifyConnect.outgoingBandwidth);
+
+		enet_protocol_notify_connect(host, peer, event);
+
+		return 0;
+	}
+
+	static int enet_protocol_handle_incoming_commands(ENetHost* host, ENetEvent* event) {
+		ENetProtocolHeader* header;
+		ENetProtocol* command;
+		ENetPeer* peer;
+		enet_uint8* currentData;
+		size_t headerSize;
+		enet_uint16 peerID, flags;
+		enet_uint8 sessionID;
+
+		if (host->receivedDataLength < (size_t)&((ENetProtocolHeader*)0)->sentTime)
+			return 0;
+
+		header     = (ENetProtocolHeader*)host->receivedData;
+		peerID     = ENET_NET_TO_HOST_16(header->peerID);
+		sessionID  = (peerID & ENET_PROTOCOL_HEADER_SESSION_MASK) >> ENET_PROTOCOL_HEADER_SESSION_SHIFT;
+		flags      = peerID & ENET_PROTOCOL_HEADER_FLAG_MASK;
+		peerID    &= ~(ENET_PROTOCOL_HEADER_FLAG_MASK | ENET_PROTOCOL_HEADER_SESSION_MASK);
+		headerSize = (flags & ENET_PROTOCOL_HEADER_FLAG_SENT_TIME ? sizeof(ENetProtocolHeader) : (size_t)&((ENetProtocolHeader*)0)->sentTime);
+
+		if (host->checksumCallback != NULL)
+			headerSize += sizeof(enet_uint32);
+
+		if (peerID == ENET_PROTOCOL_MAXIMUM_PEER_ID) {
+			peer = NULL;
+		} else if (peerID >= host->peerCount) {
+			return 0;
+		} else {
+			peer = &host->peers[peerID];
+
+			if (peer->state == ENET_PEER_STATE_DISCONNECTED || peer->state == ENET_PEER_STATE_ZOMBIE || ((!in6_equal(host->receivedAddress.host, peer->address.host) || host->receivedAddress.port != peer->address.port) && 1 /* No broadcast in IPv6 - !in6_equal(peer->address.host, ENET_HOST_BROADCAST) */) || (peer->outgoingPeerID < ENET_PROTOCOL_MAXIMUM_PEER_ID && sessionID != peer->incomingSessionID))
+				return 0;
+		}
+
+		#ifdef ENET_LZ4
+			if (flags & ENET_PROTOCOL_HEADER_FLAG_COMPRESSED) {
+				size_t originalSize = LZ4_decompress_safe((const char*)host->receivedData + headerSize, (char*)host->packetData[1] + headerSize, host->receivedDataLength - headerSize, sizeof(host->packetData[1]) - headerSize);
+
+				if (originalSize <= 0 || originalSize > sizeof(host->packetData[1]) - headerSize)
+					return 0;
+
+				memcpy(host->packetData[1], header, headerSize);
+
+				host->receivedData       = host->packetData[1];
+				host->receivedDataLength = headerSize + originalSize;
+			}
+		#endif
+
+		if (host->checksumCallback != NULL) {
+			enet_uint32* checksum = (enet_uint32*)&host->receivedData[headerSize - sizeof(enet_uint32)];
+			enet_uint32 desiredChecksum = *checksum;
+			ENetBuffer buffer;
+			*checksum = peer != NULL ? peer->connectID : 0;
+			buffer.data       = host->receivedData;
+			buffer.dataLength = host->receivedDataLength;
+
+			if (host->checksumCallback(&buffer, 1) != desiredChecksum)
+				return 0;
+		}
+
+		if (peer != NULL) {
+			peer->address.host       = host->receivedAddress.host;
+			peer->address.port       = host->receivedAddress.port;
+			peer->incomingDataTotal += host->receivedDataLength;
+			peer->totalDataReceived += host->receivedDataLength;
+		}
+
+		currentData = host->receivedData + headerSize;
+
+		while (currentData < &host->receivedData[host->receivedDataLength]) {
+			enet_uint8 commandNumber;
+			size_t commandSize;
+			command = (ENetProtocol*)currentData;
+
+			if (currentData + sizeof(ENetProtocolCommandHeader) > &host->receivedData[host->receivedDataLength])
+				break;
+
+			commandNumber = command->header.command & ENET_PROTOCOL_COMMAND_MASK;
+
+			if (commandNumber >= ENET_PROTOCOL_COMMAND_COUNT)
+				break;
+
+			commandSize = commandSizes[commandNumber];
+
+			if (commandSize == 0 || currentData + commandSize > &host->receivedData[host->receivedDataLength])
+				break;
+
+			currentData += commandSize;
+
+			if (peer == NULL && (commandNumber != ENET_PROTOCOL_COMMAND_CONNECT || currentData < &host->receivedData[host->receivedDataLength]))
+				break;
+
+			command->header.reliableSequenceNumber = ENET_NET_TO_HOST_16(command->header.reliableSequenceNumber);
+
+			switch (commandNumber) {
+				case ENET_PROTOCOL_COMMAND_ACKNOWLEDGE:
+					if (enet_protocol_handle_acknowledge(host, event, peer, command))
+						goto commandError;
+
+					break;
+
+				case ENET_PROTOCOL_COMMAND_CONNECT:
+					if (peer != NULL)
+						goto commandError;
+
+					if (host->preventConnections == 0) {
+						peer = enet_protocol_handle_connect(host, header, command);
+
+						if (peer == NULL)
+							goto commandError;
+					}
+
+					break;
+
+				case ENET_PROTOCOL_COMMAND_VERIFY_CONNECT:
+					if (enet_protocol_handle_verify_connect(host, event, peer, command))
+						goto commandError;
+
+					break;
+
+				case ENET_PROTOCOL_COMMAND_DISCONNECT:
+					if (enet_protocol_handle_disconnect(host, peer, command))
+						goto commandError;
+
+					break;
+
+				case ENET_PROTOCOL_COMMAND_PING:
+					if (enet_protocol_handle_ping(host, peer, command))
+						goto commandError;
+
+					break;
+
+				case ENET_PROTOCOL_COMMAND_SEND_RELIABLE:
+					if (enet_protocol_handle_send_reliable(host, peer, command, &currentData))
+						goto commandError;
+
+					break;
+
+				case ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE:
+					if (enet_protocol_handle_send_unreliable(host, peer, command, &currentData))
+						goto commandError;
+
+					break;
+
+				case ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED:
+					if (enet_protocol_handle_send_unsequenced(host, peer, command, &currentData))
+						goto commandError;
+
+					break;
+
+				case ENET_PROTOCOL_COMMAND_SEND_FRAGMENT:
+					if (enet_protocol_handle_send_fragment(host, peer, command, &currentData))
+						goto commandError;
+
+					break;
+
+				case ENET_PROTOCOL_COMMAND_BANDWIDTH_LIMIT:
+					if (enet_protocol_handle_bandwidth_limit(host, peer, command))
+						goto commandError;
+
+					break;
+
+				case ENET_PROTOCOL_COMMAND_THROTTLE_CONFIGURE:
+					if (enet_protocol_handle_throttle_configure(host, peer, command))
+						goto commandError;
+
+					break;
+
+				case ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE_FRAGMENT:
+					if (enet_protocol_handle_send_unreliable_fragment(host, peer, command, &currentData))
+						goto commandError;
+
+					break;
+
+				default:
+					goto commandError;
+			}
+
+			if (peer != NULL && (command->header.command & ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE) != 0) {
+				enet_uint16 sentTime;
+
+				if (!(flags & ENET_PROTOCOL_HEADER_FLAG_SENT_TIME))
+					break;
+
+				sentTime = ENET_NET_TO_HOST_16(header->sentTime);
+
+				switch (peer->state) {
+					case ENET_PEER_STATE_DISCONNECTING:
+					case ENET_PEER_STATE_ACKNOWLEDGING_CONNECT:
+					case ENET_PEER_STATE_DISCONNECTED:
+					case ENET_PEER_STATE_ZOMBIE:
+						break;
+
+					case ENET_PEER_STATE_ACKNOWLEDGING_DISCONNECT:
+						if ((command->header.command & ENET_PROTOCOL_COMMAND_MASK) == ENET_PROTOCOL_COMMAND_DISCONNECT)
+							enet_peer_queue_acknowledgement(peer, command, sentTime);
+
+						break;
+
+					default:
+						enet_peer_queue_acknowledgement(peer, command, sentTime);
+
+						break;
+				}
+			}
+		}
+
+		commandError:
+
+		if (event != NULL && event->type != ENET_EVENT_TYPE_NONE)
+			return 1;
+
+		return 0;
+	}
+
+	static int enet_protocol_receive_incoming_commands(ENetHost* host, ENetEvent* event) {
+		int packets;
+
+		for (packets = 0; packets < 256; ++packets) {
+			int receivedLength;
+			ENetBuffer buffer;
+			buffer.data       = host->packetData[0];
+			buffer.dataLength = host->mtu;
+			receivedLength    = enet_socket_receive(host->socket, &host->receivedAddress, &buffer, 1);
+
+			if (receivedLength == -2)
+				continue;
+
+			if (receivedLength < 0)
+				return -1;
+
+			if (receivedLength == 0)
+				return 0;
+
+			host->receivedData       = host->packetData[0];
+			host->receivedDataLength = receivedLength;
+			host->totalReceivedData += receivedLength;
+			host->totalReceivedPackets++;
+
+			if (host->interceptCallback != NULL) {
+				switch (host->interceptCallback(host, (void*)event)) {
+					case 1:
+						if (event != NULL && event->type != ENET_EVENT_TYPE_NONE)
+							return 1;
+
+						continue;
+
+					case -1:
+						return -1;
+
+					default:
+						break;
+				}
+			}
+
+			switch (enet_protocol_handle_incoming_commands(host, event)) {
+				case 1:
+					return 1;
+
+				case -1:
+					return -1;
+
+				default:
+					break;
+			}
+		}
+
+		return -1;
+	}
+
+	static void enet_protocol_send_acknowledgements(ENetHost* host, ENetPeer* peer) {
+		ENetProtocol* command = &host->commands[host->commandCount];
+		ENetBuffer* buffer    = &host->buffers[host->bufferCount];
+		ENetAcknowledgement* acknowledgement;
+		ENetListIterator currentAcknowledgement;
+		enet_uint16 reliableSequenceNumber;
+		currentAcknowledgement = enet_list_begin(&peer->acknowledgements);
+
+		while (currentAcknowledgement != enet_list_end(&peer->acknowledgements)) {
+			if (command >= &host->commands[sizeof(host->commands) / sizeof(ENetProtocol)] || buffer >= &host->buffers[sizeof(host->buffers) / sizeof(ENetBuffer)] || peer->mtu - host->packetSize < sizeof(ENetProtocolAcknowledge)) {
+				host->continueSending = 1;
+
+				break;
+			}
+
+			acknowledgement = (ENetAcknowledgement*)currentAcknowledgement;
+			currentAcknowledgement = enet_list_next(currentAcknowledgement);
+			buffer->data       = command;
+			buffer->dataLength = sizeof(ENetProtocolAcknowledge);
+			host->packetSize  += buffer->dataLength;
+			reliableSequenceNumber = ENET_HOST_TO_NET_16(acknowledgement->command.header.reliableSequenceNumber);
+			command->header.command   = ENET_PROTOCOL_COMMAND_ACKNOWLEDGE;
+			command->header.channelID = acknowledgement->command.header.channelID;
+			command->header.reliableSequenceNumber = reliableSequenceNumber;
+			command->acknowledge.receivedReliableSequenceNumber = reliableSequenceNumber;
+			command->acknowledge.receivedSentTime = ENET_HOST_TO_NET_16(acknowledgement->sentTime);
+
+			if ((acknowledgement->command.header.command & ENET_PROTOCOL_COMMAND_MASK) == ENET_PROTOCOL_COMMAND_DISCONNECT)
+				enet_protocol_dispatch_state(host, peer, ENET_PEER_STATE_ZOMBIE);
+
+			enet_list_remove(&acknowledgement->acknowledgementList);
+			enet_free(acknowledgement);
+
+			++command;
+			++buffer;
+		}
+
+		host->commandCount = command - host->commands;
+		host->bufferCount  = buffer - host->buffers;
+	}
+
+	static void enet_protocol_send_unreliable_outgoing_commands(ENetHost* host, ENetPeer* peer) {
+		ENetProtocol* command = &host->commands[host->commandCount];
+		ENetBuffer* buffer    = &host->buffers[host->bufferCount];
+		ENetOutgoingCommand* outgoingCommand;
+		ENetListIterator currentCommand;
+		currentCommand = enet_list_begin(&peer->outgoingUnreliableCommands);
+
+		while (currentCommand != enet_list_end(&peer->outgoingUnreliableCommands)) {
+			size_t commandSize;
+			outgoingCommand = (ENetOutgoingCommand*)currentCommand;
+			commandSize     = commandSizes[outgoingCommand->command.header.command & ENET_PROTOCOL_COMMAND_MASK];
+
+			if (command >= &host->commands[sizeof(host->commands) / sizeof(ENetProtocol)] || buffer + 1 >= &host->buffers[sizeof(host->buffers) / sizeof(ENetBuffer)] || peer->mtu - host->packetSize < commandSize || (outgoingCommand->packet != NULL && peer->mtu - host->packetSize < commandSize + outgoingCommand->fragmentLength)) {
+				host->continueSending = 1;
+
+				break;
+			}
+
+			currentCommand = enet_list_next(currentCommand);
+
+			if (outgoingCommand->packet != NULL && outgoingCommand->fragmentOffset == 0) {
+				peer->packetThrottleCounter += ENET_PEER_PACKET_THROTTLE_COUNTER;
+				peer->packetThrottleCounter %= ENET_PEER_PACKET_THROTTLE_SCALE;
+
+				if (peer->packetThrottleCounter > peer->packetThrottle) {
+					enet_uint16 reliableSequenceNumber = outgoingCommand->reliableSequenceNumber;
+					enet_uint16 unreliableSequenceNumber = outgoingCommand->unreliableSequenceNumber;
+
+					for (;;) {
+						--outgoingCommand->packet->referenceCount;
+
+						if (outgoingCommand->packet->referenceCount == 0)
+							enet_packet_destroy(outgoingCommand->packet);
+
+						enet_list_remove(&outgoingCommand->outgoingCommandList);
+						enet_free(outgoingCommand);
+
+						if (currentCommand == enet_list_end(&peer->outgoingUnreliableCommands))
+							break;
+
+						outgoingCommand = (ENetOutgoingCommand*)currentCommand;
+
+						if (outgoingCommand->reliableSequenceNumber != reliableSequenceNumber || outgoingCommand->unreliableSequenceNumber != unreliableSequenceNumber)
+							break;
+
+						currentCommand = enet_list_next(currentCommand);
+					}
+
+					continue;
+				}
+			}
+
+			buffer->data       = command;
+			buffer->dataLength = commandSize;
+			host->packetSize  += buffer->dataLength;
+			*command = outgoingCommand->command;
+
+			enet_list_remove(&outgoingCommand->outgoingCommandList);
+
+			if (outgoingCommand->packet != NULL) {
+				++buffer;
+
+				buffer->data       = outgoingCommand->packet->data + outgoingCommand->fragmentOffset;
+				buffer->dataLength = outgoingCommand->fragmentLength;
+				host->packetSize += buffer->dataLength;
+
+				enet_list_insert(enet_list_end(&peer->sentUnreliableCommands), outgoingCommand);
+			} else {
+				enet_free(outgoingCommand);
+			}
+			
+			++command;
+			++buffer;
+		}
+
+		host->commandCount = command - host->commands;
+		host->bufferCount  = buffer - host->buffers;
+
+		if (peer->state == ENET_PEER_STATE_DISCONNECT_LATER && enet_list_empty(&peer->outgoingReliableCommands) && enet_list_empty(&peer->outgoingUnreliableCommands) && enet_list_empty(&peer->sentReliableCommands) && enet_list_empty(&peer->sentUnreliableCommands))
+			enet_peer_disconnect(peer, peer->eventData);
+	}
+
+	static int enet_protocol_check_timeouts(ENetHost* host, ENetPeer* peer, ENetEvent* event) {
+		ENetOutgoingCommand* outgoingCommand;
+		ENetListIterator currentCommand, insertPosition;
+		currentCommand = enet_list_begin(&peer->sentReliableCommands);
+		insertPosition = enet_list_begin(&peer->outgoingReliableCommands);
+
+		while (currentCommand != enet_list_end(&peer->sentReliableCommands)) {
+			outgoingCommand = (ENetOutgoingCommand*)currentCommand;
+			currentCommand = enet_list_next(currentCommand);
+
+			if (ENET_TIME_DIFFERENCE(host->serviceTime, outgoingCommand->sentTime) < outgoingCommand->roundTripTimeout)
+				continue;
+
+			if (peer->earliestTimeout == 0 || ENET_TIME_LESS(outgoingCommand->sentTime, peer->earliestTimeout))
+				peer->earliestTimeout = outgoingCommand->sentTime;
+
+			if (peer->earliestTimeout != 0 && (ENET_TIME_DIFFERENCE(host->serviceTime, peer->earliestTimeout) >= peer->timeoutMaximum || (outgoingCommand->roundTripTimeout >= outgoingCommand->roundTripTimeoutLimit && ENET_TIME_DIFFERENCE(host->serviceTime, peer->earliestTimeout) >= peer->timeoutMinimum))) {
+				enet_protocol_notify_disconnect_timeout(host, peer, event);
+
+				return 1;
+			}
+
+			if (outgoingCommand->packet != NULL)
+				peer->reliableDataInTransit -= outgoingCommand->fragmentLength;
+
+			++peer->packetsLost;
+			++peer->totalPacketsLost;
+			outgoingCommand->roundTripTimeout = peer->roundTripTime + 4 * peer->roundTripTimeVariance;
+			outgoingCommand->roundTripTimeoutLimit = peer->timeoutLimit * outgoingCommand->roundTripTimeout;
+
+			enet_list_insert(insertPosition, enet_list_remove(&outgoingCommand->outgoingCommandList));
+
+			if (currentCommand == enet_list_begin(&peer->sentReliableCommands) && !enet_list_empty(&peer->sentReliableCommands)) {
+				outgoingCommand = (ENetOutgoingCommand*)currentCommand;
+				peer->nextTimeout = outgoingCommand->sentTime + outgoingCommand->roundTripTimeout;
+			}
+		}
+
+		return 0;
+	}
+
+	static int enet_protocol_send_reliable_outgoing_commands(ENetHost* host, ENetPeer* peer) {
+		ENetProtocol* command = &host->commands[host->commandCount];
+		ENetBuffer* buffer    = &host->buffers[host->bufferCount];
+		ENetOutgoingCommand* outgoingCommand;
+		ENetListIterator currentCommand;
+		ENetChannel* channel;
+		enet_uint16 reliableWindow;
+		size_t commandSize;
+		int windowExceeded = 0, windowWrap = 0, canPing = 1;
+		currentCommand = enet_list_begin(&peer->outgoingReliableCommands);
+
+		while (currentCommand != enet_list_end(&peer->outgoingReliableCommands)) {
+			outgoingCommand = (ENetOutgoingCommand*)currentCommand;
+			channel = outgoingCommand->command.header.channelID < peer->channelCount ? &peer->channels[outgoingCommand->command.header.channelID] : NULL;
+			reliableWindow = outgoingCommand->reliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
+
+			if (channel != NULL) {
+				if (!windowWrap && outgoingCommand->sendAttempts < 1 && !(outgoingCommand->reliableSequenceNumber % ENET_PEER_RELIABLE_WINDOW_SIZE) && (channel->reliableWindows[(reliableWindow + ENET_PEER_RELIABLE_WINDOWS - 1) % ENET_PEER_RELIABLE_WINDOWS] >= ENET_PEER_RELIABLE_WINDOW_SIZE || channel->usedReliableWindows & ((((1 << ENET_PEER_FREE_RELIABLE_WINDOWS) - 1) << reliableWindow) | (((1 << ENET_PEER_FREE_RELIABLE_WINDOWS) - 1) >> (ENET_PEER_RELIABLE_WINDOWS - reliableWindow)))))
+					windowWrap = 1;
+
+				if (windowWrap) {
+					currentCommand = enet_list_next(currentCommand);
+
+					continue;
+				}
+			}
+
+			if (outgoingCommand->packet != NULL) {
+				if (!windowExceeded) {
+					enet_uint32 windowSize = (peer->packetThrottle * peer->windowSize) / ENET_PEER_PACKET_THROTTLE_SCALE;
+
+					if (peer->reliableDataInTransit + outgoingCommand->fragmentLength > ENET_MAX(windowSize, peer->mtu))
+						windowExceeded = 1;
+				}
+
+				if (windowExceeded) {
+					currentCommand = enet_list_next(currentCommand);
+
+					continue;
+				}
+			}
+
+			canPing = 0;
+			commandSize = commandSizes[outgoingCommand->command.header.command & ENET_PROTOCOL_COMMAND_MASK];
+
+			if (command >= &host->commands[sizeof(host->commands) / sizeof(ENetProtocol)] || buffer + 1 >= &host->buffers[sizeof(host->buffers) / sizeof(ENetBuffer)] || peer->mtu - host->packetSize < commandSize || (outgoingCommand->packet != NULL && (enet_uint16)(peer->mtu - host->packetSize) < (enet_uint16)(commandSize + outgoingCommand->fragmentLength))) {
+				host->continueSending = 1;
+
+				break;
+			}
+
+			currentCommand = enet_list_next(currentCommand);
+
+			if (channel != NULL && outgoingCommand->sendAttempts < 1) {
+				channel->usedReliableWindows |= 1 << reliableWindow;
+				++channel->reliableWindows[reliableWindow];
+			}
+
+			++outgoingCommand->sendAttempts;
+
+			if (outgoingCommand->roundTripTimeout == 0) {
+				outgoingCommand->roundTripTimeout      = peer->roundTripTime + 4 * peer->roundTripTimeVariance;
+				outgoingCommand->roundTripTimeoutLimit = peer->timeoutLimit * outgoingCommand->roundTripTimeout;
+			}
+
+			if (enet_list_empty(&peer->sentReliableCommands))
+				peer->nextTimeout = host->serviceTime + outgoingCommand->roundTripTimeout;
+
+			enet_list_insert(enet_list_end(&peer->sentReliableCommands), enet_list_remove(&outgoingCommand->outgoingCommandList));
+
+			outgoingCommand->sentTime = host->serviceTime;
+			buffer->data       = command;
+			buffer->dataLength = commandSize;
+			host->packetSize  += buffer->dataLength;
+			host->headerFlags |= ENET_PROTOCOL_HEADER_FLAG_SENT_TIME;
+			*command = outgoingCommand->command;
+
+			if (outgoingCommand->packet != NULL) {
+				++buffer;
+				buffer->data       = outgoingCommand->packet->data + outgoingCommand->fragmentOffset;
+				buffer->dataLength = outgoingCommand->fragmentLength;
+				host->packetSize  += outgoingCommand->fragmentLength;
+				peer->reliableDataInTransit += outgoingCommand->fragmentLength;
+			}
+
+			++peer->packetsSent;
+			++peer->totalPacketsSent;
+			++command;
+			++buffer;
+		}
+
+		host->commandCount = command - host->commands;
+		host->bufferCount  = buffer - host->buffers;
+
+		return canPing;
+	}
+
+	static int enet_protocol_send_outgoing_commands(ENetHost* host, ENetEvent* event, int checkForTimeouts) {
+		enet_uint8 headerData[sizeof(ENetProtocolHeader) + sizeof(enet_uint32)];
+		ENetProtocolHeader* header = (ENetProtocolHeader*)headerData;
+		ENetPeer* currentPeer;
+		int sentLength;
+		host->continueSending = 1;
+
+		#ifdef ENET_LZ4
+			size_t shouldCompress = 0;
+		#endif
+
+		while (host->continueSending)
+			for (host->continueSending = 0, currentPeer = host->peers; currentPeer < &host->peers[host->peerCount]; ++currentPeer) {
+				if (currentPeer->state == ENET_PEER_STATE_DISCONNECTED || currentPeer->state == ENET_PEER_STATE_ZOMBIE)
+					continue;
+
+				host->headerFlags  = 0;
+				host->commandCount = 0;
+				host->bufferCount  = 1;
+				host->packetSize   = sizeof(ENetProtocolHeader);
+
+				if (!enet_list_empty(&currentPeer->acknowledgements))
+					enet_protocol_send_acknowledgements(host, currentPeer);
+
+				if (checkForTimeouts != 0 && !enet_list_empty(&currentPeer->sentReliableCommands) && ENET_TIME_GREATER_EQUAL(host->serviceTime, currentPeer->nextTimeout) && enet_protocol_check_timeouts(host, currentPeer, event) == 1) {
+					if (event != NULL && event->type != ENET_EVENT_TYPE_NONE)
+						return 1;
+					else
+						continue;
+				}
+
+				if ((enet_list_empty(&currentPeer->outgoingReliableCommands) || enet_protocol_send_reliable_outgoing_commands(host, currentPeer)) && enet_list_empty(&currentPeer->sentReliableCommands) && ENET_TIME_DIFFERENCE(host->serviceTime, currentPeer->lastReceiveTime) >= currentPeer->pingInterval && currentPeer->mtu - host->packetSize >= sizeof(ENetProtocolPing)) {
+					enet_peer_ping(currentPeer);
+					enet_protocol_send_reliable_outgoing_commands(host, currentPeer);
+				}
+
+				if (!enet_list_empty(&currentPeer->outgoingUnreliableCommands))
+					enet_protocol_send_unreliable_outgoing_commands(host, currentPeer);
+
+				if (host->commandCount == 0)
+					continue;
+
+				if (currentPeer->packetLossEpoch == 0) {
+					currentPeer->packetLossEpoch = host->serviceTime;
+				} else if (ENET_TIME_DIFFERENCE(host->serviceTime, currentPeer->packetLossEpoch) >= ENET_PEER_PACKET_LOSS_INTERVAL && currentPeer->packetsSent > 0) {
+					enet_uint32 packetLoss = currentPeer->packetsLost * ENET_PEER_PACKET_LOSS_SCALE / currentPeer->packetsSent;
+
+					#ifdef ENET_DEBUG
+						printf(
+							"peer %u: %f%%+-%f%% packet loss, %u+-%u ms round trip time, %f%% throttle, %u/%u outgoing, %u/%u incoming\n", currentPeer->incomingPeerID,
+							currentPeer->packetLoss / (float)ENET_PEER_PACKET_LOSS_SCALE,
+							currentPeer->packetLossVariance / (float)ENET_PEER_PACKET_LOSS_SCALE, currentPeer->roundTripTime, currentPeer->roundTripTimeVariance,
+							currentPeer->packetThrottle / (float)ENET_PEER_PACKET_THROTTLE_SCALE,
+
+							enet_list_size(&currentPeer->outgoingReliableCommands),
+							enet_list_size(&currentPeer->outgoingUnreliableCommands),
+
+							currentPeer->channels != NULL ? enet_list_size(&currentPeer->channels->incomingReliableCommands) : 0,
+							currentPeer->channels != NULL ? enet_list_size(&currentPeer->channels->incomingUnreliableCommands) : 0
+						);
+					#endif
+
+					currentPeer->packetLossVariance -= currentPeer->packetLossVariance / 4;
+
+					if (packetLoss >= currentPeer->packetLoss) {
+						currentPeer->packetLoss         += (packetLoss - currentPeer->packetLoss) / 8;
+						currentPeer->packetLossVariance += (packetLoss - currentPeer->packetLoss) / 4;
+					} else {
+						currentPeer->packetLoss         -= (currentPeer->packetLoss - packetLoss) / 8;
+						currentPeer->packetLossVariance += (currentPeer->packetLoss - packetLoss) / 4;
+					}
+
+					currentPeer->packetLossEpoch = host->serviceTime;
+					currentPeer->packetsSent     = 0;
+					currentPeer->packetsLost     = 0;
+				}
+
+				host->buffers->data = headerData;
+
+				if (host->headerFlags & ENET_PROTOCOL_HEADER_FLAG_SENT_TIME) {
+					header->sentTime = ENET_HOST_TO_NET_16(host->serviceTime & 0xFFFF);
+					host->buffers->dataLength = sizeof(ENetProtocolHeader);
+				} else {
+					host->buffers->dataLength = (size_t)&((ENetProtocolHeader*)0)->sentTime;
+				}
+
+				#ifdef ENET_LZ4
+					if (host->compression == 1 && host->packetSize > 64) {
+						size_t originalSize = host->packetSize - sizeof(ENetProtocolHeader), compressedSize = 0;
+						const ENetBuffer* buffers = &host->buffers[1];
+
+						if (host->compressionBufferSize < originalSize) {
+							enet_free(host->compressionBuffer);
+
+							host->compressionBuffer = (char*)enet_malloc(originalSize);
+							host->compressionBufferSize = originalSize;
+						}
+
+						int totalSize = originalSize, dataSize = 0;
+
+						while (totalSize) {
+							for (int i = 0; i < host->bufferCount - 1; i++) {
+								int copySize = ENET_MIN(totalSize, (int)buffers[i].dataLength);
+
+								memcpy(host->compressionBuffer + dataSize, buffers[i].data, copySize);
+
+								totalSize -= copySize;
+								dataSize  += copySize;
+							}
+						}
+
+						compressedSize = LZ4_compress_default((const char*)host->compressionBuffer, (char*)host->packetData[1], dataSize, originalSize);
+
+						if (compressedSize > 0 && compressedSize < originalSize) {
+							host->headerFlags |= ENET_PROTOCOL_HEADER_FLAG_COMPRESSED;
+							shouldCompress     = compressedSize;
+
+							#ifdef ENET_DEBUG_COMPRESS
+								printf("peer %u: compressed %u->%u (%u%%)\n", currentPeer->incomingPeerID, originalSize, compressedSize, (compressedSize * 100) / originalSize);
+							#endif
+						}
+					}
+				#endif
+
+				if (currentPeer->outgoingPeerID < ENET_PROTOCOL_MAXIMUM_PEER_ID)
+					host->headerFlags |= currentPeer->outgoingSessionID << ENET_PROTOCOL_HEADER_SESSION_SHIFT;
+
+				header->peerID = ENET_HOST_TO_NET_16(currentPeer->outgoingPeerID | host->headerFlags);
+
+				if (host->checksumCallback != NULL) {
+					enet_uint32* checksum = (enet_uint32*)&headerData[host->buffers->dataLength];
+					*checksum = currentPeer->outgoingPeerID < ENET_PROTOCOL_MAXIMUM_PEER_ID ? currentPeer->connectID : 0;
+					host->buffers->dataLength += sizeof(enet_uint32);
+					*checksum = host->checksumCallback(host->buffers, host->bufferCount);
+				}
+
+				#ifdef ENET_LZ4
+					if (shouldCompress > 0) {
+						host->buffers[1].data       = host->packetData[1];
+						host->buffers[1].dataLength = shouldCompress;
+						host->bufferCount           = 2;
+					}
+				#endif
+
+				currentPeer->lastSendTime = host->serviceTime;
+				sentLength = enet_socket_send(host->socket, &currentPeer->address, host->buffers, host->bufferCount);
+
+				enet_protocol_remove_sent_unreliable_commands(currentPeer);
+
+				if (sentLength < 0)
+					return -1;
+
+				host->totalSentData += sentLength;
+				currentPeer->totalDataSent += sentLength;
+				host->totalSentPackets++;
+			}
+
+		return 0;
+	}
+
+	void enet_host_flush(ENetHost* host) {
+		host->serviceTime = enet_time_get();
+
+		enet_protocol_send_outgoing_commands(host, NULL, 0);
+	}
+
+	int enet_host_check_events(ENetHost* host, ENetEvent* event) {
+		if (event == NULL)
+			return -1;
+
+		event->type   = ENET_EVENT_TYPE_NONE;
+		event->peer   = NULL;
+		event->packet = NULL;
+
+		return enet_protocol_dispatch_incoming_commands(host, event);
+	}
+
+	int enet_host_service(ENetHost* host, ENetEvent* event, enet_uint32 timeout) {
+		enet_uint32 waitCondition;
+
+		if (event != NULL) {
+			event->type   = ENET_EVENT_TYPE_NONE;
+			event->peer   = NULL;
+			event->packet = NULL;
+
+			switch (enet_protocol_dispatch_incoming_commands(host, event)) {
+				case 1:
+					return 1;
+
+				case -1:
+					#ifdef ENET_DEBUG
+						perror("Error dispatching incoming packets");
+					#endif
+
+					return -1;
+
+				default:
+					break;
+			}
+		}
+
+		host->serviceTime = enet_time_get();
+		timeout += host->serviceTime;
+
+		do {
+			if (ENET_TIME_DIFFERENCE(host->serviceTime, host->bandwidthThrottleEpoch) >= ENET_HOST_BANDWIDTH_THROTTLE_INTERVAL)
+				enet_host_bandwidth_throttle(host);
+
+			switch (enet_protocol_send_outgoing_commands(host, event, 1)) {
+				case 1:
+					return 1;
+
+				case -1:
+					#ifdef ENET_DEBUG
+						perror("Error sending outgoing packets");
+					#endif
+
+					return -1;
+
+				default:
+					break;
+			}
+
+			switch (enet_protocol_receive_incoming_commands(host, event)) {
+				case 1:
+					return 1;
+
+				case -1:
+					#ifdef ENET_DEBUG
+						perror("Error receiving incoming packets");
+					#endif
+
+					return -1;
+
+				default:
+					break;
+			}
+
+			switch (enet_protocol_send_outgoing_commands(host, event, 1)) {
+				case 1:
+					return 1;
+
+				case -1:
+					#ifdef ENET_DEBUG
+						perror("Error sending outgoing packets");
+					#endif
+
+					return -1;
+
+				default:
+					break;
+			}
+
+			if (event != NULL) {
+				switch (enet_protocol_dispatch_incoming_commands(host, event)) {
+					case 1:
+						return 1;
+
+					case -1:
+						#ifdef ENET_DEBUG
+							perror("Error dispatching incoming packets");
+						#endif
+
+						return -1;
+
+					default:
+						break;
+				}
+			}
+
+			if (ENET_TIME_GREATER_EQUAL(host->serviceTime, timeout))
+				return 0;
+
+			do {
+				host->serviceTime = enet_time_get();
+
+				if (ENET_TIME_GREATER_EQUAL(host->serviceTime, timeout))
+					return 0;
+
+				waitCondition = ENET_SOCKET_WAIT_RECEIVE | ENET_SOCKET_WAIT_INTERRUPT;
+
+				if (enet_socket_wait(host->socket, &waitCondition, ENET_TIME_DIFFERENCE(timeout, host->serviceTime)) != 0)
+					return -1;
+			}
+
+			while (waitCondition & ENET_SOCKET_WAIT_INTERRUPT);
+
+			host->serviceTime = enet_time_get();
+		}
+
+		while (waitCondition & ENET_SOCKET_WAIT_RECEIVE);
+
+		return 0;
+	}
+
+// =======================================================================//
+// !
+// ! Peer
+// !
+// =======================================================================//
+
+	void enet_peer_throttle_configure(ENetPeer* peer, enet_uint32 interval, enet_uint32 acceleration, enet_uint32 deceleration) {
+		ENetProtocol command;
+		peer->packetThrottleInterval     = interval;
+		peer->packetThrottleAcceleration = acceleration;
+		peer->packetThrottleDeceleration = deceleration;
+		command.header.command   = ENET_PROTOCOL_COMMAND_THROTTLE_CONFIGURE | ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE;
+		command.header.channelID = 0xFF;
+		command.throttleConfigure.packetThrottleInterval     = ENET_HOST_TO_NET_32(interval);
+		command.throttleConfigure.packetThrottleAcceleration = ENET_HOST_TO_NET_32(acceleration);
+		command.throttleConfigure.packetThrottleDeceleration = ENET_HOST_TO_NET_32(deceleration);
+
+		enet_peer_queue_outgoing_command(peer, &command, NULL, 0, 0);
+	}
+
+	int enet_peer_throttle(ENetPeer* peer, enet_uint32 rtt) {
+		if (peer->lastRoundTripTime <= peer->lastRoundTripTimeVariance) {
+			peer->packetThrottle = peer->packetThrottleLimit;
+		} else if (rtt < peer->lastRoundTripTime) {
+			peer->packetThrottle += peer->packetThrottleAcceleration;
+
+			if (peer->packetThrottle > peer->packetThrottleLimit)
+				peer->packetThrottle = peer->packetThrottleLimit;
+
+			return 1;
+		} else if (rtt > peer->lastRoundTripTime + 2 * peer->lastRoundTripTimeVariance) {
+			if (peer->packetThrottle > peer->packetThrottleDeceleration)
+				peer->packetThrottle -= peer->packetThrottleDeceleration;
+			else
+				peer->packetThrottle = 0;
+
+			return -1;
+		}
+
+		return 0;
+	}
+
+	int enet_peer_send(ENetPeer* peer, enet_uint8 channelID, ENetPacket* packet) {
+		ENetChannel* channel = &peer->channels[channelID];
+		ENetProtocol command;
+		size_t fragmentLength;
+
+		if (peer->state != ENET_PEER_STATE_CONNECTED || channelID >= peer->channelCount || packet->dataLength > peer->host->maximumPacketSize)
+			return -1;
+
+		fragmentLength = peer->mtu - sizeof(ENetProtocolHeader) - sizeof(ENetProtocolSendFragment);
+
+		if (peer->host->checksumCallback != NULL)
+			fragmentLength -= sizeof(enet_uint32);
+
+		if (packet->dataLength > fragmentLength) {
+			enet_uint32 fragmentCount = (packet->dataLength + fragmentLength - 1) / fragmentLength, fragmentNumber, fragmentOffset;
+			enet_uint8 commandNumber;
+			enet_uint16 startSequenceNumber;
+			ENetList fragments;
+			ENetOutgoingCommand* fragment;
+
+			if (fragmentCount > ENET_PROTOCOL_MAXIMUM_FRAGMENT_COUNT)
+				return -1;
+
+			if ((packet->flags & (ENET_PACKET_FLAG_RELIABLE | ENET_PACKET_FLAG_UNRELIABLE_FRAGMENT)) == ENET_PACKET_FLAG_UNRELIABLE_FRAGMENT && channel->outgoingUnreliableSequenceNumber < 0xFFFF) {
+				commandNumber       = ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE_FRAGMENT;
+				startSequenceNumber = ENET_HOST_TO_NET_16(channel->outgoingUnreliableSequenceNumber + 1);
+			} else {
+				commandNumber       = ENET_PROTOCOL_COMMAND_SEND_FRAGMENT | ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE;
+				startSequenceNumber = ENET_HOST_TO_NET_16(channel->outgoingReliableSequenceNumber + 1);
+			}
+
+			enet_list_clear(&fragments);
+
+			for (fragmentNumber = 0, fragmentOffset = 0; fragmentOffset < packet->dataLength; ++fragmentNumber, fragmentOffset += fragmentLength) {
+				if (packet->dataLength - fragmentOffset < fragmentLength)
+					fragmentLength = packet->dataLength - fragmentOffset;
+
+				fragment = (ENetOutgoingCommand*)enet_malloc(sizeof(ENetOutgoingCommand));
+
+				if (fragment == NULL) {
+					while (!enet_list_empty(&fragments)) {
+						fragment = (ENetOutgoingCommand*)enet_list_remove(enet_list_begin(&fragments));
+
+						enet_free(fragment);
+					}
+
+					return -1;
+				}
+
+				fragment->fragmentOffset           = fragmentOffset;
+				fragment->fragmentLength           = fragmentLength;
+				fragment->packet                   = packet;
+				fragment->command.header.command   = commandNumber;
+				fragment->command.header.channelID = channelID;
+				fragment->command.sendFragment.startSequenceNumber = startSequenceNumber;
+				fragment->command.sendFragment.dataLength     = ENET_HOST_TO_NET_16(fragmentLength);
+				fragment->command.sendFragment.fragmentCount  = ENET_HOST_TO_NET_32(fragmentCount);
+				fragment->command.sendFragment.fragmentNumber = ENET_HOST_TO_NET_32(fragmentNumber);
+				fragment->command.sendFragment.totalLength    = ENET_HOST_TO_NET_32(packet->dataLength);
+				fragment->command.sendFragment.fragmentOffset = ENET_NET_TO_HOST_32(fragmentOffset);
+
+				enet_list_insert(enet_list_end(&fragments), fragment);
+			}
+
+			packet->referenceCount += fragmentNumber;
+
+			while (!enet_list_empty(&fragments)) {
+				fragment = (ENetOutgoingCommand*)enet_list_remove(enet_list_begin(&fragments));
+
+				enet_peer_setup_outgoing_command(peer, fragment);
+			}
+
+			return 0;
+		}
+
+		command.header.channelID = channelID;
+
+		if ((packet->flags & (ENET_PACKET_FLAG_RELIABLE | ENET_PACKET_FLAG_UNSEQUENCED)) == ENET_PACKET_FLAG_UNSEQUENCED) {
+			command.header.command = ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED | ENET_PROTOCOL_COMMAND_FLAG_UNSEQUENCED;
+			command.sendUnsequenced.dataLength = ENET_HOST_TO_NET_16(packet->dataLength);
+		} else if (packet->flags & ENET_PACKET_FLAG_RELIABLE || channel->outgoingUnreliableSequenceNumber >= 0xFFFF) {
+			command.header.command = ENET_PROTOCOL_COMMAND_SEND_RELIABLE | ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE;
+			command.sendReliable.dataLength = ENET_HOST_TO_NET_16(packet->dataLength);
+		} else {
+			command.header.command = ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE;
+			command.sendUnreliable.dataLength = ENET_HOST_TO_NET_16(packet->dataLength);
+		}
+
+		if (enet_peer_queue_outgoing_command(peer, &command, packet, 0, packet->dataLength) == NULL)
+			return -1;
+
+		return 0;
+	}
+
+	ENetPacket* enet_peer_receive(ENetPeer* peer, enet_uint8* channelID) {
+		ENetIncomingCommand* incomingCommand;
+		ENetPacket* packet;
+
+		if (enet_list_empty(&peer->dispatchedCommands))
+			return NULL;
+
+		incomingCommand = (ENetIncomingCommand*)enet_list_remove(enet_list_begin(&peer->dispatchedCommands));
+
+		if (channelID != NULL)
+			*channelID = incomingCommand->command.header.channelID;
+
+		packet = incomingCommand->packet;
+		--packet->referenceCount;
+
+		if (incomingCommand->fragments != NULL)
+			enet_free(incomingCommand->fragments);
+
+		enet_free(incomingCommand);
+
+		peer->totalWaitingData -= packet->dataLength;
+
+		return packet;
+	}
+
+	static void enet_peer_reset_outgoing_commands(ENetList* queue) {
+		ENetOutgoingCommand* outgoingCommand;
+
+		while (!enet_list_empty(queue)) {
+			outgoingCommand = (ENetOutgoingCommand*)enet_list_remove(enet_list_begin(queue));
+
+			if (outgoingCommand->packet != NULL) {
+				--outgoingCommand->packet->referenceCount;
+
+				if (outgoingCommand->packet->referenceCount == 0)
+					enet_packet_destroy(outgoingCommand->packet);
+			}
+
+			enet_free(outgoingCommand);
+		}
+	}
+
+	static void enet_peer_remove_incoming_commands(ENetList* queue, ENetListIterator startCommand, ENetListIterator endCommand) {
+		ENetListIterator currentCommand;
+
+		for (currentCommand = startCommand; currentCommand != endCommand;) {
+			ENetIncomingCommand* incomingCommand = (ENetIncomingCommand*)currentCommand;
+			currentCommand = enet_list_next(currentCommand);
+
+			enet_list_remove(&incomingCommand->incomingCommandList);
+
+			if (incomingCommand->packet != NULL) {
+				--incomingCommand->packet->referenceCount;
+
+				if (incomingCommand->packet->referenceCount == 0)
+					enet_packet_destroy(incomingCommand->packet);
+			}
+
+			if (incomingCommand->fragments != NULL)
+				enet_free(incomingCommand->fragments);
+
+			enet_free(incomingCommand);
+		}
+	}
+
+	static void enet_peer_reset_incoming_commands(ENetList* queue) {
+		enet_peer_remove_incoming_commands(queue, enet_list_begin(queue), enet_list_end(queue));
+	}
+
+	void enet_peer_reset_queues(ENetPeer* peer) {
+		ENetChannel* channel;
+
+		if (peer->needsDispatch) {
+			enet_list_remove(&peer->dispatchList);
+
+			peer->needsDispatch = 0;
+		}
+
+		while (!enet_list_empty(&peer->acknowledgements)) {
+			enet_free(enet_list_remove(enet_list_begin(&peer->acknowledgements)));
+		}
+
+		enet_peer_reset_outgoing_commands(&peer->sentReliableCommands);
+		enet_peer_reset_outgoing_commands(&peer->sentUnreliableCommands);
+		enet_peer_reset_outgoing_commands(&peer->outgoingReliableCommands);
+		enet_peer_reset_outgoing_commands(&peer->outgoingUnreliableCommands);
+		enet_peer_reset_incoming_commands(&peer->dispatchedCommands);
+
+		if (peer->channels != NULL && peer->channelCount > 0) {
+			for (channel = peer->channels; channel < &peer->channels[peer->channelCount]; ++channel) {
+				enet_peer_reset_incoming_commands(&channel->incomingReliableCommands);
+				enet_peer_reset_incoming_commands(&channel->incomingUnreliableCommands);
+			}
+
+			enet_free(peer->channels);
+		}
+
+		peer->channels     = NULL;
+		peer->channelCount = 0;
+	}
+
+	void enet_peer_on_connect(ENetPeer* peer) {
+		if (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER) {
+			if (peer->incomingBandwidth != 0)
+				++peer->host->bandwidthLimitedPeers;
+
+			++peer->host->connectedPeers;
+		}
+	}
+
+	void enet_peer_on_disconnect(ENetPeer* peer) {
+		if (peer->state == ENET_PEER_STATE_CONNECTED || peer->state == ENET_PEER_STATE_DISCONNECT_LATER) {
+			if (peer->incomingBandwidth != 0)
+				--peer->host->bandwidthLimitedPeers;
+
+			--peer->host->connectedPeers;
+		}
+	}
+
+	void enet_peer_reset(ENetPeer* peer) {
+		enet_peer_on_disconnect(peer);
+
+		peer->outgoingPeerID                 = ENET_PROTOCOL_MAXIMUM_PEER_ID;
+		peer->state                          = ENET_PEER_STATE_DISCONNECTED;
+		peer->incomingBandwidth              = 0;
+		peer->outgoingBandwidth              = 0;
+		peer->incomingBandwidthThrottleEpoch = 0;
+		peer->outgoingBandwidthThrottleEpoch = 0;
+		peer->incomingDataTotal              = 0;
+		peer->totalDataReceived              = 0;
+		peer->outgoingDataTotal              = 0;
+		peer->totalDataSent                  = 0;
+		peer->lastSendTime                   = 0;
+		peer->lastReceiveTime                = 0;
+		peer->nextTimeout                    = 0;
+		peer->earliestTimeout                = 0;
+		peer->packetLossEpoch                = 0;
+		peer->packetsSent                    = 0;
+		peer->totalPacketsSent               = 0;
+		peer->packetsLost                    = 0;
+		peer->totalPacketsLost               = 0;
+		peer->packetLoss                     = 0;
+		peer->packetLossVariance             = 0;
+		peer->packetThrottle                 = ENET_PEER_DEFAULT_PACKET_THROTTLE;
+		peer->packetThrottleLimit            = ENET_PEER_PACKET_THROTTLE_SCALE;
+		peer->packetThrottleCounter          = 0;
+		peer->packetThrottleEpoch            = 0;
+		peer->packetThrottleAcceleration     = ENET_PEER_PACKET_THROTTLE_ACCELERATION;
+		peer->packetThrottleDeceleration     = ENET_PEER_PACKET_THROTTLE_DECELERATION;
+		peer->packetThrottleInterval         = ENET_PEER_PACKET_THROTTLE_INTERVAL;
+		peer->pingInterval                   = ENET_PEER_PING_INTERVAL;
+		peer->timeoutLimit                   = ENET_PEER_TIMEOUT_LIMIT;
+		peer->timeoutMinimum                 = ENET_PEER_TIMEOUT_MINIMUM;
+		peer->timeoutMaximum                 = ENET_PEER_TIMEOUT_MAXIMUM;
+		peer->smoothedRoundTripTime          = 0;
+		peer->lastRoundTripTime              = ENET_PEER_DEFAULT_ROUND_TRIP_TIME;
+		peer->lowestRoundTripTime            = ENET_PEER_DEFAULT_ROUND_TRIP_TIME;
+		peer->lastRoundTripTimeVariance      = 0;
+		peer->highestRoundTripTimeVariance   = 0;
+		peer->roundTripTime                  = ENET_PEER_DEFAULT_ROUND_TRIP_TIME;
+		peer->roundTripTimeVariance          = 0;
+		peer->mtu                            = peer->host->mtu;
+		peer->reliableDataInTransit          = 0;
+		peer->outgoingReliableSequenceNumber = 0;
+		peer->windowSize                     = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
+		peer->incomingUnsequencedGroup       = 0;
+		peer->outgoingUnsequencedGroup       = 0;
+		peer->eventData                      = 0;
+		peer->totalWaitingData               = 0;
+
+		memset(peer->unsequencedWindow, 0, sizeof(peer->unsequencedWindow));
+		enet_peer_reset_queues(peer);
+	}
+
+	void enet_peer_ping(ENetPeer* peer) {
+		ENetProtocol command;
+
+		if (peer->state != ENET_PEER_STATE_CONNECTED)
+			return;
+
+		command.header.command   = ENET_PROTOCOL_COMMAND_PING | ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE;
+		command.header.channelID = 0xFF;
+
+		enet_peer_queue_outgoing_command(peer, &command, NULL, 0, 0);
+	}
+
+	void enet_peer_ping_interval(ENetPeer* peer, enet_uint32 pingInterval) {
+		peer->pingInterval = pingInterval ? pingInterval : ENET_PEER_PING_INTERVAL;
+	}
+
+	void enet_peer_timeout(ENetPeer* peer, enet_uint32 timeoutLimit, enet_uint32 timeoutMinimum, enet_uint32 timeoutMaximum) {
+		peer->timeoutLimit   = timeoutLimit ? timeoutLimit : ENET_PEER_TIMEOUT_LIMIT;
+		peer->timeoutMinimum = timeoutMinimum ? timeoutMinimum : ENET_PEER_TIMEOUT_MINIMUM;
+		peer->timeoutMaximum = timeoutMaximum ? timeoutMaximum : ENET_PEER_TIMEOUT_MAXIMUM;
+	}
+
+	void enet_peer_disconnect_now(ENetPeer* peer, enet_uint32 data) {
+		ENetProtocol command;
+
+		if (peer->state == ENET_PEER_STATE_DISCONNECTED)
+			return;
+
+		if (peer->state != ENET_PEER_STATE_ZOMBIE && peer->state != ENET_PEER_STATE_DISCONNECTING) {
+			enet_peer_reset_queues(peer);
+
+			command.header.command   = ENET_PROTOCOL_COMMAND_DISCONNECT | ENET_PROTOCOL_COMMAND_FLAG_UNSEQUENCED;
+			command.header.channelID = 0xFF;
+			command.disconnect.data  = ENET_HOST_TO_NET_32(data);
+
+			enet_peer_queue_outgoing_command(peer, &command, NULL, 0, 0);
+			enet_host_flush(peer->host);
+		}
+
+		enet_peer_reset(peer);
+	}
+
+	void enet_peer_disconnect(ENetPeer* peer, enet_uint32 data) {
+		ENetProtocol command;
+
+		if (peer->state == ENET_PEER_STATE_DISCONNECTING || peer->state == ENET_PEER_STATE_DISCONNECTED || peer->state == ENET_PEER_STATE_ACKNOWLEDGING_DISCONNECT || peer->state == ENET_PEER_STATE_ZOMBIE)
+			return;
+
+		enet_peer_reset_queues(peer);
+
+		command.header.command   = ENET_PROTOCOL_COMMAND_DISCONNECT;
+		command.header.channelID = 0xFF;
+		command.disconnect.data  = ENET_HOST_TO_NET_32(data);
+
+		if (peer->state == ENET_PEER_STATE_CONNECTED || peer->state == ENET_PEER_STATE_DISCONNECT_LATER)
+			command.header.command |= ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE;
+		else
+			command.header.command |= ENET_PROTOCOL_COMMAND_FLAG_UNSEQUENCED;
+
+		enet_peer_queue_outgoing_command(peer, &command, NULL, 0, 0);
+
+		if (peer->state == ENET_PEER_STATE_CONNECTED || peer->state == ENET_PEER_STATE_DISCONNECT_LATER) {
+			enet_peer_on_disconnect(peer);
+
+			peer->state = ENET_PEER_STATE_DISCONNECTING;
+		} else {
+			enet_host_flush(peer->host);
+			enet_peer_reset(peer);
+		}
+	}
+
+	void enet_peer_disconnect_later(ENetPeer* peer, enet_uint32 data) {
+		if ((peer->state == ENET_PEER_STATE_CONNECTED || peer->state == ENET_PEER_STATE_DISCONNECT_LATER) && !(enet_list_empty(&peer->outgoingReliableCommands) && enet_list_empty(&peer->outgoingUnreliableCommands) && enet_list_empty(&peer->sentReliableCommands))) {
+			peer->state     = ENET_PEER_STATE_DISCONNECT_LATER;
+			peer->eventData = data;
+		} else {
+			enet_peer_disconnect(peer, data);
+		}
+	}
+
+	ENetAcknowledgement* enet_peer_queue_acknowledgement(ENetPeer* peer, const ENetProtocol* command, enet_uint16 sentTime) {
+		ENetAcknowledgement* acknowledgement;
+
+		if (command->header.channelID < peer->channelCount) {
+			ENetChannel* channel       = &peer->channels[command->header.channelID];
+			enet_uint16 reliableWindow = command->header.reliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
+			enet_uint16 currentWindow  = channel->incomingReliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
+
+			if (command->header.reliableSequenceNumber < channel->incomingReliableSequenceNumber)
+				reliableWindow += ENET_PEER_RELIABLE_WINDOWS;
+
+			if (reliableWindow >= currentWindow + ENET_PEER_FREE_RELIABLE_WINDOWS - 1 && reliableWindow <= currentWindow + ENET_PEER_FREE_RELIABLE_WINDOWS)
+				return NULL;
+		}
+
+		acknowledgement = (ENetAcknowledgement*)enet_malloc(sizeof(ENetAcknowledgement));
+
+		if (acknowledgement == NULL)
+			return NULL;
+
+		peer->outgoingDataTotal  += sizeof(ENetProtocolAcknowledge);
+		acknowledgement->sentTime = sentTime;
+		acknowledgement->command  = *command;
+
+		enet_list_insert(enet_list_end(&peer->acknowledgements), acknowledgement);
+
+		return acknowledgement;
+	}
+
+	void enet_peer_setup_outgoing_command(ENetPeer* peer, ENetOutgoingCommand* outgoingCommand) {
+		ENetChannel* channel = &peer->channels[outgoingCommand->command.header.channelID];
+		peer->outgoingDataTotal += enet_protocol_command_size(outgoingCommand->command.header.command) + outgoingCommand->fragmentLength;
+
+		if (outgoingCommand->command.header.channelID == 0xFF) {
+			++peer->outgoingReliableSequenceNumber;
+			outgoingCommand->reliableSequenceNumber   = peer->outgoingReliableSequenceNumber;
+			outgoingCommand->unreliableSequenceNumber = 0;
+		} else if (outgoingCommand->command.header.command & ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE) {
+			++channel->outgoingReliableSequenceNumber;
+			channel->outgoingUnreliableSequenceNumber = 0;
+			outgoingCommand->reliableSequenceNumber   = channel->outgoingReliableSequenceNumber;
+			outgoingCommand->unreliableSequenceNumber = 0;
+		} else if (outgoingCommand->command.header.command & ENET_PROTOCOL_COMMAND_FLAG_UNSEQUENCED) {
+			++peer->outgoingUnsequencedGroup;
+			outgoingCommand->reliableSequenceNumber   = 0;
+			outgoingCommand->unreliableSequenceNumber = 0;
+		} else {
+			if (outgoingCommand->fragmentOffset == 0)
+				++channel->outgoingUnreliableSequenceNumber;
+
+			outgoingCommand->reliableSequenceNumber   = channel->outgoingReliableSequenceNumber;
+			outgoingCommand->unreliableSequenceNumber = channel->outgoingUnreliableSequenceNumber;
+		}
+
+		outgoingCommand->sendAttempts          = 0;
+		outgoingCommand->sentTime              = 0;
+		outgoingCommand->roundTripTimeout      = 0;
+		outgoingCommand->roundTripTimeoutLimit = 0;
+		outgoingCommand->command.header.reliableSequenceNumber = ENET_HOST_TO_NET_16(outgoingCommand->reliableSequenceNumber);
+
+		switch (outgoingCommand->command.header.command & ENET_PROTOCOL_COMMAND_MASK) {
+			case ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE:
+				outgoingCommand->command.sendUnreliable.unreliableSequenceNumber = ENET_HOST_TO_NET_16(outgoingCommand->unreliableSequenceNumber);
+
+				break;
+
+			case ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED:
+				outgoingCommand->command.sendUnsequenced.unsequencedGroup = ENET_HOST_TO_NET_16(peer->outgoingUnsequencedGroup);
+
+				break;
+
+			default:
+				break;
+		}
+
+		if (outgoingCommand->command.header.command & ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE)
+			enet_list_insert(enet_list_end(&peer->outgoingReliableCommands), outgoingCommand);
+		else
+			enet_list_insert(enet_list_end(&peer->outgoingUnreliableCommands), outgoingCommand);
+	}
+
+	ENetOutgoingCommand* enet_peer_queue_outgoing_command(ENetPeer* peer, const ENetProtocol* command, ENetPacket* packet, enet_uint32 offset, enet_uint16 length) {
+		ENetOutgoingCommand* outgoingCommand = (ENetOutgoingCommand*)enet_malloc(sizeof(ENetOutgoingCommand));
+
+		if (outgoingCommand == NULL)
+			return NULL;
+
+		outgoingCommand->command        = *command;
+		outgoingCommand->fragmentOffset = offset;
+		outgoingCommand->fragmentLength = length;
+		outgoingCommand->packet         = packet;
+
+		if (packet != NULL)
+			++packet->referenceCount;
+
+		enet_peer_setup_outgoing_command(peer, outgoingCommand);
+
+		return outgoingCommand;
+	}
+
+	void enet_peer_dispatch_incoming_unreliable_commands(ENetPeer* peer, ENetChannel* channel) {
+		ENetListIterator droppedCommand, startCommand, currentCommand;
+
+		for (droppedCommand = startCommand = currentCommand = enet_list_begin(&channel->incomingUnreliableCommands); currentCommand != enet_list_end(&channel->incomingUnreliableCommands); currentCommand = enet_list_next(currentCommand)) {
+			ENetIncomingCommand* incomingCommand = (ENetIncomingCommand*)currentCommand;
+
+			if ((incomingCommand->command.header.command & ENET_PROTOCOL_COMMAND_MASK) == ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED)
+				continue;
+
+			if (incomingCommand->reliableSequenceNumber == channel->incomingReliableSequenceNumber) {
+				if (incomingCommand->fragmentsRemaining <= 0) {
+					channel->incomingUnreliableSequenceNumber = incomingCommand->unreliableSequenceNumber;
+
+					continue;
+				}
+
+			if (startCommand != currentCommand) {
+				enet_list_move(enet_list_end(&peer->dispatchedCommands), startCommand, enet_list_previous(currentCommand));
+
+				if (!peer->needsDispatch) {
+					enet_list_insert(enet_list_end(&peer->host->dispatchQueue), &peer->dispatchList);
+
+					peer->needsDispatch = 1;
+				}
+
+				droppedCommand = currentCommand;
+			} else if (droppedCommand != currentCommand)
+				droppedCommand = enet_list_previous(currentCommand);
+			} else {
+				enet_uint16 reliableWindow = incomingCommand->reliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
+				enet_uint16 currentWindow  = channel->incomingReliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
+
+				if (incomingCommand->reliableSequenceNumber < channel->incomingReliableSequenceNumber)
+					reliableWindow += ENET_PEER_RELIABLE_WINDOWS;
+
+				if (reliableWindow >= currentWindow && reliableWindow < currentWindow + ENET_PEER_FREE_RELIABLE_WINDOWS - 1)
+					break;
+
+				droppedCommand = enet_list_next(currentCommand);
+
+				if (startCommand != currentCommand) {
+					enet_list_move(enet_list_end(&peer->dispatchedCommands), startCommand, enet_list_previous(currentCommand));
+
+					if (!peer->needsDispatch) {
+						enet_list_insert(enet_list_end(&peer->host->dispatchQueue), &peer->dispatchList);
+
+						peer->needsDispatch = 1;
+					}
+				}
+			}
+
+			startCommand = enet_list_next(currentCommand);
+		}
+
+		if (startCommand != currentCommand) {
+			enet_list_move(enet_list_end(&peer->dispatchedCommands), startCommand, enet_list_previous(currentCommand));
+
+			if (!peer->needsDispatch) {
+				enet_list_insert(enet_list_end(&peer->host->dispatchQueue), &peer->dispatchList);
+
+				peer->needsDispatch = 1;
+			}
+
+			droppedCommand = currentCommand;
+		}
+
+		enet_peer_remove_incoming_commands(&channel->incomingUnreliableCommands, enet_list_begin(&channel->incomingUnreliableCommands), droppedCommand);
+	}
+
+	void enet_peer_dispatch_incoming_reliable_commands(ENetPeer* peer, ENetChannel* channel) {
+		ENetListIterator currentCommand;
+
+		for (currentCommand = enet_list_begin(&channel->incomingReliableCommands); currentCommand != enet_list_end(&channel->incomingReliableCommands); currentCommand = enet_list_next(currentCommand)) {
+			ENetIncomingCommand* incomingCommand = (ENetIncomingCommand*)currentCommand;
+
+			if (incomingCommand->fragmentsRemaining > 0 || incomingCommand->reliableSequenceNumber != (enet_uint16)(channel->incomingReliableSequenceNumber + 1))
+				break;
+
+			channel->incomingReliableSequenceNumber = incomingCommand->reliableSequenceNumber;
+
+			if (incomingCommand->fragmentCount > 0)
+				channel->incomingReliableSequenceNumber += incomingCommand->fragmentCount - 1;
+		}
+
+		if (currentCommand == enet_list_begin(&channel->incomingReliableCommands))
+			return;
+
+		channel->incomingUnreliableSequenceNumber = 0;
+
+		enet_list_move(enet_list_end(&peer->dispatchedCommands), enet_list_begin(&channel->incomingReliableCommands), enet_list_previous(currentCommand));
+
+		if (!peer->needsDispatch) {
+			enet_list_insert(enet_list_end(&peer->host->dispatchQueue), &peer->dispatchList);
+
+			peer->needsDispatch = 1;
+		}
+
+		if (!enet_list_empty(&channel->incomingUnreliableCommands))
+			enet_peer_dispatch_incoming_unreliable_commands(peer, channel);
+	}
+
+	ENetIncomingCommand* enet_peer_queue_incoming_command(ENetPeer* peer, const ENetProtocol* command, const void* data, size_t dataLength, enet_uint32 flags, enet_uint32 fragmentCount) {
+		static ENetIncomingCommand dummyCommand;
+
+		ENetChannel* channel = &peer->channels[command->header.channelID];
+		enet_uint32 unreliableSequenceNumber = 0, reliableSequenceNumber = 0;
+		enet_uint16 reliableWindow, currentWindow;
+		ENetIncomingCommand* incomingCommand;
+		ENetListIterator currentCommand;
+		ENetPacket* packet = NULL;
+
+		if (peer->state == ENET_PEER_STATE_DISCONNECT_LATER)
+			goto discardCommand;
+
+		if ((command->header.command & ENET_PROTOCOL_COMMAND_MASK) != ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED) {
+			reliableSequenceNumber = command->header.reliableSequenceNumber;
+			reliableWindow = reliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
+			currentWindow  = channel->incomingReliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE;
+
+			if (reliableSequenceNumber < channel->incomingReliableSequenceNumber)
+				reliableWindow += ENET_PEER_RELIABLE_WINDOWS;
+
+			if (reliableWindow < currentWindow || reliableWindow >= currentWindow + ENET_PEER_FREE_RELIABLE_WINDOWS - 1)
+				goto discardCommand;
+		}
+
+		switch (command->header.command & ENET_PROTOCOL_COMMAND_MASK) {
+			case ENET_PROTOCOL_COMMAND_SEND_FRAGMENT:
+			case ENET_PROTOCOL_COMMAND_SEND_RELIABLE:
+				if (reliableSequenceNumber == channel->incomingReliableSequenceNumber)
+					goto discardCommand;
+
+				for (currentCommand = enet_list_previous(enet_list_end(&channel->incomingReliableCommands)); currentCommand != enet_list_end(&channel->incomingReliableCommands); currentCommand = enet_list_previous(currentCommand)) {
+					incomingCommand = (ENetIncomingCommand*)currentCommand;
+
+					if (reliableSequenceNumber >= channel->incomingReliableSequenceNumber) {
+						if (incomingCommand->reliableSequenceNumber < channel->incomingReliableSequenceNumber)
+							continue;
+					} else if (incomingCommand->reliableSequenceNumber >= channel->incomingReliableSequenceNumber) {
+						break;
+					}
+
+					if (incomingCommand->reliableSequenceNumber <= reliableSequenceNumber) {
+						if (incomingCommand->reliableSequenceNumber < reliableSequenceNumber)
+							break;
+
+						goto discardCommand;
+					}
+				}
+
+				break;
+
+			case ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE:
+			case ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE_FRAGMENT:
+				unreliableSequenceNumber = ENET_NET_TO_HOST_16(command->sendUnreliable.unreliableSequenceNumber);
+
+				if (reliableSequenceNumber == channel->incomingReliableSequenceNumber && unreliableSequenceNumber <= channel->incomingUnreliableSequenceNumber)
+					goto discardCommand;
+
+				for (currentCommand = enet_list_previous(enet_list_end(&channel->incomingUnreliableCommands)); currentCommand != enet_list_end(&channel->incomingUnreliableCommands); currentCommand = enet_list_previous(currentCommand)) {
+					incomingCommand = (ENetIncomingCommand*)currentCommand;
+
+					if ((command->header.command & ENET_PROTOCOL_COMMAND_MASK) == ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED)
+						continue;
+
+					if (reliableSequenceNumber >= channel->incomingReliableSequenceNumber) {
+						if (incomingCommand->reliableSequenceNumber < channel->incomingReliableSequenceNumber)
+							continue;
+					} else if (incomingCommand->reliableSequenceNumber >= channel->incomingReliableSequenceNumber) {
+						break;
+					}
+
+					if (incomingCommand->reliableSequenceNumber < reliableSequenceNumber)
+						break;
+
+					if (incomingCommand->reliableSequenceNumber > reliableSequenceNumber)
+						continue;
+
+					if (incomingCommand->unreliableSequenceNumber <= unreliableSequenceNumber) {
+						if (incomingCommand->unreliableSequenceNumber < unreliableSequenceNumber)
+							break;
+
+						goto discardCommand;
+					}
+				}
+
+				break;
+
+			case ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED:
+				currentCommand = enet_list_end(&channel->incomingUnreliableCommands);
+
+				break;
+
+			default:
+				goto discardCommand;
+		}
+
+		if (peer->totalWaitingData >= peer->host->maximumWaitingData)
+			goto notifyError;
+
+		packet = enet_packet_create(data, dataLength, flags);
+
+		if (packet == NULL)
+			goto notifyError;
+
+		incomingCommand = (ENetIncomingCommand*)enet_malloc(sizeof(ENetIncomingCommand));
+
+		if (incomingCommand == NULL)
+			goto notifyError;
+
+		incomingCommand->reliableSequenceNumber   = command->header.reliableSequenceNumber;
+		incomingCommand->unreliableSequenceNumber = unreliableSequenceNumber & 0xFFFF;
+		incomingCommand->command                  = *command;
+		incomingCommand->fragmentCount            = fragmentCount;
+		incomingCommand->fragmentsRemaining       = fragmentCount;
+		incomingCommand->packet                   = packet;
+		incomingCommand->fragments                = NULL;
+
+		if (fragmentCount > 0) {
+			if (fragmentCount <= ENET_PROTOCOL_MAXIMUM_FRAGMENT_COUNT)
+				incomingCommand->fragments = (enet_uint32*)enet_malloc((fragmentCount + 31) / 32 * sizeof(enet_uint32));
+
+			if (incomingCommand->fragments == NULL) {
+				enet_free(incomingCommand);
+
+				goto notifyError;
+			}
+
+			memset(incomingCommand->fragments, 0, (fragmentCount + 31) / 32 * sizeof(enet_uint32));
+		}
+
+		if (packet != NULL) {
+			++packet->referenceCount;
+			peer->totalWaitingData += packet->dataLength;
+		}
+
+		enet_list_insert(enet_list_next(currentCommand), incomingCommand);
+
+		switch (command->header.command & ENET_PROTOCOL_COMMAND_MASK) {
+			case ENET_PROTOCOL_COMMAND_SEND_FRAGMENT:
+			case ENET_PROTOCOL_COMMAND_SEND_RELIABLE:
+				enet_peer_dispatch_incoming_reliable_commands(peer, channel);
+
+				break;
+
+			default:
+				enet_peer_dispatch_incoming_unreliable_commands(peer, channel);
+
+				break;
+		}
+
+		return incomingCommand;
+
+		discardCommand:
+
+		if (fragmentCount > 0)
+			goto notifyError;
+
+		if (packet != NULL && packet->referenceCount == 0)
+			enet_packet_destroy(packet);
+
+		return &dummyCommand;
+
+		notifyError:
+
+		if (packet != NULL && packet->referenceCount == 0)
+			enet_packet_destroy(packet);
+
+		return NULL;
+	}
+
+// =======================================================================//
+// !
+// ! Host
+// !
+// =======================================================================//
+
+	ENetHost* enet_host_create(const ENetAddress* address, size_t peerCount, size_t channelLimit, enet_uint32 incomingBandwidth, enet_uint32 outgoingBandwidth) {
+		ENetHost* host;
+		ENetPeer* currentPeer;
+
+		if (peerCount > ENET_PROTOCOL_MAXIMUM_PEER_ID)
+			return NULL;
+
+		host = (ENetHost*)enet_malloc(sizeof(ENetHost));
+
+		if (host == NULL)
+			return NULL;
+
+		memset(host, 0, sizeof(ENetHost));
+
+		host->peers = (ENetPeer*)enet_malloc(peerCount * sizeof(ENetPeer));
+
+		if (host->peers == NULL) {
+			enet_free(host);
+
+			return NULL;
+		}
+
+		memset(host->peers, 0, peerCount * sizeof(ENetPeer));
+
+		host->socket = enet_socket_create(ENET_SOCKET_TYPE_DATAGRAM);
+
+		if (host->socket != ENET_SOCKET_NULL)
+			enet_socket_set_option(host->socket, ENET_SOCKOPT_IPV6_V6ONLY, 0);
+
+		if (host->socket == ENET_SOCKET_NULL || (address != NULL && enet_socket_bind(host->socket, address) < 0)) {
+			if (host->socket != ENET_SOCKET_NULL)
+				enet_socket_destroy(host->socket);
+			
+			enet_free(host->peers);
+			enet_free(host);
+
+			return NULL;
+		}
+
+		enet_socket_set_option(host->socket, ENET_SOCKOPT_NONBLOCK, 1);
+		enet_socket_set_option(host->socket, ENET_SOCKOPT_BROADCAST, 1);
+		enet_socket_set_option(host->socket, ENET_SOCKOPT_RCVBUF, ENET_HOST_RECEIVE_BUFFER_SIZE);
+		enet_socket_set_option(host->socket, ENET_SOCKOPT_SNDBUF, ENET_HOST_SEND_BUFFER_SIZE);
+
+		if (address != NULL && enet_socket_get_address(host->socket, &host->address) < 0)
+			host->address = *address;
+
+		if (!channelLimit || channelLimit > ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT)
+			channelLimit = ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT;
+		else if (channelLimit < ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT)
+			channelLimit = ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT;
+
+		host->randomSeed                 = (enet_uint32)(size_t)host;
+		host->randomSeed                += enet_host_random_seed();
+		host->randomSeed                 = (host->randomSeed << 16) | (host->randomSeed >> 16);
+		host->channelLimit               = channelLimit;
+		host->incomingBandwidth          = incomingBandwidth;
+		host->outgoingBandwidth          = outgoingBandwidth;
+		host->bandwidthThrottleEpoch     = 0;
+		host->recalculateBandwidthLimits = 0;
+		host->preventConnections         = 0;
+		host->mtu                        = ENET_HOST_DEFAULT_MTU;
+		host->peerCount                  = peerCount;
+		host->commandCount               = 0;
+		host->bufferCount                = 0;
+		host->compression                = 0;
+		host->compressionBufferSize      = 0;
+		host->checksumCallback           = NULL;
+		host->receivedAddress.host       = ENET_HOST_ANY;
+		host->receivedAddress.port       = 0;
+		host->receivedData               = NULL;
+		host->receivedDataLength         = 0;
+		host->totalSentData              = 0;
+		host->totalSentPackets           = 0;
+		host->totalReceivedData          = 0;
+		host->totalReceivedPackets       = 0;
+		host->connectedPeers             = 0;
+		host->bandwidthLimitedPeers      = 0;
+		host->duplicatePeers             = ENET_PROTOCOL_MAXIMUM_PEER_ID;
+		host->maximumPacketSize          = ENET_HOST_DEFAULT_MAXIMUM_PACKET_SIZE;
+		host->maximumWaitingData         = ENET_HOST_DEFAULT_MAXIMUM_WAITING_DATA;
+		host->interceptCallback          = NULL;
+
+		enet_list_clear(&host->dispatchQueue);
+
+		for (currentPeer = host->peers; currentPeer < &host->peers[host->peerCount]; ++currentPeer) {
+			currentPeer->host = host;
+			currentPeer->incomingPeerID    = currentPeer - host->peers;
+			currentPeer->outgoingSessionID = currentPeer->incomingSessionID = 0xFF;
+			currentPeer->data = NULL;
+
+			enet_list_clear(&currentPeer->acknowledgements);
+			enet_list_clear(&currentPeer->sentReliableCommands);
+			enet_list_clear(&currentPeer->sentUnreliableCommands);
+			enet_list_clear(&currentPeer->outgoingReliableCommands);
+			enet_list_clear(&currentPeer->outgoingUnreliableCommands);
+			enet_list_clear(&currentPeer->dispatchedCommands);
+			enet_peer_reset(currentPeer);
+		}
+
+		return host;
+	}
+
+	void enet_host_destroy(ENetHost* host) {
+		ENetPeer* currentPeer;
+
+		if (host == NULL)
+			return;
+
+		enet_socket_destroy(host->socket);
+
+		for (currentPeer = host->peers; currentPeer < &host->peers[host->peerCount]; ++currentPeer) {
+			enet_peer_reset(currentPeer);
+		}
+
+		enet_free(host->peers);
+		enet_free(host->compressionBuffer);
+		enet_free(host);
+	}
+
+	void enet_host_enable_compression(ENetHost* host) {
+		if (host == NULL)
+			return;
+
+		host->compression = 1;
+	}
+
+	void enet_host_prevent_connections(ENetHost* host, enet_uint8 state) {
+		if (host == NULL)
+			return;
+
+		host->preventConnections = state;
+	}
+
+	ENetPeer* enet_host_connect(ENetHost* host, const ENetAddress* address, size_t channelCount, enet_uint32 data) {
+		ENetPeer* currentPeer;
+		ENetChannel* channel;
+		ENetProtocol command;
+
+		if (channelCount < ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT)
+			channelCount = ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT;
+		else if (channelCount > ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT)
+			channelCount = ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT;
+
+		for (currentPeer = host->peers; currentPeer < &host->peers[host->peerCount]; ++currentPeer) {
+			if (currentPeer->state == ENET_PEER_STATE_DISCONNECTED)
+				break;
+		}
+
+		if (currentPeer >= &host->peers[host->peerCount])
+			return NULL;
+
+		currentPeer->channels = (ENetChannel*)enet_malloc(channelCount * sizeof(ENetChannel));
+
+		if (currentPeer->channels == NULL)
+			return NULL;
+
+		currentPeer->channelCount = channelCount;
+		currentPeer->state        = ENET_PEER_STATE_CONNECTING;
+		currentPeer->address      = *address;
+		currentPeer->connectID    = ++host->randomSeed;
+
+		if (host->outgoingBandwidth == 0)
+			currentPeer->windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
+		else
+			currentPeer->windowSize = (host->outgoingBandwidth / ENET_PEER_WINDOW_SIZE_SCALE) * ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
+
+		if (currentPeer->windowSize < ENET_PROTOCOL_MINIMUM_WINDOW_SIZE)
+			currentPeer->windowSize = ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
+		else if (currentPeer->windowSize > ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE)
+			currentPeer->windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
+
+		for (channel = currentPeer->channels; channel < &currentPeer->channels[channelCount]; ++channel) {
+			channel->outgoingReliableSequenceNumber   = 0;
+			channel->outgoingUnreliableSequenceNumber = 0;
+			channel->incomingReliableSequenceNumber   = 0;
+			channel->incomingUnreliableSequenceNumber = 0;
+
+			enet_list_clear(&channel->incomingReliableCommands);
+			enet_list_clear(&channel->incomingUnreliableCommands);
+
+			channel->usedReliableWindows = 0;
+
+			memset(channel->reliableWindows, 0, sizeof(channel->reliableWindows));
+		}
+
+		command.header.command                     = ENET_PROTOCOL_COMMAND_CONNECT | ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE;
+		command.header.channelID                   = 0xFF;
+		command.connect.outgoingPeerID             = ENET_HOST_TO_NET_16(currentPeer->incomingPeerID);
+		command.connect.incomingSessionID          = currentPeer->incomingSessionID;
+		command.connect.outgoingSessionID          = currentPeer->outgoingSessionID;
+		command.connect.mtu                        = ENET_HOST_TO_NET_32(currentPeer->mtu);
+		command.connect.windowSize                 = ENET_HOST_TO_NET_32(currentPeer->windowSize);
+		command.connect.channelCount               = ENET_HOST_TO_NET_32(channelCount);
+		command.connect.incomingBandwidth          = ENET_HOST_TO_NET_32(host->incomingBandwidth);
+		command.connect.outgoingBandwidth          = ENET_HOST_TO_NET_32(host->outgoingBandwidth);
+		command.connect.packetThrottleInterval     = ENET_HOST_TO_NET_32(currentPeer->packetThrottleInterval);
+		command.connect.packetThrottleAcceleration = ENET_HOST_TO_NET_32(currentPeer->packetThrottleAcceleration);
+		command.connect.packetThrottleDeceleration = ENET_HOST_TO_NET_32(currentPeer->packetThrottleDeceleration);
+		command.connect.connectID                  = currentPeer->connectID;
+		command.connect.data                       = ENET_HOST_TO_NET_32(data);
+
+		enet_peer_queue_outgoing_command(currentPeer, &command, NULL, 0, 0);
+
+		return currentPeer;
+	}
+
+	void enet_host_broadcast(ENetHost* host, enet_uint8 channelID, ENetPacket* packet) {
+		ENetPeer* currentPeer;
+
+		for (currentPeer = host->peers; currentPeer < &host->peers[host->peerCount]; ++currentPeer) {
+			if (currentPeer->state != ENET_PEER_STATE_CONNECTED)
+				continue;
+
+			enet_peer_send(currentPeer, channelID, packet);
+		}
+
+		if (packet->referenceCount == 0)
+			enet_packet_destroy(packet);
+	}
+
+	void enet_host_broadcast_selective(ENetHost* host, enet_uint8 channelID, ENetPacket* packet, ENetPeer** peers, size_t length) {
+		ENetPeer* currentPeer;
+
+		if (host == NULL)
+			return;
+
+		for (int i = 0; i < length; i++) {
+			currentPeer = peers[i];
+
+			if (currentPeer == NULL || currentPeer->state != ENET_PEER_STATE_CONNECTED)
+				continue;
+
+			enet_peer_send(currentPeer, channelID, packet);
+		}
+
+		if (packet->referenceCount == 0)
+			enet_packet_destroy(packet);
+	}
+
+	void enet_host_channel_limit(ENetHost* host, size_t channelLimit) {
+		if (!channelLimit || channelLimit > ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT)
+			channelLimit = ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT;
+		else if (channelLimit < ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT)
+			channelLimit = ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT;
+
+		host->channelLimit = channelLimit;
+	}
+
+	void enet_host_bandwidth_limit(ENetHost* host, enet_uint32 incomingBandwidth, enet_uint32 outgoingBandwidth) {
+		host->incomingBandwidth = incomingBandwidth;
+		host->outgoingBandwidth = outgoingBandwidth;
+		host->recalculateBandwidthLimits = 1;
+	}
+
+	void enet_host_bandwidth_throttle(ENetHost* host) {
+		enet_uint32 timeCurrent    = enet_time_get();
+		enet_uint32 elapsedTime    = timeCurrent - host->bandwidthThrottleEpoch;
+		enet_uint32 peersRemaining = (enet_uint32)host->connectedPeers;
+		enet_uint32 dataTotal      = ~0;
+		enet_uint32 bandwidth      = ~0;
+		enet_uint32 throttle       = 0;
+		enet_uint32 bandwidthLimit = 0;
+
+		int needsAdjustment = host->bandwidthLimitedPeers > 0 ? 1 : 0;
+		ENetPeer* peer;
+		ENetProtocol command;
+
+		if (elapsedTime < ENET_HOST_BANDWIDTH_THROTTLE_INTERVAL)
+			return;
+
+		if (host->outgoingBandwidth == 0 && host->incomingBandwidth == 0)
+			return;
+
+		host->bandwidthThrottleEpoch = timeCurrent;
+
+		if (peersRemaining == 0)
+			return;
+
+		if (host->outgoingBandwidth != 0) {
+			dataTotal = 0;
+			bandwidth = (host->outgoingBandwidth * elapsedTime) / 1000;
+
+			for (peer = host->peers; peer < &host->peers[host->peerCount]; ++peer) {
+				if (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER)
+					continue;
+
+				dataTotal += peer->outgoingDataTotal;
+			}
+		}
+
+		while (peersRemaining > 0 && needsAdjustment != 0) {
+			needsAdjustment = 0;
+
+			if (dataTotal <= bandwidth)
+				throttle = ENET_PEER_PACKET_THROTTLE_SCALE;
+			else
+				throttle = (bandwidth * ENET_PEER_PACKET_THROTTLE_SCALE) / dataTotal;
+
+			for (peer = host->peers; peer < &host->peers[host->peerCount]; ++peer) {
+				enet_uint32 peerBandwidth;
+
+				if ((peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER) || peer->incomingBandwidth == 0 || peer->outgoingBandwidthThrottleEpoch == timeCurrent)
+					continue;
+
+				peerBandwidth = (peer->incomingBandwidth * elapsedTime) / 1000;
+
+				if ((throttle * peer->outgoingDataTotal) / ENET_PEER_PACKET_THROTTLE_SCALE <= peerBandwidth)
+					continue;
+
+				peer->packetThrottleLimit = (peerBandwidth * ENET_PEER_PACKET_THROTTLE_SCALE) / peer->outgoingDataTotal;
+
+				if (peer->packetThrottleLimit == 0)
+					peer->packetThrottleLimit = 1;
+
+				if (peer->packetThrottle > peer->packetThrottleLimit)
+					peer->packetThrottle = peer->packetThrottleLimit;
+
+				peer->outgoingBandwidthThrottleEpoch = timeCurrent;
+				peer->incomingDataTotal = 0;
+				peer->outgoingDataTotal = 0;
+				needsAdjustment = 1;
+				--peersRemaining;
+				bandwidth -= peerBandwidth;
+				dataTotal -= peerBandwidth;
+			}
+		}
+
+		if (peersRemaining > 0) {
+			if (dataTotal <= bandwidth)
+				throttle = ENET_PEER_PACKET_THROTTLE_SCALE;
+			else
+				throttle = (bandwidth * ENET_PEER_PACKET_THROTTLE_SCALE) / dataTotal;
+
+			for (peer = host->peers; peer < &host->peers[host->peerCount]; ++peer) {
+				if ((peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER) || peer->outgoingBandwidthThrottleEpoch == timeCurrent)
+					continue;
+
+				peer->packetThrottleLimit = throttle;
+
+				if (peer->packetThrottle > peer->packetThrottleLimit)
+					peer->packetThrottle = peer->packetThrottleLimit;
+
+				peer->incomingDataTotal = 0;
+				peer->outgoingDataTotal = 0;
+			}
+		}
+
+		if (host->recalculateBandwidthLimits) {
+			host->recalculateBandwidthLimits = 0;
+			peersRemaining  = (enet_uint32)host->connectedPeers;
+			bandwidth       = host->incomingBandwidth;
+			needsAdjustment = 1;
+
+			if (bandwidth == 0) {
+				bandwidthLimit = 0;
+			} else {
+				while (peersRemaining > 0 && needsAdjustment != 0) {
+					needsAdjustment = 0;
+					bandwidthLimit  = bandwidth / peersRemaining;
+
+					for (peer = host->peers; peer < &host->peers[host->peerCount]; ++peer) {
+						if ((peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER) || peer->incomingBandwidthThrottleEpoch == timeCurrent)
+							continue;
+
+						if (peer->outgoingBandwidth > 0 && peer->outgoingBandwidth >= bandwidthLimit)
+							continue;
+
+						peer->incomingBandwidthThrottleEpoch = timeCurrent;
+						needsAdjustment = 1;
+						--peersRemaining;
+						bandwidth -= peer->outgoingBandwidth;
+					}
+				}
+			}
+
+			for (peer = host->peers; peer < &host->peers[host->peerCount]; ++peer) {
+				if (peer->state != ENET_PEER_STATE_CONNECTED && peer->state != ENET_PEER_STATE_DISCONNECT_LATER)
+					continue;
+
+				command.header.command   = ENET_PROTOCOL_COMMAND_BANDWIDTH_LIMIT | ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE;
+				command.header.channelID = 0xFF;
+				command.bandwidthLimit.outgoingBandwidth = ENET_HOST_TO_NET_32(host->outgoingBandwidth);
+
+				if (peer->incomingBandwidthThrottleEpoch == timeCurrent)
+					command.bandwidthLimit.incomingBandwidth = ENET_HOST_TO_NET_32(peer->outgoingBandwidth);
+				else
+					command.bandwidthLimit.incomingBandwidth = ENET_HOST_TO_NET_32(bandwidthLimit);
+
+				enet_peer_queue_outgoing_command(peer, &command, NULL, 0, 0);
+			}
+		}
+	}
+
+// =======================================================================//
+// !
+// ! Time
+// !
+// =======================================================================//
+
+	#ifdef _WIN32
+		static LARGE_INTEGER getFILETIMEoffset() {
+			SYSTEMTIME s;
+			FILETIME f;
+			LARGE_INTEGER t;
+			s.wYear = 1970;
+			s.wMonth = 1;
+			s.wDay = 1;
+			s.wHour = 0;
+			s.wMinute = 0;
+			s.wSecond = 0;
+			s.wMilliseconds = 0;
+
+			SystemTimeToFileTime(&s, &f);
+
+			t.QuadPart = f.dwHighDateTime;
+			t.QuadPart <<= 32;
+			t.QuadPart |= f.dwLowDateTime;
+
+			return t;
+		}
+
+		int clock_gettime(int X, struct timespec* tv) {
+			LARGE_INTEGER t;
+			FILETIME f;
+			double microseconds;
+
+			static LARGE_INTEGER offset;
+			static double frequencyToMicroseconds;
+			static int initialized = 0;
+			static BOOL usePerformanceCounter = 0;
+
+			if (!initialized) {
+				LARGE_INTEGER performanceFrequency;
+				initialized = 1;
+				usePerformanceCounter = QueryPerformanceFrequency(&performanceFrequency);
+
+				if (usePerformanceCounter) {
+					QueryPerformanceCounter(&offset);
+
+					frequencyToMicroseconds = (double)performanceFrequency.QuadPart / 1000000.;
+				} else {
+					offset = getFILETIMEoffset();
+					frequencyToMicroseconds = 10.;
+				}
+			}
+
+			if (usePerformanceCounter) {
+				QueryPerformanceCounter(&t);
+			} else {
+				GetSystemTimeAsFileTime(&f);
+
+				t.QuadPart = f.dwHighDateTime;
+				t.QuadPart <<= 32;
+				t.QuadPart |= f.dwLowDateTime;
+			}
+
+			t.QuadPart -= offset.QuadPart;
+			microseconds = (double)t.QuadPart / frequencyToMicroseconds;
+			t.QuadPart = (LONGLONG)microseconds;
+			tv->tv_sec = (long)(t.QuadPart / 1000000);
+			tv->tv_nsec = t.QuadPart % 1000000 * 1000;
+
+			return 0;
+		}
+	#elif __APPLE__ && __MAC_OS_X_VERSION_MIN_REQUIRED < 101200 && !defined(CLOCK_MONOTONIC)
+		#define CLOCK_MONOTONIC 0
+
+		int clock_gettime(int X, struct timespec* ts) {
+			clock_serv_t cclock;
+			mach_timespec_t mts;
+
+			host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &cclock);
+			clock_get_time(cclock, &mts);
+			mach_port_deallocate(mach_task_self(), cclock);
+
+			ts->tv_sec = mts.tv_sec;
+			ts->tv_nsec = mts.tv_nsec;
+
+			return 0;
+		}
+	#endif
+
+	enet_uint32 enet_time_get() {
+		static enet_uint64 start_time_ns = 0;
+
+		struct timespec ts;
+
+		#ifdef CLOCK_MONOTONIC_RAW
+			clock_gettime(CLOCK_MONOTONIC_RAW, &ts);
+		#else
+			clock_gettime(CLOCK_MONOTONIC, &ts);
+		#endif
+
+		static const enet_uint64 ns_in_s = 1000 * 1000 * 1000;
+		static const enet_uint64 ns_in_ms = 1000 * 1000;
+
+		enet_uint64 current_time_ns = ts.tv_nsec + (enet_uint64)ts.tv_sec * ns_in_s;
+		enet_uint64 offset_ns = ENET_ATOMIC_READ(&start_time_ns);
+
+		if (offset_ns == 0) {
+			enet_uint64 want_value = current_time_ns - 1 * ns_in_ms;
+			enet_uint64 old_value = ENET_ATOMIC_CAS(&start_time_ns, 0, want_value);
+			offset_ns = old_value == 0 ? want_value : old_value;
+		}
+
+		enet_uint64 result_in_ns = current_time_ns - offset_ns;
+
+		return (enet_uint32)(result_in_ns / ns_in_ms);
+	}
+
+// =======================================================================//
+// !
+// ! Extended functionality
+// !
+// =======================================================================//
+
+	void* enet_packet_get_data(const ENetPacket* packet) {
+		return (void*)packet->data;
+	}
+
+	int enet_packet_get_length(const ENetPacket* packet) {
+		return packet->dataLength;
+	}
+
+	void enet_packet_set_free_callback(ENetPacket* packet, const void* callback) {
+		packet->freeCallback = (ENetPacketFreeCallback)callback;
+	}
+
+	int enet_packet_check_references(const ENetPacket* packet) {
+		return (int)packet->referenceCount;
+	}
+
+	void enet_packet_dispose(ENetPacket* packet) {
+		if (packet->referenceCount == 0)
+			enet_packet_destroy(packet);
+	}
+
+	enet_uint32 enet_host_get_peers_count(const ENetHost* host) {
+		return host->connectedPeers;
+	}
+
+	enet_uint32 enet_host_get_packets_sent(const ENetHost* host) {
+		return host->totalSentPackets;
+	}
+
+	enet_uint32 enet_host_get_packets_received(const ENetHost* host) {
+		return host->totalReceivedPackets;
+	}
+
+	enet_uint32 enet_host_get_bytes_sent(const ENetHost* host) {
+		return host->totalSentData;
+	}
+
+	enet_uint32 enet_host_get_bytes_received(const ENetHost* host) {
+		return host->totalReceivedData;
+	}
+
+	enet_uint32 enet_peer_get_id(const ENetPeer* peer) {
+		return peer->connectID;
+	}
+
+	int enet_peer_get_ip(const ENetPeer* peer, char* ip, size_t ipLength) {
+		return enet_address_get_host_ip(&peer->address, ip, ipLength);
+	}
+
+	enet_uint16 enet_peer_get_port(const ENetPeer* peer) {
+		return peer->address.port;
+	}
+
+	enet_uint32 enet_peer_get_mtu(const ENetPeer* peer) {
+		return peer->mtu;
+	}
+
+	ENetPeerState enet_peer_get_state(const ENetPeer* peer) {
+		return peer->state;
+	}
+
+	enet_uint32 enet_peer_get_rtt(const ENetPeer* peer) {
+		return peer->smoothedRoundTripTime;
+	}
+
+	enet_uint32 enet_peer_get_lastsendtime(const ENetPeer* peer) {
+		return peer->lastSendTime;
+	}
+
+	enet_uint32 enet_peer_get_lastreceivetime(const ENetPeer* peer) {
+		return peer->lastReceiveTime;
+	}
+
+	enet_uint64 enet_peer_get_packets_sent(const ENetPeer* peer) {
+		return peer->totalPacketsSent;
+	}
+
+	enet_uint64 enet_peer_get_packets_lost(const ENetPeer* peer) {
+		return peer->totalPacketsLost;
+	}
+
+	enet_uint64 enet_peer_get_bytes_sent(const ENetPeer* peer) {
+		return peer->totalDataSent;
+	}
+
+	enet_uint64 enet_peer_get_bytes_received(const ENetPeer* peer) {
+		return peer->totalDataReceived;
+	}
+
+	void* enet_peer_get_data(const ENetPeer* peer) {
+		return (void*)peer->data;
+	}
+
+	void enet_peer_set_data(ENetPeer* peer, const void* data) {
+		peer->data = (enet_uint32*)data;
+	}
+
+// =======================================================================//
+// !
+// ! Platform Specific (Unix)
+// !
+// =======================================================================//
+
+	#ifndef _WIN32
+		int enet_initialize(void) {
+			return 0;
+		}
+
+		void enet_deinitialize(void) { }
+
+		enet_uint64 enet_host_random_seed(void) {
+			return (enet_uint64)time(NULL);
+		}
+
+		int enet_address_set_host_ip(ENetAddress* address, const char* name) {
+			if (!inet_pton(AF_INET6, name, &address->host))
+				return -1;
+
+			return 0;
+		}
+
+		int enet_address_set_host(ENetAddress* address, const char* name) {
+			struct addrinfo hints, * resultList = NULL, * result = NULL;
+
+			memset(&hints, 0, sizeof(hints));
+
+			hints.ai_family = AF_UNSPEC;
+
+			if (getaddrinfo(name, NULL, &hints, &resultList) != 0)
+				return -1;
+
+			for (result = resultList; result != NULL; result = result->ai_next) {
+				if (result->ai_addr != NULL && result->ai_addrlen >= sizeof(struct sockaddr_in)) {
+					if (result->ai_family == AF_INET) {
+						struct sockaddr_in* sin = (struct sockaddr_in*)result->ai_addr;
+
+						((enet_uint32*)&address->host.s6_addr)[0] = 0;
+						((enet_uint32*)&address->host.s6_addr)[1] = 0;
+						((enet_uint32*)&address->host.s6_addr)[2] = ENET_HOST_TO_NET_32(0xFFFF);
+						((enet_uint32*)&address->host.s6_addr)[3] = sin->sin_addr.s_addr;
+
+						freeaddrinfo(resultList);
+
+						return 0;
+					} else if (result->ai_family == AF_INET6) {
+						struct sockaddr_in6* sin = (struct sockaddr_in6*)result->ai_addr;
+
+						address->host  = sin->sin6_addr;
+						address->scope = sin->sin6_scope_id;
+
+						freeaddrinfo(resultList);
+
+						return 0;
+					}
+				}
+			}
+
+			if (resultList != NULL)
+				freeaddrinfo(resultList);
+
+			return enet_address_set_host_ip(address, name);
+		}
+
+		int enet_address_get_host_ip(const ENetAddress* address, char* name, size_t nameLength) {
+			if (inet_ntop(AF_INET6, &address->host, name, nameLength) == NULL)
+				return -1;
+
+			return 0;
+		}
+
+		int enet_address_get_host(const ENetAddress* address, char* name, size_t nameLength) {
+			struct sockaddr_in6 sin;
+			int err;
+
+			memset(&sin, 0, sizeof(struct sockaddr_in6));
+
+			sin.sin6_family   = AF_INET6;
+			sin.sin6_port     = ENET_HOST_TO_NET_16(address->port);
+			sin.sin6_addr     = address->host;
+			sin.sin6_scope_id = address->scope;
+
+			err = getnameinfo((struct sockaddr*)&sin, sizeof(sin), name, nameLength, NULL, 0, NI_NAMEREQD);
+
+			if (!err) {
+				if (name != NULL && nameLength > 0 && !memchr(name, '\0', nameLength))
+					return -1;
+
+				return 0;
+			}
+
+			if (err != EAI_NONAME)
+				return -1;
+
+			return enet_address_get_host_ip(address, name, nameLength);
+		}
+
+		int enet_socket_bind(ENetSocket socket, const ENetAddress* address) {
+			struct sockaddr_in6 sin;
+
+			memset(&sin, 0, sizeof(struct sockaddr_in6));
+
+			sin.sin6_family = AF_INET6;
+
+			if (address != NULL) {
+				sin.sin6_port     = ENET_HOST_TO_NET_16(address->port);
+				sin.sin6_addr     = address->host;
+				sin.sin6_scope_id = address->scope;
+			} else {
+				sin.sin6_port     = 0;
+				sin.sin6_addr     = ENET_HOST_ANY;
+				sin.sin6_scope_id = 0;
+			}
+
+			return bind(socket, (struct sockaddr*)&sin, sizeof(struct sockaddr_in6));
+		}
+
+		int enet_socket_get_address(ENetSocket socket, ENetAddress* address) {
+			struct sockaddr_in6 sin;
+
+			socklen_t sinLength = sizeof(struct sockaddr_in6);
+
+			if (getsockname(socket, (struct sockaddr*)&sin, &sinLength) == -1)
+				return -1;
+
+			address->host  = sin.sin6_addr;
+			address->port  = ENET_NET_TO_HOST_16(sin.sin6_port);
+			address->scope = sin.sin6_scope_id;
+
+			return 0;
+		}
+
+		int enet_socket_listen(ENetSocket socket, int backlog) {
+			return listen(socket, backlog < 0 ? SOMAXCONN : backlog);
+		}
+
+		ENetSocket enet_socket_create(ENetSocketType type) {
+			return socket(PF_INET6, type == ENET_SOCKET_TYPE_DATAGRAM ? SOCK_DGRAM : SOCK_STREAM, 0);
+		}
+
+		int enet_socket_set_option(ENetSocket socket, ENetSocketOption option, int value) {
+			int result = -1;
+
+			switch (option) {
+				case ENET_SOCKOPT_NONBLOCK:
+					result = fcntl(socket, F_SETFL, (value ? O_NONBLOCK : 0) | (fcntl(socket, F_GETFL) & ~O_NONBLOCK));
+
+					break;
+
+				case ENET_SOCKOPT_BROADCAST:
+					result = setsockopt(socket, SOL_SOCKET, SO_BROADCAST, (char*)&value, sizeof(int));
+
+					break;
+
+				case ENET_SOCKOPT_REUSEADDR:
+					result = setsockopt(socket, SOL_SOCKET, SO_REUSEADDR, (char*)&value, sizeof(int));
+
+					break;
+
+				case ENET_SOCKOPT_RCVBUF:
+					result = setsockopt(socket, SOL_SOCKET, SO_RCVBUF, (char*)&value, sizeof(int));
+
+					break;
+
+				case ENET_SOCKOPT_SNDBUF:
+					result = setsockopt(socket, SOL_SOCKET, SO_SNDBUF, (char*)&value, sizeof(int));
+
+					break;
+
+				case ENET_SOCKOPT_RCVTIMEO: {
+					struct timeval timeVal;
+
+					timeVal.tv_sec  = value / 1000;
+					timeVal.tv_usec = (value % 1000) * 1000;
+					result = setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeVal, sizeof(struct timeval));
+
+					break;
+				}
+
+				case ENET_SOCKOPT_SNDTIMEO: {
+					struct timeval timeVal;
+
+					timeVal.tv_sec  = value / 1000;
+					timeVal.tv_usec = (value % 1000) * 1000;
+					result = setsockopt(socket, SOL_SOCKET, SO_SNDTIMEO, (char*)&timeVal, sizeof(struct timeval));
+
+					break;
+				}
+
+				case ENET_SOCKOPT_NODELAY:
+					result = setsockopt(socket, IPPROTO_TCP, TCP_NODELAY, (char*)&value, sizeof(int));
+
+					break;
+
+				case ENET_SOCKOPT_IPV6_V6ONLY:
+					result = setsockopt(socket, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&value, sizeof(int));
+
+					break;
+
+				default:
+					break;
+			}
+
+			return result == -1 ? -1 : 0;
+		}
+
+		int enet_socket_get_option(ENetSocket socket, ENetSocketOption option, int* value) {
+			int result = -1;
+			socklen_t len;
+
+			switch (option) {
+				case ENET_SOCKOPT_ERROR:
+					len    = sizeof(int);
+					result = getsockopt(socket, SOL_SOCKET, SO_ERROR, value, &len);
+
+					break;
+
+				default:
+					break;
+			}
+
+			return result == -1 ? -1 : 0;
+		}
+
+		int enet_socket_connect(ENetSocket socket, const ENetAddress* address) {
+			struct sockaddr_in6 sin;
+			int result;
+
+			memset(&sin, 0, sizeof(struct sockaddr_in6));
+
+			sin.sin6_family   = AF_INET6;
+			sin.sin6_port     = ENET_HOST_TO_NET_16(address->port);
+			sin.sin6_addr     = address->host;
+			sin.sin6_scope_id = address->scope;
+			result = connect(socket, (struct sockaddr*)&sin, sizeof(struct sockaddr_in6));
+
+			if (result == -1 && errno == EINPROGRESS)
+				return 0;
+
+			return result;
+		}
+
+		ENetSocket enet_socket_accept(ENetSocket socket, ENetAddress* address) {
+			int result;
+			struct sockaddr_in6 sin;
+			socklen_t sinLength = sizeof(struct sockaddr_in6);
+
+			result = accept(socket, address != NULL ? (struct sockaddr*)&sin : NULL, address != NULL ? &sinLength : NULL);
+
+			if (result == -1)
+				return ENET_SOCKET_NULL;
+
+			if (address != NULL) {
+				address->host  = sin.sin6_addr;
+				address->port  = ENET_NET_TO_HOST_16(sin.sin6_port);
+				address->scope = sin.sin6_scope_id;
+			}
+
+			return result;
+		}
+
+		int enet_socket_shutdown(ENetSocket socket, ENetSocketShutdown how) {
+			return shutdown(socket, (int)how);
+		}
+
+		void enet_socket_destroy(ENetSocket socket) {
+			if (socket != -1)
+				close(socket);
+		}
+
+		int enet_socket_send(ENetSocket socket, const ENetAddress* address, const ENetBuffer* buffers, size_t bufferCount) {
+			struct msghdr msgHdr;
+			struct sockaddr_in6 sin;
+			int sentLength;
+
+			memset(&msgHdr, 0, sizeof(struct msghdr));
+
+			if (address != NULL) {
+				memset(&sin, 0, sizeof(struct sockaddr_in6));
+
+				sin.sin6_family    = AF_INET6;
+				sin.sin6_port      = ENET_HOST_TO_NET_16(address->port);
+				sin.sin6_addr      = address->host;
+				sin.sin6_scope_id  = address->scope;
+				msgHdr.msg_name    = &sin;
+				msgHdr.msg_namelen = sizeof(struct sockaddr_in6);
+			}
+
+			msgHdr.msg_iov    = (struct iovec*)buffers;
+			msgHdr.msg_iovlen = bufferCount;
+			sentLength = sendmsg(socket, &msgHdr, MSG_NOSIGNAL);
+
+			if (sentLength == -1) {
+				if (errno == EWOULDBLOCK)
+					return 0;
+
+				return -1;
+			}
+
+			return sentLength;
+		}
+
+		int enet_socket_receive(ENetSocket socket, ENetAddress* address, ENetBuffer* buffers, size_t bufferCount) {
+			struct msghdr msgHdr;
+			struct sockaddr_in6 sin;
+			int recvLength;
+
+			memset(&msgHdr, 0, sizeof(struct msghdr));
+
+			if (address != NULL) {
+				msgHdr.msg_name    = &sin;
+				msgHdr.msg_namelen = sizeof(struct sockaddr_in6);
+			}
+
+			msgHdr.msg_iov    = (struct iovec*)buffers;
+			msgHdr.msg_iovlen = bufferCount;
+			recvLength = recvmsg(socket, &msgHdr, MSG_NOSIGNAL);
+
+			if (recvLength == -1) {
+				if (errno == EWOULDBLOCK)
+					return 0;
+
+				return -1;
+			}
+
+			if (msgHdr.msg_flags & MSG_TRUNC)
+				return -1;
+
+			if (address != NULL) {
+				address->host  = sin.sin6_addr;
+				address->port  = ENET_NET_TO_HOST_16(sin.sin6_port);
+				address->scope = sin.sin6_scope_id;
+			}
+
+			return recvLength;
+		}
+
+		int enet_socket_set_select(ENetSocket maxSocket, ENetSocketSet* readSet, ENetSocketSet* writeSet, enet_uint32 timeout) {
+			struct timeval timeVal;
+
+			timeVal.tv_sec  = timeout / 1000;
+			timeVal.tv_usec = (timeout % 1000) * 1000;
+
+			return select(maxSocket + 1, readSet, writeSet, NULL, &timeVal);
+		}
+
+		int enet_socket_wait(ENetSocket socket, enet_uint32* condition, enet_uint64 timeout) {
+			struct pollfd pollSocket;
+			int pollCount;
+
+			pollSocket.fd     = socket;
+			pollSocket.events = 0;
+
+			if (*condition & ENET_SOCKET_WAIT_SEND)
+				pollSocket.events |= POLLOUT;
+
+			if (*condition & ENET_SOCKET_WAIT_RECEIVE)
+				pollSocket.events |= POLLIN;
+
+			pollCount = poll(&pollSocket, 1, timeout);
+
+			if (pollCount < 0) {
+				if (errno == EINTR && *condition & ENET_SOCKET_WAIT_INTERRUPT) {
+					*condition = ENET_SOCKET_WAIT_INTERRUPT;
+
+					return 0;
+				}
+
+				return -1;
+			}
+
+			*condition = ENET_SOCKET_WAIT_NONE;
+
+			if (pollCount == 0)
+				return 0;
+
+			if (pollSocket.revents & POLLOUT)
+				*condition |= ENET_SOCKET_WAIT_SEND;
+
+			if (pollSocket.revents & POLLIN)
+				*condition |= ENET_SOCKET_WAIT_RECEIVE;
+
+			return 0;
+		}
+	#endif
+
+// =======================================================================//
+// !
+// ! Platform Specific (Win)
+// !
+// =======================================================================//
+
+	#ifdef _WIN32
+		int enet_initialize(void) {
+			WORD versionRequested = MAKEWORD(1, 1);
+			WSADATA wsaData;
+
+			if (WSAStartup(versionRequested, &wsaData))
+				return -1;
+
+			if (LOBYTE(wsaData.wVersion) != 1 || HIBYTE(wsaData.wVersion) != 1) {
+				WSACleanup();
+
+				return -1;
+			}
+
+			timeBeginPeriod(1);
+
+			return 0;
+		}
+
+		void enet_deinitialize(void) {
+			timeEndPeriod(1);
+			WSACleanup();
+		}
+
+		enet_uint64 enet_host_random_seed(void) {
+			return (enet_uint64)timeGetTime();
+		}
+
+		int enet_address_set_host_ip(ENetAddress* address, const char* name) {
+			enet_uint8 vals[4] = { 0, 0, 0, 0 };
+			int i;
+
+			for (i = 0; i < 4; ++i) {
+				const char* next = name + 1;
+
+				if (*name != '0') {
+					long val = strtol(name, (char**)&next, 10);
+
+					if (val < 0 || val > 255 || next == name || next - name > 3)
+						return -1;
+
+					vals[i] = (enet_uint8)val;
+				}
+
+				if (*next != (i < 3 ? '.' : '\0'))
+					return -1;
+
+				name = next + 1;
+			}
+
+			memcpy(&address->host, vals, sizeof(enet_uint32));
+
+			return 0;
+		}
+
+		int enet_address_set_host(ENetAddress* address, const char* name) {
+			struct hostent* hostEntry = NULL;
+
+			hostEntry = gethostbyname(name);
+
+			if (hostEntry == NULL || hostEntry->h_addrtype != AF_INET) {
+				if (!inet_pton(AF_INET6, name, &address->host))
+					return -1;
+
+				return 0;
+			}
+
+			((enet_uint32*)&address->host.s6_addr)[0] = 0;
+			((enet_uint32*)&address->host.s6_addr)[1] = 0;
+			((enet_uint32*)&address->host.s6_addr)[2] = ENET_HOST_TO_NET_32(0xFFFF);
+			((enet_uint32*)&address->host.s6_addr)[3] = *(enet_uint32*)hostEntry->h_addr_list[0];
+
+			return 0;
+		}
+
+		int enet_address_get_host_ip(const ENetAddress* address, char* name, size_t nameLength) {
+			if (inet_ntop(AF_INET6, (PVOID)&address->host, name, nameLength) == NULL)
+				return -1;
+
+			return 0;
+		}
+
+		int enet_address_get_host(const ENetAddress* address, char* name, size_t nameLength) {
+			struct in6_addr in;
+			struct hostent* hostEntry = NULL;
+
+			in = address->host;
+			hostEntry = gethostbyaddr((char*)&in, sizeof(struct in6_addr), AF_INET6);
+
+			if (hostEntry == NULL) {
+				return enet_address_get_host_ip(address, name, nameLength);
+			} else {
+				size_t hostLen = strlen(hostEntry->h_name);
+
+				if (hostLen >= nameLength)
+					return -1;
+
+				memcpy(name, hostEntry->h_name, hostLen + 1);
+			}
+
+			return 0;
+		}
+
+		int enet_socket_bind(ENetSocket socket, const ENetAddress* address) {
+			struct sockaddr_in6 sin;
+			memset(&sin, 0, sizeof(struct sockaddr_in6));
+
+			sin.sin6_family = AF_INET6;
+
+			if (address != NULL) {
+				sin.sin6_port     = ENET_HOST_TO_NET_16(address->port);
+				sin.sin6_addr     = address->host;
+				sin.sin6_scope_id = address->scope;
+			} else {
+				sin.sin6_port     = 0;
+				sin.sin6_addr     = in6addr_any;
+				sin.sin6_scope_id = 0;
+			}
+
+			return bind(socket, (struct sockaddr*)&sin, sizeof(struct sockaddr_in6)) == SOCKET_ERROR ? -1 : 0;
+		}
+
+		int enet_socket_get_address(ENetSocket socket, ENetAddress* address) {
+			struct sockaddr_in6 sin;
+			int sinLength = sizeof(struct sockaddr_in6);
+
+			if (getsockname(socket, (struct sockaddr*)&sin, &sinLength) == -1)
+				return -1;
+
+			address->host  = sin.sin6_addr;
+			address->port  = ENET_NET_TO_HOST_16(sin.sin6_port);
+			address->scope = sin.sin6_scope_id;
+
+			return 0;
+		}
+
+		int enet_socket_listen(ENetSocket socket, int backlog) {
+			return listen(socket, backlog < 0 ? SOMAXCONN : backlog) == SOCKET_ERROR ? -1 : 0;
+		}
+
+		ENetSocket enet_socket_create(ENetSocketType type) {
+			return socket(PF_INET6, type == ENET_SOCKET_TYPE_DATAGRAM ? SOCK_DGRAM : SOCK_STREAM, 0);
+		}
+
+		int enet_socket_set_option(ENetSocket socket, ENetSocketOption option, int value) {
+			int result = SOCKET_ERROR;
+
+			switch (option) {
+				case ENET_SOCKOPT_NONBLOCK: {
+					u_long nonBlocking = (u_long)value;
+
+					result = ioctlsocket(socket, FIONBIO, &nonBlocking);
+
+					break;
+				}
+
+				case ENET_SOCKOPT_BROADCAST:
+					result = setsockopt(socket, SOL_SOCKET, SO_BROADCAST, (char*)&value, sizeof(int));
+
+					break;
+
+				case ENET_SOCKOPT_REUSEADDR:
+					result = setsockopt(socket, SOL_SOCKET, SO_REUSEADDR, (char*)&value, sizeof(int));
+
+					break;
+
+				case ENET_SOCKOPT_RCVBUF:
+					result = setsockopt(socket, SOL_SOCKET, SO_RCVBUF, (char*)&value, sizeof(int));
+
+					break;
+
+				case ENET_SOCKOPT_SNDBUF:
+					result = setsockopt(socket, SOL_SOCKET, SO_SNDBUF, (char*)&value, sizeof(int));
+
+					break;
+
+				case ENET_SOCKOPT_RCVTIMEO:
+					result = setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (char*)&value, sizeof(int));
+
+					break;
+
+				case ENET_SOCKOPT_SNDTIMEO:
+					result = setsockopt(socket, SOL_SOCKET, SO_SNDTIMEO, (char*)&value, sizeof(int));
+
+					break;
+
+				case ENET_SOCKOPT_NODELAY:
+					result = setsockopt(socket, IPPROTO_TCP, TCP_NODELAY, (char*)&value, sizeof(int));
+
+					break;
+
+				case ENET_SOCKOPT_IPV6_V6ONLY:
+					result = setsockopt(socket, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&value, sizeof(int));
+
+					break;
+
+				default:
+					break;
+			}
+
+			return result == SOCKET_ERROR ? -1 : 0;
+		}
+
+		int enet_socket_get_option(ENetSocket socket, ENetSocketOption option, int* value) {
+			int result = SOCKET_ERROR, len;
+
+			switch (option) {
+				case ENET_SOCKOPT_ERROR:
+					len    = sizeof(int);
+					result = getsockopt(socket, SOL_SOCKET, SO_ERROR, (char*)value, &len);
+
+					break;
+
+				default:
+					break;
+			}
+
+			return result == SOCKET_ERROR ? -1 : 0;
+		}
+
+		int enet_socket_connect(ENetSocket socket, const ENetAddress* address) {
+			struct sockaddr_in6 sin;
+			int result;
+
+			memset(&sin, 0, sizeof(struct sockaddr_in6));
+
+			sin.sin6_family   = AF_INET6;
+			sin.sin6_port     = ENET_HOST_TO_NET_16(address->port);
+			sin.sin6_addr     = address->host;
+			sin.sin6_scope_id = address->scope;
+			result = connect(socket, (struct sockaddr*)&sin, sizeof(struct sockaddr_in6));
+
+			if (result == SOCKET_ERROR && WSAGetLastError() != WSAEWOULDBLOCK)
+				return -1;
+
+			return 0;
+		}
+
+		ENetSocket enet_socket_accept(ENetSocket socket, ENetAddress* address) {
+			SOCKET result;
+			struct sockaddr_in6 sin;
+			int sinLength = sizeof(struct sockaddr_in6);
+
+			result = accept(socket, address != NULL ? (struct sockaddr*)&sin : NULL, address != NULL ? &sinLength : NULL);
+
+			if (result == INVALID_SOCKET)
+				return ENET_SOCKET_NULL;
+
+			if (address != NULL) {
+				address->host  = sin.sin6_addr;
+				address->port  = ENET_NET_TO_HOST_16(sin.sin6_port);
+				address->scope = sin.sin6_scope_id;
+			}
+
+			return result;
+		}
+
+		int enet_socket_shutdown(ENetSocket socket, ENetSocketShutdown how) {
+			return shutdown(socket, (int)how) == SOCKET_ERROR ? -1 : 0;
+		}
+
+		void enet_socket_destroy(ENetSocket socket) {
+			if (socket != INVALID_SOCKET)
+				closesocket(socket);
+		}
+
+		int enet_socket_send(ENetSocket socket, const ENetAddress* address, const ENetBuffer* buffers, size_t bufferCount) {
+			struct sockaddr_in6 sin;
+			DWORD sentLength;
+
+			if (address != NULL) {
+				memset(&sin, 0, sizeof(struct sockaddr_in6));
+
+				sin.sin6_family   = AF_INET6;
+				sin.sin6_port     = ENET_HOST_TO_NET_16(address->port);
+				sin.sin6_addr     = address->host;
+				sin.sin6_scope_id = address->scope;
+			}
+
+			if (WSASendTo(socket, (LPWSABUF)buffers, (DWORD)bufferCount, &sentLength, 0, address != NULL ? (struct sockaddr*)&sin : NULL, address != NULL ? sizeof(struct sockaddr_in6) : 0, NULL, NULL) == SOCKET_ERROR)
+				return (WSAGetLastError() == WSAEWOULDBLOCK) ? 0 : 1;
+
+			return (int)sentLength;
+		}
+
+		int enet_socket_receive(ENetSocket socket, ENetAddress* address, ENetBuffer* buffers, size_t bufferCount) {
+			INT sinLength = sizeof(struct sockaddr_in6);
+			DWORD flags   = 0, recvLength;
+			struct sockaddr_in6 sin;
+
+			if (WSARecvFrom(socket, (LPWSABUF)buffers, (DWORD)bufferCount, &recvLength, &flags, address != NULL ? (struct sockaddr*)&sin : NULL, address != NULL ? &sinLength : NULL, NULL, NULL) == SOCKET_ERROR) {
+				switch (WSAGetLastError()) {
+					case WSAEWOULDBLOCK:
+					case WSAECONNRESET:
+						return 0;
+				}
+
+				return -1;
+			}
+
+			if (flags & MSG_PARTIAL)
+				return -1;
+
+			if (address != NULL) {
+				address->host  = sin.sin6_addr;
+				address->port  = ENET_NET_TO_HOST_16(sin.sin6_port);
+				address->scope = sin.sin6_scope_id;
+			}
+
+			return (int)recvLength;
+		}
+
+		int enet_socket_set_select(ENetSocket maxSocket, ENetSocketSet* readSet, ENetSocketSet* writeSet, enet_uint32 timeout) {
+			struct timeval timeVal;
+
+			timeVal.tv_sec  = timeout / 1000;
+			timeVal.tv_usec = (timeout % 1000) * 1000;
+
+			return select(maxSocket + 1, readSet, writeSet, NULL, &timeVal);
+		}
+
+		int enet_socket_wait(ENetSocket socket, enet_uint32* condition, enet_uint64 timeout) {
+			fd_set readSet, writeSet;
+			struct timeval timeVal;
+			int selectCount;
+
+			timeVal.tv_sec  = timeout / 1000;
+			timeVal.tv_usec = (timeout % 1000) * 1000;
+
+			FD_ZERO(&readSet);
+			FD_ZERO(&writeSet);
+
+			if (*condition & ENET_SOCKET_WAIT_SEND)
+				FD_SET(socket, &writeSet);
+
+			if (*condition & ENET_SOCKET_WAIT_RECEIVE)
+				FD_SET(socket, &readSet);
+
+			selectCount = select(socket + 1, &readSet, &writeSet, NULL, &timeVal);
+
+			if (selectCount < 0)
+				return -1;
+
+			*condition = ENET_SOCKET_WAIT_NONE;
+
+			if (selectCount == 0)
+				return 0;
+
+			if (FD_ISSET(socket, &writeSet))
+				*condition |= ENET_SOCKET_WAIT_SEND;
+
+			if (FD_ISSET(socket, &readSet))
+				*condition |= ENET_SOCKET_WAIT_RECEIVE;
+
+			return 0;
+		}
+	#endif
+
+#ifdef __cplusplus
+}
+#endif
+#endif
+#endif

+ 16 - 0
Source/Native/jni/Android.mk

@@ -0,0 +1,16 @@
+LOCAL_PATH := $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_MODULE    := libenet
+LOCAL_SRC_FILES := ..\enet.c
+
+ifdef ENET_LZ4
+	LOCAL_CFLAGS += -DENET_LZ4
+	LOCAL_SRC_FILES += ..\lz4\lz4.c
+endif
+
+ifdef ENET_STATIC
+	include $(BUILD_STATIC_LIBRARY)
+else
+	include $(BUILD_SHARED_LIBRARY)
+endif

+ 3 - 0
Source/Native/jni/Application.mk

@@ -0,0 +1,3 @@
+APP_PLATFORM := android-16
+APP_OPTIM := release
+APP_MODULES := libenet

+ 1969 - 0
Source/Native/lz4/lz4.c

@@ -0,0 +1,1969 @@
+/*
+   LZ4 - Fast LZ compression algorithm
+   Copyright (C) 2011-present, Yann Collet.
+
+   BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
+
+   Redistribution and use in source and binary forms, with or without
+   modification, are permitted provided that the following conditions are
+   met:
+
+       * Redistributions of source code must retain the above copyright
+   notice, this list of conditions and the following disclaimer.
+       * Redistributions in binary form must reproduce the above
+   copyright notice, this list of conditions and the following disclaimer
+   in the documentation and/or other materials provided with the
+   distribution.
+
+   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+   You can contact the author at :
+    - LZ4 homepage : http://www.lz4.org
+    - LZ4 source repository : https://github.com/lz4/lz4
+*/
+
+
+/*-************************************
+*  Tuning parameters
+**************************************/
+/*
+ * LZ4_HEAPMODE :
+ * Select how default compression functions will allocate memory for their hash table,
+ * in memory stack (0:default, fastest), or in memory heap (1:requires malloc()).
+ */
+#ifndef LZ4_HEAPMODE
+#  define LZ4_HEAPMODE 0
+#endif
+
+/*
+ * ACCELERATION_DEFAULT :
+ * Select "acceleration" for LZ4_compress_fast() when parameter value <= 0
+ */
+#define ACCELERATION_DEFAULT 1
+
+
+/*-************************************
+*  CPU Feature Detection
+**************************************/
+/* LZ4_FORCE_MEMORY_ACCESS
+ * By default, access to unaligned memory is controlled by `memcpy()`, which is safe and portable.
+ * Unfortunately, on some target/compiler combinations, the generated assembly is sub-optimal.
+ * The below switch allow to select different access method for improved performance.
+ * Method 0 (default) : use `memcpy()`. Safe and portable.
+ * Method 1 : `__packed` statement. It depends on compiler extension (ie, not portable).
+ *            This method is safe if your compiler supports it, and *generally* as fast or faster than `memcpy`.
+ * Method 2 : direct access. This method is portable but violate C standard.
+ *            It can generate buggy code on targets which assembly generation depends on alignment.
+ *            But in some circumstances, it's the only known way to get the most performance (ie GCC + ARMv6)
+ * See https://fastcompression.blogspot.fr/2015/08/accessing-unaligned-memory.html for details.
+ * Prefer these methods in priority order (0 > 1 > 2)
+ */
+#ifndef LZ4_FORCE_MEMORY_ACCESS   /* can be defined externally */
+#  if defined(__GNUC__) && \
+  ( defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) || defined(__ARM_ARCH_6K__) \
+  || defined(__ARM_ARCH_6Z__) || defined(__ARM_ARCH_6ZK__) || defined(__ARM_ARCH_6T2__) )
+#    define LZ4_FORCE_MEMORY_ACCESS 2
+#  elif (defined(__INTEL_COMPILER) && !defined(_WIN32)) || defined(__GNUC__)
+#    define LZ4_FORCE_MEMORY_ACCESS 1
+#  endif
+#endif
+
+/*
+ * LZ4_FORCE_SW_BITCOUNT
+ * Define this parameter if your target system or compiler does not support hardware bit count
+ */
+#if defined(_MSC_VER) && defined(_WIN32_WCE)   /* Visual Studio for WinCE doesn't support Hardware bit count */
+#  define LZ4_FORCE_SW_BITCOUNT
+#endif
+
+
+
+/*-************************************
+*  Dependency
+**************************************/
+#define LZ4_STATIC_LINKING_ONLY
+#define LZ4_DISABLE_DEPRECATE_WARNINGS /* due to LZ4_decompress_safe_withPrefix64k */
+#include "lz4.h"
+/* see also "memory routines" below */
+
+
+/*-************************************
+*  Compiler Options
+**************************************/
+#ifdef _MSC_VER    /* Visual Studio */
+#  include <intrin.h>
+#  pragma warning(disable : 4127)        /* disable: C4127: conditional expression is constant */
+#  pragma warning(disable : 4293)        /* disable: C4293: too large shift (32-bits) */
+#endif  /* _MSC_VER */
+
+#ifndef LZ4_FORCE_INLINE
+#  ifdef _MSC_VER    /* Visual Studio */
+#    define LZ4_FORCE_INLINE static __forceinline
+#  else
+#    if defined (__cplusplus) || defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L   /* C99 */
+#      ifdef __GNUC__
+#        define LZ4_FORCE_INLINE static inline __attribute__((always_inline))
+#      else
+#        define LZ4_FORCE_INLINE static inline
+#      endif
+#    else
+#      define LZ4_FORCE_INLINE static
+#    endif /* __STDC_VERSION__ */
+#  endif  /* _MSC_VER */
+#endif /* LZ4_FORCE_INLINE */
+
+/* LZ4_FORCE_O2_GCC_PPC64LE and LZ4_FORCE_O2_INLINE_GCC_PPC64LE
+ * Gcc on ppc64le generates an unrolled SIMDized loop for LZ4_wildCopy,
+ * together with a simple 8-byte copy loop as a fall-back path.
+ * However, this optimization hurts the decompression speed by >30%,
+ * because the execution does not go to the optimized loop
+ * for typical compressible data, and all of the preamble checks
+ * before going to the fall-back path become useless overhead.
+ * This optimization happens only with the -O3 flag, and -O2 generates
+ * a simple 8-byte copy loop.
+ * With gcc on ppc64le, all of the LZ4_decompress_* and LZ4_wildCopy
+ * functions are annotated with __attribute__((optimize("O2"))),
+ * and also LZ4_wildCopy is forcibly inlined, so that the O2 attribute
+ * of LZ4_wildCopy does not affect the compression speed.
+ */
+#if defined(__PPC64__) && defined(__LITTLE_ENDIAN__) && defined(__GNUC__)
+#  define LZ4_FORCE_O2_GCC_PPC64LE __attribute__((optimize("O2")))
+#  define LZ4_FORCE_O2_INLINE_GCC_PPC64LE __attribute__((optimize("O2"))) LZ4_FORCE_INLINE
+#else
+#  define LZ4_FORCE_O2_GCC_PPC64LE
+#  define LZ4_FORCE_O2_INLINE_GCC_PPC64LE static
+#endif
+
+#if (defined(__GNUC__) && (__GNUC__ >= 3)) || (defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 800)) || defined(__clang__)
+#  define expect(expr,value)    (__builtin_expect ((expr),(value)) )
+#else
+#  define expect(expr,value)    (expr)
+#endif
+
+#ifndef likely
+#define likely(expr)     expect((expr) != 0, 1)
+#endif
+#ifndef unlikely
+#define unlikely(expr)   expect((expr) != 0, 0)
+#endif
+
+
+/*-************************************
+*  Memory routines
+**************************************/
+#include <stdlib.h>   /* malloc, calloc, free */
+#define ALLOC(s)          malloc(s)
+#define ALLOC_AND_ZERO(s) calloc(1,s)
+#define FREEMEM(p)        free(p)
+#include <string.h>   /* memset, memcpy */
+#define MEM_INIT(p,v,s)   memset((p),(v),(s))
+
+
+/*-************************************
+*  Basic Types
+**************************************/
+#if defined(__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */)
+# include <stdint.h>
+  typedef  uint8_t BYTE;
+  typedef uint16_t U16;
+  typedef uint32_t U32;
+  typedef  int32_t S32;
+  typedef uint64_t U64;
+  typedef uintptr_t uptrval;
+#else
+  typedef unsigned char       BYTE;
+  typedef unsigned short      U16;
+  typedef unsigned int        U32;
+  typedef   signed int        S32;
+  typedef unsigned long long  U64;
+  typedef size_t              uptrval;   /* generally true, except OpenVMS-64 */
+#endif
+
+#if defined(__x86_64__)
+  typedef U64    reg_t;   /* 64-bits in x32 mode */
+#else
+  typedef size_t reg_t;   /* 32-bits in x32 mode */
+#endif
+
+/*-************************************
+*  Reading and writing into memory
+**************************************/
+static unsigned LZ4_isLittleEndian(void)
+{
+    const union { U32 u; BYTE c[4]; } one = { 1 };   /* don't use static : performance detrimental */
+    return one.c[0];
+}
+
+
+#if defined(LZ4_FORCE_MEMORY_ACCESS) && (LZ4_FORCE_MEMORY_ACCESS==2)
+/* lie to the compiler about data alignment; use with caution */
+
+static U16 LZ4_read16(const void* memPtr) { return *(const U16*) memPtr; }
+static U32 LZ4_read32(const void* memPtr) { return *(const U32*) memPtr; }
+static reg_t LZ4_read_ARCH(const void* memPtr) { return *(const reg_t*) memPtr; }
+
+static void LZ4_write16(void* memPtr, U16 value) { *(U16*)memPtr = value; }
+static void LZ4_write32(void* memPtr, U32 value) { *(U32*)memPtr = value; }
+
+#elif defined(LZ4_FORCE_MEMORY_ACCESS) && (LZ4_FORCE_MEMORY_ACCESS==1)
+
+/* __pack instructions are safer, but compiler specific, hence potentially problematic for some compilers */
+/* currently only defined for gcc and icc */
+typedef union { U16 u16; U32 u32; reg_t uArch; } __attribute__((packed)) unalign;
+
+static U16 LZ4_read16(const void* ptr) { return ((const unalign*)ptr)->u16; }
+static U32 LZ4_read32(const void* ptr) { return ((const unalign*)ptr)->u32; }
+static reg_t LZ4_read_ARCH(const void* ptr) { return ((const unalign*)ptr)->uArch; }
+
+static void LZ4_write16(void* memPtr, U16 value) { ((unalign*)memPtr)->u16 = value; }
+static void LZ4_write32(void* memPtr, U32 value) { ((unalign*)memPtr)->u32 = value; }
+
+#else  /* safe and portable access through memcpy() */
+
+static U16 LZ4_read16(const void* memPtr)
+{
+    U16 val; memcpy(&val, memPtr, sizeof(val)); return val;
+}
+
+static U32 LZ4_read32(const void* memPtr)
+{
+    U32 val; memcpy(&val, memPtr, sizeof(val)); return val;
+}
+
+static reg_t LZ4_read_ARCH(const void* memPtr)
+{
+    reg_t val; memcpy(&val, memPtr, sizeof(val)); return val;
+}
+
+static void LZ4_write16(void* memPtr, U16 value)
+{
+    memcpy(memPtr, &value, sizeof(value));
+}
+
+static void LZ4_write32(void* memPtr, U32 value)
+{
+    memcpy(memPtr, &value, sizeof(value));
+}
+
+#endif /* LZ4_FORCE_MEMORY_ACCESS */
+
+
+static U16 LZ4_readLE16(const void* memPtr)
+{
+    if (LZ4_isLittleEndian()) {
+        return LZ4_read16(memPtr);
+    } else {
+        const BYTE* p = (const BYTE*)memPtr;
+        return (U16)((U16)p[0] + (p[1]<<8));
+    }
+}
+
+static void LZ4_writeLE16(void* memPtr, U16 value)
+{
+    if (LZ4_isLittleEndian()) {
+        LZ4_write16(memPtr, value);
+    } else {
+        BYTE* p = (BYTE*)memPtr;
+        p[0] = (BYTE) value;
+        p[1] = (BYTE)(value>>8);
+    }
+}
+
+/* customized variant of memcpy, which can overwrite up to 8 bytes beyond dstEnd */
+LZ4_FORCE_O2_INLINE_GCC_PPC64LE
+void LZ4_wildCopy(void* dstPtr, const void* srcPtr, void* dstEnd)
+{
+    BYTE* d = (BYTE*)dstPtr;
+    const BYTE* s = (const BYTE*)srcPtr;
+    BYTE* const e = (BYTE*)dstEnd;
+
+    do { memcpy(d,s,8); d+=8; s+=8; } while (d<e);
+}
+
+
+/*-************************************
+*  Common Constants
+**************************************/
+#define MINMATCH 4
+
+#define WILDCOPYLENGTH 8
+#define LASTLITERALS   5   /* see ../doc/lz4_Block_format.md#parsing-restrictions */
+#define MFLIMIT       12   /* see ../doc/lz4_Block_format.md#parsing-restrictions */
+#define MATCH_SAFEGUARD_DISTANCE  ((2*WILDCOPYLENGTH) - MINMATCH)   /* ensure it's possible to write 2 x wildcopyLength without overflowing output buffer */
+static const int LZ4_minLength = (MFLIMIT+1);
+
+#define KB *(1 <<10)
+#define MB *(1 <<20)
+#define GB *(1U<<30)
+
+#define MAXD_LOG 16
+#define MAX_DISTANCE ((1 << MAXD_LOG) - 1)
+
+#define ML_BITS  4
+#define ML_MASK  ((1U<<ML_BITS)-1)
+#define RUN_BITS (8-ML_BITS)
+#define RUN_MASK ((1U<<RUN_BITS)-1)
+
+
+/*-************************************
+*  Error detection
+**************************************/
+#if defined(LZ4_DEBUG) && (LZ4_DEBUG>=1)
+#  include <assert.h>
+#else
+#  ifndef assert
+#    define assert(condition) ((void)0)
+#  endif
+#endif
+
+#define LZ4_STATIC_ASSERT(c)   { enum { LZ4_static_assert = 1/(int)(!!(c)) }; }   /* use after variable declarations */
+
+#if defined(LZ4_DEBUG) && (LZ4_DEBUG>=2)
+#  include <stdio.h>
+static int g_debuglog_enable = 1;
+#  define DEBUGLOG(l, ...) {                                  \
+                if ((g_debuglog_enable) && (l<=LZ4_DEBUG)) {  \
+                    fprintf(stderr, __FILE__ ": ");           \
+                    fprintf(stderr, __VA_ARGS__);             \
+                    fprintf(stderr, " \n");                   \
+            }   }
+#else
+#  define DEBUGLOG(l, ...)      {}    /* disabled */
+#endif
+
+
+/*-************************************
+*  Common functions
+**************************************/
+static unsigned LZ4_NbCommonBytes (reg_t val)
+{
+    if (LZ4_isLittleEndian()) {
+        if (sizeof(val)==8) {
+#       if defined(_MSC_VER) && defined(_WIN64) && !defined(LZ4_FORCE_SW_BITCOUNT)
+            unsigned long r = 0;
+            _BitScanForward64( &r, (U64)val );
+            return (int)(r>>3);
+#       elif (defined(__clang__) || (defined(__GNUC__) && (__GNUC__>=3))) && !defined(LZ4_FORCE_SW_BITCOUNT)
+            return (__builtin_ctzll((U64)val) >> 3);
+#       else
+            static const int DeBruijnBytePos[64] = { 0, 0, 0, 0, 0, 1, 1, 2,
+                                                     0, 3, 1, 3, 1, 4, 2, 7,
+                                                     0, 2, 3, 6, 1, 5, 3, 5,
+                                                     1, 3, 4, 4, 2, 5, 6, 7,
+                                                     7, 0, 1, 2, 3, 3, 4, 6,
+                                                     2, 6, 5, 5, 3, 4, 5, 6,
+                                                     7, 1, 2, 4, 6, 4, 4, 5,
+                                                     7, 2, 6, 5, 7, 6, 7, 7 };
+            return DeBruijnBytePos[((U64)((val & -(long long)val) * 0x0218A392CDABBD3FULL)) >> 58];
+#       endif
+        } else /* 32 bits */ {
+#       if defined(_MSC_VER) && !defined(LZ4_FORCE_SW_BITCOUNT)
+            unsigned long r;
+            _BitScanForward( &r, (U32)val );
+            return (int)(r>>3);
+#       elif (defined(__clang__) || (defined(__GNUC__) && (__GNUC__>=3))) && !defined(LZ4_FORCE_SW_BITCOUNT)
+            return (__builtin_ctz((U32)val) >> 3);
+#       else
+            static const int DeBruijnBytePos[32] = { 0, 0, 3, 0, 3, 1, 3, 0,
+                                                     3, 2, 2, 1, 3, 2, 0, 1,
+                                                     3, 3, 1, 2, 2, 2, 2, 0,
+                                                     3, 1, 2, 0, 1, 0, 1, 1 };
+            return DeBruijnBytePos[((U32)((val & -(S32)val) * 0x077CB531U)) >> 27];
+#       endif
+        }
+    } else   /* Big Endian CPU */ {
+        if (sizeof(val)==8) {   /* 64-bits */
+#       if defined(_MSC_VER) && defined(_WIN64) && !defined(LZ4_FORCE_SW_BITCOUNT)
+            unsigned long r = 0;
+            _BitScanReverse64( &r, val );
+            return (unsigned)(r>>3);
+#       elif (defined(__clang__) || (defined(__GNUC__) && (__GNUC__>=3))) && !defined(LZ4_FORCE_SW_BITCOUNT)
+            return (__builtin_clzll((U64)val) >> 3);
+#       else
+            static const U32 by32 = sizeof(val)*4;  /* 32 on 64 bits (goal), 16 on 32 bits.
+                Just to avoid some static analyzer complaining about shift by 32 on 32-bits target.
+                Note that this code path is never triggered in 32-bits mode. */
+            unsigned r;
+            if (!(val>>by32)) { r=4; } else { r=0; val>>=by32; }
+            if (!(val>>16)) { r+=2; val>>=8; } else { val>>=24; }
+            r += (!val);
+            return r;
+#       endif
+        } else /* 32 bits */ {
+#       if defined(_MSC_VER) && !defined(LZ4_FORCE_SW_BITCOUNT)
+            unsigned long r = 0;
+            _BitScanReverse( &r, (unsigned long)val );
+            return (unsigned)(r>>3);
+#       elif (defined(__clang__) || (defined(__GNUC__) && (__GNUC__>=3))) && !defined(LZ4_FORCE_SW_BITCOUNT)
+            return (__builtin_clz((U32)val) >> 3);
+#       else
+            unsigned r;
+            if (!(val>>16)) { r=2; val>>=8; } else { r=0; val>>=24; }
+            r += (!val);
+            return r;
+#       endif
+        }
+    }
+}
+
+#define STEPSIZE sizeof(reg_t)
+LZ4_FORCE_INLINE
+unsigned LZ4_count(const BYTE* pIn, const BYTE* pMatch, const BYTE* pInLimit)
+{
+    const BYTE* const pStart = pIn;
+
+    if (likely(pIn < pInLimit-(STEPSIZE-1))) {
+        reg_t const diff = LZ4_read_ARCH(pMatch) ^ LZ4_read_ARCH(pIn);
+        if (!diff) {
+            pIn+=STEPSIZE; pMatch+=STEPSIZE;
+        } else {
+            return LZ4_NbCommonBytes(diff);
+    }   }
+
+    while (likely(pIn < pInLimit-(STEPSIZE-1))) {
+        reg_t const diff = LZ4_read_ARCH(pMatch) ^ LZ4_read_ARCH(pIn);
+        if (!diff) { pIn+=STEPSIZE; pMatch+=STEPSIZE; continue; }
+        pIn += LZ4_NbCommonBytes(diff);
+        return (unsigned)(pIn - pStart);
+    }
+
+    if ((STEPSIZE==8) && (pIn<(pInLimit-3)) && (LZ4_read32(pMatch) == LZ4_read32(pIn))) { pIn+=4; pMatch+=4; }
+    if ((pIn<(pInLimit-1)) && (LZ4_read16(pMatch) == LZ4_read16(pIn))) { pIn+=2; pMatch+=2; }
+    if ((pIn<pInLimit) && (*pMatch == *pIn)) pIn++;
+    return (unsigned)(pIn - pStart);
+}
+
+
+#ifndef LZ4_COMMONDEFS_ONLY
+/*-************************************
+*  Local Constants
+**************************************/
+static const int LZ4_64Klimit = ((64 KB) + (MFLIMIT-1));
+static const U32 LZ4_skipTrigger = 6;  /* Increase this value ==> compression run slower on incompressible data */
+
+
+/*-************************************
+*  Local Structures and types
+**************************************/
+typedef enum { notLimited = 0, limitedOutput = 1, fillOutput = 2 } limitedOutput_directive;
+typedef enum { clearedTable = 0, byPtr, byU32, byU16 } tableType_t;
+
+/**
+ * This enum distinguishes several different modes of accessing previous
+ * content in the stream.
+ *
+ * - noDict        : There is no preceding content.
+ * - withPrefix64k : Table entries up to ctx->dictSize before the current blob
+ *                   blob being compressed are valid and refer to the preceding
+ *                   content (of length ctx->dictSize), which is available
+ *                   contiguously preceding in memory the content currently
+ *                   being compressed.
+ * - usingExtDict  : Like withPrefix64k, but the preceding content is somewhere
+ *                   else in memory, starting at ctx->dictionary with length
+ *                   ctx->dictSize.
+ * - usingDictCtx  : Like usingExtDict, but everything concerning the preceding
+ *                   content is in a separate context, pointed to by
+ *                   ctx->dictCtx. ctx->dictionary, ctx->dictSize, and table
+ *                   entries in the current context that refer to positions
+ *                   preceding the beginning of the current compression are
+ *                   ignored. Instead, ctx->dictCtx->dictionary and ctx->dictCtx
+ *                   ->dictSize describe the location and size of the preceding
+ *                   content, and matches are found by looking in the ctx
+ *                   ->dictCtx->hashTable.
+ */
+typedef enum { noDict = 0, withPrefix64k, usingExtDict, usingDictCtx } dict_directive;
+typedef enum { noDictIssue = 0, dictSmall } dictIssue_directive;
+
+
+/*-************************************
+*  Local Utils
+**************************************/
+int LZ4_versionNumber (void) { return LZ4_VERSION_NUMBER; }
+const char* LZ4_versionString(void) { return LZ4_VERSION_STRING; }
+int LZ4_compressBound(int isize)  { return LZ4_COMPRESSBOUND(isize); }
+int LZ4_sizeofState() { return LZ4_STREAMSIZE; }
+
+
+/*-************************************
+*  Internal Definitions used in Tests
+**************************************/
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
+int LZ4_compress_forceExtDict (LZ4_stream_t* LZ4_stream, const char* source, char* dest, int inputSize);
+
+int LZ4_decompress_safe_forceExtDict(const char* in, char* out, int inSize, int outSize, const void* dict, size_t dictSize);
+
+#if defined (__cplusplus)
+}
+#endif
+
+/*-******************************
+*  Compression functions
+********************************/
+static U32 LZ4_hash4(U32 sequence, tableType_t const tableType)
+{
+    if (tableType == byU16)
+        return ((sequence * 2654435761U) >> ((MINMATCH*8)-(LZ4_HASHLOG+1)));
+    else
+        return ((sequence * 2654435761U) >> ((MINMATCH*8)-LZ4_HASHLOG));
+}
+
+static U32 LZ4_hash5(U64 sequence, tableType_t const tableType)
+{
+    static const U64 prime5bytes = 889523592379ULL;
+    static const U64 prime8bytes = 11400714785074694791ULL;
+    const U32 hashLog = (tableType == byU16) ? LZ4_HASHLOG+1 : LZ4_HASHLOG;
+    if (LZ4_isLittleEndian())
+        return (U32)(((sequence << 24) * prime5bytes) >> (64 - hashLog));
+    else
+        return (U32)(((sequence >> 24) * prime8bytes) >> (64 - hashLog));
+}
+
+LZ4_FORCE_INLINE U32 LZ4_hashPosition(const void* const p, tableType_t const tableType)
+{
+    if ((sizeof(reg_t)==8) && (tableType != byU16)) return LZ4_hash5(LZ4_read_ARCH(p), tableType);
+    return LZ4_hash4(LZ4_read32(p), tableType);
+}
+
+static void LZ4_putIndexOnHash(U32 idx, U32 h, void* tableBase, tableType_t const tableType)
+{
+    switch (tableType)
+    {
+    default: /* fallthrough */
+    case clearedTable: /* fallthrough */
+    case byPtr: { /* illegal! */ assert(0); return; }
+    case byU32: { U32* hashTable = (U32*) tableBase; hashTable[h] = idx; return; }
+    case byU16: { U16* hashTable = (U16*) tableBase; assert(idx < 65536); hashTable[h] = (U16)idx; return; }
+    }
+}
+
+static void LZ4_putPositionOnHash(const BYTE* p, U32 h,
+                                  void* tableBase, tableType_t const tableType,
+                            const BYTE* srcBase)
+{
+    switch (tableType)
+    {
+    case clearedTable: { /* illegal! */ assert(0); return; }
+    case byPtr: { const BYTE** hashTable = (const BYTE**)tableBase; hashTable[h] = p; return; }
+    case byU32: { U32* hashTable = (U32*) tableBase; hashTable[h] = (U32)(p-srcBase); return; }
+    case byU16: { U16* hashTable = (U16*) tableBase; hashTable[h] = (U16)(p-srcBase); return; }
+    }
+}
+
+LZ4_FORCE_INLINE void LZ4_putPosition(const BYTE* p, void* tableBase, tableType_t tableType, const BYTE* srcBase)
+{
+    U32 const h = LZ4_hashPosition(p, tableType);
+    LZ4_putPositionOnHash(p, h, tableBase, tableType, srcBase);
+}
+
+/* LZ4_getIndexOnHash() :
+ * Index of match position registered in hash table.
+ * hash position must be calculated by using base+index, or dictBase+index.
+ * Assumption 1 : only valid if tableType == byU32 or byU16.
+ * Assumption 2 : h is presumed valid (within limits of hash table)
+ */
+static U32 LZ4_getIndexOnHash(U32 h, const void* tableBase, tableType_t tableType)
+{
+    LZ4_STATIC_ASSERT(LZ4_MEMORY_USAGE > 2);
+    if (tableType == byU32) {
+        const U32* const hashTable = (const U32*) tableBase;
+        assert(h < (1U << (LZ4_MEMORY_USAGE-2)));
+        return hashTable[h];
+    }
+    if (tableType == byU16) {
+        const U16* const hashTable = (const U16*) tableBase;
+        assert(h < (1U << (LZ4_MEMORY_USAGE-1)));
+        return hashTable[h];
+    }
+    assert(0); return 0;  /* forbidden case */
+}
+
+static const BYTE* LZ4_getPositionOnHash(U32 h, const void* tableBase, tableType_t tableType, const BYTE* srcBase)
+{
+    if (tableType == byPtr) { const BYTE* const* hashTable = (const BYTE* const*) tableBase; return hashTable[h]; }
+    if (tableType == byU32) { const U32* const hashTable = (const U32*) tableBase; return hashTable[h] + srcBase; }
+    { const U16* const hashTable = (const U16*) tableBase; return hashTable[h] + srcBase; }   /* default, to ensure a return */
+}
+
+LZ4_FORCE_INLINE const BYTE* LZ4_getPosition(const BYTE* p,
+                                             const void* tableBase, tableType_t tableType,
+                                             const BYTE* srcBase)
+{
+    U32 const h = LZ4_hashPosition(p, tableType);
+    return LZ4_getPositionOnHash(h, tableBase, tableType, srcBase);
+}
+
+LZ4_FORCE_INLINE void LZ4_prepareTable(
+        LZ4_stream_t_internal* const cctx,
+        const int inputSize,
+        const tableType_t tableType) {
+    /* If the table hasn't been used, it's guaranteed to be zeroed out, and is
+     * therefore safe to use no matter what mode we're in. Otherwise, we figure
+     * out if it's safe to leave as is or whether it needs to be reset.
+     */
+    if (cctx->tableType != clearedTable) {
+        if (cctx->tableType != tableType
+          || (tableType == byU16 && cctx->currentOffset + inputSize >= 0xFFFFU)
+          || (tableType == byU32 && cctx->currentOffset > 1 GB)
+          || tableType == byPtr
+          || inputSize >= 4 KB)
+        {
+            DEBUGLOG(4, "LZ4_prepareTable: Resetting table in %p", cctx);
+            MEM_INIT(cctx->hashTable, 0, LZ4_HASHTABLESIZE);
+            cctx->currentOffset = 0;
+            cctx->tableType = clearedTable;
+        } else {
+            DEBUGLOG(4, "LZ4_prepareTable: Re-use hash table (no reset)");
+        }
+    }
+
+    /* Adding a gap, so all previous entries are > MAX_DISTANCE back, is faster
+     * than compressing without a gap. However, compressing with
+     * currentOffset == 0 is faster still, so we preserve that case.
+     */
+    if (cctx->currentOffset != 0 && tableType == byU32) {
+        DEBUGLOG(5, "LZ4_prepareTable: adding 64KB to currentOffset");
+        cctx->currentOffset += 64 KB;
+    }
+
+    /* Finally, clear history */
+    cctx->dictCtx = NULL;
+    cctx->dictionary = NULL;
+    cctx->dictSize = 0;
+}
+
+/** LZ4_compress_generic() :
+    inlined, to ensure branches are decided at compilation time */
+LZ4_FORCE_INLINE int LZ4_compress_generic(
+                 LZ4_stream_t_internal* const cctx,
+                 const char* const source,
+                 char* const dest,
+                 const int inputSize,
+                 int *inputConsumed, /* only written when outputLimited == fillOutput */
+                 const int maxOutputSize,
+                 const limitedOutput_directive outputLimited,
+                 const tableType_t tableType,
+                 const dict_directive dictDirective,
+                 const dictIssue_directive dictIssue,
+                 const U32 acceleration)
+{
+    const BYTE* ip = (const BYTE*) source;
+
+    U32 const startIndex = cctx->currentOffset;
+    const BYTE* base = (const BYTE*) source - startIndex;
+    const BYTE* lowLimit;
+
+    const LZ4_stream_t_internal* dictCtx = (const LZ4_stream_t_internal*) cctx->dictCtx;
+    const BYTE* const dictionary =
+        dictDirective == usingDictCtx ? dictCtx->dictionary : cctx->dictionary;
+    const U32 dictSize =
+        dictDirective == usingDictCtx ? dictCtx->dictSize : cctx->dictSize;
+    const U32 dictDelta = (dictDirective == usingDictCtx) ? startIndex - dictCtx->currentOffset : 0;   /* make indexes in dictCtx comparable with index in current context */
+
+    int const maybe_extMem = (dictDirective == usingExtDict) || (dictDirective == usingDictCtx);
+    U32 const prefixIdxLimit = startIndex - dictSize;   /* used when dictDirective == dictSmall */
+    const BYTE* const dictEnd = dictionary + dictSize;
+    const BYTE* anchor = (const BYTE*) source;
+    const BYTE* const iend = ip + inputSize;
+    const BYTE* const mflimitPlusOne = iend - MFLIMIT + 1;
+    const BYTE* const matchlimit = iend - LASTLITERALS;
+
+    /* the dictCtx currentOffset is indexed on the start of the dictionary,
+     * while a dictionary in the current context precedes the currentOffset */
+    const BYTE* dictBase = (dictDirective == usingDictCtx) ?
+                            dictionary + dictSize - dictCtx->currentOffset :
+                            dictionary + dictSize - startIndex;
+
+    BYTE* op = (BYTE*) dest;
+    BYTE* const olimit = op + maxOutputSize;
+
+    U32 offset = 0;
+    U32 forwardH;
+
+    DEBUGLOG(5, "LZ4_compress_generic: srcSize=%i, tableType=%u", inputSize, tableType);
+    /* Init conditions */
+    if (outputLimited == fillOutput && maxOutputSize < 1) return 0; /* Impossible to store anything */
+    if ((U32)inputSize > (U32)LZ4_MAX_INPUT_SIZE) return 0;   /* Unsupported inputSize, too large (or negative) */
+    if ((tableType == byU16) && (inputSize>=LZ4_64Klimit)) return 0;  /* Size too large (not within 64K limit) */
+    if (tableType==byPtr) assert(dictDirective==noDict);      /* only supported use case with byPtr */
+    assert(acceleration >= 1);
+
+    lowLimit = (const BYTE*)source - (dictDirective == withPrefix64k ? dictSize : 0);
+
+    /* Update context state */
+    if (dictDirective == usingDictCtx) {
+        /* Subsequent linked blocks can't use the dictionary. */
+        /* Instead, they use the block we just compressed. */
+        cctx->dictCtx = NULL;
+        cctx->dictSize = (U32)inputSize;
+    } else {
+        cctx->dictSize += (U32)inputSize;
+    }
+    cctx->currentOffset += (U32)inputSize;
+    cctx->tableType = (U16)tableType;
+
+    if (inputSize<LZ4_minLength) goto _last_literals;        /* Input too small, no compression (all literals) */
+
+    /* First Byte */
+    LZ4_putPosition(ip, cctx->hashTable, tableType, base);
+    ip++; forwardH = LZ4_hashPosition(ip, tableType);
+
+    /* Main Loop */
+    for ( ; ; ) {
+        const BYTE* match;
+        BYTE* token;
+
+        /* Find a match */
+        if (tableType == byPtr) {
+            const BYTE* forwardIp = ip;
+            unsigned step = 1;
+            unsigned searchMatchNb = acceleration << LZ4_skipTrigger;
+            do {
+                U32 const h = forwardH;
+                ip = forwardIp;
+                forwardIp += step;
+                step = (searchMatchNb++ >> LZ4_skipTrigger);
+
+                if (unlikely(forwardIp > mflimitPlusOne)) goto _last_literals;
+                assert(ip < mflimitPlusOne);
+
+                match = LZ4_getPositionOnHash(h, cctx->hashTable, tableType, base);
+                forwardH = LZ4_hashPosition(forwardIp, tableType);
+                LZ4_putPositionOnHash(ip, h, cctx->hashTable, tableType, base);
+
+            } while ( (match+MAX_DISTANCE < ip)
+                   || (LZ4_read32(match) != LZ4_read32(ip)) );
+
+        } else {   /* byU32, byU16 */
+
+            const BYTE* forwardIp = ip;
+            unsigned step = 1;
+            unsigned searchMatchNb = acceleration << LZ4_skipTrigger;
+            do {
+                U32 const h = forwardH;
+                U32 const current = (U32)(forwardIp - base);
+                U32 matchIndex = LZ4_getIndexOnHash(h, cctx->hashTable, tableType);
+                assert(matchIndex <= current);
+                assert(forwardIp - base < (ptrdiff_t)(2 GB - 1));
+                ip = forwardIp;
+                forwardIp += step;
+                step = (searchMatchNb++ >> LZ4_skipTrigger);
+
+                if (unlikely(forwardIp > mflimitPlusOne)) goto _last_literals;
+                assert(ip < mflimitPlusOne);
+
+                if (dictDirective == usingDictCtx) {
+                    if (matchIndex < startIndex) {
+                        /* there was no match, try the dictionary */
+                        assert(tableType == byU32);
+                        matchIndex = LZ4_getIndexOnHash(h, dictCtx->hashTable, byU32);
+                        match = dictBase + matchIndex;
+                        matchIndex += dictDelta;   /* make dictCtx index comparable with current context */
+                        lowLimit = dictionary;
+                    } else {
+                        match = base + matchIndex;
+                        lowLimit = (const BYTE*)source;
+                    }
+                } else if (dictDirective==usingExtDict) {
+                    if (matchIndex < startIndex) {
+                        DEBUGLOG(7, "extDict candidate: matchIndex=%5u  <  startIndex=%5u", matchIndex, startIndex);
+                        assert(startIndex - matchIndex >= MINMATCH);
+                        match = dictBase + matchIndex;
+                        lowLimit = dictionary;
+                    } else {
+                        match = base + matchIndex;
+                        lowLimit = (const BYTE*)source;
+                    }
+                } else {   /* single continuous memory segment */
+                    match = base + matchIndex;
+                }
+                forwardH = LZ4_hashPosition(forwardIp, tableType);
+                LZ4_putIndexOnHash(current, h, cctx->hashTable, tableType);
+
+                if ((dictIssue == dictSmall) && (matchIndex < prefixIdxLimit)) continue;    /* match outside of valid area */
+                assert(matchIndex < current);
+                if ((tableType != byU16) && (matchIndex+MAX_DISTANCE < current)) continue;  /* too far */
+                if (tableType == byU16) assert((current - matchIndex) <= MAX_DISTANCE);     /* too_far presumed impossible with byU16 */
+
+                if (LZ4_read32(match) == LZ4_read32(ip)) {
+                    if (maybe_extMem) offset = current - matchIndex;
+                    break;   /* match found */
+                }
+
+            } while(1);
+        }
+
+        /* Catch up */
+        while (((ip>anchor) & (match > lowLimit)) && (unlikely(ip[-1]==match[-1]))) { ip--; match--; }
+
+        /* Encode Literals */
+        {   unsigned const litLength = (unsigned)(ip - anchor);
+            token = op++;
+            if ((outputLimited == limitedOutput) &&  /* Check output buffer overflow */
+                (unlikely(op + litLength + (2 + 1 + LASTLITERALS) + (litLength/255) > olimit)))
+                return 0;
+            if ((outputLimited == fillOutput) &&
+                (unlikely(op + (litLength+240)/255 /* litlen */ + litLength /* literals */ + 2 /* offset */ + 1 /* token */ + MFLIMIT - MINMATCH /* min last literals so last match is <= end - MFLIMIT */ > olimit))) {
+                op--;
+                goto _last_literals;
+            }
+            if (litLength >= RUN_MASK) {
+                int len = (int)litLength-RUN_MASK;
+                *token = (RUN_MASK<<ML_BITS);
+                for(; len >= 255 ; len-=255) *op++ = 255;
+                *op++ = (BYTE)len;
+            }
+            else *token = (BYTE)(litLength<<ML_BITS);
+
+            /* Copy Literals */
+            LZ4_wildCopy(op, anchor, op+litLength);
+            op+=litLength;
+            DEBUGLOG(6, "seq.start:%i, literals=%u, match.start:%i",
+                        (int)(anchor-(const BYTE*)source), litLength, (int)(ip-(const BYTE*)source));
+        }
+
+_next_match:
+        /* at this stage, the following variables must be correctly set :
+         * - ip : at start of LZ operation
+         * - match : at start of previous pattern occurence; can be within current prefix, or within extDict
+         * - offset : if maybe_ext_memSegment==1 (constant)
+         * - lowLimit : must be == dictionary to mean "match is within extDict"; must be == source otherwise
+         * - token and *token : position to write 4-bits for match length; higher 4-bits for literal length supposed already written
+         */
+
+        if ((outputLimited == fillOutput) &&
+            (op + 2 /* offset */ + 1 /* token */ + MFLIMIT - MINMATCH /* min last literals so last match is <= end - MFLIMIT */ > olimit)) {
+            /* the match was too close to the end, rewind and go to last literals */
+            op = token;
+            goto _last_literals;
+        }
+
+        /* Encode Offset */
+        if (maybe_extMem) {   /* static test */
+            DEBUGLOG(6, "             with offset=%u  (ext if > %i)", offset, (int)(ip - (const BYTE*)source));
+            assert(offset <= MAX_DISTANCE && offset > 0);
+            LZ4_writeLE16(op, (U16)offset); op+=2;
+        } else  {
+            DEBUGLOG(6, "             with offset=%u  (same segment)", (U32)(ip - match));
+            assert(ip-match <= MAX_DISTANCE);
+            LZ4_writeLE16(op, (U16)(ip - match)); op+=2;
+        }
+
+        /* Encode MatchLength */
+        {   unsigned matchCode;
+
+            if ( (dictDirective==usingExtDict || dictDirective==usingDictCtx)
+              && (lowLimit==dictionary) /* match within extDict */ ) {
+                const BYTE* limit = ip + (dictEnd-match);
+                assert(dictEnd > match);
+                if (limit > matchlimit) limit = matchlimit;
+                matchCode = LZ4_count(ip+MINMATCH, match+MINMATCH, limit);
+                ip += MINMATCH + matchCode;
+                if (ip==limit) {
+                    unsigned const more = LZ4_count(limit, (const BYTE*)source, matchlimit);
+                    matchCode += more;
+                    ip += more;
+                }
+                DEBUGLOG(6, "             with matchLength=%u starting in extDict", matchCode+MINMATCH);
+            } else {
+                matchCode = LZ4_count(ip+MINMATCH, match+MINMATCH, matchlimit);
+                ip += MINMATCH + matchCode;
+                DEBUGLOG(6, "             with matchLength=%u", matchCode+MINMATCH);
+            }
+
+            if ((outputLimited) &&    /* Check output buffer overflow */
+                (unlikely(op + (1 + LASTLITERALS) + (matchCode>>8) > olimit)) ) {
+                if (outputLimited == limitedOutput)
+                  return 0;
+                if (outputLimited == fillOutput) {
+                    /* Match description too long : reduce it */
+                    U32 newMatchCode = 15 /* in token */ - 1 /* to avoid needing a zero byte */ + ((U32)(olimit - op) - 2 - 1 - LASTLITERALS) * 255;
+                    ip -= matchCode - newMatchCode;
+                    matchCode = newMatchCode;
+                }
+            }
+            if (matchCode >= ML_MASK) {
+                *token += ML_MASK;
+                matchCode -= ML_MASK;
+                LZ4_write32(op, 0xFFFFFFFF);
+                while (matchCode >= 4*255) {
+                    op+=4;
+                    LZ4_write32(op, 0xFFFFFFFF);
+                    matchCode -= 4*255;
+                }
+                op += matchCode / 255;
+                *op++ = (BYTE)(matchCode % 255);
+            } else
+                *token += (BYTE)(matchCode);
+        }
+
+        anchor = ip;
+
+        /* Test end of chunk */
+        if (ip >= mflimitPlusOne) break;
+
+        /* Fill table */
+        LZ4_putPosition(ip-2, cctx->hashTable, tableType, base);
+
+        /* Test next position */
+        if (tableType == byPtr) {
+
+            match = LZ4_getPosition(ip, cctx->hashTable, tableType, base);
+            LZ4_putPosition(ip, cctx->hashTable, tableType, base);
+            if ( (match+MAX_DISTANCE >= ip)
+              && (LZ4_read32(match) == LZ4_read32(ip)) )
+            { token=op++; *token=0; goto _next_match; }
+
+        } else {   /* byU32, byU16 */
+
+            U32 const h = LZ4_hashPosition(ip, tableType);
+            U32 const current = (U32)(ip-base);
+            U32 matchIndex = LZ4_getIndexOnHash(h, cctx->hashTable, tableType);
+            assert(matchIndex < current);
+            if (dictDirective == usingDictCtx) {
+                if (matchIndex < startIndex) {
+                    /* there was no match, try the dictionary */
+                    matchIndex = LZ4_getIndexOnHash(h, dictCtx->hashTable, byU32);
+                    match = dictBase + matchIndex;
+                    lowLimit = dictionary;   /* required for match length counter */
+                    matchIndex += dictDelta;
+                } else {
+                    match = base + matchIndex;
+                    lowLimit = (const BYTE*)source;  /* required for match length counter */
+                }
+            } else if (dictDirective==usingExtDict) {
+                if (matchIndex < startIndex) {
+                    match = dictBase + matchIndex;
+                    lowLimit = dictionary;   /* required for match length counter */
+                } else {
+                    match = base + matchIndex;
+                    lowLimit = (const BYTE*)source;   /* required for match length counter */
+                }
+            } else {   /* single memory segment */
+                match = base + matchIndex;
+            }
+            LZ4_putIndexOnHash(current, h, cctx->hashTable, tableType);
+            assert(matchIndex < current);
+            if ( ((dictIssue==dictSmall) ? (matchIndex >= prefixIdxLimit) : 1)
+              && ((tableType==byU16) ? 1 : (matchIndex+MAX_DISTANCE >= current))
+              && (LZ4_read32(match) == LZ4_read32(ip)) ) {
+                token=op++;
+                *token=0;
+                if (maybe_extMem) offset = current - matchIndex;
+                DEBUGLOG(6, "seq.start:%i, literals=%u, match.start:%i",
+                            (int)(anchor-(const BYTE*)source), 0, (int)(ip-(const BYTE*)source));
+                goto _next_match;
+            }
+        }
+
+        /* Prepare next loop */
+        forwardH = LZ4_hashPosition(++ip, tableType);
+
+    }
+
+_last_literals:
+    /* Encode Last Literals */
+    {   size_t lastRun = (size_t)(iend - anchor);
+        if ( (outputLimited) &&  /* Check output buffer overflow */
+            (op + lastRun + 1 + ((lastRun+255-RUN_MASK)/255) > olimit)) {
+            if (outputLimited == fillOutput) {
+                /* adapt lastRun to fill 'dst' */
+                lastRun  = (olimit-op) - 1;
+                lastRun -= (lastRun+240)/255;
+            }
+            if (outputLimited == limitedOutput)
+                return 0;
+        }
+        if (lastRun >= RUN_MASK) {
+            size_t accumulator = lastRun - RUN_MASK;
+            *op++ = RUN_MASK << ML_BITS;
+            for(; accumulator >= 255 ; accumulator-=255) *op++ = 255;
+            *op++ = (BYTE) accumulator;
+        } else {
+            *op++ = (BYTE)(lastRun<<ML_BITS);
+        }
+        memcpy(op, anchor, lastRun);
+        ip = anchor + lastRun;
+        op += lastRun;
+    }
+
+    if (outputLimited == fillOutput) {
+        *inputConsumed = (int) (((const char*)ip)-source);
+    }
+    DEBUGLOG(5, "LZ4_compress_generic: compressed %i bytes into %i bytes", inputSize, (int)(((char*)op) - dest));
+    return (int)(((char*)op) - dest);
+}
+
+
+int LZ4_compress_fast_extState(void* state, const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration)
+{
+    LZ4_stream_t_internal* ctx = &((LZ4_stream_t*)state)->internal_donotuse;
+    if (acceleration < 1) acceleration = ACCELERATION_DEFAULT;
+    LZ4_resetStream((LZ4_stream_t*)state);
+    if (maxOutputSize >= LZ4_compressBound(inputSize)) {
+        if (inputSize < LZ4_64Klimit) {
+            return LZ4_compress_generic(ctx, source, dest, inputSize, NULL, 0, notLimited, byU16, noDict, noDictIssue, acceleration);
+        } else {
+            const tableType_t tableType = ((sizeof(void*)==4) && ((uptrval)source > MAX_DISTANCE)) ? byPtr : byU32;
+            return LZ4_compress_generic(ctx, source, dest, inputSize, NULL, 0, notLimited, tableType, noDict, noDictIssue, acceleration);
+        }
+    } else {
+        if (inputSize < LZ4_64Klimit) {;
+            return LZ4_compress_generic(ctx, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, byU16, noDict, noDictIssue, acceleration);
+        } else {
+            const tableType_t tableType = ((sizeof(void*)==4) && ((uptrval)source > MAX_DISTANCE)) ? byPtr : byU32;
+            return LZ4_compress_generic(ctx, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, noDict, noDictIssue, acceleration);
+        }
+    }
+}
+
+/**
+ * LZ4_compress_fast_extState_fastReset() :
+ * A variant of LZ4_compress_fast_extState().
+ *
+ * Using this variant avoids an expensive initialization step. It is only safe
+ * to call if the state buffer is known to be correctly initialized already
+ * (see comment in lz4.h on LZ4_resetStream_fast() for a definition of
+ * "correctly initialized").
+ */
+int LZ4_compress_fast_extState_fastReset(void* state, const char* src, char* dst, int srcSize, int dstCapacity, int acceleration)
+{
+    LZ4_stream_t_internal* ctx = &((LZ4_stream_t*)state)->internal_donotuse;
+    if (acceleration < 1) acceleration = ACCELERATION_DEFAULT;
+
+    if (dstCapacity >= LZ4_compressBound(srcSize)) {
+        if (srcSize < LZ4_64Klimit) {
+            const tableType_t tableType = byU16;
+            LZ4_prepareTable(ctx, srcSize, tableType);
+            if (ctx->currentOffset) {
+                return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, 0, notLimited, tableType, noDict, dictSmall, acceleration);
+            } else {
+                return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, 0, notLimited, tableType, noDict, noDictIssue, acceleration);
+            }
+        } else {
+            const tableType_t tableType = ((sizeof(void*)==4) && ((uptrval)src > MAX_DISTANCE)) ? byPtr : byU32;
+            LZ4_prepareTable(ctx, srcSize, tableType);
+            return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, 0, notLimited, tableType, noDict, noDictIssue, acceleration);
+        }
+    } else {
+        if (srcSize < LZ4_64Klimit) {
+            const tableType_t tableType = byU16;
+            LZ4_prepareTable(ctx, srcSize, tableType);
+            if (ctx->currentOffset) {
+                return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, dstCapacity, limitedOutput, tableType, noDict, dictSmall, acceleration);
+            } else {
+                return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, dstCapacity, limitedOutput, tableType, noDict, noDictIssue, acceleration);
+            }
+        } else {
+            const tableType_t tableType = ((sizeof(void*)==4) && ((uptrval)src > MAX_DISTANCE)) ? byPtr : byU32;
+            LZ4_prepareTable(ctx, srcSize, tableType);
+            return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, dstCapacity, limitedOutput, tableType, noDict, noDictIssue, acceleration);
+        }
+    }
+}
+
+
+int LZ4_compress_fast(const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration)
+{
+    int result;
+#if (LZ4_HEAPMODE)
+    LZ4_stream_t* ctxPtr = ALLOC(sizeof(LZ4_stream_t));   /* malloc-calloc always properly aligned */
+    if (ctxPtr == NULL) return 0;
+#else
+    LZ4_stream_t ctx;
+    LZ4_stream_t* const ctxPtr = &ctx;
+#endif
+    result = LZ4_compress_fast_extState(ctxPtr, source, dest, inputSize, maxOutputSize, acceleration);
+
+#if (LZ4_HEAPMODE)
+    FREEMEM(ctxPtr);
+#endif
+    return result;
+}
+
+
+int LZ4_compress_default(const char* source, char* dest, int inputSize, int maxOutputSize)
+{
+    return LZ4_compress_fast(source, dest, inputSize, maxOutputSize, 1);
+}
+
+
+/* hidden debug function */
+/* strangely enough, gcc generates faster code when this function is uncommented, even if unused */
+int LZ4_compress_fast_force(const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration)
+{
+    LZ4_stream_t ctx;
+    LZ4_resetStream(&ctx);
+
+    if (inputSize < LZ4_64Klimit)
+        return LZ4_compress_generic(&ctx.internal_donotuse, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, byU16,                        noDict, noDictIssue, acceleration);
+    else
+        return LZ4_compress_generic(&ctx.internal_donotuse, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, sizeof(void*)==8 ? byU32 : byPtr, noDict, noDictIssue, acceleration);
+}
+
+
+/* Note!: This function leaves the stream in an unclean/broken state!
+ * It is not safe to subsequently use the same state with a _fastReset() or
+ * _continue() call without resetting it. */
+static int LZ4_compress_destSize_extState (LZ4_stream_t* state, const char* src, char* dst, int* srcSizePtr, int targetDstSize)
+{
+    LZ4_resetStream(state);
+
+    if (targetDstSize >= LZ4_compressBound(*srcSizePtr)) {  /* compression success is guaranteed */
+        return LZ4_compress_fast_extState(state, src, dst, *srcSizePtr, targetDstSize, 1);
+    } else {
+        if (*srcSizePtr < LZ4_64Klimit) {
+            return LZ4_compress_generic(&state->internal_donotuse, src, dst, *srcSizePtr, srcSizePtr, targetDstSize, fillOutput, byU16, noDict, noDictIssue, 1);
+        } else {
+            tableType_t const tableType = ((sizeof(void*)==4) && ((uptrval)src > MAX_DISTANCE)) ? byPtr : byU32;
+            return LZ4_compress_generic(&state->internal_donotuse, src, dst, *srcSizePtr, srcSizePtr, targetDstSize, fillOutput, tableType, noDict, noDictIssue, 1);
+    }   }
+}
+
+
+int LZ4_compress_destSize(const char* src, char* dst, int* srcSizePtr, int targetDstSize)
+{
+#if (LZ4_HEAPMODE)
+    LZ4_stream_t* ctx = (LZ4_stream_t*)ALLOC(sizeof(LZ4_stream_t));   /* malloc-calloc always properly aligned */
+    if (ctx == NULL) return 0;
+#else
+    LZ4_stream_t ctxBody;
+    LZ4_stream_t* ctx = &ctxBody;
+#endif
+
+    int result = LZ4_compress_destSize_extState(ctx, src, dst, srcSizePtr, targetDstSize);
+
+#if (LZ4_HEAPMODE)
+    FREEMEM(ctx);
+#endif
+    return result;
+}
+
+
+
+/*-******************************
+*  Streaming functions
+********************************/
+
+LZ4_stream_t* LZ4_createStream(void)
+{
+    LZ4_stream_t* lz4s = (LZ4_stream_t*)ALLOC(sizeof(LZ4_stream_t));
+    LZ4_STATIC_ASSERT(LZ4_STREAMSIZE >= sizeof(LZ4_stream_t_internal));    /* A compilation error here means LZ4_STREAMSIZE is not large enough */
+    DEBUGLOG(4, "LZ4_createStream %p", lz4s);
+    if (lz4s == NULL) return NULL;
+    LZ4_resetStream(lz4s);
+    return lz4s;
+}
+
+void LZ4_resetStream (LZ4_stream_t* LZ4_stream)
+{
+    DEBUGLOG(5, "LZ4_resetStream (ctx:%p)", LZ4_stream);
+    MEM_INIT(LZ4_stream, 0, sizeof(LZ4_stream_t));
+}
+
+void LZ4_resetStream_fast(LZ4_stream_t* ctx) {
+    LZ4_prepareTable(&(ctx->internal_donotuse), 0, byU32);
+}
+
+int LZ4_freeStream (LZ4_stream_t* LZ4_stream)
+{
+    if (!LZ4_stream) return 0;   /* support free on NULL */
+    DEBUGLOG(5, "LZ4_freeStream %p", LZ4_stream);
+    FREEMEM(LZ4_stream);
+    return (0);
+}
+
+
+#define HASH_UNIT sizeof(reg_t)
+int LZ4_loadDict (LZ4_stream_t* LZ4_dict, const char* dictionary, int dictSize)
+{
+    LZ4_stream_t_internal* dict = &LZ4_dict->internal_donotuse;
+    const tableType_t tableType = byU32;
+    const BYTE* p = (const BYTE*)dictionary;
+    const BYTE* const dictEnd = p + dictSize;
+    const BYTE* base;
+
+    DEBUGLOG(4, "LZ4_loadDict (%i bytes from %p into %p)", dictSize, dictionary, LZ4_dict);
+
+    /* It's necessary to reset the context,
+     * and not just continue it with prepareTable()
+     * to avoid any risk of generating overflowing matchIndex
+     * when compressing using this dictionary */
+    LZ4_resetStream(LZ4_dict);
+
+    /* We always increment the offset by 64 KB, since, if the dict is longer,
+     * we truncate it to the last 64k, and if it's shorter, we still want to
+     * advance by a whole window length so we can provide the guarantee that
+     * there are only valid offsets in the window, which allows an optimization
+     * in LZ4_compress_fast_continue() where it uses noDictIssue even when the
+     * dictionary isn't a full 64k. */
+
+    if ((dictEnd - p) > 64 KB) p = dictEnd - 64 KB;
+    base = dictEnd - 64 KB - dict->currentOffset;
+    dict->dictionary = p;
+    dict->dictSize = (U32)(dictEnd - p);
+    dict->currentOffset += 64 KB;
+    dict->tableType = tableType;
+
+    if (dictSize < (int)HASH_UNIT) {
+        return 0;
+    }
+
+    while (p <= dictEnd-HASH_UNIT) {
+        LZ4_putPosition(p, dict->hashTable, tableType, base);
+        p+=3;
+    }
+
+    return dict->dictSize;
+}
+
+void LZ4_attach_dictionary(LZ4_stream_t *working_stream, const LZ4_stream_t *dictionary_stream) {
+    if (dictionary_stream != NULL) {
+        /* If the current offset is zero, we will never look in the
+         * external dictionary context, since there is no value a table
+         * entry can take that indicate a miss. In that case, we need
+         * to bump the offset to something non-zero.
+         */
+        if (working_stream->internal_donotuse.currentOffset == 0) {
+            working_stream->internal_donotuse.currentOffset = 64 KB;
+        }
+        working_stream->internal_donotuse.dictCtx = &(dictionary_stream->internal_donotuse);
+    } else {
+        working_stream->internal_donotuse.dictCtx = NULL;
+    }
+}
+
+
+static void LZ4_renormDictT(LZ4_stream_t_internal* LZ4_dict, int nextSize)
+{
+    if (LZ4_dict->currentOffset + nextSize > 0x80000000) {   /* potential ptrdiff_t overflow (32-bits mode) */
+        /* rescale hash table */
+        U32 const delta = LZ4_dict->currentOffset - 64 KB;
+        const BYTE* dictEnd = LZ4_dict->dictionary + LZ4_dict->dictSize;
+        int i;
+        DEBUGLOG(4, "LZ4_renormDictT");
+        for (i=0; i<LZ4_HASH_SIZE_U32; i++) {
+            if (LZ4_dict->hashTable[i] < delta) LZ4_dict->hashTable[i]=0;
+            else LZ4_dict->hashTable[i] -= delta;
+        }
+        LZ4_dict->currentOffset = 64 KB;
+        if (LZ4_dict->dictSize > 64 KB) LZ4_dict->dictSize = 64 KB;
+        LZ4_dict->dictionary = dictEnd - LZ4_dict->dictSize;
+    }
+}
+
+
+int LZ4_compress_fast_continue (LZ4_stream_t* LZ4_stream, const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration)
+{
+    const tableType_t tableType = byU32;
+    LZ4_stream_t_internal* streamPtr = &LZ4_stream->internal_donotuse;
+    const BYTE* dictEnd = streamPtr->dictionary + streamPtr->dictSize;
+
+    DEBUGLOG(5, "LZ4_compress_fast_continue (inputSize=%i)", inputSize);
+
+    if (streamPtr->initCheck) return 0;   /* Uninitialized structure detected */
+    LZ4_renormDictT(streamPtr, inputSize);   /* avoid index overflow */
+    if (acceleration < 1) acceleration = ACCELERATION_DEFAULT;
+
+    /* invalidate tiny dictionaries */
+    if ( (streamPtr->dictSize-1 < 4)   /* intentional underflow */
+      && (dictEnd != (const BYTE*)source) ) {
+        DEBUGLOG(5, "LZ4_compress_fast_continue: dictSize(%u) at addr:%p is too small", streamPtr->dictSize, streamPtr->dictionary);
+        streamPtr->dictSize = 0;
+        streamPtr->dictionary = (const BYTE*)source;
+        dictEnd = (const BYTE*)source;
+    }
+
+    /* Check overlapping input/dictionary space */
+    {   const BYTE* sourceEnd = (const BYTE*) source + inputSize;
+        if ((sourceEnd > streamPtr->dictionary) && (sourceEnd < dictEnd)) {
+            streamPtr->dictSize = (U32)(dictEnd - sourceEnd);
+            if (streamPtr->dictSize > 64 KB) streamPtr->dictSize = 64 KB;
+            if (streamPtr->dictSize < 4) streamPtr->dictSize = 0;
+            streamPtr->dictionary = dictEnd - streamPtr->dictSize;
+        }
+    }
+
+    /* prefix mode : source data follows dictionary */
+    if (dictEnd == (const BYTE*)source) {
+        if ((streamPtr->dictSize < 64 KB) && (streamPtr->dictSize < streamPtr->currentOffset))
+            return LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, withPrefix64k, dictSmall, acceleration);
+        else
+            return LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, withPrefix64k, noDictIssue, acceleration);
+    }
+
+    /* external dictionary mode */
+    {   int result;
+        if (streamPtr->dictCtx) {
+            /* We depend here on the fact that dictCtx'es (produced by
+             * LZ4_loadDict) guarantee that their tables contain no references
+             * to offsets between dictCtx->currentOffset - 64 KB and
+             * dictCtx->currentOffset - dictCtx->dictSize. This makes it safe
+             * to use noDictIssue even when the dict isn't a full 64 KB.
+             */
+            if (inputSize > 4 KB) {
+                /* For compressing large blobs, it is faster to pay the setup
+                 * cost to copy the dictionary's tables into the active context,
+                 * so that the compression loop is only looking into one table.
+                 */
+                memcpy(streamPtr, streamPtr->dictCtx, sizeof(LZ4_stream_t));
+                result = LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, usingExtDict, noDictIssue, acceleration);
+            } else {
+                result = LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, usingDictCtx, noDictIssue, acceleration);
+            }
+        } else {
+            if ((streamPtr->dictSize < 64 KB) && (streamPtr->dictSize < streamPtr->currentOffset)) {
+                result = LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, usingExtDict, dictSmall, acceleration);
+            } else {
+                result = LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, usingExtDict, noDictIssue, acceleration);
+            }
+        }
+        streamPtr->dictionary = (const BYTE*)source;
+        streamPtr->dictSize = (U32)inputSize;
+        return result;
+    }
+}
+
+
+/* Hidden debug function, to force-test external dictionary mode */
+int LZ4_compress_forceExtDict (LZ4_stream_t* LZ4_dict, const char* source, char* dest, int srcSize)
+{
+    LZ4_stream_t_internal* streamPtr = &LZ4_dict->internal_donotuse;
+    int result;
+
+    LZ4_renormDictT(streamPtr, srcSize);
+
+    if ((streamPtr->dictSize < 64 KB) && (streamPtr->dictSize < streamPtr->currentOffset)) {
+        result = LZ4_compress_generic(streamPtr, source, dest, srcSize, NULL, 0, notLimited, byU32, usingExtDict, dictSmall, 1);
+    } else {
+        result = LZ4_compress_generic(streamPtr, source, dest, srcSize, NULL, 0, notLimited, byU32, usingExtDict, noDictIssue, 1);
+    }
+
+    streamPtr->dictionary = (const BYTE*)source;
+    streamPtr->dictSize = (U32)srcSize;
+
+    return result;
+}
+
+
+/*! LZ4_saveDict() :
+ *  If previously compressed data block is not guaranteed to remain available at its memory location,
+ *  save it into a safer place (char* safeBuffer).
+ *  Note : you don't need to call LZ4_loadDict() afterwards,
+ *         dictionary is immediately usable, you can therefore call LZ4_compress_fast_continue().
+ *  Return : saved dictionary size in bytes (necessarily <= dictSize), or 0 if error.
+ */
+int LZ4_saveDict (LZ4_stream_t* LZ4_dict, char* safeBuffer, int dictSize)
+{
+    LZ4_stream_t_internal* const dict = &LZ4_dict->internal_donotuse;
+    const BYTE* const previousDictEnd = dict->dictionary + dict->dictSize;
+
+    if ((U32)dictSize > 64 KB) dictSize = 64 KB;   /* useless to define a dictionary > 64 KB */
+    if ((U32)dictSize > dict->dictSize) dictSize = dict->dictSize;
+
+    memmove(safeBuffer, previousDictEnd - dictSize, dictSize);
+
+    dict->dictionary = (const BYTE*)safeBuffer;
+    dict->dictSize = (U32)dictSize;
+
+    return dictSize;
+}
+
+
+
+/*-*******************************
+ *  Decompression functions
+ ********************************/
+
+typedef enum { endOnOutputSize = 0, endOnInputSize = 1 } endCondition_directive;
+typedef enum { decode_full_block = 0, partial_decode = 1 } earlyEnd_directive;
+
+#undef MIN
+#define MIN(a,b)    ( (a) < (b) ? (a) : (b) )
+
+/*! LZ4_decompress_generic() :
+ *  This generic decompression function covers all use cases.
+ *  It shall be instantiated several times, using different sets of directives.
+ *  Note that it is important for performance that this function really get inlined,
+ *  in order to remove useless branches during compilation optimization.
+ */
+LZ4_FORCE_INLINE int
+LZ4_decompress_generic(
+                 const char* const src,
+                 char* const dst,
+                 int srcSize,
+                 int outputSize,         /* If endOnInput==endOnInputSize, this value is `dstCapacity` */
+
+                 endCondition_directive endOnInput,   /* endOnOutputSize, endOnInputSize */
+                 earlyEnd_directive partialDecoding,  /* full, partial */
+                 dict_directive dict,                 /* noDict, withPrefix64k, usingExtDict */
+                 const BYTE* const lowPrefix,  /* always <= dst, == dst when no prefix */
+                 const BYTE* const dictStart,  /* only if dict==usingExtDict */
+                 const size_t dictSize         /* note : = 0 if noDict */
+                 )
+{
+    const BYTE* ip = (const BYTE*) src;
+    const BYTE* const iend = ip + srcSize;
+
+    BYTE* op = (BYTE*) dst;
+    BYTE* const oend = op + outputSize;
+    BYTE* cpy;
+
+    const BYTE* const dictEnd = (const BYTE*)dictStart + dictSize;
+    const unsigned inc32table[8] = {0, 1, 2,  1,  0,  4, 4, 4};
+    const int      dec64table[8] = {0, 0, 0, -1, -4,  1, 2, 3};
+
+    const int safeDecode = (endOnInput==endOnInputSize);
+    const int checkOffset = ((safeDecode) && (dictSize < (int)(64 KB)));
+
+    /* Set up the "end" pointers for the shortcut. */
+    const BYTE* const shortiend = iend - (endOnInput ? 14 : 8) /*maxLL*/ - 2 /*offset*/;
+    const BYTE* const shortoend = oend - (endOnInput ? 14 : 8) /*maxLL*/ - 18 /*maxML*/;
+
+    DEBUGLOG(5, "LZ4_decompress_generic (srcSize:%i, dstSize:%i)", srcSize, outputSize);
+
+    /* Special cases */
+    assert(lowPrefix <= op);
+    assert(src != NULL);
+    if ((endOnInput) && (unlikely(outputSize==0))) return ((srcSize==1) && (*ip==0)) ? 0 : -1;  /* Empty output buffer */
+    if ((!endOnInput) && (unlikely(outputSize==0))) return (*ip==0 ? 1 : -1);
+    if ((endOnInput) && unlikely(srcSize==0)) return -1;
+
+    /* Main Loop : decode sequences */
+    while (1) {
+        const BYTE* match;
+        size_t offset;
+
+        unsigned const token = *ip++;
+        size_t length = token >> ML_BITS;  /* literal length */
+
+        assert(!endOnInput || ip <= iend); /* ip < iend before the increment */
+
+        /* A two-stage shortcut for the most common case:
+         * 1) If the literal length is 0..14, and there is enough space,
+         * enter the shortcut and copy 16 bytes on behalf of the literals
+         * (in the fast mode, only 8 bytes can be safely copied this way).
+         * 2) Further if the match length is 4..18, copy 18 bytes in a similar
+         * manner; but we ensure that there's enough space in the output for
+         * those 18 bytes earlier, upon entering the shortcut (in other words,
+         * there is a combined check for both stages).
+         */
+        if ( (endOnInput ? length != RUN_MASK : length <= 8)
+            /* strictly "less than" on input, to re-enter the loop with at least one byte */
+          && likely((endOnInput ? ip < shortiend : 1) & (op <= shortoend)) ) {
+            /* Copy the literals */
+            memcpy(op, ip, endOnInput ? 16 : 8);
+            op += length; ip += length;
+
+            /* The second stage: prepare for match copying, decode full info.
+             * If it doesn't work out, the info won't be wasted. */
+            length = token & ML_MASK; /* match length */
+            offset = LZ4_readLE16(ip); ip += 2;
+            match = op - offset;
+            assert(match <= op); /* check overflow */
+
+            /* Do not deal with overlapping matches. */
+            if ( (length != ML_MASK)
+              && (offset >= 8)
+              && (dict==withPrefix64k || match >= lowPrefix) ) {
+                /* Copy the match. */
+                memcpy(op + 0, match + 0, 8);
+                memcpy(op + 8, match + 8, 8);
+                memcpy(op +16, match +16, 2);
+                op += length + MINMATCH;
+                /* Both stages worked, load the next token. */
+                continue;
+            }
+
+            /* The second stage didn't work out, but the info is ready.
+             * Propel it right to the point of match copying. */
+            goto _copy_match;
+        }
+
+        /* decode literal length */
+        if (length == RUN_MASK) {
+            unsigned s;
+            if (unlikely(endOnInput ? ip >= iend-RUN_MASK : 0)) goto _output_error;   /* overflow detection */
+            do {
+                s = *ip++;
+                length += s;
+            } while ( likely(endOnInput ? ip<iend-RUN_MASK : 1) & (s==255) );
+            if ((safeDecode) && unlikely((uptrval)(op)+length<(uptrval)(op))) goto _output_error;   /* overflow detection */
+            if ((safeDecode) && unlikely((uptrval)(ip)+length<(uptrval)(ip))) goto _output_error;   /* overflow detection */
+        }
+
+        /* copy literals */
+        cpy = op+length;
+        LZ4_STATIC_ASSERT(MFLIMIT >= WILDCOPYLENGTH);
+        if ( ((endOnInput) && ((cpy>oend-MFLIMIT) || (ip+length>iend-(2+1+LASTLITERALS))) )
+          || ((!endOnInput) && (cpy>oend-WILDCOPYLENGTH)) )
+        {
+            if (partialDecoding) {
+                if (cpy > oend) { cpy = oend; length = oend-op; }             /* Partial decoding : stop in the middle of literal segment */
+                if ((endOnInput) && (ip+length > iend)) goto _output_error;   /* Error : read attempt beyond end of input buffer */
+            } else {
+                if ((!endOnInput) && (cpy != oend)) goto _output_error;       /* Error : block decoding must stop exactly there */
+                if ((endOnInput) && ((ip+length != iend) || (cpy > oend))) goto _output_error;   /* Error : input must be consumed */
+            }
+            memcpy(op, ip, length);
+            ip += length;
+            op += length;
+            if (!partialDecoding || (cpy == oend)) {
+                /* Necessarily EOF, due to parsing restrictions */
+                break;
+            }
+
+        } else {
+            LZ4_wildCopy(op, ip, cpy);   /* may overwrite up to WILDCOPYLENGTH beyond cpy */
+            ip += length; op = cpy;
+        }
+
+        /* get offset */
+        offset = LZ4_readLE16(ip); ip+=2;
+        match = op - offset;
+
+        /* get matchlength */
+        length = token & ML_MASK;
+
+_copy_match:
+        if ((checkOffset) && (unlikely(match + dictSize < lowPrefix))) goto _output_error;   /* Error : offset outside buffers */
+        if (!partialDecoding) {
+            assert(oend > op);
+            assert(oend - op >= 4);
+            LZ4_write32(op, 0);   /* silence an msan warning when offset==0; costs <1%; */
+        }   /* note : when partialDecoding, there is no guarantee that at least 4 bytes remain available in output buffer */
+
+        if (length == ML_MASK) {
+            unsigned s;
+            do {
+                s = *ip++;
+                if ((endOnInput) && (ip > iend-LASTLITERALS)) goto _output_error;
+                length += s;
+            } while (s==255);
+            if ((safeDecode) && unlikely((uptrval)(op)+length<(uptrval)op)) goto _output_error;   /* overflow detection */
+        }
+        length += MINMATCH;
+
+        /* match starting within external dictionary */
+        if ((dict==usingExtDict) && (match < lowPrefix)) {
+            if (unlikely(op+length > oend-LASTLITERALS)) {
+                if (partialDecoding) length = MIN(length, (size_t)(oend-op));
+                else goto _output_error;   /* doesn't respect parsing restriction */
+            }
+
+            if (length <= (size_t)(lowPrefix-match)) {
+                /* match fits entirely within external dictionary : just copy */
+                memmove(op, dictEnd - (lowPrefix-match), length);
+                op += length;
+            } else {
+                /* match stretches into both external dictionary and current block */
+                size_t const copySize = (size_t)(lowPrefix - match);
+                size_t const restSize = length - copySize;
+                memcpy(op, dictEnd - copySize, copySize);
+                op += copySize;
+                if (restSize > (size_t)(op - lowPrefix)) {  /* overlap copy */
+                    BYTE* const endOfMatch = op + restSize;
+                    const BYTE* copyFrom = lowPrefix;
+                    while (op < endOfMatch) *op++ = *copyFrom++;
+                } else {
+                    memcpy(op, lowPrefix, restSize);
+                    op += restSize;
+            }   }
+            continue;
+        }
+
+        /* copy match within block */
+        cpy = op + length;
+
+        /* partialDecoding : may not respect endBlock parsing restrictions */
+        assert(op<=oend);
+        if (partialDecoding && (cpy > oend-MATCH_SAFEGUARD_DISTANCE)) {
+            size_t const mlen = MIN(length, (size_t)(oend-op));
+            const BYTE* const matchEnd = match + mlen;
+            BYTE* const copyEnd = op + mlen;
+            if (matchEnd > op) {   /* overlap copy */
+                while (op < copyEnd) *op++ = *match++;
+            } else {
+                memcpy(op, match, mlen);
+            }
+            op = copyEnd;
+            if (op==oend) break;
+            continue;
+        }
+
+        if (unlikely(offset<8)) {
+            op[0] = match[0];
+            op[1] = match[1];
+            op[2] = match[2];
+            op[3] = match[3];
+            match += inc32table[offset];
+            memcpy(op+4, match, 4);
+            match -= dec64table[offset];
+        } else {
+            memcpy(op, match, 8);
+            match += 8;
+        }
+        op += 8;
+
+        if (unlikely(cpy > oend-MATCH_SAFEGUARD_DISTANCE)) {
+            BYTE* const oCopyLimit = oend - (WILDCOPYLENGTH-1);
+            if (cpy > oend-LASTLITERALS) goto _output_error;    /* Error : last LASTLITERALS bytes must be literals (uncompressed) */
+            if (op < oCopyLimit) {
+                LZ4_wildCopy(op, match, oCopyLimit);
+                match += oCopyLimit - op;
+                op = oCopyLimit;
+            }
+            while (op < cpy) *op++ = *match++;
+        } else {
+            memcpy(op, match, 8);
+            if (length > 16) LZ4_wildCopy(op+8, match+8, cpy);
+        }
+        op = cpy;   /* wildcopy correction */
+    }
+
+    /* end of decoding */
+    if (endOnInput)
+       return (int) (((char*)op)-dst);     /* Nb of output bytes decoded */
+    else
+       return (int) (((const char*)ip)-src);   /* Nb of input bytes read */
+
+    /* Overflow error detected */
+_output_error:
+    return (int) (-(((const char*)ip)-src))-1;
+}
+
+
+/*===== Instantiate the API decoding functions. =====*/
+
+LZ4_FORCE_O2_GCC_PPC64LE
+int LZ4_decompress_safe(const char* source, char* dest, int compressedSize, int maxDecompressedSize)
+{
+    return LZ4_decompress_generic(source, dest, compressedSize, maxDecompressedSize,
+                                  endOnInputSize, decode_full_block, noDict,
+                                  (BYTE*)dest, NULL, 0);
+}
+
+LZ4_FORCE_O2_GCC_PPC64LE
+int LZ4_decompress_safe_partial(const char* src, char* dst, int compressedSize, int targetOutputSize, int dstCapacity)
+{
+    dstCapacity = MIN(targetOutputSize, dstCapacity);
+    return LZ4_decompress_generic(src, dst, compressedSize, dstCapacity,
+                                  endOnInputSize, partial_decode,
+                                  noDict, (BYTE*)dst, NULL, 0);
+}
+
+LZ4_FORCE_O2_GCC_PPC64LE
+int LZ4_decompress_fast(const char* source, char* dest, int originalSize)
+{
+    return LZ4_decompress_generic(source, dest, 0, originalSize,
+                                  endOnOutputSize, decode_full_block, withPrefix64k,
+                                  (BYTE*)dest - 64 KB, NULL, 0);
+}
+
+/*===== Instantiate a few more decoding cases, used more than once. =====*/
+
+LZ4_FORCE_O2_GCC_PPC64LE /* Exported, an obsolete API function. */
+int LZ4_decompress_safe_withPrefix64k(const char* source, char* dest, int compressedSize, int maxOutputSize)
+{
+    return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize,
+                                  endOnInputSize, decode_full_block, withPrefix64k,
+                                  (BYTE*)dest - 64 KB, NULL, 0);
+}
+
+/* Another obsolete API function, paired with the previous one. */
+int LZ4_decompress_fast_withPrefix64k(const char* source, char* dest, int originalSize)
+{
+    /* LZ4_decompress_fast doesn't validate match offsets,
+     * and thus serves well with any prefixed dictionary. */
+    return LZ4_decompress_fast(source, dest, originalSize);
+}
+
+LZ4_FORCE_O2_GCC_PPC64LE
+static int LZ4_decompress_safe_withSmallPrefix(const char* source, char* dest, int compressedSize, int maxOutputSize,
+                                               size_t prefixSize)
+{
+    return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize,
+                                  endOnInputSize, decode_full_block, noDict,
+                                  (BYTE*)dest-prefixSize, NULL, 0);
+}
+
+LZ4_FORCE_O2_GCC_PPC64LE
+int LZ4_decompress_safe_forceExtDict(const char* source, char* dest,
+                                     int compressedSize, int maxOutputSize,
+                                     const void* dictStart, size_t dictSize)
+{
+    return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize,
+                                  endOnInputSize, decode_full_block, usingExtDict,
+                                  (BYTE*)dest, (const BYTE*)dictStart, dictSize);
+}
+
+LZ4_FORCE_O2_GCC_PPC64LE
+static int LZ4_decompress_fast_extDict(const char* source, char* dest, int originalSize,
+                                       const void* dictStart, size_t dictSize)
+{
+    return LZ4_decompress_generic(source, dest, 0, originalSize,
+                                  endOnOutputSize, decode_full_block, usingExtDict,
+                                  (BYTE*)dest, (const BYTE*)dictStart, dictSize);
+}
+
+/* The "double dictionary" mode, for use with e.g. ring buffers: the first part
+ * of the dictionary is passed as prefix, and the second via dictStart + dictSize.
+ * These routines are used only once, in LZ4_decompress_*_continue().
+ */
+LZ4_FORCE_INLINE
+int LZ4_decompress_safe_doubleDict(const char* source, char* dest, int compressedSize, int maxOutputSize,
+                                   size_t prefixSize, const void* dictStart, size_t dictSize)
+{
+    return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize,
+                                  endOnInputSize, decode_full_block, usingExtDict,
+                                  (BYTE*)dest-prefixSize, (const BYTE*)dictStart, dictSize);
+}
+
+LZ4_FORCE_INLINE
+int LZ4_decompress_fast_doubleDict(const char* source, char* dest, int originalSize,
+                                   size_t prefixSize, const void* dictStart, size_t dictSize)
+{
+    return LZ4_decompress_generic(source, dest, 0, originalSize,
+                                  endOnOutputSize, decode_full_block, usingExtDict,
+                                  (BYTE*)dest-prefixSize, (const BYTE*)dictStart, dictSize);
+}
+
+/*===== streaming decompression functions =====*/
+
+LZ4_streamDecode_t* LZ4_createStreamDecode(void)
+{
+    LZ4_streamDecode_t* lz4s = (LZ4_streamDecode_t*) ALLOC_AND_ZERO(sizeof(LZ4_streamDecode_t));
+    return lz4s;
+}
+
+int LZ4_freeStreamDecode (LZ4_streamDecode_t* LZ4_stream)
+{
+    if (!LZ4_stream) return 0;   /* support free on NULL */
+    FREEMEM(LZ4_stream);
+    return 0;
+}
+
+/*! LZ4_setStreamDecode() :
+ *  Use this function to instruct where to find the dictionary.
+ *  This function is not necessary if previous data is still available where it was decoded.
+ *  Loading a size of 0 is allowed (same effect as no dictionary).
+ * @return : 1 if OK, 0 if error
+ */
+int LZ4_setStreamDecode (LZ4_streamDecode_t* LZ4_streamDecode, const char* dictionary, int dictSize)
+{
+    LZ4_streamDecode_t_internal* lz4sd = &LZ4_streamDecode->internal_donotuse;
+    lz4sd->prefixSize = (size_t) dictSize;
+    lz4sd->prefixEnd = (const BYTE*) dictionary + dictSize;
+    lz4sd->externalDict = NULL;
+    lz4sd->extDictSize  = 0;
+    return 1;
+}
+
+/*! LZ4_decoderRingBufferSize() :
+ *  when setting a ring buffer for streaming decompression (optional scenario),
+ *  provides the minimum size of this ring buffer
+ *  to be compatible with any source respecting maxBlockSize condition.
+ *  Note : in a ring buffer scenario,
+ *  blocks are presumed decompressed next to each other.
+ *  When not enough space remains for next block (remainingSize < maxBlockSize),
+ *  decoding resumes from beginning of ring buffer.
+ * @return : minimum ring buffer size,
+ *           or 0 if there is an error (invalid maxBlockSize).
+ */
+int LZ4_decoderRingBufferSize(int maxBlockSize)
+{
+    if (maxBlockSize < 0) return 0;
+    if (maxBlockSize > LZ4_MAX_INPUT_SIZE) return 0;
+    if (maxBlockSize < 16) maxBlockSize = 16;
+    return LZ4_DECODER_RING_BUFFER_SIZE(maxBlockSize);
+}
+
+/*
+*_continue() :
+    These decoding functions allow decompression of multiple blocks in "streaming" mode.
+    Previously decoded blocks must still be available at the memory position where they were decoded.
+    If it's not possible, save the relevant part of decoded data into a safe buffer,
+    and indicate where it stands using LZ4_setStreamDecode()
+*/
+LZ4_FORCE_O2_GCC_PPC64LE
+int LZ4_decompress_safe_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* source, char* dest, int compressedSize, int maxOutputSize)
+{
+    LZ4_streamDecode_t_internal* lz4sd = &LZ4_streamDecode->internal_donotuse;
+    int result;
+
+    if (lz4sd->prefixSize == 0) {
+        /* The first call, no dictionary yet. */
+        assert(lz4sd->extDictSize == 0);
+        result = LZ4_decompress_safe(source, dest, compressedSize, maxOutputSize);
+        if (result <= 0) return result;
+        lz4sd->prefixSize = result;
+        lz4sd->prefixEnd = (BYTE*)dest + result;
+    } else if (lz4sd->prefixEnd == (BYTE*)dest) {
+        /* They're rolling the current segment. */
+        if (lz4sd->prefixSize >= 64 KB - 1)
+            result = LZ4_decompress_safe_withPrefix64k(source, dest, compressedSize, maxOutputSize);
+        else if (lz4sd->extDictSize == 0)
+            result = LZ4_decompress_safe_withSmallPrefix(source, dest, compressedSize, maxOutputSize,
+                                                         lz4sd->prefixSize);
+        else
+            result = LZ4_decompress_safe_doubleDict(source, dest, compressedSize, maxOutputSize,
+                                                    lz4sd->prefixSize, lz4sd->externalDict, lz4sd->extDictSize);
+        if (result <= 0) return result;
+        lz4sd->prefixSize += result;
+        lz4sd->prefixEnd  += result;
+    } else {
+        /* The buffer wraps around, or they're switching to another buffer. */
+        lz4sd->extDictSize = lz4sd->prefixSize;
+        lz4sd->externalDict = lz4sd->prefixEnd - lz4sd->extDictSize;
+        result = LZ4_decompress_safe_forceExtDict(source, dest, compressedSize, maxOutputSize,
+                                                  lz4sd->externalDict, lz4sd->extDictSize);
+        if (result <= 0) return result;
+        lz4sd->prefixSize = result;
+        lz4sd->prefixEnd  = (BYTE*)dest + result;
+    }
+
+    return result;
+}
+
+LZ4_FORCE_O2_GCC_PPC64LE
+int LZ4_decompress_fast_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* source, char* dest, int originalSize)
+{
+    LZ4_streamDecode_t_internal* lz4sd = &LZ4_streamDecode->internal_donotuse;
+    int result;
+
+    if (lz4sd->prefixSize == 0) {
+        assert(lz4sd->extDictSize == 0);
+        result = LZ4_decompress_fast(source, dest, originalSize);
+        if (result <= 0) return result;
+        lz4sd->prefixSize = originalSize;
+        lz4sd->prefixEnd = (BYTE*)dest + originalSize;
+    } else if (lz4sd->prefixEnd == (BYTE*)dest) {
+        if (lz4sd->prefixSize >= 64 KB - 1 || lz4sd->extDictSize == 0)
+            result = LZ4_decompress_fast(source, dest, originalSize);
+        else
+            result = LZ4_decompress_fast_doubleDict(source, dest, originalSize,
+                                                    lz4sd->prefixSize, lz4sd->externalDict, lz4sd->extDictSize);
+        if (result <= 0) return result;
+        lz4sd->prefixSize += originalSize;
+        lz4sd->prefixEnd  += originalSize;
+    } else {
+        lz4sd->extDictSize = lz4sd->prefixSize;
+        lz4sd->externalDict = lz4sd->prefixEnd - lz4sd->extDictSize;
+        result = LZ4_decompress_fast_extDict(source, dest, originalSize,
+                                             lz4sd->externalDict, lz4sd->extDictSize);
+        if (result <= 0) return result;
+        lz4sd->prefixSize = originalSize;
+        lz4sd->prefixEnd  = (BYTE*)dest + originalSize;
+    }
+
+    return result;
+}
+
+
+/*
+Advanced decoding functions :
+*_usingDict() :
+    These decoding functions work the same as "_continue" ones,
+    the dictionary must be explicitly provided within parameters
+*/
+
+int LZ4_decompress_safe_usingDict(const char* source, char* dest, int compressedSize, int maxOutputSize, const char* dictStart, int dictSize)
+{
+    if (dictSize==0)
+        return LZ4_decompress_safe(source, dest, compressedSize, maxOutputSize);
+    if (dictStart+dictSize == dest) {
+        if (dictSize >= 64 KB - 1)
+            return LZ4_decompress_safe_withPrefix64k(source, dest, compressedSize, maxOutputSize);
+        return LZ4_decompress_safe_withSmallPrefix(source, dest, compressedSize, maxOutputSize, dictSize);
+    }
+    return LZ4_decompress_safe_forceExtDict(source, dest, compressedSize, maxOutputSize, dictStart, dictSize);
+}
+
+int LZ4_decompress_fast_usingDict(const char* source, char* dest, int originalSize, const char* dictStart, int dictSize)
+{
+    if (dictSize==0 || dictStart+dictSize == dest)
+        return LZ4_decompress_fast(source, dest, originalSize);
+    return LZ4_decompress_fast_extDict(source, dest, originalSize, dictStart, dictSize);
+}
+
+
+/*=*************************************************
+*  Obsolete Functions
+***************************************************/
+/* obsolete compression functions */
+int LZ4_compress_limitedOutput(const char* source, char* dest, int inputSize, int maxOutputSize)
+{
+    return LZ4_compress_default(source, dest, inputSize, maxOutputSize);
+}
+int LZ4_compress(const char* source, char* dest, int inputSize)
+{
+    return LZ4_compress_default(source, dest, inputSize, LZ4_compressBound(inputSize));
+}
+int LZ4_compress_limitedOutput_withState (void* state, const char* src, char* dst, int srcSize, int dstSize)
+{
+    return LZ4_compress_fast_extState(state, src, dst, srcSize, dstSize, 1);
+}
+int LZ4_compress_withState (void* state, const char* src, char* dst, int srcSize)
+{
+    return LZ4_compress_fast_extState(state, src, dst, srcSize, LZ4_compressBound(srcSize), 1);
+}
+int LZ4_compress_limitedOutput_continue (LZ4_stream_t* LZ4_stream, const char* src, char* dst, int srcSize, int dstCapacity)
+{
+    return LZ4_compress_fast_continue(LZ4_stream, src, dst, srcSize, dstCapacity, 1);
+}
+int LZ4_compress_continue (LZ4_stream_t* LZ4_stream, const char* source, char* dest, int inputSize)
+{
+    return LZ4_compress_fast_continue(LZ4_stream, source, dest, inputSize, LZ4_compressBound(inputSize), 1);
+}
+
+/*
+These decompression functions are deprecated and should no longer be used.
+They are only provided here for compatibility with older user programs.
+- LZ4_uncompress is totally equivalent to LZ4_decompress_fast
+- LZ4_uncompress_unknownOutputSize is totally equivalent to LZ4_decompress_safe
+*/
+int LZ4_uncompress (const char* source, char* dest, int outputSize)
+{
+    return LZ4_decompress_fast(source, dest, outputSize);
+}
+int LZ4_uncompress_unknownOutputSize (const char* source, char* dest, int isize, int maxOutputSize)
+{
+    return LZ4_decompress_safe(source, dest, isize, maxOutputSize);
+}
+
+/* Obsolete Streaming functions */
+
+int LZ4_sizeofStreamState() { return LZ4_STREAMSIZE; }
+
+int LZ4_resetStreamState(void* state, char* inputBuffer)
+{
+    (void)inputBuffer;
+    LZ4_resetStream((LZ4_stream_t*)state);
+    return 0;
+}
+
+void* LZ4_create (char* inputBuffer)
+{
+    (void)inputBuffer;
+    return LZ4_createStream();
+}
+
+char* LZ4_slideInputBuffer (void* state)
+{
+    /* avoid const char * -> char * conversion warning */
+    return (char *)(uptrval)((LZ4_stream_t*)state)->internal_donotuse.dictionary;
+}
+
+#endif   /* LZ4_COMMONDEFS_ONLY */

+ 631 - 0
Source/Native/lz4/lz4.h

@@ -0,0 +1,631 @@
+/*
+ *  LZ4 - Fast LZ compression algorithm
+ *  Header File
+ *  Copyright (C) 2011-present, Yann Collet.
+
+   BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
+
+   Redistribution and use in source and binary forms, with or without
+   modification, are permitted provided that the following conditions are
+   met:
+
+       * Redistributions of source code must retain the above copyright
+   notice, this list of conditions and the following disclaimer.
+       * Redistributions in binary form must reproduce the above
+   copyright notice, this list of conditions and the following disclaimer
+   in the documentation and/or other materials provided with the
+   distribution.
+
+   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+   You can contact the author at :
+    - LZ4 homepage : http://www.lz4.org
+    - LZ4 source repository : https://github.com/lz4/lz4
+*/
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
+#ifndef LZ4_H_2983827168210
+#define LZ4_H_2983827168210
+
+/* --- Dependency --- */
+#include <stddef.h>   /* size_t */
+
+
+/**
+  Introduction
+
+  LZ4 is lossless compression algorithm, providing compression speed at 500 MB/s per core,
+  scalable with multi-cores CPU. It features an extremely fast decoder, with speed in
+  multiple GB/s per core, typically reaching RAM speed limits on multi-core systems.
+
+  The LZ4 compression library provides in-memory compression and decompression functions.
+  Compression can be done in:
+    - a single step (described as Simple Functions)
+    - a single step, reusing a context (described in Advanced Functions)
+    - unbounded multiple steps (described as Streaming compression)
+
+  lz4.h provides block compression functions. It gives full buffer control to user.
+  Decompressing an lz4-compressed block also requires metadata (such as compressed size).
+  Each application is free to encode such metadata in whichever way it wants.
+
+  An additional format, called LZ4 frame specification (doc/lz4_Frame_format.md),
+  take care of encoding standard metadata alongside LZ4-compressed blocks.
+  Frame format is required for interoperability.
+  It is delivered through a companion API, declared in lz4frame.h.
+*/
+
+/*^***************************************************************
+*  Export parameters
+*****************************************************************/
+/*
+*  LZ4_DLL_EXPORT :
+*  Enable exporting of functions when building a Windows DLL
+*  LZ4LIB_VISIBILITY :
+*  Control library symbols visibility.
+*/
+#ifndef LZ4LIB_VISIBILITY
+#  if defined(__GNUC__) && (__GNUC__ >= 4)
+#    define LZ4LIB_VISIBILITY __attribute__ ((visibility ("default")))
+#  else
+#    define LZ4LIB_VISIBILITY
+#  endif
+#endif
+#if defined(LZ4_DLL_EXPORT) && (LZ4_DLL_EXPORT==1)
+#  define LZ4LIB_API __declspec(dllexport) LZ4LIB_VISIBILITY
+#elif defined(LZ4_DLL_IMPORT) && (LZ4_DLL_IMPORT==1)
+#  define LZ4LIB_API __declspec(dllimport) LZ4LIB_VISIBILITY /* It isn't required but allows to generate better code, saving a function pointer load from the IAT and an indirect jump.*/
+#else
+#  define LZ4LIB_API LZ4LIB_VISIBILITY
+#endif
+
+/*------   Version   ------*/
+#define LZ4_VERSION_MAJOR    1    /* for breaking interface changes  */
+#define LZ4_VERSION_MINOR    8    /* for new (non-breaking) interface capabilities */
+#define LZ4_VERSION_RELEASE  3    /* for tweaks, bug-fixes, or development */
+
+#define LZ4_VERSION_NUMBER (LZ4_VERSION_MAJOR *100*100 + LZ4_VERSION_MINOR *100 + LZ4_VERSION_RELEASE)
+
+#define LZ4_LIB_VERSION LZ4_VERSION_MAJOR.LZ4_VERSION_MINOR.LZ4_VERSION_RELEASE
+#define LZ4_QUOTE(str) #str
+#define LZ4_EXPAND_AND_QUOTE(str) LZ4_QUOTE(str)
+#define LZ4_VERSION_STRING LZ4_EXPAND_AND_QUOTE(LZ4_LIB_VERSION)
+
+LZ4LIB_API int LZ4_versionNumber (void);  /**< library version number; useful to check dll version */
+LZ4LIB_API const char* LZ4_versionString (void);   /**< library version string; unseful to check dll version */
+
+
+/*-************************************
+*  Tuning parameter
+**************************************/
+/*!
+ * LZ4_MEMORY_USAGE :
+ * Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; etc.)
+ * Increasing memory usage improves compression ratio
+ * Reduced memory usage may improve speed, thanks to cache effect
+ * Default value is 14, for 16KB, which nicely fits into Intel x86 L1 cache
+ */
+#ifndef LZ4_MEMORY_USAGE
+# define LZ4_MEMORY_USAGE 14
+#endif
+
+/*-************************************
+*  Simple Functions
+**************************************/
+/*! LZ4_compress_default() :
+    Compresses 'srcSize' bytes from buffer 'src'
+    into already allocated 'dst' buffer of size 'dstCapacity'.
+    Compression is guaranteed to succeed if 'dstCapacity' >= LZ4_compressBound(srcSize).
+    It also runs faster, so it's a recommended setting.
+    If the function cannot compress 'src' into a more limited 'dst' budget,
+    compression stops *immediately*, and the function result is zero.
+    Note : as a consequence, 'dst' content is not valid.
+    Note 2 : This function is protected against buffer overflow scenarios (never writes outside 'dst' buffer, nor read outside 'source' buffer).
+        srcSize : max supported value is LZ4_MAX_INPUT_SIZE.
+        dstCapacity : size of buffer 'dst' (which must be already allocated)
+        return  : the number of bytes written into buffer 'dst' (necessarily <= dstCapacity)
+                  or 0 if compression fails */
+LZ4LIB_API int LZ4_compress_default(const char* src, char* dst, int srcSize, int dstCapacity);
+
+/*! LZ4_decompress_safe() :
+    compressedSize : is the exact complete size of the compressed block.
+    dstCapacity : is the size of destination buffer, which must be already allocated.
+    return : the number of bytes decompressed into destination buffer (necessarily <= dstCapacity)
+             If destination buffer is not large enough, decoding will stop and output an error code (negative value).
+             If the source stream is detected malformed, the function will stop decoding and return a negative result.
+             This function is protected against malicious data packets.
+*/
+LZ4LIB_API int LZ4_decompress_safe (const char* src, char* dst, int compressedSize, int dstCapacity);
+
+
+/*-************************************
+*  Advanced Functions
+**************************************/
+#define LZ4_MAX_INPUT_SIZE        0x7E000000   /* 2 113 929 216 bytes */
+#define LZ4_COMPRESSBOUND(isize)  ((unsigned)(isize) > (unsigned)LZ4_MAX_INPUT_SIZE ? 0 : (isize) + ((isize)/255) + 16)
+
+/*!
+LZ4_compressBound() :
+    Provides the maximum size that LZ4 compression may output in a "worst case" scenario (input data not compressible)
+    This function is primarily useful for memory allocation purposes (destination buffer size).
+    Macro LZ4_COMPRESSBOUND() is also provided for compilation-time evaluation (stack memory allocation for example).
+    Note that LZ4_compress_default() compresses faster when dstCapacity is >= LZ4_compressBound(srcSize)
+        inputSize  : max supported value is LZ4_MAX_INPUT_SIZE
+        return : maximum output size in a "worst case" scenario
+              or 0, if input size is incorrect (too large or negative)
+*/
+LZ4LIB_API int LZ4_compressBound(int inputSize);
+
+/*!
+LZ4_compress_fast() :
+    Same as LZ4_compress_default(), but allows selection of "acceleration" factor.
+    The larger the acceleration value, the faster the algorithm, but also the lesser the compression.
+    It's a trade-off. It can be fine tuned, with each successive value providing roughly +~3% to speed.
+    An acceleration value of "1" is the same as regular LZ4_compress_default()
+    Values <= 0 will be replaced by ACCELERATION_DEFAULT (currently == 1, see lz4.c).
+*/
+LZ4LIB_API int LZ4_compress_fast (const char* src, char* dst, int srcSize, int dstCapacity, int acceleration);
+
+
+/*!
+LZ4_compress_fast_extState() :
+    Same compression function, just using an externally allocated memory space to store compression state.
+    Use LZ4_sizeofState() to know how much memory must be allocated,
+    and allocate it on 8-bytes boundaries (using malloc() typically).
+    Then, provide this buffer as 'void* state' to compression function.
+*/
+LZ4LIB_API int LZ4_sizeofState(void);
+LZ4LIB_API int LZ4_compress_fast_extState (void* state, const char* src, char* dst, int srcSize, int dstCapacity, int acceleration);
+
+
+/*! LZ4_compress_destSize() :
+ *  Reverse the logic : compresses as much data as possible from 'src' buffer
+ *  into already allocated buffer 'dst', of size >= 'targetDestSize'.
+ *  This function either compresses the entire 'src' content into 'dst' if it's large enough,
+ *  or fill 'dst' buffer completely with as much data as possible from 'src'.
+ *  note: acceleration parameter is fixed to "default".
+ *
+ * *srcSizePtr : will be modified to indicate how many bytes where read from 'src' to fill 'dst'.
+ *               New value is necessarily <= input value.
+ * @return : Nb bytes written into 'dst' (necessarily <= targetDestSize)
+ *           or 0 if compression fails.
+*/
+LZ4LIB_API int LZ4_compress_destSize (const char* src, char* dst, int* srcSizePtr, int targetDstSize);
+
+
+/*! LZ4_decompress_fast() : **unsafe!**
+ *  This function used to be a bit faster than LZ4_decompress_safe(),
+ *  though situation has changed in recent versions,
+ *  and now `LZ4_decompress_safe()` can be as fast and sometimes faster than `LZ4_decompress_fast()`.
+ *  Moreover, LZ4_decompress_fast() is not protected vs malformed input, as it doesn't perform full validation of compressed data.
+ *  As a consequence, this function is no longer recommended, and may be deprecated in future versions.
+ *  It's only remaining specificity is that it can decompress data without knowing its compressed size.
+ *
+ *  originalSize : is the uncompressed size to regenerate.
+ *                 `dst` must be already allocated, its size must be >= 'originalSize' bytes.
+ * @return : number of bytes read from source buffer (== compressed size).
+ *           If the source stream is detected malformed, the function stops decoding and returns a negative result.
+ *  note : This function requires uncompressed originalSize to be known in advance.
+ *         The function never writes past the output buffer.
+ *         However, since it doesn't know its 'src' size, it may read past the intended input.
+ *         Also, because match offsets are not validated during decoding,
+ *         reads from 'src' may underflow.
+ *         Use this function in trusted environment **only**.
+ */
+LZ4LIB_API int LZ4_decompress_fast (const char* src, char* dst, int originalSize);
+
+/*! LZ4_decompress_safe_partial() :
+ *  Decompress an LZ4 compressed block, of size 'srcSize' at position 'src',
+ *  into destination buffer 'dst' of size 'dstCapacity'.
+ *  Up to 'targetOutputSize' bytes will be decoded.
+ *  The function stops decoding on reaching this objective,
+ *  which can boost performance when only the beginning of a block is required.
+ *
+ * @return : the number of bytes decoded in `dst` (necessarily <= dstCapacity)
+ *           If source stream is detected malformed, function returns a negative result.
+ *
+ *  Note : @return can be < targetOutputSize, if compressed block contains less data.
+ *
+ *  Note 2 : this function features 2 parameters, targetOutputSize and dstCapacity,
+ *           and expects targetOutputSize <= dstCapacity.
+ *           It effectively stops decoding on reaching targetOutputSize,
+ *           so dstCapacity is kind of redundant.
+ *           This is because in a previous version of this function,
+ *           decoding operation would not "break" a sequence in the middle.
+ *           As a consequence, there was no guarantee that decoding would stop at exactly targetOutputSize,
+ *           it could write more bytes, though only up to dstCapacity.
+ *           Some "margin" used to be required for this operation to work properly.
+ *           This is no longer necessary.
+ *           The function nonetheless keeps its signature, in an effort to not break API.
+ */
+LZ4LIB_API int LZ4_decompress_safe_partial (const char* src, char* dst, int srcSize, int targetOutputSize, int dstCapacity);
+
+
+/*-*********************************************
+*  Streaming Compression Functions
+***********************************************/
+typedef union LZ4_stream_u LZ4_stream_t;  /* incomplete type (defined later) */
+
+/*! LZ4_createStream() and LZ4_freeStream() :
+ *  LZ4_createStream() will allocate and initialize an `LZ4_stream_t` structure.
+ *  LZ4_freeStream() releases its memory.
+ */
+LZ4LIB_API LZ4_stream_t* LZ4_createStream(void);
+LZ4LIB_API int           LZ4_freeStream (LZ4_stream_t* streamPtr);
+
+/*! LZ4_resetStream() :
+ *  An LZ4_stream_t structure can be allocated once and re-used multiple times.
+ *  Use this function to start compressing a new stream.
+ */
+LZ4LIB_API void LZ4_resetStream (LZ4_stream_t* streamPtr);
+
+/*! LZ4_loadDict() :
+ *  Use this function to load a static dictionary into LZ4_stream_t.
+ *  Any previous data will be forgotten, only 'dictionary' will remain in memory.
+ *  Loading a size of 0 is allowed, and is the same as reset.
+ * @return : dictionary size, in bytes (necessarily <= 64 KB)
+ */
+LZ4LIB_API int LZ4_loadDict (LZ4_stream_t* streamPtr, const char* dictionary, int dictSize);
+
+/*! LZ4_compress_fast_continue() :
+ *  Compress 'src' content using data from previously compressed blocks, for better compression ratio.
+ *  'dst' buffer must be already allocated.
+ *  If dstCapacity >= LZ4_compressBound(srcSize), compression is guaranteed to succeed, and runs faster.
+ *
+ * @return : size of compressed block
+ *           or 0 if there is an error (typically, cannot fit into 'dst').
+ *
+ *  Note 1 : Each invocation to LZ4_compress_fast_continue() generates a new block.
+ *           Each block has precise boundaries.
+ *           It's not possible to append blocks together and expect a single invocation of LZ4_decompress_*() to decompress them together.
+ *           Each block must be decompressed separately, calling LZ4_decompress_*() with associated metadata.
+ *
+ *  Note 2 : The previous 64KB of source data is __assumed__ to remain present, unmodified, at same address in memory!
+ *
+ *  Note 3 : When input is structured as a double-buffer, each buffer can have any size, including < 64 KB.
+ *           Make sure that buffers are separated, by at least one byte.
+ *           This construction ensures that each block only depends on previous block.
+ *
+ *  Note 4 : If input buffer is a ring-buffer, it can have any size, including < 64 KB.
+ *
+ *  Note 5 : After an error, the stream status is invalid, it can only be reset or freed.
+ */
+LZ4LIB_API int LZ4_compress_fast_continue (LZ4_stream_t* streamPtr, const char* src, char* dst, int srcSize, int dstCapacity, int acceleration);
+
+/*! LZ4_saveDict() :
+ *  If last 64KB data cannot be guaranteed to remain available at its current memory location,
+ *  save it into a safer place (char* safeBuffer).
+ *  This is schematically equivalent to a memcpy() followed by LZ4_loadDict(),
+ *  but is much faster, because LZ4_saveDict() doesn't need to rebuild tables.
+ * @return : saved dictionary size in bytes (necessarily <= maxDictSize), or 0 if error.
+ */
+LZ4LIB_API int LZ4_saveDict (LZ4_stream_t* streamPtr, char* safeBuffer, int maxDictSize);
+
+
+/*-**********************************************
+*  Streaming Decompression Functions
+*  Bufferless synchronous API
+************************************************/
+typedef union LZ4_streamDecode_u LZ4_streamDecode_t;   /* tracking context */
+
+/*! LZ4_createStreamDecode() and LZ4_freeStreamDecode() :
+ *  creation / destruction of streaming decompression tracking context.
+ *  A tracking context can be re-used multiple times.
+ */
+LZ4LIB_API LZ4_streamDecode_t* LZ4_createStreamDecode(void);
+LZ4LIB_API int                 LZ4_freeStreamDecode (LZ4_streamDecode_t* LZ4_stream);
+
+/*! LZ4_setStreamDecode() :
+ *  An LZ4_streamDecode_t context can be allocated once and re-used multiple times.
+ *  Use this function to start decompression of a new stream of blocks.
+ *  A dictionary can optionally be set. Use NULL or size 0 for a reset order.
+ *  Dictionary is presumed stable : it must remain accessible and unmodified during next decompression.
+ * @return : 1 if OK, 0 if error
+ */
+LZ4LIB_API int LZ4_setStreamDecode (LZ4_streamDecode_t* LZ4_streamDecode, const char* dictionary, int dictSize);
+
+/*! LZ4_decoderRingBufferSize() : v1.8.2
+ *  Note : in a ring buffer scenario (optional),
+ *  blocks are presumed decompressed next to each other
+ *  up to the moment there is not enough remaining space for next block (remainingSize < maxBlockSize),
+ *  at which stage it resumes from beginning of ring buffer.
+ *  When setting such a ring buffer for streaming decompression,
+ *  provides the minimum size of this ring buffer
+ *  to be compatible with any source respecting maxBlockSize condition.
+ * @return : minimum ring buffer size,
+ *           or 0 if there is an error (invalid maxBlockSize).
+ */
+LZ4LIB_API int LZ4_decoderRingBufferSize(int maxBlockSize);
+#define LZ4_DECODER_RING_BUFFER_SIZE(mbs) (65536 + 14 + (mbs))  /* for static allocation; mbs presumed valid */
+
+/*! LZ4_decompress_*_continue() :
+ *  These decoding functions allow decompression of consecutive blocks in "streaming" mode.
+ *  A block is an unsplittable entity, it must be presented entirely to a decompression function.
+ *  Decompression functions only accepts one block at a time.
+ *  The last 64KB of previously decoded data *must* remain available and unmodified at the memory position where they were decoded.
+ *  If less than 64KB of data has been decoded, all the data must be present.
+ *
+ *  Special : if decompression side sets a ring buffer, it must respect one of the following conditions :
+ *  - Decompression buffer size is _at least_ LZ4_decoderRingBufferSize(maxBlockSize).
+ *    maxBlockSize is the maximum size of any single block. It can have any value > 16 bytes.
+ *    In which case, encoding and decoding buffers do not need to be synchronized.
+ *    Actually, data can be produced by any source compliant with LZ4 format specification, and respecting maxBlockSize.
+ *  - Synchronized mode :
+ *    Decompression buffer size is _exactly_ the same as compression buffer size,
+ *    and follows exactly same update rule (block boundaries at same positions),
+ *    and decoding function is provided with exact decompressed size of each block (exception for last block of the stream),
+ *    _then_ decoding & encoding ring buffer can have any size, including small ones ( < 64 KB).
+ *  - Decompression buffer is larger than encoding buffer, by a minimum of maxBlockSize more bytes.
+ *    In which case, encoding and decoding buffers do not need to be synchronized,
+ *    and encoding ring buffer can have any size, including small ones ( < 64 KB).
+ *
+ *  Whenever these conditions are not possible,
+ *  save the last 64KB of decoded data into a safe buffer where it can't be modified during decompression,
+ *  then indicate where this data is saved using LZ4_setStreamDecode(), before decompressing next block.
+*/
+LZ4LIB_API int LZ4_decompress_safe_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* src, char* dst, int srcSize, int dstCapacity);
+LZ4LIB_API int LZ4_decompress_fast_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* src, char* dst, int originalSize);
+
+
+/*! LZ4_decompress_*_usingDict() :
+ *  These decoding functions work the same as
+ *  a combination of LZ4_setStreamDecode() followed by LZ4_decompress_*_continue()
+ *  They are stand-alone, and don't need an LZ4_streamDecode_t structure.
+ *  Dictionary is presumed stable : it must remain accessible and unmodified during next decompression.
+ */
+LZ4LIB_API int LZ4_decompress_safe_usingDict (const char* src, char* dst, int srcSize, int dstCapcity, const char* dictStart, int dictSize);
+LZ4LIB_API int LZ4_decompress_fast_usingDict (const char* src, char* dst, int originalSize, const char* dictStart, int dictSize);
+
+
+/*^**********************************************
+ * !!!!!!   STATIC LINKING ONLY   !!!!!!
+ ***********************************************/
+
+/*-************************************
+ *  Unstable declarations
+ **************************************
+ * Declarations in this section should be considered unstable.
+ * Use at your own peril, etc., etc.
+ * They may be removed in the future.
+ * Their signatures may change.
+ **************************************/
+
+#ifdef LZ4_STATIC_LINKING_ONLY
+
+/*! LZ4_resetStream_fast() :
+ *  Use this, like LZ4_resetStream(), to prepare a context for a new chain of
+ *  calls to a streaming API (e.g., LZ4_compress_fast_continue()).
+ *
+ *  Note:
+ *  Using this in advance of a non- streaming-compression function is redundant,
+ *  and potentially bad for performance, since they all perform their own custom
+ *  reset internally.
+ *
+ *  Differences from LZ4_resetStream():
+ *  When an LZ4_stream_t is known to be in a internally coherent state,
+ *  it can often be prepared for a new compression with almost no work, only
+ *  sometimes falling back to the full, expensive reset that is always required
+ *  when the stream is in an indeterminate state (i.e., the reset performed by
+ *  LZ4_resetStream()).
+ *
+ *  LZ4_streams are guaranteed to be in a valid state when:
+ *  - returned from LZ4_createStream()
+ *  - reset by LZ4_resetStream()
+ *  - memset(stream, 0, sizeof(LZ4_stream_t)), though this is discouraged
+ *  - the stream was in a valid state and was reset by LZ4_resetStream_fast()
+ *  - the stream was in a valid state and was then used in any compression call
+ *    that returned success
+ *  - the stream was in an indeterminate state and was used in a compression
+ *    call that fully reset the state (e.g., LZ4_compress_fast_extState()) and
+ *    that returned success
+ *
+ *  When a stream isn't known to be in a valid state, it is not safe to pass to
+ *  any fastReset or streaming function. It must first be cleansed by the full
+ *  LZ4_resetStream().
+ */
+LZ4LIB_API void LZ4_resetStream_fast (LZ4_stream_t* streamPtr);
+
+/*! LZ4_compress_fast_extState_fastReset() :
+ *  A variant of LZ4_compress_fast_extState().
+ *
+ *  Using this variant avoids an expensive initialization step. It is only safe
+ *  to call if the state buffer is known to be correctly initialized already
+ *  (see above comment on LZ4_resetStream_fast() for a definition of "correctly
+ *  initialized"). From a high level, the difference is that this function
+ *  initializes the provided state with a call to something like
+ *  LZ4_resetStream_fast() while LZ4_compress_fast_extState() starts with a
+ *  call to LZ4_resetStream().
+ */
+LZ4LIB_API int LZ4_compress_fast_extState_fastReset (void* state, const char* src, char* dst, int srcSize, int dstCapacity, int acceleration);
+
+/*! LZ4_attach_dictionary() :
+ *  This is an experimental API that allows for the efficient use of a
+ *  static dictionary many times.
+ *
+ *  Rather than re-loading the dictionary buffer into a working context before
+ *  each compression, or copying a pre-loaded dictionary's LZ4_stream_t into a
+ *  working LZ4_stream_t, this function introduces a no-copy setup mechanism,
+ *  in which the working stream references the dictionary stream in-place.
+ *
+ *  Several assumptions are made about the state of the dictionary stream.
+ *  Currently, only streams which have been prepared by LZ4_loadDict() should
+ *  be expected to work.
+ *
+ *  Alternatively, the provided dictionary stream pointer may be NULL, in which
+ *  case any existing dictionary stream is unset.
+ *
+ *  If a dictionary is provided, it replaces any pre-existing stream history.
+ *  The dictionary contents are the only history that can be referenced and
+ *  logically immediately precede the data compressed in the first subsequent
+ *  compression call.
+ *
+ *  The dictionary will only remain attached to the working stream through the
+ *  first compression call, at the end of which it is cleared. The dictionary
+ *  stream (and source buffer) must remain in-place / accessible / unchanged
+ *  through the completion of the first compression call on the stream.
+ */
+LZ4LIB_API void LZ4_attach_dictionary(LZ4_stream_t *working_stream, const LZ4_stream_t *dictionary_stream);
+
+#endif
+
+/*-************************************
+ *  Private definitions
+ **************************************
+ * Do not use these definitions.
+ * They are exposed to allow static allocation of `LZ4_stream_t` and `LZ4_streamDecode_t`.
+ * Using these definitions will expose code to API and/or ABI break in future versions of the library.
+ **************************************/
+#define LZ4_HASHLOG   (LZ4_MEMORY_USAGE-2)
+#define LZ4_HASHTABLESIZE (1 << LZ4_MEMORY_USAGE)
+#define LZ4_HASH_SIZE_U32 (1 << LZ4_HASHLOG)       /* required as macro for static allocation */
+
+#if defined(__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */)
+#include <stdint.h>
+
+typedef struct LZ4_stream_t_internal LZ4_stream_t_internal;
+struct LZ4_stream_t_internal {
+    uint32_t hashTable[LZ4_HASH_SIZE_U32];
+    uint32_t currentOffset;
+    uint16_t initCheck;
+    uint16_t tableType;
+    const uint8_t* dictionary;
+    const LZ4_stream_t_internal* dictCtx;
+    uint32_t dictSize;
+};
+
+typedef struct {
+    const uint8_t* externalDict;
+    size_t extDictSize;
+    const uint8_t* prefixEnd;
+    size_t prefixSize;
+} LZ4_streamDecode_t_internal;
+
+#else
+
+typedef struct LZ4_stream_t_internal LZ4_stream_t_internal;
+struct LZ4_stream_t_internal {
+    unsigned int hashTable[LZ4_HASH_SIZE_U32];
+    unsigned int currentOffset;
+    unsigned short initCheck;
+    unsigned short tableType;
+    const unsigned char* dictionary;
+    const LZ4_stream_t_internal* dictCtx;
+    unsigned int dictSize;
+};
+
+typedef struct {
+    const unsigned char* externalDict;
+    size_t extDictSize;
+    const unsigned char* prefixEnd;
+    size_t prefixSize;
+} LZ4_streamDecode_t_internal;
+
+#endif
+
+/*!
+ * LZ4_stream_t :
+ * information structure to track an LZ4 stream.
+ * init this structure before first use.
+ * note : only use in association with static linking !
+ *        this definition is not API/ABI safe,
+ *        it may change in a future version !
+ */
+#define LZ4_STREAMSIZE_U64 ((1 << (LZ4_MEMORY_USAGE-3)) + 4)
+#define LZ4_STREAMSIZE     (LZ4_STREAMSIZE_U64 * sizeof(unsigned long long))
+union LZ4_stream_u {
+    unsigned long long table[LZ4_STREAMSIZE_U64];
+    LZ4_stream_t_internal internal_donotuse;
+} ;  /* previously typedef'd to LZ4_stream_t */
+
+
+/*!
+ * LZ4_streamDecode_t :
+ * information structure to track an LZ4 stream during decompression.
+ * init this structure  using LZ4_setStreamDecode (or memset()) before first use
+ * note : only use in association with static linking !
+ *        this definition is not API/ABI safe,
+ *        and may change in a future version !
+ */
+#define LZ4_STREAMDECODESIZE_U64  4
+#define LZ4_STREAMDECODESIZE     (LZ4_STREAMDECODESIZE_U64 * sizeof(unsigned long long))
+union LZ4_streamDecode_u {
+    unsigned long long table[LZ4_STREAMDECODESIZE_U64];
+    LZ4_streamDecode_t_internal internal_donotuse;
+} ;   /* previously typedef'd to LZ4_streamDecode_t */
+
+
+/*-************************************
+*  Obsolete Functions
+**************************************/
+
+/*! Deprecation warnings
+   Should deprecation warnings be a problem,
+   it is generally possible to disable them,
+   typically with -Wno-deprecated-declarations for gcc
+   or _CRT_SECURE_NO_WARNINGS in Visual.
+   Otherwise, it's also possible to define LZ4_DISABLE_DEPRECATE_WARNINGS */
+#ifdef LZ4_DISABLE_DEPRECATE_WARNINGS
+#  define LZ4_DEPRECATED(message)   /* disable deprecation warnings */
+#else
+#  define LZ4_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)
+#  if defined (__cplusplus) && (__cplusplus >= 201402) /* C++14 or greater */
+#    define LZ4_DEPRECATED(message) [[deprecated(message)]]
+#  elif (LZ4_GCC_VERSION >= 405) || defined(__clang__)
+#    define LZ4_DEPRECATED(message) __attribute__((deprecated(message)))
+#  elif (LZ4_GCC_VERSION >= 301)
+#    define LZ4_DEPRECATED(message) __attribute__((deprecated))
+#  elif defined(_MSC_VER)
+#    define LZ4_DEPRECATED(message) __declspec(deprecated(message))
+#  else
+#    pragma message("WARNING: You need to implement LZ4_DEPRECATED for this compiler")
+#    define LZ4_DEPRECATED(message)
+#  endif
+#endif /* LZ4_DISABLE_DEPRECATE_WARNINGS */
+
+/* Obsolete compression functions */
+LZ4_DEPRECATED("use LZ4_compress_default() instead") LZ4LIB_API int LZ4_compress               (const char* source, char* dest, int sourceSize);
+LZ4_DEPRECATED("use LZ4_compress_default() instead") LZ4LIB_API int LZ4_compress_limitedOutput (const char* source, char* dest, int sourceSize, int maxOutputSize);
+LZ4_DEPRECATED("use LZ4_compress_fast_extState() instead") LZ4LIB_API int LZ4_compress_withState               (void* state, const char* source, char* dest, int inputSize);
+LZ4_DEPRECATED("use LZ4_compress_fast_extState() instead") LZ4LIB_API int LZ4_compress_limitedOutput_withState (void* state, const char* source, char* dest, int inputSize, int maxOutputSize);
+LZ4_DEPRECATED("use LZ4_compress_fast_continue() instead") LZ4LIB_API int LZ4_compress_continue                (LZ4_stream_t* LZ4_streamPtr, const char* source, char* dest, int inputSize);
+LZ4_DEPRECATED("use LZ4_compress_fast_continue() instead") LZ4LIB_API int LZ4_compress_limitedOutput_continue  (LZ4_stream_t* LZ4_streamPtr, const char* source, char* dest, int inputSize, int maxOutputSize);
+
+/* Obsolete decompression functions */
+LZ4_DEPRECATED("use LZ4_decompress_fast() instead") LZ4LIB_API int LZ4_uncompress (const char* source, char* dest, int outputSize);
+LZ4_DEPRECATED("use LZ4_decompress_safe() instead") LZ4LIB_API int LZ4_uncompress_unknownOutputSize (const char* source, char* dest, int isize, int maxOutputSize);
+
+/* Obsolete streaming functions; degraded functionality; do not use!
+ *
+ * In order to perform streaming compression, these functions depended on data
+ * that is no longer tracked in the state. They have been preserved as well as
+ * possible: using them will still produce a correct output. However, they don't
+ * actually retain any history between compression calls. The compression ratio
+ * achieved will therefore be no better than compressing each chunk
+ * independently.
+ */
+LZ4_DEPRECATED("Use LZ4_createStream() instead") LZ4LIB_API void* LZ4_create (char* inputBuffer);
+LZ4_DEPRECATED("Use LZ4_createStream() instead") LZ4LIB_API int   LZ4_sizeofStreamState(void);
+LZ4_DEPRECATED("Use LZ4_resetStream() instead") LZ4LIB_API  int   LZ4_resetStreamState(void* state, char* inputBuffer);
+LZ4_DEPRECATED("Use LZ4_saveDict() instead") LZ4LIB_API     char* LZ4_slideInputBuffer (void* state);
+
+/* Obsolete streaming decoding functions */
+LZ4_DEPRECATED("use LZ4_decompress_safe_usingDict() instead") LZ4LIB_API int LZ4_decompress_safe_withPrefix64k (const char* src, char* dst, int compressedSize, int maxDstSize);
+LZ4_DEPRECATED("use LZ4_decompress_fast_usingDict() instead") LZ4LIB_API int LZ4_decompress_fast_withPrefix64k (const char* src, char* dst, int originalSize);
+
+#endif /* LZ4_H_2983827168210 */
+
+
+#if defined (__cplusplus)
+}
+#endif

+ 194 - 0
Source/Native/mingw/inet_ntop.c

@@ -0,0 +1,194 @@
+/*
+ * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (c) 1996-1999 by Internet Software Consortium.
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
+ * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+#if defined(LIBC_SCCS) && !defined(lint)
+static const char rcsid[] = "$Id: inet_ntop.c,v 1.3.18.2 2005/11/03 23:02:22 marka Exp $";
+#endif /* LIBC_SCCS and not lint */
+
+#ifdef __FreeBSD__
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD: stable/9/sys/libkern/inet_ntop.c 213103 2010-09-24 15:01:45Z attilio $");
+#endif
+
+#if !defined(_WIN32)
+#include <sys/param.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#else
+#include <ws2tcpip.h>
+#endif
+
+#include <stdio.h>
+#include <string.h>
+
+#if !defined(_WIN32) && __FreeBSD_version < 700000
+#define strchr index
+#endif
+
+/*%
+ * WARNING: Don't even consider trying to compile this on a system where
+ * sizeof(int) < 4.  sizeof(int) > 4 is fine; all the world's not a VAX.
+ */
+
+static char *inet_ntop4(const u_char * src, char *dst, socklen_t size);
+static char *inet_ntop6(const u_char * src, char *dst, socklen_t size);
+
+/* char *
+ * inet_ntop(af, src, dst, size)
+ *	convert a network format address to presentation format.
+ * return:
+ *	pointer to presentation format address (`dst'), or NULL (see errno).
+ * author:
+ *	Paul Vixie, 1996.
+ */
+char *inet_ntop(int af, const void *src, char *dst, socklen_t size)
+{
+    switch (af) {
+    case AF_INET:
+        return (inet_ntop4(src, dst, size));
+    case AF_INET6:
+        return (inet_ntop6(src, dst, size));
+    default:
+        return (NULL);
+    }
+    /* NOTREACHED */
+}
+
+/* const char *
+ * inet_ntop4(src, dst, size)
+ *	format an IPv4 address
+ * return:
+ *	`dst' (as a const)
+ * notes:
+ *	(1) uses no statics
+ *	(2) takes a u_char* not an in_addr as input
+ * author:
+ *	Paul Vixie, 1996.
+ */
+static char *inet_ntop4(const u_char * src, char *dst, socklen_t size)
+{
+    static const char fmt[] = "%u.%u.%u.%u";
+    char tmp[sizeof "255.255.255.255"];
+    int l;
+
+    l = snprintf(tmp, sizeof(tmp), fmt, src[0], src[1], src[2], src[3]);
+    if (l <= 0 || (socklen_t) l >= size) {
+        return (NULL);
+    }
+//      strlcpy(dst, tmp, size);
+    memcpy(dst, tmp, size);
+    dst[size] = '\0';
+    return (dst);
+}
+
+/* const char *
+ * inet_ntop6(src, dst, size)
+ *	convert IPv6 binary address into presentation (printable) format
+ * author:
+ *	Paul Vixie, 1996.
+ */
+static char *inet_ntop6(const u_char * src, char *dst, socklen_t size)
+{
+    /*
+     * Note that int32_t and int16_t need only be "at least" large enough
+     * to contain a value of the specified size.  On some systems, like
+     * Crays, there is no such thing as an integer variable with 16 bits.
+     * Keep this in mind if you think this function should have been coded
+     * to use pointer overlays.  All the world's not a VAX.
+     */
+    char tmp[sizeof "ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255"], *tp;
+    struct {
+        int base, len;
+    } best, cur;
+#define NS_IN6ADDRSZ	16
+#define NS_INT16SZ	2
+    u_int words[NS_IN6ADDRSZ / NS_INT16SZ];
+    int i;
+
+    /*
+     * Preprocess:
+     *      Copy the input (bytewise) array into a wordwise array.
+     *      Find the longest run of 0x00's in src[] for :: shorthanding.
+     */
+    memset(words, '\0', sizeof words);
+    for (i = 0; i < NS_IN6ADDRSZ; i++)
+        words[i / 2] |= (src[i] << ((1 - (i % 2)) << 3));
+    best.base = -1;
+    best.len = 0;
+    cur.base = -1;
+    cur.len = 0;
+    for (i = 0; i < (NS_IN6ADDRSZ / NS_INT16SZ); i++) {
+        if (words[i] == 0) {
+            if (cur.base == -1)
+                cur.base = i, cur.len = 1;
+            else
+                cur.len++;
+        } else {
+            if (cur.base != -1) {
+                if (best.base == -1 || cur.len > best.len)
+                    best = cur;
+                cur.base = -1;
+            }
+        }
+    }
+    if (cur.base != -1) {
+        if (best.base == -1 || cur.len > best.len)
+            best = cur;
+    }
+    if (best.base != -1 && best.len < 2)
+        best.base = -1;
+
+    /*
+     * Format the result.
+     */
+    tp = tmp;
+    for (i = 0; i < (NS_IN6ADDRSZ / NS_INT16SZ); i++) {
+        /* Are we inside the best run of 0x00's? */
+        if (best.base != -1 && i >= best.base && i < (best.base + best.len)) {
+            if (i == best.base)
+                *tp++ = ':';
+            continue;
+        }
+        /* Are we following an initial run of 0x00s or any real hex? */
+        if (i != 0)
+            *tp++ = ':';
+        /* Is this address an encapsulated IPv4? */
+        if (i == 6 && best.base == 0 && (best.len == 6 ||
+                                         (best.len == 7 && words[7] != 0x0001) ||
+                                         (best.len == 5 && words[5] == 0xffff))) {
+            if (!inet_ntop4(src + 12, tp, sizeof tmp - (tp - tmp)))
+                return (NULL);
+            tp += strlen(tp);
+            break;
+        }
+        tp += sprintf(tp, "%x", words[i]);
+    }
+    /* Was it a trailing run of 0x00's? */
+    if (best.base != -1 && (best.base + best.len) == (NS_IN6ADDRSZ / NS_INT16SZ))
+        *tp++ = ':';
+    *tp++ = '\0';
+
+    /*
+     * Check for overflow, copy, and we're done.
+     */
+    if ((socklen_t) (tp - tmp) > size) {
+        return (NULL);
+    }
+    strcpy(dst, tmp);
+    return (dst);
+}
+/*! \file */

+ 222 - 0
Source/Native/mingw/inet_pton.c

@@ -0,0 +1,222 @@
+/*
+ * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (c) 1996,1999 by Internet Software Consortium.
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
+ * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+#if defined(LIBC_SCCS) && !defined(lint)
+static const char rcsid[] = "$Id: inet_pton.c,v 1.3.18.2 2005/07/28 07:38:07 marka Exp $";
+#endif /* LIBC_SCCS and not lint */
+
+#ifdef __FreeBSD__
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD: stable/9/sys/libkern/inet_pton.c 213103 2010-09-24 15:01:45Z attilio $");
+#endif
+
+#if !defined(_WIN32) 
+#include <sys/param.h>
+#include <sys/socket.h>
+
+#include <netinet/in.h>
+#else
+#include <ws2tcpip.h>
+#endif
+
+#include <stdio.h>
+#include <string.h>
+
+#if !defined(_WIN32) && __FreeBSD_version < 700000
+#define strchr index
+#endif
+
+/*%
+ * WARNING: Don't even consider trying to compile this on a system where
+ * sizeof(int) < 4.  sizeof(int) > 4 is fine; all the world's not a VAX.
+ */
+
+static int inet_pton4(const char *src, u_char * dst);
+static int inet_pton6(const char *src, u_char * dst);
+
+/* int
+ * inet_pton(af, src, dst)
+ *	convert from presentation format (which usually means ASCII printable)
+ *	to network format (which is usually some kind of binary format).
+ * return:
+ *	1 if the address was valid for the specified address family
+ *	0 if the address wasn't valid (`dst' is untouched in this case)
+ *	-1 if some other error occurred (`dst' is untouched in this case, too)
+ * author:
+ *	Paul Vixie, 1996.
+ */
+int inet_pton(int af, const char *src, void *dst)
+{
+    switch (af) {
+    case AF_INET:
+        return (inet_pton4(src, dst));
+    case AF_INET6:
+        return (inet_pton6(src, dst));
+    default:
+        return (-1);
+    }
+    /* NOTREACHED */
+}
+
+/* int
+ * inet_pton4(src, dst)
+ *	like inet_aton() but without all the hexadecimal and shorthand.
+ * return:
+ *	1 if `src' is a valid dotted quad, else 0.
+ * notice:
+ *	does not touch `dst' unless it's returning 1.
+ * author:
+ *	Paul Vixie, 1996.
+ */
+static int inet_pton4(const char *src, u_char * dst)
+{
+    static const char digits[] = "0123456789";
+    int saw_digit, octets, ch;
+#define NS_INADDRSZ	4
+    u_char tmp[NS_INADDRSZ], *tp;
+
+    saw_digit = 0;
+    octets = 0;
+    *(tp = tmp) = 0;
+    while ((ch = *src++) != '\0') {
+        const char *pch;
+
+        if ((pch = strchr(digits, ch)) != NULL) {
+            u_int new = *tp * 10 + (pch - digits);
+
+            if (saw_digit && *tp == 0)
+                return (0);
+            if (new > 255)
+                return (0);
+            *tp = new;
+            if (!saw_digit) {
+                if (++octets > 4)
+                    return (0);
+                saw_digit = 1;
+            }
+        } else if (ch == '.' && saw_digit) {
+            if (octets == 4)
+                return (0);
+            *++tp = 0;
+            saw_digit = 0;
+        } else
+            return (0);
+    }
+    if (octets < 4)
+        return (0);
+    memcpy(dst, tmp, NS_INADDRSZ);
+    return (1);
+}
+
+/* int
+ * inet_pton6(src, dst)
+ *	convert presentation level address to network order binary form.
+ * return:
+ *	1 if `src' is a valid [RFC1884 2.2] address, else 0.
+ * notice:
+ *	(1) does not touch `dst' unless it's returning 1.
+ *	(2) :: in a full address is silently ignored.
+ * credit:
+ *	inspired by Mark Andrews.
+ * author:
+ *	Paul Vixie, 1996.
+ */
+static int inet_pton6(const char *src, u_char * dst)
+{
+    static const char xdigits_l[] = "0123456789abcdef", xdigits_u[] = "0123456789ABCDEF";
+#define NS_IN6ADDRSZ	16
+#define NS_INT16SZ	2
+    u_char tmp[NS_IN6ADDRSZ], *tp, *endp, *colonp;
+    const char *xdigits, *curtok;
+    int ch, seen_xdigits;
+    u_int val;
+
+    memset((tp = tmp), '\0', NS_IN6ADDRSZ);
+    endp = tp + NS_IN6ADDRSZ;
+    colonp = NULL;
+    /* Leading :: requires some special handling. */
+    if (*src == ':')
+        if (*++src != ':')
+            return (0);
+    curtok = src;
+    seen_xdigits = 0;
+    val = 0;
+    while ((ch = *src++) != '\0') {
+        const char *pch;
+
+        if ((pch = strchr((xdigits = xdigits_l), ch)) == NULL)
+            pch = strchr((xdigits = xdigits_u), ch);
+        if (pch != NULL) {
+            val <<= 4;
+            val |= (pch - xdigits);
+            if (++seen_xdigits > 4)
+                return (0);
+            continue;
+        }
+        if (ch == ':') {
+            curtok = src;
+            if (!seen_xdigits) {
+                if (colonp)
+                    return (0);
+                colonp = tp;
+                continue;
+            } else if (*src == '\0') {
+                return (0);
+            }
+            if (tp + NS_INT16SZ > endp)
+                return (0);
+            *tp++ = (u_char) (val >> 8) & 0xff;
+            *tp++ = (u_char) val & 0xff;
+            seen_xdigits = 0;
+            val = 0;
+            continue;
+        }
+        if (ch == '.' && ((tp + NS_INADDRSZ) <= endp) && inet_pton4(curtok, tp) > 0) {
+            tp += NS_INADDRSZ;
+            seen_xdigits = 0;
+            break;              /*%< '\\0' was seen by inet_pton4(). */
+        }
+        return (0);
+    }
+    if (seen_xdigits) {
+        if (tp + NS_INT16SZ > endp)
+            return (0);
+        *tp++ = (u_char) (val >> 8) & 0xff;
+        *tp++ = (u_char) val & 0xff;
+    }
+    if (colonp != NULL) {
+        /*
+         * Since some memmove()'s erroneously fail to handle
+         * overlapping regions, we'll do the shift by hand.
+         */
+        const int n = tp - colonp;
+        int i;
+
+        if (tp == endp)
+            return (0);
+        for (i = 1; i <= n; i++) {
+            endp[-i] = colonp[n - i];
+            colonp[n - i] = 0;
+        }
+        tp = endp;
+    }
+    if (tp != endp)
+        return (0);
+    memcpy(dst, tmp, NS_IN6ADDRSZ);
+    return (1);
+}
+/*! \file */