monotone

monotone Mtn Source Tree

Root/src/numeric_vocab.hh

1// Copyright (C) 2004 Graydon Hoare <graydon@pobox.com>
2//
3// This program is made available under the GNU GPL version 2.0 or
4// greater. See the accompanying file COPYING for details.
5//
6// This program is distributed WITHOUT ANY WARRANTY; without even the
7// implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
8// PURPOSE.
9
10#ifndef __NUMERIC_VOCAB__
11#define __NUMERIC_VOCAB__
12
13#include <cstddef>
14#include <climits> // Some architectures need this for CHAR_BIT
15 // The lack of this was reported as bug #19984
16#include <limits>
17#include <boost/static_assert.hpp>
18
19typedef TYPE_U8 u8;
20typedef TYPE_U16 u16;
21typedef TYPE_U32 u32;
22typedef TYPE_U64 u64;
23
24typedef TYPE_S8 s8;
25typedef TYPE_S16 s16;
26typedef TYPE_S32 s32;
27typedef TYPE_S64 s64;
28
29// This is similar to static_cast<T>(v). The difference is that when T is
30// unsigned, this cast does not sign-extend:
31// static_cast<u32>((signed char) -1) = 4294967295
32// widen<u32,signed char>(-1) == 255
33template <typename T, typename V>
34inline T
35widen(V const & v)
36{
37 BOOST_STATIC_ASSERT(sizeof(T) >= sizeof(V));
38 if (std::numeric_limits<T>::is_signed)
39 return static_cast<T>(v);
40 else if (!std::numeric_limits<V>::is_signed)
41 return static_cast<T>(v);
42 else
43 {
44 const size_t char_bit = std::numeric_limits<unsigned char>::digits;
45 T mask = std::numeric_limits<T>::max();
46 size_t shift = (sizeof(T) - sizeof(V)) * char_bit;
47 mask >>= shift;
48 return static_cast<T>(v) & mask;
49 }
50}
51
52// Writing a 64-bit constant is tricky. We cannot use the macros that
53// <stdint.h> provides in C99 (INT64_C, or even INT64_MAX) because those
54// macros are not in C++'s version of <stdint.h>. std::numeric_limits<s64>
55// cannot be used directly, so we have to resort to #ifdef chains on the old
56// skool C limits macros. BOOST_STATIC_ASSERT is defined in a way that
57// doesn't let us use std::numeric_limits<s64>::max(), so we rely on
58// one of the users (the unit tests for dates.cc) to check it at runtime.
59
60#if defined LONG_MAX && LONG_MAX > UINT_MAX
61 #define PROBABLE_S64_MAX LONG_MAX
62 #define s64_C(x) x##L
63#elif defined LLONG_MAX && LLONG_MAX > UINT_MAX
64 #define PROBABLE_S64_MAX LLONG_MAX
65 #define s64_C(x) x##LL
66#elif defined LONG_LONG_MAX && LONG_LONG_MAX > UINT_MAX
67 #define PROBABLE_S64_MAX LONG_LONG_MAX
68 #define s64_C(x) x##LL
69#else
70 #error "How do I write a constant of type s64?"
71#endif
72
73#endif
74
75// Local Variables:
76// mode: C++
77// fill-column: 76
78// c-file-style: "gnu"
79// indent-tabs-mode: nil
80// End:
81// vim: et:sw=2:sts=2:ts=2:cino=>2s,{s,\:s,+s,t0,g0,^-2,e-2,n-2,p2s,(0,=s:

Archive Download this file

Branches

Tags

Quick Links:     www.monotone.ca    -     Downloads    -     Documentation    -     Wiki    -     Code Forge    -     Build Status