summaryrefslogtreecommitdiff
path: root/AK
diff options
context:
space:
mode:
authorAndreas Kling <awesomekling@gmail.com>2019-04-02 20:04:54 +0200
committerAndreas Kling <awesomekling@gmail.com>2019-04-02 20:04:54 +0200
commit17e02e7450adf6e0bdf6156b3fc1ed58f0f3c258 (patch)
tree3dd424d02a71c6c0c15a2c7507957e94f74562ee /AK
parent649c81a714e120a300439ca5d3fdd5e7f6f6b34d (diff)
downloadserenity-17e02e7450adf6e0bdf6156b3fc1ed58f0f3c258.zip
Move NetworkOrdered.h to AK/ since it's used in both kernel and userspace.
Diffstat (limited to 'AK')
-rw-r--r--AK/NetworkOrdered.h48
1 files changed, 48 insertions, 0 deletions
diff --git a/AK/NetworkOrdered.h b/AK/NetworkOrdered.h
new file mode 100644
index 0000000000..b5dc404103
--- /dev/null
+++ b/AK/NetworkOrdered.h
@@ -0,0 +1,48 @@
+#pragma once
+
+#include <AK/Types.h>
+
+template<typename T>
+T convert_between_host_and_network(T host_value)
+{
+ if constexpr (sizeof(T) == 4) {
+ auto* s = (byte*)&host_value;
+ return (dword)(s[0] << 24 | s[1] << 16 | s[2] << 8 | s[3]);
+ }
+ if constexpr (sizeof(T) == 2) {
+ auto* s = (byte*)&host_value;
+ return (word)(s[0] << 8 | s[1]);
+ }
+ if constexpr (sizeof(T) == 1)
+ return host_value;
+}
+
+template<typename T>
+class [[gnu::packed]] NetworkOrdered {
+public:
+ NetworkOrdered()
+ : m_network_value(0)
+ {
+ }
+
+ NetworkOrdered(const T& host_value)
+ : m_network_value(convert_between_host_and_network(host_value))
+ {
+ }
+
+ NetworkOrdered(const NetworkOrdered& other)
+ : m_network_value(other.m_network_value)
+ {
+ }
+
+ NetworkOrdered& operator=(const NetworkOrdered& other)
+ {
+ m_network_value = other.m_network_value;
+ return *this;
+ }
+
+ operator T() const { return convert_between_host_and_network(m_network_value); }
+
+private:
+ T m_network_value { 0 };
+};