byte_swap.hh

00001 /* vim: set sw=4 sts=4 et foldmethod=syntax : */
00002 
00003 /*
00004  * Copyright (c) 2007, 2008 David Leverton
00005  *
00006  * This file is part of the Paludis package manager. Paludis is free software;
00007  * you can redistribute it and/or modify it under the terms of the GNU General
00008  * Public License version 2, as published by the Free Software Foundation.
00009  *
00010  * Paludis is distributed in the hope that it will be useful, but WITHOUT ANY
00011  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
00012  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
00013  * details.
00014  *
00015  * You should have received a copy of the GNU General Public License along with
00016  * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
00017  * Place, Suite 330, Boston, MA  02111-1307  USA
00018  */
00019 
00020 #ifndef PALUDIS_GUARD_PALUDIS_UTIL_BYTE_SWAP_HH
00021 #define PALUDIS_GUARD_PALUDIS_UTIL_BYTE_SWAP_HH
00022 
00023 #include <cstddef>
00024 
00025 namespace paludis
00026 {
00027     namespace byte_swap_internals
00028     {
00029         template <std::size_t, typename> struct ByteSwap;
00030 
00031         template <typename T_>
00032         struct ByteSwap<1, T_>
00033         {
00034             static T_ swap(T_ x)
00035             {
00036                 return x;
00037             }
00038         };
00039 
00040         template <typename T_>
00041         struct ByteSwap<2, T_>
00042         {
00043             static T_ swap(T_ x)
00044             {
00045                 return ((x << 8) & (T_(0xFF) << 8)) | ((x >> 8) & T_(0xFF));
00046             }
00047         };
00048 
00049         template <typename T_>
00050         struct ByteSwap<4, T_>
00051         {
00052             static T_ swap(T_ x)
00053             {
00054                 return ((x << 24) & (T_(0xFF) << 24)) | ((x <<  8) & (T_(0xFF) << 16))
00055                      | ((x >>  8) & (T_(0xFF) <<  8)) | ((x >> 24) &  T_(0xFF)       );
00056             }
00057         };
00058 
00059         template <typename T_>
00060         struct ByteSwap<8, T_>
00061         {
00062             static T_ swap(T_ x)
00063             {
00064                 return ((x << 56) & (T_(0xFF) << 56)) | ((x << 40) & (T_(0xFF) << 48))
00065                      | ((x << 24) & (T_(0xFF) << 40)) | ((x <<  8) & (T_(0xFF) << 32))
00066                      | ((x >>  8) & (T_(0xFF) << 24)) | ((x >> 24) & (T_(0xFF) << 16))
00067                      | ((x >> 40) & (T_(0xFF) <<  8)) | ((x >> 56) &  T_(0xFF)       );
00068             }
00069         };
00070     }
00071 
00072     template <typename T_>
00073     inline T_
00074     byte_swap(T_ x)
00075     {
00076         return byte_swap_internals::ByteSwap<sizeof(T_), T_>::swap(x);
00077     }
00078 }
00079 
00080 #endif

Generated on Mon Sep 21 10:36:08 2009 for paludis by  doxygen 1.5.4