1 // Copyright (c) 2009 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
7 #include "base/format_macros.h"
8 #include "base/logging.h"
9 #include "base/strings/stringprintf.h"
10 #include "net/http/http_byte_range.h"
14 const int64 kPositionNotSpecified = -1;
20 HttpByteRange::HttpByteRange()
21 : first_byte_position_(kPositionNotSpecified),
22 last_byte_position_(kPositionNotSpecified),
23 suffix_length_(kPositionNotSpecified),
24 has_computed_bounds_(false) {
28 HttpByteRange HttpByteRange::Bounded(int64 first_byte_position,
29 int64 last_byte_position) {
31 range.set_first_byte_position(first_byte_position);
32 range.set_last_byte_position(last_byte_position);
37 HttpByteRange HttpByteRange::RightUnbounded(int64 first_byte_position) {
39 range.set_first_byte_position(first_byte_position);
44 HttpByteRange HttpByteRange::Suffix(int64 suffix_length) {
46 range.set_suffix_length(suffix_length);
50 bool HttpByteRange::IsSuffixByteRange() const {
51 return suffix_length_ != kPositionNotSpecified;
54 bool HttpByteRange::HasFirstBytePosition() const {
55 return first_byte_position_ != kPositionNotSpecified;
58 bool HttpByteRange::HasLastBytePosition() const {
59 return last_byte_position_ != kPositionNotSpecified;
62 bool HttpByteRange::IsValid() const {
63 if (suffix_length_ > 0)
65 return (first_byte_position_ >= 0 &&
66 (last_byte_position_ == kPositionNotSpecified ||
67 last_byte_position_ >= first_byte_position_));
70 std::string HttpByteRange::GetHeaderValue() const {
73 if (IsSuffixByteRange())
74 return base::StringPrintf("bytes=-%" PRId64, suffix_length());
76 DCHECK(HasFirstBytePosition());
78 if (!HasLastBytePosition())
79 return base::StringPrintf("bytes=%" PRId64 "-", first_byte_position());
81 return base::StringPrintf("bytes=%" PRId64 "-%" PRId64,
82 first_byte_position(), last_byte_position());
85 bool HttpByteRange::ComputeBounds(int64 size) {
88 if (has_computed_bounds_)
90 has_computed_bounds_ = true;
93 if (!HasFirstBytePosition() &&
94 !HasLastBytePosition() &&
95 !IsSuffixByteRange()) {
96 first_byte_position_ = 0;
97 last_byte_position_ = size - 1;
102 if (IsSuffixByteRange()) {
103 first_byte_position_ = size - std::min(size, suffix_length_);
104 last_byte_position_ = size - 1;
107 if (first_byte_position_ < size) {
108 if (HasLastBytePosition())
109 last_byte_position_ = std::min(size - 1, last_byte_position_);
111 last_byte_position_ = size - 1;