Commit d673e215 authored by Dennis Jenkins's avatar Dennis Jenkins

Reformatted all .cc files with clang-format (default options). Reformatting...

Reformatted all .cc files with clang-format (default options).  Reformatting the .h files causes cppcheck to segfault, so I'll tackle those later.
parent 2447ef55
This diff is collapsed.
...@@ -4,20 +4,19 @@ ...@@ -4,20 +4,19 @@
Cookie implementation Cookie implementation
*/ */
#include <pistache/cookie.h>
#include <pistache/config.h> #include <pistache/config.h>
#include <pistache/cookie.h>
#include <pistache/stream.h> #include <pistache/stream.h>
#include <iterator> #include <iterator>
#include <unordered_map> #include <unordered_map>
namespace Pistache { namespace Pistache {
namespace Http { namespace Http {
namespace { namespace {
StreamCursor::Token matchValue(StreamCursor& cursor) { StreamCursor::Token matchValue(StreamCursor &cursor) {
int c; int c;
if ((c = cursor.current()) != StreamCursor::Eof && c != '=') if ((c = cursor.current()) != StreamCursor::Eof && c != '=')
throw std::runtime_error("Invalid cookie"); throw std::runtime_error("Invalid cookie");
...@@ -29,22 +28,21 @@ namespace { ...@@ -29,22 +28,21 @@ namespace {
match_until(';', cursor); match_until(';', cursor);
return token; return token;
} }
template<typename T> template <typename T> struct AttributeMatcher;
struct AttributeMatcher;
template<> template <> struct AttributeMatcher<Optional<std::string>> {
struct AttributeMatcher<Optional<std::string>> { static void match(StreamCursor &cursor, Cookie *obj,
static void match(StreamCursor& cursor, Cookie* obj, Optional<std::string> Cookie::*attr) { Optional<std::string> Cookie::*attr) {
auto token = matchValue(cursor); auto token = matchValue(cursor);
obj->*attr = Some(token.text()); obj->*attr = Some(token.text());
} }
}; };
template<> template <> struct AttributeMatcher<Optional<int>> {
struct AttributeMatcher<Optional<int>> { static void match(StreamCursor &cursor, Cookie *obj,
static void match(StreamCursor& cursor, Cookie* obj, Optional<int> Cookie::*attr) { Optional<int> Cookie::*attr) {
auto token = matchValue(cursor); auto token = matchValue(cursor);
auto strntol = [](const char *str, size_t len) { auto strntol = [](const char *str, size_t len) {
...@@ -62,26 +60,26 @@ namespace { ...@@ -62,26 +60,26 @@ namespace {
obj->*attr = Some(strntol(token.rawText(), token.size())); obj->*attr = Some(strntol(token.rawText(), token.size()));
} }
}; };
template<> template <> struct AttributeMatcher<bool> {
struct AttributeMatcher<bool> { static void match(StreamCursor &cursor, Cookie *obj, bool Cookie::*attr) {
static void match(StreamCursor& cursor, Cookie* obj, bool Cookie::*attr) {
UNUSED(cursor) UNUSED(cursor)
obj->*attr = true; obj->*attr = true;
} }
}; };
template<> template <> struct AttributeMatcher<Optional<FullDate>> {
struct AttributeMatcher<Optional<FullDate>> { static void match(StreamCursor &cursor, Cookie *obj,
static void match(StreamCursor& cursor, Cookie* obj, Optional<FullDate> Cookie::*attr) { Optional<FullDate> Cookie::*attr) {
auto token = matchValue(cursor); auto token = matchValue(cursor);
obj->*attr = Some(FullDate::fromString(token.text())); obj->*attr = Some(FullDate::fromString(token.text()));
} }
}; };
template<typename T> template <typename T>
bool match_attribute(const char* name, size_t len, StreamCursor& cursor, Cookie* obj, T Cookie::*attr) { bool match_attribute(const char *name, size_t len, StreamCursor &cursor,
Cookie *obj, T Cookie::*attr) {
if (match_string(name, len, cursor)) { if (match_string(name, len, cursor)) {
AttributeMatcher<T>::match(cursor, obj, attr); AttributeMatcher<T>::match(cursor, obj, attr);
cursor.advance(1); cursor.advance(1);
...@@ -90,25 +88,15 @@ namespace { ...@@ -90,25 +88,15 @@ namespace {
} }
return false; return false;
}
} }
} // namespace
Cookie::Cookie(std::string name, std::string value) Cookie::Cookie(std::string name, std::string value)
: name(std::move(name)) : name(std::move(name)), value(std::move(value)), path(), domain(),
, value(std::move(value)) expires(), maxAge(), secure(false), httpOnly(false), ext() {}
, path()
, domain() Cookie Cookie::fromRaw(const char *str, size_t len) {
, expires()
, maxAge()
, secure(false)
, httpOnly(false)
, ext()
{ }
Cookie
Cookie::fromRaw(const char* str, size_t len)
{
RawStreamBuf<> buf(const_cast<char *>(str), len); RawStreamBuf<> buf(const_cast<char *>(str), len);
StreamCursor cursor(&buf); StreamCursor cursor(&buf);
...@@ -139,12 +127,19 @@ Cookie::fromRaw(const char* str, size_t len) ...@@ -139,12 +127,19 @@ Cookie::fromRaw(const char* str, size_t len)
do { do {
skip_whitespaces(cursor); skip_whitespaces(cursor);
if (match_attribute(STR("Path"), cursor, &cookie, &Cookie::path)) ; if (match_attribute(STR("Path"), cursor, &cookie, &Cookie::path))
else if (match_attribute(STR("Domain"), cursor, &cookie, &Cookie::domain)) ; ;
else if (match_attribute(STR("Secure"), cursor, &cookie, &Cookie::secure)) ; else if (match_attribute(STR("Domain"), cursor, &cookie, &Cookie::domain))
else if (match_attribute(STR("HttpOnly"), cursor, &cookie, &Cookie::httpOnly)) ; ;
else if (match_attribute(STR("Max-Age"), cursor, &cookie, &Cookie::maxAge)) ; else if (match_attribute(STR("Secure"), cursor, &cookie, &Cookie::secure))
else if (match_attribute(STR("Expires"), cursor, &cookie, &Cookie::expires)) ; ;
else if (match_attribute(STR("HttpOnly"), cursor, &cookie,
&Cookie::httpOnly))
;
else if (match_attribute(STR("Max-Age"), cursor, &cookie, &Cookie::maxAge))
;
else if (match_attribute(STR("Expires"), cursor, &cookie, &Cookie::expires))
;
// ext // ext
else { else {
StreamCursor::Token nameToken_(cursor); StreamCursor::Token nameToken_(cursor);
...@@ -166,19 +161,17 @@ Cookie::fromRaw(const char* str, size_t len) ...@@ -166,19 +161,17 @@ Cookie::fromRaw(const char* str, size_t len)
return cookie; return cookie;
} }
Cookie Cookie Cookie::fromString(const std::string &str) {
Cookie::fromString(const std::string& str) {
return Cookie::fromRaw(str.c_str(), str.size()); return Cookie::fromRaw(str.c_str(), str.size());
} }
void void Cookie::write(std::ostream &os) const {
Cookie::write(std::ostream& os) const {
os << name << "=" << value; os << name << "=" << value;
optionally_do(path, [&](const std::string& value) { optionally_do(path, [&](const std::string &value) {
os << "; "; os << "; ";
os << "Path=" << value; os << "Path=" << value;
}); });
optionally_do(domain, [&](const std::string& value) { optionally_do(domain, [&](const std::string &value) {
os << "; "; os << "; ";
os << "Domain=" << value; os << "Domain=" << value;
}); });
...@@ -186,7 +179,7 @@ Cookie::write(std::ostream& os) const { ...@@ -186,7 +179,7 @@ Cookie::write(std::ostream& os) const {
os << "; "; os << "; ";
os << "Max-Age=" << value; os << "Max-Age=" << value;
}); });
optionally_do(expires, [&](const FullDate& value) { optionally_do(expires, [&](const FullDate &value) {
os << "; "; os << "; ";
os << "Expires="; os << "Expires=";
value.write(os); value.write(os);
...@@ -203,43 +196,33 @@ Cookie::write(std::ostream& os) const { ...@@ -203,43 +196,33 @@ Cookie::write(std::ostream& os) const {
os << "; "; os << "; ";
} }
} }
} }
std::ostream& operator<<(std::ostream& os, const Cookie& cookie) std::ostream &operator<<(std::ostream &os, const Cookie &cookie) {
{
cookie.write(os); cookie.write(os);
return os; return os;
} }
CookieJar::CookieJar() CookieJar::CookieJar() : cookies() {}
: cookies()
{ }
void void CookieJar::add(const Cookie &cookie) {
CookieJar::add(const Cookie& cookie) {
std::string cookieName = cookie.name; std::string cookieName = cookie.name;
std::string cookieValue = cookie.value; std::string cookieValue = cookie.value;
Storage::iterator it = cookies.find(cookieName); Storage::iterator it = cookies.find(cookieName);
if(it == cookies.end()) { if (it == cookies.end()) {
HashMapCookies hashmapWithFirstCookie; HashMapCookies hashmapWithFirstCookie;
hashmapWithFirstCookie.insert(std::make_pair(cookieValue,cookie)); hashmapWithFirstCookie.insert(std::make_pair(cookieValue, cookie));
cookies.insert(std::make_pair(cookieName, hashmapWithFirstCookie)); cookies.insert(std::make_pair(cookieName, hashmapWithFirstCookie));
} else { } else {
it->second.insert(std::make_pair(cookieValue,cookie)); it->second.insert(std::make_pair(cookieValue, cookie));
} }
} }
void void CookieJar::removeAllCookies() { cookies.clear(); }
CookieJar::removeAllCookies() {
cookies.clear();
}
void void CookieJar::addFromRaw(const char *str, size_t len) {
CookieJar::addFromRaw(const char *str, size_t len) {
RawStreamBuf<> buf(const_cast<char *>(str), len); RawStreamBuf<> buf(const_cast<char *>(str), len);
StreamCursor cursor(&buf); StreamCursor cursor(&buf);
...@@ -267,17 +250,16 @@ CookieJar::addFromRaw(const char *str, size_t len) { ...@@ -267,17 +250,16 @@ CookieJar::addFromRaw(const char *str, size_t len) {
} }
} }
Cookie Cookie CookieJar::get(const std::string &name) const {
CookieJar::get(const std::string& name) const {
Storage::const_iterator it = cookies.find(name); Storage::const_iterator it = cookies.find(name);
if(it != cookies.end()) { if (it != cookies.end()) {
return it->second.begin()->second; // it returns begin(), first element, could be changed. return it->second.begin()
->second; // it returns begin(), first element, could be changed.
} }
throw std::runtime_error("Could not find requested cookie"); throw std::runtime_error("Could not find requested cookie");
} }
bool bool CookieJar::has(const std::string &name) const {
CookieJar::has(const std::string& name) const {
return cookies.find(name) != cookies.end(); return cookies.find(name) != cookies.end();
} }
......
This diff is collapsed.
...@@ -4,59 +4,49 @@ ...@@ -4,59 +4,49 @@
Implementation of http definitions Implementation of http definitions
*/ */
#include <iostream>
#include <iomanip> #include <iomanip>
#include <iostream>
#include <pistache/http_defs.h>
#include <pistache/common.h> #include <pistache/common.h>
#include <pistache/date.h> #include <pistache/date.h>
#include <pistache/http_defs.h>
namespace Pistache { namespace Pistache {
namespace Http { namespace Http {
namespace { namespace {
using time_point = FullDate::time_point; using time_point = FullDate::time_point;
bool parse_RFC_1123(const std::string& s, time_point &tp) bool parse_RFC_1123(const std::string &s, time_point &tp) {
{
std::istringstream in{s}; std::istringstream in{s};
in >> date::parse("%a, %d %b %Y %T %Z", tp); in >> date::parse("%a, %d %b %Y %T %Z", tp);
return !in.fail(); return !in.fail();
} }
bool parse_RFC_850(const std::string& s, time_point &tp) bool parse_RFC_850(const std::string &s, time_point &tp) {
{
std::istringstream in{s}; std::istringstream in{s};
in >> date::parse("%a, %d-%b-%y %T %Z", tp); in >> date::parse("%a, %d-%b-%y %T %Z", tp);
return !in.fail(); return !in.fail();
} }
bool parse_asctime(const std::string& s, time_point &tp) bool parse_asctime(const std::string &s, time_point &tp) {
{
std::istringstream in{s}; std::istringstream in{s};
in >> date::parse("%a %b %d %T %Y", tp); in >> date::parse("%a %b %d %T %Y", tp);
return !in.fail(); return !in.fail();
} }
} // anonymous namespace } // anonymous namespace
CacheDirective::CacheDirective(Directive directive) CacheDirective::CacheDirective(Directive directive) : directive_(), data() {
: directive_()
, data()
{
init(directive, std::chrono::seconds(0)); init(directive, std::chrono::seconds(0));
} }
CacheDirective::CacheDirective(Directive directive, std::chrono::seconds delta) CacheDirective::CacheDirective(Directive directive, std::chrono::seconds delta)
: directive_() : directive_(), data() {
, data()
{
init(directive, delta); init(directive, delta);
} }
std::chrono::seconds std::chrono::seconds CacheDirective::delta() const {
CacheDirective::delta() const
{
switch (directive_) { switch (directive_) {
case MaxAge: case MaxAge:
return std::chrono::seconds(data.maxAge); return std::chrono::seconds(data.maxAge);
...@@ -71,9 +61,7 @@ CacheDirective::delta() const ...@@ -71,9 +61,7 @@ CacheDirective::delta() const
} }
} }
void void CacheDirective::init(Directive directive, std::chrono::seconds delta) {
CacheDirective::init(Directive directive, std::chrono::seconds delta)
{
directive_ = directive; directive_ = directive;
switch (directive) { switch (directive) {
case MaxAge: case MaxAge:
...@@ -93,23 +81,20 @@ CacheDirective::init(Directive directive, std::chrono::seconds delta) ...@@ -93,23 +81,20 @@ CacheDirective::init(Directive directive, std::chrono::seconds delta)
} }
} }
FullDate FullDate FullDate::fromString(const std::string &str) {
FullDate::fromString(const std::string& str) {
FullDate::time_point tp; FullDate::time_point tp;
if(parse_RFC_1123(str, tp)) if (parse_RFC_1123(str, tp))
return FullDate(tp); return FullDate(tp);
else if(parse_RFC_850(str, tp)) else if (parse_RFC_850(str, tp))
return FullDate(tp); return FullDate(tp);
else if(parse_asctime(str, tp)) else if (parse_asctime(str, tp))
return FullDate(tp); return FullDate(tp);
throw std::runtime_error("Invalid Date format"); throw std::runtime_error("Invalid Date format");
} }
void void FullDate::write(std::ostream &os, Type type) const {
FullDate::write(std::ostream& os, Type type) const
{
switch (type) { switch (type) {
case Type::RFC1123: case Type::RFC1123:
date::to_stream(os, "%a, %d %b %Y %T %Z", date_); date::to_stream(os, "%a, %d %b %Y %T %Z", date_);
...@@ -136,8 +121,7 @@ const char *versionString(Version version) { ...@@ -136,8 +121,7 @@ const char *versionString(Version version) {
unreachable(); unreachable();
} }
const char* methodString(Method method) const char *methodString(Method method) {
{
switch (method) { switch (method) {
#define METHOD(name, str) \ #define METHOD(name, str) \
case Method::name: \ case Method::name: \
...@@ -149,8 +133,7 @@ const char* methodString(Method method) ...@@ -149,8 +133,7 @@ const char* methodString(Method method)
unreachable(); unreachable();
} }
const char* codeString(Code code) const char *codeString(Code code) {
{
switch (code) { switch (code) {
#define CODE(_, name, str) \ #define CODE(_, name, str) \
case Code::name: \ case Code::name: \
...@@ -162,31 +145,26 @@ const char* codeString(Code code) ...@@ -162,31 +145,26 @@ const char* codeString(Code code)
return ""; return "";
} }
std::ostream& operator<<(std::ostream& os, Version version) { std::ostream &operator<<(std::ostream &os, Version version) {
os << versionString(version); os << versionString(version);
return os; return os;
} }
std::ostream& operator<<(std::ostream& os, Method method) { std::ostream &operator<<(std::ostream &os, Method method) {
os << methodString(method); os << methodString(method);
return os; return os;
} }
std::ostream& operator<<(std::ostream& os, Code code) { std::ostream &operator<<(std::ostream &os, Code code) {
os << codeString(code); os << codeString(code);
return os; return os;
} }
HttpError::HttpError(Code code, std::string reason) HttpError::HttpError(Code code, std::string reason)
: code_(static_cast<int>(code)) : code_(static_cast<int>(code)), reason_(std::move(reason)) {}
, reason_(std::move(reason))
{ }
HttpError::HttpError(int code, std::string reason) HttpError::HttpError(int code, std::string reason)
: code_(code) : code_(code), reason_(std::move(reason)) {}
, reason_(std::move(reason))
{ }
} // namespace Http } // namespace Http
} // namespace Pistache } // namespace Pistache
This diff is collapsed.
...@@ -35,35 +35,30 @@ RegisterHeader(Location); ...@@ -35,35 +35,30 @@ RegisterHeader(Location);
RegisterHeader(Server); RegisterHeader(Server);
RegisterHeader(UserAgent); RegisterHeader(UserAgent);
std::string std::string toLowercase(std::string str) {
toLowercase(std::string str) {
std::transform(str.begin(), str.end(), str.begin(), ::tolower); std::transform(str.begin(), str.end(), str.begin(), ::tolower);
return str; return str;
} }
bool bool LowercaseEqualStatic(const std::string &dynamic,
LowercaseEqualStatic(const std::string& dynamic, const std::string& statik) { const std::string &statik) {
return std::equal(dynamic.begin(), dynamic.end(), statik.begin(), statik.end(), return std::equal(
[] (const char& a, const char& b) { dynamic.begin(), dynamic.end(), statik.begin(), statik.end(),
return std::tolower(a) == b; [](const char &a, const char &b) { return std::tolower(a) == b; });
});
} }
Registry& Registry::instance() { Registry &Registry::instance() {
static Registry instance; static Registry instance;
return instance; return instance;
} }
Registry::Registry() Registry::Registry() {}
{}
Registry::~Registry() Registry::~Registry() {}
{}
void void Registry::registerHeader(const std::string &name,
Registry::registerHeader(const std::string& name, Registry::RegistryFunc func) Registry::RegistryFunc func) {
{
auto it = registry.find(name); auto it = registry.find(name);
if (it != std::end(registry)) { if (it != std::end(registry)) {
throw std::runtime_error("Header already registered"); throw std::runtime_error("Header already registered");
...@@ -72,20 +67,18 @@ Registry::registerHeader(const std::string& name, Registry::RegistryFunc func) ...@@ -72,20 +67,18 @@ Registry::registerHeader(const std::string& name, Registry::RegistryFunc func)
registry.insert(std::make_pair(name, std::move(func))); registry.insert(std::make_pair(name, std::move(func)));
} }
std::vector<std::string> std::vector<std::string> Registry::headersList() {
Registry::headersList() {
std::vector<std::string> names; std::vector<std::string> names;
names.reserve(registry.size()); names.reserve(registry.size());
for (const auto &header: registry) { for (const auto &header : registry) {
names.push_back(header.first); names.push_back(header.first);
} }
return names; return names;
} }
std::unique_ptr<Header> std::unique_ptr<Header> Registry::makeHeader(const std::string &name) {
Registry::makeHeader(const std::string& name) {
auto it = registry.find(name); auto it = registry.find(name);
if (it == std::end(registry)) { if (it == std::end(registry)) {
throw std::runtime_error("Unknown header"); throw std::runtime_error("Unknown header");
...@@ -94,27 +87,23 @@ Registry::makeHeader(const std::string& name) { ...@@ -94,27 +87,23 @@ Registry::makeHeader(const std::string& name) {
return it->second(); return it->second();
} }
bool bool Registry::isRegistered(const std::string &name) {
Registry::isRegistered(const std::string& name) {
auto it = registry.find(name); auto it = registry.find(name);
return it != std::end(registry); return it != std::end(registry);
} }
Collection& Collection &Collection::add(const std::shared_ptr<Header> &header) {
Collection::add(const std::shared_ptr<Header>& header) {
headers.insert(std::make_pair(header->name(), header)); headers.insert(std::make_pair(header->name(), header));
return *this; return *this;
} }
Collection& Collection &Collection::addRaw(const Raw &raw) {
Collection::addRaw(const Raw& raw) {
rawHeaders.insert(std::make_pair(raw.name(), raw)); rawHeaders.insert(std::make_pair(raw.name(), raw));
return *this; return *this;
} }
std::shared_ptr<const Header> std::shared_ptr<const Header> Collection::get(const std::string &name) const {
Collection::get(const std::string& name) const {
auto header = getImpl(name); auto header = getImpl(name);
if (!header.first) { if (!header.first) {
throw std::runtime_error("Could not find header"); throw std::runtime_error("Could not find header");
...@@ -123,8 +112,7 @@ Collection::get(const std::string& name) const { ...@@ -123,8 +112,7 @@ Collection::get(const std::string& name) const {
return header.second; return header.second;
} }
std::shared_ptr<Header> std::shared_ptr<Header> Collection::get(const std::string &name) {
Collection::get(const std::string& name) {
auto header = getImpl(name); auto header = getImpl(name);
if (!header.first) { if (!header.first) {
throw std::runtime_error("Could not find header"); throw std::runtime_error("Could not find header");
...@@ -133,8 +121,7 @@ Collection::get(const std::string& name) { ...@@ -133,8 +121,7 @@ Collection::get(const std::string& name) {
return header.second; return header.second;
} }
Raw Raw Collection::getRaw(const std::string &name) const {
Collection::getRaw(const std::string& name) const {
auto it = rawHeaders.find(name); auto it = rawHeaders.find(name);
if (it == std::end(rawHeaders)) { if (it == std::end(rawHeaders)) {
throw std::runtime_error("Could not find header"); throw std::runtime_error("Could not find header");
...@@ -144,23 +131,23 @@ Collection::getRaw(const std::string& name) const { ...@@ -144,23 +131,23 @@ Collection::getRaw(const std::string& name) const {
} }
std::shared_ptr<const Header> std::shared_ptr<const Header>
Collection::tryGet(const std::string& name) const { Collection::tryGet(const std::string &name) const {
auto header = getImpl(name); auto header = getImpl(name);
if (!header.first) return nullptr; if (!header.first)
return nullptr;
return header.second; return header.second;
} }
std::shared_ptr<Header> std::shared_ptr<Header> Collection::tryGet(const std::string &name) {
Collection::tryGet(const std::string& name) {
auto header = getImpl(name); auto header = getImpl(name);
if (!header.first) return nullptr; if (!header.first)
return nullptr;
return header.second; return header.second;
} }
Optional<Raw> Optional<Raw> Collection::tryGetRaw(const std::string &name) const {
Collection::tryGetRaw(const std::string& name) const {
auto it = rawHeaders.find(name); auto it = rawHeaders.find(name);
if (it == std::end(rawHeaders)) { if (it == std::end(rawHeaders)) {
return Optional<Raw>(None()); return Optional<Raw>(None());
...@@ -169,28 +156,26 @@ Collection::tryGetRaw(const std::string& name) const { ...@@ -169,28 +156,26 @@ Collection::tryGetRaw(const std::string& name) const {
return Optional<Raw>(Some(it->second)); return Optional<Raw>(Some(it->second));
} }
bool bool Collection::has(const std::string &name) const {
Collection::has(const std::string& name) const {
return getImpl(name).first; return getImpl(name).first;
} }
std::vector<std::shared_ptr<Header>> std::vector<std::shared_ptr<Header>> Collection::list() const {
Collection::list() const {
std::vector<std::shared_ptr<Header>> ret; std::vector<std::shared_ptr<Header>> ret;
ret.reserve(headers.size()); ret.reserve(headers.size());
for (const auto& h: headers) { for (const auto &h : headers) {
ret.push_back(h.second); ret.push_back(h.second);
} }
return ret; return ret;
} }
bool bool Collection::remove(const std::string &name) {
Collection::remove(const std::string& name) {
auto tit = headers.find(name); auto tit = headers.find(name);
if (tit == std::end(headers)) { if (tit == std::end(headers)) {
auto rit = rawHeaders.find(name); auto rit = rawHeaders.find(name);
if (rit == std::end(rawHeaders)) return false; if (rit == std::end(rawHeaders))
return false;
rawHeaders.erase(rit); rawHeaders.erase(rit);
return true; return true;
...@@ -199,14 +184,13 @@ Collection::remove(const std::string& name) { ...@@ -199,14 +184,13 @@ Collection::remove(const std::string& name) {
return true; return true;
} }
void void Collection::clear() {
Collection::clear() {
headers.clear(); headers.clear();
rawHeaders.clear(); rawHeaders.clear();
} }
std::pair<bool, std::shared_ptr<Header>> std::pair<bool, std::shared_ptr<Header>>
Collection::getImpl(const std::string& name) const { Collection::getImpl(const std::string &name) const {
auto it = headers.find(name); auto it = headers.find(name);
if (it == std::end(headers)) { if (it == std::end(headers)) {
return std::make_pair(false, nullptr); return std::make_pair(false, nullptr);
......
...@@ -6,16 +6,14 @@ ...@@ -6,16 +6,14 @@
#include <cstring> #include <cstring>
#include <pistache/mime.h>
#include <pistache/http.h> #include <pistache/http.h>
#include <pistache/mime.h>
namespace Pistache { namespace Pistache {
namespace Http { namespace Http {
namespace Mime { namespace Mime {
std::string std::string Q::toString() const {
Q::toString() const {
if (val_ == 0) if (val_ == 0)
return "q=0"; return "q=0";
else if (val_ == 100) else if (val_ == 100)
...@@ -31,27 +29,22 @@ Q::toString() const { ...@@ -31,27 +29,22 @@ Q::toString() const {
return std::string(buff); return std::string(buff);
} }
MediaType MediaType MediaType::fromString(const std::string &str) {
MediaType::fromString(const std::string& str) {
return fromRaw(str.c_str(), str.size()); return fromRaw(str.c_str(), str.size());
} }
MediaType MediaType MediaType::fromString(std::string &&str) {
MediaType::fromString(std::string&& str) {
return fromRaw(str.c_str(), str.size()); return fromRaw(str.c_str(), str.size());
} }
MediaType MediaType MediaType::fromRaw(const char *str, size_t len) {
MediaType::fromRaw(const char* str, size_t len) {
MediaType res; MediaType res;
res.parseRaw(str, len); res.parseRaw(str, len);
return res; return res;
} }
MediaType MediaType MediaType::fromFile(const char *fileName) {
MediaType::fromFile(const char* fileName)
{
const char *extensionOffset = nullptr; const char *extensionOffset = nullptr;
const char *p = fileName; const char *p = fileName;
while (*p) { while (*p) {
...@@ -66,27 +59,28 @@ MediaType::fromFile(const char* fileName) ...@@ -66,27 +59,28 @@ MediaType::fromFile(const char* fileName)
++extensionOffset; ++extensionOffset;
struct Extension { struct Extension {
const char* const raw; const char *const raw;
Mime::Type top; Mime::Type top;
Mime::Subtype sub; Mime::Subtype sub;
}; };
// @Data: maybe one day try to export http://www.iana.org/assignments/media-types/media-types.xhtml // @Data: maybe one day try to export
// as an item-list // http://www.iana.org/assignments/media-types/media-types.xhtml as an
// item-list
static constexpr Extension KnownExtensions[] = { static constexpr Extension KnownExtensions[] = {
{ "jpg", Type::Image, Subtype::Jpeg }, {"jpg", Type::Image, Subtype::Jpeg},
{ "jpeg", Type::Image, Subtype::Jpeg }, {"jpeg", Type::Image, Subtype::Jpeg},
{ "png", Type::Image, Subtype::Png }, {"png", Type::Image, Subtype::Png},
{ "bmp", Type::Image, Subtype::Bmp }, {"bmp", Type::Image, Subtype::Bmp},
{ "txt", Type::Text, Subtype::Plain }, {"txt", Type::Text, Subtype::Plain},
{ "md", Type::Text, Subtype::Plain }, {"md", Type::Text, Subtype::Plain},
{ "bin", Type::Application, Subtype::OctetStream}, {"bin", Type::Application, Subtype::OctetStream},
}; };
for (const auto& ext: KnownExtensions) { for (const auto &ext : KnownExtensions) {
if (!strcmp(extensionOffset, ext.raw)) { if (!strcmp(extensionOffset, ext.raw)) {
return MediaType(ext.top, ext.sub); return MediaType(ext.top, ext.sub);
} }
...@@ -95,9 +89,8 @@ MediaType::fromFile(const char* fileName) ...@@ -95,9 +89,8 @@ MediaType::fromFile(const char* fileName)
return MediaType(); return MediaType();
} }
void void MediaType::parseRaw(const char *str, size_t len) {
MediaType::parseRaw(const char* str, size_t len) { auto raise = [&](const char *str) {
auto raise = [&](const char* str) {
// TODO: eventually, we should throw a more generic exception // TODO: eventually, we should throw a more generic exception
// that could then be catched in lower stack frames to rethrow // that could then be catched in lower stack frames to rethrow
// an HttpError // an HttpError
...@@ -111,9 +104,10 @@ MediaType::parseRaw(const char* str, size_t len) { ...@@ -111,9 +104,10 @@ MediaType::parseRaw(const char* str, size_t len) {
Mime::Type top = Type::None; Mime::Type top = Type::None;
// The reason we are using a do { } while (0); syntax construct here is to emulate // The reason we are using a do { } while (0); syntax construct here is to
// if / else-if. Since we are using items-list macros to compare the strings, // emulate if / else-if. Since we are using items-list macros to compare the
// we want to avoid evaluating all the branches when one of them evaluates to true. // strings, we want to avoid evaluating all the branches when one of them
// evaluates to true.
// //
// Instead, we break the loop when a branch evaluates to true so that we do // Instead, we break the loop when a branch evaluates to true so that we do
// not evaluate all the subsequent ones. // not evaluate all the subsequent ones.
...@@ -159,20 +153,22 @@ MediaType::parseRaw(const char* str, size_t len) { ...@@ -159,20 +153,22 @@ MediaType::parseRaw(const char* str, size_t len) {
} }
if (sub == Subtype::Ext || sub == Subtype::Vendor) { if (sub == Subtype::Ext || sub == Subtype::Vendor) {
(void) match_until({ ';', '+' }, cursor); (void)match_until({';', '+'}, cursor);
rawSubIndex.beg = subToken.start(); rawSubIndex.beg = subToken.start();
rawSubIndex.end = subToken.end() - 1; rawSubIndex.end = subToken.end() - 1;
} }
sub_ = sub; sub_ = sub;
if (cursor.eof()) return; if (cursor.eof())
return;
// Parse suffix // Parse suffix
Mime::Suffix suffix = Suffix::None; Mime::Suffix suffix = Suffix::None;
if (match_literal('+', cursor)) { if (match_literal('+', cursor)) {
if (cursor.eof()) raise("Malformed Media Type, expected suffix, got EOF"); if (cursor.eof())
raise("Malformed Media Type, expected suffix, got EOF");
StreamCursor::Token suffixToken(cursor); StreamCursor::Token suffixToken(cursor);
...@@ -188,7 +184,7 @@ MediaType::parseRaw(const char* str, size_t len) { ...@@ -188,7 +184,7 @@ MediaType::parseRaw(const char* str, size_t len) {
} while (0); } while (0);
if (suffix == Suffix::Ext) { if (suffix == Suffix::Ext) {
(void) match_until({ ';', '+' }, cursor); (void)match_until({';', '+'}, cursor);
rawSuffixIndex.beg = suffixToken.start(); rawSuffixIndex.beg = suffixToken.start();
rawSuffixIndex.end = suffixToken.end() - 1; rawSuffixIndex.end = suffixToken.end() - 1;
} }
...@@ -208,21 +204,20 @@ MediaType::parseRaw(const char* str, size_t len) { ...@@ -208,21 +204,20 @@ MediaType::parseRaw(const char* str, size_t len) {
else if (match_literal('q', cursor)) { else if (match_literal('q', cursor)) {
if (cursor.eof()) raise("Invalid quality factor"); if (cursor.eof())
raise("Invalid quality factor");
if (match_literal('=', cursor)) { if (match_literal('=', cursor)) {
double val; double val;
if (!match_double(&val, cursor)) if (!match_double(&val, cursor))
raise("Invalid quality factor"); raise("Invalid quality factor");
q_ = Some(Q::fromFloat(val)); q_ = Some(Q::fromFloat(val));
} } else {
else {
raise("Missing quality factor"); raise("Missing quality factor");
} }
} } else {
else {
StreamCursor::Token keyToken(cursor); StreamCursor::Token keyToken(cursor);
(void) match_until('=', cursor); (void)match_until('=', cursor);
int c; int c;
if (cursor.eof() || (c = cursor.next()) == StreamCursor::Eof || c == 0) if (cursor.eof() || (c = cursor.next()) == StreamCursor::Eof || c == 0)
...@@ -232,21 +227,15 @@ MediaType::parseRaw(const char* str, size_t len) { ...@@ -232,21 +227,15 @@ MediaType::parseRaw(const char* str, size_t len) {
cursor.advance(1); cursor.advance(1);
StreamCursor::Token valueToken(cursor); StreamCursor::Token valueToken(cursor);
(void) match_until({ ' ', ';' }, cursor); (void)match_until({' ', ';'}, cursor);
params.insert(std::make_pair(std::move(key), valueToken.text())); params.insert(std::make_pair(std::move(key), valueToken.text()));
} }
} }
} }
void void MediaType::setQuality(Q quality) { q_ = Some(quality); }
MediaType::setQuality(Q quality) {
q_ = Some(quality);
}
Optional<std::string> Optional<std::string> MediaType::getParam(const std::string &name) const {
MediaType::getParam(const std::string& name) const {
auto it = params.find(name); auto it = params.find(name);
if (it == std::end(params)) { if (it == std::end(params)) {
return Optional<std::string>(None()); return Optional<std::string>(None());
...@@ -255,15 +244,14 @@ MediaType::getParam(const std::string& name) const { ...@@ -255,15 +244,14 @@ MediaType::getParam(const std::string& name) const {
return Optional<std::string>(Some(it->second)); return Optional<std::string>(Some(it->second));
} }
void void MediaType::setParam(const std::string &name, std::string value) {
MediaType::setParam(const std::string& name, std::string value) {
params[name] = std::move(value); params[name] = std::move(value);
} }
std::string std::string MediaType::toString() const {
MediaType::toString() const {
if (!raw_.empty()) return raw_; if (!raw_.empty())
return raw_;
auto topString = [](Mime::Type top) -> const char * { auto topString = [](Mime::Type top) -> const char * {
switch (top) { switch (top) {
...@@ -315,7 +303,7 @@ MediaType::toString() const { ...@@ -315,7 +303,7 @@ MediaType::toString() const {
res += quality.toString(); res += quality.toString();
}); });
for (const auto& param: params) { for (const auto &param : params) {
res += "; "; res += "; ";
res += param.first + "=" + param.second; res += param.first + "=" + param.second;
} }
...@@ -323,8 +311,7 @@ MediaType::toString() const { ...@@ -323,8 +311,7 @@ MediaType::toString() const {
return res; return res;
} }
bool bool MediaType::isValid() const {
MediaType::isValid() const {
return top_ != Type::None && sub_ != Subtype::None; return top_ != Type::None && sub_ != Subtype::None;
} }
......
This diff is collapsed.
...@@ -7,51 +7,40 @@ ...@@ -7,51 +7,40 @@
#include <pistache/config.h> #include <pistache/config.h>
#include <pistache/os.h> #include <pistache/os.h>
#include <unistd.h>
#include <fcntl.h> #include <fcntl.h>
#include <sys/epoll.h> #include <sys/epoll.h>
#include <sys/eventfd.h> #include <sys/eventfd.h>
#include <unistd.h>
#include <algorithm> #include <algorithm>
#include <fstream> #include <fstream>
#include <iterator> #include <iterator>
#include <thread> #include <thread>
namespace Pistache { namespace Pistache {
uint hardware_concurrency() { uint hardware_concurrency() { return std::thread::hardware_concurrency(); }
return std::thread::hardware_concurrency();
}
bool make_non_blocking(int fd) bool make_non_blocking(int fd) {
{ int flags = fcntl(fd, F_GETFL, 0);
int flags = fcntl (fd, F_GETFL, 0); if (flags == -1)
if (flags == -1) return false; return false;
flags |= O_NONBLOCK; flags |= O_NONBLOCK;
int ret = fcntl (fd, F_SETFL, flags); int ret = fcntl(fd, F_SETFL, flags);
if (ret == -1) return false; if (ret == -1)
return false;
return true; return true;
} }
CpuSet::CpuSet() { CpuSet::CpuSet() { bits.reset(); }
bits.reset();
}
CpuSet::CpuSet(std::initializer_list<size_t> cpus) { CpuSet::CpuSet(std::initializer_list<size_t> cpus) { set(cpus); }
set(cpus);
}
void void CpuSet::clear() { bits.reset(); }
CpuSet::clear() {
bits.reset();
}
CpuSet& CpuSet &CpuSet::set(size_t cpu) {
CpuSet::set(size_t cpu) {
if (cpu >= Size) { if (cpu >= Size) {
throw std::invalid_argument("Trying to set invalid cpu number"); throw std::invalid_argument("Trying to set invalid cpu number");
} }
...@@ -60,8 +49,7 @@ CpuSet::set(size_t cpu) { ...@@ -60,8 +49,7 @@ CpuSet::set(size_t cpu) {
return *this; return *this;
} }
CpuSet& CpuSet &CpuSet::unset(size_t cpu) {
CpuSet::unset(size_t cpu) {
if (cpu >= Size) { if (cpu >= Size) {
throw std::invalid_argument("Trying to unset invalid cpu number"); throw std::invalid_argument("Trying to unset invalid cpu number");
} }
...@@ -70,20 +58,19 @@ CpuSet::unset(size_t cpu) { ...@@ -70,20 +58,19 @@ CpuSet::unset(size_t cpu) {
return *this; return *this;
} }
CpuSet& CpuSet &CpuSet::set(std::initializer_list<size_t> cpus) {
CpuSet::set(std::initializer_list<size_t> cpus) { for (auto cpu : cpus)
for (auto cpu: cpus) set(cpu); set(cpu);
return *this; return *this;
} }
CpuSet& CpuSet &CpuSet::unset(std::initializer_list<size_t> cpus) {
CpuSet::unset(std::initializer_list<size_t> cpus) { for (auto cpu : cpus)
for (auto cpu: cpus) unset(cpu); unset(cpu);
return *this; return *this;
} }
CpuSet& CpuSet &CpuSet::setRange(size_t begin, size_t end) {
CpuSet::setRange(size_t begin, size_t end) {
if (begin > end) { if (begin > end) {
throw std::range_error("Invalid range, begin > end"); throw std::range_error("Invalid range, begin > end");
} }
...@@ -95,8 +82,7 @@ CpuSet::setRange(size_t begin, size_t end) { ...@@ -95,8 +82,7 @@ CpuSet::setRange(size_t begin, size_t end) {
return *this; return *this;
} }
CpuSet& CpuSet &CpuSet::unsetRange(size_t begin, size_t end) {
CpuSet::unsetRange(size_t begin, size_t end) {
if (begin > end) { if (begin > end) {
throw std::range_error("Invalid range, begin > end"); throw std::range_error("Invalid range, begin > end");
} }
...@@ -108,8 +94,7 @@ CpuSet::unsetRange(size_t begin, size_t end) { ...@@ -108,8 +94,7 @@ CpuSet::unsetRange(size_t begin, size_t end) {
return *this; return *this;
} }
bool bool CpuSet::isSet(size_t cpu) const {
CpuSet::isSet(size_t cpu) const {
if (cpu >= Size) { if (cpu >= Size) {
throw std::invalid_argument("Trying to test invalid cpu number"); throw std::invalid_argument("Trying to test invalid cpu number");
} }
...@@ -117,13 +102,9 @@ CpuSet::isSet(size_t cpu) const { ...@@ -117,13 +102,9 @@ CpuSet::isSet(size_t cpu) const {
return bits.test(cpu); return bits.test(cpu);
} }
size_t size_t CpuSet::count() const { return bits.count(); }
CpuSet::count() const {
return bits.count();
}
cpu_set_t cpu_set_t CpuSet::toPosix() const {
CpuSet::toPosix() const {
cpu_set_t cpu_set; cpu_set_t cpu_set;
CPU_ZERO(&cpu_set); CPU_ZERO(&cpu_set);
...@@ -137,26 +118,18 @@ CpuSet::toPosix() const { ...@@ -137,26 +118,18 @@ CpuSet::toPosix() const {
namespace Polling { namespace Polling {
Event::Event(Tag _tag) Event::Event(Tag _tag) : flags(), fd(-1), tag(_tag) {}
: flags()
, fd(-1)
, tag(_tag)
{ }
Epoll::Epoll(): Epoll::Epoll()
epoll_fd([&](){return TRY_RET(epoll_create(Const::MaxEvents));}()) : epoll_fd([&]() { return TRY_RET(epoll_create(Const::MaxEvents)); }()) {}
{ }
Epoll::~Epoll() Epoll::~Epoll() {
{ if (epoll_fd >= 0) {
if (epoll_fd >= 0)
{
close(epoll_fd); close(epoll_fd);
} }
} }
void void Epoll::addFd(Fd fd, Flags<NotifyOn> interest, Tag tag, Mode mode) {
Epoll::addFd(Fd fd, Flags<NotifyOn> interest, Tag tag, Mode mode) {
struct epoll_event ev; struct epoll_event ev;
ev.events = toEpollEvents(interest); ev.events = toEpollEvents(interest);
if (mode == Mode::Edge) if (mode == Mode::Edge)
...@@ -164,10 +137,9 @@ namespace Polling { ...@@ -164,10 +137,9 @@ namespace Polling {
ev.data.u64 = tag.value_; ev.data.u64 = tag.value_;
TRY(epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev)); TRY(epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev));
} }
void void Epoll::addFdOneShot(Fd fd, Flags<NotifyOn> interest, Tag tag, Mode mode) {
Epoll::addFdOneShot(Fd fd, Flags<NotifyOn> interest, Tag tag, Mode mode) {
struct epoll_event ev; struct epoll_event ev;
ev.events = toEpollEvents(interest); ev.events = toEpollEvents(interest);
ev.events |= EPOLLONESHOT; ev.events |= EPOLLONESHOT;
...@@ -176,16 +148,14 @@ namespace Polling { ...@@ -176,16 +148,14 @@ namespace Polling {
ev.data.u64 = tag.value_; ev.data.u64 = tag.value_;
TRY(epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev)); TRY(epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev));
} }
void void Epoll::removeFd(Fd fd) {
Epoll::removeFd(Fd fd) {
struct epoll_event ev; struct epoll_event ev;
TRY(epoll_ctl(epoll_fd, EPOLL_CTL_DEL, fd, &ev)); TRY(epoll_ctl(epoll_fd, EPOLL_CTL_DEL, fd, &ev));
} }
void void Epoll::rearmFd(Fd fd, Flags<NotifyOn> interest, Tag tag, Mode mode) {
Epoll::rearmFd(Fd fd, Flags<NotifyOn> interest, Tag tag, Mode mode) {
struct epoll_event ev; struct epoll_event ev;
ev.events = toEpollEvents(interest); ev.events = toEpollEvents(interest);
if (mode == Mode::Edge) if (mode == Mode::Edge)
...@@ -193,16 +163,16 @@ namespace Polling { ...@@ -193,16 +163,16 @@ namespace Polling {
ev.data.u64 = tag.value_; ev.data.u64 = tag.value_;
TRY(epoll_ctl(epoll_fd, EPOLL_CTL_MOD, fd, &ev)); TRY(epoll_ctl(epoll_fd, EPOLL_CTL_MOD, fd, &ev));
} }
int int Epoll::poll(std::vector<Event> &events,
Epoll::poll(std::vector<Event>& events, const std::chrono::milliseconds timeout) const { const std::chrono::milliseconds timeout) const {
struct epoll_event evs[Const::MaxEvents]; struct epoll_event evs[Const::MaxEvents];
int ready_fds = -1; int ready_fds = -1;
do { do {
ready_fds = ::epoll_wait(epoll_fd, evs, Const::MaxEvents, timeout.count()); ready_fds = ::epoll_wait(epoll_fd, evs, Const::MaxEvents, timeout.count());
} while(ready_fds < 0 && errno == EINTR); } while (ready_fds < 0 && errno == EINTR);
for (int i = 0; i < ready_fds; ++i) { for (int i = 0; i < ready_fds; ++i) {
const struct epoll_event *ev = evs + i; const struct epoll_event *ev = evs + i;
...@@ -215,10 +185,9 @@ namespace Polling { ...@@ -215,10 +185,9 @@ namespace Polling {
} }
return ready_fds; return ready_fds;
} }
int int Epoll::toEpollEvents(const Flags<NotifyOn> &interest) {
Epoll::toEpollEvents(const Flags<NotifyOn>& interest) {
int events = 0; int events = 0;
if (interest.hasFlag(NotifyOn::Read)) if (interest.hasFlag(NotifyOn::Read))
...@@ -231,10 +200,9 @@ namespace Polling { ...@@ -231,10 +200,9 @@ namespace Polling {
events |= EPOLLRDHUP; events |= EPOLLRDHUP;
return events; return events;
} }
Flags<NotifyOn> Flags<NotifyOn> Epoll::toNotifyOn(int events) {
Epoll::toNotifyOn(int events) {
Flags<NotifyOn> flags; Flags<NotifyOn> flags;
if (events & EPOLLIN) if (events & EPOLLIN)
...@@ -248,51 +216,40 @@ namespace Polling { ...@@ -248,51 +216,40 @@ namespace Polling {
} }
return flags; return flags;
} }
} // namespace Poller } // namespace Polling
NotifyFd::NotifyFd() NotifyFd::NotifyFd() : event_fd(-1) {}
: event_fd(-1)
{ }
Polling::Tag Polling::Tag NotifyFd::bind(Polling::Epoll &poller) {
NotifyFd::bind(Polling::Epoll& poller) {
event_fd = TRY_RET(eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC)); event_fd = TRY_RET(eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC));
Polling::Tag tag(event_fd); Polling::Tag tag(event_fd);
poller.addFd(event_fd, Flags<Polling::NotifyOn>(Polling::NotifyOn::Read), tag, Polling::Mode::Edge); poller.addFd(event_fd, Flags<Polling::NotifyOn>(Polling::NotifyOn::Read), tag,
Polling::Mode::Edge);
return tag; return tag;
} }
bool bool NotifyFd::isBound() const { return event_fd != -1; }
NotifyFd::isBound() const {
return event_fd != -1;
}
Polling::Tag Polling::Tag NotifyFd::tag() const { return Polling::Tag(event_fd); }
NotifyFd::tag() const {
return Polling::Tag(event_fd);
}
void void NotifyFd::notify() const {
NotifyFd::notify() const {
if (!isBound()) if (!isBound())
throw std::runtime_error("Can not notify an unbound fd"); throw std::runtime_error("Can not notify an unbound fd");
eventfd_t val = 1; eventfd_t val = 1;
TRY(eventfd_write(event_fd, val)); TRY(eventfd_write(event_fd, val));
} }
void void NotifyFd::read() const {
NotifyFd::read() const {
if (!isBound()) if (!isBound())
throw std::runtime_error("Can not read an unbound fd"); throw std::runtime_error("Can not read an unbound fd");
eventfd_t val; eventfd_t val;
TRY(eventfd_read(event_fd, &val)); TRY(eventfd_read(event_fd, &val));
} }
bool bool NotifyFd::tryRead() const {
NotifyFd::tryRead() const {
eventfd_t val; eventfd_t val;
int res = eventfd_read(event_fd, &val); int res = eventfd_read(event_fd, &val);
if (res == -1) { if (res == -1) {
......
...@@ -6,46 +6,33 @@ ...@@ -6,46 +6,33 @@
#include <iostream> #include <iostream>
#include <stdexcept> #include <stdexcept>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h> #include <arpa/inet.h>
#include <netdb.h> #include <netdb.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <pistache/peer.h>
#include <pistache/async.h> #include <pistache/async.h>
#include <pistache/peer.h>
#include <pistache/transport.h> #include <pistache/transport.h>
namespace Pistache { namespace Pistache {
namespace Tcp { namespace Tcp {
Peer::Peer() Peer::Peer() : transport_(nullptr), fd_(-1), ssl_(NULL) {}
: transport_(nullptr)
, fd_(-1) Peer::Peer(const Address &addr)
, ssl_(NULL) : transport_(nullptr), addr(addr), fd_(-1), ssl_(NULL) {}
{ }
Peer::~Peer() {
Peer::Peer(const Address& addr)
: transport_(nullptr)
, addr(addr)
, fd_(-1)
, ssl_(NULL)
{ }
Peer::~Peer()
{
#ifdef PISTACHE_USE_SSL #ifdef PISTACHE_USE_SSL
if (ssl_) if (ssl_)
SSL_free((SSL *)ssl_); SSL_free((SSL *)ssl_);
#endif /* PISTACHE_USE_SSL */ #endif /* PISTACHE_USE_SSL */
} }
const Address& Peer::address() const const Address &Peer::address() const { return addr; }
{
return addr;
}
const std::string& Peer::hostname() const std::string &Peer::hostname() {
{
if (hostname_.empty()) { if (hostname_.empty()) {
char host[NI_MAXHOST]; char host[NI_MAXHOST];
struct sockaddr_in sa; struct sockaddr_in sa;
...@@ -53,12 +40,11 @@ const std::string& Peer::hostname() ...@@ -53,12 +40,11 @@ const std::string& Peer::hostname()
if (inet_pton(AF_INET, addr.host().c_str(), &sa.sin_addr) == 0) { if (inet_pton(AF_INET, addr.host().c_str(), &sa.sin_addr) == 0) {
hostname_ = addr.host(); hostname_ = addr.host();
} else { } else {
if (!getnameinfo((struct sockaddr*)&sa, sizeof(sa) if (!getnameinfo((struct sockaddr *)&sa, sizeof(sa), host, sizeof(host),
, host, sizeof(host) NULL, 0 // Service info
, NULL, 0 // Service info ,
, NI_NAMEREQD // Raise an error if name resolution failed NI_NAMEREQD // Raise an error if name resolution failed
) )) {
) {
hostname_.assign((char *)host); hostname_.assign((char *)host);
} }
} }
...@@ -66,26 +52,15 @@ const std::string& Peer::hostname() ...@@ -66,26 +52,15 @@ const std::string& Peer::hostname()
return hostname_; return hostname_;
} }
void void Peer::associateFd(int fd) { fd_ = fd; }
Peer::associateFd(int fd) {
fd_ = fd;
}
#ifdef PISTACHE_USE_SSL #ifdef PISTACHE_USE_SSL
void void Peer::associateSSL(void *ssl) { ssl_ = ssl; }
Peer::associateSSL(void *ssl)
{
ssl_ = ssl;
}
void * void *Peer::ssl(void) const { return ssl_; }
Peer::ssl(void) const {
return ssl_;
}
#endif /* PISTACHE_USE_SSL */ #endif /* PISTACHE_USE_SSL */
int int Peer::fd() const {
Peer::fd() const {
if (fd_ == -1) { if (fd_ == -1) {
throw std::runtime_error("The peer has no associated fd"); throw std::runtime_error("The peer has no associated fd");
} }
...@@ -93,8 +68,8 @@ Peer::fd() const { ...@@ -93,8 +68,8 @@ Peer::fd() const {
return fd_; return fd_;
} }
void void Peer::putData(std::string name,
Peer::putData(std::string name, std::shared_ptr<Pistache::Http::Private::ParserBase> data) { std::shared_ptr<Pistache::Http::Private::ParserBase> data) {
auto it = data_.find(name); auto it = data_.find(name);
if (it != std::end(data_)) { if (it != std::end(data_)) {
throw std::runtime_error("The data already exists"); throw std::runtime_error("The data already exists");
...@@ -116,29 +91,26 @@ Peer::getData(std::string name) const { ...@@ -116,29 +91,26 @@ Peer::getData(std::string name) const {
std::shared_ptr<Pistache::Http::Private::ParserBase> std::shared_ptr<Pistache::Http::Private::ParserBase>
Peer::tryGetData(std::string(name)) const { Peer::tryGetData(std::string(name)) const {
auto it = data_.find(name); auto it = data_.find(name);
if (it == std::end(data_)) return nullptr; if (it == std::end(data_))
return nullptr;
return it->second; return it->second;
} }
Async::Promise<ssize_t> Async::Promise<ssize_t> Peer::send(const RawBuffer &buffer, int flags) {
Peer::send(const RawBuffer& buffer, int flags) {
return transport()->asyncWrite(fd_, buffer, flags); return transport()->asyncWrite(fd_, buffer, flags);
} }
std::ostream& operator<<(std::ostream& os, Peer& peer) { std::ostream &operator<<(std::ostream &os, Peer &peer) {
const auto& addr = peer.address(); const auto &addr = peer.address();
os << "(" << addr.host() << ", " << addr.port() << ") [" << peer.hostname() << "]"; os << "(" << addr.host() << ", " << addr.port() << ") [" << peer.hostname()
<< "]";
return os; return os;
} }
void void Peer::associateTransport(Transport *transport) { transport_ = transport; }
Peer::associateTransport(Transport* transport) {
transport_ = transport;
}
Transport* Transport *Peer::transport() const {
Peer::transport() const {
if (!transport_) if (!transport_)
throw std::logic_error("Orphaned peer"); throw std::logic_error("Orphaned peer");
......
This diff is collapsed.
This diff is collapsed.
...@@ -4,32 +4,25 @@ ...@@ -4,32 +4,25 @@
TCP TCP
*/ */
#include <pistache/tcp.h>
#include <pistache/peer.h> #include <pistache/peer.h>
#include <pistache/tcp.h>
namespace Pistache { namespace Pistache {
namespace Tcp { namespace Tcp {
Handler::Handler() Handler::Handler() : transport_(nullptr) {}
: transport_(nullptr)
{
}
Handler::~Handler() Handler::~Handler() {}
{ }
void void Handler::associateTransport(Transport *transport) {
Handler::associateTransport(Transport* transport) {
transport_ = transport; transport_ = transport;
} }
void void Handler::onConnection(const std::shared_ptr<Tcp::Peer> &peer) {
Handler::onConnection(const std::shared_ptr<Tcp::Peer>& peer) {
UNUSED(peer) UNUSED(peer)
} }
void void Handler::onDisconnection(const std::shared_ptr<Tcp::Peer> &peer) {
Handler::onDisconnection(const std::shared_ptr<Tcp::Peer>& peer) {
UNUSED(peer) UNUSED(peer)
} }
......
...@@ -13,35 +13,28 @@ ...@@ -13,35 +13,28 @@
namespace Pistache { namespace Pistache {
TimerPool::Entry::Entry() TimerPool::Entry::Entry() : fd_(-1), registered(false) {
: fd_(-1)
, registered(false)
{
state.store(static_cast<uint32_t>(State::Idle)); state.store(static_cast<uint32_t>(State::Idle));
} }
TimerPool::Entry::~Entry() TimerPool::Entry::~Entry() {
{
if (fd_ != -1) if (fd_ != -1)
close(fd_); close(fd_);
} }
Fd TimerPool::Entry::fd() const Fd TimerPool::Entry::fd() const {
{
assert(fd_ != -1); assert(fd_ != -1);
return fd_; return fd_;
} }
void void TimerPool::Entry::initialize() {
TimerPool::Entry::initialize() {
if (fd_ == -1) { if (fd_ == -1) {
fd_ = TRY_RET(timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK)); fd_ = TRY_RET(timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK));
} }
} }
void TimerPool::Entry::disarm() void TimerPool::Entry::disarm() {
{
assert(fd_ != -1); assert(fd_ != -1);
itimerspec spec; itimerspec spec;
...@@ -54,44 +47,39 @@ void TimerPool::Entry::disarm() ...@@ -54,44 +47,39 @@ void TimerPool::Entry::disarm()
TRY(timerfd_settime(fd_, 0, &spec, 0)); TRY(timerfd_settime(fd_, 0, &spec, 0));
} }
void TimerPool::Entry::registerReactor(const Aio::Reactor::Key& key, Aio::Reactor* reactor) void TimerPool::Entry::registerReactor(const Aio::Reactor::Key &key,
{ Aio::Reactor *reactor) {
if (!registered) if (!registered) {
{
reactor->registerFd(key, fd_, Polling::NotifyOn::Read); reactor->registerFd(key, fd_, Polling::NotifyOn::Read);
registered = true; registered = true;
} }
} }
void void TimerPool::Entry::armMs(std::chrono::milliseconds value) {
TimerPool::Entry::armMs(std::chrono::milliseconds value)
{
itimerspec spec; itimerspec spec;
spec.it_interval.tv_sec = 0; spec.it_interval.tv_sec = 0;
spec.it_interval.tv_nsec = 0; spec.it_interval.tv_nsec = 0;
if (value.count() < 1000) { if (value.count() < 1000) {
spec.it_value.tv_sec = 0; spec.it_value.tv_sec = 0;
spec.it_value.tv_nsec spec.it_value.tv_nsec =
= std::chrono::duration_cast<std::chrono::nanoseconds>(value).count(); std::chrono::duration_cast<std::chrono::nanoseconds>(value).count();
} else { } else {
spec.it_value.tv_sec spec.it_value.tv_sec =
= std::chrono::duration_cast<std::chrono::seconds>(value).count(); std::chrono::duration_cast<std::chrono::seconds>(value).count();
spec.it_value.tv_nsec = 0; spec.it_value.tv_nsec = 0;
} }
TRY(timerfd_settime(fd_, 0, &spec, 0)); TRY(timerfd_settime(fd_, 0, &spec, 0));
} }
TimerPool::TimerPool(size_t initialSize) TimerPool::TimerPool(size_t initialSize) {
{
for (size_t i = 0; i < initialSize; ++i) { for (size_t i = 0; i < initialSize; ++i) {
timers.push_back(std::make_shared<TimerPool::Entry>()); timers.push_back(std::make_shared<TimerPool::Entry>());
} }
} }
std::shared_ptr<TimerPool::Entry> std::shared_ptr<TimerPool::Entry> TimerPool::pickTimer() {
TimerPool::pickTimer() { for (auto &entry : timers) {
for (auto& entry: timers) {
auto curState = static_cast<uint32_t>(TimerPool::Entry::State::Idle); auto curState = static_cast<uint32_t>(TimerPool::Entry::State::Idle);
auto newState = static_cast<uint32_t>(TimerPool::Entry::State::Used); auto newState = static_cast<uint32_t>(TimerPool::Entry::State::Used);
if (entry->state.compare_exchange_strong(curState, newState)) { if (entry->state.compare_exchange_strong(curState, newState)) {
...@@ -103,8 +91,7 @@ TimerPool::pickTimer() { ...@@ -103,8 +91,7 @@ TimerPool::pickTimer() {
return nullptr; return nullptr;
} }
void void TimerPool::releaseTimer(const std::shared_ptr<Entry> &timer) {
TimerPool::releaseTimer(const std::shared_ptr<Entry>& timer) {
timer->state.store(static_cast<uint32_t>(TimerPool::Entry::State::Idle)); timer->state.store(static_cast<uint32_t>(TimerPool::Entry::State::Idle));
} }
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment