From 35425896b07b5124651c249d6ce29285cf71ea3b Mon Sep 17 00:00:00 2001 From: Tom Sepez Date: Thu, 5 Feb 2015 10:03:18 -0800 Subject: Merge to XFA: Add namespace and-re-arrange PDFium's local copy of /base. Original revieww URL: https://codereview.chromium.org/900753002 TBR=jam@chromium.org Review URL: https://codereview.chromium.org/880603004 --- third_party/base/numerics/safe_conversions.h | 66 ++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 third_party/base/numerics/safe_conversions.h (limited to 'third_party/base/numerics/safe_conversions.h') diff --git a/third_party/base/numerics/safe_conversions.h b/third_party/base/numerics/safe_conversions.h new file mode 100644 index 0000000000..e95608e0a5 --- /dev/null +++ b/third_party/base/numerics/safe_conversions.h @@ -0,0 +1,66 @@ +// 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 PDFIUM_THIRD_PARTY_BASE_SAFE_CONVERSIONS_H_ +#define PDFIUM_THIRD_PARTY_BASE_SAFE_CONVERSIONS_H_ + +#include + +#include "../logging.h" +#include "safe_conversions_impl.h" + +namespace pdfium { +namespace base { + +// Convenience function that returns true if the supplied value is in range +// for the destination type. +template +inline bool IsValueInRangeForNumericType(Src value) { + return internal::DstRangeRelationToSrcRange(value) == + internal::RANGE_VALID; +} + +// 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 +inline Dst checked_cast(Src value) { + CHECK(IsValueInRangeForNumericType(value)); + return static_cast(value); +} + +// saturated_cast<> is analogous to static_cast<> for numeric types, except +// that the specified numeric conversion will saturate rather than overflow or +// underflow. NaN assignment to an integral will trigger a CHECK condition. +template +inline Dst saturated_cast(Src value) { + // Optimization for floating point values, which already saturate. + if (std::numeric_limits::is_iec559) + return static_cast(value); + + switch (internal::DstRangeRelationToSrcRange(value)) { + case internal::RANGE_VALID: + return static_cast(value); + + case internal::RANGE_UNDERFLOW: + return std::numeric_limits::min(); + + case internal::RANGE_OVERFLOW: + return std::numeric_limits::max(); + + // Should fail only on attempting to assign NaN to a saturated integer. + case internal::RANGE_INVALID: + CHECK(false); + return std::numeric_limits::max(); + } + + NOTREACHED(); + return static_cast(value); +} + +} // namespace base +} // namespace pdfium + +#endif // PDFIUM_THIRD_PARTY_BASE_SAFE_CONVERSIONS_H_ + -- cgit v1.2.3