changeset 246:9cfa6fbc9c03

Socket: add operators for SocketAddress
author David Demelier <markand@malikania.fr>
date Mon, 29 Sep 2014 12:57:43 +0200
parents 3c12f0e8bbb9
children 806dbb6011c7
files C++/Socket.cpp C++/SocketAddress.cpp C++/SocketAddress.h
diffstat 3 files changed, 35 insertions(+), 2 deletions(-) [+]
line wrap: on
line diff
--- a/C++/Socket.cpp	Sun Sep 28 21:15:26 2014 +0200
+++ b/C++/Socket.cpp	Mon Sep 29 12:57:43 2014 +0200
@@ -16,7 +16,6 @@
  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  */
 
-#include <cerrno>
 #include <cstring>
 
 #include "Socket.h"
@@ -115,7 +114,6 @@
 	auto &sa = addr.address();
 	auto addrlen = addr.length();
 
-
 	if (::bind(s.handle(), (sockaddr *)&sa, addrlen) == SOCKET_ERROR)
 		throw SocketError(Socket::syserror());
 }
--- a/C++/SocketAddress.cpp	Sun Sep 28 21:15:26 2014 +0200
+++ b/C++/SocketAddress.cpp	Mon Sep 29 12:57:43 2014 +0200
@@ -16,6 +16,7 @@
  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  */
 
+#include <algorithm>
 #include <cstring>
 
 #include "Socket.h"
@@ -111,3 +112,19 @@
 {
 	return m_addrlen;
 }
+
+bool operator<(const SocketAddress &s1, const SocketAddress &s2)
+{
+	const auto &array1 = reinterpret_cast<const unsigned char *>(&s1.address());
+	const auto &array2 = reinterpret_cast<const unsigned char *>(&s2.address());
+
+	return std::lexicographical_compare(array1, array1 + s1.length(), array2, array2 + s2.length());
+}
+
+bool operator==(const SocketAddress &s1, const SocketAddress &s2)
+{
+	const auto &array1 = reinterpret_cast<const unsigned char *>(&s1.address());
+	const auto &array2 = reinterpret_cast<const unsigned char *>(&s2.address());
+
+	return std::equal(array1, array1 + s1.length(), array2, array2 + s2.length());
+}
--- a/C++/SocketAddress.h	Sun Sep 28 21:15:26 2014 +0200
+++ b/C++/SocketAddress.h	Mon Sep 29 12:57:43 2014 +0200
@@ -66,6 +66,24 @@
 	 * @return the address
 	 */
 	const sockaddr_storage &address() const;
+
+	/**
+	 * Compare the addresses. The check is lexicographical.
+	 *
+	 * @param s1 the first address
+	 * @param s2 the second address
+	 * @return true if s1 is less than s2
+	 */
+	friend bool operator<(const SocketAddress &s1, const SocketAddress &s2);
+
+	/**
+	 * Compare the addresses.
+	 *
+	 * @param s1 the first address
+	 * @param s2 the second address
+	 * @return true if s1 == s2
+	 */
+	friend bool operator==(const SocketAddress &s1, const SocketAddress &s2);
 };
 
 namespace address {