1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #ifndef vm_Uint8Clamped_h
8 #define vm_Uint8Clamped_h
14 extern uint32_t ClampDoubleToUint8(const double x
);
16 struct uint8_clamped
{
19 uint8_clamped() = default;
20 uint8_clamped(const uint8_clamped
& other
) = default;
22 // invoke our assignment helpers for constructor conversion
23 explicit uint8_clamped(uint8_t x
) { *this = x
; }
24 explicit uint8_clamped(uint16_t x
) { *this = x
; }
25 explicit uint8_clamped(uint32_t x
) { *this = x
; }
26 explicit uint8_clamped(uint64_t x
) { *this = x
; }
27 explicit uint8_clamped(int8_t x
) { *this = x
; }
28 explicit uint8_clamped(int16_t x
) { *this = x
; }
29 explicit uint8_clamped(int32_t x
) { *this = x
; }
30 explicit uint8_clamped(int64_t x
) { *this = x
; }
31 explicit uint8_clamped(double x
) { *this = x
; }
33 uint8_clamped
& operator=(const uint8_clamped
& x
) = default;
35 uint8_clamped
& operator=(uint8_t x
) {
40 uint8_clamped
& operator=(uint16_t x
) {
41 val
= (x
> 255) ? 255 : uint8_t(x
);
45 uint8_clamped
& operator=(uint32_t x
) {
46 val
= (x
> 255) ? 255 : uint8_t(x
);
50 uint8_clamped
& operator=(uint64_t x
) {
51 val
= (x
> 255) ? 255 : uint8_t(x
);
55 uint8_clamped
& operator=(int8_t x
) {
56 val
= (x
>= 0) ? uint8_t(x
) : 0;
60 uint8_clamped
& operator=(int16_t x
) {
61 val
= (x
>= 0) ? ((x
< 255) ? uint8_t(x
) : 255) : 0;
65 uint8_clamped
& operator=(int32_t x
) {
66 val
= (x
>= 0) ? ((x
< 255) ? uint8_t(x
) : 255) : 0;
70 uint8_clamped
& operator=(int64_t x
) {
71 val
= (x
>= 0) ? ((x
< 255) ? uint8_t(x
) : 255) : 0;
75 uint8_clamped
& operator=(const double x
) {
76 val
= uint8_t(ClampDoubleToUint8(x
));
80 operator uint8_t() const { return val
; }
82 void staticAsserts() {
83 static_assert(sizeof(uint8_clamped
) == 1,
84 "uint8_clamped must be layout-compatible with uint8_t");
88 /* Note that we can't use std::numeric_limits here due to uint8_clamped. */
90 inline constexpr bool TypeIsFloatingPoint() {
94 inline constexpr bool TypeIsFloatingPoint
<float>() {
98 inline constexpr bool TypeIsFloatingPoint
<double>() {
102 template <typename T
>
103 inline constexpr bool TypeIsUnsigned() {
107 inline constexpr bool TypeIsUnsigned
<uint8_t>() {
111 inline constexpr bool TypeIsUnsigned
<uint16_t>() {
115 inline constexpr bool TypeIsUnsigned
<uint32_t>() {
121 #endif // vm_Uint8Clamped_h