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