fork additional raw chromium a11y code

This commit is contained in:
Chun-Heng Tai
2020-12-21 11:15:26 -08:00
committed by chunhtai
parent dc25ace136
commit da504d2db0
59 changed files with 11198 additions and 2 deletions

View File

@@ -122,7 +122,7 @@ function verify_licenses() (
local actualLicenseCount
actualLicenseCount="$(tail -n 1 flutter/ci/licenses_golden/licenses_flutter | tr -dc '0-9')"
local expectedLicenseCount=15 # When changing this number: Update the error message below as well describing all expected license types.
local expectedLicenseCount=17 # When changing this number: Update the error message below as well describing all expected license types.
if [[ $actualLicenseCount -ne $expectedLicenseCount ]]; then
echo "=============================== ERROR ==============================="

View File

@@ -22,6 +22,10 @@ FILE: ../../../flutter/third_party/accessibility/ax/platform/ax_platform_node_ma
FILE: ../../../flutter/third_party/accessibility/ax/platform/ax_platform_node_mac.mm
FILE: ../../../flutter/third_party/accessibility/ax/tree_generator.cc
FILE: ../../../flutter/third_party/accessibility/ax/tree_generator.h
FILE: ../../../flutter/third_party/accessibility/base/numerics/safe_conversions.h
FILE: ../../../flutter/third_party/accessibility/base/numerics/safe_conversions_impl.h
FILE: ../../../flutter/third_party/accessibility/gfx/mac/coordinate_conversion.h
FILE: ../../../flutter/third_party/accessibility/gfx/mac/coordinate_conversion.mm
----------------------------------------------------------------------------------------------------
Copyright 2014 The Chromium Authors. All rights reserved.
@@ -152,6 +156,17 @@ FILE: ../../../flutter/third_party/accessibility/ax/platform/ax_system_caret_win
FILE: ../../../flutter/third_party/accessibility/ax/platform/ax_system_caret_win.h
FILE: ../../../flutter/third_party/accessibility/ax/platform/ax_unique_id.cc
FILE: ../../../flutter/third_party/accessibility/ax/platform/ax_unique_id.h
FILE: ../../../flutter/third_party/accessibility/base/numerics/checked_math.h
FILE: ../../../flutter/third_party/accessibility/base/numerics/checked_math_impl.h
FILE: ../../../flutter/third_party/accessibility/base/numerics/clamped_math.h
FILE: ../../../flutter/third_party/accessibility/base/numerics/clamped_math_impl.h
FILE: ../../../flutter/third_party/accessibility/base/numerics/math_constants.h
FILE: ../../../flutter/third_party/accessibility/base/numerics/ranges.h
FILE: ../../../flutter/third_party/accessibility/base/numerics/safe_conversions_arm_impl.h
FILE: ../../../flutter/third_party/accessibility/base/numerics/safe_math.h
FILE: ../../../flutter/third_party/accessibility/base/numerics/safe_math_arm_impl.h
FILE: ../../../flutter/third_party/accessibility/base/numerics/safe_math_clang_gcc_impl.h
FILE: ../../../flutter/third_party/accessibility/base/numerics/safe_math_shared_impl.h
----------------------------------------------------------------------------------------------------
Copyright 2017 The Chromium Authors. All rights reserved.
@@ -283,6 +298,7 @@ LIBRARY: accessibility
ORIGIN: ../../../flutter/third_party/accessibility/ax/ax_text_utils.cc + ../../../LICENSE
TYPE: LicenseType.bsd
FILE: ../../../flutter/third_party/accessibility/ax/ax_text_utils.cc
FILE: ../../../flutter/third_party/accessibility/base/auto_reset.h
----------------------------------------------------------------------------------------------------
Copyright (c) 2011 The Chromium Authors. All rights reserved.
@@ -319,6 +335,40 @@ ORIGIN: ../../../flutter/third_party/accessibility/ax/ax_text_utils.h + ../../..
TYPE: LicenseType.bsd
FILE: ../../../flutter/third_party/accessibility/ax/ax_text_utils.h
FILE: ../../../flutter/third_party/accessibility/ax_build/build_config.h
FILE: ../../../flutter/third_party/accessibility/base/compiler_specific.h
FILE: ../../../flutter/third_party/accessibility/gfx/geometry/insets.h
FILE: ../../../flutter/third_party/accessibility/gfx/geometry/insets_f.cc
FILE: ../../../flutter/third_party/accessibility/gfx/geometry/insets_f.h
FILE: ../../../flutter/third_party/accessibility/gfx/geometry/point.cc
FILE: ../../../flutter/third_party/accessibility/gfx/geometry/point.h
FILE: ../../../flutter/third_party/accessibility/gfx/geometry/point_conversions.cc
FILE: ../../../flutter/third_party/accessibility/gfx/geometry/point_conversions.h
FILE: ../../../flutter/third_party/accessibility/gfx/geometry/point_f.cc
FILE: ../../../flutter/third_party/accessibility/gfx/geometry/point_f.h
FILE: ../../../flutter/third_party/accessibility/gfx/geometry/point_unittest.cc
FILE: ../../../flutter/third_party/accessibility/gfx/geometry/rect.cc
FILE: ../../../flutter/third_party/accessibility/gfx/geometry/rect.h
FILE: ../../../flutter/third_party/accessibility/gfx/geometry/rect_conversions.cc
FILE: ../../../flutter/third_party/accessibility/gfx/geometry/rect_conversions.h
FILE: ../../../flutter/third_party/accessibility/gfx/geometry/rect_f.cc
FILE: ../../../flutter/third_party/accessibility/gfx/geometry/rect_f.h
FILE: ../../../flutter/third_party/accessibility/gfx/geometry/size.cc
FILE: ../../../flutter/third_party/accessibility/gfx/geometry/size.h
FILE: ../../../flutter/third_party/accessibility/gfx/geometry/size_conversions.cc
FILE: ../../../flutter/third_party/accessibility/gfx/geometry/size_conversions.h
FILE: ../../../flutter/third_party/accessibility/gfx/geometry/size_f.cc
FILE: ../../../flutter/third_party/accessibility/gfx/geometry/size_f.h
FILE: ../../../flutter/third_party/accessibility/gfx/geometry/size_unittest.cc
FILE: ../../../flutter/third_party/accessibility/gfx/geometry/vector2d.cc
FILE: ../../../flutter/third_party/accessibility/gfx/geometry/vector2d.h
FILE: ../../../flutter/third_party/accessibility/gfx/geometry/vector2d_conversions.cc
FILE: ../../../flutter/third_party/accessibility/gfx/geometry/vector2d_conversions.h
FILE: ../../../flutter/third_party/accessibility/gfx/geometry/vector2d_f.cc
FILE: ../../../flutter/third_party/accessibility/gfx/geometry/vector2d_f.h
FILE: ../../../flutter/third_party/accessibility/gfx/geometry/vector2d_unittest.cc
FILE: ../../../flutter/third_party/accessibility/gfx/native_widget_types.h
FILE: ../../../flutter/third_party/accessibility/gfx/transform.cc
FILE: ../../../flutter/third_party/accessibility/gfx/transform.h
----------------------------------------------------------------------------------------------------
Copyright (c) 2012 The Chromium Authors. All rights reserved.
@@ -411,6 +461,7 @@ FILE: ../../../flutter/third_party/accessibility/ax/platform/ax_platform_node_te
FILE: ../../../flutter/third_party/accessibility/ax/platform/compute_attributes.cc
FILE: ../../../flutter/third_party/accessibility/ax/platform/compute_attributes.h
FILE: ../../../flutter/third_party/accessibility/ax/run_all_unittests.cc
FILE: ../../../flutter/third_party/accessibility/base/no_destructor.h
----------------------------------------------------------------------------------------------------
Copyright 2018 The Chromium Authors. All rights reserved.
@@ -606,6 +657,78 @@ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
====================================================================================================
====================================================================================================
LIBRARY: accessibility
ORIGIN: ../../../flutter/third_party/accessibility/gfx/geometry/insets.cc + ../../../LICENSE
TYPE: LicenseType.bsd
FILE: ../../../flutter/third_party/accessibility/gfx/geometry/insets.cc
FILE: ../../../flutter/third_party/accessibility/gfx/geometry/insets_unittest.cc
----------------------------------------------------------------------------------------------------
Copyright (c) 2009 The Chromium Authors. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
====================================================================================================
====================================================================================================
LIBRARY: accessibility
ORIGIN: ../../../flutter/third_party/accessibility/gfx/geometry/rect_unittest.cc + ../../../LICENSE
TYPE: LicenseType.bsd
FILE: ../../../flutter/third_party/accessibility/gfx/geometry/rect_unittest.cc
FILE: ../../../flutter/third_party/accessibility/gfx/gfx_export.h
----------------------------------------------------------------------------------------------------
Copyright (c) 2013 The Chromium Authors. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
====================================================================================================
====================================================================================================
LIBRARY: accessibility
ORIGIN: ../../../third_party/icu/scripts/LICENSE
@@ -2549,4 +2672,4 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
====================================================================================================
Total license count: 15
Total license count: 17

View File

@@ -0,0 +1,52 @@
// Copyright (c) 2011 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.
#ifndef BASE_AUTO_RESET_H_
#define BASE_AUTO_RESET_H_
#include <utility>
// base::AutoReset<> is useful for setting a variable to a new value only within
// a particular scope. An base::AutoReset<> object resets a variable to its
// original value upon destruction, making it an alternative to writing
// "var = false;" or "var = old_val;" at all of a block's exit points.
//
// This should be obvious, but note that an base::AutoReset<> instance should
// have a shorter lifetime than its scoped_variable, to prevent invalid memory
// writes when the base::AutoReset<> object is destroyed.
namespace base {
template <typename T>
class AutoReset {
public:
template <typename U>
AutoReset(T* scoped_variable, U&& new_value)
: scoped_variable_(scoped_variable),
original_value_(
std::exchange(*scoped_variable_, std::forward<U>(new_value))) {}
AutoReset(AutoReset&& other)
: scoped_variable_(std::exchange(other.scoped_variable_, nullptr)),
original_value_(std::move(other.original_value_)) {}
AutoReset& operator=(AutoReset&& rhs) {
scoped_variable_ = std::exchange(rhs.scoped_variable_, nullptr);
original_value_ = std::move(rhs.original_value_);
return *this;
}
~AutoReset() {
if (scoped_variable_)
*scoped_variable_ = std::move(original_value_);
}
private:
T* scoped_variable_;
T original_value_;
};
} // namespace base
#endif // BASE_AUTO_RESET_H_

View File

@@ -0,0 +1,308 @@
// Copyright (c) 2012 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.
#ifndef BASE_COMPILER_SPECIFIC_H_
#define BASE_COMPILER_SPECIFIC_H_
#include "build/build_config.h"
#if defined(COMPILER_MSVC) && !defined(__clang__)
#error "Only clang-cl is supported on Windows, see https://crbug.com/988071"
#endif
// Annotate a variable indicating it's ok if the variable is not used.
// (Typically used to silence a compiler warning when the assignment
// is important for some other reason.)
// Use like:
// int x = ...;
// ALLOW_UNUSED_LOCAL(x);
#define ALLOW_UNUSED_LOCAL(x) (void)x
// Annotate a typedef or function indicating it's ok if it's not used.
// Use like:
// typedef Foo Bar ALLOW_UNUSED_TYPE;
#if defined(COMPILER_GCC) || defined(__clang__)
#define ALLOW_UNUSED_TYPE __attribute__((unused))
#else
#define ALLOW_UNUSED_TYPE
#endif
// Annotate a function indicating it should not be inlined.
// Use like:
// NOINLINE void DoStuff() { ... }
#if defined(COMPILER_GCC)
#define NOINLINE __attribute__((noinline))
#elif defined(COMPILER_MSVC)
#define NOINLINE __declspec(noinline)
#else
#define NOINLINE
#endif
#if defined(COMPILER_GCC) && defined(NDEBUG)
#define ALWAYS_INLINE inline __attribute__((__always_inline__))
#elif defined(COMPILER_MSVC) && defined(NDEBUG)
#define ALWAYS_INLINE __forceinline
#else
#define ALWAYS_INLINE inline
#endif
// Annotate a function indicating it should never be tail called. Useful to make
// sure callers of the annotated function are never omitted from call-stacks.
// To provide the complementary behavior (prevent the annotated function from
// being omitted) look at NOINLINE. Also note that this doesn't prevent code
// folding of multiple identical caller functions into a single signature. To
// prevent code folding, see base::debug::Alias.
// Use like:
// void NOT_TAIL_CALLED FooBar();
#if defined(__clang__) && __has_attribute(not_tail_called)
#define NOT_TAIL_CALLED __attribute__((not_tail_called))
#else
#define NOT_TAIL_CALLED
#endif
// Specify memory alignment for structs, classes, etc.
// Use like:
// class ALIGNAS(16) MyClass { ... }
// ALIGNAS(16) int array[4];
//
// In most places you can use the C++11 keyword "alignas", which is preferred.
//
// But compilers have trouble mixing __attribute__((...)) syntax with
// alignas(...) syntax.
//
// Doesn't work in clang or gcc:
// struct alignas(16) __attribute__((packed)) S { char c; };
// Works in clang but not gcc:
// struct __attribute__((packed)) alignas(16) S2 { char c; };
// Works in clang and gcc:
// struct alignas(16) S3 { char c; } __attribute__((packed));
//
// There are also some attributes that must be specified *before* a class
// definition: visibility (used for exporting functions/classes) is one of
// these attributes. This means that it is not possible to use alignas() with a
// class that is marked as exported.
#if defined(COMPILER_MSVC)
#define ALIGNAS(byte_alignment) __declspec(align(byte_alignment))
#elif defined(COMPILER_GCC)
#define ALIGNAS(byte_alignment) __attribute__((aligned(byte_alignment)))
#endif
// Annotate a function indicating the caller must examine the return value.
// Use like:
// int foo() WARN_UNUSED_RESULT;
// To explicitly ignore a result, see |ignore_result()| in base/macros.h.
#undef WARN_UNUSED_RESULT
#if defined(COMPILER_GCC) || defined(__clang__)
#define WARN_UNUSED_RESULT __attribute__((warn_unused_result))
#else
#define WARN_UNUSED_RESULT
#endif
// Tell the compiler a function is using a printf-style format string.
// |format_param| is the one-based index of the format string parameter;
// |dots_param| is the one-based index of the "..." parameter.
// For v*printf functions (which take a va_list), pass 0 for dots_param.
// (This is undocumented but matches what the system C headers do.)
// For member functions, the implicit this parameter counts as index 1.
#if defined(COMPILER_GCC) || defined(__clang__)
#define PRINTF_FORMAT(format_param, dots_param) \
__attribute__((format(printf, format_param, dots_param)))
#else
#define PRINTF_FORMAT(format_param, dots_param)
#endif
// WPRINTF_FORMAT is the same, but for wide format strings.
// This doesn't appear to yet be implemented in any compiler.
// See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=38308 .
#define WPRINTF_FORMAT(format_param, dots_param)
// If available, it would look like:
// __attribute__((format(wprintf, format_param, dots_param)))
// Sanitizers annotations.
#if defined(__has_attribute)
#if __has_attribute(no_sanitize)
#define NO_SANITIZE(what) __attribute__((no_sanitize(what)))
#endif
#endif
#if !defined(NO_SANITIZE)
#define NO_SANITIZE(what)
#endif
// MemorySanitizer annotations.
#if defined(MEMORY_SANITIZER) && !defined(OS_NACL)
#include <sanitizer/msan_interface.h>
// Mark a memory region fully initialized.
// Use this to annotate code that deliberately reads uninitialized data, for
// example a GC scavenging root set pointers from the stack.
#define MSAN_UNPOISON(p, size) __msan_unpoison(p, size)
// Check a memory region for initializedness, as if it was being used here.
// If any bits are uninitialized, crash with an MSan report.
// Use this to sanitize data which MSan won't be able to track, e.g. before
// passing data to another process via shared memory.
#define MSAN_CHECK_MEM_IS_INITIALIZED(p, size) \
__msan_check_mem_is_initialized(p, size)
#else // MEMORY_SANITIZER
#define MSAN_UNPOISON(p, size)
#define MSAN_CHECK_MEM_IS_INITIALIZED(p, size)
#endif // MEMORY_SANITIZER
// DISABLE_CFI_PERF -- Disable Control Flow Integrity for perf reasons.
#if !defined(DISABLE_CFI_PERF)
#if defined(__clang__) && defined(OFFICIAL_BUILD)
#define DISABLE_CFI_PERF __attribute__((no_sanitize("cfi")))
#else
#define DISABLE_CFI_PERF
#endif
#endif
// DISABLE_CFI_ICALL -- Disable Control Flow Integrity indirect call checks.
#if !defined(DISABLE_CFI_ICALL)
#if defined(OS_WIN)
// Windows also needs __declspec(guard(nocf)).
#define DISABLE_CFI_ICALL NO_SANITIZE("cfi-icall") __declspec(guard(nocf))
#else
#define DISABLE_CFI_ICALL NO_SANITIZE("cfi-icall")
#endif
#endif
#if !defined(DISABLE_CFI_ICALL)
#define DISABLE_CFI_ICALL
#endif
// Macro useful for writing cross-platform function pointers.
#if !defined(CDECL)
#if defined(OS_WIN)
#define CDECL __cdecl
#else // defined(OS_WIN)
#define CDECL
#endif // defined(OS_WIN)
#endif // !defined(CDECL)
// Macro for hinting that an expression is likely to be false.
#if !defined(UNLIKELY)
#if defined(COMPILER_GCC) || defined(__clang__)
#define UNLIKELY(x) __builtin_expect(!!(x), 0)
#else
#define UNLIKELY(x) (x)
#endif // defined(COMPILER_GCC)
#endif // !defined(UNLIKELY)
#if !defined(LIKELY)
#if defined(COMPILER_GCC) || defined(__clang__)
#define LIKELY(x) __builtin_expect(!!(x), 1)
#else
#define LIKELY(x) (x)
#endif // defined(COMPILER_GCC)
#endif // !defined(LIKELY)
// Compiler feature-detection.
// clang.llvm.org/docs/LanguageExtensions.html#has-feature-and-has-extension
#if defined(__has_feature)
#define HAS_FEATURE(FEATURE) __has_feature(FEATURE)
#else
#define HAS_FEATURE(FEATURE) 0
#endif
// Macro for telling -Wimplicit-fallthrough that a fallthrough is intentional.
#if defined(__clang__)
#define FALLTHROUGH [[clang::fallthrough]]
#else
#define FALLTHROUGH
#endif
#if defined(COMPILER_GCC)
#define PRETTY_FUNCTION __PRETTY_FUNCTION__
#elif defined(COMPILER_MSVC)
#define PRETTY_FUNCTION __FUNCSIG__
#else
// See https://en.cppreference.com/w/c/language/function_definition#func
#define PRETTY_FUNCTION __func__
#endif
#if !defined(CPU_ARM_NEON)
#if defined(__arm__)
#if !defined(__ARMEB__) && !defined(__ARM_EABI__) && !defined(__EABI__) && \
!defined(__VFP_FP__) && !defined(_WIN32_WCE) && !defined(ANDROID)
#error Chromium does not support middle endian architecture
#endif
#if defined(__ARM_NEON__)
#define CPU_ARM_NEON 1
#endif
#endif // defined(__arm__)
#endif // !defined(CPU_ARM_NEON)
#if !defined(HAVE_MIPS_MSA_INTRINSICS)
#if defined(__mips_msa) && defined(__mips_isa_rev) && (__mips_isa_rev >= 5)
#define HAVE_MIPS_MSA_INTRINSICS 1
#endif
#endif
#if defined(__clang__) && __has_attribute(uninitialized)
// Attribute "uninitialized" disables -ftrivial-auto-var-init=pattern for
// the specified variable.
// Library-wide alternative is
// 'configs -= [ "//build/config/compiler:default_init_stack_vars" ]' in .gn
// file.
//
// See "init_stack_vars" in build/config/compiler/BUILD.gn and
// http://crbug.com/977230
// "init_stack_vars" is enabled for non-official builds and we hope to enable it
// in official build in 2020 as well. The flag writes fixed pattern into
// uninitialized parts of all local variables. In rare cases such initialization
// is undesirable and attribute can be used:
// 1. Degraded performance
// In most cases compiler is able to remove additional stores. E.g. if memory is
// never accessed or properly initialized later. Preserved stores mostly will
// not affect program performance. However if compiler failed on some
// performance critical code we can get a visible regression in a benchmark.
// 2. memset, memcpy calls
// Compiler may replaces some memory writes with memset or memcpy calls. This is
// not -ftrivial-auto-var-init specific, but it can happen more likely with the
// flag. It can be a problem if code is not linked with C run-time library.
//
// Note: The flag is security risk mitigation feature. So in future the
// attribute uses should be avoided when possible. However to enable this
// mitigation on the most of the code we need to be less strict now and minimize
// number of exceptions later. So if in doubt feel free to use attribute, but
// please document the problem for someone who is going to cleanup it later.
// E.g. platform, bot, benchmark or test name in patch description or next to
// the attribute.
#define STACK_UNINITIALIZED __attribute__((uninitialized))
#else
#define STACK_UNINITIALIZED
#endif
// The ANALYZER_ASSUME_TRUE(bool arg) macro adds compiler-specific hints
// to Clang which control what code paths are statically analyzed,
// and is meant to be used in conjunction with assert & assert-like functions.
// The expression is passed straight through if analysis isn't enabled.
//
// ANALYZER_SKIP_THIS_PATH() suppresses static analysis for the current
// codepath and any other branching codepaths that might follow.
#if defined(__clang_analyzer__)
inline constexpr bool AnalyzerNoReturn() __attribute__((analyzer_noreturn)) {
return false;
}
inline constexpr bool AnalyzerAssumeTrue(bool arg) {
// AnalyzerNoReturn() is invoked and analysis is terminated if |arg| is
// false.
return arg || AnalyzerNoReturn();
}
#define ANALYZER_ASSUME_TRUE(arg) ::AnalyzerAssumeTrue(!!(arg))
#define ANALYZER_SKIP_THIS_PATH() static_cast<void>(::AnalyzerNoReturn())
#define ANALYZER_ALLOW_UNUSED(var) static_cast<void>(var);
#else // !defined(__clang_analyzer__)
#define ANALYZER_ASSUME_TRUE(arg) (arg)
#define ANALYZER_SKIP_THIS_PATH()
#define ANALYZER_ALLOW_UNUSED(var) static_cast<void>(var);
#endif // defined(__clang_analyzer__)
#endif // BASE_COMPILER_SPECIFIC_H_

View File

@@ -0,0 +1,98 @@
// Copyright 2018 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.
#ifndef BASE_NO_DESTRUCTOR_H_
#define BASE_NO_DESTRUCTOR_H_
#include <new>
#include <utility>
namespace base {
// A wrapper that makes it easy to create an object of type T with static
// storage duration that:
// - is only constructed on first access
// - never invokes the destructor
// in order to satisfy the styleguide ban on global constructors and
// destructors.
//
// Runtime constant example:
// const std::string& GetLineSeparator() {
// // Forwards to std::string(size_t, char, const Allocator&) constructor.
// static const base::NoDestructor<std::string> s(5, '-');
// return *s;
// }
//
// More complex initialization with a lambda:
// const std::string& GetSessionNonce() {
// static const base::NoDestructor<std::string> nonce([] {
// std::string s(16);
// crypto::RandString(s.data(), s.size());
// return s;
// }());
// return *nonce;
// }
//
// NoDestructor<T> stores the object inline, so it also avoids a pointer
// indirection and a malloc. Also note that since C++11 static local variable
// initialization is thread-safe and so is this pattern. Code should prefer to
// use NoDestructor<T> over:
// - A function scoped static T* or T& that is dynamically initialized.
// - A global base::LazyInstance<T>.
//
// Note that since the destructor is never run, this *will* leak memory if used
// as a stack or member variable. Furthermore, a NoDestructor<T> should never
// have global scope as that may require a static initializer.
template <typename T>
class NoDestructor {
public:
// Not constexpr; just write static constexpr T x = ...; if the value should
// be a constexpr.
template <typename... Args>
explicit NoDestructor(Args&&... args) {
new (storage_) T(std::forward<Args>(args)...);
}
// Allows copy and move construction of the contained type, to allow
// construction from an initializer list, e.g. for std::vector.
explicit NoDestructor(const T& x) { new (storage_) T(x); }
explicit NoDestructor(T&& x) { new (storage_) T(std::move(x)); }
NoDestructor(const NoDestructor&) = delete;
NoDestructor& operator=(const NoDestructor&) = delete;
~NoDestructor() = default;
const T& operator*() const { return *get(); }
T& operator*() { return *get(); }
const T* operator->() const { return get(); }
T* operator->() { return get(); }
const T* get() const { return reinterpret_cast<const T*>(storage_); }
T* get() { return reinterpret_cast<T*>(storage_); }
private:
alignas(T) char storage_[sizeof(T)];
#if defined(LEAK_SANITIZER)
// TODO(https://crbug.com/812277): This is a hack to work around the fact
// that LSan doesn't seem to treat NoDestructor as a root for reachability
// analysis. This means that code like this:
// static base::NoDestructor<std::vector<int>> v({1, 2, 3});
// is considered a leak. Using the standard leak sanitizer annotations to
// suppress leaks doesn't work: std::vector is implicitly constructed before
// calling the base::NoDestructor constructor.
//
// Unfortunately, I haven't been able to demonstrate this issue in simpler
// reproductions: until that's resolved, hold an explicit pointer to the
// placement-new'd object in leak sanitizer mode to help LSan realize that
// objects allocated by the contained type are still reachable.
T* storage_ptr_ = reinterpret_cast<T*>(storage_);
#endif // defined(LEAK_SANITIZER)
};
} // namespace base
#endif // BASE_NO_DESTRUCTOR_H_

View File

@@ -0,0 +1,28 @@
# Copyright (c) 2017 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.
# This is a dependency-free, header-only, library, and it needs to stay that
# way to facilitate pulling it into various third-party projects. So, this
# file is here to protect against accidentally introducing external
# dependencies or depending on internal implementation details.
source_set("base_numerics") {
visibility = [ "//base/*" ]
sources = [
"checked_math_impl.h",
"clamped_math_impl.h",
"safe_conversions_arm_impl.h",
"safe_conversions_impl.h",
"safe_math_arm_impl.h",
"safe_math_clang_gcc_impl.h",
"safe_math_shared_impl.h",
]
public = [
"checked_math.h",
"clamped_math.h",
"math_constants.h",
"ranges.h",
"safe_conversions.h",
"safe_math.h",
]
}

View File

@@ -0,0 +1,451 @@
# `base/numerics`
This directory contains a dependency-free, header-only library of templates
providing well-defined semantics for safely and performantly handling a variety
of numeric operations, including most common arithmetic operations and
conversions.
The public API is broken out into the following header files:
* `checked_math.h` contains the `CheckedNumeric` template class and helper
functions for performing arithmetic and conversion operations that detect
errors and boundary conditions (e.g. overflow, truncation, etc.).
* `clamped_math.h` contains the `ClampedNumeric` template class and
helper functions for performing fast, clamped (i.e. [non-sticky](#notsticky)
saturating) arithmetic operations and conversions.
* `safe_conversions.h` contains the `StrictNumeric` template class and
a collection of custom casting templates and helper functions for safely
converting between a range of numeric types.
* `safe_math.h` includes all of the previously mentioned headers.
*** aside
**Note:** The `Numeric` template types implicitly convert from C numeric types
and `Numeric` templates that are convertable to an underlying C numeric type.
The conversion priority for `Numeric` type coercions is:
* `StrictNumeric` coerces to `ClampedNumeric` and `CheckedNumeric`
* `ClampedNumeric` coerces to `CheckedNumeric`
***
[TOC]
## Common patterns and use-cases
The following covers the preferred style for the most common uses of this
library. Please don't cargo-cult from anywhere else. 😉
### Performing checked arithmetic type conversions
The `checked_cast` template converts between arbitrary arithmetic types, and is
used for cases where a conversion failure should result in program termination:
```cpp
// Crash if signed_value is out of range for buff_size.
size_t buff_size = checked_cast<size_t>(signed_value);
```
### Performing saturated (clamped) arithmetic type conversions
The `saturated_cast` template converts between arbitrary arithmetic types, and
is used in cases where an out-of-bounds source value should be saturated to the
corresponding maximum or minimum of the destination type:
```cpp
// Cast to a smaller type, saturating as needed.
int8_t eight_bit_value = saturated_cast<int8_t>(int_value);
// Convert from float with saturation to INT_MAX, INT_MIN, or 0 for NaN.
int int_value = saturated_cast<int>(floating_point_value);
```
`ClampCeil`, `ClampFloor`, and `ClampRound` provide similar functionality to the
versions in `std::`, but saturate and return an integral type. An optional
template parameter specifies the desired destination type (`int` if
unspecified). These should be used for most floating-to-integral conversions.
```cpp
// Basically saturated_cast<int>(std::round(floating_point_value)).
int int_value = ClampRound(floating_point_value);
// A destination type can be explicitly specified.
uint8_t byte_value = ClampFloor<uint8_t>(floating_point_value);
```
### Enforcing arithmetic type conversions at compile-time
The `strict_cast` emits code that is identical to `static_cast`. However,
provides static checks that will cause a compilation failure if the
destination type cannot represent the full range of the source type:
```cpp
// Throw a compiler error if byte_value is changed to an out-of-range-type.
int int_value = strict_cast<int>(byte_value);
```
You can also enforce these compile-time restrictions on function parameters by
using the `StrictNumeric` template:
```cpp
// Throw a compiler error if the size argument cannot be represented by a
// size_t (e.g. passing an int will fail to compile).
bool AllocateBuffer(void** buffer, StrictCast<size_t> size);
```
### Comparing values between arbitrary arithmetic types
Both the `StrictNumeric` and `ClampedNumeric` types provide well defined
comparisons between arbitrary arithmetic types. This allows you to perform
comparisons that are not legal or would trigger compiler warnings or errors
under the normal arithmetic promotion rules:
```cpp
bool foo(unsigned value, int upper_bound) {
// Converting to StrictNumeric allows this comparison to work correctly.
if (MakeStrictNum(value) >= upper_bound)
return false;
```
*** note
**Warning:** Do not perform manual conversions using the comparison operators.
Instead, use the cast templates described in the previous sections, or the
constexpr template functions `IsValueInRangeForNumericType` and
`IsTypeInRangeForNumericType`, as these templates properly handle the full range
of corner cases and employ various optimizations.
***
### Calculating a buffer size (checked arithmetic)
When making exact calculations—such as for buffer lengths—it's often necessary
to know when those calculations trigger an overflow, undefined behavior, or
other boundary conditions. The `CheckedNumeric` template does this by storing
a bit determining whether or not some arithmetic operation has occured that
would put the variable in an "invalid" state. Attempting to extract the value
from a variable in an invalid state will trigger a check/trap condition, that
by default will result in process termination.
Here's an example of a buffer calculation using a `CheckedNumeric` type (note:
the AssignIfValid method will trigger a compile error if the result is ignored).
```cpp
// Calculate the buffer size and detect if an overflow occurs.
size_t size;
if (!CheckAdd(kHeaderSize, CheckMul(count, kItemSize)).AssignIfValid(&size)) {
// Handle an overflow error...
}
```
### Calculating clamped coordinates (non-sticky saturating arithmetic)
Certain classes of calculations—such as coordinate calculations—require
well-defined semantics that always produce a valid result on boundary
conditions. The `ClampedNumeric` template addresses this by providing
performant, non-sticky saturating arithmetic operations.
Here's an example of using a `ClampedNumeric` to calculate an operation
insetting a rectangle.
```cpp
// Use clamped arithmetic since inset calculations might overflow.
void Rect::Inset(int left, int top, int right, int bottom) {
origin_ += Vector2d(left, top);
set_width(ClampSub(width(), ClampAdd(left, right)));
set_height(ClampSub(height(), ClampAdd(top, bottom)));
}
```
*** note
<a name="notsticky"></a>
The `ClampedNumeric` type is not "sticky", which means the saturation is not
retained across individual operations. As such, one arithmetic operation may
result in a saturated value, while the next operation may then "desaturate"
the value. Here's an example:
```cpp
ClampedNumeric<int> value = INT_MAX;
++value; // value is still INT_MAX, due to saturation.
--value; // value is now (INT_MAX - 1), because saturation is not sticky.
```
***
## Conversion functions and StrictNumeric<> in safe_conversions.h
This header includes a collection of helper `constexpr` templates for safely
performing a range of conversions, assignments, and tests.
### Safe casting templates
* `as_signed()` - Returns the supplied integral value as a signed type of
the same width.
* `as_unsigned()` - Returns the supplied integral value as an unsigned type
of the same width.
* `checked_cast<>()` - Analogous to `static_cast<>` for numeric types, except
that by default it will trigger a crash on an out-of-bounds conversion (e.g.
overflow, underflow, NaN to integral) or a compile error if the conversion
error can be detected at compile time. The crash handler can be overridden
to perform a behavior other than crashing.
* `saturated_cast<>()` - Analogous to `static_cast` for numeric types, except
that it returns a saturated result when the specified numeric conversion
would otherwise overflow or underflow. An NaN source returns 0 by
default, but can be overridden to return a different result.
* `strict_cast<>()` - Analogous to `static_cast` for numeric types, except
this causes a compile failure if the destination type is not large
enough to contain any value in the source type. It performs no runtime
checking and thus introduces no runtime overhead.
### Other helper and conversion functions
* `ClampCeil<>()` - A convenience function that computes the ceil of its floating-
point arg, then saturates to the destination type (template parameter,
defaults to `int`).
* `ClampFloor<>()` - A convenience function that computes the floor of its
floating-point arg, then saturates to the destination type (template
parameter, defaults to `int`).
* `IsTypeInRangeForNumericType<>()` - A convenience function that evaluates
entirely at compile-time and returns true if the destination type (first
template parameter) can represent the full range of the source type
(second template parameter).
* `IsValueInRangeForNumericType<>()` - A convenience function that returns
true if the type supplied as the template parameter can represent the value
passed as an argument to the function.
* `IsValueNegative()` - A convenience function that will accept any
arithmetic type as an argument and will return whether the value is less
than zero. Unsigned types always return false.
* `ClampRound<>()` - A convenience function that rounds its floating-point arg,
then saturates to the destination type (template parameter, defaults to
`int`).
* `SafeUnsignedAbs()` - Returns the absolute value of the supplied integer
parameter as an unsigned result (thus avoiding an overflow if the value
is the signed, two's complement minimum).
### StrictNumeric<>
`StrictNumeric<>` is a wrapper type that performs assignments and copies via
the `strict_cast` template, and can perform valid arithmetic comparisons
across any range of arithmetic types. `StrictNumeric` is the return type for
values extracted from a `CheckedNumeric` class instance. The raw numeric value
is extracted via `static_cast` to the underlying type or any type with
sufficient range to represent the underlying type.
* `MakeStrictNum()` - Creates a new `StrictNumeric` from the underlying type
of the supplied arithmetic or StrictNumeric type.
* `SizeT` - Alias for `StrictNumeric<size_t>`.
## CheckedNumeric<> in checked_math.h
`CheckedNumeric<>` implements all the logic and operators for detecting integer
boundary conditions such as overflow, underflow, and invalid conversions.
The `CheckedNumeric` type implicitly converts from floating point and integer
data types, and contains overloads for basic arithmetic operations (i.e.: `+`,
`-`, `*`, `/` for all types and `%`, `<<`, `>>`, `&`, `|`, `^` for integers).
However, *the [variadic template functions
](#CheckedNumeric_in-checked_math_h-Non_member-helper-functions)
are the prefered API,* as they remove type ambiguities and help prevent a number
of common errors. The variadic functions can also be more performant, as they
eliminate redundant expressions that are unavoidable with the with the operator
overloads. (Ideally the compiler should optimize those away, but better to avoid
them in the first place.)
Type promotions are a slightly modified version of the [standard C/C++ numeric
promotions
](http://en.cppreference.com/w/cpp/language/implicit_conversion#Numeric_promotions)
with the two differences being that *there is no default promotion to int*
and *bitwise logical operations always return an unsigned of the wider type.*
### Example
```
#include "base/numerics/checked_math.h"
...
CheckedNumeric<uint32_t> variable = 0;
variable++;
variable--;
if (variable.ValueOrDie() == 0)
// Fine, |variable| still within valid range.
variable--;
variable++;
if (variable.ValueOrDie() == 0) // Breakpoint or configured CheckHandler
// Does not happen as variable underflowed.
```
### Members
The unary negation, increment, and decrement operators are supported, along
with the following unary arithmetic methods, which return a new
`CheckedNumeric` as a result of the operation:
* `Abs()` - Absolute value.
* `UnsignedAbs()` - Absolute value as an equal-width unsigned underlying type
(valid for only integral types).
* `Max()` - Returns whichever is greater of the current instance or argument.
The underlying return type is whichever has the greatest magnitude.
* `Min()` - Returns whichever is lowest of the current instance or argument.
The underlying return type is whichever has can represent the lowest
number in the smallest width (e.g. int8_t over unsigned, int over
int8_t, and float over int).
The following are for converting `CheckedNumeric` instances:
* `type` - The underlying numeric type.
* `AssignIfValid()` - Assigns the underlying value to the supplied
destination pointer if the value is currently valid and within the
range supported by the destination type. Returns true on success.
* `Cast<>()` - Instance method returning a `CheckedNumeric` derived from
casting the current instance to a `CheckedNumeric` of the supplied
destination type.
*** aside
The following member functions return a `StrictNumeric`, which is valid for
comparison and assignment operations, but will trigger a compile failure on
attempts to assign to a type of insufficient range. The underlying value can
be extracted by an explicit `static_cast` to the underlying type or any type
with sufficient range to represent the underlying type.
***
* `IsValid()` - Returns true if the underlying numeric value is valid (i.e.
has not wrapped or saturated and is not the result of an invalid
conversion).
* `ValueOrDie()` - Returns the underlying value. If the state is not valid
this call will trigger a crash by default (but may be overridden by
supplying an alternate handler to the template).
* `ValueOrDefault()` - Returns the current value, or the supplied default if
the state is not valid (but will not crash).
**Comparison operators are explicitly not provided** for `CheckedNumeric`
types because they could result in a crash if the type is not in a valid state.
Patterns like the following should be used instead:
```cpp
// Either input or padding (or both) may be arbitrary sizes.
size_t buff_size;
if (!CheckAdd(input, padding, kHeaderLength).AssignIfValid(&buff_size) ||
buff_size >= kMaxBuffer) {
// Handle an error...
} else {
// Do stuff on success...
}
```
### Non-member helper functions
The following variadic convenience functions, which accept standard arithmetic
or `CheckedNumeric` types, perform arithmetic operations, and return a
`CheckedNumeric` result. The supported functions are:
* `CheckAdd()` - Addition.
* `CheckSub()` - Subtraction.
* `CheckMul()` - Multiplication.
* `CheckDiv()` - Division.
* `CheckMod()` - Modulus (integer only).
* `CheckLsh()` - Left integer shift (integer only).
* `CheckRsh()` - Right integer shift (integer only).
* `CheckAnd()` - Bitwise AND (integer only with unsigned result).
* `CheckOr()` - Bitwise OR (integer only with unsigned result).
* `CheckXor()` - Bitwise XOR (integer only with unsigned result).
* `CheckMax()` - Maximum of supplied arguments.
* `CheckMin()` - Minimum of supplied arguments.
The following wrapper functions can be used to avoid the template
disambiguator syntax when converting a destination type.
* `IsValidForType<>()` in place of: `a.template IsValid<>()`
* `ValueOrDieForType<>()` in place of: `a.template ValueOrDie<>()`
* `ValueOrDefaultForType<>()` in place of: `a.template ValueOrDefault<>()`
The following general utility methods is are useful for converting from
arithmetic types to `CheckedNumeric` types:
* `MakeCheckedNum()` - Creates a new `CheckedNumeric` from the underlying type
of the supplied arithmetic or directly convertible type.
## ClampedNumeric<> in clamped_math.h
`ClampedNumeric<>` implements all the logic and operators for clamped
(non-sticky saturating) arithmetic operations and conversions. The
`ClampedNumeric` type implicitly converts back and forth between floating point
and integer data types, saturating on assignment as appropriate. It contains
overloads for basic arithmetic operations (i.e.: `+`, `-`, `*`, `/` for
all types and `%`, `<<`, `>>`, `&`, `|`, `^` for integers) along with comparison
operators for arithmetic types of any size. However, *the [variadic template
functions
](#ClampedNumeric_in-clamped_math_h-Non_member-helper-functions)
are the prefered API,* as they remove type ambiguities and help prevent
a number of common errors. The variadic functions can also be more performant,
as they eliminate redundant expressions that are unavoidable with the operator
overloads. (Ideally the compiler should optimize those away, but better to avoid
them in the first place.)
Type promotions are a slightly modified version of the [standard C/C++ numeric
promotions
](http://en.cppreference.com/w/cpp/language/implicit_conversion#Numeric_promotions)
with the two differences being that *there is no default promotion to int*
and *bitwise logical operations always return an unsigned of the wider type.*
*** aside
Most arithmetic operations saturate normally, to the numeric limit in the
direction of the sign. The potentially unusual cases are:
* **Division:** Division by zero returns the saturated limit in the direction
of sign of the dividend (first argument). The one exception is 0/0, which
returns zero (although logically is NaN).
* **Modulus:** Division by zero returns the dividend (first argument).
* **Left shift:** Non-zero values saturate in the direction of the signed
limit (max/min), even for shifts larger than the bit width. 0 shifted any
amount results in 0.
* **Right shift:** Negative values saturate to -1. Positive or 0 saturates
to 0. (Effectively just an unbounded arithmetic-right-shift.)
* **Bitwise operations:** No saturation; bit pattern is identical to
non-saturated bitwise operations.
***
### Members
The unary negation, increment, and decrement operators are supported, along
with the following unary arithmetic methods, which return a new
`ClampedNumeric` as a result of the operation:
* `Abs()` - Absolute value.
* `UnsignedAbs()` - Absolute value as an equal-width unsigned underlying type
(valid for only integral types).
* `Max()` - Returns whichever is greater of the current instance or argument.
The underlying return type is whichever has the greatest magnitude.
* `Min()` - Returns whichever is lowest of the current instance or argument.
The underlying return type is whichever has can represent the lowest
number in the smallest width (e.g. int8_t over unsigned, int over
int8_t, and float over int).
The following are for converting `ClampedNumeric` instances:
* `type` - The underlying numeric type.
* `RawValue()` - Returns the raw value as the underlying arithmetic type. This
is useful when e.g. assigning to an auto type or passing as a deduced
template parameter.
* `Cast<>()` - Instance method returning a `ClampedNumeric` derived from
casting the current instance to a `ClampedNumeric` of the supplied
destination type.
### Non-member helper functions
The following variadic convenience functions, which accept standard arithmetic
or `ClampedNumeric` types, perform arithmetic operations, and return a
`ClampedNumeric` result. The supported functions are:
* `ClampAdd()` - Addition.
* `ClampSub()` - Subtraction.
* `ClampMul()` - Multiplication.
* `ClampDiv()` - Division.
* `ClampMod()` - Modulus (integer only).
* `ClampLsh()` - Left integer shift (integer only).
* `ClampRsh()` - Right integer shift (integer only).
* `ClampAnd()` - Bitwise AND (integer only with unsigned result).
* `ClampOr()` - Bitwise OR (integer only with unsigned result).
* `ClampXor()` - Bitwise XOR (integer only with unsigned result).
* `ClampMax()` - Maximum of supplied arguments.
* `ClampMin()` - Minimum of supplied arguments.
The following is a general utility method that is useful for converting
to a `ClampedNumeric` type:
* `MakeClampedNum()` - Creates a new `ClampedNumeric` from the underlying type
of the supplied arithmetic or directly convertible type.

View File

@@ -0,0 +1,393 @@
// Copyright 2017 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.
#ifndef BASE_NUMERICS_CHECKED_MATH_H_
#define BASE_NUMERICS_CHECKED_MATH_H_
#include <stddef.h>
#include <limits>
#include <type_traits>
#include "base/numerics/checked_math_impl.h"
namespace base {
namespace internal {
template <typename T>
class CheckedNumeric {
static_assert(std::is_arithmetic<T>::value,
"CheckedNumeric<T>: T must be a numeric type.");
public:
using type = T;
constexpr CheckedNumeric() = default;
// Copy constructor.
template <typename Src>
constexpr CheckedNumeric(const CheckedNumeric<Src>& rhs)
: state_(rhs.state_.value(), rhs.IsValid()) {}
template <typename Src>
friend class CheckedNumeric;
// This is not an explicit constructor because we implicitly upgrade regular
// numerics to CheckedNumerics to make them easier to use.
template <typename Src>
constexpr CheckedNumeric(Src value) // NOLINT(runtime/explicit)
: state_(value) {
static_assert(std::is_arithmetic<Src>::value, "Argument must be numeric.");
}
// This is not an explicit constructor because we want a seamless conversion
// from StrictNumeric types.
template <typename Src>
constexpr CheckedNumeric(
StrictNumeric<Src> value) // NOLINT(runtime/explicit)
: state_(static_cast<Src>(value)) {}
// IsValid() - The public API to test if a CheckedNumeric is currently valid.
// A range checked destination type can be supplied using the Dst template
// parameter.
template <typename Dst = T>
constexpr bool IsValid() const {
return state_.is_valid() &&
IsValueInRangeForNumericType<Dst>(state_.value());
}
// AssignIfValid(Dst) - Assigns the underlying value if it is currently valid
// and is within the range supported by the destination type. Returns true if
// successful and false otherwise.
template <typename Dst>
#if defined(__clang__) || defined(__GNUC__)
__attribute__((warn_unused_result))
#elif defined(_MSC_VER)
_Check_return_
#endif
constexpr bool
AssignIfValid(Dst* result) const {
return BASE_NUMERICS_LIKELY(IsValid<Dst>())
? ((*result = static_cast<Dst>(state_.value())), true)
: false;
}
// ValueOrDie() - The primary accessor for the underlying value. If the
// current state is not valid it will CHECK and crash.
// A range checked destination type can be supplied using the Dst template
// parameter, which will trigger a CHECK if the value is not in bounds for
// the destination.
// The CHECK behavior can be overridden by supplying a handler as a
// template parameter, for test code, etc. However, the handler cannot access
// the underlying value, and it is not available through other means.
template <typename Dst = T, class CheckHandler = CheckOnFailure>
constexpr StrictNumeric<Dst> ValueOrDie() const {
return BASE_NUMERICS_LIKELY(IsValid<Dst>())
? static_cast<Dst>(state_.value())
: CheckHandler::template HandleFailure<Dst>();
}
// ValueOrDefault(T default_value) - A convenience method that returns the
// current value if the state is valid, and the supplied default_value for
// any other state.
// A range checked destination type can be supplied using the Dst template
// parameter. WARNING: This function may fail to compile or CHECK at runtime
// if the supplied default_value is not within range of the destination type.
template <typename Dst = T, typename Src>
constexpr StrictNumeric<Dst> ValueOrDefault(const Src default_value) const {
return BASE_NUMERICS_LIKELY(IsValid<Dst>())
? static_cast<Dst>(state_.value())
: checked_cast<Dst>(default_value);
}
// Returns a checked numeric of the specified type, cast from the current
// CheckedNumeric. If the current state is invalid or the destination cannot
// represent the result then the returned CheckedNumeric will be invalid.
template <typename Dst>
constexpr CheckedNumeric<typename UnderlyingType<Dst>::type> Cast() const {
return *this;
}
// This friend method is available solely for providing more detailed logging
// in the tests. Do not implement it in production code, because the
// underlying values may change at any time.
template <typename U>
friend U GetNumericValueForTest(const CheckedNumeric<U>& src);
// Prototypes for the supported arithmetic operator overloads.
template <typename Src>
constexpr CheckedNumeric& operator+=(const Src rhs);
template <typename Src>
constexpr CheckedNumeric& operator-=(const Src rhs);
template <typename Src>
constexpr CheckedNumeric& operator*=(const Src rhs);
template <typename Src>
constexpr CheckedNumeric& operator/=(const Src rhs);
template <typename Src>
constexpr CheckedNumeric& operator%=(const Src rhs);
template <typename Src>
constexpr CheckedNumeric& operator<<=(const Src rhs);
template <typename Src>
constexpr CheckedNumeric& operator>>=(const Src rhs);
template <typename Src>
constexpr CheckedNumeric& operator&=(const Src rhs);
template <typename Src>
constexpr CheckedNumeric& operator|=(const Src rhs);
template <typename Src>
constexpr CheckedNumeric& operator^=(const Src rhs);
constexpr CheckedNumeric operator-() const {
// The negation of two's complement int min is int min, so we simply
// check for that in the constexpr case.
// We use an optimized code path for a known run-time variable.
return MustTreatAsConstexpr(state_.value()) || !std::is_signed<T>::value ||
std::is_floating_point<T>::value
? CheckedNumeric<T>(
NegateWrapper(state_.value()),
IsValid() && (!std::is_signed<T>::value ||
std::is_floating_point<T>::value ||
NegateWrapper(state_.value()) !=
std::numeric_limits<T>::lowest()))
: FastRuntimeNegate();
}
constexpr CheckedNumeric operator~() const {
return CheckedNumeric<decltype(InvertWrapper(T()))>(
InvertWrapper(state_.value()), IsValid());
}
constexpr CheckedNumeric Abs() const {
return !IsValueNegative(state_.value()) ? *this : -*this;
}
template <typename U>
constexpr CheckedNumeric<typename MathWrapper<CheckedMaxOp, T, U>::type> Max(
const U rhs) const {
using R = typename UnderlyingType<U>::type;
using result_type = typename MathWrapper<CheckedMaxOp, T, U>::type;
// TODO(jschuh): This can be converted to the MathOp version and remain
// constexpr once we have C++14 support.
return CheckedNumeric<result_type>(
static_cast<result_type>(
IsGreater<T, R>::Test(state_.value(), Wrapper<U>::value(rhs))
? state_.value()
: Wrapper<U>::value(rhs)),
state_.is_valid() && Wrapper<U>::is_valid(rhs));
}
template <typename U>
constexpr CheckedNumeric<typename MathWrapper<CheckedMinOp, T, U>::type> Min(
const U rhs) const {
using R = typename UnderlyingType<U>::type;
using result_type = typename MathWrapper<CheckedMinOp, T, U>::type;
// TODO(jschuh): This can be converted to the MathOp version and remain
// constexpr once we have C++14 support.
return CheckedNumeric<result_type>(
static_cast<result_type>(
IsLess<T, R>::Test(state_.value(), Wrapper<U>::value(rhs))
? state_.value()
: Wrapper<U>::value(rhs)),
state_.is_valid() && Wrapper<U>::is_valid(rhs));
}
// This function is available only for integral types. It returns an unsigned
// integer of the same width as the source type, containing the absolute value
// of the source, and properly handling signed min.
constexpr CheckedNumeric<typename UnsignedOrFloatForSize<T>::type>
UnsignedAbs() const {
return CheckedNumeric<typename UnsignedOrFloatForSize<T>::type>(
SafeUnsignedAbs(state_.value()), state_.is_valid());
}
constexpr CheckedNumeric& operator++() {
*this += 1;
return *this;
}
constexpr CheckedNumeric operator++(int) {
CheckedNumeric value = *this;
*this += 1;
return value;
}
constexpr CheckedNumeric& operator--() {
*this -= 1;
return *this;
}
constexpr CheckedNumeric operator--(int) {
CheckedNumeric value = *this;
*this -= 1;
return value;
}
// These perform the actual math operations on the CheckedNumerics.
// Binary arithmetic operations.
template <template <typename, typename, typename> class M,
typename L,
typename R>
static constexpr CheckedNumeric MathOp(const L lhs, const R rhs) {
using Math = typename MathWrapper<M, L, R>::math;
T result = 0;
bool is_valid =
Wrapper<L>::is_valid(lhs) && Wrapper<R>::is_valid(rhs) &&
Math::Do(Wrapper<L>::value(lhs), Wrapper<R>::value(rhs), &result);
return CheckedNumeric<T>(result, is_valid);
}
// Assignment arithmetic operations.
template <template <typename, typename, typename> class M, typename R>
constexpr CheckedNumeric& MathOp(const R rhs) {
using Math = typename MathWrapper<M, T, R>::math;
T result = 0; // Using T as the destination saves a range check.
bool is_valid = state_.is_valid() && Wrapper<R>::is_valid(rhs) &&
Math::Do(state_.value(), Wrapper<R>::value(rhs), &result);
*this = CheckedNumeric<T>(result, is_valid);
return *this;
}
private:
CheckedNumericState<T> state_;
CheckedNumeric FastRuntimeNegate() const {
T result;
bool success = CheckedSubOp<T, T>::Do(T(0), state_.value(), &result);
return CheckedNumeric<T>(result, IsValid() && success);
}
template <typename Src>
constexpr CheckedNumeric(Src value, bool is_valid)
: state_(value, is_valid) {}
// These wrappers allow us to handle state the same way for both
// CheckedNumeric and POD arithmetic types.
template <typename Src>
struct Wrapper {
static constexpr bool is_valid(Src) { return true; }
static constexpr Src value(Src value) { return value; }
};
template <typename Src>
struct Wrapper<CheckedNumeric<Src>> {
static constexpr bool is_valid(const CheckedNumeric<Src> v) {
return v.IsValid();
}
static constexpr Src value(const CheckedNumeric<Src> v) {
return v.state_.value();
}
};
template <typename Src>
struct Wrapper<StrictNumeric<Src>> {
static constexpr bool is_valid(const StrictNumeric<Src>) { return true; }
static constexpr Src value(const StrictNumeric<Src> v) {
return static_cast<Src>(v);
}
};
};
// Convenience functions to avoid the ugly template disambiguator syntax.
template <typename Dst, typename Src>
constexpr bool IsValidForType(const CheckedNumeric<Src> value) {
return value.template IsValid<Dst>();
}
template <typename Dst, typename Src>
constexpr StrictNumeric<Dst> ValueOrDieForType(
const CheckedNumeric<Src> value) {
return value.template ValueOrDie<Dst>();
}
template <typename Dst, typename Src, typename Default>
constexpr StrictNumeric<Dst> ValueOrDefaultForType(
const CheckedNumeric<Src> value,
const Default default_value) {
return value.template ValueOrDefault<Dst>(default_value);
}
// Convience wrapper to return a new CheckedNumeric from the provided arithmetic
// or CheckedNumericType.
template <typename T>
constexpr CheckedNumeric<typename UnderlyingType<T>::type> MakeCheckedNum(
const T value) {
return value;
}
// These implement the variadic wrapper for the math operations.
template <template <typename, typename, typename> class M,
typename L,
typename R>
constexpr CheckedNumeric<typename MathWrapper<M, L, R>::type> CheckMathOp(
const L lhs,
const R rhs) {
using Math = typename MathWrapper<M, L, R>::math;
return CheckedNumeric<typename Math::result_type>::template MathOp<M>(lhs,
rhs);
}
// General purpose wrapper template for arithmetic operations.
template <template <typename, typename, typename> class M,
typename L,
typename R,
typename... Args>
constexpr CheckedNumeric<typename ResultType<M, L, R, Args...>::type>
CheckMathOp(const L lhs, const R rhs, const Args... args) {
return CheckMathOp<M>(CheckMathOp<M>(lhs, rhs), args...);
}
BASE_NUMERIC_ARITHMETIC_OPERATORS(Checked, Check, Add, +, +=)
BASE_NUMERIC_ARITHMETIC_OPERATORS(Checked, Check, Sub, -, -=)
BASE_NUMERIC_ARITHMETIC_OPERATORS(Checked, Check, Mul, *, *=)
BASE_NUMERIC_ARITHMETIC_OPERATORS(Checked, Check, Div, /, /=)
BASE_NUMERIC_ARITHMETIC_OPERATORS(Checked, Check, Mod, %, %=)
BASE_NUMERIC_ARITHMETIC_OPERATORS(Checked, Check, Lsh, <<, <<=)
BASE_NUMERIC_ARITHMETIC_OPERATORS(Checked, Check, Rsh, >>, >>=)
BASE_NUMERIC_ARITHMETIC_OPERATORS(Checked, Check, And, &, &=)
BASE_NUMERIC_ARITHMETIC_OPERATORS(Checked, Check, Or, |, |=)
BASE_NUMERIC_ARITHMETIC_OPERATORS(Checked, Check, Xor, ^, ^=)
BASE_NUMERIC_ARITHMETIC_VARIADIC(Checked, Check, Max)
BASE_NUMERIC_ARITHMETIC_VARIADIC(Checked, Check, Min)
// These are some extra StrictNumeric operators to support simple pointer
// arithmetic with our result types. Since wrapping on a pointer is always
// bad, we trigger the CHECK condition here.
template <typename L, typename R>
L* operator+(L* lhs, const StrictNumeric<R> rhs) {
uintptr_t result = CheckAdd(reinterpret_cast<uintptr_t>(lhs),
CheckMul(sizeof(L), static_cast<R>(rhs)))
.template ValueOrDie<uintptr_t>();
return reinterpret_cast<L*>(result);
}
template <typename L, typename R>
L* operator-(L* lhs, const StrictNumeric<R> rhs) {
uintptr_t result = CheckSub(reinterpret_cast<uintptr_t>(lhs),
CheckMul(sizeof(L), static_cast<R>(rhs)))
.template ValueOrDie<uintptr_t>();
return reinterpret_cast<L*>(result);
}
} // namespace internal
using internal::CheckedNumeric;
using internal::IsValidForType;
using internal::ValueOrDieForType;
using internal::ValueOrDefaultForType;
using internal::MakeCheckedNum;
using internal::CheckMax;
using internal::CheckMin;
using internal::CheckAdd;
using internal::CheckSub;
using internal::CheckMul;
using internal::CheckDiv;
using internal::CheckMod;
using internal::CheckLsh;
using internal::CheckRsh;
using internal::CheckAnd;
using internal::CheckOr;
using internal::CheckXor;
} // namespace base
#endif // BASE_NUMERICS_CHECKED_MATH_H_

View File

@@ -0,0 +1,577 @@
// Copyright 2017 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.
#ifndef BASE_NUMERICS_CHECKED_MATH_IMPL_H_
#define BASE_NUMERICS_CHECKED_MATH_IMPL_H_
#include <stddef.h>
#include <stdint.h>
#include <climits>
#include <cmath>
#include <cstdlib>
#include <limits>
#include <type_traits>
#include "base/numerics/safe_conversions.h"
#include "base/numerics/safe_math_shared_impl.h"
namespace base {
namespace internal {
template <typename T>
constexpr bool CheckedAddImpl(T x, T y, T* result) {
static_assert(std::is_integral<T>::value, "Type must be integral");
// Since the value of x+y is undefined if we have a signed type, we compute
// it using the unsigned type of the same size.
using UnsignedDst = typename std::make_unsigned<T>::type;
using SignedDst = typename std::make_signed<T>::type;
UnsignedDst ux = static_cast<UnsignedDst>(x);
UnsignedDst uy = static_cast<UnsignedDst>(y);
UnsignedDst uresult = static_cast<UnsignedDst>(ux + uy);
*result = static_cast<T>(uresult);
// Addition is valid if the sign of (x + y) is equal to either that of x or
// that of y.
return (std::is_signed<T>::value)
? static_cast<SignedDst>((uresult ^ ux) & (uresult ^ uy)) >= 0
: uresult >= uy; // Unsigned is either valid or underflow.
}
template <typename T, typename U, class Enable = void>
struct CheckedAddOp {};
template <typename T, typename U>
struct CheckedAddOp<T,
U,
typename std::enable_if<std::is_integral<T>::value &&
std::is_integral<U>::value>::type> {
using result_type = typename MaxExponentPromotion<T, U>::type;
template <typename V>
static constexpr bool Do(T x, U y, V* result) {
// TODO(jschuh) Make this "constexpr if" once we're C++17.
if (CheckedAddFastOp<T, U>::is_supported)
return CheckedAddFastOp<T, U>::Do(x, y, result);
// Double the underlying type up to a full machine word.
using FastPromotion = typename FastIntegerArithmeticPromotion<T, U>::type;
using Promotion =
typename std::conditional<(IntegerBitsPlusSign<FastPromotion>::value >
IntegerBitsPlusSign<intptr_t>::value),
typename BigEnoughPromotion<T, U>::type,
FastPromotion>::type;
// Fail if either operand is out of range for the promoted type.
// TODO(jschuh): This could be made to work for a broader range of values.
if (BASE_NUMERICS_UNLIKELY(!IsValueInRangeForNumericType<Promotion>(x) ||
!IsValueInRangeForNumericType<Promotion>(y))) {
return false;
}
Promotion presult = {};
bool is_valid = true;
if (IsIntegerArithmeticSafe<Promotion, T, U>::value) {
presult = static_cast<Promotion>(x) + static_cast<Promotion>(y);
} else {
is_valid = CheckedAddImpl(static_cast<Promotion>(x),
static_cast<Promotion>(y), &presult);
}
*result = static_cast<V>(presult);
return is_valid && IsValueInRangeForNumericType<V>(presult);
}
};
template <typename T>
constexpr bool CheckedSubImpl(T x, T y, T* result) {
static_assert(std::is_integral<T>::value, "Type must be integral");
// Since the value of x+y is undefined if we have a signed type, we compute
// it using the unsigned type of the same size.
using UnsignedDst = typename std::make_unsigned<T>::type;
using SignedDst = typename std::make_signed<T>::type;
UnsignedDst ux = static_cast<UnsignedDst>(x);
UnsignedDst uy = static_cast<UnsignedDst>(y);
UnsignedDst uresult = static_cast<UnsignedDst>(ux - uy);
*result = static_cast<T>(uresult);
// Subtraction is valid if either x and y have same sign, or (x-y) and x have
// the same sign.
return (std::is_signed<T>::value)
? static_cast<SignedDst>((uresult ^ ux) & (ux ^ uy)) >= 0
: x >= y;
}
template <typename T, typename U, class Enable = void>
struct CheckedSubOp {};
template <typename T, typename U>
struct CheckedSubOp<T,
U,
typename std::enable_if<std::is_integral<T>::value &&
std::is_integral<U>::value>::type> {
using result_type = typename MaxExponentPromotion<T, U>::type;
template <typename V>
static constexpr bool Do(T x, U y, V* result) {
// TODO(jschuh) Make this "constexpr if" once we're C++17.
if (CheckedSubFastOp<T, U>::is_supported)
return CheckedSubFastOp<T, U>::Do(x, y, result);
// Double the underlying type up to a full machine word.
using FastPromotion = typename FastIntegerArithmeticPromotion<T, U>::type;
using Promotion =
typename std::conditional<(IntegerBitsPlusSign<FastPromotion>::value >
IntegerBitsPlusSign<intptr_t>::value),
typename BigEnoughPromotion<T, U>::type,
FastPromotion>::type;
// Fail if either operand is out of range for the promoted type.
// TODO(jschuh): This could be made to work for a broader range of values.
if (BASE_NUMERICS_UNLIKELY(!IsValueInRangeForNumericType<Promotion>(x) ||
!IsValueInRangeForNumericType<Promotion>(y))) {
return false;
}
Promotion presult = {};
bool is_valid = true;
if (IsIntegerArithmeticSafe<Promotion, T, U>::value) {
presult = static_cast<Promotion>(x) - static_cast<Promotion>(y);
} else {
is_valid = CheckedSubImpl(static_cast<Promotion>(x),
static_cast<Promotion>(y), &presult);
}
*result = static_cast<V>(presult);
return is_valid && IsValueInRangeForNumericType<V>(presult);
}
};
template <typename T>
constexpr bool CheckedMulImpl(T x, T y, T* result) {
static_assert(std::is_integral<T>::value, "Type must be integral");
// Since the value of x*y is potentially undefined if we have a signed type,
// we compute it using the unsigned type of the same size.
using UnsignedDst = typename std::make_unsigned<T>::type;
using SignedDst = typename std::make_signed<T>::type;
const UnsignedDst ux = SafeUnsignedAbs(x);
const UnsignedDst uy = SafeUnsignedAbs(y);
UnsignedDst uresult = static_cast<UnsignedDst>(ux * uy);
const bool is_negative =
std::is_signed<T>::value && static_cast<SignedDst>(x ^ y) < 0;
*result = is_negative ? 0 - uresult : uresult;
// We have a fast out for unsigned identity or zero on the second operand.
// After that it's an unsigned overflow check on the absolute value, with
// a +1 bound for a negative result.
return uy <= UnsignedDst(!std::is_signed<T>::value || is_negative) ||
ux <= (std::numeric_limits<T>::max() + UnsignedDst(is_negative)) / uy;
}
template <typename T, typename U, class Enable = void>
struct CheckedMulOp {};
template <typename T, typename U>
struct CheckedMulOp<T,
U,
typename std::enable_if<std::is_integral<T>::value &&
std::is_integral<U>::value>::type> {
using result_type = typename MaxExponentPromotion<T, U>::type;
template <typename V>
static constexpr bool Do(T x, U y, V* result) {
// TODO(jschuh) Make this "constexpr if" once we're C++17.
if (CheckedMulFastOp<T, U>::is_supported)
return CheckedMulFastOp<T, U>::Do(x, y, result);
using Promotion = typename FastIntegerArithmeticPromotion<T, U>::type;
// Verify the destination type can hold the result (always true for 0).
if (BASE_NUMERICS_UNLIKELY((!IsValueInRangeForNumericType<Promotion>(x) ||
!IsValueInRangeForNumericType<Promotion>(y)) &&
x && y)) {
return false;
}
Promotion presult = {};
bool is_valid = true;
if (CheckedMulFastOp<Promotion, Promotion>::is_supported) {
// The fast op may be available with the promoted type.
is_valid = CheckedMulFastOp<Promotion, Promotion>::Do(x, y, &presult);
} else if (IsIntegerArithmeticSafe<Promotion, T, U>::value) {
presult = static_cast<Promotion>(x) * static_cast<Promotion>(y);
} else {
is_valid = CheckedMulImpl(static_cast<Promotion>(x),
static_cast<Promotion>(y), &presult);
}
*result = static_cast<V>(presult);
return is_valid && IsValueInRangeForNumericType<V>(presult);
}
};
// Division just requires a check for a zero denominator or an invalid negation
// on signed min/-1.
template <typename T, typename U, class Enable = void>
struct CheckedDivOp {};
template <typename T, typename U>
struct CheckedDivOp<T,
U,
typename std::enable_if<std::is_integral<T>::value &&
std::is_integral<U>::value>::type> {
using result_type = typename MaxExponentPromotion<T, U>::type;
template <typename V>
static constexpr bool Do(T x, U y, V* result) {
if (BASE_NUMERICS_UNLIKELY(!y))
return false;
// The overflow check can be compiled away if we don't have the exact
// combination of types needed to trigger this case.
using Promotion = typename BigEnoughPromotion<T, U>::type;
if (BASE_NUMERICS_UNLIKELY(
(std::is_signed<T>::value && std::is_signed<U>::value &&
IsTypeInRangeForNumericType<T, Promotion>::value &&
static_cast<Promotion>(x) ==
std::numeric_limits<Promotion>::lowest() &&
y == static_cast<U>(-1)))) {
return false;
}
// This branch always compiles away if the above branch wasn't removed.
if (BASE_NUMERICS_UNLIKELY((!IsValueInRangeForNumericType<Promotion>(x) ||
!IsValueInRangeForNumericType<Promotion>(y)) &&
x)) {
return false;
}
Promotion presult = Promotion(x) / Promotion(y);
*result = static_cast<V>(presult);
return IsValueInRangeForNumericType<V>(presult);
}
};
template <typename T, typename U, class Enable = void>
struct CheckedModOp {};
template <typename T, typename U>
struct CheckedModOp<T,
U,
typename std::enable_if<std::is_integral<T>::value &&
std::is_integral<U>::value>::type> {
using result_type = typename MaxExponentPromotion<T, U>::type;
template <typename V>
static constexpr bool Do(T x, U y, V* result) {
if (BASE_NUMERICS_UNLIKELY(!y))
return false;
using Promotion = typename BigEnoughPromotion<T, U>::type;
if (BASE_NUMERICS_UNLIKELY(
(std::is_signed<T>::value && std::is_signed<U>::value &&
IsTypeInRangeForNumericType<T, Promotion>::value &&
static_cast<Promotion>(x) ==
std::numeric_limits<Promotion>::lowest() &&
y == static_cast<U>(-1)))) {
*result = 0;
return true;
}
Promotion presult = static_cast<Promotion>(x) % static_cast<Promotion>(y);
*result = static_cast<Promotion>(presult);
return IsValueInRangeForNumericType<V>(presult);
}
};
template <typename T, typename U, class Enable = void>
struct CheckedLshOp {};
// Left shift. Shifts less than 0 or greater than or equal to the number
// of bits in the promoted type are undefined. Shifts of negative values
// are undefined. Otherwise it is defined when the result fits.
template <typename T, typename U>
struct CheckedLshOp<T,
U,
typename std::enable_if<std::is_integral<T>::value &&
std::is_integral<U>::value>::type> {
using result_type = T;
template <typename V>
static constexpr bool Do(T x, U shift, V* result) {
// Disallow negative numbers and verify the shift is in bounds.
if (BASE_NUMERICS_LIKELY(!IsValueNegative(x) &&
as_unsigned(shift) <
as_unsigned(std::numeric_limits<T>::digits))) {
// Shift as unsigned to avoid undefined behavior.
*result = static_cast<V>(as_unsigned(x) << shift);
// If the shift can be reversed, we know it was valid.
return *result >> shift == x;
}
// Handle the legal corner-case of a full-width signed shift of zero.
return std::is_signed<T>::value && !x &&
as_unsigned(shift) == as_unsigned(std::numeric_limits<T>::digits);
}
};
template <typename T, typename U, class Enable = void>
struct CheckedRshOp {};
// Right shift. Shifts less than 0 or greater than or equal to the number
// of bits in the promoted type are undefined. Otherwise, it is always defined,
// but a right shift of a negative value is implementation-dependent.
template <typename T, typename U>
struct CheckedRshOp<T,
U,
typename std::enable_if<std::is_integral<T>::value &&
std::is_integral<U>::value>::type> {
using result_type = T;
template <typename V>
static bool Do(T x, U shift, V* result) {
// Use the type conversion push negative values out of range.
if (BASE_NUMERICS_LIKELY(as_unsigned(shift) <
IntegerBitsPlusSign<T>::value)) {
T tmp = x >> shift;
*result = static_cast<V>(tmp);
return IsValueInRangeForNumericType<V>(tmp);
}
return false;
}
};
template <typename T, typename U, class Enable = void>
struct CheckedAndOp {};
// For simplicity we support only unsigned integer results.
template <typename T, typename U>
struct CheckedAndOp<T,
U,
typename std::enable_if<std::is_integral<T>::value &&
std::is_integral<U>::value>::type> {
using result_type = typename std::make_unsigned<
typename MaxExponentPromotion<T, U>::type>::type;
template <typename V>
static constexpr bool Do(T x, U y, V* result) {
result_type tmp = static_cast<result_type>(x) & static_cast<result_type>(y);
*result = static_cast<V>(tmp);
return IsValueInRangeForNumericType<V>(tmp);
}
};
template <typename T, typename U, class Enable = void>
struct CheckedOrOp {};
// For simplicity we support only unsigned integers.
template <typename T, typename U>
struct CheckedOrOp<T,
U,
typename std::enable_if<std::is_integral<T>::value &&
std::is_integral<U>::value>::type> {
using result_type = typename std::make_unsigned<
typename MaxExponentPromotion<T, U>::type>::type;
template <typename V>
static constexpr bool Do(T x, U y, V* result) {
result_type tmp = static_cast<result_type>(x) | static_cast<result_type>(y);
*result = static_cast<V>(tmp);
return IsValueInRangeForNumericType<V>(tmp);
}
};
template <typename T, typename U, class Enable = void>
struct CheckedXorOp {};
// For simplicity we support only unsigned integers.
template <typename T, typename U>
struct CheckedXorOp<T,
U,
typename std::enable_if<std::is_integral<T>::value &&
std::is_integral<U>::value>::type> {
using result_type = typename std::make_unsigned<
typename MaxExponentPromotion<T, U>::type>::type;
template <typename V>
static constexpr bool Do(T x, U y, V* result) {
result_type tmp = static_cast<result_type>(x) ^ static_cast<result_type>(y);
*result = static_cast<V>(tmp);
return IsValueInRangeForNumericType<V>(tmp);
}
};
// Max doesn't really need to be implemented this way because it can't fail,
// but it makes the code much cleaner to use the MathOp wrappers.
template <typename T, typename U, class Enable = void>
struct CheckedMaxOp {};
template <typename T, typename U>
struct CheckedMaxOp<
T,
U,
typename std::enable_if<std::is_arithmetic<T>::value &&
std::is_arithmetic<U>::value>::type> {
using result_type = typename MaxExponentPromotion<T, U>::type;
template <typename V>
static constexpr bool Do(T x, U y, V* result) {
result_type tmp = IsGreater<T, U>::Test(x, y) ? static_cast<result_type>(x)
: static_cast<result_type>(y);
*result = static_cast<V>(tmp);
return IsValueInRangeForNumericType<V>(tmp);
}
};
// Min doesn't really need to be implemented this way because it can't fail,
// but it makes the code much cleaner to use the MathOp wrappers.
template <typename T, typename U, class Enable = void>
struct CheckedMinOp {};
template <typename T, typename U>
struct CheckedMinOp<
T,
U,
typename std::enable_if<std::is_arithmetic<T>::value &&
std::is_arithmetic<U>::value>::type> {
using result_type = typename LowestValuePromotion<T, U>::type;
template <typename V>
static constexpr bool Do(T x, U y, V* result) {
result_type tmp = IsLess<T, U>::Test(x, y) ? static_cast<result_type>(x)
: static_cast<result_type>(y);
*result = static_cast<V>(tmp);
return IsValueInRangeForNumericType<V>(tmp);
}
};
// This is just boilerplate that wraps the standard floating point arithmetic.
// A macro isn't the nicest solution, but it beats rewriting these repeatedly.
#define BASE_FLOAT_ARITHMETIC_OPS(NAME, OP) \
template <typename T, typename U> \
struct Checked##NAME##Op< \
T, U, \
typename std::enable_if<std::is_floating_point<T>::value || \
std::is_floating_point<U>::value>::type> { \
using result_type = typename MaxExponentPromotion<T, U>::type; \
template <typename V> \
static constexpr bool Do(T x, U y, V* result) { \
using Promotion = typename MaxExponentPromotion<T, U>::type; \
Promotion presult = x OP y; \
*result = static_cast<V>(presult); \
return IsValueInRangeForNumericType<V>(presult); \
} \
};
BASE_FLOAT_ARITHMETIC_OPS(Add, +)
BASE_FLOAT_ARITHMETIC_OPS(Sub, -)
BASE_FLOAT_ARITHMETIC_OPS(Mul, *)
BASE_FLOAT_ARITHMETIC_OPS(Div, /)
#undef BASE_FLOAT_ARITHMETIC_OPS
// Floats carry around their validity state with them, but integers do not. So,
// we wrap the underlying value in a specialization in order to hide that detail
// and expose an interface via accessors.
enum NumericRepresentation {
NUMERIC_INTEGER,
NUMERIC_FLOATING,
NUMERIC_UNKNOWN
};
template <typename NumericType>
struct GetNumericRepresentation {
static const NumericRepresentation value =
std::is_integral<NumericType>::value
? NUMERIC_INTEGER
: (std::is_floating_point<NumericType>::value ? NUMERIC_FLOATING
: NUMERIC_UNKNOWN);
};
template <typename T,
NumericRepresentation type = GetNumericRepresentation<T>::value>
class CheckedNumericState {};
// Integrals require quite a bit of additional housekeeping to manage state.
template <typename T>
class CheckedNumericState<T, NUMERIC_INTEGER> {
private:
// is_valid_ precedes value_ because member intializers in the constructors
// are evaluated in field order, and is_valid_ must be read when initializing
// value_.
bool is_valid_;
T value_;
// Ensures that a type conversion does not trigger undefined behavior.
template <typename Src>
static constexpr T WellDefinedConversionOrZero(const Src value,
const bool is_valid) {
using SrcType = typename internal::UnderlyingType<Src>::type;
return (std::is_integral<SrcType>::value || is_valid)
? static_cast<T>(value)
: static_cast<T>(0);
}
public:
template <typename Src, NumericRepresentation type>
friend class CheckedNumericState;
constexpr CheckedNumericState() : is_valid_(true), value_(0) {}
template <typename Src>
constexpr CheckedNumericState(Src value, bool is_valid)
: is_valid_(is_valid && IsValueInRangeForNumericType<T>(value)),
value_(WellDefinedConversionOrZero(value, is_valid_)) {
static_assert(std::is_arithmetic<Src>::value, "Argument must be numeric.");
}
// Copy constructor.
template <typename Src>
constexpr CheckedNumericState(const CheckedNumericState<Src>& rhs)
: is_valid_(rhs.IsValid()),
value_(WellDefinedConversionOrZero(rhs.value(), is_valid_)) {}
template <typename Src>
constexpr explicit CheckedNumericState(Src value)
: is_valid_(IsValueInRangeForNumericType<T>(value)),
value_(WellDefinedConversionOrZero(value, is_valid_)) {}
constexpr bool is_valid() const { return is_valid_; }
constexpr T value() const { return value_; }
};
// Floating points maintain their own validity, but need translation wrappers.
template <typename T>
class CheckedNumericState<T, NUMERIC_FLOATING> {
private:
T value_;
// Ensures that a type conversion does not trigger undefined behavior.
template <typename Src>
static constexpr T WellDefinedConversionOrNaN(const Src value,
const bool is_valid) {
using SrcType = typename internal::UnderlyingType<Src>::type;
return (StaticDstRangeRelationToSrcRange<T, SrcType>::value ==
NUMERIC_RANGE_CONTAINED ||
is_valid)
? static_cast<T>(value)
: std::numeric_limits<T>::quiet_NaN();
}
public:
template <typename Src, NumericRepresentation type>
friend class CheckedNumericState;
constexpr CheckedNumericState() : value_(0.0) {}
template <typename Src>
constexpr CheckedNumericState(Src value, bool is_valid)
: value_(WellDefinedConversionOrNaN(value, is_valid)) {}
template <typename Src>
constexpr explicit CheckedNumericState(Src value)
: value_(WellDefinedConversionOrNaN(
value,
IsValueInRangeForNumericType<T>(value))) {}
// Copy constructor.
template <typename Src>
constexpr CheckedNumericState(const CheckedNumericState<Src>& rhs)
: value_(WellDefinedConversionOrNaN(
rhs.value(),
rhs.is_valid() && IsValueInRangeForNumericType<T>(rhs.value()))) {}
constexpr bool is_valid() const {
// Written this way because std::isfinite is not reliably constexpr.
return MustTreatAsConstexpr(value_)
? value_ <= std::numeric_limits<T>::max() &&
value_ >= std::numeric_limits<T>::lowest()
: std::isfinite(value_);
}
constexpr T value() const { return value_; }
};
} // namespace internal
} // namespace base
#endif // BASE_NUMERICS_CHECKED_MATH_IMPL_H_

View File

@@ -0,0 +1,264 @@
// Copyright 2017 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.
#ifndef BASE_NUMERICS_CLAMPED_MATH_H_
#define BASE_NUMERICS_CLAMPED_MATH_H_
#include <stddef.h>
#include <limits>
#include <type_traits>
#include "base/numerics/clamped_math_impl.h"
namespace base {
namespace internal {
template <typename T>
class ClampedNumeric {
static_assert(std::is_arithmetic<T>::value,
"ClampedNumeric<T>: T must be a numeric type.");
public:
using type = T;
constexpr ClampedNumeric() : value_(0) {}
// Copy constructor.
template <typename Src>
constexpr ClampedNumeric(const ClampedNumeric<Src>& rhs)
: value_(saturated_cast<T>(rhs.value_)) {}
template <typename Src>
friend class ClampedNumeric;
// This is not an explicit constructor because we implicitly upgrade regular
// numerics to ClampedNumerics to make them easier to use.
template <typename Src>
constexpr ClampedNumeric(Src value) // NOLINT(runtime/explicit)
: value_(saturated_cast<T>(value)) {
static_assert(std::is_arithmetic<Src>::value, "Argument must be numeric.");
}
// This is not an explicit constructor because we want a seamless conversion
// from StrictNumeric types.
template <typename Src>
constexpr ClampedNumeric(
StrictNumeric<Src> value) // NOLINT(runtime/explicit)
: value_(saturated_cast<T>(static_cast<Src>(value))) {}
// Returns a ClampedNumeric of the specified type, cast from the current
// ClampedNumeric, and saturated to the destination type.
template <typename Dst>
constexpr ClampedNumeric<typename UnderlyingType<Dst>::type> Cast() const {
return *this;
}
// Prototypes for the supported arithmetic operator overloads.
template <typename Src>
constexpr ClampedNumeric& operator+=(const Src rhs);
template <typename Src>
constexpr ClampedNumeric& operator-=(const Src rhs);
template <typename Src>
constexpr ClampedNumeric& operator*=(const Src rhs);
template <typename Src>
constexpr ClampedNumeric& operator/=(const Src rhs);
template <typename Src>
constexpr ClampedNumeric& operator%=(const Src rhs);
template <typename Src>
constexpr ClampedNumeric& operator<<=(const Src rhs);
template <typename Src>
constexpr ClampedNumeric& operator>>=(const Src rhs);
template <typename Src>
constexpr ClampedNumeric& operator&=(const Src rhs);
template <typename Src>
constexpr ClampedNumeric& operator|=(const Src rhs);
template <typename Src>
constexpr ClampedNumeric& operator^=(const Src rhs);
constexpr ClampedNumeric operator-() const {
// The negation of two's complement int min is int min, so that's the
// only overflow case where we will saturate.
return ClampedNumeric<T>(SaturatedNegWrapper(value_));
}
constexpr ClampedNumeric operator~() const {
return ClampedNumeric<decltype(InvertWrapper(T()))>(InvertWrapper(value_));
}
constexpr ClampedNumeric Abs() const {
// The negation of two's complement int min is int min, so that's the
// only overflow case where we will saturate.
return ClampedNumeric<T>(SaturatedAbsWrapper(value_));
}
template <typename U>
constexpr ClampedNumeric<typename MathWrapper<ClampedMaxOp, T, U>::type> Max(
const U rhs) const {
using result_type = typename MathWrapper<ClampedMaxOp, T, U>::type;
return ClampedNumeric<result_type>(
ClampedMaxOp<T, U>::Do(value_, Wrapper<U>::value(rhs)));
}
template <typename U>
constexpr ClampedNumeric<typename MathWrapper<ClampedMinOp, T, U>::type> Min(
const U rhs) const {
using result_type = typename MathWrapper<ClampedMinOp, T, U>::type;
return ClampedNumeric<result_type>(
ClampedMinOp<T, U>::Do(value_, Wrapper<U>::value(rhs)));
}
// This function is available only for integral types. It returns an unsigned
// integer of the same width as the source type, containing the absolute value
// of the source, and properly handling signed min.
constexpr ClampedNumeric<typename UnsignedOrFloatForSize<T>::type>
UnsignedAbs() const {
return ClampedNumeric<typename UnsignedOrFloatForSize<T>::type>(
SafeUnsignedAbs(value_));
}
constexpr ClampedNumeric& operator++() {
*this += 1;
return *this;
}
constexpr ClampedNumeric operator++(int) {
ClampedNumeric value = *this;
*this += 1;
return value;
}
constexpr ClampedNumeric& operator--() {
*this -= 1;
return *this;
}
constexpr ClampedNumeric operator--(int) {
ClampedNumeric value = *this;
*this -= 1;
return value;
}
// These perform the actual math operations on the ClampedNumerics.
// Binary arithmetic operations.
template <template <typename, typename, typename> class M,
typename L,
typename R>
static constexpr ClampedNumeric MathOp(const L lhs, const R rhs) {
using Math = typename MathWrapper<M, L, R>::math;
return ClampedNumeric<T>(
Math::template Do<T>(Wrapper<L>::value(lhs), Wrapper<R>::value(rhs)));
}
// Assignment arithmetic operations.
template <template <typename, typename, typename> class M, typename R>
constexpr ClampedNumeric& MathOp(const R rhs) {
using Math = typename MathWrapper<M, T, R>::math;
*this =
ClampedNumeric<T>(Math::template Do<T>(value_, Wrapper<R>::value(rhs)));
return *this;
}
template <typename Dst>
constexpr operator Dst() const {
return saturated_cast<typename ArithmeticOrUnderlyingEnum<Dst>::type>(
value_);
}
// This method extracts the raw integer value without saturating it to the
// destination type as the conversion operator does. This is useful when
// e.g. assigning to an auto type or passing as a deduced template parameter.
constexpr T RawValue() const { return value_; }
private:
T value_;
// These wrappers allow us to handle state the same way for both
// ClampedNumeric and POD arithmetic types.
template <typename Src>
struct Wrapper {
static constexpr Src value(Src value) {
return static_cast<typename UnderlyingType<Src>::type>(value);
}
};
};
// Convience wrapper to return a new ClampedNumeric from the provided arithmetic
// or ClampedNumericType.
template <typename T>
constexpr ClampedNumeric<typename UnderlyingType<T>::type> MakeClampedNum(
const T value) {
return value;
}
#if !BASE_NUMERICS_DISABLE_OSTREAM_OPERATORS
// Overload the ostream output operator to make logging work nicely.
template <typename T>
std::ostream& operator<<(std::ostream& os, const ClampedNumeric<T>& value) {
os << static_cast<T>(value);
return os;
}
#endif
// These implement the variadic wrapper for the math operations.
template <template <typename, typename, typename> class M,
typename L,
typename R>
constexpr ClampedNumeric<typename MathWrapper<M, L, R>::type> ClampMathOp(
const L lhs,
const R rhs) {
using Math = typename MathWrapper<M, L, R>::math;
return ClampedNumeric<typename Math::result_type>::template MathOp<M>(lhs,
rhs);
}
// General purpose wrapper template for arithmetic operations.
template <template <typename, typename, typename> class M,
typename L,
typename R,
typename... Args>
constexpr ClampedNumeric<typename ResultType<M, L, R, Args...>::type>
ClampMathOp(const L lhs, const R rhs, const Args... args) {
return ClampMathOp<M>(ClampMathOp<M>(lhs, rhs), args...);
}
BASE_NUMERIC_ARITHMETIC_OPERATORS(Clamped, Clamp, Add, +, +=)
BASE_NUMERIC_ARITHMETIC_OPERATORS(Clamped, Clamp, Sub, -, -=)
BASE_NUMERIC_ARITHMETIC_OPERATORS(Clamped, Clamp, Mul, *, *=)
BASE_NUMERIC_ARITHMETIC_OPERATORS(Clamped, Clamp, Div, /, /=)
BASE_NUMERIC_ARITHMETIC_OPERATORS(Clamped, Clamp, Mod, %, %=)
BASE_NUMERIC_ARITHMETIC_OPERATORS(Clamped, Clamp, Lsh, <<, <<=)
BASE_NUMERIC_ARITHMETIC_OPERATORS(Clamped, Clamp, Rsh, >>, >>=)
BASE_NUMERIC_ARITHMETIC_OPERATORS(Clamped, Clamp, And, &, &=)
BASE_NUMERIC_ARITHMETIC_OPERATORS(Clamped, Clamp, Or, |, |=)
BASE_NUMERIC_ARITHMETIC_OPERATORS(Clamped, Clamp, Xor, ^, ^=)
BASE_NUMERIC_ARITHMETIC_VARIADIC(Clamped, Clamp, Max)
BASE_NUMERIC_ARITHMETIC_VARIADIC(Clamped, Clamp, Min)
BASE_NUMERIC_COMPARISON_OPERATORS(Clamped, IsLess, <)
BASE_NUMERIC_COMPARISON_OPERATORS(Clamped, IsLessOrEqual, <=)
BASE_NUMERIC_COMPARISON_OPERATORS(Clamped, IsGreater, >)
BASE_NUMERIC_COMPARISON_OPERATORS(Clamped, IsGreaterOrEqual, >=)
BASE_NUMERIC_COMPARISON_OPERATORS(Clamped, IsEqual, ==)
BASE_NUMERIC_COMPARISON_OPERATORS(Clamped, IsNotEqual, !=)
} // namespace internal
using internal::ClampedNumeric;
using internal::MakeClampedNum;
using internal::ClampMax;
using internal::ClampMin;
using internal::ClampAdd;
using internal::ClampSub;
using internal::ClampMul;
using internal::ClampDiv;
using internal::ClampMod;
using internal::ClampLsh;
using internal::ClampRsh;
using internal::ClampAnd;
using internal::ClampOr;
using internal::ClampXor;
} // namespace base
#endif // BASE_NUMERICS_CLAMPED_MATH_H_

View File

@@ -0,0 +1,341 @@
// Copyright 2017 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.
#ifndef BASE_NUMERICS_CLAMPED_MATH_IMPL_H_
#define BASE_NUMERICS_CLAMPED_MATH_IMPL_H_
#include <stddef.h>
#include <stdint.h>
#include <climits>
#include <cmath>
#include <cstdlib>
#include <limits>
#include <type_traits>
#include "base/numerics/checked_math.h"
#include "base/numerics/safe_conversions.h"
#include "base/numerics/safe_math_shared_impl.h"
namespace base {
namespace internal {
template <typename T,
typename std::enable_if<std::is_integral<T>::value &&
std::is_signed<T>::value>::type* = nullptr>
constexpr T SaturatedNegWrapper(T value) {
return MustTreatAsConstexpr(value) || !ClampedNegFastOp<T>::is_supported
? (NegateWrapper(value) != std::numeric_limits<T>::lowest()
? NegateWrapper(value)
: std::numeric_limits<T>::max())
: ClampedNegFastOp<T>::Do(value);
}
template <typename T,
typename std::enable_if<std::is_integral<T>::value &&
!std::is_signed<T>::value>::type* = nullptr>
constexpr T SaturatedNegWrapper(T value) {
return T(0);
}
template <
typename T,
typename std::enable_if<std::is_floating_point<T>::value>::type* = nullptr>
constexpr T SaturatedNegWrapper(T value) {
return -value;
}
template <typename T,
typename std::enable_if<std::is_integral<T>::value>::type* = nullptr>
constexpr T SaturatedAbsWrapper(T value) {
// The calculation below is a static identity for unsigned types, but for
// signed integer types it provides a non-branching, saturated absolute value.
// This works because SafeUnsignedAbs() returns an unsigned type, which can
// represent the absolute value of all negative numbers of an equal-width
// integer type. The call to IsValueNegative() then detects overflow in the
// special case of numeric_limits<T>::min(), by evaluating the bit pattern as
// a signed integer value. If it is the overflow case, we end up subtracting
// one from the unsigned result, thus saturating to numeric_limits<T>::max().
return static_cast<T>(SafeUnsignedAbs(value) -
IsValueNegative<T>(SafeUnsignedAbs(value)));
}
template <
typename T,
typename std::enable_if<std::is_floating_point<T>::value>::type* = nullptr>
constexpr T SaturatedAbsWrapper(T value) {
return value < 0 ? -value : value;
}
template <typename T, typename U, class Enable = void>
struct ClampedAddOp {};
template <typename T, typename U>
struct ClampedAddOp<T,
U,
typename std::enable_if<std::is_integral<T>::value &&
std::is_integral<U>::value>::type> {
using result_type = typename MaxExponentPromotion<T, U>::type;
template <typename V = result_type>
static constexpr V Do(T x, U y) {
if (ClampedAddFastOp<T, U>::is_supported)
return ClampedAddFastOp<T, U>::template Do<V>(x, y);
static_assert(std::is_same<V, result_type>::value ||
IsTypeInRangeForNumericType<U, V>::value,
"The saturation result cannot be determined from the "
"provided types.");
const V saturated = CommonMaxOrMin<V>(IsValueNegative(y));
V result = {};
return BASE_NUMERICS_LIKELY((CheckedAddOp<T, U>::Do(x, y, &result)))
? result
: saturated;
}
};
template <typename T, typename U, class Enable = void>
struct ClampedSubOp {};
template <typename T, typename U>
struct ClampedSubOp<T,
U,
typename std::enable_if<std::is_integral<T>::value &&
std::is_integral<U>::value>::type> {
using result_type = typename MaxExponentPromotion<T, U>::type;
template <typename V = result_type>
static constexpr V Do(T x, U y) {
// TODO(jschuh) Make this "constexpr if" once we're C++17.
if (ClampedSubFastOp<T, U>::is_supported)
return ClampedSubFastOp<T, U>::template Do<V>(x, y);
static_assert(std::is_same<V, result_type>::value ||
IsTypeInRangeForNumericType<U, V>::value,
"The saturation result cannot be determined from the "
"provided types.");
const V saturated = CommonMaxOrMin<V>(!IsValueNegative(y));
V result = {};
return BASE_NUMERICS_LIKELY((CheckedSubOp<T, U>::Do(x, y, &result)))
? result
: saturated;
}
};
template <typename T, typename U, class Enable = void>
struct ClampedMulOp {};
template <typename T, typename U>
struct ClampedMulOp<T,
U,
typename std::enable_if<std::is_integral<T>::value &&
std::is_integral<U>::value>::type> {
using result_type = typename MaxExponentPromotion<T, U>::type;
template <typename V = result_type>
static constexpr V Do(T x, U y) {
// TODO(jschuh) Make this "constexpr if" once we're C++17.
if (ClampedMulFastOp<T, U>::is_supported)
return ClampedMulFastOp<T, U>::template Do<V>(x, y);
V result = {};
const V saturated =
CommonMaxOrMin<V>(IsValueNegative(x) ^ IsValueNegative(y));
return BASE_NUMERICS_LIKELY((CheckedMulOp<T, U>::Do(x, y, &result)))
? result
: saturated;
}
};
template <typename T, typename U, class Enable = void>
struct ClampedDivOp {};
template <typename T, typename U>
struct ClampedDivOp<T,
U,
typename std::enable_if<std::is_integral<T>::value &&
std::is_integral<U>::value>::type> {
using result_type = typename MaxExponentPromotion<T, U>::type;
template <typename V = result_type>
static constexpr V Do(T x, U y) {
V result = {};
if (BASE_NUMERICS_LIKELY((CheckedDivOp<T, U>::Do(x, y, &result))))
return result;
// Saturation goes to max, min, or NaN (if x is zero).
return x ? CommonMaxOrMin<V>(IsValueNegative(x) ^ IsValueNegative(y))
: SaturationDefaultLimits<V>::NaN();
}
};
template <typename T, typename U, class Enable = void>
struct ClampedModOp {};
template <typename T, typename U>
struct ClampedModOp<T,
U,
typename std::enable_if<std::is_integral<T>::value &&
std::is_integral<U>::value>::type> {
using result_type = typename MaxExponentPromotion<T, U>::type;
template <typename V = result_type>
static constexpr V Do(T x, U y) {
V result = {};
return BASE_NUMERICS_LIKELY((CheckedModOp<T, U>::Do(x, y, &result)))
? result
: x;
}
};
template <typename T, typename U, class Enable = void>
struct ClampedLshOp {};
// Left shift. Non-zero values saturate in the direction of the sign. A zero
// shifted by any value always results in zero.
template <typename T, typename U>
struct ClampedLshOp<T,
U,
typename std::enable_if<std::is_integral<T>::value &&
std::is_integral<U>::value>::type> {
using result_type = T;
template <typename V = result_type>
static constexpr V Do(T x, U shift) {
static_assert(!std::is_signed<U>::value, "Shift value must be unsigned.");
if (BASE_NUMERICS_LIKELY(shift < std::numeric_limits<T>::digits)) {
// Shift as unsigned to avoid undefined behavior.
V result = static_cast<V>(as_unsigned(x) << shift);
// If the shift can be reversed, we know it was valid.
if (BASE_NUMERICS_LIKELY(result >> shift == x))
return result;
}
return x ? CommonMaxOrMin<V>(IsValueNegative(x)) : 0;
}
};
template <typename T, typename U, class Enable = void>
struct ClampedRshOp {};
// Right shift. Negative values saturate to -1. Positive or 0 saturates to 0.
template <typename T, typename U>
struct ClampedRshOp<T,
U,
typename std::enable_if<std::is_integral<T>::value &&
std::is_integral<U>::value>::type> {
using result_type = T;
template <typename V = result_type>
static constexpr V Do(T x, U shift) {
static_assert(!std::is_signed<U>::value, "Shift value must be unsigned.");
// Signed right shift is odd, because it saturates to -1 or 0.
const V saturated = as_unsigned(V(0)) - IsValueNegative(x);
return BASE_NUMERICS_LIKELY(shift < IntegerBitsPlusSign<T>::value)
? saturated_cast<V>(x >> shift)
: saturated;
}
};
template <typename T, typename U, class Enable = void>
struct ClampedAndOp {};
template <typename T, typename U>
struct ClampedAndOp<T,
U,
typename std::enable_if<std::is_integral<T>::value &&
std::is_integral<U>::value>::type> {
using result_type = typename std::make_unsigned<
typename MaxExponentPromotion<T, U>::type>::type;
template <typename V>
static constexpr V Do(T x, U y) {
return static_cast<result_type>(x) & static_cast<result_type>(y);
}
};
template <typename T, typename U, class Enable = void>
struct ClampedOrOp {};
// For simplicity we promote to unsigned integers.
template <typename T, typename U>
struct ClampedOrOp<T,
U,
typename std::enable_if<std::is_integral<T>::value &&
std::is_integral<U>::value>::type> {
using result_type = typename std::make_unsigned<
typename MaxExponentPromotion<T, U>::type>::type;
template <typename V>
static constexpr V Do(T x, U y) {
return static_cast<result_type>(x) | static_cast<result_type>(y);
}
};
template <typename T, typename U, class Enable = void>
struct ClampedXorOp {};
// For simplicity we support only unsigned integers.
template <typename T, typename U>
struct ClampedXorOp<T,
U,
typename std::enable_if<std::is_integral<T>::value &&
std::is_integral<U>::value>::type> {
using result_type = typename std::make_unsigned<
typename MaxExponentPromotion<T, U>::type>::type;
template <typename V>
static constexpr V Do(T x, U y) {
return static_cast<result_type>(x) ^ static_cast<result_type>(y);
}
};
template <typename T, typename U, class Enable = void>
struct ClampedMaxOp {};
template <typename T, typename U>
struct ClampedMaxOp<
T,
U,
typename std::enable_if<std::is_arithmetic<T>::value &&
std::is_arithmetic<U>::value>::type> {
using result_type = typename MaxExponentPromotion<T, U>::type;
template <typename V = result_type>
static constexpr V Do(T x, U y) {
return IsGreater<T, U>::Test(x, y) ? saturated_cast<V>(x)
: saturated_cast<V>(y);
}
};
template <typename T, typename U, class Enable = void>
struct ClampedMinOp {};
template <typename T, typename U>
struct ClampedMinOp<
T,
U,
typename std::enable_if<std::is_arithmetic<T>::value &&
std::is_arithmetic<U>::value>::type> {
using result_type = typename LowestValuePromotion<T, U>::type;
template <typename V = result_type>
static constexpr V Do(T x, U y) {
return IsLess<T, U>::Test(x, y) ? saturated_cast<V>(x)
: saturated_cast<V>(y);
}
};
// This is just boilerplate that wraps the standard floating point arithmetic.
// A macro isn't the nicest solution, but it beats rewriting these repeatedly.
#define BASE_FLOAT_ARITHMETIC_OPS(NAME, OP) \
template <typename T, typename U> \
struct Clamped##NAME##Op< \
T, U, \
typename std::enable_if<std::is_floating_point<T>::value || \
std::is_floating_point<U>::value>::type> { \
using result_type = typename MaxExponentPromotion<T, U>::type; \
template <typename V = result_type> \
static constexpr V Do(T x, U y) { \
return saturated_cast<V>(x OP y); \
} \
};
BASE_FLOAT_ARITHMETIC_OPS(Add, +)
BASE_FLOAT_ARITHMETIC_OPS(Sub, -)
BASE_FLOAT_ARITHMETIC_OPS(Mul, *)
BASE_FLOAT_ARITHMETIC_OPS(Div, /)
#undef BASE_FLOAT_ARITHMETIC_OPS
} // namespace internal
} // namespace base
#endif // BASE_NUMERICS_CLAMPED_MATH_IMPL_H_

View File

@@ -0,0 +1,19 @@
// Copyright 2017 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.
#ifndef BASE_NUMERICS_MATH_CONSTANTS_H_
#define BASE_NUMERICS_MATH_CONSTANTS_H_
namespace base {
constexpr double kPiDouble = 3.14159265358979323846;
constexpr float kPiFloat = 3.14159265358979323846f;
// The mean acceleration due to gravity on Earth in m/s^2.
constexpr double kMeanGravityDouble = 9.80665;
constexpr float kMeanGravityFloat = 9.80665f;
} // namespace base
#endif // BASE_NUMERICS_MATH_CONSTANTS_H_

View File

@@ -0,0 +1,27 @@
// Copyright 2017 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.
#ifndef BASE_NUMERICS_RANGES_H_
#define BASE_NUMERICS_RANGES_H_
#include <algorithm>
#include <cmath>
namespace base {
// To be replaced with std::clamp() from C++17, someday.
template <class T>
constexpr const T& ClampToRange(const T& value, const T& min, const T& max) {
return std::min(std::max(value, min), max);
}
template <typename T>
constexpr bool IsApproximatelyEqual(T lhs, T rhs, T tolerance) {
static_assert(std::is_arithmetic<T>::value, "Argument must be arithmetic");
return std::abs(rhs - lhs) <= tolerance;
}
} // namespace base
#endif // BASE_NUMERICS_RANGES_H_

View File

@@ -0,0 +1,387 @@
// Copyright 2014 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.
#ifndef BASE_NUMERICS_SAFE_CONVERSIONS_H_
#define BASE_NUMERICS_SAFE_CONVERSIONS_H_
#include <stddef.h>
#include <cmath>
#include <limits>
#include <type_traits>
#include "base/numerics/safe_conversions_impl.h"
#if !defined(__native_client__) && (defined(__ARMEL__) || defined(__arch64__))
#include "base/numerics/safe_conversions_arm_impl.h"
#define BASE_HAS_OPTIMIZED_SAFE_CONVERSIONS (1)
#else
#define BASE_HAS_OPTIMIZED_SAFE_CONVERSIONS (0)
#endif
#if !BASE_NUMERICS_DISABLE_OSTREAM_OPERATORS
#include <ostream>
#endif
namespace base {
namespace internal {
#if !BASE_HAS_OPTIMIZED_SAFE_CONVERSIONS
template <typename Dst, typename Src>
struct SaturateFastAsmOp {
static constexpr bool is_supported = false;
static constexpr Dst Do(Src) {
// Force a compile failure if instantiated.
return CheckOnFailure::template HandleFailure<Dst>();
}
};
#endif // BASE_HAS_OPTIMIZED_SAFE_CONVERSIONS
#undef BASE_HAS_OPTIMIZED_SAFE_CONVERSIONS
// The following special case a few specific integer conversions where we can
// eke out better performance than range checking.
template <typename Dst, typename Src, typename Enable = void>
struct IsValueInRangeFastOp {
static constexpr bool is_supported = false;
static constexpr bool Do(Src value) {
// Force a compile failure if instantiated.
return CheckOnFailure::template HandleFailure<bool>();
}
};
// Signed to signed range comparison.
template <typename Dst, typename Src>
struct IsValueInRangeFastOp<
Dst,
Src,
typename std::enable_if<
std::is_integral<Dst>::value && std::is_integral<Src>::value &&
std::is_signed<Dst>::value && std::is_signed<Src>::value &&
!IsTypeInRangeForNumericType<Dst, Src>::value>::type> {
static constexpr bool is_supported = true;
static constexpr bool Do(Src value) {
// Just downcast to the smaller type, sign extend it back to the original
// type, and then see if it matches the original value.
return value == static_cast<Dst>(value);
}
};
// Signed to unsigned range comparison.
template <typename Dst, typename Src>
struct IsValueInRangeFastOp<
Dst,
Src,
typename std::enable_if<
std::is_integral<Dst>::value && std::is_integral<Src>::value &&
!std::is_signed<Dst>::value && std::is_signed<Src>::value &&
!IsTypeInRangeForNumericType<Dst, Src>::value>::type> {
static constexpr bool is_supported = true;
static constexpr bool Do(Src value) {
// We cast a signed as unsigned to overflow negative values to the top,
// then compare against whichever maximum is smaller, as our upper bound.
return as_unsigned(value) <= as_unsigned(CommonMax<Src, Dst>());
}
};
// Convenience function that returns true if the supplied value is in range
// for the destination type.
template <typename Dst, typename Src>
constexpr bool IsValueInRangeForNumericType(Src value) {
using SrcType = typename internal::UnderlyingType<Src>::type;
return internal::IsValueInRangeFastOp<Dst, SrcType>::is_supported
? internal::IsValueInRangeFastOp<Dst, SrcType>::Do(
static_cast<SrcType>(value))
: internal::DstRangeRelationToSrcRange<Dst>(
static_cast<SrcType>(value))
.IsValid();
}
// checked_cast<> is analogous to static_cast<> for numeric types,
// except that it CHECKs that the specified numeric conversion will not
// overflow or underflow. NaN source will always trigger a CHECK.
template <typename Dst,
class CheckHandler = internal::CheckOnFailure,
typename Src>
constexpr Dst checked_cast(Src value) {
// This throws a compile-time error on evaluating the constexpr if it can be
// determined at compile-time as failing, otherwise it will CHECK at runtime.
using SrcType = typename internal::UnderlyingType<Src>::type;
return BASE_NUMERICS_LIKELY((IsValueInRangeForNumericType<Dst>(value)))
? static_cast<Dst>(static_cast<SrcType>(value))
: CheckHandler::template HandleFailure<Dst>();
}
// Default boundaries for integral/float: max/infinity, lowest/-infinity, 0/NaN.
// You may provide your own limits (e.g. to saturated_cast) so long as you
// implement all of the static constexpr member functions in the class below.
template <typename T>
struct SaturationDefaultLimits : public std::numeric_limits<T> {
static constexpr T NaN() {
return std::numeric_limits<T>::has_quiet_NaN
? std::numeric_limits<T>::quiet_NaN()
: T();
}
using std::numeric_limits<T>::max;
static constexpr T Overflow() {
return std::numeric_limits<T>::has_infinity
? std::numeric_limits<T>::infinity()
: std::numeric_limits<T>::max();
}
using std::numeric_limits<T>::lowest;
static constexpr T Underflow() {
return std::numeric_limits<T>::has_infinity
? std::numeric_limits<T>::infinity() * -1
: std::numeric_limits<T>::lowest();
}
};
template <typename Dst, template <typename> class S, typename Src>
constexpr Dst saturated_cast_impl(Src value, RangeCheck constraint) {
// For some reason clang generates much better code when the branch is
// structured exactly this way, rather than a sequence of checks.
return !constraint.IsOverflowFlagSet()
? (!constraint.IsUnderflowFlagSet() ? static_cast<Dst>(value)
: S<Dst>::Underflow())
// Skip this check for integral Src, which cannot be NaN.
: (std::is_integral<Src>::value || !constraint.IsUnderflowFlagSet()
? S<Dst>::Overflow()
: S<Dst>::NaN());
}
// We can reduce the number of conditions and get slightly better performance
// for normal signed and unsigned integer ranges. And in the specific case of
// Arm, we can use the optimized saturation instructions.
template <typename Dst, typename Src, typename Enable = void>
struct SaturateFastOp {
static constexpr bool is_supported = false;
static constexpr Dst Do(Src value) {
// Force a compile failure if instantiated.
return CheckOnFailure::template HandleFailure<Dst>();
}
};
template <typename Dst, typename Src>
struct SaturateFastOp<
Dst,
Src,
typename std::enable_if<std::is_integral<Src>::value &&
std::is_integral<Dst>::value &&
SaturateFastAsmOp<Dst, Src>::is_supported>::type> {
static constexpr bool is_supported = true;
static constexpr Dst Do(Src value) { return SaturateFastAsmOp<Dst, Src>::Do(value); }
};
template <typename Dst, typename Src>
struct SaturateFastOp<
Dst,
Src,
typename std::enable_if<std::is_integral<Src>::value &&
std::is_integral<Dst>::value &&
!SaturateFastAsmOp<Dst, Src>::is_supported>::type> {
static constexpr bool is_supported = true;
static constexpr Dst Do(Src value) {
// The exact order of the following is structured to hit the correct
// optimization heuristics across compilers. Do not change without
// checking the emitted code.
const Dst saturated = CommonMaxOrMin<Dst, Src>(
IsMaxInRangeForNumericType<Dst, Src>() ||
(!IsMinInRangeForNumericType<Dst, Src>() && IsValueNegative(value)));
return BASE_NUMERICS_LIKELY(IsValueInRangeForNumericType<Dst>(value))
? static_cast<Dst>(value)
: saturated;
}
};
// saturated_cast<> is analogous to static_cast<> for numeric types, except
// that the specified numeric conversion will saturate by default rather than
// overflow or underflow, and NaN assignment to an integral will return 0.
// All boundary condition behaviors can be overriden with a custom handler.
template <typename Dst,
template <typename> class SaturationHandler = SaturationDefaultLimits,
typename Src>
constexpr Dst saturated_cast(Src value) {
using SrcType = typename UnderlyingType<Src>::type;
return !IsCompileTimeConstant(value) &&
SaturateFastOp<Dst, SrcType>::is_supported &&
std::is_same<SaturationHandler<Dst>,
SaturationDefaultLimits<Dst>>::value
? SaturateFastOp<Dst, SrcType>::Do(static_cast<SrcType>(value))
: saturated_cast_impl<Dst, SaturationHandler, SrcType>(
static_cast<SrcType>(value),
DstRangeRelationToSrcRange<Dst, SaturationHandler, SrcType>(
static_cast<SrcType>(value)));
}
// strict_cast<> is analogous to static_cast<> for numeric types, except that
// it will cause a compile failure if the destination type is not large enough
// to contain any value in the source type. It performs no runtime checking.
template <typename Dst, typename Src>
constexpr Dst strict_cast(Src value) {
using SrcType = typename UnderlyingType<Src>::type;
static_assert(UnderlyingType<Src>::is_numeric, "Argument must be numeric.");
static_assert(std::is_arithmetic<Dst>::value, "Result must be numeric.");
// If you got here from a compiler error, it's because you tried to assign
// from a source type to a destination type that has insufficient range.
// The solution may be to change the destination type you're assigning to,
// and use one large enough to represent the source.
// Alternatively, you may be better served with the checked_cast<> or
// saturated_cast<> template functions for your particular use case.
static_assert(StaticDstRangeRelationToSrcRange<Dst, SrcType>::value ==
NUMERIC_RANGE_CONTAINED,
"The source type is out of range for the destination type. "
"Please see strict_cast<> comments for more information.");
return static_cast<Dst>(static_cast<SrcType>(value));
}
// Some wrappers to statically check that a type is in range.
template <typename Dst, typename Src, class Enable = void>
struct IsNumericRangeContained {
static constexpr bool value = false;
};
template <typename Dst, typename Src>
struct IsNumericRangeContained<
Dst,
Src,
typename std::enable_if<ArithmeticOrUnderlyingEnum<Dst>::value &&
ArithmeticOrUnderlyingEnum<Src>::value>::type> {
static constexpr bool value =
StaticDstRangeRelationToSrcRange<Dst, Src>::value ==
NUMERIC_RANGE_CONTAINED;
};
// StrictNumeric implements compile time range checking between numeric types by
// wrapping assignment operations in a strict_cast. This class is intended to be
// used for function arguments and return types, to ensure the destination type
// can always contain the source type. This is essentially the same as enforcing
// -Wconversion in gcc and C4302 warnings on MSVC, but it can be applied
// incrementally at API boundaries, making it easier to convert code so that it
// compiles cleanly with truncation warnings enabled.
// This template should introduce no runtime overhead, but it also provides no
// runtime checking of any of the associated mathematical operations. Use
// CheckedNumeric for runtime range checks of the actual value being assigned.
template <typename T>
class StrictNumeric {
public:
using type = T;
constexpr StrictNumeric() : value_(0) {}
// Copy constructor.
template <typename Src>
constexpr StrictNumeric(const StrictNumeric<Src>& rhs)
: value_(strict_cast<T>(rhs.value_)) {}
// This is not an explicit constructor because we implicitly upgrade regular
// numerics to StrictNumerics to make them easier to use.
template <typename Src>
constexpr StrictNumeric(Src value) // NOLINT(runtime/explicit)
: value_(strict_cast<T>(value)) {}
// If you got here from a compiler error, it's because you tried to assign
// from a source type to a destination type that has insufficient range.
// The solution may be to change the destination type you're assigning to,
// and use one large enough to represent the source.
// If you're assigning from a CheckedNumeric<> class, you may be able to use
// the AssignIfValid() member function, specify a narrower destination type to
// the member value functions (e.g. val.template ValueOrDie<Dst>()), use one
// of the value helper functions (e.g. ValueOrDieForType<Dst>(val)).
// If you've encountered an _ambiguous overload_ you can use a static_cast<>
// to explicitly cast the result to the destination type.
// If none of that works, you may be better served with the checked_cast<> or
// saturated_cast<> template functions for your particular use case.
template <typename Dst,
typename std::enable_if<
IsNumericRangeContained<Dst, T>::value>::type* = nullptr>
constexpr operator Dst() const {
return static_cast<typename ArithmeticOrUnderlyingEnum<Dst>::type>(value_);
}
private:
const T value_;
};
// Convience wrapper returns a StrictNumeric from the provided arithmetic type.
template <typename T>
constexpr StrictNumeric<typename UnderlyingType<T>::type> MakeStrictNum(
const T value) {
return value;
}
#if !BASE_NUMERICS_DISABLE_OSTREAM_OPERATORS
// Overload the ostream output operator to make logging work nicely.
template <typename T>
std::ostream& operator<<(std::ostream& os, const StrictNumeric<T>& value) {
os << static_cast<T>(value);
return os;
}
#endif
#define BASE_NUMERIC_COMPARISON_OPERATORS(CLASS, NAME, OP) \
template <typename L, typename R, \
typename std::enable_if< \
internal::Is##CLASS##Op<L, R>::value>::type* = nullptr> \
constexpr bool operator OP(const L lhs, const R rhs) { \
return SafeCompare<NAME, typename UnderlyingType<L>::type, \
typename UnderlyingType<R>::type>(lhs, rhs); \
}
BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsLess, <)
BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsLessOrEqual, <=)
BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsGreater, >)
BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsGreaterOrEqual, >=)
BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsEqual, ==)
BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsNotEqual, !=)
} // namespace internal
using internal::as_signed;
using internal::as_unsigned;
using internal::checked_cast;
using internal::strict_cast;
using internal::saturated_cast;
using internal::SafeUnsignedAbs;
using internal::StrictNumeric;
using internal::MakeStrictNum;
using internal::IsValueInRangeForNumericType;
using internal::IsTypeInRangeForNumericType;
using internal::IsValueNegative;
// Explicitly make a shorter size_t alias for convenience.
using SizeT = StrictNumeric<size_t>;
// floating -> integral conversions that saturate and thus can actually return
// an integral type. In most cases, these should be preferred over the std::
// versions.
template <typename Dst = int,
typename Src,
typename = std::enable_if_t<std::is_integral<Dst>::value &&
std::is_floating_point<Src>::value>>
Dst ClampFloor(Src value) {
return saturated_cast<Dst>(std::floor(value));
}
template <typename Dst = int,
typename Src,
typename = std::enable_if_t<std::is_integral<Dst>::value &&
std::is_floating_point<Src>::value>>
Dst ClampCeil(Src value) {
return saturated_cast<Dst>(std::ceil(value));
}
template <typename Dst = int,
typename Src,
typename = std::enable_if_t<std::is_integral<Dst>::value &&
std::is_floating_point<Src>::value>>
Dst ClampRound(Src value) {
const Src rounded =
(value >= 0.0f) ? std::floor(value + 0.5f) : std::ceil(value - 0.5f);
return saturated_cast<Dst>(rounded);
}
} // namespace base
#endif // BASE_NUMERICS_SAFE_CONVERSIONS_H_

View File

@@ -0,0 +1,51 @@
// Copyright 2017 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.
#ifndef BASE_NUMERICS_SAFE_CONVERSIONS_ARM_IMPL_H_
#define BASE_NUMERICS_SAFE_CONVERSIONS_ARM_IMPL_H_
#include <cassert>
#include <limits>
#include <type_traits>
#include "base/numerics/safe_conversions_impl.h"
namespace base {
namespace internal {
// Fast saturation to a destination type.
template <typename Dst, typename Src>
struct SaturateFastAsmOp {
static constexpr bool is_supported =
std::is_signed<Src>::value && std::is_integral<Dst>::value &&
std::is_integral<Src>::value &&
IntegerBitsPlusSign<Src>::value <= IntegerBitsPlusSign<int32_t>::value &&
IntegerBitsPlusSign<Dst>::value <= IntegerBitsPlusSign<int32_t>::value &&
!IsTypeInRangeForNumericType<Dst, Src>::value;
__attribute__((always_inline)) static Dst Do(Src value) {
int32_t src = value;
typename std::conditional<std::is_signed<Dst>::value, int32_t,
uint32_t>::type result;
if (std::is_signed<Dst>::value) {
asm("ssat %[dst], %[shift], %[src]"
: [dst] "=r"(result)
: [src] "r"(src), [shift] "n"(IntegerBitsPlusSign<Dst>::value <= 32
? IntegerBitsPlusSign<Dst>::value
: 32));
} else {
asm("usat %[dst], %[shift], %[src]"
: [dst] "=r"(result)
: [src] "r"(src), [shift] "n"(IntegerBitsPlusSign<Dst>::value < 32
? IntegerBitsPlusSign<Dst>::value
: 31));
}
return static_cast<Dst>(result);
}
};
} // namespace internal
} // namespace base
#endif // BASE_NUMERICS_SAFE_CONVERSIONS_ARM_IMPL_H_

View File

@@ -0,0 +1,851 @@
// Copyright 2014 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.
#ifndef BASE_NUMERICS_SAFE_CONVERSIONS_IMPL_H_
#define BASE_NUMERICS_SAFE_CONVERSIONS_IMPL_H_
#include <stdint.h>
#include <limits>
#include <type_traits>
#if defined(__GNUC__) || defined(__clang__)
#define BASE_NUMERICS_LIKELY(x) __builtin_expect(!!(x), 1)
#define BASE_NUMERICS_UNLIKELY(x) __builtin_expect(!!(x), 0)
#else
#define BASE_NUMERICS_LIKELY(x) (x)
#define BASE_NUMERICS_UNLIKELY(x) (x)
#endif
namespace base {
namespace internal {
// The std library doesn't provide a binary max_exponent for integers, however
// we can compute an analog using std::numeric_limits<>::digits.
template <typename NumericType>
struct MaxExponent {
static const int value = std::is_floating_point<NumericType>::value
? std::numeric_limits<NumericType>::max_exponent
: std::numeric_limits<NumericType>::digits + 1;
};
// The number of bits (including the sign) in an integer. Eliminates sizeof
// hacks.
template <typename NumericType>
struct IntegerBitsPlusSign {
static const int value = std::numeric_limits<NumericType>::digits +
std::is_signed<NumericType>::value;
};
// Helper templates for integer manipulations.
template <typename Integer>
struct PositionOfSignBit {
static const size_t value = IntegerBitsPlusSign<Integer>::value - 1;
};
// Determines if a numeric value is negative without throwing compiler
// warnings on: unsigned(value) < 0.
template <typename T,
typename std::enable_if<std::is_signed<T>::value>::type* = nullptr>
constexpr bool IsValueNegative(T value) {
static_assert(std::is_arithmetic<T>::value, "Argument must be numeric.");
return value < 0;
}
template <typename T,
typename std::enable_if<!std::is_signed<T>::value>::type* = nullptr>
constexpr bool IsValueNegative(T) {
static_assert(std::is_arithmetic<T>::value, "Argument must be numeric.");
return false;
}
// This performs a fast negation, returning a signed value. It works on unsigned
// arguments, but probably doesn't do what you want for any unsigned value
// larger than max / 2 + 1 (i.e. signed min cast to unsigned).
template <typename T>
constexpr typename std::make_signed<T>::type ConditionalNegate(
T x,
bool is_negative) {
static_assert(std::is_integral<T>::value, "Type must be integral");
using SignedT = typename std::make_signed<T>::type;
using UnsignedT = typename std::make_unsigned<T>::type;
return static_cast<SignedT>(
(static_cast<UnsignedT>(x) ^ -SignedT(is_negative)) + is_negative);
}
// This performs a safe, absolute value via unsigned overflow.
template <typename T>
constexpr typename std::make_unsigned<T>::type SafeUnsignedAbs(T value) {
static_assert(std::is_integral<T>::value, "Type must be integral");
using UnsignedT = typename std::make_unsigned<T>::type;
return IsValueNegative(value)
? static_cast<UnsignedT>(0u - static_cast<UnsignedT>(value))
: static_cast<UnsignedT>(value);
}
// This allows us to switch paths on known compile-time constants.
#if defined(__clang__) || defined(__GNUC__)
constexpr bool CanDetectCompileTimeConstant() {
return true;
}
template <typename T>
constexpr bool IsCompileTimeConstant(const T v) {
return __builtin_constant_p(v);
}
#else
constexpr bool CanDetectCompileTimeConstant() {
return false;
}
template <typename T>
constexpr bool IsCompileTimeConstant(const T) {
return false;
}
#endif
template <typename T>
constexpr bool MustTreatAsConstexpr(const T v) {
// Either we can't detect a compile-time constant, and must always use the
// constexpr path, or we know we have a compile-time constant.
return !CanDetectCompileTimeConstant() || IsCompileTimeConstant(v);
}
// Forces a crash, like a CHECK(false). Used for numeric boundary errors.
// Also used in a constexpr template to trigger a compilation failure on
// an error condition.
struct CheckOnFailure {
template <typename T>
static T HandleFailure() {
#if defined(_MSC_VER)
__debugbreak();
#elif defined(__GNUC__) || defined(__clang__)
__builtin_trap();
#else
((void)(*(volatile char*)0 = 0));
#endif
return T();
}
};
enum IntegerRepresentation {
INTEGER_REPRESENTATION_UNSIGNED,
INTEGER_REPRESENTATION_SIGNED
};
// A range for a given nunmeric Src type is contained for a given numeric Dst
// type if both numeric_limits<Src>::max() <= numeric_limits<Dst>::max() and
// numeric_limits<Src>::lowest() >= numeric_limits<Dst>::lowest() are true.
// We implement this as template specializations rather than simple static
// comparisons to ensure type correctness in our comparisons.
enum NumericRangeRepresentation {
NUMERIC_RANGE_NOT_CONTAINED,
NUMERIC_RANGE_CONTAINED
};
// Helper templates to statically determine if our destination type can contain
// maximum and minimum values represented by the source type.
template <typename Dst,
typename Src,
IntegerRepresentation DstSign = std::is_signed<Dst>::value
? INTEGER_REPRESENTATION_SIGNED
: INTEGER_REPRESENTATION_UNSIGNED,
IntegerRepresentation SrcSign = std::is_signed<Src>::value
? INTEGER_REPRESENTATION_SIGNED
: INTEGER_REPRESENTATION_UNSIGNED>
struct StaticDstRangeRelationToSrcRange;
// Same sign: Dst is guaranteed to contain Src only if its range is equal or
// larger.
template <typename Dst, typename Src, IntegerRepresentation Sign>
struct StaticDstRangeRelationToSrcRange<Dst, Src, Sign, Sign> {
static const NumericRangeRepresentation value =
MaxExponent<Dst>::value >= MaxExponent<Src>::value
? NUMERIC_RANGE_CONTAINED
: NUMERIC_RANGE_NOT_CONTAINED;
};
// Unsigned to signed: Dst is guaranteed to contain source only if its range is
// larger.
template <typename Dst, typename Src>
struct StaticDstRangeRelationToSrcRange<Dst,
Src,
INTEGER_REPRESENTATION_SIGNED,
INTEGER_REPRESENTATION_UNSIGNED> {
static const NumericRangeRepresentation value =
MaxExponent<Dst>::value > MaxExponent<Src>::value
? NUMERIC_RANGE_CONTAINED
: NUMERIC_RANGE_NOT_CONTAINED;
};
// Signed to unsigned: Dst cannot be statically determined to contain Src.
template <typename Dst, typename Src>
struct StaticDstRangeRelationToSrcRange<Dst,
Src,
INTEGER_REPRESENTATION_UNSIGNED,
INTEGER_REPRESENTATION_SIGNED> {
static const NumericRangeRepresentation value = NUMERIC_RANGE_NOT_CONTAINED;
};
// This class wraps the range constraints as separate booleans so the compiler
// can identify constants and eliminate unused code paths.
class RangeCheck {
public:
constexpr RangeCheck(bool is_in_lower_bound, bool is_in_upper_bound)
: is_underflow_(!is_in_lower_bound), is_overflow_(!is_in_upper_bound) {}
constexpr RangeCheck() : is_underflow_(0), is_overflow_(0) {}
constexpr bool IsValid() const { return !is_overflow_ && !is_underflow_; }
constexpr bool IsInvalid() const { return is_overflow_ && is_underflow_; }
constexpr bool IsOverflow() const { return is_overflow_ && !is_underflow_; }
constexpr bool IsUnderflow() const { return !is_overflow_ && is_underflow_; }
constexpr bool IsOverflowFlagSet() const { return is_overflow_; }
constexpr bool IsUnderflowFlagSet() const { return is_underflow_; }
constexpr bool operator==(const RangeCheck rhs) const {
return is_underflow_ == rhs.is_underflow_ &&
is_overflow_ == rhs.is_overflow_;
}
constexpr bool operator!=(const RangeCheck rhs) const {
return !(*this == rhs);
}
private:
// Do not change the order of these member variables. The integral conversion
// optimization depends on this exact order.
const bool is_underflow_;
const bool is_overflow_;
};
// The following helper template addresses a corner case in range checks for
// conversion from a floating-point type to an integral type of smaller range
// but larger precision (e.g. float -> unsigned). The problem is as follows:
// 1. Integral maximum is always one less than a power of two, so it must be
// truncated to fit the mantissa of the floating point. The direction of
// rounding is implementation defined, but by default it's always IEEE
// floats, which round to nearest and thus result in a value of larger
// magnitude than the integral value.
// Example: float f = UINT_MAX; // f is 4294967296f but UINT_MAX
// // is 4294967295u.
// 2. If the floating point value is equal to the promoted integral maximum
// value, a range check will erroneously pass.
// Example: (4294967296f <= 4294967295u) // This is true due to a precision
// // loss in rounding up to float.
// 3. When the floating point value is then converted to an integral, the
// resulting value is out of range for the target integral type and
// thus is implementation defined.
// Example: unsigned u = (float)INT_MAX; // u will typically overflow to 0.
// To fix this bug we manually truncate the maximum value when the destination
// type is an integral of larger precision than the source floating-point type,
// such that the resulting maximum is represented exactly as a floating point.
template <typename Dst, typename Src, template <typename> class Bounds>
struct NarrowingRange {
using SrcLimits = std::numeric_limits<Src>;
using DstLimits = typename std::numeric_limits<Dst>;
// Computes the mask required to make an accurate comparison between types.
static const int kShift =
(MaxExponent<Src>::value > MaxExponent<Dst>::value &&
SrcLimits::digits < DstLimits::digits)
? (DstLimits::digits - SrcLimits::digits)
: 0;
template <
typename T,
typename std::enable_if<std::is_integral<T>::value>::type* = nullptr>
// Masks out the integer bits that are beyond the precision of the
// intermediate type used for comparison.
static constexpr T Adjust(T value) {
static_assert(std::is_same<T, Dst>::value, "");
static_assert(kShift < DstLimits::digits, "");
return static_cast<T>(
ConditionalNegate(SafeUnsignedAbs(value) & ~((T(1) << kShift) - T(1)),
IsValueNegative(value)));
}
template <typename T,
typename std::enable_if<std::is_floating_point<T>::value>::type* =
nullptr>
static constexpr T Adjust(T value) {
static_assert(std::is_same<T, Dst>::value, "");
static_assert(kShift == 0, "");
return value;
}
static constexpr Dst max() { return Adjust(Bounds<Dst>::max()); }
static constexpr Dst lowest() { return Adjust(Bounds<Dst>::lowest()); }
};
template <typename Dst,
typename Src,
template <typename> class Bounds,
IntegerRepresentation DstSign = std::is_signed<Dst>::value
? INTEGER_REPRESENTATION_SIGNED
: INTEGER_REPRESENTATION_UNSIGNED,
IntegerRepresentation SrcSign = std::is_signed<Src>::value
? INTEGER_REPRESENTATION_SIGNED
: INTEGER_REPRESENTATION_UNSIGNED,
NumericRangeRepresentation DstRange =
StaticDstRangeRelationToSrcRange<Dst, Src>::value>
struct DstRangeRelationToSrcRangeImpl;
// The following templates are for ranges that must be verified at runtime. We
// split it into checks based on signedness to avoid confusing casts and
// compiler warnings on signed an unsigned comparisons.
// Same sign narrowing: The range is contained for normal limits.
template <typename Dst,
typename Src,
template <typename> class Bounds,
IntegerRepresentation DstSign,
IntegerRepresentation SrcSign>
struct DstRangeRelationToSrcRangeImpl<Dst,
Src,
Bounds,
DstSign,
SrcSign,
NUMERIC_RANGE_CONTAINED> {
static constexpr RangeCheck Check(Src value) {
using SrcLimits = std::numeric_limits<Src>;
using DstLimits = NarrowingRange<Dst, Src, Bounds>;
return RangeCheck(
static_cast<Dst>(SrcLimits::lowest()) >= DstLimits::lowest() ||
static_cast<Dst>(value) >= DstLimits::lowest(),
static_cast<Dst>(SrcLimits::max()) <= DstLimits::max() ||
static_cast<Dst>(value) <= DstLimits::max());
}
};
// Signed to signed narrowing: Both the upper and lower boundaries may be
// exceeded for standard limits.
template <typename Dst, typename Src, template <typename> class Bounds>
struct DstRangeRelationToSrcRangeImpl<Dst,
Src,
Bounds,
INTEGER_REPRESENTATION_SIGNED,
INTEGER_REPRESENTATION_SIGNED,
NUMERIC_RANGE_NOT_CONTAINED> {
static constexpr RangeCheck Check(Src value) {
using DstLimits = NarrowingRange<Dst, Src, Bounds>;
return RangeCheck(value >= DstLimits::lowest(), value <= DstLimits::max());
}
};
// Unsigned to unsigned narrowing: Only the upper bound can be exceeded for
// standard limits.
template <typename Dst, typename Src, template <typename> class Bounds>
struct DstRangeRelationToSrcRangeImpl<Dst,
Src,
Bounds,
INTEGER_REPRESENTATION_UNSIGNED,
INTEGER_REPRESENTATION_UNSIGNED,
NUMERIC_RANGE_NOT_CONTAINED> {
static constexpr RangeCheck Check(Src value) {
using DstLimits = NarrowingRange<Dst, Src, Bounds>;
return RangeCheck(
DstLimits::lowest() == Dst(0) || value >= DstLimits::lowest(),
value <= DstLimits::max());
}
};
// Unsigned to signed: Only the upper bound can be exceeded for standard limits.
template <typename Dst, typename Src, template <typename> class Bounds>
struct DstRangeRelationToSrcRangeImpl<Dst,
Src,
Bounds,
INTEGER_REPRESENTATION_SIGNED,
INTEGER_REPRESENTATION_UNSIGNED,
NUMERIC_RANGE_NOT_CONTAINED> {
static constexpr RangeCheck Check(Src value) {
using DstLimits = NarrowingRange<Dst, Src, Bounds>;
using Promotion = decltype(Src() + Dst());
return RangeCheck(DstLimits::lowest() <= Dst(0) ||
static_cast<Promotion>(value) >=
static_cast<Promotion>(DstLimits::lowest()),
static_cast<Promotion>(value) <=
static_cast<Promotion>(DstLimits::max()));
}
};
// Signed to unsigned: The upper boundary may be exceeded for a narrower Dst,
// and any negative value exceeds the lower boundary for standard limits.
template <typename Dst, typename Src, template <typename> class Bounds>
struct DstRangeRelationToSrcRangeImpl<Dst,
Src,
Bounds,
INTEGER_REPRESENTATION_UNSIGNED,
INTEGER_REPRESENTATION_SIGNED,
NUMERIC_RANGE_NOT_CONTAINED> {
static constexpr RangeCheck Check(Src value) {
using SrcLimits = std::numeric_limits<Src>;
using DstLimits = NarrowingRange<Dst, Src, Bounds>;
using Promotion = decltype(Src() + Dst());
return RangeCheck(
value >= Src(0) && (DstLimits::lowest() == 0 ||
static_cast<Dst>(value) >= DstLimits::lowest()),
static_cast<Promotion>(SrcLimits::max()) <=
static_cast<Promotion>(DstLimits::max()) ||
static_cast<Promotion>(value) <=
static_cast<Promotion>(DstLimits::max()));
}
};
// Simple wrapper for statically checking if a type's range is contained.
template <typename Dst, typename Src>
struct IsTypeInRangeForNumericType {
static const bool value = StaticDstRangeRelationToSrcRange<Dst, Src>::value ==
NUMERIC_RANGE_CONTAINED;
};
template <typename Dst,
template <typename> class Bounds = std::numeric_limits,
typename Src>
constexpr RangeCheck DstRangeRelationToSrcRange(Src value) {
static_assert(std::is_arithmetic<Src>::value, "Argument must be numeric.");
static_assert(std::is_arithmetic<Dst>::value, "Result must be numeric.");
static_assert(Bounds<Dst>::lowest() < Bounds<Dst>::max(), "");
return DstRangeRelationToSrcRangeImpl<Dst, Src, Bounds>::Check(value);
}
// Integer promotion templates used by the portable checked integer arithmetic.
template <size_t Size, bool IsSigned>
struct IntegerForDigitsAndSign;
#define INTEGER_FOR_DIGITS_AND_SIGN(I) \
template <> \
struct IntegerForDigitsAndSign<IntegerBitsPlusSign<I>::value, \
std::is_signed<I>::value> { \
using type = I; \
}
INTEGER_FOR_DIGITS_AND_SIGN(int8_t);
INTEGER_FOR_DIGITS_AND_SIGN(uint8_t);
INTEGER_FOR_DIGITS_AND_SIGN(int16_t);
INTEGER_FOR_DIGITS_AND_SIGN(uint16_t);
INTEGER_FOR_DIGITS_AND_SIGN(int32_t);
INTEGER_FOR_DIGITS_AND_SIGN(uint32_t);
INTEGER_FOR_DIGITS_AND_SIGN(int64_t);
INTEGER_FOR_DIGITS_AND_SIGN(uint64_t);
#undef INTEGER_FOR_DIGITS_AND_SIGN
// WARNING: We have no IntegerForSizeAndSign<16, *>. If we ever add one to
// support 128-bit math, then the ArithmeticPromotion template below will need
// to be updated (or more likely replaced with a decltype expression).
static_assert(IntegerBitsPlusSign<intmax_t>::value == 64,
"Max integer size not supported for this toolchain.");
template <typename Integer, bool IsSigned = std::is_signed<Integer>::value>
struct TwiceWiderInteger {
using type =
typename IntegerForDigitsAndSign<IntegerBitsPlusSign<Integer>::value * 2,
IsSigned>::type;
};
enum ArithmeticPromotionCategory {
LEFT_PROMOTION, // Use the type of the left-hand argument.
RIGHT_PROMOTION // Use the type of the right-hand argument.
};
// Determines the type that can represent the largest positive value.
template <typename Lhs,
typename Rhs,
ArithmeticPromotionCategory Promotion =
(MaxExponent<Lhs>::value > MaxExponent<Rhs>::value)
? LEFT_PROMOTION
: RIGHT_PROMOTION>
struct MaxExponentPromotion;
template <typename Lhs, typename Rhs>
struct MaxExponentPromotion<Lhs, Rhs, LEFT_PROMOTION> {
using type = Lhs;
};
template <typename Lhs, typename Rhs>
struct MaxExponentPromotion<Lhs, Rhs, RIGHT_PROMOTION> {
using type = Rhs;
};
// Determines the type that can represent the lowest arithmetic value.
template <typename Lhs,
typename Rhs,
ArithmeticPromotionCategory Promotion =
std::is_signed<Lhs>::value
? (std::is_signed<Rhs>::value
? (MaxExponent<Lhs>::value > MaxExponent<Rhs>::value
? LEFT_PROMOTION
: RIGHT_PROMOTION)
: LEFT_PROMOTION)
: (std::is_signed<Rhs>::value
? RIGHT_PROMOTION
: (MaxExponent<Lhs>::value < MaxExponent<Rhs>::value
? LEFT_PROMOTION
: RIGHT_PROMOTION))>
struct LowestValuePromotion;
template <typename Lhs, typename Rhs>
struct LowestValuePromotion<Lhs, Rhs, LEFT_PROMOTION> {
using type = Lhs;
};
template <typename Lhs, typename Rhs>
struct LowestValuePromotion<Lhs, Rhs, RIGHT_PROMOTION> {
using type = Rhs;
};
// Determines the type that is best able to represent an arithmetic result.
template <
typename Lhs,
typename Rhs = Lhs,
bool is_intmax_type =
std::is_integral<typename MaxExponentPromotion<Lhs, Rhs>::type>::value&&
IntegerBitsPlusSign<typename MaxExponentPromotion<Lhs, Rhs>::type>::
value == IntegerBitsPlusSign<intmax_t>::value,
bool is_max_exponent =
StaticDstRangeRelationToSrcRange<
typename MaxExponentPromotion<Lhs, Rhs>::type,
Lhs>::value ==
NUMERIC_RANGE_CONTAINED&& StaticDstRangeRelationToSrcRange<
typename MaxExponentPromotion<Lhs, Rhs>::type,
Rhs>::value == NUMERIC_RANGE_CONTAINED>
struct BigEnoughPromotion;
// The side with the max exponent is big enough.
template <typename Lhs, typename Rhs, bool is_intmax_type>
struct BigEnoughPromotion<Lhs, Rhs, is_intmax_type, true> {
using type = typename MaxExponentPromotion<Lhs, Rhs>::type;
static const bool is_contained = true;
};
// We can use a twice wider type to fit.
template <typename Lhs, typename Rhs>
struct BigEnoughPromotion<Lhs, Rhs, false, false> {
using type =
typename TwiceWiderInteger<typename MaxExponentPromotion<Lhs, Rhs>::type,
std::is_signed<Lhs>::value ||
std::is_signed<Rhs>::value>::type;
static const bool is_contained = true;
};
// No type is large enough.
template <typename Lhs, typename Rhs>
struct BigEnoughPromotion<Lhs, Rhs, true, false> {
using type = typename MaxExponentPromotion<Lhs, Rhs>::type;
static const bool is_contained = false;
};
// We can statically check if operations on the provided types can wrap, so we
// can skip the checked operations if they're not needed. So, for an integer we
// care if the destination type preserves the sign and is twice the width of
// the source.
template <typename T, typename Lhs, typename Rhs = Lhs>
struct IsIntegerArithmeticSafe {
static const bool value =
!std::is_floating_point<T>::value &&
!std::is_floating_point<Lhs>::value &&
!std::is_floating_point<Rhs>::value &&
std::is_signed<T>::value >= std::is_signed<Lhs>::value &&
IntegerBitsPlusSign<T>::value >= (2 * IntegerBitsPlusSign<Lhs>::value) &&
std::is_signed<T>::value >= std::is_signed<Rhs>::value &&
IntegerBitsPlusSign<T>::value >= (2 * IntegerBitsPlusSign<Rhs>::value);
};
// Promotes to a type that can represent any possible result of a binary
// arithmetic operation with the source types.
template <typename Lhs,
typename Rhs,
bool is_promotion_possible = IsIntegerArithmeticSafe<
typename std::conditional<std::is_signed<Lhs>::value ||
std::is_signed<Rhs>::value,
intmax_t,
uintmax_t>::type,
typename MaxExponentPromotion<Lhs, Rhs>::type>::value>
struct FastIntegerArithmeticPromotion;
template <typename Lhs, typename Rhs>
struct FastIntegerArithmeticPromotion<Lhs, Rhs, true> {
using type =
typename TwiceWiderInteger<typename MaxExponentPromotion<Lhs, Rhs>::type,
std::is_signed<Lhs>::value ||
std::is_signed<Rhs>::value>::type;
static_assert(IsIntegerArithmeticSafe<type, Lhs, Rhs>::value, "");
static const bool is_contained = true;
};
template <typename Lhs, typename Rhs>
struct FastIntegerArithmeticPromotion<Lhs, Rhs, false> {
using type = typename BigEnoughPromotion<Lhs, Rhs>::type;
static const bool is_contained = false;
};
// Extracts the underlying type from an enum.
template <typename T, bool is_enum = std::is_enum<T>::value>
struct ArithmeticOrUnderlyingEnum;
template <typename T>
struct ArithmeticOrUnderlyingEnum<T, true> {
using type = typename std::underlying_type<T>::type;
static const bool value = std::is_arithmetic<type>::value;
};
template <typename T>
struct ArithmeticOrUnderlyingEnum<T, false> {
using type = T;
static const bool value = std::is_arithmetic<type>::value;
};
// The following are helper templates used in the CheckedNumeric class.
template <typename T>
class CheckedNumeric;
template <typename T>
class ClampedNumeric;
template <typename T>
class StrictNumeric;
// Used to treat CheckedNumeric and arithmetic underlying types the same.
template <typename T>
struct UnderlyingType {
using type = typename ArithmeticOrUnderlyingEnum<T>::type;
static const bool is_numeric = std::is_arithmetic<type>::value;
static const bool is_checked = false;
static const bool is_clamped = false;
static const bool is_strict = false;
};
template <typename T>
struct UnderlyingType<CheckedNumeric<T>> {
using type = T;
static const bool is_numeric = true;
static const bool is_checked = true;
static const bool is_clamped = false;
static const bool is_strict = false;
};
template <typename T>
struct UnderlyingType<ClampedNumeric<T>> {
using type = T;
static const bool is_numeric = true;
static const bool is_checked = false;
static const bool is_clamped = true;
static const bool is_strict = false;
};
template <typename T>
struct UnderlyingType<StrictNumeric<T>> {
using type = T;
static const bool is_numeric = true;
static const bool is_checked = false;
static const bool is_clamped = false;
static const bool is_strict = true;
};
template <typename L, typename R>
struct IsCheckedOp {
static const bool value =
UnderlyingType<L>::is_numeric && UnderlyingType<R>::is_numeric &&
(UnderlyingType<L>::is_checked || UnderlyingType<R>::is_checked);
};
template <typename L, typename R>
struct IsClampedOp {
static const bool value =
UnderlyingType<L>::is_numeric && UnderlyingType<R>::is_numeric &&
(UnderlyingType<L>::is_clamped || UnderlyingType<R>::is_clamped) &&
!(UnderlyingType<L>::is_checked || UnderlyingType<R>::is_checked);
};
template <typename L, typename R>
struct IsStrictOp {
static const bool value =
UnderlyingType<L>::is_numeric && UnderlyingType<R>::is_numeric &&
(UnderlyingType<L>::is_strict || UnderlyingType<R>::is_strict) &&
!(UnderlyingType<L>::is_checked || UnderlyingType<R>::is_checked) &&
!(UnderlyingType<L>::is_clamped || UnderlyingType<R>::is_clamped);
};
// as_signed<> returns the supplied integral value (or integral castable
// Numeric template) cast as a signed integral of equivalent precision.
// I.e. it's mostly an alias for: static_cast<std::make_signed<T>::type>(t)
template <typename Src>
constexpr typename std::make_signed<
typename base::internal::UnderlyingType<Src>::type>::type
as_signed(const Src value) {
static_assert(std::is_integral<decltype(as_signed(value))>::value,
"Argument must be a signed or unsigned integer type.");
return static_cast<decltype(as_signed(value))>(value);
}
// as_unsigned<> returns the supplied integral value (or integral castable
// Numeric template) cast as an unsigned integral of equivalent precision.
// I.e. it's mostly an alias for: static_cast<std::make_unsigned<T>::type>(t)
template <typename Src>
constexpr typename std::make_unsigned<
typename base::internal::UnderlyingType<Src>::type>::type
as_unsigned(const Src value) {
static_assert(std::is_integral<decltype(as_unsigned(value))>::value,
"Argument must be a signed or unsigned integer type.");
return static_cast<decltype(as_unsigned(value))>(value);
}
template <typename L, typename R>
constexpr bool IsLessImpl(const L lhs,
const R rhs,
const RangeCheck l_range,
const RangeCheck r_range) {
return l_range.IsUnderflow() || r_range.IsOverflow() ||
(l_range == r_range &&
static_cast<decltype(lhs + rhs)>(lhs) <
static_cast<decltype(lhs + rhs)>(rhs));
}
template <typename L, typename R>
struct IsLess {
static_assert(std::is_arithmetic<L>::value && std::is_arithmetic<R>::value,
"Types must be numeric.");
static constexpr bool Test(const L lhs, const R rhs) {
return IsLessImpl(lhs, rhs, DstRangeRelationToSrcRange<R>(lhs),
DstRangeRelationToSrcRange<L>(rhs));
}
};
template <typename L, typename R>
constexpr bool IsLessOrEqualImpl(const L lhs,
const R rhs,
const RangeCheck l_range,
const RangeCheck r_range) {
return l_range.IsUnderflow() || r_range.IsOverflow() ||
(l_range == r_range &&
static_cast<decltype(lhs + rhs)>(lhs) <=
static_cast<decltype(lhs + rhs)>(rhs));
}
template <typename L, typename R>
struct IsLessOrEqual {
static_assert(std::is_arithmetic<L>::value && std::is_arithmetic<R>::value,
"Types must be numeric.");
static constexpr bool Test(const L lhs, const R rhs) {
return IsLessOrEqualImpl(lhs, rhs, DstRangeRelationToSrcRange<R>(lhs),
DstRangeRelationToSrcRange<L>(rhs));
}
};
template <typename L, typename R>
constexpr bool IsGreaterImpl(const L lhs,
const R rhs,
const RangeCheck l_range,
const RangeCheck r_range) {
return l_range.IsOverflow() || r_range.IsUnderflow() ||
(l_range == r_range &&
static_cast<decltype(lhs + rhs)>(lhs) >
static_cast<decltype(lhs + rhs)>(rhs));
}
template <typename L, typename R>
struct IsGreater {
static_assert(std::is_arithmetic<L>::value && std::is_arithmetic<R>::value,
"Types must be numeric.");
static constexpr bool Test(const L lhs, const R rhs) {
return IsGreaterImpl(lhs, rhs, DstRangeRelationToSrcRange<R>(lhs),
DstRangeRelationToSrcRange<L>(rhs));
}
};
template <typename L, typename R>
constexpr bool IsGreaterOrEqualImpl(const L lhs,
const R rhs,
const RangeCheck l_range,
const RangeCheck r_range) {
return l_range.IsOverflow() || r_range.IsUnderflow() ||
(l_range == r_range &&
static_cast<decltype(lhs + rhs)>(lhs) >=
static_cast<decltype(lhs + rhs)>(rhs));
}
template <typename L, typename R>
struct IsGreaterOrEqual {
static_assert(std::is_arithmetic<L>::value && std::is_arithmetic<R>::value,
"Types must be numeric.");
static constexpr bool Test(const L lhs, const R rhs) {
return IsGreaterOrEqualImpl(lhs, rhs, DstRangeRelationToSrcRange<R>(lhs),
DstRangeRelationToSrcRange<L>(rhs));
}
};
template <typename L, typename R>
struct IsEqual {
static_assert(std::is_arithmetic<L>::value && std::is_arithmetic<R>::value,
"Types must be numeric.");
static constexpr bool Test(const L lhs, const R rhs) {
return DstRangeRelationToSrcRange<R>(lhs) ==
DstRangeRelationToSrcRange<L>(rhs) &&
static_cast<decltype(lhs + rhs)>(lhs) ==
static_cast<decltype(lhs + rhs)>(rhs);
}
};
template <typename L, typename R>
struct IsNotEqual {
static_assert(std::is_arithmetic<L>::value && std::is_arithmetic<R>::value,
"Types must be numeric.");
static constexpr bool Test(const L lhs, const R rhs) {
return DstRangeRelationToSrcRange<R>(lhs) !=
DstRangeRelationToSrcRange<L>(rhs) ||
static_cast<decltype(lhs + rhs)>(lhs) !=
static_cast<decltype(lhs + rhs)>(rhs);
}
};
// These perform the actual math operations on the CheckedNumerics.
// Binary arithmetic operations.
template <template <typename, typename> class C, typename L, typename R>
constexpr bool SafeCompare(const L lhs, const R rhs) {
static_assert(std::is_arithmetic<L>::value && std::is_arithmetic<R>::value,
"Types must be numeric.");
using Promotion = BigEnoughPromotion<L, R>;
using BigType = typename Promotion::type;
return Promotion::is_contained
// Force to a larger type for speed if both are contained.
? C<BigType, BigType>::Test(
static_cast<BigType>(static_cast<L>(lhs)),
static_cast<BigType>(static_cast<R>(rhs)))
// Let the template functions figure it out for mixed types.
: C<L, R>::Test(lhs, rhs);
}
template <typename Dst, typename Src>
constexpr bool IsMaxInRangeForNumericType() {
return IsGreaterOrEqual<Dst, Src>::Test(std::numeric_limits<Dst>::max(),
std::numeric_limits<Src>::max());
}
template <typename Dst, typename Src>
constexpr bool IsMinInRangeForNumericType() {
return IsLessOrEqual<Dst, Src>::Test(std::numeric_limits<Dst>::lowest(),
std::numeric_limits<Src>::lowest());
}
template <typename Dst, typename Src>
constexpr Dst CommonMax() {
return !IsMaxInRangeForNumericType<Dst, Src>()
? Dst(std::numeric_limits<Dst>::max())
: Dst(std::numeric_limits<Src>::max());
}
template <typename Dst, typename Src>
constexpr Dst CommonMin() {
return !IsMinInRangeForNumericType<Dst, Src>()
? Dst(std::numeric_limits<Dst>::lowest())
: Dst(std::numeric_limits<Src>::lowest());
}
// This is a wrapper to generate return the max or min for a supplied type.
// If the argument is false, the returned value is the maximum. If true the
// returned value is the minimum.
template <typename Dst, typename Src = Dst>
constexpr Dst CommonMaxOrMin(bool is_min) {
return is_min ? CommonMin<Dst, Src>() : CommonMax<Dst, Src>();
}
} // namespace internal
} // namespace base
#endif // BASE_NUMERICS_SAFE_CONVERSIONS_IMPL_H_

View File

@@ -0,0 +1,12 @@
// Copyright 2017 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.
#ifndef BASE_NUMERICS_SAFE_MATH_H_
#define BASE_NUMERICS_SAFE_MATH_H_
#include "base/numerics/checked_math.h"
#include "base/numerics/clamped_math.h"
#include "base/numerics/safe_conversions.h"
#endif // BASE_NUMERICS_SAFE_MATH_H_

View File

@@ -0,0 +1,122 @@
// Copyright 2017 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.
#ifndef BASE_NUMERICS_SAFE_MATH_ARM_IMPL_H_
#define BASE_NUMERICS_SAFE_MATH_ARM_IMPL_H_
#include <cassert>
#include <limits>
#include <type_traits>
#include "base/numerics/safe_conversions.h"
namespace base {
namespace internal {
template <typename T, typename U>
struct CheckedMulFastAsmOp {
static const bool is_supported =
FastIntegerArithmeticPromotion<T, U>::is_contained;
// The following is much more efficient than the Clang and GCC builtins for
// performing overflow-checked multiplication when a twice wider type is
// available. The below compiles down to 2-3 instructions, depending on the
// width of the types in use.
// As an example, an int32_t multiply compiles to:
// smull r0, r1, r0, r1
// cmp r1, r1, asr #31
// And an int16_t multiply compiles to:
// smulbb r1, r1, r0
// asr r2, r1, #16
// cmp r2, r1, asr #15
template <typename V>
__attribute__((always_inline)) static bool Do(T x, U y, V* result) {
using Promotion = typename FastIntegerArithmeticPromotion<T, U>::type;
Promotion presult;
presult = static_cast<Promotion>(x) * static_cast<Promotion>(y);
*result = static_cast<V>(presult);
return IsValueInRangeForNumericType<V>(presult);
}
};
template <typename T, typename U>
struct ClampedAddFastAsmOp {
static const bool is_supported =
BigEnoughPromotion<T, U>::is_contained &&
IsTypeInRangeForNumericType<
int32_t,
typename BigEnoughPromotion<T, U>::type>::value;
template <typename V>
__attribute__((always_inline)) static V Do(T x, U y) {
// This will get promoted to an int, so let the compiler do whatever is
// clever and rely on the saturated cast to bounds check.
if (IsIntegerArithmeticSafe<int, T, U>::value)
return saturated_cast<V>(x + y);
int32_t result;
int32_t x_i32 = checked_cast<int32_t>(x);
int32_t y_i32 = checked_cast<int32_t>(y);
asm("qadd %[result], %[first], %[second]"
: [result] "=r"(result)
: [first] "r"(x_i32), [second] "r"(y_i32));
return saturated_cast<V>(result);
}
};
template <typename T, typename U>
struct ClampedSubFastAsmOp {
static const bool is_supported =
BigEnoughPromotion<T, U>::is_contained &&
IsTypeInRangeForNumericType<
int32_t,
typename BigEnoughPromotion<T, U>::type>::value;
template <typename V>
__attribute__((always_inline)) static V Do(T x, U y) {
// This will get promoted to an int, so let the compiler do whatever is
// clever and rely on the saturated cast to bounds check.
if (IsIntegerArithmeticSafe<int, T, U>::value)
return saturated_cast<V>(x - y);
int32_t result;
int32_t x_i32 = checked_cast<int32_t>(x);
int32_t y_i32 = checked_cast<int32_t>(y);
asm("qsub %[result], %[first], %[second]"
: [result] "=r"(result)
: [first] "r"(x_i32), [second] "r"(y_i32));
return saturated_cast<V>(result);
}
};
template <typename T, typename U>
struct ClampedMulFastAsmOp {
static const bool is_supported = CheckedMulFastAsmOp<T, U>::is_supported;
template <typename V>
__attribute__((always_inline)) static V Do(T x, U y) {
// Use the CheckedMulFastAsmOp for full-width 32-bit values, because
// it's fewer instructions than promoting and then saturating.
if (!IsIntegerArithmeticSafe<int32_t, T, U>::value &&
!IsIntegerArithmeticSafe<uint32_t, T, U>::value) {
V result;
if (CheckedMulFastAsmOp<T, U>::Do(x, y, &result))
return result;
return CommonMaxOrMin<V>(IsValueNegative(x) ^ IsValueNegative(y));
}
assert((FastIntegerArithmeticPromotion<T, U>::is_contained));
using Promotion = typename FastIntegerArithmeticPromotion<T, U>::type;
return saturated_cast<V>(static_cast<Promotion>(x) *
static_cast<Promotion>(y));
}
};
} // namespace internal
} // namespace base
#endif // BASE_NUMERICS_SAFE_MATH_ARM_IMPL_H_

View File

@@ -0,0 +1,157 @@
// Copyright 2017 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.
#ifndef BASE_NUMERICS_SAFE_MATH_CLANG_GCC_IMPL_H_
#define BASE_NUMERICS_SAFE_MATH_CLANG_GCC_IMPL_H_
#include <cassert>
#include <limits>
#include <type_traits>
#include "base/numerics/safe_conversions.h"
#if !defined(__native_client__) && (defined(__ARMEL__) || defined(__arch64__))
#include "base/numerics/safe_math_arm_impl.h"
#define BASE_HAS_ASSEMBLER_SAFE_MATH (1)
#else
#define BASE_HAS_ASSEMBLER_SAFE_MATH (0)
#endif
namespace base {
namespace internal {
// These are the non-functioning boilerplate implementations of the optimized
// safe math routines.
#if !BASE_HAS_ASSEMBLER_SAFE_MATH
template <typename T, typename U>
struct CheckedMulFastAsmOp {
static const bool is_supported = false;
template <typename V>
static constexpr bool Do(T, U, V*) {
// Force a compile failure if instantiated.
return CheckOnFailure::template HandleFailure<bool>();
}
};
template <typename T, typename U>
struct ClampedAddFastAsmOp {
static const bool is_supported = false;
template <typename V>
static constexpr V Do(T, U) {
// Force a compile failure if instantiated.
return CheckOnFailure::template HandleFailure<V>();
}
};
template <typename T, typename U>
struct ClampedSubFastAsmOp {
static const bool is_supported = false;
template <typename V>
static constexpr V Do(T, U) {
// Force a compile failure if instantiated.
return CheckOnFailure::template HandleFailure<V>();
}
};
template <typename T, typename U>
struct ClampedMulFastAsmOp {
static const bool is_supported = false;
template <typename V>
static constexpr V Do(T, U) {
// Force a compile failure if instantiated.
return CheckOnFailure::template HandleFailure<V>();
}
};
#endif // BASE_HAS_ASSEMBLER_SAFE_MATH
#undef BASE_HAS_ASSEMBLER_SAFE_MATH
template <typename T, typename U>
struct CheckedAddFastOp {
static const bool is_supported = true;
template <typename V>
__attribute__((always_inline)) static constexpr bool Do(T x, U y, V* result) {
return !__builtin_add_overflow(x, y, result);
}
};
template <typename T, typename U>
struct CheckedSubFastOp {
static const bool is_supported = true;
template <typename V>
__attribute__((always_inline)) static constexpr bool Do(T x, U y, V* result) {
return !__builtin_sub_overflow(x, y, result);
}
};
template <typename T, typename U>
struct CheckedMulFastOp {
#if defined(__clang__)
// TODO(jschuh): Get the Clang runtime library issues sorted out so we can
// support full-width, mixed-sign multiply builtins.
// https://crbug.com/613003
// We can support intptr_t, uintptr_t, or a smaller common type.
static const bool is_supported =
(IsTypeInRangeForNumericType<intptr_t, T>::value &&
IsTypeInRangeForNumericType<intptr_t, U>::value) ||
(IsTypeInRangeForNumericType<uintptr_t, T>::value &&
IsTypeInRangeForNumericType<uintptr_t, U>::value);
#else
static const bool is_supported = true;
#endif
template <typename V>
__attribute__((always_inline)) static constexpr bool Do(T x, U y, V* result) {
return CheckedMulFastAsmOp<T, U>::is_supported
? CheckedMulFastAsmOp<T, U>::Do(x, y, result)
: !__builtin_mul_overflow(x, y, result);
}
};
template <typename T, typename U>
struct ClampedAddFastOp {
static const bool is_supported = ClampedAddFastAsmOp<T, U>::is_supported;
template <typename V>
__attribute__((always_inline)) static V Do(T x, U y) {
return ClampedAddFastAsmOp<T, U>::template Do<V>(x, y);
}
};
template <typename T, typename U>
struct ClampedSubFastOp {
static const bool is_supported = ClampedSubFastAsmOp<T, U>::is_supported;
template <typename V>
__attribute__((always_inline)) static V Do(T x, U y) {
return ClampedSubFastAsmOp<T, U>::template Do<V>(x, y);
}
};
template <typename T, typename U>
struct ClampedMulFastOp {
static const bool is_supported = ClampedMulFastAsmOp<T, U>::is_supported;
template <typename V>
__attribute__((always_inline)) static V Do(T x, U y) {
return ClampedMulFastAsmOp<T, U>::template Do<V>(x, y);
}
};
template <typename T>
struct ClampedNegFastOp {
static const bool is_supported = std::is_signed<T>::value;
__attribute__((always_inline)) static T Do(T value) {
// Use this when there is no assembler path available.
if (!ClampedSubFastAsmOp<T, T>::is_supported) {
T result;
return !__builtin_sub_overflow(T(0), value, &result)
? result
: std::numeric_limits<T>::max();
}
// Fallback to the normal subtraction path.
return ClampedSubFastOp<T, T>::template Do<T>(T(0), value);
}
};
} // namespace internal
} // namespace base
#endif // BASE_NUMERICS_SAFE_MATH_CLANG_GCC_IMPL_H_

View File

@@ -0,0 +1,241 @@
// Copyright 2017 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.
#ifndef BASE_NUMERICS_SAFE_MATH_SHARED_IMPL_H_
#define BASE_NUMERICS_SAFE_MATH_SHARED_IMPL_H_
#include <stddef.h>
#include <stdint.h>
#include <cassert>
#include <climits>
#include <cmath>
#include <cstdlib>
#include <limits>
#include <type_traits>
#include "base/numerics/safe_conversions.h"
#include "build/build_config.h"
#if defined(OS_ASMJS)
// Optimized safe math instructions are incompatible with asmjs.
#define BASE_HAS_OPTIMIZED_SAFE_MATH (0)
// Where available use builtin math overflow support on Clang and GCC.
#elif !defined(__native_client__) && \
((defined(__clang__) && \
((__clang_major__ > 3) || \
(__clang_major__ == 3 && __clang_minor__ >= 4))) || \
(defined(__GNUC__) && __GNUC__ >= 5))
#include "base/numerics/safe_math_clang_gcc_impl.h"
#define BASE_HAS_OPTIMIZED_SAFE_MATH (1)
#else
#define BASE_HAS_OPTIMIZED_SAFE_MATH (0)
#endif
namespace base {
namespace internal {
// These are the non-functioning boilerplate implementations of the optimized
// safe math routines.
#if !BASE_HAS_OPTIMIZED_SAFE_MATH
template <typename T, typename U>
struct CheckedAddFastOp {
static const bool is_supported = false;
template <typename V>
static constexpr bool Do(T, U, V*) {
// Force a compile failure if instantiated.
return CheckOnFailure::template HandleFailure<bool>();
}
};
template <typename T, typename U>
struct CheckedSubFastOp {
static const bool is_supported = false;
template <typename V>
static constexpr bool Do(T, U, V*) {
// Force a compile failure if instantiated.
return CheckOnFailure::template HandleFailure<bool>();
}
};
template <typename T, typename U>
struct CheckedMulFastOp {
static const bool is_supported = false;
template <typename V>
static constexpr bool Do(T, U, V*) {
// Force a compile failure if instantiated.
return CheckOnFailure::template HandleFailure<bool>();
}
};
template <typename T, typename U>
struct ClampedAddFastOp {
static const bool is_supported = false;
template <typename V>
static constexpr V Do(T, U) {
// Force a compile failure if instantiated.
return CheckOnFailure::template HandleFailure<V>();
}
};
template <typename T, typename U>
struct ClampedSubFastOp {
static const bool is_supported = false;
template <typename V>
static constexpr V Do(T, U) {
// Force a compile failure if instantiated.
return CheckOnFailure::template HandleFailure<V>();
}
};
template <typename T, typename U>
struct ClampedMulFastOp {
static const bool is_supported = false;
template <typename V>
static constexpr V Do(T, U) {
// Force a compile failure if instantiated.
return CheckOnFailure::template HandleFailure<V>();
}
};
template <typename T>
struct ClampedNegFastOp {
static const bool is_supported = false;
static constexpr T Do(T) {
// Force a compile failure if instantiated.
return CheckOnFailure::template HandleFailure<T>();
}
};
#endif // BASE_HAS_OPTIMIZED_SAFE_MATH
#undef BASE_HAS_OPTIMIZED_SAFE_MATH
// This is used for UnsignedAbs, where we need to support floating-point
// template instantiations even though we don't actually support the operations.
// However, there is no corresponding implementation of e.g. SafeUnsignedAbs,
// so the float versions will not compile.
template <typename Numeric,
bool IsInteger = std::is_integral<Numeric>::value,
bool IsFloat = std::is_floating_point<Numeric>::value>
struct UnsignedOrFloatForSize;
template <typename Numeric>
struct UnsignedOrFloatForSize<Numeric, true, false> {
using type = typename std::make_unsigned<Numeric>::type;
};
template <typename Numeric>
struct UnsignedOrFloatForSize<Numeric, false, true> {
using type = Numeric;
};
// Wrap the unary operations to allow SFINAE when instantiating integrals versus
// floating points. These don't perform any overflow checking. Rather, they
// exhibit well-defined overflow semantics and rely on the caller to detect
// if an overflow occured.
template <typename T,
typename std::enable_if<std::is_integral<T>::value>::type* = nullptr>
constexpr T NegateWrapper(T value) {
using UnsignedT = typename std::make_unsigned<T>::type;
// This will compile to a NEG on Intel, and is normal negation on ARM.
return static_cast<T>(UnsignedT(0) - static_cast<UnsignedT>(value));
}
template <
typename T,
typename std::enable_if<std::is_floating_point<T>::value>::type* = nullptr>
constexpr T NegateWrapper(T value) {
return -value;
}
template <typename T,
typename std::enable_if<std::is_integral<T>::value>::type* = nullptr>
constexpr typename std::make_unsigned<T>::type InvertWrapper(T value) {
return ~value;
}
template <typename T,
typename std::enable_if<std::is_integral<T>::value>::type* = nullptr>
constexpr T AbsWrapper(T value) {
return static_cast<T>(SafeUnsignedAbs(value));
}
template <
typename T,
typename std::enable_if<std::is_floating_point<T>::value>::type* = nullptr>
constexpr T AbsWrapper(T value) {
return value < 0 ? -value : value;
}
template <template <typename, typename, typename> class M,
typename L,
typename R>
struct MathWrapper {
using math = M<typename UnderlyingType<L>::type,
typename UnderlyingType<R>::type,
void>;
using type = typename math::result_type;
};
// These variadic templates work out the return types.
// TODO(jschuh): Rip all this out once we have C++14 non-trailing auto support.
template <template <typename, typename, typename> class M,
typename L,
typename R,
typename... Args>
struct ResultType;
template <template <typename, typename, typename> class M,
typename L,
typename R>
struct ResultType<M, L, R> {
using type = typename MathWrapper<M, L, R>::type;
};
template <template <typename, typename, typename> class M,
typename L,
typename R,
typename... Args>
struct ResultType {
using type =
typename ResultType<M, typename ResultType<M, L, R>::type, Args...>::type;
};
// The following macros are just boilerplate for the standard arithmetic
// operator overloads and variadic function templates. A macro isn't the nicest
// solution, but it beats rewriting these over and over again.
#define BASE_NUMERIC_ARITHMETIC_VARIADIC(CLASS, CL_ABBR, OP_NAME) \
template <typename L, typename R, typename... Args> \
constexpr CLASS##Numeric< \
typename ResultType<CLASS##OP_NAME##Op, L, R, Args...>::type> \
CL_ABBR##OP_NAME(const L lhs, const R rhs, const Args... args) { \
return CL_ABBR##MathOp<CLASS##OP_NAME##Op, L, R, Args...>(lhs, rhs, \
args...); \
}
#define BASE_NUMERIC_ARITHMETIC_OPERATORS(CLASS, CL_ABBR, OP_NAME, OP, CMP_OP) \
/* Binary arithmetic operator for all CLASS##Numeric operations. */ \
template <typename L, typename R, \
typename std::enable_if<Is##CLASS##Op<L, R>::value>::type* = \
nullptr> \
constexpr CLASS##Numeric< \
typename MathWrapper<CLASS##OP_NAME##Op, L, R>::type> \
operator OP(const L lhs, const R rhs) { \
return decltype(lhs OP rhs)::template MathOp<CLASS##OP_NAME##Op>(lhs, \
rhs); \
} \
/* Assignment arithmetic operator implementation from CLASS##Numeric. */ \
template <typename L> \
template <typename R> \
constexpr CLASS##Numeric<L>& CLASS##Numeric<L>::operator CMP_OP( \
const R rhs) { \
return MathOp<CLASS##OP_NAME##Op>(rhs); \
} \
/* Variadic arithmetic functions that return CLASS##Numeric. */ \
BASE_NUMERIC_ARITHMETIC_VARIADIC(CLASS, CL_ABBR, OP_NAME)
} // namespace internal
} // namespace base
#endif // BASE_NUMERICS_SAFE_MATH_SHARED_IMPL_H_

View File

@@ -0,0 +1,24 @@
// Copyright (c) 2009 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/geometry/insets.h"
#include "base/strings/stringprintf.h"
#include "ui/gfx/geometry/vector2d.h"
namespace gfx {
std::string Insets::ToString() const {
// Print members in the same order of the constructor parameters.
return base::StringPrintf("%d,%d,%d,%d", top(), left(), bottom(), right());
}
Insets Insets::Offset(const gfx::Vector2d& vector) const {
return gfx::Insets(base::ClampAdd(top(), vector.y()),
base::ClampAdd(left(), vector.x()),
base::ClampSub(bottom(), vector.y()),
base::ClampSub(right(), vector.x()));
}
} // namespace gfx

View File

@@ -0,0 +1,189 @@
// Copyright (c) 2012 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.
#ifndef UI_GFX_GEOMETRY_INSETS_H_
#define UI_GFX_GEOMETRY_INSETS_H_
#include <string>
#include "base/numerics/clamped_math.h"
#include "ui/gfx/geometry/geometry_export.h"
#include "ui/gfx/geometry/insets_f.h"
#include "ui/gfx/geometry/size.h"
namespace gfx {
class Vector2d;
// Represents the widths of the four borders or margins of an unspecified
// rectangle. An Insets stores the thickness of the top, left, bottom and right
// edges, without storing the actual size and position of the rectangle itself.
//
// This can be used to represent a space within a rectangle, by "shrinking" the
// rectangle by the inset amount on all four sides. Alternatively, it can
// represent a border that has a different thickness on each side.
class GEOMETRY_EXPORT Insets {
public:
constexpr Insets() : top_(0), left_(0), bottom_(0), right_(0) {}
constexpr explicit Insets(int all)
: top_(all),
left_(all),
bottom_(GetClampedValue(all, all)),
right_(GetClampedValue(all, all)) {}
constexpr explicit Insets(int vertical, int horizontal)
: top_(vertical),
left_(horizontal),
bottom_(GetClampedValue(vertical, vertical)),
right_(GetClampedValue(horizontal, horizontal)) {}
constexpr Insets(int top, int left, int bottom, int right)
: top_(top),
left_(left),
bottom_(GetClampedValue(top, bottom)),
right_(GetClampedValue(left, right)) {}
constexpr int top() const { return top_; }
constexpr int left() const { return left_; }
constexpr int bottom() const { return bottom_; }
constexpr int right() const { return right_; }
// Returns the total width taken up by the insets, which is the sum of the
// left and right insets.
constexpr int width() const { return left_ + right_; }
// Returns the total height taken up by the insets, which is the sum of the
// top and bottom insets.
constexpr int height() const { return top_ + bottom_; }
// Returns the sum of the left and right insets as the width, the sum of the
// top and bottom insets as the height.
constexpr Size size() const { return Size(width(), height()); }
// Returns true if the insets are empty.
bool IsEmpty() const { return width() == 0 && height() == 0; }
void set_top(int top) {
top_ = top;
bottom_ = GetClampedValue(top_, bottom_);
}
void set_left(int left) {
left_ = left;
right_ = GetClampedValue(left_, right_);
}
void set_bottom(int bottom) { bottom_ = GetClampedValue(top_, bottom); }
void set_right(int right) { right_ = GetClampedValue(left_, right); }
void Set(int top, int left, int bottom, int right) {
top_ = top;
left_ = left;
bottom_ = GetClampedValue(top_, bottom);
right_ = GetClampedValue(left_, right);
}
bool operator==(const Insets& insets) const {
return top_ == insets.top_ && left_ == insets.left_ &&
bottom_ == insets.bottom_ && right_ == insets.right_;
}
bool operator!=(const Insets& insets) const {
return !(*this == insets);
}
void operator+=(const Insets& insets) {
top_ = base::ClampAdd(top_, insets.top_);
left_ = base::ClampAdd(left_, insets.left_);
bottom_ = GetClampedValue(top_, base::ClampAdd(bottom_, insets.bottom_));
right_ = GetClampedValue(left_, base::ClampAdd(right_, insets.right_));
}
void operator-=(const Insets& insets) {
top_ = base::ClampSub(top_, insets.top_);
left_ = base::ClampSub(left_, insets.left_);
bottom_ = GetClampedValue(top_, base::ClampSub(bottom_, insets.bottom_));
right_ = GetClampedValue(left_, base::ClampSub(right_, insets.right_));
}
Insets operator-() const {
return Insets(-base::MakeClampedNum(top_), -base::MakeClampedNum(left_),
-base::MakeClampedNum(bottom_),
-base::MakeClampedNum(right_));
}
Insets Scale(float scale) const { return Scale(scale, scale); }
Insets Scale(float x_scale, float y_scale) const {
return Insets(static_cast<int>(base::ClampMul(top(), y_scale)),
static_cast<int>(base::ClampMul(left(), x_scale)),
static_cast<int>(base::ClampMul(bottom(), y_scale)),
static_cast<int>(base::ClampMul(right(), x_scale)));
}
// Adjusts the vertical and horizontal dimensions by the values described in
// |vector|. Offsetting insets before applying to a rectangle would be
// equivalent to offseting the rectangle then applying the insets.
Insets Offset(const gfx::Vector2d& vector) const;
operator InsetsF() const {
return InsetsF(static_cast<float>(top()), static_cast<float>(left()),
static_cast<float>(bottom()), static_cast<float>(right()));
}
// Returns a string representation of the insets.
std::string ToString() const;
private:
int top_;
int left_;
int bottom_;
int right_;
// See ui/gfx/geometry/rect.h
// Returns true iff a+b would overflow max int.
static constexpr bool AddWouldOverflow(int a, int b) {
// In this function, GCC tries to make optimizations that would only work if
// max - a wouldn't overflow but it isn't smart enough to notice that a > 0.
// So cast everything to unsigned to avoid this. As it is guaranteed that
// max - a and b are both already positive, the cast is a noop.
//
// This is intended to be: a > 0 && max - a < b
return a > 0 && b > 0 &&
static_cast<unsigned>(std::numeric_limits<int>::max() - a) <
static_cast<unsigned>(b);
}
// Returns true iff a+b would underflow min int.
static constexpr bool AddWouldUnderflow(int a, int b) {
return a < 0 && b < 0 && std::numeric_limits<int>::min() - a > b;
}
// Clamp the right/bottom to avoid integer over/underflow in width() and
// height(). This returns the right/bottom given a top_or_left and a
// bottom_or_right.
// TODO(enne): this should probably use base::ClampAdd, but that
// function is not a constexpr.
static constexpr int GetClampedValue(int top_or_left, int bottom_or_right) {
if (AddWouldOverflow(top_or_left, bottom_or_right)) {
return std::numeric_limits<int>::max() - top_or_left;
} else if (AddWouldUnderflow(top_or_left, bottom_or_right)) {
// If |top_or_left| and |bottom_or_right| are both negative,
// adds |top_or_left| to prevent underflow by subtracting it.
return std::numeric_limits<int>::min() - top_or_left;
} else {
return bottom_or_right;
}
}
};
inline Insets operator+(Insets lhs, const Insets& rhs) {
lhs += rhs;
return lhs;
}
inline Insets operator-(Insets lhs, const Insets& rhs) {
lhs -= rhs;
return lhs;
}
} // namespace gfx
#endif // UI_GFX_GEOMETRY_INSETS_H_

View File

@@ -0,0 +1,16 @@
// Copyright (c) 2012 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/geometry/insets_f.h"
#include "base/strings/stringprintf.h"
namespace gfx {
std::string InsetsF::ToString() const {
// Print members in the same order of the constructor parameters.
return base::StringPrintf("%f,%f,%f,%f", top(), left(), bottom(), right());
}
} // namespace gfx

View File

@@ -0,0 +1,105 @@
// Copyright (c) 2012 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.
#ifndef UI_GFX_GEOMETRY_INSETS_F_H_
#define UI_GFX_GEOMETRY_INSETS_F_H_
#include <string>
#include "ui/gfx/geometry/geometry_export.h"
namespace gfx {
// A floating point version of gfx::Insets.
class GEOMETRY_EXPORT InsetsF {
public:
constexpr InsetsF() : top_(0.f), left_(0.f), bottom_(0.f), right_(0.f) {}
constexpr explicit InsetsF(float all)
: top_(all), left_(all), bottom_(all), right_(all) {}
constexpr InsetsF(float vertical, float horizontal)
: top_(vertical),
left_(horizontal),
bottom_(vertical),
right_(horizontal) {}
constexpr InsetsF(float top, float left, float bottom, float right)
: top_(top), left_(left), bottom_(bottom), right_(right) {}
constexpr float top() const { return top_; }
constexpr float left() const { return left_; }
constexpr float bottom() const { return bottom_; }
constexpr float right() const { return right_; }
// Returns the total width taken up by the insets, which is the sum of the
// left and right insets.
constexpr float width() const { return left_ + right_; }
// Returns the total height taken up by the insets, which is the sum of the
// top and bottom insets.
constexpr float height() const { return top_ + bottom_; }
// Returns true if the insets are empty.
bool IsEmpty() const { return width() == 0.f && height() == 0.f; }
void Set(float top, float left, float bottom, float right) {
top_ = top;
left_ = left;
bottom_ = bottom;
right_ = right;
}
bool operator==(const InsetsF& insets) const {
return top_ == insets.top_ && left_ == insets.left_ &&
bottom_ == insets.bottom_ && right_ == insets.right_;
}
bool operator!=(const InsetsF& insets) const {
return !(*this == insets);
}
void operator+=(const InsetsF& insets) {
top_ += insets.top_;
left_ += insets.left_;
bottom_ += insets.bottom_;
right_ += insets.right_;
}
void operator-=(const InsetsF& insets) {
top_ -= insets.top_;
left_ -= insets.left_;
bottom_ -= insets.bottom_;
right_ -= insets.right_;
}
InsetsF operator-() const {
return InsetsF(-top_, -left_, -bottom_, -right_);
}
InsetsF Scale(float scale) const {
return InsetsF(scale * top(), scale * left(), scale * bottom(),
scale * right());
}
// Returns a string representation of the insets.
std::string ToString() const;
private:
float top_;
float left_;
float bottom_;
float right_;
};
inline InsetsF operator+(InsetsF lhs, const InsetsF& rhs) {
lhs += rhs;
return lhs;
}
inline InsetsF operator-(InsetsF lhs, const InsetsF& rhs) {
lhs -= rhs;
return lhs;
}
} // namespace gfx
#endif // UI_GFX_GEOMETRY_INSETS_F_H_

View File

@@ -0,0 +1,288 @@
// Copyright (c) 2009 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/geometry/insets.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/gfx/geometry/insets_f.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/geometry/vector2d.h"
TEST(InsetsTest, InsetsDefault) {
gfx::Insets insets;
EXPECT_EQ(0, insets.top());
EXPECT_EQ(0, insets.left());
EXPECT_EQ(0, insets.bottom());
EXPECT_EQ(0, insets.right());
EXPECT_EQ(0, insets.width());
EXPECT_EQ(0, insets.height());
EXPECT_TRUE(insets.IsEmpty());
}
TEST(InsetsTest, Insets) {
gfx::Insets insets(1, 2, 3, 4);
EXPECT_EQ(1, insets.top());
EXPECT_EQ(2, insets.left());
EXPECT_EQ(3, insets.bottom());
EXPECT_EQ(4, insets.right());
EXPECT_EQ(6, insets.width()); // Left + right.
EXPECT_EQ(4, insets.height()); // Top + bottom.
EXPECT_FALSE(insets.IsEmpty());
}
TEST(InsetsTest, SetTop) {
gfx::Insets insets(1);
insets.set_top(2);
EXPECT_EQ(gfx::Insets(2, 1, 1, 1), insets);
}
TEST(InsetsTest, SetBottom) {
gfx::Insets insets(1);
insets.set_bottom(2);
EXPECT_EQ(gfx::Insets(1, 1, 2, 1), insets);
}
TEST(InsetsTest, SetLeft) {
gfx::Insets insets(1);
insets.set_left(2);
EXPECT_EQ(gfx::Insets(1, 2, 1, 1), insets);
}
TEST(InsetsTest, SetRight) {
gfx::Insets insets(1);
insets.set_right(2);
EXPECT_EQ(gfx::Insets(1, 1, 1, 2), insets);
}
TEST(InsetsTest, Set) {
gfx::Insets insets;
insets.Set(1, 2, 3, 4);
EXPECT_EQ(1, insets.top());
EXPECT_EQ(2, insets.left());
EXPECT_EQ(3, insets.bottom());
EXPECT_EQ(4, insets.right());
}
TEST(InsetsTest, Operators) {
gfx::Insets insets;
insets.Set(1, 2, 3, 4);
insets += gfx::Insets(5, 6, 7, 8);
EXPECT_EQ(6, insets.top());
EXPECT_EQ(8, insets.left());
EXPECT_EQ(10, insets.bottom());
EXPECT_EQ(12, insets.right());
insets -= gfx::Insets(-1, 0, 1, 2);
EXPECT_EQ(7, insets.top());
EXPECT_EQ(8, insets.left());
EXPECT_EQ(9, insets.bottom());
EXPECT_EQ(10, insets.right());
insets = gfx::Insets(10, 10, 10, 10) + gfx::Insets(5, 5, 0, -20);
EXPECT_EQ(15, insets.top());
EXPECT_EQ(15, insets.left());
EXPECT_EQ(10, insets.bottom());
EXPECT_EQ(-10, insets.right());
insets = gfx::Insets(10, 10, 10, 10) - gfx::Insets(5, 5, 0, -20);
EXPECT_EQ(5, insets.top());
EXPECT_EQ(5, insets.left());
EXPECT_EQ(10, insets.bottom());
EXPECT_EQ(30, insets.right());
}
TEST(InsetsFTest, Operators) {
gfx::InsetsF insets;
insets.Set(1.f, 2.5f, 3.3f, 4.1f);
insets += gfx::InsetsF(5.8f, 6.7f, 7.6f, 8.5f);
EXPECT_FLOAT_EQ(6.8f, insets.top());
EXPECT_FLOAT_EQ(9.2f, insets.left());
EXPECT_FLOAT_EQ(10.9f, insets.bottom());
EXPECT_FLOAT_EQ(12.6f, insets.right());
insets -= gfx::InsetsF(-1.f, 0, 1.1f, 2.2f);
EXPECT_FLOAT_EQ(7.8f, insets.top());
EXPECT_FLOAT_EQ(9.2f, insets.left());
EXPECT_FLOAT_EQ(9.8f, insets.bottom());
EXPECT_FLOAT_EQ(10.4f, insets.right());
insets = gfx::InsetsF(10, 10.1f, 10.01f, 10.001f) +
gfx::InsetsF(5.5f, 5.f, 0, -20.2f);
EXPECT_FLOAT_EQ(15.5f, insets.top());
EXPECT_FLOAT_EQ(15.1f, insets.left());
EXPECT_FLOAT_EQ(10.01f, insets.bottom());
EXPECT_FLOAT_EQ(-10.199f, insets.right());
insets = gfx::InsetsF(10, 10.1f, 10.01f, 10.001f) -
gfx::InsetsF(5.5f, 5.f, 0, -20.2f);
EXPECT_FLOAT_EQ(4.5f, insets.top());
EXPECT_FLOAT_EQ(5.1f, insets.left());
EXPECT_FLOAT_EQ(10.01f, insets.bottom());
EXPECT_FLOAT_EQ(30.201f, insets.right());
}
TEST(InsetsTest, Equality) {
gfx::Insets insets1;
insets1.Set(1, 2, 3, 4);
gfx::Insets insets2;
// Test operator== and operator!=.
EXPECT_FALSE(insets1 == insets2);
EXPECT_TRUE(insets1 != insets2);
insets2.Set(1, 2, 3, 4);
EXPECT_TRUE(insets1 == insets2);
EXPECT_FALSE(insets1 != insets2);
}
TEST(InsetsTest, ToString) {
gfx::Insets insets(1, 2, 3, 4);
EXPECT_EQ("1,2,3,4", insets.ToString());
}
TEST(InsetsTest, Offset) {
const gfx::Insets insets(1, 2, 3, 4);
const gfx::Rect rect(5, 6, 7, 8);
const gfx::Vector2d vector(9, 10);
// Whether you inset then offset the rect, offset then inset the rect, or
// offset the insets then apply to the rect, the outcome should be the same.
gfx::Rect inset_first = rect;
inset_first.Inset(insets);
inset_first.Offset(vector);
gfx::Rect offset_first = rect;
offset_first.Offset(vector);
offset_first.Inset(insets);
gfx::Rect inset_by_offset = rect;
inset_by_offset.Inset(insets.Offset(vector));
EXPECT_EQ(inset_first, offset_first);
EXPECT_EQ(inset_by_offset, inset_first);
}
TEST(InsetsTest, Scale) {
gfx::Insets test(10, 5);
test = test.Scale(2.f, 3.f);
EXPECT_EQ(gfx::Insets(30, 10), test);
test = gfx::Insets(7, 3);
test = test.Scale(-2.f, -3.f);
EXPECT_EQ(gfx::Insets(-21, -6), test);
}
TEST(InsetsTest, IntegerOverflow) {
constexpr int int_min = std::numeric_limits<int>::min();
constexpr int int_max = std::numeric_limits<int>::max();
gfx::Insets width_height_test(int_max);
EXPECT_EQ(int_max, width_height_test.width());
EXPECT_EQ(int_max, width_height_test.height());
gfx::Insets plus_test(int_max);
plus_test += gfx::Insets(int_max);
EXPECT_EQ(gfx::Insets(int_max), plus_test);
gfx::Insets negation_test = -gfx::Insets(int_min);
EXPECT_EQ(gfx::Insets(int_max), negation_test);
gfx::Insets scale_test(int_max);
scale_test = scale_test.Scale(2.f, 2.f);
EXPECT_EQ(gfx::Insets(int_max), scale_test);
}
TEST(InsetsTest, IntegerUnderflow) {
constexpr int int_min = std::numeric_limits<int>::min();
constexpr int int_max = std::numeric_limits<int>::max();
gfx::Insets width_height_test = gfx::Insets(int_min);
EXPECT_EQ(int_min, width_height_test.width());
EXPECT_EQ(int_min, width_height_test.height());
gfx::Insets minus_test(int_min);
minus_test -= gfx::Insets(int_max);
EXPECT_EQ(gfx::Insets(int_min), minus_test);
gfx::Insets scale_test = gfx::Insets(int_min);
scale_test = scale_test.Scale(2.f, 2.f);
EXPECT_EQ(gfx::Insets(int_min), scale_test);
}
TEST(InsetsTest, IntegerOverflowSetVariants) {
constexpr int int_max = std::numeric_limits<int>::max();
gfx::Insets set_test(20);
set_test.set_top(int_max);
EXPECT_EQ(int_max, set_test.top());
EXPECT_EQ(0, set_test.bottom());
set_test.set_left(int_max);
EXPECT_EQ(int_max, set_test.left());
EXPECT_EQ(0, set_test.right());
set_test = gfx::Insets(30);
set_test.set_bottom(int_max);
EXPECT_EQ(int_max - 30, set_test.bottom());
EXPECT_EQ(30, set_test.top());
set_test.set_right(int_max);
EXPECT_EQ(int_max - 30, set_test.right());
EXPECT_EQ(30, set_test.left());
}
TEST(InsetsTest, IntegerUnderflowSetVariants) {
constexpr int int_min = std::numeric_limits<int>::min();
gfx::Insets set_test(-20);
set_test.set_top(int_min);
EXPECT_EQ(int_min, set_test.top());
EXPECT_EQ(0, set_test.bottom());
set_test.set_left(int_min);
EXPECT_EQ(int_min, set_test.left());
EXPECT_EQ(0, set_test.right());
set_test = gfx::Insets(-30);
set_test.set_bottom(int_min);
EXPECT_EQ(int_min + 30, set_test.bottom());
EXPECT_EQ(-30, set_test.top());
set_test.set_right(int_min);
EXPECT_EQ(int_min + 30, set_test.right());
EXPECT_EQ(-30, set_test.left());
}
TEST(InsetsTest, IntegerOverflowSet) {
constexpr int int_max = std::numeric_limits<int>::max();
gfx::Insets set_all_test;
set_all_test.Set(10, 20, int_max, int_max);
EXPECT_EQ(gfx::Insets(10, 20, int_max - 10, int_max - 20), set_all_test);
}
TEST(InsetsTest, IntegerOverflowOffset) {
constexpr int int_max = std::numeric_limits<int>::max();
const gfx::Vector2d max_vector(int_max, int_max);
gfx::Insets insets(1, 2, 3, 4);
gfx::Insets offset_test = insets.Offset(max_vector);
EXPECT_EQ(gfx::Insets(int_max, int_max, 3 - int_max, 4 - int_max),
offset_test);
}
TEST(InsetsTest, IntegerUnderflowOffset) {
constexpr int int_min = std::numeric_limits<int>::min();
const gfx::Vector2d min_vector(int_min, int_min);
gfx::Insets insets(-10);
gfx::Insets offset_test = insets.Offset(min_vector);
EXPECT_EQ(gfx::Insets(int_min, int_min, -10 - int_min, -10 - int_min),
offset_test);
}
TEST(InsetsTest, Size) {
gfx::Insets insets(1, 2, 3, 4);
EXPECT_EQ(gfx::Size(6, 4), insets.size());
}

View File

@@ -0,0 +1,105 @@
// Copyright (c) 2012 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/geometry/point.h"
#include "base/strings/stringprintf.h"
#include "build/build_config.h"
#include "ui/gfx/geometry/point_conversions.h"
#include "ui/gfx/geometry/point_f.h"
#if defined(OS_WIN)
#include <windows.h>
#elif defined(OS_IOS)
#include <CoreGraphics/CoreGraphics.h>
#elif defined(OS_APPLE)
#include <ApplicationServices/ApplicationServices.h>
#endif
namespace gfx {
#if defined(OS_WIN)
Point::Point(DWORD point) {
POINTS points = MAKEPOINTS(point);
x_ = points.x;
y_ = points.y;
}
Point::Point(const POINT& point) : x_(point.x), y_(point.y) {
}
Point& Point::operator=(const POINT& point) {
x_ = point.x;
y_ = point.y;
return *this;
}
#elif defined(OS_APPLE)
Point::Point(const CGPoint& point) : x_(point.x), y_(point.y) {
}
#endif
#if defined(OS_WIN)
POINT Point::ToPOINT() const {
POINT p;
p.x = x();
p.y = y();
return p;
}
#elif defined(OS_APPLE)
CGPoint Point::ToCGPoint() const {
return CGPointMake(x(), y());
}
#endif
void Point::SetToMin(const Point& other) {
x_ = x_ <= other.x_ ? x_ : other.x_;
y_ = y_ <= other.y_ ? y_ : other.y_;
}
void Point::SetToMax(const Point& other) {
x_ = x_ >= other.x_ ? x_ : other.x_;
y_ = y_ >= other.y_ ? y_ : other.y_;
}
std::string Point::ToString() const {
return base::StringPrintf("%d,%d", x(), y());
}
Point ScaleToCeiledPoint(const Point& point, float x_scale, float y_scale) {
if (x_scale == 1.f && y_scale == 1.f)
return point;
return ToCeiledPoint(ScalePoint(gfx::PointF(point), x_scale, y_scale));
}
Point ScaleToCeiledPoint(const Point& point, float scale) {
if (scale == 1.f)
return point;
return ToCeiledPoint(ScalePoint(gfx::PointF(point), scale, scale));
}
Point ScaleToFlooredPoint(const Point& point, float x_scale, float y_scale) {
if (x_scale == 1.f && y_scale == 1.f)
return point;
return ToFlooredPoint(ScalePoint(gfx::PointF(point), x_scale, y_scale));
}
Point ScaleToFlooredPoint(const Point& point, float scale) {
if (scale == 1.f)
return point;
return ToFlooredPoint(ScalePoint(gfx::PointF(point), scale, scale));
}
Point ScaleToRoundedPoint(const Point& point, float x_scale, float y_scale) {
if (x_scale == 1.f && y_scale == 1.f)
return point;
return ToRoundedPoint(ScalePoint(gfx::PointF(point), x_scale, y_scale));
}
Point ScaleToRoundedPoint(const Point& point, float scale) {
if (scale == 1.f)
return point;
return ToRoundedPoint(ScalePoint(gfx::PointF(point), scale, scale));
}
} // namespace gfx

View File

@@ -0,0 +1,148 @@
// Copyright (c) 2012 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.
#ifndef UI_GFX_GEOMETRY_POINT_H_
#define UI_GFX_GEOMETRY_POINT_H_
#include <iosfwd>
#include <string>
#include <tuple>
#include "base/numerics/clamped_math.h"
#include "build/build_config.h"
#include "ui/gfx/geometry/geometry_export.h"
#include "ui/gfx/geometry/vector2d.h"
#if defined(OS_WIN)
typedef unsigned long DWORD;
typedef struct tagPOINT POINT;
#elif defined(OS_APPLE)
typedef struct CGPoint CGPoint;
#endif
namespace gfx {
// A point has an x and y coordinate.
class GEOMETRY_EXPORT Point {
public:
constexpr Point() : x_(0), y_(0) {}
constexpr Point(int x, int y) : x_(x), y_(y) {}
#if defined(OS_WIN)
// |point| is a DWORD value that contains a coordinate. The x-coordinate is
// the low-order short and the y-coordinate is the high-order short. This
// value is commonly acquired from GetMessagePos/GetCursorPos.
explicit Point(DWORD point);
explicit Point(const POINT& point);
Point& operator=(const POINT& point);
#elif defined(OS_APPLE)
explicit Point(const CGPoint& point);
#endif
#if defined(OS_WIN)
POINT ToPOINT() const;
#elif defined(OS_APPLE)
CGPoint ToCGPoint() const;
#endif
constexpr int x() const { return x_; }
constexpr int y() const { return y_; }
void set_x(int x) { x_ = x; }
void set_y(int y) { y_ = y; }
void SetPoint(int x, int y) {
x_ = x;
y_ = y;
}
void Offset(int delta_x, int delta_y) {
x_ = base::ClampAdd(x_, delta_x);
y_ = base::ClampAdd(y_, delta_y);
}
void operator+=(const Vector2d& vector) {
x_ = base::ClampAdd(x_, vector.x());
y_ = base::ClampAdd(y_, vector.y());
}
void operator-=(const Vector2d& vector) {
x_ = base::ClampSub(x_, vector.x());
y_ = base::ClampSub(y_, vector.y());
}
void SetToMin(const Point& other);
void SetToMax(const Point& other);
bool IsOrigin() const { return x_ == 0 && y_ == 0; }
Vector2d OffsetFromOrigin() const { return Vector2d(x_, y_); }
// A point is less than another point if its y-value is closer
// to the origin. If the y-values are the same, then point with
// the x-value closer to the origin is considered less than the
// other.
// This comparison is required to use Point in sets, or sorted
// vectors.
bool operator<(const Point& rhs) const {
return std::tie(y_, x_) < std::tie(rhs.y_, rhs.x_);
}
// Returns a string representation of point.
std::string ToString() const;
private:
int x_;
int y_;
};
inline bool operator==(const Point& lhs, const Point& rhs) {
return lhs.x() == rhs.x() && lhs.y() == rhs.y();
}
inline bool operator!=(const Point& lhs, const Point& rhs) {
return !(lhs == rhs);
}
inline Point operator+(const Point& lhs, const Vector2d& rhs) {
Point result(lhs);
result += rhs;
return result;
}
inline Point operator-(const Point& lhs, const Vector2d& rhs) {
Point result(lhs);
result -= rhs;
return result;
}
inline Vector2d operator-(const Point& lhs, const Point& rhs) {
return Vector2d(base::ClampSub(lhs.x(), rhs.x()),
base::ClampSub(lhs.y(), rhs.y()));
}
inline Point PointAtOffsetFromOrigin(const Vector2d& offset_from_origin) {
return Point(offset_from_origin.x(), offset_from_origin.y());
}
// This is declared here for use in gtest-based unit tests but is defined in
// the //ui/gfx:test_support target. Depend on that to use this in your unit
// test. This should not be used in production code - call ToString() instead.
void PrintTo(const Point& point, ::std::ostream* os);
// Helper methods to scale a gfx::Point to a new gfx::Point.
GEOMETRY_EXPORT Point ScaleToCeiledPoint(const Point& point,
float x_scale,
float y_scale);
GEOMETRY_EXPORT Point ScaleToCeiledPoint(const Point& point, float x_scale);
GEOMETRY_EXPORT Point ScaleToFlooredPoint(const Point& point,
float x_scale,
float y_scale);
GEOMETRY_EXPORT Point ScaleToFlooredPoint(const Point& point, float x_scale);
GEOMETRY_EXPORT Point ScaleToRoundedPoint(const Point& point,
float x_scale,
float y_scale);
GEOMETRY_EXPORT Point ScaleToRoundedPoint(const Point& point, float x_scale);
} // namespace gfx
#endif // UI_GFX_GEOMETRY_POINT_H_

View File

@@ -0,0 +1,24 @@
// Copyright (c) 2012 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/geometry/point_conversions.h"
#include "base/numerics/safe_conversions.h"
namespace gfx {
Point ToFlooredPoint(const PointF& point) {
return Point(base::ClampFloor(point.x()), base::ClampFloor(point.y()));
}
Point ToCeiledPoint(const PointF& point) {
return Point(base::ClampCeil(point.x()), base::ClampCeil(point.y()));
}
Point ToRoundedPoint(const PointF& point) {
return Point(base::ClampRound(point.x()), base::ClampRound(point.y()));
}
} // namespace gfx

View File

@@ -0,0 +1,24 @@
// Copyright (c) 2012 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.
#ifndef UI_GFX_GEOMETRY_POINT_CONVERSIONS_H_
#define UI_GFX_GEOMETRY_POINT_CONVERSIONS_H_
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/point_f.h"
namespace gfx {
// Returns a Point with each component from the input PointF floored.
GEOMETRY_EXPORT Point ToFlooredPoint(const PointF& point);
// Returns a Point with each component from the input PointF ceiled.
GEOMETRY_EXPORT Point ToCeiledPoint(const PointF& point);
// Returns a Point with each component from the input PointF rounded.
GEOMETRY_EXPORT Point ToRoundedPoint(const PointF& point);
} // namespace gfx
#endif // UI_GFX_GEOMETRY_POINT_CONVERSIONS_H_

View File

@@ -0,0 +1,32 @@
// Copyright (c) 2012 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/geometry/point_f.h"
#include "base/strings/stringprintf.h"
namespace gfx {
void PointF::SetToMin(const PointF& other) {
x_ = x_ <= other.x_ ? x_ : other.x_;
y_ = y_ <= other.y_ ? y_ : other.y_;
}
void PointF::SetToMax(const PointF& other) {
x_ = x_ >= other.x_ ? x_ : other.x_;
y_ = y_ >= other.y_ ? y_ : other.y_;
}
std::string PointF::ToString() const {
return base::StringPrintf("%f,%f", x(), y());
}
PointF ScalePoint(const PointF& p, float x_scale, float y_scale) {
PointF scaled_p(p);
scaled_p.Scale(x_scale, y_scale);
return scaled_p;
}
} // namespace gfx

View File

@@ -0,0 +1,128 @@
// Copyright (c) 2012 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.
#ifndef UI_GFX_GEOMETRY_POINT_F_H_
#define UI_GFX_GEOMETRY_POINT_F_H_
#include <iosfwd>
#include <string>
#include <tuple>
#include "ui/gfx/geometry/geometry_export.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/vector2d_f.h"
namespace gfx {
// A floating version of gfx::Point.
class GEOMETRY_EXPORT PointF {
public:
constexpr PointF() : x_(0.f), y_(0.f) {}
constexpr PointF(float x, float y) : x_(x), y_(y) {}
constexpr explicit PointF(const Point& p)
: PointF(static_cast<float>(p.x()), static_cast<float>(p.y())) {}
constexpr float x() const { return x_; }
constexpr float y() const { return y_; }
void set_x(float x) { x_ = x; }
void set_y(float y) { y_ = y; }
void SetPoint(float x, float y) {
x_ = x;
y_ = y;
}
void Offset(float delta_x, float delta_y) {
x_ += delta_x;
y_ += delta_y;
}
void operator+=(const Vector2dF& vector) {
x_ += vector.x();
y_ += vector.y();
}
void operator-=(const Vector2dF& vector) {
x_ -= vector.x();
y_ -= vector.y();
}
void SetToMin(const PointF& other);
void SetToMax(const PointF& other);
bool IsOrigin() const { return x_ == 0 && y_ == 0; }
Vector2dF OffsetFromOrigin() const { return Vector2dF(x_, y_); }
// A point is less than another point if its y-value is closer
// to the origin. If the y-values are the same, then point with
// the x-value closer to the origin is considered less than the
// other.
// This comparison is required to use PointF in sets, or sorted
// vectors.
bool operator<(const PointF& rhs) const {
return std::tie(y_, x_) < std::tie(rhs.y_, rhs.x_);
}
void Scale(float scale) {
Scale(scale, scale);
}
void Scale(float x_scale, float y_scale) {
SetPoint(x() * x_scale, y() * y_scale);
}
// Returns a string representation of point.
std::string ToString() const;
private:
float x_;
float y_;
};
inline bool operator==(const PointF& lhs, const PointF& rhs) {
return lhs.x() == rhs.x() && lhs.y() == rhs.y();
}
inline bool operator!=(const PointF& lhs, const PointF& rhs) {
return !(lhs == rhs);
}
inline PointF operator+(const PointF& lhs, const Vector2dF& rhs) {
PointF result(lhs);
result += rhs;
return result;
}
inline PointF operator-(const PointF& lhs, const Vector2dF& rhs) {
PointF result(lhs);
result -= rhs;
return result;
}
inline Vector2dF operator-(const PointF& lhs, const PointF& rhs) {
return Vector2dF(lhs.x() - rhs.x(), lhs.y() - rhs.y());
}
inline PointF PointAtOffsetFromOrigin(const Vector2dF& offset_from_origin) {
return PointF(offset_from_origin.x(), offset_from_origin.y());
}
GEOMETRY_EXPORT PointF ScalePoint(const PointF& p,
float x_scale,
float y_scale);
inline PointF ScalePoint(const PointF& p, float scale) {
return ScalePoint(p, scale, scale);
}
// This is declared here for use in gtest-based unit tests but is defined in
// the //ui/gfx:test_support target. Depend on that to use this in your unit
// test. This should not be used in production code - call ToString() instead.
void PrintTo(const PointF& point, ::std::ostream* os);
} // namespace gfx
#endif // UI_GFX_GEOMETRY_POINT_F_H_

View File

@@ -0,0 +1,236 @@
// Copyright (c) 2012 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 <stddef.h>
#include "base/stl_util.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/point_conversions.h"
#include "ui/gfx/geometry/point_f.h"
namespace gfx {
TEST(PointTest, ToPointF) {
// Check that explicit conversion from integer to float compiles.
Point a(10, 20);
PointF b = PointF(a);
EXPECT_EQ(static_cast<float>(a.x()), b.x());
EXPECT_EQ(static_cast<float>(a.y()), b.y());
}
TEST(PointTest, IsOrigin) {
EXPECT_FALSE(Point(1, 0).IsOrigin());
EXPECT_FALSE(Point(0, 1).IsOrigin());
EXPECT_FALSE(Point(1, 2).IsOrigin());
EXPECT_FALSE(Point(-1, 0).IsOrigin());
EXPECT_FALSE(Point(0, -1).IsOrigin());
EXPECT_FALSE(Point(-1, -2).IsOrigin());
EXPECT_TRUE(Point(0, 0).IsOrigin());
EXPECT_FALSE(PointF(0.1f, 0).IsOrigin());
EXPECT_FALSE(PointF(0, 0.1f).IsOrigin());
EXPECT_FALSE(PointF(0.1f, 2).IsOrigin());
EXPECT_FALSE(PointF(-0.1f, 0).IsOrigin());
EXPECT_FALSE(PointF(0, -0.1f).IsOrigin());
EXPECT_FALSE(PointF(-0.1f, -2).IsOrigin());
EXPECT_TRUE(PointF(0, 0).IsOrigin());
}
TEST(PointTest, VectorArithmetic) {
Point a(1, 5);
Vector2d v1(3, -3);
Vector2d v2(-8, 1);
static const struct {
Point expected;
Point actual;
} tests[] = {
{ Point(4, 2), a + v1 },
{ Point(-2, 8), a - v1 },
{ a, a - v1 + v1 },
{ a, a + v1 - v1 },
{ a, a + Vector2d() },
{ Point(12, 1), a + v1 - v2 },
{ Point(-10, 9), a - v1 + v2 }
};
for (size_t i = 0; i < base::size(tests); ++i)
EXPECT_EQ(tests[i].expected.ToString(), tests[i].actual.ToString());
}
TEST(PointTest, OffsetFromPoint) {
Point a(1, 5);
Point b(-20, 8);
EXPECT_EQ(Vector2d(-20 - 1, 8 - 5).ToString(), (b - a).ToString());
}
TEST(PointTest, ToRoundedPoint) {
EXPECT_EQ(Point(0, 0), ToRoundedPoint(PointF(0, 0)));
EXPECT_EQ(Point(0, 0), ToRoundedPoint(PointF(0.0001f, 0.0001f)));
EXPECT_EQ(Point(0, 0), ToRoundedPoint(PointF(0.4999f, 0.4999f)));
EXPECT_EQ(Point(1, 1), ToRoundedPoint(PointF(0.5f, 0.5f)));
EXPECT_EQ(Point(1, 1), ToRoundedPoint(PointF(0.9999f, 0.9999f)));
EXPECT_EQ(Point(10, 10), ToRoundedPoint(PointF(10, 10)));
EXPECT_EQ(Point(10, 10), ToRoundedPoint(PointF(10.0001f, 10.0001f)));
EXPECT_EQ(Point(10, 10), ToRoundedPoint(PointF(10.4999f, 10.4999f)));
EXPECT_EQ(Point(11, 11), ToRoundedPoint(PointF(10.5f, 10.5f)));
EXPECT_EQ(Point(11, 11), ToRoundedPoint(PointF(10.9999f, 10.9999f)));
EXPECT_EQ(Point(-10, -10), ToRoundedPoint(PointF(-10, -10)));
EXPECT_EQ(Point(-10, -10), ToRoundedPoint(PointF(-10.0001f, -10.0001f)));
EXPECT_EQ(Point(-10, -10), ToRoundedPoint(PointF(-10.4999f, -10.4999f)));
EXPECT_EQ(Point(-11, -11), ToRoundedPoint(PointF(-10.5f, -10.5f)));
EXPECT_EQ(Point(-11, -11), ToRoundedPoint(PointF(-10.9999f, -10.9999f)));
}
TEST(PointTest, Scale) {
EXPECT_EQ(PointF().ToString(), ScalePoint(PointF(), 2).ToString());
EXPECT_EQ(PointF().ToString(), ScalePoint(PointF(), 2, 2).ToString());
EXPECT_EQ(PointF(2, -2).ToString(), ScalePoint(PointF(1, -1), 2).ToString());
EXPECT_EQ(PointF(2, -2).ToString(),
ScalePoint(PointF(1, -1), 2, 2).ToString());
PointF zero;
PointF one(1, -1);
zero.Scale(2);
zero.Scale(3, 1.5);
one.Scale(2);
one.Scale(3, 1.5);
EXPECT_EQ(PointF().ToString(), zero.ToString());
EXPECT_EQ(PointF(6, -3).ToString(), one.ToString());
}
TEST(PointTest, ClampPoint) {
Point a;
a = Point(3, 5);
EXPECT_EQ(Point(3, 5).ToString(), a.ToString());
a.SetToMax(Point(2, 4));
EXPECT_EQ(Point(3, 5).ToString(), a.ToString());
a.SetToMax(Point(3, 5));
EXPECT_EQ(Point(3, 5).ToString(), a.ToString());
a.SetToMax(Point(4, 2));
EXPECT_EQ(Point(4, 5).ToString(), a.ToString());
a.SetToMax(Point(8, 10));
EXPECT_EQ(Point(8, 10).ToString(), a.ToString());
a.SetToMin(Point(9, 11));
EXPECT_EQ(Point(8, 10).ToString(), a.ToString());
a.SetToMin(Point(8, 10));
EXPECT_EQ(Point(8, 10).ToString(), a.ToString());
a.SetToMin(Point(11, 9));
EXPECT_EQ(Point(8, 9).ToString(), a.ToString());
a.SetToMin(Point(7, 11));
EXPECT_EQ(Point(7, 9).ToString(), a.ToString());
a.SetToMin(Point(3, 5));
EXPECT_EQ(Point(3, 5).ToString(), a.ToString());
}
TEST(PointTest, ClampPointF) {
PointF a;
a = PointF(3.5f, 5.5f);
EXPECT_EQ(PointF(3.5f, 5.5f).ToString(), a.ToString());
a.SetToMax(PointF(2.5f, 4.5f));
EXPECT_EQ(PointF(3.5f, 5.5f).ToString(), a.ToString());
a.SetToMax(PointF(3.5f, 5.5f));
EXPECT_EQ(PointF(3.5f, 5.5f).ToString(), a.ToString());
a.SetToMax(PointF(4.5f, 2.5f));
EXPECT_EQ(PointF(4.5f, 5.5f).ToString(), a.ToString());
a.SetToMax(PointF(8.5f, 10.5f));
EXPECT_EQ(PointF(8.5f, 10.5f).ToString(), a.ToString());
a.SetToMin(PointF(9.5f, 11.5f));
EXPECT_EQ(PointF(8.5f, 10.5f).ToString(), a.ToString());
a.SetToMin(PointF(8.5f, 10.5f));
EXPECT_EQ(PointF(8.5f, 10.5f).ToString(), a.ToString());
a.SetToMin(PointF(11.5f, 9.5f));
EXPECT_EQ(PointF(8.5f, 9.5f).ToString(), a.ToString());
a.SetToMin(PointF(7.5f, 11.5f));
EXPECT_EQ(PointF(7.5f, 9.5f).ToString(), a.ToString());
a.SetToMin(PointF(3.5f, 5.5f));
EXPECT_EQ(PointF(3.5f, 5.5f).ToString(), a.ToString());
}
TEST(PointTest, Offset) {
Point test(3, 4);
test.Offset(5, -8);
EXPECT_EQ(test, Point(8, -4));
}
TEST(PointTest, VectorMath) {
Point test = Point(3, 4);
test += Vector2d(5, -8);
EXPECT_EQ(test, Point(8, -4));
Point test2 = Point(3, 4);
test2 -= Vector2d(5, -8);
EXPECT_EQ(test2, Point(-2, 12));
}
TEST(PointTest, IntegerOverflow) {
int int_max = std::numeric_limits<int>::max();
int int_min = std::numeric_limits<int>::min();
Point max_point(int_max, int_max);
Point min_point(int_min, int_min);
Point test;
test = Point();
test.Offset(int_max, int_max);
EXPECT_EQ(test, max_point);
test = Point();
test.Offset(int_min, int_min);
EXPECT_EQ(test, min_point);
test = Point(10, 20);
test.Offset(int_max, int_max);
EXPECT_EQ(test, max_point);
test = Point(-10, -20);
test.Offset(int_min, int_min);
EXPECT_EQ(test, min_point);
test = Point();
test += Vector2d(int_max, int_max);
EXPECT_EQ(test, max_point);
test = Point();
test += Vector2d(int_min, int_min);
EXPECT_EQ(test, min_point);
test = Point(10, 20);
test += Vector2d(int_max, int_max);
EXPECT_EQ(test, max_point);
test = Point(-10, -20);
test += Vector2d(int_min, int_min);
EXPECT_EQ(test, min_point);
test = Point();
test -= Vector2d(int_max, int_max);
EXPECT_EQ(test, Point(-int_max, -int_max));
test = Point();
test -= Vector2d(int_min, int_min);
EXPECT_EQ(test, max_point);
test = Point(10, 20);
test -= Vector2d(int_min, int_min);
EXPECT_EQ(test, max_point);
test = Point(-10, -20);
test -= Vector2d(int_max, int_max);
EXPECT_EQ(test, min_point);
}
} // namespace gfx

View File

@@ -0,0 +1,348 @@
// Copyright (c) 2012 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/geometry/rect.h"
#include <algorithm>
#if defined(OS_WIN)
#include <windows.h>
#elif defined(OS_IOS)
#include <CoreGraphics/CoreGraphics.h>
#elif defined(OS_APPLE)
#include <ApplicationServices/ApplicationServices.h>
#endif
#include "base/check.h"
#include "base/numerics/clamped_math.h"
#include "base/strings/stringprintf.h"
#include "build/build_config.h"
#include "ui/gfx/geometry/insets.h"
namespace gfx {
#if defined(OS_WIN)
Rect::Rect(const RECT& r)
: origin_(r.left, r.top),
size_(std::abs(r.right - r.left), std::abs(r.bottom - r.top)) {
}
#elif defined(OS_APPLE)
Rect::Rect(const CGRect& r)
: origin_(r.origin.x, r.origin.y), size_(r.size.width, r.size.height) {
}
#endif
#if defined(OS_WIN)
RECT Rect::ToRECT() const {
RECT r;
r.left = x();
r.right = right();
r.top = y();
r.bottom = bottom();
return r;
}
#elif defined(OS_APPLE)
CGRect Rect::ToCGRect() const {
return CGRectMake(x(), y(), width(), height());
}
#endif
void AdjustAlongAxis(int dst_origin, int dst_size, int* origin, int* size) {
*size = std::min(dst_size, *size);
if (*origin < dst_origin)
*origin = dst_origin;
else
*origin = std::min(dst_origin + dst_size, *origin + *size) - *size;
}
} // namespace
namespace gfx {
// This is the per-axis heuristic for picking the most useful origin and
// width/height to represent the input range.
static void SaturatedClampRange(int min, int max, int* origin, int* span) {
if (max < min) {
*span = 0;
*origin = min;
return;
}
int effective_span = base::ClampSub(max, min);
int span_loss = base::ClampSub(max, min + effective_span);
// If the desired width is within the limits of ints, we can just
// use the simple computations to represent the range precisely.
if (span_loss == 0) {
*span = effective_span;
*origin = min;
return;
}
// Now we have to approximate. If one of min or max is close enough
// to zero we choose to represent that one precisely. The other side is
// probably practically "infinite", so we move it.
constexpr unsigned kMaxDimension = std::numeric_limits<int>::max() / 2;
if (base::SafeUnsignedAbs(max) < kMaxDimension) {
// Maintain origin + span == max.
*span = effective_span;
*origin = max - effective_span;
} else if (base::SafeUnsignedAbs(min) < kMaxDimension) {
// Maintain origin == min.
*span = effective_span;
*origin = min;
} else {
// Both are big, so keep the center.
*span = effective_span;
*origin = min + span_loss / 2;
}
}
void Rect::SetByBounds(int left, int top, int right, int bottom) {
int x, y;
int width, height;
SaturatedClampRange(left, right, &x, &width);
SaturatedClampRange(top, bottom, &y, &height);
origin_.SetPoint(x, y);
size_.SetSize(width, height);
}
void Rect::Inset(const Insets& insets) {
Inset(insets.left(), insets.top(), insets.right(), insets.bottom());
}
void Rect::Inset(int left, int top, int right, int bottom) {
origin_ += Vector2d(left, top);
// left+right might overflow/underflow, but width() - (left+right) might
// overflow as well.
set_width(base::ClampSub(width(), base::ClampAdd(left, right)));
set_height(base::ClampSub(height(), base::ClampAdd(top, bottom)));
}
void Rect::Offset(int horizontal, int vertical) {
origin_ += Vector2d(horizontal, vertical);
// Ensure that width and height remain valid.
set_width(width());
set_height(height());
}
void Rect::operator+=(const Vector2d& offset) {
origin_ += offset;
// Ensure that width and height remain valid.
set_width(width());
set_height(height());
}
void Rect::operator-=(const Vector2d& offset) {
origin_ -= offset;
}
Insets Rect::InsetsFrom(const Rect& inner) const {
return Insets(inner.y() - y(),
inner.x() - x(),
bottom() - inner.bottom(),
right() - inner.right());
}
bool Rect::operator<(const Rect& other) const {
if (origin_ == other.origin_) {
if (width() == other.width()) {
return height() < other.height();
} else {
return width() < other.width();
}
} else {
return origin_ < other.origin_;
}
}
bool Rect::Contains(int point_x, int point_y) const {
return (point_x >= x()) && (point_x < right()) && (point_y >= y()) &&
(point_y < bottom());
}
bool Rect::Contains(const Rect& rect) const {
return (rect.x() >= x() && rect.right() <= right() && rect.y() >= y() &&
rect.bottom() <= bottom());
}
bool Rect::Intersects(const Rect& rect) const {
return !(IsEmpty() || rect.IsEmpty() || rect.x() >= right() ||
rect.right() <= x() || rect.y() >= bottom() || rect.bottom() <= y());
}
void Rect::Intersect(const Rect& rect) {
if (IsEmpty() || rect.IsEmpty()) {
SetRect(0, 0, 0, 0); // Throws away empty position.
return;
}
int left = std::max(x(), rect.x());
int top = std::max(y(), rect.y());
int new_right = std::min(right(), rect.right());
int new_bottom = std::min(bottom(), rect.bottom());
if (left >= new_right || top >= new_bottom) {
SetRect(0, 0, 0, 0); // Throws away empty position.
return;
}
SetByBounds(left, top, new_right, new_bottom);
}
void Rect::Union(const Rect& rect) {
if (IsEmpty()) {
*this = rect;
return;
}
if (rect.IsEmpty())
return;
SetByBounds(std::min(x(), rect.x()), std::min(y(), rect.y()),
std::max(right(), rect.right()),
std::max(bottom(), rect.bottom()));
}
void Rect::Subtract(const Rect& rect) {
if (!Intersects(rect))
return;
if (rect.Contains(*this)) {
SetRect(0, 0, 0, 0);
return;
}
int rx = x();
int ry = y();
int rr = right();
int rb = bottom();
if (rect.y() <= y() && rect.bottom() >= bottom()) {
// complete intersection in the y-direction
if (rect.x() <= x()) {
rx = rect.right();
} else if (rect.right() >= right()) {
rr = rect.x();
}
} else if (rect.x() <= x() && rect.right() >= right()) {
// complete intersection in the x-direction
if (rect.y() <= y()) {
ry = rect.bottom();
} else if (rect.bottom() >= bottom()) {
rb = rect.y();
}
}
SetByBounds(rx, ry, rr, rb);
}
void Rect::AdjustToFit(const Rect& rect) {
int new_x = x();
int new_y = y();
int new_width = width();
int new_height = height();
AdjustAlongAxis(rect.x(), rect.width(), &new_x, &new_width);
AdjustAlongAxis(rect.y(), rect.height(), &new_y, &new_height);
SetRect(new_x, new_y, new_width, new_height);
}
Point Rect::CenterPoint() const {
return Point(x() + width() / 2, y() + height() / 2);
}
void Rect::ClampToCenteredSize(const Size& size) {
int new_width = std::min(width(), size.width());
int new_height = std::min(height(), size.height());
int new_x = x() + (width() - new_width) / 2;
int new_y = y() + (height() - new_height) / 2;
SetRect(new_x, new_y, new_width, new_height);
}
void Rect::Transpose() {
SetRect(y(), x(), height(), width());
}
void Rect::SplitVertically(Rect* left_half, Rect* right_half) const {
DCHECK(left_half);
DCHECK(right_half);
left_half->SetRect(x(), y(), width() / 2, height());
right_half->SetRect(
left_half->right(), y(), width() - left_half->width(), height());
}
bool Rect::SharesEdgeWith(const Rect& rect) const {
return (y() == rect.y() && height() == rect.height() &&
(x() == rect.right() || right() == rect.x())) ||
(x() == rect.x() && width() == rect.width() &&
(y() == rect.bottom() || bottom() == rect.y()));
}
int Rect::ManhattanDistanceToPoint(const Point& point) const {
int x_distance =
std::max<int>(0, std::max(x() - point.x(), point.x() - right()));
int y_distance =
std::max<int>(0, std::max(y() - point.y(), point.y() - bottom()));
return x_distance + y_distance;
}
int Rect::ManhattanInternalDistance(const Rect& rect) const {
Rect c(*this);
c.Union(rect);
int x = std::max(0, c.width() - width() - rect.width() + 1);
int y = std::max(0, c.height() - height() - rect.height() + 1);
return x + y;
}
std::string Rect::ToString() const {
return base::StringPrintf("%s %s",
origin().ToString().c_str(),
size().ToString().c_str());
}
bool Rect::ApproximatelyEqual(const Rect& rect, int tolerance) const {
return std::abs(x() - rect.x()) <= tolerance &&
std::abs(y() - rect.y()) <= tolerance &&
std::abs(right() - rect.right()) <= tolerance &&
std::abs(bottom() - rect.bottom()) <= tolerance;
}
Rect operator+(const Rect& lhs, const Vector2d& rhs) {
Rect result(lhs);
result += rhs;
return result;
}
Rect operator-(const Rect& lhs, const Vector2d& rhs) {
Rect result(lhs);
result -= rhs;
return result;
}
Rect IntersectRects(const Rect& a, const Rect& b) {
Rect result = a;
result.Intersect(b);
return result;
}
Rect UnionRects(const Rect& a, const Rect& b) {
Rect result = a;
result.Union(b);
return result;
}
Rect SubtractRects(const Rect& a, const Rect& b) {
Rect result = a;
result.Subtract(b);
return result;
}
Rect BoundingRect(const Point& p1, const Point& p2) {
Rect result;
result.SetByBounds(std::min(p1.x(), p2.x()), std::min(p1.y(), p2.y()),
std::max(p1.x(), p2.x()), std::max(p1.y(), p2.y()));
return result;
}
} // namespace gfx

View File

@@ -0,0 +1,401 @@
// Copyright (c) 2012 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.
// Defines a simple integer rectangle class. The containment semantics
// are array-like; that is, the coordinate (x, y) is considered to be
// contained by the rectangle, but the coordinate (x + width, y) is not.
// The class will happily let you create malformed rectangles (that is,
// rectangles with negative width and/or height), but there will be assertions
// in the operations (such as Contains()) to complain in this case.
#ifndef UI_GFX_GEOMETRY_RECT_H_
#define UI_GFX_GEOMETRY_RECT_H_
#include <cmath>
#include <iosfwd>
#include <string>
#include "base/check.h"
#include "base/numerics/safe_conversions.h"
#include "build/build_config.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/geometry/vector2d.h"
#if defined(OS_WIN)
typedef struct tagRECT RECT;
#elif defined(OS_APPLE)
typedef struct CGRect CGRect;
#endif
namespace gfx {
class Insets;
class GEOMETRY_EXPORT Rect {
public:
constexpr Rect() = default;
constexpr Rect(int width, int height) : size_(width, height) {}
constexpr Rect(int x, int y, int width, int height)
: origin_(x, y),
size_(GetClampedValue(x, width), GetClampedValue(y, height)) {}
constexpr explicit Rect(const Size& size) : size_(size) {}
constexpr Rect(const Point& origin, const Size& size)
: origin_(origin),
size_(GetClampedValue(origin.x(), size.width()),
GetClampedValue(origin.y(), size.height())) {}
#if defined(OS_WIN)
explicit Rect(const RECT& r);
#elif defined(OS_APPLE)
explicit Rect(const CGRect& r);
#endif
#if defined(OS_WIN)
// Construct an equivalent Win32 RECT object.
RECT ToRECT() const;
#elif defined(OS_APPLE)
// Construct an equivalent CoreGraphics object.
CGRect ToCGRect() const;
#endif
constexpr int x() const { return origin_.x(); }
// Sets the X position while preserving the width.
void set_x(int x) {
origin_.set_x(x);
size_.set_width(GetClampedValue(x, width()));
}
constexpr int y() const { return origin_.y(); }
// Sets the Y position while preserving the height.
void set_y(int y) {
origin_.set_y(y);
size_.set_height(GetClampedValue(y, height()));
}
constexpr int width() const { return size_.width(); }
void set_width(int width) { size_.set_width(GetClampedValue(x(), width)); }
constexpr int height() const { return size_.height(); }
void set_height(int height) {
size_.set_height(GetClampedValue(y(), height));
}
constexpr const Point& origin() const { return origin_; }
void set_origin(const Point& origin) {
origin_ = origin;
// Ensure that width and height remain valid.
set_width(width());
set_height(height());
}
constexpr const Size& size() const { return size_; }
void set_size(const Size& size) {
set_width(size.width());
set_height(size.height());
}
constexpr int right() const { return x() + width(); }
constexpr int bottom() const { return y() + height(); }
constexpr Point top_right() const { return Point(right(), y()); }
constexpr Point bottom_left() const { return Point(x(), bottom()); }
constexpr Point bottom_right() const { return Point(right(), bottom()); }
constexpr Point left_center() const { return Point(x(), y() + height() / 2); }
constexpr Point top_center() const { return Point(x() + width() / 2, y()); }
constexpr Point right_center() const {
return Point(right(), y() + height() / 2);
}
constexpr Point bottom_center() const {
return Point(x() + width() / 2, bottom());
}
Vector2d OffsetFromOrigin() const { return Vector2d(x(), y()); }
void SetRect(int x, int y, int width, int height) {
origin_.SetPoint(x, y);
// Ensure that width and height remain valid.
set_width(width);
set_height(height);
}
// Use in place of SetRect() when you know the edges of the rectangle instead
// of the dimensions, rather than trying to determine the width/height
// yourself. This safely handles cases where the width/height would overflow.
void SetByBounds(int left, int top, int right, int bottom);
// Shrink the rectangle by a horizontal and vertical distance on all sides.
void Inset(int horizontal, int vertical) {
Inset(horizontal, vertical, horizontal, vertical);
}
// Shrink the rectangle by the given insets.
void Inset(const Insets& insets);
// Shrink the rectangle by the specified amount on each side.
void Inset(int left, int top, int right, int bottom);
// Move the rectangle by a horizontal and vertical distance.
void Offset(int horizontal, int vertical);
void Offset(const Vector2d& distance) { Offset(distance.x(), distance.y()); }
void operator+=(const Vector2d& offset);
void operator-=(const Vector2d& offset);
Insets InsetsFrom(const Rect& inner) const;
// Returns true if the area of the rectangle is zero.
bool IsEmpty() const { return size_.IsEmpty(); }
// A rect is less than another rect if its origin is less than
// the other rect's origin. If the origins are equal, then the
// shortest rect is less than the other. If the origin and the
// height are equal, then the narrowest rect is less than.
// This comparison is required to use Rects in sets, or sorted
// vectors.
bool operator<(const Rect& other) const;
// Returns true if the point identified by point_x and point_y falls inside
// this rectangle. The point (x, y) is inside the rectangle, but the
// point (x + width, y + height) is not.
bool Contains(int point_x, int point_y) const;
// Returns true if the specified point is contained by this rectangle.
bool Contains(const Point& point) const {
return Contains(point.x(), point.y());
}
// Returns true if this rectangle contains the specified rectangle.
bool Contains(const Rect& rect) const;
// Returns true if this rectangle intersects the specified rectangle.
// An empty rectangle doesn't intersect any rectangle.
bool Intersects(const Rect& rect) const;
// Computes the intersection of this rectangle with the given rectangle.
void Intersect(const Rect& rect);
// Computes the union of this rectangle with the given rectangle. The union
// is the smallest rectangle containing both rectangles.
void Union(const Rect& rect);
// Computes the rectangle resulting from subtracting |rect| from |*this|,
// i.e. the bounding rect of |Region(*this) - Region(rect)|.
void Subtract(const Rect& rect);
// Fits as much of the receiving rectangle into the supplied rectangle as
// possible, becoming the result. For example, if the receiver had
// a x-location of 2 and a width of 4, and the supplied rectangle had
// an x-location of 0 with a width of 5, the returned rectangle would have
// an x-location of 1 with a width of 4.
void AdjustToFit(const Rect& rect);
// Returns the center of this rectangle.
Point CenterPoint() const;
// Becomes a rectangle that has the same center point but with a size capped
// at given |size|.
void ClampToCenteredSize(const Size& size);
// Transpose x and y axis.
void Transpose();
// Splits |this| in two halves, |left_half| and |right_half|.
void SplitVertically(Rect* left_half, Rect* right_half) const;
// Returns true if this rectangle shares an entire edge (i.e., same width or
// same height) with the given rectangle, and the rectangles do not overlap.
bool SharesEdgeWith(const Rect& rect) const;
// Returns the manhattan distance from the rect to the point. If the point is
// inside the rect, returns 0.
int ManhattanDistanceToPoint(const Point& point) const;
// Returns the manhattan distance between the contents of this rect and the
// contents of the given rect. That is, if the intersection of the two rects
// is non-empty then the function returns 0. If the rects share a side, it
// returns the smallest non-zero value appropriate for int.
int ManhattanInternalDistance(const Rect& rect) const;
std::string ToString() const;
bool ApproximatelyEqual(const Rect& rect, int tolerance) const;
private:
gfx::Point origin_;
gfx::Size size_;
// Returns true iff a+b would overflow max int.
static constexpr bool AddWouldOverflow(int a, int b) {
// In this function, GCC tries to make optimizations that would only work if
// max - a wouldn't overflow but it isn't smart enough to notice that a > 0.
// So cast everything to unsigned to avoid this. As it is guaranteed that
// max - a and b are both already positive, the cast is a noop.
//
// This is intended to be: a > 0 && max - a < b
return a > 0 && b > 0 &&
static_cast<unsigned>(std::numeric_limits<int>::max() - a) <
static_cast<unsigned>(b);
}
// Clamp the size to avoid integer overflow in bottom() and right().
// This returns the width given an origin and a width.
// TODO(enne): this should probably use base::ClampAdd, but that
// function is not a constexpr.
static constexpr int GetClampedValue(int origin, int size) {
return AddWouldOverflow(origin, size)
? std::numeric_limits<int>::max() - origin
: size;
}
};
inline bool operator==(const Rect& lhs, const Rect& rhs) {
return lhs.origin() == rhs.origin() && lhs.size() == rhs.size();
}
inline bool operator!=(const Rect& lhs, const Rect& rhs) {
return !(lhs == rhs);
}
GEOMETRY_EXPORT Rect operator+(const Rect& lhs, const Vector2d& rhs);
GEOMETRY_EXPORT Rect operator-(const Rect& lhs, const Vector2d& rhs);
inline Rect operator+(const Vector2d& lhs, const Rect& rhs) {
return rhs + lhs;
}
GEOMETRY_EXPORT Rect IntersectRects(const Rect& a, const Rect& b);
GEOMETRY_EXPORT Rect UnionRects(const Rect& a, const Rect& b);
GEOMETRY_EXPORT Rect SubtractRects(const Rect& a, const Rect& b);
// Constructs a rectangle with |p1| and |p2| as opposite corners.
//
// This could also be thought of as "the smallest rect that contains both
// points", except that we consider points on the right/bottom edges of the
// rect to be outside the rect. So technically one or both points will not be
// contained within the rect, because they will appear on one of these edges.
GEOMETRY_EXPORT Rect BoundingRect(const Point& p1, const Point& p2);
// Scales the rect and returns the enclosing rect. Use this only the inputs are
// known to not overflow. Use ScaleToEnclosingRectSafe if the inputs are
// unknown and need to use saturated math.
inline Rect ScaleToEnclosingRect(const Rect& rect,
float x_scale,
float y_scale) {
if (x_scale == 1.f && y_scale == 1.f)
return rect;
// These next functions cast instead of using e.g. base::ClampFloor() because
// we haven't checked to ensure that the clamping behavior of the helper
// functions doesn't degrade performance, and callers shouldn't be passing
// values that cause overflow anyway.
DCHECK(base::IsValueInRangeForNumericType<int>(
std::floor(rect.x() * x_scale)));
DCHECK(base::IsValueInRangeForNumericType<int>(
std::floor(rect.y() * y_scale)));
DCHECK(base::IsValueInRangeForNumericType<int>(
std::ceil(rect.right() * x_scale)));
DCHECK(base::IsValueInRangeForNumericType<int>(
std::ceil(rect.bottom() * y_scale)));
int x = static_cast<int>(std::floor(rect.x() * x_scale));
int y = static_cast<int>(std::floor(rect.y() * y_scale));
int r = rect.width() == 0 ?
x : static_cast<int>(std::ceil(rect.right() * x_scale));
int b = rect.height() == 0 ?
y : static_cast<int>(std::ceil(rect.bottom() * y_scale));
return Rect(x, y, r - x, b - y);
}
inline Rect ScaleToEnclosingRect(const Rect& rect, float scale) {
return ScaleToEnclosingRect(rect, scale, scale);
}
// ScaleToEnclosingRect but clamping instead of asserting if the resulting rect
// would overflow.
// TODO(pkasting): Attempt to switch ScaleTo...Rect() to this construction and
// check performance.
inline Rect ScaleToEnclosingRectSafe(const Rect& rect,
float x_scale,
float y_scale) {
if (x_scale == 1.f && y_scale == 1.f)
return rect;
int x = base::ClampFloor(rect.x() * x_scale);
int y = base::ClampFloor(rect.y() * y_scale);
int w = base::ClampCeil(rect.width() * x_scale);
int h = base::ClampCeil(rect.height() * y_scale);
return Rect(x, y, w, h);
}
inline Rect ScaleToEnclosingRectSafe(const Rect& rect, float scale) {
return ScaleToEnclosingRectSafe(rect, scale, scale);
}
inline Rect ScaleToEnclosedRect(const Rect& rect,
float x_scale,
float y_scale) {
if (x_scale == 1.f && y_scale == 1.f)
return rect;
DCHECK(base::IsValueInRangeForNumericType<int>(
std::ceil(rect.x() * x_scale)));
DCHECK(base::IsValueInRangeForNumericType<int>(
std::ceil(rect.y() * y_scale)));
DCHECK(base::IsValueInRangeForNumericType<int>(
std::floor(rect.right() * x_scale)));
DCHECK(base::IsValueInRangeForNumericType<int>(
std::floor(rect.bottom() * y_scale)));
int x = static_cast<int>(std::ceil(rect.x() * x_scale));
int y = static_cast<int>(std::ceil(rect.y() * y_scale));
int r = rect.width() == 0 ?
x : static_cast<int>(std::floor(rect.right() * x_scale));
int b = rect.height() == 0 ?
y : static_cast<int>(std::floor(rect.bottom() * y_scale));
return Rect(x, y, r - x, b - y);
}
inline Rect ScaleToEnclosedRect(const Rect& rect, float scale) {
return ScaleToEnclosedRect(rect, scale, scale);
}
// Scales |rect| by scaling its four corner points. If the corner points lie on
// non-integral coordinate after scaling, their values are rounded to the
// nearest integer.
// This is helpful during layout when relative positions of multiple gfx::Rect
// in a given coordinate space needs to be same after scaling as it was before
// scaling. ie. this gives a lossless relative positioning of rects.
inline Rect ScaleToRoundedRect(const Rect& rect, float x_scale, float y_scale) {
if (x_scale == 1.f && y_scale == 1.f)
return rect;
DCHECK(
base::IsValueInRangeForNumericType<int>(std::round(rect.x() * x_scale)));
DCHECK(
base::IsValueInRangeForNumericType<int>(std::round(rect.y() * y_scale)));
DCHECK(base::IsValueInRangeForNumericType<int>(
std::round(rect.right() * x_scale)));
DCHECK(base::IsValueInRangeForNumericType<int>(
std::round(rect.bottom() * y_scale)));
int x = static_cast<int>(std::round(rect.x() * x_scale));
int y = static_cast<int>(std::round(rect.y() * y_scale));
int r = rect.width() == 0
? x
: static_cast<int>(std::round(rect.right() * x_scale));
int b = rect.height() == 0
? y
: static_cast<int>(std::round(rect.bottom() * y_scale));
return Rect(x, y, r - x, b - y);
}
inline Rect ScaleToRoundedRect(const Rect& rect, float scale) {
return ScaleToRoundedRect(rect, scale, scale);
}
// This is declared here for use in gtest-based unit tests but is defined in
// the //ui/gfx:test_support target. Depend on that to use this in your unit
// test. This should not be used in production code - call ToString() instead.
void PrintTo(const Rect& rect, ::std::ostream* os);
} // namespace gfx
#endif // UI_GFX_GEOMETRY_RECT_H_

View File

@@ -0,0 +1,126 @@
// Copyright (c) 2012 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/geometry/rect_conversions.h"
#include <algorithm>
#include <cmath>
#include "base/check.h"
#include "base/numerics/safe_conversions.h"
namespace gfx {
namespace {
int FloorIgnoringError(float f, float error) {
int rounded = base::ClampRound(f);
return std::abs(rounded - f) < error ? rounded : base::ClampFloor(f);
}
int CeilIgnoringError(float f, float error) {
int rounded = base::ClampRound(f);
return std::abs(rounded - f) < error ? rounded : base::ClampCeil(f);
}
} // anonymous namespace
Rect ToEnclosingRect(const RectF& r) {
int left = base::ClampFloor(r.x());
int right = r.width() ? base::ClampCeil(r.right()) : left;
int top = base::ClampFloor(r.y());
int bottom = r.height() ? base::ClampCeil(r.bottom()) : top;
Rect result;
result.SetByBounds(left, top, right, bottom);
return result;
}
Rect ToEnclosingRectIgnoringError(const RectF& r, float error) {
int left = FloorIgnoringError(r.x(), error);
int right = r.width() ? CeilIgnoringError(r.right(), error) : left;
int top = FloorIgnoringError(r.y(), error);
int bottom = r.height() ? CeilIgnoringError(r.bottom(), error) : top;
Rect result;
result.SetByBounds(left, top, right, bottom);
return result;
}
Rect ToEnclosedRect(const RectF& rect) {
Rect result;
result.SetByBounds(base::ClampCeil(rect.x()), base::ClampCeil(rect.y()),
base::ClampFloor(rect.right()),
base::ClampFloor(rect.bottom()));
return result;
}
Rect ToEnclosedRectIgnoringError(const RectF& r, float error) {
int left = CeilIgnoringError(r.x(), error);
int right = r.width() ? FloorIgnoringError(r.right(), error) : left;
int top = CeilIgnoringError(r.y(), error);
int bottom = r.height() ? FloorIgnoringError(r.bottom(), error) : top;
Rect result;
result.SetByBounds(left, top, right, bottom);
return result;
}
Rect ToNearestRect(const RectF& rect) {
float float_min_x = rect.x();
float float_min_y = rect.y();
float float_max_x = rect.right();
float float_max_y = rect.bottom();
int min_x = base::ClampRound(float_min_x);
int min_y = base::ClampRound(float_min_y);
int max_x = base::ClampRound(float_max_x);
int max_y = base::ClampRound(float_max_y);
// If these DCHECKs fail, you're using the wrong method, consider using
// ToEnclosingRect or ToEnclosedRect instead.
DCHECK(std::abs(min_x - float_min_x) < 0.01f);
DCHECK(std::abs(min_y - float_min_y) < 0.01f);
DCHECK(std::abs(max_x - float_max_x) < 0.01f);
DCHECK(std::abs(max_y - float_max_y) < 0.01f);
Rect result;
result.SetByBounds(min_x, min_y, max_x, max_y);
return result;
}
bool IsNearestRectWithinDistance(const gfx::RectF& rect, float distance) {
float float_min_x = rect.x();
float float_min_y = rect.y();
float float_max_x = rect.right();
float float_max_y = rect.bottom();
int min_x = base::ClampRound(float_min_x);
int min_y = base::ClampRound(float_min_y);
int max_x = base::ClampRound(float_max_x);
int max_y = base::ClampRound(float_max_y);
return (std::abs(min_x - float_min_x) < distance) &&
(std::abs(min_y - float_min_y) < distance) &&
(std::abs(max_x - float_max_x) < distance) &&
(std::abs(max_y - float_max_y) < distance);
}
gfx::Rect ToRoundedRect(const gfx::RectF& rect) {
int left = base::ClampRound(rect.x());
int top = base::ClampRound(rect.y());
int right = base::ClampRound(rect.right());
int bottom = base::ClampRound(rect.bottom());
gfx::Rect result;
result.SetByBounds(left, top, right, bottom);
return result;
}
Rect ToFlooredRectDeprecated(const RectF& rect) {
return Rect(base::ClampFloor(rect.x()), base::ClampFloor(rect.y()),
base::ClampFloor(rect.width()), base::ClampFloor(rect.height()));
}
} // namespace gfx

View File

@@ -0,0 +1,55 @@
// Copyright (c) 2012 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.
#ifndef UI_GFX_GEOMETRY_RECT_CONVERSIONS_H_
#define UI_GFX_GEOMETRY_RECT_CONVERSIONS_H_
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/rect_f.h"
namespace gfx {
// Returns the smallest Rect that encloses the given RectF.
GEOMETRY_EXPORT Rect ToEnclosingRect(const RectF& rect);
// Similar to ToEnclosingRect(), but for each edge, if the distance between the
// edge and the nearest integer grid is smaller than |error|, the edge is
// snapped to the integer grid. Unlike ToNearestRect() which only accepts
// integer rect with or without floating point error, this function also accepts
// non-integer rect.
GEOMETRY_EXPORT Rect ToEnclosingRectIgnoringError(const RectF& rect,
float error);
// Returns the largest Rect that is enclosed by the given RectF.
GEOMETRY_EXPORT Rect ToEnclosedRect(const RectF& rect);
// Similar to ToEnclosedRect(), but for each edge, if the distance between the
// edge and the nearest integer grid is smaller than |error|, the edge is
// snapped to the integer grid. Unlike ToNearestRect() which only accepts
// integer rect with or without floating point error, this function also accepts
// non-integer rect.
GEOMETRY_EXPORT Rect ToEnclosedRectIgnoringError(const RectF& rect,
float error);
// Returns the Rect after snapping the corners of the RectF to an integer grid.
// This should only be used when the RectF you provide is expected to be an
// integer rect with floating point error. If it is an arbitrary RectF, then
// you should use a different method.
GEOMETRY_EXPORT Rect ToNearestRect(const RectF& rect);
// Returns true if the Rect produced after snapping the corners of the RectF
// to an integer grid is withing |distance|.
GEOMETRY_EXPORT bool IsNearestRectWithinDistance(const gfx::RectF& rect,
float distance);
// Returns the Rect after rounding the corners of the RectF to an integer grid.
GEOMETRY_EXPORT gfx::Rect ToRoundedRect(const gfx::RectF& rect);
// Returns a Rect obtained by flooring the values of the given RectF.
// Please prefer the previous two functions in new code.
GEOMETRY_EXPORT Rect ToFlooredRectDeprecated(const RectF& rect);
} // namespace gfx
#endif // UI_GFX_GEOMETRY_RECT_CONVERSIONS_H_

View File

@@ -0,0 +1,266 @@
// Copyright (c) 2012 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/geometry/rect_f.h"
#include <algorithm>
#include <limits>
#include "base/check.h"
#include "base/numerics/safe_conversions.h"
#include "base/strings/stringprintf.h"
#include "build/build_config.h"
#include "ui/gfx/geometry/insets_f.h"
#if defined(OS_IOS)
#include <CoreGraphics/CoreGraphics.h>
#elif defined(OS_APPLE)
#include <ApplicationServices/ApplicationServices.h>
#endif
namespace gfx {
static void AdjustAlongAxis(float dst_origin,
float dst_size,
float* origin,
float* size) {
*size = std::min(dst_size, *size);
if (*origin < dst_origin)
*origin = dst_origin;
else
*origin = std::min(dst_origin + dst_size, *origin + *size) - *size;
}
#if defined(OS_APPLE)
RectF::RectF(const CGRect& r)
: origin_(r.origin.x, r.origin.y), size_(r.size.width, r.size.height) {
}
CGRect RectF::ToCGRect() const {
return CGRectMake(x(), y(), width(), height());
}
#endif
void RectF::Inset(const InsetsF& insets) {
Inset(insets.left(), insets.top(), insets.right(), insets.bottom());
}
void RectF::Inset(float left, float top, float right, float bottom) {
origin_ += Vector2dF(left, top);
set_width(std::max(width() - left - right, 0.0f));
set_height(std::max(height() - top - bottom, 0.0f));
}
void RectF::Offset(float horizontal, float vertical) {
origin_ += Vector2dF(horizontal, vertical);
}
void RectF::operator+=(const Vector2dF& offset) {
origin_ += offset;
}
void RectF::operator-=(const Vector2dF& offset) {
origin_ -= offset;
}
InsetsF RectF::InsetsFrom(const RectF& inner) const {
return InsetsF(inner.y() - y(),
inner.x() - x(),
bottom() - inner.bottom(),
right() - inner.right());
}
bool RectF::operator<(const RectF& other) const {
if (origin_ != other.origin_)
return origin_ < other.origin_;
if (width() == other.width())
return height() < other.height();
return width() < other.width();
}
bool RectF::Contains(float point_x, float point_y) const {
return point_x >= x() && point_x < right() && point_y >= y() &&
point_y < bottom();
}
bool RectF::Contains(const RectF& rect) const {
return rect.x() >= x() && rect.right() <= right() && rect.y() >= y() &&
rect.bottom() <= bottom();
}
bool RectF::Intersects(const RectF& rect) const {
return !IsEmpty() && !rect.IsEmpty() && rect.x() < right() &&
rect.right() > x() && rect.y() < bottom() && rect.bottom() > y();
}
void RectF::Intersect(const RectF& rect) {
if (IsEmpty() || rect.IsEmpty()) {
SetRect(0, 0, 0, 0);
return;
}
float rx = std::max(x(), rect.x());
float ry = std::max(y(), rect.y());
float rr = std::min(right(), rect.right());
float rb = std::min(bottom(), rect.bottom());
if (rx >= rr || ry >= rb) {
SetRect(0, 0, 0, 0);
return;
}
SetRect(rx, ry, rr - rx, rb - ry);
}
void RectF::Union(const RectF& rect) {
if (IsEmpty()) {
*this = rect;
return;
}
if (rect.IsEmpty())
return;
float rx = std::min(x(), rect.x());
float ry = std::min(y(), rect.y());
float rr = std::max(right(), rect.right());
float rb = std::max(bottom(), rect.bottom());
SetRect(rx, ry, rr - rx, rb - ry);
}
void RectF::Subtract(const RectF& rect) {
if (!Intersects(rect))
return;
if (rect.Contains(*this)) {
SetRect(0, 0, 0, 0);
return;
}
float rx = x();
float ry = y();
float rr = right();
float rb = bottom();
if (rect.y() <= y() && rect.bottom() >= bottom()) {
// complete intersection in the y-direction
if (rect.x() <= x()) {
rx = rect.right();
} else if (rect.right() >= right()) {
rr = rect.x();
}
} else if (rect.x() <= x() && rect.right() >= right()) {
// complete intersection in the x-direction
if (rect.y() <= y()) {
ry = rect.bottom();
} else if (rect.bottom() >= bottom()) {
rb = rect.y();
}
}
SetRect(rx, ry, rr - rx, rb - ry);
}
void RectF::AdjustToFit(const RectF& rect) {
float new_x = x();
float new_y = y();
float new_width = width();
float new_height = height();
AdjustAlongAxis(rect.x(), rect.width(), &new_x, &new_width);
AdjustAlongAxis(rect.y(), rect.height(), &new_y, &new_height);
SetRect(new_x, new_y, new_width, new_height);
}
PointF RectF::CenterPoint() const {
return PointF(x() + width() / 2, y() + height() / 2);
}
void RectF::ClampToCenteredSize(const SizeF& size) {
float new_width = std::min(width(), size.width());
float new_height = std::min(height(), size.height());
float new_x = x() + (width() - new_width) / 2;
float new_y = y() + (height() - new_height) / 2;
SetRect(new_x, new_y, new_width, new_height);
}
void RectF::Transpose() {
SetRect(y(), x(), height(), width());
}
void RectF::SplitVertically(RectF* left_half, RectF* right_half) const {
DCHECK(left_half);
DCHECK(right_half);
left_half->SetRect(x(), y(), width() / 2, height());
right_half->SetRect(
left_half->right(), y(), width() - left_half->width(), height());
}
bool RectF::SharesEdgeWith(const RectF& rect) const {
return (y() == rect.y() && height() == rect.height() &&
(x() == rect.right() || right() == rect.x())) ||
(x() == rect.x() && width() == rect.width() &&
(y() == rect.bottom() || bottom() == rect.y()));
}
float RectF::ManhattanDistanceToPoint(const PointF& point) const {
float x_distance =
std::max<float>(0, std::max(x() - point.x(), point.x() - right()));
float y_distance =
std::max<float>(0, std::max(y() - point.y(), point.y() - bottom()));
return x_distance + y_distance;
}
float RectF::ManhattanInternalDistance(const RectF& rect) const {
RectF c(*this);
c.Union(rect);
static constexpr float kEpsilon = std::numeric_limits<float>::epsilon();
float x = std::max(0.f, c.width() - width() - rect.width() + kEpsilon);
float y = std::max(0.f, c.height() - height() - rect.height() + kEpsilon);
return x + y;
}
bool RectF::IsExpressibleAsRect() const {
return base::IsValueInRangeForNumericType<int>(x()) &&
base::IsValueInRangeForNumericType<int>(y()) &&
base::IsValueInRangeForNumericType<int>(width()) &&
base::IsValueInRangeForNumericType<int>(height()) &&
base::IsValueInRangeForNumericType<int>(right()) &&
base::IsValueInRangeForNumericType<int>(bottom());
}
std::string RectF::ToString() const {
return base::StringPrintf("%s %s",
origin().ToString().c_str(),
size().ToString().c_str());
}
RectF IntersectRects(const RectF& a, const RectF& b) {
RectF result = a;
result.Intersect(b);
return result;
}
RectF UnionRects(const RectF& a, const RectF& b) {
RectF result = a;
result.Union(b);
return result;
}
RectF SubtractRects(const RectF& a, const RectF& b) {
RectF result = a;
result.Subtract(b);
return result;
}
RectF BoundingRect(const PointF& p1, const PointF& p2) {
float rx = std::min(p1.x(), p2.x());
float ry = std::min(p1.y(), p2.y());
float rr = std::max(p1.x(), p2.x());
float rb = std::max(p1.y(), p2.y());
return RectF(rx, ry, rr - rx, rb - ry);
}
} // namespace gfx

View File

@@ -0,0 +1,256 @@
// Copyright (c) 2012 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.
#ifndef UI_GFX_GEOMETRY_RECT_F_H_
#define UI_GFX_GEOMETRY_RECT_F_H_
#include <iosfwd>
#include <string>
#include "build/build_config.h"
#include "ui/gfx/geometry/point_f.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/size_f.h"
#include "ui/gfx/geometry/vector2d_f.h"
#if defined(OS_APPLE)
typedef struct CGRect CGRect;
#endif
namespace gfx {
class InsetsF;
// A floating version of gfx::Rect.
class GEOMETRY_EXPORT RectF {
public:
constexpr RectF() = default;
constexpr RectF(float width, float height) : size_(width, height) {}
constexpr RectF(float x, float y, float width, float height)
: origin_(x, y), size_(width, height) {}
constexpr explicit RectF(const SizeF& size) : size_(size) {}
constexpr RectF(const PointF& origin, const SizeF& size)
: origin_(origin), size_(size) {}
constexpr explicit RectF(const Rect& r)
: RectF(static_cast<float>(r.x()),
static_cast<float>(r.y()),
static_cast<float>(r.width()),
static_cast<float>(r.height())) {}
#if defined(OS_APPLE)
explicit RectF(const CGRect& r);
// Construct an equivalent CoreGraphics object.
CGRect ToCGRect() const;
#endif
constexpr float x() const { return origin_.x(); }
void set_x(float x) { origin_.set_x(x); }
constexpr float y() const { return origin_.y(); }
void set_y(float y) { origin_.set_y(y); }
constexpr float width() const { return size_.width(); }
void set_width(float width) { size_.set_width(width); }
constexpr float height() const { return size_.height(); }
void set_height(float height) { size_.set_height(height); }
constexpr const PointF& origin() const { return origin_; }
void set_origin(const PointF& origin) { origin_ = origin; }
constexpr const SizeF& size() const { return size_; }
void set_size(const SizeF& size) { size_ = size; }
constexpr float right() const { return x() + width(); }
constexpr float bottom() const { return y() + height(); }
constexpr PointF top_right() const { return PointF(right(), y()); }
constexpr PointF bottom_left() const { return PointF(x(), bottom()); }
constexpr PointF bottom_right() const { return PointF(right(), bottom()); }
constexpr PointF left_center() const {
return PointF(x(), y() + height() / 2);
}
constexpr PointF top_center() const { return PointF(x() + width() / 2, y()); }
constexpr PointF right_center() const {
return PointF(right(), y() + height() / 2);
}
constexpr PointF bottom_center() const {
return PointF(x() + width() / 2, bottom());
}
Vector2dF OffsetFromOrigin() const { return Vector2dF(x(), y()); }
void SetRect(float x, float y, float width, float height) {
origin_.SetPoint(x, y);
size_.SetSize(width, height);
}
// Shrink the rectangle by a horizontal and vertical distance on all sides.
void Inset(float horizontal, float vertical) {
Inset(horizontal, vertical, horizontal, vertical);
}
// Shrink the rectangle by the given insets.
void Inset(const InsetsF& insets);
// Shrink the rectangle by the specified amount on each side.
void Inset(float left, float top, float right, float bottom);
// Move the rectangle by a horizontal and vertical distance.
void Offset(float horizontal, float vertical);
void Offset(const Vector2dF& distance) { Offset(distance.x(), distance.y()); }
void operator+=(const Vector2dF& offset);
void operator-=(const Vector2dF& offset);
InsetsF InsetsFrom(const RectF& inner) const;
// Returns true if the area of the rectangle is zero.
bool IsEmpty() const { return size_.IsEmpty(); }
// A rect is less than another rect if its origin is less than
// the other rect's origin. If the origins are equal, then the
// shortest rect is less than the other. If the origin and the
// height are equal, then the narrowest rect is less than.
// This comparison is required to use Rects in sets, or sorted
// vectors.
bool operator<(const RectF& other) const;
// Returns true if the point identified by point_x and point_y falls inside
// this rectangle. The point (x, y) is inside the rectangle, but the
// point (x + width, y + height) is not.
bool Contains(float point_x, float point_y) const;
// Returns true if the specified point is contained by this rectangle.
bool Contains(const PointF& point) const {
return Contains(point.x(), point.y());
}
// Returns true if this rectangle contains the specified rectangle.
bool Contains(const RectF& rect) const;
// Returns true if this rectangle intersects the specified rectangle.
// An empty rectangle doesn't intersect any rectangle.
bool Intersects(const RectF& rect) const;
// Computes the intersection of this rectangle with the given rectangle.
void Intersect(const RectF& rect);
// Computes the union of this rectangle with the given rectangle. The union
// is the smallest rectangle containing both rectangles.
void Union(const RectF& rect);
// Computes the rectangle resulting from subtracting |rect| from |*this|,
// i.e. the bounding rect of |Region(*this) - Region(rect)|.
void Subtract(const RectF& rect);
// Fits as much of the receiving rectangle into the supplied rectangle as
// possible, becoming the result. For example, if the receiver had
// a x-location of 2 and a width of 4, and the supplied rectangle had
// an x-location of 0 with a width of 5, the returned rectangle would have
// an x-location of 1 with a width of 4.
void AdjustToFit(const RectF& rect);
// Returns the center of this rectangle.
PointF CenterPoint() const;
// Becomes a rectangle that has the same center point but with a size capped
// at given |size|.
void ClampToCenteredSize(const SizeF& size);
// Transpose x and y axis.
void Transpose();
// Splits |this| in two halves, |left_half| and |right_half|.
void SplitVertically(RectF* left_half, RectF* right_half) const;
// Returns true if this rectangle shares an entire edge (i.e., same width or
// same height) with the given rectangle, and the rectangles do not overlap.
bool SharesEdgeWith(const RectF& rect) const;
// Returns the manhattan distance from the rect to the point. If the point is
// inside the rect, returns 0.
float ManhattanDistanceToPoint(const PointF& point) const;
// Returns the manhattan distance between the contents of this rect and the
// contents of the given rect. That is, if the intersection of the two rects
// is non-empty then the function returns 0. If the rects share a side, it
// returns the smallest non-zero value appropriate for float.
float ManhattanInternalDistance(const RectF& rect) const;
// Scales the rectangle by |scale|.
void Scale(float scale) {
Scale(scale, scale);
}
void Scale(float x_scale, float y_scale) {
set_origin(ScalePoint(origin(), x_scale, y_scale));
set_size(ScaleSize(size(), x_scale, y_scale));
}
// This method reports if the RectF can be safely converted to an integer
// Rect. When it is false, some dimension of the RectF is outside the bounds
// of what an integer can represent, and converting it to a Rect will require
// clamping.
bool IsExpressibleAsRect() const;
std::string ToString() const;
private:
PointF origin_;
SizeF size_;
};
inline bool operator==(const RectF& lhs, const RectF& rhs) {
return lhs.origin() == rhs.origin() && lhs.size() == rhs.size();
}
inline bool operator!=(const RectF& lhs, const RectF& rhs) {
return !(lhs == rhs);
}
inline RectF operator+(const RectF& lhs, const Vector2dF& rhs) {
return RectF(lhs.x() + rhs.x(), lhs.y() + rhs.y(),
lhs.width(), lhs.height());
}
inline RectF operator-(const RectF& lhs, const Vector2dF& rhs) {
return RectF(lhs.x() - rhs.x(), lhs.y() - rhs.y(),
lhs.width(), lhs.height());
}
inline RectF operator+(const Vector2dF& lhs, const RectF& rhs) {
return rhs + lhs;
}
GEOMETRY_EXPORT RectF IntersectRects(const RectF& a, const RectF& b);
GEOMETRY_EXPORT RectF UnionRects(const RectF& a, const RectF& b);
GEOMETRY_EXPORT RectF SubtractRects(const RectF& a, const RectF& b);
inline RectF ScaleRect(const RectF& r, float x_scale, float y_scale) {
return RectF(r.x() * x_scale, r.y() * y_scale,
r.width() * x_scale, r.height() * y_scale);
}
inline RectF ScaleRect(const RectF& r, float scale) {
return ScaleRect(r, scale, scale);
}
// Constructs a rectangle with |p1| and |p2| as opposite corners.
//
// This could also be thought of as "the smallest rect that contains both
// points", except that we consider points on the right/bottom edges of the
// rect to be outside the rect. So technically one or both points will not be
// contained within the rect, because they will appear on one of these edges.
GEOMETRY_EXPORT RectF BoundingRect(const PointF& p1, const PointF& p2);
// This is declared here for use in gtest-based unit tests but is defined in
// the //ui/gfx:test_support target. Depend on that to use this in your unit
// test. This should not be used in production code - call ToString() instead.
void PrintTo(const RectF& rect, ::std::ostream* os);
} // namespace gfx
#endif // UI_GFX_GEOMETRY_RECT_F_H_

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,122 @@
// Copyright (c) 2012 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/geometry/size.h"
#if defined(OS_WIN)
#include <windows.h>
#elif defined(OS_IOS)
#include <CoreGraphics/CoreGraphics.h>
#elif defined(OS_APPLE)
#include <ApplicationServices/ApplicationServices.h>
#endif
#include "base/numerics/clamped_math.h"
#include "base/numerics/safe_math.h"
#include "base/strings/stringprintf.h"
#include "build/build_config.h"
#include "ui/gfx/geometry/size_conversions.h"
namespace gfx {
#if defined(OS_APPLE)
Size::Size(const CGSize& s)
: width_(s.width < 0 ? 0 : s.width),
height_(s.height < 0 ? 0 : s.height) {
}
Size& Size::operator=(const CGSize& s) {
set_width(s.width);
set_height(s.height);
return *this;
}
#endif
void Size::operator+=(const Size& size) {
Enlarge(size.width(), size.height());
}
void Size::operator-=(const Size& size) {
Enlarge(-size.width(), -size.height());
}
#if defined(OS_WIN)
SIZE Size::ToSIZE() const {
SIZE s;
s.cx = width();
s.cy = height();
return s;
}
#elif defined(OS_APPLE)
CGSize Size::ToCGSize() const {
return CGSizeMake(width(), height());
}
#endif
int Size::GetArea() const {
return GetCheckedArea().ValueOrDie();
}
base::CheckedNumeric<int> Size::GetCheckedArea() const {
base::CheckedNumeric<int> checked_area = width();
checked_area *= height();
return checked_area;
}
void Size::Enlarge(int grow_width, int grow_height) {
SetSize(base::ClampAdd(width(), grow_width),
base::ClampAdd(height(), grow_height));
}
void Size::SetToMin(const Size& other) {
width_ = width() <= other.width() ? width() : other.width();
height_ = height() <= other.height() ? height() : other.height();
}
void Size::SetToMax(const Size& other) {
width_ = width() >= other.width() ? width() : other.width();
height_ = height() >= other.height() ? height() : other.height();
}
std::string Size::ToString() const {
return base::StringPrintf("%dx%d", width(), height());
}
Size ScaleToCeiledSize(const Size& size, float x_scale, float y_scale) {
if (x_scale == 1.f && y_scale == 1.f)
return size;
return ToCeiledSize(ScaleSize(gfx::SizeF(size), x_scale, y_scale));
}
Size ScaleToCeiledSize(const Size& size, float scale) {
if (scale == 1.f)
return size;
return ToCeiledSize(ScaleSize(gfx::SizeF(size), scale, scale));
}
Size ScaleToFlooredSize(const Size& size, float x_scale, float y_scale) {
if (x_scale == 1.f && y_scale == 1.f)
return size;
return ToFlooredSize(ScaleSize(gfx::SizeF(size), x_scale, y_scale));
}
Size ScaleToFlooredSize(const Size& size, float scale) {
if (scale == 1.f)
return size;
return ToFlooredSize(ScaleSize(gfx::SizeF(size), scale, scale));
}
Size ScaleToRoundedSize(const Size& size, float x_scale, float y_scale) {
if (x_scale == 1.f && y_scale == 1.f)
return size;
return ToRoundedSize(ScaleSize(gfx::SizeF(size), x_scale, y_scale));
}
Size ScaleToRoundedSize(const Size& size, float scale) {
if (scale == 1.f)
return size;
return ToRoundedSize(ScaleSize(gfx::SizeF(size), scale, scale));
}
} // namespace gfx

View File

@@ -0,0 +1,118 @@
// Copyright (c) 2012 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.
#ifndef UI_GFX_GEOMETRY_SIZE_H_
#define UI_GFX_GEOMETRY_SIZE_H_
#include <algorithm>
#include <iosfwd>
#include <string>
#include "base/compiler_specific.h"
#include "base/numerics/safe_math.h"
#include "build/build_config.h"
#include "ui/gfx/geometry/geometry_export.h"
#if defined(OS_WIN)
typedef struct tagSIZE SIZE;
#elif defined(OS_APPLE)
typedef struct CGSize CGSize;
#endif
namespace gfx {
// A size has width and height values.
class GEOMETRY_EXPORT Size {
public:
constexpr Size() : width_(0), height_(0) {}
constexpr Size(int width, int height)
: width_(std::max(0, width)), height_(std::max(0, height)) {}
#if defined(OS_APPLE)
explicit Size(const CGSize& s);
#endif
#if defined(OS_APPLE)
Size& operator=(const CGSize& s);
#endif
void operator+=(const Size& size);
void operator-=(const Size& size);
#if defined(OS_WIN)
SIZE ToSIZE() const;
#elif defined(OS_APPLE)
CGSize ToCGSize() const;
#endif
constexpr int width() const { return width_; }
constexpr int height() const { return height_; }
void set_width(int width) { width_ = std::max(0, width); }
void set_height(int height) { height_ = std::max(0, height); }
// This call will CHECK if the area of this size would overflow int.
int GetArea() const;
// Returns a checked numeric representation of the area.
base::CheckedNumeric<int> GetCheckedArea() const;
void SetSize(int width, int height) {
set_width(width);
set_height(height);
}
void Enlarge(int grow_width, int grow_height);
void SetToMin(const Size& other);
void SetToMax(const Size& other);
bool IsEmpty() const { return !width() || !height(); }
std::string ToString() const;
private:
int width_;
int height_;
};
inline bool operator==(const Size& lhs, const Size& rhs) {
return lhs.width() == rhs.width() && lhs.height() == rhs.height();
}
inline bool operator!=(const Size& lhs, const Size& rhs) {
return !(lhs == rhs);
}
inline Size operator+(Size lhs, const Size& rhs) {
lhs += rhs;
return lhs;
}
inline Size operator-(Size lhs, const Size& rhs) {
lhs -= rhs;
return lhs;
}
// This is declared here for use in gtest-based unit tests but is defined in
// the //ui/gfx:test_support target. Depend on that to use this in your unit
// test. This should not be used in production code - call ToString() instead.
void PrintTo(const Size& size, ::std::ostream* os);
// Helper methods to scale a gfx::Size to a new gfx::Size.
GEOMETRY_EXPORT Size ScaleToCeiledSize(const Size& size,
float x_scale,
float y_scale);
GEOMETRY_EXPORT Size ScaleToCeiledSize(const Size& size, float scale);
GEOMETRY_EXPORT Size ScaleToFlooredSize(const Size& size,
float x_scale,
float y_scale);
GEOMETRY_EXPORT Size ScaleToFlooredSize(const Size& size, float scale);
GEOMETRY_EXPORT Size ScaleToRoundedSize(const Size& size,
float x_scale,
float y_scale);
GEOMETRY_EXPORT Size ScaleToRoundedSize(const Size& size, float scale);
} // namespace gfx
#endif // UI_GFX_GEOMETRY_SIZE_H_

View File

@@ -0,0 +1,24 @@
// Copyright (c) 2012 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/geometry/size_conversions.h"
#include "base/numerics/safe_conversions.h"
namespace gfx {
Size ToFlooredSize(const SizeF& size) {
return Size(base::ClampFloor(size.width()), base::ClampFloor(size.height()));
}
Size ToCeiledSize(const SizeF& size) {
return Size(base::ClampCeil(size.width()), base::ClampCeil(size.height()));
}
Size ToRoundedSize(const SizeF& size) {
return Size(base::ClampRound(size.width()), base::ClampRound(size.height()));
}
} // namespace gfx

View File

@@ -0,0 +1,24 @@
// Copyright (c) 2012 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.
#ifndef UI_GFX_GEOMETRY_SIZE_CONVERSIONS_H_
#define UI_GFX_GEOMETRY_SIZE_CONVERSIONS_H_
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/geometry/size_f.h"
namespace gfx {
// Returns a Size with each component from the input SizeF floored.
GEOMETRY_EXPORT Size ToFlooredSize(const SizeF& size);
// Returns a Size with each component from the input SizeF ceiled.
GEOMETRY_EXPORT Size ToCeiledSize(const SizeF& size);
// Returns a Size with each component from the input SizeF rounded.
GEOMETRY_EXPORT Size ToRoundedSize(const SizeF& size);
} // namespace gfx
#endif // UI_GFX_GEOMETRY_SIZE_CONVERSIONS_H_

View File

@@ -0,0 +1,39 @@
// Copyright (c) 2012 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/geometry/size_f.h"
#include "base/strings/stringprintf.h"
namespace gfx {
float SizeF::GetArea() const {
return width() * height();
}
void SizeF::Enlarge(float grow_width, float grow_height) {
SetSize(width() + grow_width, height() + grow_height);
}
void SizeF::SetToMin(const SizeF& other) {
width_ = width() <= other.width() ? width() : other.width();
height_ = height() <= other.height() ? height() : other.height();
}
void SizeF::SetToMax(const SizeF& other) {
width_ = width() >= other.width() ? width() : other.width();
height_ = height() >= other.height() ? height() : other.height();
}
std::string SizeF::ToString() const {
return base::StringPrintf("%fx%f", width(), height());
}
SizeF ScaleSize(const SizeF& s, float x_scale, float y_scale) {
SizeF scaled_s(s);
scaled_s.Scale(x_scale, y_scale);
return scaled_s;
}
} // namespace gfx

View File

@@ -0,0 +1,97 @@
// Copyright (c) 2012 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.
#ifndef UI_GFX_GEOMETRY_SIZE_F_H_
#define UI_GFX_GEOMETRY_SIZE_F_H_
#include <iosfwd>
#include <string>
#include "base/compiler_specific.h"
#include "base/gtest_prod_util.h"
#include "ui/gfx/geometry/geometry_export.h"
#include "ui/gfx/geometry/size.h"
namespace gfx {
FORWARD_DECLARE_TEST(SizeTest, TrivialDimensionTests);
FORWARD_DECLARE_TEST(SizeTest, ClampsToZero);
FORWARD_DECLARE_TEST(SizeTest, ConsistentClamping);
// A floating version of gfx::Size.
class GEOMETRY_EXPORT SizeF {
public:
constexpr SizeF() : width_(0.f), height_(0.f) {}
constexpr SizeF(float width, float height)
: width_(clamp(width)), height_(clamp(height)) {}
constexpr explicit SizeF(const Size& size)
: SizeF(static_cast<float>(size.width()),
static_cast<float>(size.height())) {}
constexpr float width() const { return width_; }
constexpr float height() const { return height_; }
void set_width(float width) { width_ = clamp(width); }
void set_height(float height) { height_ = clamp(height); }
float GetArea() const;
void SetSize(float width, float height) {
set_width(width);
set_height(height);
}
void Enlarge(float grow_width, float grow_height);
void SetToMin(const SizeF& other);
void SetToMax(const SizeF& other);
bool IsEmpty() const { return !width() || !height(); }
void Scale(float scale) {
Scale(scale, scale);
}
void Scale(float x_scale, float y_scale) {
SetSize(width() * x_scale, height() * y_scale);
}
std::string ToString() const;
private:
FRIEND_TEST_ALL_PREFIXES(SizeTest, TrivialDimensionTests);
FRIEND_TEST_ALL_PREFIXES(SizeTest, ClampsToZero);
FRIEND_TEST_ALL_PREFIXES(SizeTest, ConsistentClamping);
static constexpr float kTrivial = 8.f * std::numeric_limits<float>::epsilon();
static constexpr float clamp(float f) { return f > kTrivial ? f : 0.f; }
float width_;
float height_;
};
inline bool operator==(const SizeF& lhs, const SizeF& rhs) {
return lhs.width() == rhs.width() && lhs.height() == rhs.height();
}
inline bool operator!=(const SizeF& lhs, const SizeF& rhs) {
return !(lhs == rhs);
}
GEOMETRY_EXPORT SizeF ScaleSize(const SizeF& p, float x_scale, float y_scale);
inline SizeF ScaleSize(const SizeF& p, float scale) {
return ScaleSize(p, scale, scale);
}
// This is declared here for use in gtest-based unit tests but is defined in
// the //ui/gfx:test_support target. Depend on that to use this in your unit
// test. This should not be used in production code - call ToString() instead.
void PrintTo(const SizeF& size, ::std::ostream* os);
} // namespace gfx
#endif // UI_GFX_GEOMETRY_SIZE_F_H_

View File

@@ -0,0 +1,300 @@
// Copyright (c) 2012 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 "testing/gtest/include/gtest/gtest.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/geometry/size_conversions.h"
#include "ui/gfx/geometry/size_f.h"
namespace gfx {
namespace {
int TestSizeF(const SizeF& s) {
return s.width();
}
} // namespace
TEST(SizeTest, ToSizeF) {
// Check that explicit conversion from integer to float compiles.
Size a(10, 20);
float width = TestSizeF(gfx::SizeF(a));
EXPECT_EQ(width, a.width());
SizeF b(10, 20);
EXPECT_EQ(b, gfx::SizeF(a));
}
TEST(SizeTest, ToFlooredSize) {
EXPECT_EQ(Size(0, 0), ToFlooredSize(SizeF(0, 0)));
EXPECT_EQ(Size(0, 0), ToFlooredSize(SizeF(0.0001f, 0.0001f)));
EXPECT_EQ(Size(0, 0), ToFlooredSize(SizeF(0.4999f, 0.4999f)));
EXPECT_EQ(Size(0, 0), ToFlooredSize(SizeF(0.5f, 0.5f)));
EXPECT_EQ(Size(0, 0), ToFlooredSize(SizeF(0.9999f, 0.9999f)));
EXPECT_EQ(Size(10, 10), ToFlooredSize(SizeF(10, 10)));
EXPECT_EQ(Size(10, 10), ToFlooredSize(SizeF(10.0001f, 10.0001f)));
EXPECT_EQ(Size(10, 10), ToFlooredSize(SizeF(10.4999f, 10.4999f)));
EXPECT_EQ(Size(10, 10), ToFlooredSize(SizeF(10.5f, 10.5f)));
EXPECT_EQ(Size(10, 10), ToFlooredSize(SizeF(10.9999f, 10.9999f)));
}
TEST(SizeTest, ToCeiledSize) {
EXPECT_EQ(Size(0, 0), ToCeiledSize(SizeF(0, 0)));
EXPECT_EQ(Size(1, 1), ToCeiledSize(SizeF(0.0001f, 0.0001f)));
EXPECT_EQ(Size(1, 1), ToCeiledSize(SizeF(0.4999f, 0.4999f)));
EXPECT_EQ(Size(1, 1), ToCeiledSize(SizeF(0.5f, 0.5f)));
EXPECT_EQ(Size(1, 1), ToCeiledSize(SizeF(0.9999f, 0.9999f)));
EXPECT_EQ(Size(10, 10), ToCeiledSize(SizeF(10, 10)));
EXPECT_EQ(Size(11, 11), ToCeiledSize(SizeF(10.0001f, 10.0001f)));
EXPECT_EQ(Size(11, 11), ToCeiledSize(SizeF(10.4999f, 10.4999f)));
EXPECT_EQ(Size(11, 11), ToCeiledSize(SizeF(10.5f, 10.5f)));
EXPECT_EQ(Size(11, 11), ToCeiledSize(SizeF(10.9999f, 10.9999f)));
}
TEST(SizeTest, ToRoundedSize) {
EXPECT_EQ(Size(0, 0), ToRoundedSize(SizeF(0, 0)));
EXPECT_EQ(Size(0, 0), ToRoundedSize(SizeF(0.0001f, 0.0001f)));
EXPECT_EQ(Size(0, 0), ToRoundedSize(SizeF(0.4999f, 0.4999f)));
EXPECT_EQ(Size(1, 1), ToRoundedSize(SizeF(0.5f, 0.5f)));
EXPECT_EQ(Size(1, 1), ToRoundedSize(SizeF(0.9999f, 0.9999f)));
EXPECT_EQ(Size(10, 10), ToRoundedSize(SizeF(10, 10)));
EXPECT_EQ(Size(10, 10), ToRoundedSize(SizeF(10.0001f, 10.0001f)));
EXPECT_EQ(Size(10, 10), ToRoundedSize(SizeF(10.4999f, 10.4999f)));
EXPECT_EQ(Size(11, 11), ToRoundedSize(SizeF(10.5f, 10.5f)));
EXPECT_EQ(Size(11, 11), ToRoundedSize(SizeF(10.9999f, 10.9999f)));
}
TEST(SizeTest, ClampSize) {
Size a;
a = Size(3, 5);
EXPECT_EQ(Size(3, 5).ToString(), a.ToString());
a.SetToMax(Size(2, 4));
EXPECT_EQ(Size(3, 5).ToString(), a.ToString());
a.SetToMax(Size(3, 5));
EXPECT_EQ(Size(3, 5).ToString(), a.ToString());
a.SetToMax(Size(4, 2));
EXPECT_EQ(Size(4, 5).ToString(), a.ToString());
a.SetToMax(Size(8, 10));
EXPECT_EQ(Size(8, 10).ToString(), a.ToString());
a.SetToMin(Size(9, 11));
EXPECT_EQ(Size(8, 10).ToString(), a.ToString());
a.SetToMin(Size(8, 10));
EXPECT_EQ(Size(8, 10).ToString(), a.ToString());
a.SetToMin(Size(11, 9));
EXPECT_EQ(Size(8, 9).ToString(), a.ToString());
a.SetToMin(Size(7, 11));
EXPECT_EQ(Size(7, 9).ToString(), a.ToString());
a.SetToMin(Size(3, 5));
EXPECT_EQ(Size(3, 5).ToString(), a.ToString());
}
TEST(SizeTest, ClampSizeF) {
SizeF a;
a = SizeF(3.5f, 5.5f);
EXPECT_EQ(SizeF(3.5f, 5.5f).ToString(), a.ToString());
a.SetToMax(SizeF(2.5f, 4.5f));
EXPECT_EQ(SizeF(3.5f, 5.5f).ToString(), a.ToString());
a.SetToMax(SizeF(3.5f, 5.5f));
EXPECT_EQ(SizeF(3.5f, 5.5f).ToString(), a.ToString());
a.SetToMax(SizeF(4.5f, 2.5f));
EXPECT_EQ(SizeF(4.5f, 5.5f).ToString(), a.ToString());
a.SetToMax(SizeF(8.5f, 10.5f));
EXPECT_EQ(SizeF(8.5f, 10.5f).ToString(), a.ToString());
a.SetToMin(SizeF(9.5f, 11.5f));
EXPECT_EQ(SizeF(8.5f, 10.5f).ToString(), a.ToString());
a.SetToMin(SizeF(8.5f, 10.5f));
EXPECT_EQ(SizeF(8.5f, 10.5f).ToString(), a.ToString());
a.SetToMin(SizeF(11.5f, 9.5f));
EXPECT_EQ(SizeF(8.5f, 9.5f).ToString(), a.ToString());
a.SetToMin(SizeF(7.5f, 11.5f));
EXPECT_EQ(SizeF(7.5f, 9.5f).ToString(), a.ToString());
a.SetToMin(SizeF(3.5f, 5.5f));
EXPECT_EQ(SizeF(3.5f, 5.5f).ToString(), a.ToString());
}
TEST(SizeTest, Enlarge) {
Size test(3, 4);
test.Enlarge(5, -8);
EXPECT_EQ(test, Size(8, -4));
}
TEST(SizeTest, IntegerOverflow) {
int int_max = std::numeric_limits<int>::max();
int int_min = std::numeric_limits<int>::min();
Size max_size(int_max, int_max);
Size min_size(int_min, int_min);
Size test;
test = Size();
test.Enlarge(int_max, int_max);
EXPECT_EQ(test, max_size);
test = Size();
test.Enlarge(int_min, int_min);
EXPECT_EQ(test, min_size);
test = Size(10, 20);
test.Enlarge(int_max, int_max);
EXPECT_EQ(test, max_size);
test = Size(-10, -20);
test.Enlarge(int_min, int_min);
EXPECT_EQ(test, min_size);
}
// This checks that we set IsEmpty appropriately.
TEST(SizeTest, TrivialDimensionTests) {
const float clearly_trivial = SizeF::kTrivial / 2.f;
const float massize_dimension = 4e13f;
// First, using the constructor.
EXPECT_TRUE(SizeF(clearly_trivial, 1.f).IsEmpty());
EXPECT_TRUE(SizeF(.01f, clearly_trivial).IsEmpty());
EXPECT_TRUE(SizeF(0.f, 0.f).IsEmpty());
EXPECT_FALSE(SizeF(.01f, .01f).IsEmpty());
// Then use the setter.
SizeF test(2.f, 1.f);
EXPECT_FALSE(test.IsEmpty());
test.SetSize(clearly_trivial, 1.f);
EXPECT_TRUE(test.IsEmpty());
test.SetSize(.01f, clearly_trivial);
EXPECT_TRUE(test.IsEmpty());
test.SetSize(0.f, 0.f);
EXPECT_TRUE(test.IsEmpty());
test.SetSize(.01f, .01f);
EXPECT_FALSE(test.IsEmpty());
// Now just one dimension at a time.
test.set_width(clearly_trivial);
EXPECT_TRUE(test.IsEmpty());
test.set_width(massize_dimension);
test.set_height(clearly_trivial);
EXPECT_TRUE(test.IsEmpty());
test.set_width(clearly_trivial);
test.set_height(massize_dimension);
EXPECT_TRUE(test.IsEmpty());
test.set_width(2.f);
EXPECT_FALSE(test.IsEmpty());
}
// These are the ramifications of the decision to keep the recorded size
// at zero for trivial sizes.
TEST(SizeTest, ClampsToZero) {
const float clearly_trivial = SizeF::kTrivial / 2.f;
const float nearly_trivial = SizeF::kTrivial * 1.5f;
SizeF test(clearly_trivial, 1.f);
EXPECT_FLOAT_EQ(0.f, test.width());
EXPECT_FLOAT_EQ(1.f, test.height());
test.SetSize(.01f, clearly_trivial);
EXPECT_FLOAT_EQ(.01f, test.width());
EXPECT_FLOAT_EQ(0.f, test.height());
test.SetSize(nearly_trivial, nearly_trivial);
EXPECT_FLOAT_EQ(nearly_trivial, test.width());
EXPECT_FLOAT_EQ(nearly_trivial, test.height());
test.Scale(0.5f);
EXPECT_FLOAT_EQ(0.f, test.width());
EXPECT_FLOAT_EQ(0.f, test.height());
test.SetSize(0.f, 0.f);
test.Enlarge(clearly_trivial, clearly_trivial);
test.Enlarge(clearly_trivial, clearly_trivial);
test.Enlarge(clearly_trivial, clearly_trivial);
EXPECT_EQ(SizeF(0.f, 0.f), test);
}
// These make sure the constructor and setter have the same effect on the
// boundary case. This claims to know the boundary, but not which way it goes.
TEST(SizeTest, ConsistentClamping) {
SizeF resized;
resized.SetSize(SizeF::kTrivial, 0.f);
EXPECT_EQ(SizeF(SizeF::kTrivial, 0.f), resized);
resized.SetSize(0.f, SizeF::kTrivial);
EXPECT_EQ(SizeF(0.f, SizeF::kTrivial), resized);
}
// Let's make sure we don't unexpectedly grow the struct by adding constants.
// Also, if some platform packs floats inefficiently, it would be worth noting.
TEST(SizeTest, StaysSmall) {
EXPECT_EQ(2 * sizeof(float), sizeof(SizeF));
}
TEST(SizeTest, OperatorAddSub) {
Size lhs(100, 20);
Size rhs(50, 10);
lhs += rhs;
EXPECT_EQ(Size(150, 30), lhs);
lhs = Size(100, 20);
EXPECT_EQ(Size(150, 30), lhs + rhs);
lhs = Size(100, 20);
lhs -= rhs;
EXPECT_EQ(Size(50, 10), lhs);
lhs = Size(100, 20);
EXPECT_EQ(Size(50, 10), lhs - rhs);
}
TEST(SizeTest, OperatorAddOverflow) {
int int_max = std::numeric_limits<int>::max();
Size lhs(int_max, int_max);
Size rhs(int_max, int_max);
EXPECT_EQ(Size(int_max, int_max), lhs + rhs);
}
TEST(SizeTest, OperatorSubClampAtZero) {
Size lhs(10, 10);
Size rhs(100, 100);
EXPECT_EQ(Size(0, 0), lhs - rhs);
lhs = Size(10, 10);
rhs = Size(100, 100);
lhs -= rhs;
EXPECT_EQ(Size(0, 0), lhs);
}
TEST(SizeTest, OperatorCompare) {
Size lhs(100, 20);
Size rhs(50, 10);
EXPECT_TRUE(lhs != rhs);
EXPECT_FALSE(lhs == rhs);
rhs = Size(100, 20);
EXPECT_TRUE(lhs == rhs);
EXPECT_FALSE(lhs != rhs);
}
} // namespace gfx

View File

@@ -0,0 +1,40 @@
// Copyright (c) 2012 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/geometry/vector2d.h"
#include <cmath>
#include "base/numerics/clamped_math.h"
#include "base/strings/stringprintf.h"
namespace gfx {
bool Vector2d::IsZero() const {
return x_ == 0 && y_ == 0;
}
void Vector2d::Add(const Vector2d& other) {
x_ = base::ClampAdd(other.x_, x_);
y_ = base::ClampAdd(other.y_, y_);
}
void Vector2d::Subtract(const Vector2d& other) {
x_ = base::ClampSub(x_, other.x_);
y_ = base::ClampSub(y_, other.y_);
}
int64_t Vector2d::LengthSquared() const {
return static_cast<int64_t>(x_) * x_ + static_cast<int64_t>(y_) * y_;
}
float Vector2d::Length() const {
return static_cast<float>(std::sqrt(static_cast<double>(LengthSquared())));
}
std::string Vector2d::ToString() const {
return base::StringPrintf("[%d %d]", x_, y_);
}
} // namespace gfx

View File

@@ -0,0 +1,99 @@
// Copyright (c) 2012 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.
// Defines a simple integer vector class. This class is used to indicate a
// distance in two dimensions between two points. Subtracting two points should
// produce a vector, and adding a vector to a point produces the point at the
// vector's distance from the original point.
#ifndef UI_GFX_GEOMETRY_VECTOR2D_H_
#define UI_GFX_GEOMETRY_VECTOR2D_H_
#include <stdint.h>
#include <iosfwd>
#include <string>
#include "ui/gfx/geometry/geometry_export.h"
#include "ui/gfx/geometry/vector2d_f.h"
namespace gfx {
class GEOMETRY_EXPORT Vector2d {
public:
constexpr Vector2d() : x_(0), y_(0) {}
constexpr Vector2d(int x, int y) : x_(x), y_(y) {}
constexpr int x() const { return x_; }
void set_x(int x) { x_ = x; }
constexpr int y() const { return y_; }
void set_y(int y) { y_ = y; }
// True if both components of the vector are 0.
bool IsZero() const;
// Add the components of the |other| vector to the current vector.
void Add(const Vector2d& other);
// Subtract the components of the |other| vector from the current vector.
void Subtract(const Vector2d& other);
constexpr bool operator==(const Vector2d& other) const {
return x_ == other.x_ && y_ == other.y_;
}
void operator+=(const Vector2d& other) { Add(other); }
void operator-=(const Vector2d& other) { Subtract(other); }
void SetToMin(const Vector2d& other) {
x_ = x_ <= other.x_ ? x_ : other.x_;
y_ = y_ <= other.y_ ? y_ : other.y_;
}
void SetToMax(const Vector2d& other) {
x_ = x_ >= other.x_ ? x_ : other.x_;
y_ = y_ >= other.y_ ? y_ : other.y_;
}
// Gives the square of the diagonal length of the vector. Since this is
// cheaper to compute than Length(), it is useful when you want to compare
// relative lengths of different vectors without needing the actual lengths.
int64_t LengthSquared() const;
// Gives the diagonal length of the vector.
float Length() const;
std::string ToString() const;
operator Vector2dF() const {
return Vector2dF(static_cast<float>(x()), static_cast<float>(y()));
}
private:
int x_;
int y_;
};
inline constexpr Vector2d operator-(const Vector2d& v) {
return Vector2d(-v.x(), -v.y());
}
inline Vector2d operator+(const Vector2d& lhs, const Vector2d& rhs) {
Vector2d result = lhs;
result.Add(rhs);
return result;
}
inline Vector2d operator-(const Vector2d& lhs, const Vector2d& rhs) {
Vector2d result = lhs;
result.Add(-rhs);
return result;
}
// This is declared here for use in gtest-based unit tests but is defined in
// the //ui/gfx:test_support target. Depend on that to use this in your unit
// test. This should not be used in production code - call ToString() instead.
void PrintTo(const Vector2d& vector, ::std::ostream* os);
} // namespace gfx
#endif // UI_GFX_GEOMETRY_VECTOR2D_H_

View File

@@ -0,0 +1,26 @@
// Copyright (c) 2012 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/geometry/vector2d_conversions.h"
#include "base/numerics/safe_conversions.h"
namespace gfx {
Vector2d ToFlooredVector2d(const Vector2dF& vector2d) {
return Vector2d(base::ClampFloor(vector2d.x()),
base::ClampFloor(vector2d.y()));
}
Vector2d ToCeiledVector2d(const Vector2dF& vector2d) {
return Vector2d(base::ClampCeil(vector2d.x()), base::ClampCeil(vector2d.y()));
}
Vector2d ToRoundedVector2d(const Vector2dF& vector2d) {
return Vector2d(base::ClampRound(vector2d.x()),
base::ClampRound(vector2d.y()));
}
} // namespace gfx

View File

@@ -0,0 +1,24 @@
// Copyright (c) 2012 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.
#ifndef UI_GFX_GEOMETRY_VECTOR2D_CONVERSIONS_H_
#define UI_GFX_GEOMETRY_VECTOR2D_CONVERSIONS_H_
#include "ui/gfx/geometry/vector2d.h"
#include "ui/gfx/geometry/vector2d_f.h"
namespace gfx {
// Returns a Vector2d with each component from the input Vector2dF floored.
GEOMETRY_EXPORT Vector2d ToFlooredVector2d(const Vector2dF& vector2d);
// Returns a Vector2d with each component from the input Vector2dF ceiled.
GEOMETRY_EXPORT Vector2d ToCeiledVector2d(const Vector2dF& vector2d);
// Returns a Vector2d with each component from the input Vector2dF rounded.
GEOMETRY_EXPORT Vector2d ToRoundedVector2d(const Vector2dF& vector2d);
} // namespace gfx
#endif // UI_GFX_GEOMETRY_VECTOR2D_CONVERSIONS_H_

View File

@@ -0,0 +1,60 @@
// Copyright (c) 2012 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/geometry/vector2d_f.h"
#include <cmath>
#include "base/strings/stringprintf.h"
namespace gfx {
std::string Vector2dF::ToString() const {
return base::StringPrintf("[%f %f]", x_, y_);
}
bool Vector2dF::IsZero() const {
return x_ == 0 && y_ == 0;
}
void Vector2dF::Add(const Vector2dF& other) {
x_ += other.x_;
y_ += other.y_;
}
void Vector2dF::Subtract(const Vector2dF& other) {
x_ -= other.x_;
y_ -= other.y_;
}
double Vector2dF::LengthSquared() const {
return static_cast<double>(x_) * x_ + static_cast<double>(y_) * y_;
}
float Vector2dF::Length() const {
return static_cast<float>(std::sqrt(LengthSquared()));
}
void Vector2dF::Scale(float x_scale, float y_scale) {
x_ *= x_scale;
y_ *= y_scale;
}
double CrossProduct(const Vector2dF& lhs, const Vector2dF& rhs) {
return static_cast<double>(lhs.x()) * rhs.y() -
static_cast<double>(lhs.y()) * rhs.x();
}
double DotProduct(const Vector2dF& lhs, const Vector2dF& rhs) {
return static_cast<double>(lhs.x()) * rhs.x() +
static_cast<double>(lhs.y()) * rhs.y();
}
Vector2dF ScaleVector2d(const Vector2dF& v, float x_scale, float y_scale) {
Vector2dF scaled_v(v);
scaled_v.Scale(x_scale, y_scale);
return scaled_v;
}
} // namespace gfx

View File

@@ -0,0 +1,118 @@
// Copyright (c) 2012 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.
// Defines a simple float vector class. This class is used to indicate a
// distance in two dimensions between two points. Subtracting two points should
// produce a vector, and adding a vector to a point produces the point at the
// vector's distance from the original point.
#ifndef UI_GFX_GEOMETRY_VECTOR2D_F_H_
#define UI_GFX_GEOMETRY_VECTOR2D_F_H_
#include <iosfwd>
#include <string>
#include "ui/gfx/geometry/geometry_export.h"
namespace gfx {
class GEOMETRY_EXPORT Vector2dF {
public:
constexpr Vector2dF() : x_(0), y_(0) {}
constexpr Vector2dF(float x, float y) : x_(x), y_(y) {}
constexpr float x() const { return x_; }
void set_x(float x) { x_ = x; }
constexpr float y() const { return y_; }
void set_y(float y) { y_ = y; }
// True if both components of the vector are 0.
bool IsZero() const;
// Add the components of the |other| vector to the current vector.
void Add(const Vector2dF& other);
// Subtract the components of the |other| vector from the current vector.
void Subtract(const Vector2dF& other);
void operator+=(const Vector2dF& other) { Add(other); }
void operator-=(const Vector2dF& other) { Subtract(other); }
void SetToMin(const Vector2dF& other) {
x_ = x_ <= other.x_ ? x_ : other.x_;
y_ = y_ <= other.y_ ? y_ : other.y_;
}
void SetToMax(const Vector2dF& other) {
x_ = x_ >= other.x_ ? x_ : other.x_;
y_ = y_ >= other.y_ ? y_ : other.y_;
}
// Gives the square of the diagonal length of the vector.
double LengthSquared() const;
// Gives the diagonal length of the vector.
float Length() const;
// Scale the x and y components of the vector by |scale|.
void Scale(float scale) { Scale(scale, scale); }
// Scale the x and y components of the vector by |x_scale| and |y_scale|
// respectively.
void Scale(float x_scale, float y_scale);
std::string ToString() const;
private:
float x_;
float y_;
};
inline constexpr bool operator==(const Vector2dF& lhs, const Vector2dF& rhs) {
return lhs.x() == rhs.x() && lhs.y() == rhs.y();
}
inline constexpr bool operator!=(const Vector2dF& lhs, const Vector2dF& rhs) {
return !(lhs == rhs);
}
inline constexpr Vector2dF operator-(const Vector2dF& v) {
return Vector2dF(-v.x(), -v.y());
}
inline Vector2dF operator+(const Vector2dF& lhs, const Vector2dF& rhs) {
Vector2dF result = lhs;
result.Add(rhs);
return result;
}
inline Vector2dF operator-(const Vector2dF& lhs, const Vector2dF& rhs) {
Vector2dF result = lhs;
result.Add(-rhs);
return result;
}
// Return the cross product of two vectors.
GEOMETRY_EXPORT double CrossProduct(const Vector2dF& lhs, const Vector2dF& rhs);
// Return the dot product of two vectors.
GEOMETRY_EXPORT double DotProduct(const Vector2dF& lhs, const Vector2dF& rhs);
// Return a vector that is |v| scaled by the given scale factors along each
// axis.
GEOMETRY_EXPORT Vector2dF ScaleVector2d(const Vector2dF& v,
float x_scale,
float y_scale);
// Return a vector that is |v| scaled by the given scale factor.
inline Vector2dF ScaleVector2d(const Vector2dF& v, float scale) {
return ScaleVector2d(v, scale, scale);
}
// This is declared here for use in gtest-based unit tests but is defined in
// the //ui/gfx:test_support target. Depend on that to use this in your unit
// test. This should not be used in production code - call ToString() instead.
void PrintTo(const Vector2dF& vector, ::std::ostream* os);
} // namespace gfx
#endif // UI_GFX_GEOMETRY_VECTOR2D_F_H_

View File

@@ -0,0 +1,293 @@
// Copyright (c) 2012 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 <stddef.h>
#include <cmath>
#include <limits>
#include "base/stl_util.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/gfx/geometry/vector2d.h"
#include "ui/gfx/geometry/vector2d_f.h"
namespace gfx {
TEST(Vector2dTest, ConversionToFloat) {
Vector2d i(3, 4);
Vector2dF f = i;
EXPECT_EQ(i, f);
}
TEST(Vector2dTest, IsZero) {
Vector2d int_zero(0, 0);
Vector2d int_nonzero(2, -2);
Vector2dF float_zero(0, 0);
Vector2dF float_nonzero(0.1f, -0.1f);
EXPECT_TRUE(int_zero.IsZero());
EXPECT_FALSE(int_nonzero.IsZero());
EXPECT_TRUE(float_zero.IsZero());
EXPECT_FALSE(float_nonzero.IsZero());
}
TEST(Vector2dTest, Add) {
Vector2d i1(3, 5);
Vector2d i2(4, -1);
const struct {
Vector2d expected;
Vector2d actual;
} int_tests[] = {
{ Vector2d(3, 5), i1 + Vector2d() },
{ Vector2d(3 + 4, 5 - 1), i1 + i2 },
{ Vector2d(3 - 4, 5 + 1), i1 - i2 }
};
for (size_t i = 0; i < base::size(int_tests); ++i)
EXPECT_EQ(int_tests[i].expected.ToString(),
int_tests[i].actual.ToString());
Vector2dF f1(3.1f, 5.1f);
Vector2dF f2(4.3f, -1.3f);
const struct {
Vector2dF expected;
Vector2dF actual;
} float_tests[] = {
{ Vector2dF(3.1F, 5.1F), f1 + Vector2d() },
{ Vector2dF(3.1F, 5.1F), f1 + Vector2dF() },
{ Vector2dF(3.1f + 4.3f, 5.1f - 1.3f), f1 + f2 },
{ Vector2dF(3.1f - 4.3f, 5.1f + 1.3f), f1 - f2 }
};
for (size_t i = 0; i < base::size(float_tests); ++i)
EXPECT_EQ(float_tests[i].expected.ToString(),
float_tests[i].actual.ToString());
}
TEST(Vector2dTest, Negative) {
const struct {
Vector2d expected;
Vector2d actual;
} int_tests[] = {
{ Vector2d(0, 0), -Vector2d(0, 0) },
{ Vector2d(-3, -3), -Vector2d(3, 3) },
{ Vector2d(3, 3), -Vector2d(-3, -3) },
{ Vector2d(-3, 3), -Vector2d(3, -3) },
{ Vector2d(3, -3), -Vector2d(-3, 3) }
};
for (size_t i = 0; i < base::size(int_tests); ++i)
EXPECT_EQ(int_tests[i].expected.ToString(),
int_tests[i].actual.ToString());
const struct {
Vector2dF expected;
Vector2dF actual;
} float_tests[] = {
{ Vector2dF(0, 0), -Vector2d(0, 0) },
{ Vector2dF(-0.3f, -0.3f), -Vector2dF(0.3f, 0.3f) },
{ Vector2dF(0.3f, 0.3f), -Vector2dF(-0.3f, -0.3f) },
{ Vector2dF(-0.3f, 0.3f), -Vector2dF(0.3f, -0.3f) },
{ Vector2dF(0.3f, -0.3f), -Vector2dF(-0.3f, 0.3f) }
};
for (size_t i = 0; i < base::size(float_tests); ++i)
EXPECT_EQ(float_tests[i].expected.ToString(),
float_tests[i].actual.ToString());
}
TEST(Vector2dTest, Scale) {
float double_values[][4] = {
{ 4.5f, 1.2f, 3.3f, 5.6f },
{ 4.5f, -1.2f, 3.3f, 5.6f },
{ 4.5f, 1.2f, 3.3f, -5.6f },
{ 4.5f, 1.2f, -3.3f, -5.6f },
{ -4.5f, 1.2f, 3.3f, 5.6f },
{ -4.5f, 1.2f, 0, 5.6f },
{ -4.5f, 1.2f, 3.3f, 0 },
{ 4.5f, 0, 3.3f, 5.6f },
{ 0, 1.2f, 3.3f, 5.6f }
};
for (size_t i = 0; i < base::size(double_values); ++i) {
Vector2dF v(double_values[i][0], double_values[i][1]);
v.Scale(double_values[i][2], double_values[i][3]);
EXPECT_EQ(v.x(), double_values[i][0] * double_values[i][2]);
EXPECT_EQ(v.y(), double_values[i][1] * double_values[i][3]);
Vector2dF v2 = ScaleVector2d(
gfx::Vector2dF(double_values[i][0], double_values[i][1]),
double_values[i][2], double_values[i][3]);
EXPECT_EQ(double_values[i][0] * double_values[i][2], v2.x());
EXPECT_EQ(double_values[i][1] * double_values[i][3], v2.y());
}
float single_values[][3] = {
{ 4.5f, 1.2f, 3.3f },
{ 4.5f, -1.2f, 3.3f },
{ 4.5f, 1.2f, 3.3f },
{ 4.5f, 1.2f, -3.3f },
{ -4.5f, 1.2f, 3.3f },
{ -4.5f, 1.2f, 0 },
{ -4.5f, 1.2f, 3.3f },
{ 4.5f, 0, 3.3f },
{ 0, 1.2f, 3.3f }
};
for (size_t i = 0; i < base::size(single_values); ++i) {
Vector2dF v(single_values[i][0], single_values[i][1]);
v.Scale(single_values[i][2]);
EXPECT_EQ(v.x(), single_values[i][0] * single_values[i][2]);
EXPECT_EQ(v.y(), single_values[i][1] * single_values[i][2]);
Vector2dF v2 = ScaleVector2d(
gfx::Vector2dF(double_values[i][0], double_values[i][1]),
double_values[i][2]);
EXPECT_EQ(single_values[i][0] * single_values[i][2], v2.x());
EXPECT_EQ(single_values[i][1] * single_values[i][2], v2.y());
}
}
TEST(Vector2dTest, Length) {
int int_values[][2] = {
{ 0, 0 },
{ 10, 20 },
{ 20, 10 },
{ -10, -20 },
{ -20, 10 },
{ 10, -20 },
};
for (size_t i = 0; i < base::size(int_values); ++i) {
int v0 = int_values[i][0];
int v1 = int_values[i][1];
double length_squared =
static_cast<double>(v0) * v0 + static_cast<double>(v1) * v1;
double length = std::sqrt(length_squared);
Vector2d vector(v0, v1);
EXPECT_EQ(static_cast<float>(length_squared), vector.LengthSquared());
EXPECT_EQ(static_cast<float>(length), vector.Length());
}
float float_values[][2] = {
{ 0, 0 },
{ 10.5f, 20.5f },
{ 20.5f, 10.5f },
{ -10.5f, -20.5f },
{ -20.5f, 10.5f },
{ 10.5f, -20.5f },
// A large vector that fails if the Length function doesn't use
// double precision internally.
{ 1236278317862780234892374893213178027.12122348904204230f,
335890352589839028212313231225425134332.38123f },
};
for (size_t i = 0; i < base::size(float_values); ++i) {
double v0 = float_values[i][0];
double v1 = float_values[i][1];
double length_squared =
static_cast<double>(v0) * v0 + static_cast<double>(v1) * v1;
double length = std::sqrt(length_squared);
Vector2dF vector(v0, v1);
EXPECT_DOUBLE_EQ(length_squared, vector.LengthSquared());
EXPECT_FLOAT_EQ(static_cast<float>(length), vector.Length());
}
}
TEST(Vector2dTest, ClampVector2d) {
Vector2d a;
a = Vector2d(3, 5);
EXPECT_EQ(Vector2d(3, 5).ToString(), a.ToString());
a.SetToMax(Vector2d(2, 4));
EXPECT_EQ(Vector2d(3, 5).ToString(), a.ToString());
a.SetToMax(Vector2d(3, 5));
EXPECT_EQ(Vector2d(3, 5).ToString(), a.ToString());
a.SetToMax(Vector2d(4, 2));
EXPECT_EQ(Vector2d(4, 5).ToString(), a.ToString());
a.SetToMax(Vector2d(8, 10));
EXPECT_EQ(Vector2d(8, 10).ToString(), a.ToString());
a.SetToMin(Vector2d(9, 11));
EXPECT_EQ(Vector2d(8, 10).ToString(), a.ToString());
a.SetToMin(Vector2d(8, 10));
EXPECT_EQ(Vector2d(8, 10).ToString(), a.ToString());
a.SetToMin(Vector2d(11, 9));
EXPECT_EQ(Vector2d(8, 9).ToString(), a.ToString());
a.SetToMin(Vector2d(7, 11));
EXPECT_EQ(Vector2d(7, 9).ToString(), a.ToString());
a.SetToMin(Vector2d(3, 5));
EXPECT_EQ(Vector2d(3, 5).ToString(), a.ToString());
}
TEST(Vector2dTest, ClampVector2dF) {
Vector2dF a;
a = Vector2dF(3.5f, 5.5f);
EXPECT_EQ(Vector2dF(3.5f, 5.5f).ToString(), a.ToString());
a.SetToMax(Vector2dF(2.5f, 4.5f));
EXPECT_EQ(Vector2dF(3.5f, 5.5f).ToString(), a.ToString());
a.SetToMax(Vector2dF(3.5f, 5.5f));
EXPECT_EQ(Vector2dF(3.5f, 5.5f).ToString(), a.ToString());
a.SetToMax(Vector2dF(4.5f, 2.5f));
EXPECT_EQ(Vector2dF(4.5f, 5.5f).ToString(), a.ToString());
a.SetToMax(Vector2dF(8.5f, 10.5f));
EXPECT_EQ(Vector2dF(8.5f, 10.5f).ToString(), a.ToString());
a.SetToMin(Vector2dF(9.5f, 11.5f));
EXPECT_EQ(Vector2dF(8.5f, 10.5f).ToString(), a.ToString());
a.SetToMin(Vector2dF(8.5f, 10.5f));
EXPECT_EQ(Vector2dF(8.5f, 10.5f).ToString(), a.ToString());
a.SetToMin(Vector2dF(11.5f, 9.5f));
EXPECT_EQ(Vector2dF(8.5f, 9.5f).ToString(), a.ToString());
a.SetToMin(Vector2dF(7.5f, 11.5f));
EXPECT_EQ(Vector2dF(7.5f, 9.5f).ToString(), a.ToString());
a.SetToMin(Vector2dF(3.5f, 5.5f));
EXPECT_EQ(Vector2dF(3.5f, 5.5f).ToString(), a.ToString());
}
TEST(Vector2dTest, IntegerOverflow) {
int int_max = std::numeric_limits<int>::max();
int int_min = std::numeric_limits<int>::min();
Vector2d max_vector(int_max, int_max);
Vector2d min_vector(int_min, int_min);
Vector2d test;
test = Vector2d();
test += Vector2d(int_max, int_max);
EXPECT_EQ(test, max_vector);
test = Vector2d();
test += Vector2d(int_min, int_min);
EXPECT_EQ(test, min_vector);
test = Vector2d(10, 20);
test += Vector2d(int_max, int_max);
EXPECT_EQ(test, max_vector);
test = Vector2d(-10, -20);
test += Vector2d(int_min, int_min);
EXPECT_EQ(test, min_vector);
test = Vector2d();
test -= Vector2d(int_max, int_max);
EXPECT_EQ(test, Vector2d(-int_max, -int_max));
test = Vector2d();
test -= Vector2d(int_min, int_min);
EXPECT_EQ(test, max_vector);
test = Vector2d(10, 20);
test -= Vector2d(int_min, int_min);
EXPECT_EQ(test, max_vector);
test = Vector2d(-10, -20);
test -= Vector2d(int_max, int_max);
EXPECT_EQ(test, min_vector);
}
} // namespace gfx

View File

@@ -0,0 +1,29 @@
// Copyright (c) 2013 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.
#ifndef UI_GFX_GFX_EXPORT_H_
#define UI_GFX_GFX_EXPORT_H_
#if defined(COMPONENT_BUILD)
#if defined(WIN32)
#if defined(GFX_IMPLEMENTATION)
#define GFX_EXPORT __declspec(dllexport)
#else
#define GFX_EXPORT __declspec(dllimport)
#endif // defined(GFX_IMPLEMENTATION)
#else // defined(WIN32)
#if defined(GFX_IMPLEMENTATION)
#define GFX_EXPORT __attribute__((visibility("default")))
#else
#define GFX_EXPORT
#endif
#endif
#else // defined(COMPONENT_BUILD)
#define GFX_EXPORT
#endif
#endif // UI_GFX_GFX_EXPORT_H_

View File

@@ -0,0 +1,35 @@
// Copyright 2014 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.
#ifndef UI_GFX_MAC_COORDINATE_CONVERSION_H_
#define UI_GFX_MAC_COORDINATE_CONVERSION_H_
#import <Foundation/Foundation.h>
#include "ui/gfx/gfx_export.h"
namespace gfx {
class Point;
class Rect;
// Convert a gfx::Rect specified with the origin at the top left of the primary
// display into AppKit secreen coordinates (origin at the bottom left).
GFX_EXPORT NSRect ScreenRectToNSRect(const Rect& rect);
// Convert an AppKit NSRect with origin in the bottom left of the primary
// display into a gfx::Rect with origin at the top left of the primary display.
GFX_EXPORT Rect ScreenRectFromNSRect(const NSRect& point);
// Convert a gfx::Point specified with the origin at the top left of the primary
// display into AppKit screen coordinates (origin at the bottom left).
GFX_EXPORT NSPoint ScreenPointToNSPoint(const Point& point);
// Convert an AppKit NSPoint with origin in the bottom left of the primary
// display into a gfx::Point with origin at the top left of the primary display.
GFX_EXPORT Point ScreenPointFromNSPoint(const NSPoint& point);
} // namespace gfx
#endif // UI_GFX_MAC_COORDINATE_CONVERSION_H_

View File

@@ -0,0 +1,45 @@
// Copyright 2014 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.
#import "ui/gfx/mac/coordinate_conversion.h"
#import <Cocoa/Cocoa.h>
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/rect.h"
namespace gfx {
namespace {
// The height of the primary display, which OSX defines as the monitor with the
// menubar. This is always at index 0.
CGFloat PrimaryDisplayHeight() {
return NSMaxY([[[NSScreen screens] firstObject] frame]);
}
} // namespace
NSRect ScreenRectToNSRect(const Rect& rect) {
return NSMakeRect(rect.x(),
PrimaryDisplayHeight() - rect.y() - rect.height(),
rect.width(),
rect.height());
}
Rect ScreenRectFromNSRect(const NSRect& rect) {
return Rect(rect.origin.x,
PrimaryDisplayHeight() - rect.origin.y - rect.size.height,
rect.size.width, rect.size.height);
}
NSPoint ScreenPointToNSPoint(const Point& point) {
return NSMakePoint(point.x(), PrimaryDisplayHeight() - point.y());
}
Point ScreenPointFromNSPoint(const NSPoint& point) {
return Point(point.x, PrimaryDisplayHeight() - point.y);
}
} // namespace gfx

View File

@@ -0,0 +1,254 @@
// Copyright (c) 2012 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.
#ifndef UI_GFX_NATIVE_WIDGET_TYPES_H_
#define UI_GFX_NATIVE_WIDGET_TYPES_H_
#include <stdint.h>
#include "build/build_config.h"
#include "ui/gfx/gfx_export.h"
#if defined(OS_ANDROID)
#include "base/android/scoped_java_ref.h"
#elif defined(OS_APPLE)
#include <objc/objc.h>
#elif defined(OS_WIN)
#include "base/win/windows_types.h"
#endif
// This file provides cross platform typedefs for native widget types.
// NativeWindow: this is a handle to a native, top-level window
// NativeView: this is a handle to a native UI element. It may be the
// same type as a NativeWindow on some platforms.
// NativeViewId: Often, in our cross process model, we need to pass around a
// reference to a "window". This reference will, say, be echoed back from a
// renderer to the browser when it wishes to query its size. On Windows we
// use an HWND for this.
//
// As a rule of thumb - if you're in the renderer, you should be dealing
// with NativeViewIds. This should remind you that you shouldn't be doing
// direct operations on platform widgets from the renderer process.
//
// If you're in the browser, you're probably dealing with NativeViews,
// unless you're in the IPC layer, which will be translating between
// NativeViewIds from the renderer and NativeViews.
//
// The name 'View' here meshes with OS X where the UI elements are called
// 'views' and with our Chrome UI code where the elements are also called
// 'views'.
#if defined(USE_AURA)
namespace aura {
class Window;
}
namespace ui {
class Cursor;
class Event;
namespace mojom {
enum class CursorType;
}
} // namespace ui
#endif // defined(USE_AURA)
#if defined(OS_WIN)
typedef struct HFONT__* HFONT;
struct IAccessible;
#elif defined(OS_IOS)
struct CGContext;
#ifdef __OBJC__
@class UIEvent;
@class UIFont;
@class UIImage;
@class UIView;
@class UIWindow;
@class UITextField;
#else
class UIEvent;
class UIFont;
class UIImage;
class UIView;
class UIWindow;
class UITextField;
#endif // __OBJC__
#elif defined(OS_MAC)
struct CGContext;
#ifdef __OBJC__
@class NSCursor;
@class NSEvent;
@class NSFont;
@class NSImage;
@class NSView;
@class NSWindow;
@class NSTextField;
#else
class NSCursor;
class NSEvent;
class NSFont;
class NSImage;
struct NSView;
class NSWindow;
class NSTextField;
#endif // __OBJC__
#endif
#if defined(OS_ANDROID)
struct ANativeWindow;
namespace ui {
class WindowAndroid;
class ViewAndroid;
} // namespace ui
#endif
class SkBitmap;
#if defined(OS_LINUX) && !defined(OS_CHROMEOS)
extern "C" {
struct _AtkObject;
typedef struct _AtkObject AtkObject;
}
#endif
namespace gfx {
#if defined(USE_AURA)
typedef ui::Cursor NativeCursor;
typedef aura::Window* NativeView;
typedef aura::Window* NativeWindow;
typedef ui::Event* NativeEvent;
constexpr NativeView kNullNativeView = nullptr;
constexpr NativeWindow kNullNativeWindow = nullptr;
#elif defined(OS_IOS)
typedef void* NativeCursor;
typedef UIView* NativeView;
typedef UIWindow* NativeWindow;
typedef UIEvent* NativeEvent;
constexpr NativeView kNullNativeView = nullptr;
constexpr NativeWindow kNullNativeWindow = nullptr;
#elif defined(OS_MAC)
typedef NSCursor* NativeCursor;
typedef NSEvent* NativeEvent;
// NativeViews and NativeWindows on macOS are not necessarily in the same
// process as the NSViews and NSWindows that they represent. Require an
// explicit function call (GetNativeNSView or GetNativeNSWindow) to retrieve
// the underlying NSView or NSWindow.
// https://crbug.com/893719
class GFX_EXPORT NativeView {
public:
constexpr NativeView() {}
// TODO(ccameron): Make this constructor explicit.
constexpr NativeView(NSView* ns_view) : ns_view_(ns_view) {}
// This function name is verbose (that is, not just GetNSView) so that it
// is easily grep-able.
NSView* GetNativeNSView() const { return ns_view_; }
operator bool() const { return ns_view_ != 0; }
bool operator==(const NativeView& other) const {
return ns_view_ == other.ns_view_;
}
bool operator!=(const NativeView& other) const {
return ns_view_ != other.ns_view_;
}
bool operator<(const NativeView& other) const {
return ns_view_ < other.ns_view_;
}
private:
NSView* ns_view_ = nullptr;
};
class GFX_EXPORT NativeWindow {
public:
constexpr NativeWindow() {}
// TODO(ccameron): Make this constructor explicit.
constexpr NativeWindow(NSWindow* ns_window) : ns_window_(ns_window) {}
// This function name is verbose (that is, not just GetNSWindow) so that it
// is easily grep-able.
NSWindow* GetNativeNSWindow() const { return ns_window_; }
operator bool() const { return ns_window_ != 0; }
bool operator==(const NativeWindow& other) const {
return ns_window_ == other.ns_window_;
}
bool operator!=(const NativeWindow& other) const {
return ns_window_ != other.ns_window_;
}
bool operator<(const NativeWindow& other) const {
return ns_window_ < other.ns_window_;
}
private:
NSWindow* ns_window_ = nullptr;
};
constexpr NativeView kNullNativeView = NativeView(nullptr);
constexpr NativeWindow kNullNativeWindow = NativeWindow(nullptr);
#elif defined(OS_ANDROID)
typedef void* NativeCursor;
typedef ui::ViewAndroid* NativeView;
typedef ui::WindowAndroid* NativeWindow;
typedef base::android::ScopedJavaGlobalRef<jobject> NativeEvent;
constexpr NativeView kNullNativeView = nullptr;
constexpr NativeWindow kNullNativeWindow = nullptr;
#else
#error Unknown build environment.
#endif
#if defined(OS_WIN)
typedef HFONT NativeFont;
typedef IAccessible* NativeViewAccessible;
#elif defined(OS_IOS)
typedef UIFont* NativeFont;
typedef id NativeViewAccessible;
#elif defined(OS_MAC)
typedef NSFont* NativeFont;
typedef id NativeViewAccessible;
#elif defined(OS_LINUX) && !defined(OS_CHROMEOS)
// Linux doesn't have a native font type.
typedef AtkObject* NativeViewAccessible;
#else
// Android, Chrome OS, etc.
typedef struct _UnimplementedNativeViewAccessible
UnimplementedNativeViewAccessible;
typedef UnimplementedNativeViewAccessible* NativeViewAccessible;
#endif
// A constant value to indicate that gfx::NativeCursor refers to no cursor.
#if defined(USE_AURA)
const ui::mojom::CursorType kNullCursor =
static_cast<ui::mojom::CursorType>(-1);
#else
const gfx::NativeCursor kNullCursor = static_cast<gfx::NativeCursor>(nullptr);
#endif
// Note: for test_shell we're packing a pointer into the NativeViewId. So, if
// you make it a type which is smaller than a pointer, you have to fix
// test_shell.
//
// See comment at the top of the file for usage.
typedef intptr_t NativeViewId;
// AcceleratedWidget provides a surface to compositors to paint pixels.
#if defined(OS_WIN)
typedef HWND AcceleratedWidget;
constexpr AcceleratedWidget kNullAcceleratedWidget = nullptr;
#elif defined(OS_IOS)
typedef UIView* AcceleratedWidget;
constexpr AcceleratedWidget kNullAcceleratedWidget = 0;
#elif defined(OS_MAC)
typedef uint64_t AcceleratedWidget;
constexpr AcceleratedWidget kNullAcceleratedWidget = 0;
#elif defined(OS_ANDROID)
typedef ANativeWindow* AcceleratedWidget;
constexpr AcceleratedWidget kNullAcceleratedWidget = 0;
#elif defined(USE_OZONE) || defined(USE_X11)
typedef uint32_t AcceleratedWidget;
constexpr AcceleratedWidget kNullAcceleratedWidget = 0;
#else
#error unknown platform
#endif
} // namespace gfx
#endif // UI_GFX_NATIVE_WIDGET_TYPES_H_

View File

@@ -0,0 +1,640 @@
// Copyright (c) 2012 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/transform.h"
#include "base/check_op.h"
#include "base/strings/stringprintf.h"
#include "ui/gfx/geometry/angle_conversions.h"
#include "ui/gfx/geometry/box_f.h"
#include "ui/gfx/geometry/point3_f.h"
#include "ui/gfx/geometry/point_conversions.h"
#include "ui/gfx/geometry/quaternion.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/vector3d_f.h"
#include "ui/gfx/rrect_f.h"
#include "ui/gfx/skia_util.h"
#include "ui/gfx/transform_util.h"
namespace gfx {
namespace {
const SkScalar kEpsilon = std::numeric_limits<float>::epsilon();
SkScalar TanDegrees(double degrees) {
return SkDoubleToScalar(std::tan(gfx::DegToRad(degrees)));
}
inline bool ApproximatelyZero(SkScalar x, SkScalar tolerance) {
return std::abs(x) <= tolerance;
}
inline bool ApproximatelyOne(SkScalar x, SkScalar tolerance) {
return std::abs(x - 1) <= tolerance;
}
} // namespace
Transform::Transform(SkScalar col1row1,
SkScalar col2row1,
SkScalar col3row1,
SkScalar col4row1,
SkScalar col1row2,
SkScalar col2row2,
SkScalar col3row2,
SkScalar col4row2,
SkScalar col1row3,
SkScalar col2row3,
SkScalar col3row3,
SkScalar col4row3,
SkScalar col1row4,
SkScalar col2row4,
SkScalar col3row4,
SkScalar col4row4)
: matrix_(SkMatrix44::kUninitialized_Constructor) {
matrix_.set4x4(col1row1, col1row2, col1row3, col1row4, col2row1, col2row2,
col2row3, col2row4, col3row1, col3row2, col3row3, col3row4,
col4row1, col4row2, col4row3, col4row4);
}
Transform::Transform(SkScalar col1row1,
SkScalar col2row1,
SkScalar col1row2,
SkScalar col2row2,
SkScalar x_translation,
SkScalar y_translation)
: matrix_(SkMatrix44::kIdentity_Constructor) {
matrix_.set(0, 0, col1row1);
matrix_.set(1, 0, col1row2);
matrix_.set(0, 1, col2row1);
matrix_.set(1, 1, col2row2);
matrix_.set(0, 3, x_translation);
matrix_.set(1, 3, y_translation);
}
Transform::Transform(const Quaternion& q)
: matrix_(SkMatrix44::kUninitialized_Constructor) {
double x = q.x();
double y = q.y();
double z = q.z();
double w = q.w();
// Implicitly calls matrix.setIdentity()
matrix_.set3x3(SkDoubleToScalar(1.0 - 2.0 * (y * y + z * z)),
SkDoubleToScalar(2.0 * (x * y + z * w)),
SkDoubleToScalar(2.0 * (x * z - y * w)),
SkDoubleToScalar(2.0 * (x * y - z * w)),
SkDoubleToScalar(1.0 - 2.0 * (x * x + z * z)),
SkDoubleToScalar(2.0 * (y * z + x * w)),
SkDoubleToScalar(2.0 * (x * z + y * w)),
SkDoubleToScalar(2.0 * (y * z - x * w)),
SkDoubleToScalar(1.0 - 2.0 * (x * x + y * y)));
}
void Transform::RotateAboutXAxis(double degrees) {
double radians = gfx::DegToRad(degrees);
SkScalar cosTheta = SkDoubleToScalar(std::cos(radians));
SkScalar sinTheta = SkDoubleToScalar(std::sin(radians));
if (matrix_.isIdentity()) {
matrix_.set3x3(1, 0, 0,
0, cosTheta, sinTheta,
0, -sinTheta, cosTheta);
} else {
SkMatrix44 rot(SkMatrix44::kUninitialized_Constructor);
rot.set3x3(1, 0, 0,
0, cosTheta, sinTheta,
0, -sinTheta, cosTheta);
matrix_.preConcat(rot);
}
}
void Transform::RotateAboutYAxis(double degrees) {
double radians = gfx::DegToRad(degrees);
SkScalar cosTheta = SkDoubleToScalar(std::cos(radians));
SkScalar sinTheta = SkDoubleToScalar(std::sin(radians));
if (matrix_.isIdentity()) {
// Note carefully the placement of the -sinTheta for rotation about
// y-axis is different than rotation about x-axis or z-axis.
matrix_.set3x3(cosTheta, 0, -sinTheta,
0, 1, 0,
sinTheta, 0, cosTheta);
} else {
SkMatrix44 rot(SkMatrix44::kUninitialized_Constructor);
rot.set3x3(cosTheta, 0, -sinTheta,
0, 1, 0,
sinTheta, 0, cosTheta);
matrix_.preConcat(rot);
}
}
void Transform::RotateAboutZAxis(double degrees) {
double radians = gfx::DegToRad(degrees);
SkScalar cosTheta = SkDoubleToScalar(std::cos(radians));
SkScalar sinTheta = SkDoubleToScalar(std::sin(radians));
if (matrix_.isIdentity()) {
matrix_.set3x3(cosTheta, sinTheta, 0,
-sinTheta, cosTheta, 0,
0, 0, 1);
} else {
SkMatrix44 rot(SkMatrix44::kUninitialized_Constructor);
rot.set3x3(cosTheta, sinTheta, 0,
-sinTheta, cosTheta, 0,
0, 0, 1);
matrix_.preConcat(rot);
}
}
void Transform::RotateAbout(const Vector3dF& axis, double degrees) {
if (matrix_.isIdentity()) {
matrix_.setRotateDegreesAbout(axis.x(), axis.y(), axis.z(),
SkDoubleToScalar(degrees));
} else {
SkMatrix44 rot(SkMatrix44::kUninitialized_Constructor);
rot.setRotateDegreesAbout(axis.x(), axis.y(), axis.z(),
SkDoubleToScalar(degrees));
matrix_.preConcat(rot);
}
}
void Transform::Scale(SkScalar x, SkScalar y) {
matrix_.preScale(x, y, 1);
}
void Transform::PostScale(SkScalar x, SkScalar y) {
matrix_.postScale(x, y, 1);
}
void Transform::Scale3d(SkScalar x, SkScalar y, SkScalar z) {
matrix_.preScale(x, y, z);
}
void Transform::Translate(const Vector2dF& offset) {
Translate(offset.x(), offset.y());
}
void Transform::Translate(SkScalar x, SkScalar y) {
matrix_.preTranslate(x, y, 0);
}
void Transform::PostTranslate(const Vector2dF& offset) {
PostTranslate(offset.x(), offset.y());
}
void Transform::PostTranslate(SkScalar x, SkScalar y) {
matrix_.postTranslate(x, y, 0);
}
void Transform::Translate3d(const Vector3dF& offset) {
Translate3d(offset.x(), offset.y(), offset.z());
}
void Transform::Translate3d(SkScalar x, SkScalar y, SkScalar z) {
matrix_.preTranslate(x, y, z);
}
void Transform::Skew(double angle_x, double angle_y) {
if (matrix_.isIdentity()) {
matrix_.set(0, 1, TanDegrees(angle_x));
matrix_.set(1, 0, TanDegrees(angle_y));
} else {
SkMatrix44 skew(SkMatrix44::kIdentity_Constructor);
skew.set(0, 1, TanDegrees(angle_x));
skew.set(1, 0, TanDegrees(angle_y));
matrix_.preConcat(skew);
}
}
void Transform::ApplyPerspectiveDepth(SkScalar depth) {
if (depth == 0)
return;
if (matrix_.isIdentity()) {
matrix_.set(3, 2, -SK_Scalar1 / depth);
} else {
SkMatrix44 m(SkMatrix44::kIdentity_Constructor);
m.set(3, 2, -SK_Scalar1 / depth);
matrix_.preConcat(m);
}
}
void Transform::PreconcatTransform(const Transform& transform) {
matrix_.preConcat(transform.matrix_);
}
void Transform::ConcatTransform(const Transform& transform) {
matrix_.postConcat(transform.matrix_);
}
bool Transform::IsApproximatelyIdentityOrTranslation(SkScalar tolerance) const {
DCHECK_GE(tolerance, 0);
return
ApproximatelyOne(matrix_.get(0, 0), tolerance) &&
ApproximatelyZero(matrix_.get(1, 0), tolerance) &&
ApproximatelyZero(matrix_.get(2, 0), tolerance) &&
matrix_.get(3, 0) == 0 &&
ApproximatelyZero(matrix_.get(0, 1), tolerance) &&
ApproximatelyOne(matrix_.get(1, 1), tolerance) &&
ApproximatelyZero(matrix_.get(2, 1), tolerance) &&
matrix_.get(3, 1) == 0 &&
ApproximatelyZero(matrix_.get(0, 2), tolerance) &&
ApproximatelyZero(matrix_.get(1, 2), tolerance) &&
ApproximatelyOne(matrix_.get(2, 2), tolerance) &&
matrix_.get(3, 2) == 0 &&
matrix_.get(3, 3) == 1;
}
bool Transform::IsApproximatelyIdentityOrIntegerTranslation(
SkScalar tolerance) const {
if (!IsApproximatelyIdentityOrTranslation(tolerance))
return false;
for (float t : {matrix_.get(0, 3), matrix_.get(1, 3), matrix_.get(2, 3)}) {
if (!base::IsValueInRangeForNumericType<int>(t) ||
std::abs(std::round(t) - t) > tolerance)
return false;
}
return true;
}
bool Transform::IsIdentityOrIntegerTranslation() const {
if (!IsIdentityOrTranslation())
return false;
for (float t : {matrix_.get(0, 3), matrix_.get(1, 3), matrix_.get(2, 3)}) {
if (!base::IsValueInRangeForNumericType<int>(t) || static_cast<int>(t) != t)
return false;
}
return true;
}
bool Transform::IsBackFaceVisible() const {
// Compute whether a layer with a forward-facing normal of (0, 0, 1, 0)
// would have its back face visible after applying the transform.
if (matrix_.isIdentity())
return false;
// This is done by transforming the normal and seeing if the resulting z
// value is positive or negative. However, note that transforming a normal
// actually requires using the inverse-transpose of the original transform.
//
// We can avoid inverting and transposing the matrix since we know we want
// to transform only the specific normal vector (0, 0, 1, 0). In this case,
// we only need the 3rd row, 3rd column of the inverse-transpose. We can
// calculate only the 3rd row 3rd column element of the inverse, skipping
// everything else.
//
// For more information, refer to:
// http://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution
//
double determinant = matrix_.determinant();
// If matrix was not invertible, then just assume back face is not visible.
if (determinant == 0)
return false;
// Compute the cofactor of the 3rd row, 3rd column.
double cofactor_part_1 =
matrix_.get(0, 0) * matrix_.get(1, 1) * matrix_.get(3, 3);
double cofactor_part_2 =
matrix_.get(0, 1) * matrix_.get(1, 3) * matrix_.get(3, 0);
double cofactor_part_3 =
matrix_.get(0, 3) * matrix_.get(1, 0) * matrix_.get(3, 1);
double cofactor_part_4 =
matrix_.get(0, 0) * matrix_.get(1, 3) * matrix_.get(3, 1);
double cofactor_part_5 =
matrix_.get(0, 1) * matrix_.get(1, 0) * matrix_.get(3, 3);
double cofactor_part_6 =
matrix_.get(0, 3) * matrix_.get(1, 1) * matrix_.get(3, 0);
double cofactor33 =
cofactor_part_1 +
cofactor_part_2 +
cofactor_part_3 -
cofactor_part_4 -
cofactor_part_5 -
cofactor_part_6;
// Technically the transformed z component is cofactor33 / determinant. But
// we can avoid the costly division because we only care about the resulting
// +/- sign; we can check this equivalently by multiplication.
return cofactor33 * determinant < -kEpsilon;
}
bool Transform::GetInverse(Transform* transform) const {
if (!matrix_.invert(&transform->matrix_)) {
// Initialize the return value to identity if this matrix turned
// out to be un-invertible.
transform->MakeIdentity();
return false;
}
return true;
}
bool Transform::Preserves2dAxisAlignment() const {
// Check whether an axis aligned 2-dimensional rect would remain axis-aligned
// after being transformed by this matrix (and implicitly projected by
// dropping any non-zero z-values).
//
// The 4th column can be ignored because translations don't affect axis
// alignment. The 3rd column can be ignored because we are assuming 2d
// inputs, where z-values will be zero. The 3rd row can also be ignored
// because we are assuming 2d outputs, and any resulting z-value is dropped
// anyway. For the inner 2x2 portion, the only effects that keep a rect axis
// aligned are (1) swapping axes and (2) scaling axes. This can be checked by
// verifying only 1 element of every column and row is non-zero. Degenerate
// cases that project the x or y dimension to zero are considered to preserve
// axis alignment.
//
// If the matrix does have perspective component that is affected by x or y
// values: The current implementation conservatively assumes that axis
// alignment is not preserved.
bool has_x_or_y_perspective =
matrix_.get(3, 0) != 0 || matrix_.get(3, 1) != 0;
int num_non_zero_in_row_0 = 0;
int num_non_zero_in_row_1 = 0;
int num_non_zero_in_col_0 = 0;
int num_non_zero_in_col_1 = 0;
if (std::abs(matrix_.get(0, 0)) > kEpsilon) {
num_non_zero_in_row_0++;
num_non_zero_in_col_0++;
}
if (std::abs(matrix_.get(0, 1)) > kEpsilon) {
num_non_zero_in_row_0++;
num_non_zero_in_col_1++;
}
if (std::abs(matrix_.get(1, 0)) > kEpsilon) {
num_non_zero_in_row_1++;
num_non_zero_in_col_0++;
}
if (std::abs(matrix_.get(1, 1)) > kEpsilon) {
num_non_zero_in_row_1++;
num_non_zero_in_col_1++;
}
return
num_non_zero_in_row_0 <= 1 &&
num_non_zero_in_row_1 <= 1 &&
num_non_zero_in_col_0 <= 1 &&
num_non_zero_in_col_1 <= 1 &&
!has_x_or_y_perspective;
}
void Transform::Transpose() {
matrix_.transpose();
}
void Transform::FlattenTo2d() {
float tmp[16];
matrix_.asColMajorf(tmp);
tmp[2] = 0.0;
tmp[6] = 0.0;
tmp[8] = 0.0;
tmp[9] = 0.0;
tmp[10] = 1.0;
tmp[11] = 0.0;
tmp[14] = 0.0;
matrix_.setColMajorf(tmp);
}
bool Transform::IsFlat() const {
return matrix_.get(2, 0) == 0.0 && matrix_.get(2, 1) == 0.0 &&
matrix_.get(0, 2) == 0.0 && matrix_.get(1, 2) == 0.0 &&
matrix_.get(2, 2) == 1.0 && matrix_.get(3, 2) == 0.0 &&
matrix_.get(2, 3) == 0.0;
}
Vector2dF Transform::To2dTranslation() const {
return gfx::Vector2dF(SkScalarToFloat(matrix_.get(0, 3)),
SkScalarToFloat(matrix_.get(1, 3)));
}
void Transform::TransformPoint(Point* point) const {
DCHECK(point);
TransformPointInternal(matrix_, point);
}
void Transform::TransformPoint(PointF* point) const {
DCHECK(point);
TransformPointInternal(matrix_, point);
}
void Transform::TransformPoint(Point3F* point) const {
DCHECK(point);
TransformPointInternal(matrix_, point);
}
void Transform::TransformVector(Vector3dF* vector) const {
DCHECK(vector);
TransformVectorInternal(matrix_, vector);
}
bool Transform::TransformPointReverse(Point* point) const {
DCHECK(point);
// TODO(sad): Try to avoid trying to invert the matrix.
SkMatrix44 inverse(SkMatrix44::kUninitialized_Constructor);
if (!matrix_.invert(&inverse))
return false;
TransformPointInternal(inverse, point);
return true;
}
bool Transform::TransformPointReverse(Point3F* point) const {
DCHECK(point);
// TODO(sad): Try to avoid trying to invert the matrix.
SkMatrix44 inverse(SkMatrix44::kUninitialized_Constructor);
if (!matrix_.invert(&inverse))
return false;
TransformPointInternal(inverse, point);
return true;
}
void Transform::TransformRect(RectF* rect) const {
if (matrix_.isIdentity())
return;
SkRect src = RectFToSkRect(*rect);
SkMatrix(matrix_).mapRect(&src);
*rect = SkRectToRectF(src);
}
bool Transform::TransformRectReverse(RectF* rect) const {
if (matrix_.isIdentity())
return true;
SkMatrix44 inverse(SkMatrix44::kUninitialized_Constructor);
if (!matrix_.invert(&inverse))
return false;
SkRect src = RectFToSkRect(*rect);
SkMatrix(inverse).mapRect(&src);
*rect = SkRectToRectF(src);
return true;
}
bool Transform::TransformRRectF(RRectF* rrect) const {
SkRRect result;
if (!SkRRect(*rrect).transform(SkMatrix(matrix_), &result))
return false;
*rrect = gfx::RRectF(result);
return true;
}
void Transform::TransformBox(BoxF* box) const {
BoxF bounds;
bool first_point = true;
for (int corner = 0; corner < 8; ++corner) {
gfx::Point3F point = box->origin();
point += gfx::Vector3dF(corner & 1 ? box->width() : 0.f,
corner & 2 ? box->height() : 0.f,
corner & 4 ? box->depth() : 0.f);
TransformPoint(&point);
if (first_point) {
bounds.set_origin(point);
first_point = false;
} else {
bounds.ExpandTo(point);
}
}
*box = bounds;
}
bool Transform::TransformBoxReverse(BoxF* box) const {
gfx::Transform inverse = *this;
if (!GetInverse(&inverse))
return false;
inverse.TransformBox(box);
return true;
}
bool Transform::Blend(const Transform& from, double progress) {
DecomposedTransform to_decomp;
DecomposedTransform from_decomp;
if (!DecomposeTransform(&to_decomp, *this) ||
!DecomposeTransform(&from_decomp, from))
return false;
to_decomp = BlendDecomposedTransforms(to_decomp, from_decomp, progress);
matrix_ = ComposeTransform(to_decomp).matrix();
return true;
}
void Transform::RoundTranslationComponents() {
matrix_.set(0, 3, std::round(matrix_.get(0, 3)));
matrix_.set(1, 3, std::round(matrix_.get(1, 3)));
}
void Transform::TransformPointInternal(const SkMatrix44& xform,
Point3F* point) const {
if (xform.isIdentity())
return;
SkScalar p[4] = {point->x(), point->y(), point->z(), 1};
xform.mapScalars(p);
if (p[3] != SK_Scalar1 && p[3] != 0.f) {
float w_inverse = SK_Scalar1 / p[3];
point->SetPoint(p[0] * w_inverse, p[1] * w_inverse, p[2] * w_inverse);
} else {
point->SetPoint(p[0], p[1], p[2]);
}
}
void Transform::TransformVectorInternal(const SkMatrix44& xform,
Vector3dF* vector) const {
if (xform.isIdentity())
return;
SkScalar p[4] = {vector->x(), vector->y(), vector->z(), 0};
xform.mapScalars(p);
vector->set_x(p[0]);
vector->set_y(p[1]);
vector->set_z(p[2]);
}
void Transform::TransformPointInternal(const SkMatrix44& xform,
PointF* point) const {
if (xform.isIdentity())
return;
SkScalar p[4] = {SkIntToScalar(point->x()), SkIntToScalar(point->y()), 0, 1};
xform.mapScalars(p);
point->SetPoint(p[0], p[1]);
}
void Transform::TransformPointInternal(const SkMatrix44& xform,
Point* point) const {
PointF point_float(*point);
TransformPointInternal(xform, &point_float);
*point = ToRoundedPoint(point_float);
}
bool Transform::ApproximatelyEqual(const gfx::Transform& transform) const {
static const float component_tolerance = 0.1f;
// We may have a larger discrepancy in the scroll components due to snapping
// (floating point error might round the other way).
static const float translation_tolerance = 1.f;
for (int row = 0; row < 4; row++) {
for (int col = 0; col < 4; col++) {
const float delta =
std::abs(matrix().get(row, col) - transform.matrix().get(row, col));
const float tolerance =
col == 3 && row < 3 ? translation_tolerance : component_tolerance;
if (delta > tolerance)
return false;
}
}
return true;
}
std::string Transform::ToString() const {
return base::StringPrintf(
"[ %+0.4f %+0.4f %+0.4f %+0.4f \n"
" %+0.4f %+0.4f %+0.4f %+0.4f \n"
" %+0.4f %+0.4f %+0.4f %+0.4f \n"
" %+0.4f %+0.4f %+0.4f %+0.4f ]\n",
matrix_.get(0, 0),
matrix_.get(0, 1),
matrix_.get(0, 2),
matrix_.get(0, 3),
matrix_.get(1, 0),
matrix_.get(1, 1),
matrix_.get(1, 2),
matrix_.get(1, 3),
matrix_.get(2, 0),
matrix_.get(2, 1),
matrix_.get(2, 2),
matrix_.get(2, 3),
matrix_.get(3, 0),
matrix_.get(3, 1),
matrix_.get(3, 2),
matrix_.get(3, 3));
}
} // namespace gfx

View File

@@ -0,0 +1,317 @@
// Copyright (c) 2012 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.
#ifndef UI_GFX_TRANSFORM_H_
#define UI_GFX_TRANSFORM_H_
#include <iosfwd>
#include <string>
#include "base/compiler_specific.h"
#include "third_party/skia/include/core/SkMatrix44.h"
#include "ui/gfx/geometry/vector2d_f.h"
#include "ui/gfx/geometry_skia_export.h"
namespace gfx {
class BoxF;
class RectF;
class RRectF;
class Point;
class PointF;
class Point3F;
class Quaternion;
class Vector3dF;
// 4x4 transformation matrix. Transform is cheap and explicitly allows
// copy/assign.
class GEOMETRY_SKIA_EXPORT Transform {
public:
enum SkipInitialization {
kSkipInitialization
};
constexpr Transform() : matrix_(SkMatrix44::kIdentity_Constructor) {}
// Skips initializing this matrix to avoid overhead, when we know it will be
// initialized before use.
Transform(SkipInitialization)
: matrix_(SkMatrix44::kUninitialized_Constructor) {}
Transform(const Transform& rhs) : matrix_(rhs.matrix_) {}
// Initialize with the concatenation of lhs * rhs.
Transform(const Transform& lhs, const Transform& rhs)
: matrix_(lhs.matrix_, rhs.matrix_) {}
explicit Transform(const SkMatrix44& matrix) : matrix_(matrix) {}
// Constructs a transform from explicit 16 matrix elements. Elements
// should be given in row-major order.
Transform(SkScalar col1row1,
SkScalar col2row1,
SkScalar col3row1,
SkScalar col4row1,
SkScalar col1row2,
SkScalar col2row2,
SkScalar col3row2,
SkScalar col4row2,
SkScalar col1row3,
SkScalar col2row3,
SkScalar col3row3,
SkScalar col4row3,
SkScalar col1row4,
SkScalar col2row4,
SkScalar col3row4,
SkScalar col4row4);
// Constructs a transform from explicit 2d elements. All other matrix
// elements remain the same as the corresponding elements of an identity
// matrix.
Transform(SkScalar col1row1,
SkScalar col2row1,
SkScalar col1row2,
SkScalar col2row2,
SkScalar x_translation,
SkScalar y_translation);
// Constructs a transform corresponding to the given quaternion.
explicit Transform(const Quaternion& q);
bool operator==(const Transform& rhs) const { return matrix_ == rhs.matrix_; }
bool operator!=(const Transform& rhs) const { return matrix_ != rhs.matrix_; }
// Resets this transform to the identity transform.
void MakeIdentity() { matrix_.setIdentity(); }
// Applies the current transformation on a 2d rotation and assigns the result
// to |this|.
void Rotate(double degrees) { RotateAboutZAxis(degrees); }
// Applies the current transformation on an axis-angle rotation and assigns
// the result to |this|.
void RotateAboutXAxis(double degrees);
void RotateAboutYAxis(double degrees);
void RotateAboutZAxis(double degrees);
void RotateAbout(const Vector3dF& axis, double degrees);
// Applies the current transformation on a scaling and assigns the result
// to |this|.
void Scale(SkScalar x, SkScalar y);
void Scale3d(SkScalar x, SkScalar y, SkScalar z);
gfx::Vector2dF Scale2d() const {
return gfx::Vector2dF(matrix_.get(0, 0), matrix_.get(1, 1));
}
// Applies a scale to the current transformation and assigns the result to
// |this|.
void PostScale(SkScalar x, SkScalar y);
// Applies the current transformation on a translation and assigns the result
// to |this|.
void Translate(const Vector2dF& offset);
void Translate(SkScalar x, SkScalar y);
void Translate3d(const Vector3dF& offset);
void Translate3d(SkScalar x, SkScalar y, SkScalar z);
// Applies a translation to the current transformation and assigns the result
// to |this|.
void PostTranslate(const Vector2dF& offset);
void PostTranslate(SkScalar x, SkScalar y);
// Applies the current transformation on a skew and assigns the result
// to |this|.
void Skew(double angle_x, double angle_y);
// Applies the current transformation on a perspective transform and assigns
// the result to |this|.
void ApplyPerspectiveDepth(SkScalar depth);
// Applies a transformation on the current transformation
// (i.e. 'this = this * transform;').
void PreconcatTransform(const Transform& transform);
// Applies a transformation on the current transformation
// (i.e. 'this = transform * this;').
void ConcatTransform(const Transform& transform);
// Returns true if this is the identity matrix.
// This function modifies a mutable variable in |matrix_|.
bool IsIdentity() const { return matrix_.isIdentity(); }
// Returns true if the matrix is either identity or pure translation.
bool IsIdentityOrTranslation() const { return matrix_.isTranslate(); }
// Returns true if the matrix is either the identity or a 2d translation.
bool IsIdentityOr2DTranslation() const {
return matrix_.isTranslate() && matrix_.get(2, 3) == 0;
}
// Returns true if the matrix is either identity or pure translation,
// allowing for an amount of inaccuracy as specified by the parameter.
bool IsApproximatelyIdentityOrTranslation(SkScalar tolerance) const;
bool IsApproximatelyIdentityOrIntegerTranslation(SkScalar tolerance) const;
// Returns true if the matrix is either a positive scale and/or a translation.
bool IsPositiveScaleOrTranslation() const {
if (!IsScaleOrTranslation())
return false;
return matrix_.get(0, 0) > 0.0 && matrix_.get(1, 1) > 0.0 &&
matrix_.get(2, 2) > 0.0;
}
// Returns true if the matrix is identity or, if the matrix consists only
// of a translation whose components can be represented as integers. Returns
// false if the translation contains a fractional component or is too large to
// fit in an integer.
bool IsIdentityOrIntegerTranslation() const;
// Returns true if the matrix had only scaling components.
bool IsScale2d() const { return matrix_.isScale(); }
// Returns true if the matrix is has only scaling and translation components.
bool IsScaleOrTranslation() const { return matrix_.isScaleTranslate(); }
// Returns true if axis-aligned 2d rects will remain axis-aligned after being
// transformed by this matrix.
bool Preserves2dAxisAlignment() const;
// Returns true if the matrix has any perspective component that would
// change the w-component of a homogeneous point.
bool HasPerspective() const { return matrix_.hasPerspective(); }
// Returns true if this transform is non-singular.
bool IsInvertible() const { return matrix_.invert(NULL); }
// Returns true if a layer with a forward-facing normal of (0, 0, 1) would
// have its back side facing frontwards after applying the transform.
bool IsBackFaceVisible() const;
// Inverts the transform which is passed in. Returns true if successful, or
// sets |transform| to the identify matrix on failure.
bool GetInverse(Transform* transform) const WARN_UNUSED_RESULT;
// Transposes this transform in place.
void Transpose();
// Set 3rd row and 3rd colum to (0, 0, 1, 0). Note that this flattening
// operation is not quite the same as an orthographic projection and is
// technically not a linear operation.
//
// One useful interpretation of doing this operation:
// - For x and y values, the new transform behaves effectively like an
// orthographic projection was added to the matrix sequence.
// - For z values, the new transform overrides any effect that the transform
// had on z, and instead it preserves the z value for any points that are
// transformed.
// - Because of linearity of transforms, this flattened transform also
// preserves the effect that any subsequent (multiplied from the right)
// transforms would have on z values.
//
void FlattenTo2d();
// Returns true if the 3rd row and 3rd column are both (0, 0, 1, 0).
bool IsFlat() const;
// Returns the x and y translation components of the matrix.
Vector2dF To2dTranslation() const;
// Applies the transformation to the point.
void TransformPoint(Point3F* point) const;
// Applies the transformation to the point.
void TransformPoint(PointF* point) const;
// Applies the transformation to the point.
void TransformPoint(Point* point) const;
// Applies the transformation to the vector.
void TransformVector(Vector3dF* vector) const;
// Applies the reverse transformation on the point. Returns true if the
// transformation can be inverted.
bool TransformPointReverse(Point3F* point) const;
// Applies the reverse transformation on the point. Returns true if the
// transformation can be inverted. Rounds the result to the nearest point.
bool TransformPointReverse(Point* point) const;
// Applies transformation on the given rect. After the function completes,
// |rect| will be the smallest axis aligned bounding rect containing the
// transformed rect.
void TransformRect(RectF* rect) const;
// Applies the reverse transformation on the given rect. After the function
// completes, |rect| will be the smallest axis aligned bounding rect
// containing the transformed rect. Returns false if the matrix cannot be
// inverted.
bool TransformRectReverse(RectF* rect) const;
// Applies transformation on the given |rrect|. Returns false if the transform
// matrix cannot be applied to rrect.
bool TransformRRectF(RRectF* rrect) const;
// Applies transformation on the given box. After the function completes,
// |box| will be the smallest axis aligned bounding box containing the
// transformed box.
void TransformBox(BoxF* box) const;
// Applies the reverse transformation on the given box. After the function
// completes, |box| will be the smallest axis aligned bounding box
// containing the transformed box. Returns false if the matrix cannot be
// inverted.
bool TransformBoxReverse(BoxF* box) const;
// Decomposes |this| and |from|, interpolates the decomposed values, and
// sets |this| to the reconstituted result. Returns false if either matrix
// can't be decomposed. Uses routines described in this spec:
// http://www.w3.org/TR/css3-3d-transforms/.
//
// Note: this call is expensive since we need to decompose the transform. If
// you're going to be calling this rapidly (e.g., in an animation) you should
// decompose once using gfx::DecomposeTransforms and reuse your
// DecomposedTransform.
bool Blend(const Transform& from, double progress);
void RoundTranslationComponents();
// Returns |this| * |other|.
Transform operator*(const Transform& other) const {
return Transform(*this, other);
}
// Sets |this| = |this| * |other|
Transform& operator*=(const Transform& other) {
PreconcatTransform(other);
return *this;
}
// Returns the underlying matrix.
const SkMatrix44& matrix() const { return matrix_; }
SkMatrix44& matrix() { return matrix_; }
bool ApproximatelyEqual(const gfx::Transform& transform) const;
std::string ToString() const;
private:
void TransformPointInternal(const SkMatrix44& xform,
Point* point) const;
void TransformPointInternal(const SkMatrix44& xform, PointF* point) const;
void TransformPointInternal(const SkMatrix44& xform,
Point3F* point) const;
void TransformVectorInternal(const SkMatrix44& xform,
Vector3dF* vector) const;
SkMatrix44 matrix_;
// copy/assign are allowed.
};
// This is declared here for use in gtest-based unit tests but is defined in
// the //ui/gfx:test_support target. Depend on that to use this in your unit
// test. This should not be used in production code - call ToString() instead.
void PrintTo(const Transform& transform, ::std::ostream* os);
} // namespace gfx
#endif // UI_GFX_TRANSFORM_H_