Moved byte-range parsing to byte_range.cpp

This commit is contained in:
Veloman Yunkan 2020-05-25 17:21:10 +04:00
parent 693905eb68
commit 67a347c0c4
3 changed files with 32 additions and 28 deletions

View File

@ -20,6 +20,8 @@
#include "byte_range.h"
#include "tools/stringTools.h"
namespace kiwix {
ByteRange::ByteRange()
@ -34,4 +36,30 @@ ByteRange::ByteRange(Kind kind, int64_t first, int64_t last)
, last_(last)
{}
ByteRange ByteRange::parse(std::string rangeStr)
{
ByteRange byteRange;
const std::string byteUnitSpec("bytes=");
if ( kiwix::startsWith(rangeStr, byteUnitSpec) ) {
rangeStr.erase(0, byteUnitSpec.size());
std::istringstream iss(rangeStr);
int64_t start, end = INT64_MAX;
if (iss >> start) {
if ( start < 0 ) {
if ( iss.eof() )
byteRange = ByteRange(ByteRange::PARSED, start, end);
} else {
char c;
if (iss >> c && c=='-') {
iss >> end; // if this fails, end is not modified, which is OK
if (iss.eof())
byteRange = ByteRange(ByteRange::PARSED, start, end);
}
}
}
}
return byteRange;
}
} // namespace kiwix

View File

@ -22,6 +22,7 @@
#define KIWIXLIB_SERVER_BYTE_RANGE_H
#include <cstdint>
#include <string>
namespace kiwix {
@ -51,6 +52,8 @@ class ByteRange
int64_t last() const { return last_; }
int64_t length() const { return last_ + 1 - first_; }
static ByteRange parse(std::string rangeStr);
private: // data
Kind kind_;
int64_t first_;

View File

@ -20,7 +20,6 @@
#include "request_context.h"
#include "tools/stringTools.h"
#include <string.h>
#include <stdexcept>
#include <sstream>
@ -63,32 +62,6 @@ fullURL2LocalURL(const std::string& full_url, const std::string& rootLocation)
}
}
ByteRange parse_byte_range(std::string range)
{
ByteRange byteRange;
const std::string byteUnitSpec("bytes=");
if ( kiwix::startsWith(range, byteUnitSpec) ) {
range.erase(0, byteUnitSpec.size());
std::istringstream iss(range);
int64_t start, end = INT64_MAX;
if (iss >> start) {
if ( start < 0 ) {
if ( iss.eof() )
byteRange = ByteRange(ByteRange::PARSED, start, end);
} else {
char c;
if (iss >> c && c=='-') {
iss >> end; // if this fails, end is not modified, which is OK
if (iss.eof())
byteRange = ByteRange(ByteRange::PARSED, start, end);
}
}
}
}
return byteRange;
}
} // unnamed namespace
@ -114,7 +87,7 @@ RequestContext::RequestContext(struct MHD_Connection* connection,
} catch (const std::out_of_range&) {}
try {
byteRange_ = parse_byte_range(get_header(MHD_HTTP_HEADER_RANGE));
byteRange_ = ByteRange::parse(get_header(MHD_HTTP_HEADER_RANGE));
} catch (const std::out_of_range&) {}
}