monotone

monotone Mtn Source Tree

Root/numeric_vocab.hh

1#ifndef __NUMERIC_VOCAB__
2#define __NUMERIC_VOCAB__
3
4// Copyright (C) 2004 Graydon Hoare <graydon@pobox.com>
5//
6// This program is made available under the GNU GPL version 2.0 or
7// greater. See the accompanying file COPYING for details.
8//
9// This program is distributed WITHOUT ANY WARRANTY; without even the
10// implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
11// PURPOSE.
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// Local Variables:
53// mode: C++
54// fill-column: 76
55// c-file-style: "gnu"
56// indent-tabs-mode: nil
57// End:
58// vim: et:sw=2:sts=2:ts=2:cino=>2s,{s,\:s,+s,t0,g0,^-2,e-2,n-2,p2s,(0,=s:
59
60#endif

Archive Download this file

Branches

Tags

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