Files
42_INT_12_webserv/srcs/utils.cpp
2022-08-08 15:25:16 +02:00

145 lines
2.5 KiB
C++

#include "utils.hpp"
void throw_test()
{
static int i = 0;
++i;
if (i % 8 == 0)
throw std::bad_alloc();
}
std::vector<std::string> split(std::string input, char delimiter)
{
std::vector<std::string> answer;
std::stringstream ss(input);
std::string temp;
while (getline(ss, temp, delimiter))
answer.push_back(temp);
return answer;
}
std::string trim(std::string str, char c)
{
str = str.substr(str.find_first_not_of(c));
str = str.substr(0, str.find_last_not_of(c) + 1);
return str;
}
std::string itos(int n)
{
std::stringstream strs;
strs << n;
return ( strs.str() );
}
bool isNumeric(std::string str)
{
for (size_t i = 0; i < str.length(); i++)
{
if (std::isdigit(str[i]) == false)
return false;
}
return true;
}
bool isNumeric_btw(int low, int high, std::string str)
{
for (size_t i = 0; i < str.length(); i++)
{
if (std::isdigit(str[i]) == false)
return false;
}
int n = std::atoi(str.c_str());
if (n < low || n > high)
return false;
return true;
}
http_method str_to_http_method(std::string &str)
{
if (str == "GET")
return GET;
else if (str == "POST")
return POST;
else if (str == "DELETE")
return DELETE;
else if (str == "ALL_METHODS")
return ANY_METHODS;
// would prefere ALL_METHODS
return UNKNOWN;
}
std::string http_methods_to_str(unsigned int methods)
{
std::string str;
if (methods & GET)
str.append("GET");
if (methods & POST)
{
if (!str.empty())
str.append(", ");
str.append("POST");
}
if (methods & DELETE)
{
if (!str.empty())
str.append(", ");
str.append("DELETE");
}
return (str);
}
# include <iostream>
// you could make this &path...
int path_is_valid(std::string path)
{
const char *tmp_path = path.c_str();
struct stat s;
if (stat(tmp_path, &s) == 0)
{
if (S_ISREG(s.st_mode))
{
// std::cout << "is a file\n";
return (2);
}
else if (S_ISDIR(s.st_mode))
{
// std::cout << "is a Dir\n";
return (1);
}
}
// std::cout << "path is neither dir nor file\n";
return (0);
}
void replace_all_substr(std::string &str, const std::string &ori_substr, const std::string &new_substr)
{
if (ori_substr.empty())
return;
size_t pos = 0;
while (1)
{
pos = str.find(ori_substr, pos);
if (pos == std::string::npos)
break;
str.replace(pos, ori_substr.size(), new_substr);
pos += new_substr.size();
}
}
bool operator==(const listen_socket& lhs, int fd)
{ return lhs.fd == fd; }
bool operator==(int fd, const listen_socket& rhs)
{ return fd == rhs.fd; }