Program Listing for File Netio3Backend.cpp

Return to documentation for file (Netio3Backend.cpp)

#include "netio3-backend/Netio3Backend.hpp"

#include "BackendLibfabric/BackendLibfabric.hpp"
#include "BackendAsyncmsg/BackendAsyncmsg.hpp"

#include <iostream>
#include <memory>
#include <stdexcept>
#include <utility>

namespace netio3{
  EndPointAddress::EndPointAddress(const std::string& ip,
                                   unsigned short port) : m_ip(ip),
                                                          m_ip_numeric{convert_ip(m_ip)},
                                                          m_port(port) {
  }

  EndPointAddress::EndPointAddress(const std::string& str) {
    const auto cpos = str.find(':');
    m_ip = str.substr(0, cpos);
    if (cpos != std::string::npos) {
      m_port = std::stoi(str.substr(cpos+1));
    }
    else {
      m_port = 0;
    }
    m_ip_numeric = convert_ip(m_ip);
  }

  std::uint32_t EndPointAddress::convert_ip(const std::string& ip)
  {
    std::uint32_t ip_numeric{};
    if (inet_pton(AF_INET, ip.data(), &ip_numeric) != 1) {
      throw std::invalid_argument(std::format("Invalid IP address format: {}", ip));
    }
    return ip_numeric;
  }


  std::ostream& operator <<(std::ostream& stream, const EndPointAddress& val) {
    return stream << val.m_ip << ":" << val.m_port;
  }

  std::ostream& operator <<(std::ostream& stream, const NetworkConfig& cfg) {
    return stream << "{mode=" << static_cast<int>(cfg.mode) << "}";
  }

  NetworkBackend::NetworkBackend(NetworkConfig config, std::shared_ptr<BaseEventLoop> evloop) :
    m_config{std::move(config)},
    m_evloop{std::move(evloop)} {
  }

  std::unique_ptr<NetworkBackend> NetworkBackend::create(NetworkType type, const NetworkConfig& config, const std::shared_ptr<BaseEventLoop>& evloop) {
    switch (type) {
      case NetworkType::LIBFABRIC:
        return std::make_unique<libfabric::BackendLibfabric>(config, evloop);
      case NetworkType::ASYNCMSG:
        return std::make_unique<asyncmsg::BackendAsyncmsg>(config, evloop);
      default:
        throw std::invalid_argument("Error: unknown network type.");
    }
  }
}