Browse Source

Kernel: Add TCPSocket::try_for_each() for fallible iteration

This API will allow users to short circuit iteration and properly
propagate errors.
Idan Horowitz 3 years ago
parent
commit
aabc8d348b
2 changed files with 10 additions and 0 deletions
  1. 9 0
      Kernel/Net/TCPSocket.cpp
  2. 1 0
      Kernel/Net/TCPSocket.h

+ 9 - 0
Kernel/Net/TCPSocket.cpp

@@ -29,6 +29,15 @@ void TCPSocket::for_each(Function<void(const TCPSocket&)> callback)
     });
 }
 
+ErrorOr<void> TCPSocket::try_for_each(Function<ErrorOr<void>(const TCPSocket&)> callback)
+{
+    return sockets_by_tuple().with_shared([&](const auto& sockets) -> ErrorOr<void> {
+        for (auto& it : sockets)
+            TRY(callback(*it.value));
+        return {};
+    });
+}
+
 bool TCPSocket::unref() const
 {
     bool did_hit_zero = sockets_by_tuple().with_exclusive([&](auto& table) {

+ 1 - 0
Kernel/Net/TCPSocket.h

@@ -19,6 +19,7 @@ namespace Kernel {
 class TCPSocket final : public IPv4Socket {
 public:
     static void for_each(Function<void(const TCPSocket&)>);
+    static ErrorOr<void> try_for_each(Function<ErrorOr<void>(const TCPSocket&)>);
     static ErrorOr<NonnullRefPtr<TCPSocket>> try_create(int protocol, NonnullOwnPtr<DoubleBuffer> receive_buffer);
     virtual ~TCPSocket() override;