1 // Copyright (c) 2012 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. 4 5 #include "ui/base/range/range.h" 6 7 #include <limits> 8 9 #include "base/format_macros.h" 10 #include "base/logging.h" 11 #include "base/strings/stringprintf.h" 12 13 namespace ui { 14 15 Range::Range() 16 : start_(0), 17 end_(0) { 18 } 19 20 Range::Range(size_t start, size_t end) 21 : start_(start), 22 end_(end) { 23 } 24 25 Range::Range(size_t position) 26 : start_(position), 27 end_(position) { 28 } 29 30 // static 31 const Range Range::InvalidRange() { 32 return Range(std::numeric_limits<size_t>::max()); 33 } 34 35 bool Range::IsValid() const { 36 return *this != InvalidRange(); 37 } 38 39 size_t Range::GetMin() const { 40 return std::min(start(), end()); 41 } 42 43 size_t Range::GetMax() const { 44 return std::max(start(), end()); 45 } 46 47 bool Range::operator==(const Range& other) const { 48 return start() == other.start() && end() == other.end(); 49 } 50 51 bool Range::operator!=(const Range& other) const { 52 return !(*this == other); 53 } 54 55 bool Range::EqualsIgnoringDirection(const Range& other) const { 56 return GetMin() == other.GetMin() && GetMax() == other.GetMax(); 57 } 58 59 bool Range::Intersects(const Range& range) const { 60 return IsValid() && range.IsValid() && 61 !(range.GetMax() < GetMin() || range.GetMin() >= GetMax()); 62 } 63 64 bool Range::Contains(const Range& range) const { 65 return IsValid() && range.IsValid() && 66 GetMin() <= range.GetMin() && range.GetMax() <= GetMax(); 67 } 68 69 Range Range::Intersect(const Range& range) const { 70 size_t min = std::max(GetMin(), range.GetMin()); 71 size_t max = std::min(GetMax(), range.GetMax()); 72 73 if (min >= max) // No intersection. 74 return InvalidRange(); 75 76 return Range(min, max); 77 } 78 79 std::string Range::ToString() const { 80 return base::StringPrintf("{%" PRIuS ",%" PRIuS "}", start(), end()); 81 } 82 83 } // namespace gfx 84