summaryrefslogtreecommitdiffstats
path: root/ui/gfx/range/range_f.cc
blob: 8af832dc9b109f5a0e2dbe6b46edf7e029c01c00 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ui/gfx/range/range_f.h"

#include <algorithm>
#include <limits>

#include "base/float_util.h"
#include "base/format_macros.h"
#include "base/strings/stringprintf.h"

namespace gfx {

RangeF::RangeF()
    : start_(0.0f),
      end_(0.0f) {
}

RangeF::RangeF(float start, float end)
    : start_(start),
      end_(end) {
}

RangeF::RangeF(float position)
    : start_(position),
      end_(position) {
}

// static
const RangeF RangeF::InvalidRange() {
  return RangeF(std::numeric_limits<float>::max());
}

bool RangeF::IsValid() const {
  return *this != InvalidRange();
}

float RangeF::GetMin() const {
  return std::min(start(), end());
}

float RangeF::GetMax() const {
  return std::max(start(), end());
}

bool RangeF::operator==(const RangeF& other) const {
  return start() == other.start() && end() == other.end();
}

bool RangeF::operator!=(const RangeF& other) const {
  return !(*this == other);
}

bool RangeF::EqualsIgnoringDirection(const RangeF& other) const {
  return GetMin() == other.GetMin() && GetMax() == other.GetMax();
}

bool RangeF::Intersects(const RangeF& range) const {
  return IsValid() && range.IsValid() &&
      !(range.GetMax() < GetMin() || range.GetMin() >= GetMax());
}

bool RangeF::Contains(const RangeF& range) const {
  return IsValid() && range.IsValid() &&
      GetMin() <= range.GetMin() && range.GetMax() <= GetMax();
}

RangeF RangeF::Intersect(const RangeF& range) const {
  float min = std::max(GetMin(), range.GetMin());
  float max = std::min(GetMax(), range.GetMax());

  if (min >= max)  // No intersection.
    return InvalidRange();

  return RangeF(min, max);
}

std::string RangeF::ToString() const {
  return base::StringPrintf("{%f,%f}", start(), end());
}

std::ostream& operator<<(std::ostream& os, const RangeF& range) {
  return os << range.ToString();
}

}  // namespace gfx