Crow/utility.h

52 lines
1.1 KiB
C
Raw Normal View History

2014-04-02 16:38:08 +00:00
#pragma once
namespace flask
{
namespace black_magic
{
struct OutOfRange
{
OutOfRange(unsigned pos, unsigned length) {}
};
constexpr unsigned requires_in_range( unsigned i, unsigned len )
{
return i >= len ? throw OutOfRange(i, len) : i;
}
// from http://akrzemi1.wordpress.com/2011/05/11/parsing-strings-at-compile-time-part-i/
2014-04-02 20:31:32 +00:00
class const_str
2014-04-02 16:38:08 +00:00
{
const char * const begin_;
unsigned size_;
public:
template< unsigned N >
2014-04-02 20:31:32 +00:00
constexpr const_str( const char(&arr)[N] ) : begin_(arr), size_(N - 1) {
2014-04-02 16:38:08 +00:00
static_assert( N >= 1, "not a string literal");
}
2014-04-02 20:31:32 +00:00
constexpr char operator[]( unsigned i ) const {
2014-04-02 16:38:08 +00:00
return requires_in_range(i, size_), begin_[i];
}
2014-04-02 20:31:32 +00:00
constexpr operator const char *() const {
2014-04-02 16:38:08 +00:00
return begin_;
}
2014-04-02 20:31:32 +00:00
constexpr unsigned size() const {
2014-04-02 16:38:08 +00:00
return size_;
}
};
2014-04-02 20:31:32 +00:00
constexpr unsigned find_closing_tag(const_str s, unsigned p)
2014-04-02 16:38:08 +00:00
{
return s[p] == '>' ? p : find_closing_tag(s, p+1);
}
2014-04-02 20:31:32 +00:00
constexpr int count(const_str s, int i=0)
2014-04-02 16:38:08 +00:00
{
return i == s.size() ? 0 : s[i] == '<' ? 1+count(s,i+1) : count(s,i+1);
}
}
}