Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / ui / gfx / range / range_f.cc
blobb9dfd7a3035f8ce841dd2962a7bf8a5e00b922b2
1 // Copyright 2015 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.
5 #include "ui/gfx/range/range_f.h"
7 #include <algorithm>
8 #include <cmath>
9 #include <limits>
11 #include "base/format_macros.h"
12 #include "base/strings/stringprintf.h"
14 namespace gfx {
16 RangeF::RangeF()
17 : start_(0.0f),
18 end_(0.0f) {
21 RangeF::RangeF(float start, float end)
22 : start_(start),
23 end_(end) {
26 RangeF::RangeF(float position)
27 : start_(position),
28 end_(position) {
31 // static
32 const RangeF RangeF::InvalidRange() {
33 return RangeF(std::numeric_limits<float>::max());
36 bool RangeF::IsValid() const {
37 return *this != InvalidRange();
40 float RangeF::GetMin() const {
41 return std::min(start(), end());
44 float RangeF::GetMax() const {
45 return std::max(start(), end());
48 bool RangeF::operator==(const RangeF& other) const {
49 return start() == other.start() && end() == other.end();
52 bool RangeF::operator!=(const RangeF& other) const {
53 return !(*this == other);
56 bool RangeF::EqualsIgnoringDirection(const RangeF& other) const {
57 return GetMin() == other.GetMin() && GetMax() == other.GetMax();
60 bool RangeF::Intersects(const RangeF& range) const {
61 return IsValid() && range.IsValid() &&
62 !(range.GetMax() < GetMin() || range.GetMin() >= GetMax());
65 bool RangeF::Contains(const RangeF& range) const {
66 return IsValid() && range.IsValid() &&
67 GetMin() <= range.GetMin() && range.GetMax() <= GetMax();
70 RangeF RangeF::Intersect(const RangeF& range) const {
71 float min = std::max(GetMin(), range.GetMin());
72 float max = std::min(GetMax(), range.GetMax());
74 if (min >= max) // No intersection.
75 return InvalidRange();
77 return RangeF(min, max);
80 RangeF RangeF::Intersect(const Range& range) const {
81 RangeF range_f(range.start(), range.end());
82 return Intersect(range_f);
85 Range RangeF::Floor() const {
86 size_t start = start_ > 0.0f ? static_cast<size_t>(std::floor(start_)) : 0;
87 size_t end = end_ > 0.0f ? static_cast<size_t>(std::floor(end_)) : 0;
88 return Range(start, end);
91 Range RangeF::Ceil() const {
92 size_t start = start_ > 0.0f ? static_cast<size_t>(std::ceil(start_)) : 0;
93 size_t end = end_ > 0.0f ? static_cast<size_t>(std::ceil(end_)) : 0;
94 return Range(start, end);
97 Range RangeF::Round() const {
98 size_t start =
99 start_ > 0.0f ? static_cast<size_t>(std::floor(start_ + 0.5f)) : 0;
100 size_t end = end_ > 0.0f ? static_cast<size_t>(std::floor(end_ + 0.5f)) : 0;
101 return Range(start, end);
104 std::string RangeF::ToString() const {
105 return base::StringPrintf("{%f,%f}", start(), end());
108 std::ostream& operator<<(std::ostream& os, const RangeF& range) {
109 return os << range.ToString();
112 } // namespace gfx