#include "select_poller.h"

#include <util/generic/ylimits.h>

void NSrvKernel::TSelectPoller::WaitRead(SOCKET sock, void* cookie) {
    Impl_.Set(cookie, sock, CONT_POLL_READ);
}

void NSrvKernel::TSelectPoller::WaitWrite(SOCKET sock, void* cookie) {
    Impl_.Set(cookie, sock, CONT_POLL_WRITE);
}

void NSrvKernel::TSelectPoller::Unwait(SOCKET sock) {
    Impl_.Remove(sock);
}

void* NSrvKernel::TSelectPoller::WaitI() {
    TImpl::TEvent tmp;

    bool succeed = false;
    for (unsigned attempt = 0; !succeed && attempt < 10; ++attempt) {
        if (Impl_.Wait(&tmp, 1, Max<int>())) {
            succeed = true;
            break;
        }
    }

    if (succeed) {
        return tmp.Data();
    }

    return nullptr;
}
