libmoost
/home/mhx/git/github/libmoost/include/moost/nagios/detail/nsca_crc32.hpp
Go to the documentation of this file.
00001 /* vim:set ts=3 sw=3 sts=3 et: */
00028 #ifndef MOOST_NAGIOS_NSCA_CRC32_HPP__
00029 #define MOOST_NAGIOS_NSCA_CRC32_HPP__
00030 
00031 #include <boost/cstdint.hpp>
00032 
00033 #include <vector>
00034 
00035 namespace moost { namespace nagios {
00036 
00037    //---> NASTY CODE ALERT
00038    // [ricky 7/14/2011] hoiked (and cleaned up a tad) from nsca_send
00039    class nsca_crc32
00040    {
00041    public:
00042 
00043       nsca_crc32()
00044          : crc32_table_(crc32_table_size)
00045       {
00046          generate_crc32_table();
00047       }
00048 
00049       boost::uint32_t calculate(nsca_data_packet const & send_packet) const
00050       {
00051          char const * buffer = reinterpret_cast<char const *>(&send_packet);
00052          size_t const buffer_size = sizeof(send_packet);
00053 
00054          boost::uint32_t crc = 0xFFFFFFFF;
00055          boost::uint32_t  this_char;
00056 
00057          crc=0xFFFFFFFF;
00058 
00059          for(size_t current_index = 0 ; current_index < buffer_size ; current_index++)
00060          {
00061             this_char = buffer[current_index];
00062             crc = ((crc >> 8) & 0x00FFFFFF) ^ crc32_table_[(crc ^ this_char) & 0xFF];
00063          }
00064 
00065          return (crc ^ 0xFFFFFFFF);
00066       }
00067 
00068    private:
00069       void generate_crc32_table()
00070       {
00071          boost::uint32_t crc;
00072          boost::uint32_t const poly = 0xEDB88320L;
00073 
00074          for(boost::uint32_t i=0 ; i < crc32_table_size ; i++)
00075          {
00076             crc = i;
00077             for(size_t j = 8 ; j > 0 ; j--)
00078             {
00079                if(crc & 1)
00080                {
00081                   crc = (crc >> 1) ^ poly;
00082                }
00083                else
00084                {
00085                   crc >>= 1;
00086                }
00087             }
00088 
00089             crc32_table_[i] = crc;
00090          }
00091 
00092          return;
00093       }
00094 
00095 
00096    private:
00097       std::vector<boost::uint32_t> crc32_table_;
00098       static size_t const crc32_table_size = 256;
00099    };
00100    // ---<
00101 
00102 }}
00103 
00104 #endif