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 <limits>
15
16#include "mt-stdint.h"
17#include <boost/static_assert.hpp>
18
19typedef uint8_t u8;
20typedef uint16_t u16;
21typedef uint32_t u32;
22typedef uint64_t u64;
23
24BOOST_STATIC_ASSERT(sizeof(char) == 1);
25BOOST_STATIC_ASSERT(CHAR_BIT == 8);
26BOOST_STATIC_ASSERT(sizeof(u8) == 1);
27BOOST_STATIC_ASSERT(sizeof(u16) == 2);
28BOOST_STATIC_ASSERT(sizeof(u32) == 4);
29BOOST_STATIC_ASSERT(sizeof(u64) == 8);
30
31// This is similar to static_cast<T>(v). The difference is that when T is
32// unsigned, this cast does not sign-extend:
33// static_cast<u32>((signed char) -1) = 4294967295
34// widen<u32,signed char>(-1) == 255
35template <typename T, typename V>
36inline T
37widen(V const & v)
38{
39 BOOST_STATIC_ASSERT(sizeof(T) >= sizeof(V));
40 if (std::numeric_limits<T>::is_signed)
41 return static_cast<T>(v);
42 else if (!std::numeric_limits<V>::is_signed)
43 return static_cast<T>(v);
44 else
45 {
46 T mask = std::numeric_limits<T>::max();
47 size_t shift = (sizeof(T) - sizeof(V)) * 8;
48 mask >>= shift;
49 return static_cast<T>(v) & mask;
50 }
51}
52
53// Local Variables:
54// mode: C++
55// fill-column: 76
56// c-file-style: "gnu"
57// indent-tabs-mode: nil
58// End:
59// vim: et:sw=2:sts=2:ts=2:cino=>2s,{s,\:s,+s,t0,g0,^-2,e-2,n-2,p2s,(0,=s:
60
61#endif

Archive Download this file

Branches

Tags

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