⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 numerics.ipp

📁 著名的Parser库Spirit在VC6上的Port
💻 IPP
📖 第 1 页 / 共 2 页
字号:
/*=============================================================================
    Numeric parsers

    Spirit V1.2
    Copyright (c) 2001, Joel de Guzman
    Copyright (c) 2001, Hartmut Kaiser

    This software is provided 'as-is', without any express or implied
    warranty. In no event will the copyright holder be held liable for
    any damages arising from the use of this software.

    Permission is granted to anyone to use this software for any purpose,
    including commercial applications, and to alter it and redistribute
    it freely, subject to the following restrictions:

    1.  The origin of this software must not be misrepresented; you must
        not claim that you wrote the original software. If you use this
        software in a product, an acknowledgment in the product documentation
        would be appreciated but is not required.

    2.  Altered source versions must be plainly marked as such, and must
        not be misrepresented as being the original software.

    3.  This notice may not be removed or altered from any source
        distribution.

    Acknowledgements:

        Special thanks to Dan Nuffer, John (EBo) David, Chris Uzdavinis,
        and Doug Gregor. These people are most instrumental in steering
        Spirit in the right direction.

        Special thanks also to people who have contributed to the code Radix
        and sample code, ported Spirit to various platforms and compilers,
        reported and provided bug fixes. Alexander Hirner, Andy Elvey,
        Bogdan Kushnir, Brett Calcott, Bruce Florman, Changzhe Han, Colin
        McPhail, Hakki Dogusan, Jan Bares, Joseph Smith, Martijn W. van der
        Lee, Raghavendra Satish, Remi Delcos, Tom Spilman, Vladimir Prus,
        W. Scott Dillman.

        Finally special thanks also to people who gave feedback and
        valuable comments, particularly members of Spirit's Source Forge
        mailing list and boost.org.

    URL: http://spirit.sourceforge.net/

=============================================================================*/
#ifndef SPIRIT_NUMERICS_IPP
#define SPIRIT_NUMERICS_IPP

///////////////////////////////////////////////////////////////////////////////

#include <cmath>
#include <functional>
#include <iterator>

#include <assert.h>

#include "boost/spirit/primitives.hpp"
#include "boost/spirit/iterators.hpp"

///////////////////////////////////////////////////////////////////////////////
namespace spirit {

//////////////////////////////////
namespace impl {

    //////////////////////////////////
    template <typename IteratorT>
    bool
    extract_sign(IteratorT& iter, unsigned& count)
    {
        //  Extract the sign

        count = 0;
        bool neg = *iter == '-';
        if (neg || (*iter == '+'))
        {
            ++iter;
            ++count;
            return neg;
        }

        return false;
    }

///////////////////////////////////////////////////////////////////////////////
// Traits class for number conversion
    template<const int Radix>
    struct radix_traits
    {
    // Tests validity of a single character in the context of the given
    // radix (template parameter Radix)
        template<typename CharT> static bool isok(CharT ch);

    // Converts a digit from character representation to binary representation
    // in the context of the given radix (template parameter Radix)
        template<typename CharT> static int uint(CharT ch);
    };

    template<>
    struct radix_traits<2> {
        template<typename CharT>
        static bool isok(CharT ch) { return ('0' == ch || '1' == ch); }

        template<typename CharT>
        static int uint(CharT ch) { return ch - '0'; }
    };

    template<>
    struct radix_traits<8> {
        template<typename CharT>
        static bool isok(CharT ch) { return ('0' <= ch && ch <= '7'); }

        template<typename CharT>
        static int uint(CharT ch) { return ch - '0'; }
    };

    template<>
    struct radix_traits<10> {
        template<typename CharT>
        static bool isok(CharT ch) { return isdigit(ch); }

        template<typename CharT>
        static int uint(CharT ch) { return ch - '0'; }
    };

    template<>
    struct radix_traits<16> {
        template<typename CharT>
        static bool isok(CharT ch) { return isxdigit(ch); }

        template<typename CharT>
        static int uint(CharT ch)
        {
            if (isdigit(ch))
                return ch - '0';
            return tolower(ch) - 'a' + 10;
        }
    };

///////////////////////////////////////////////////////////////////////////////
// Helper templates for abstracting the compare methods for different 
// numeric_parser_traits classes
    template<typename IteratorT>
    struct trait_type_cmp
    {
    // trait is given as a parser (template parameter ParserT)
        template <typename ParserT>
        static match parse (parser<ParserT> p, IteratorT &it1, IteratorT const &it2) 
        {
            return p.derived().parse(it1, it2);
        }
        template <typename ParserT>
        static match parse2 (parser<ParserT> p, IteratorT &it1, IteratorT const &it2) 
        {
            return parse (p.derived(), it1, it2);
        }

    // trait is given as a single character
        typedef typename std::iterator_traits<IteratorT>::value_type CharT;
        static match parse (CharT ch, IteratorT &it1, IteratorT const &/*it2*/) 
        {
            if (ch == *it1) {
                ++it1;
                return match(1);
            }
            return match();
        }
        static match parse2 (CharT ch, IteratorT &it1, IteratorT const &it2) 
        {
            return nocase[ch].parse(it1, it2);
        }

    // trait is given as a string
        typedef typename std::iterator_traits<IteratorT>::pointer PointerT;
        static match parse (PointerT pch, IteratorT &it1, IteratorT const &it2) 
        {
            typedef typename std::iterator_traits<IteratorT>::value_type CharT;
            return strlit<CharT>(pch).parse(it1, it2);
        }
        static match parse2 (PointerT pch, IteratorT &it1, 
                IteratorT const &it2) 
        {
            return parse (pch, it1, it2);
        }
    };
/*
    template<typename IteratorT, typename ParserT>
    struct trait_type_cmp
    {
    // trait is given as a parser (template parameter ParserT)
        static match parse (ParserT p, IteratorT &it1, IteratorT const &it2) 
        {
            return p.parse(it1, it2);
        }
        static match parse2 (ParserT p, IteratorT &it1, IteratorT const &it2) 
        {
            return parse (p, it1, it2);
        }
    };

    template<typename IteratorT>
    struct trait_type_cmp<IteratorT, const int> 
    {
    // trait is given as a single character
        typedef typename std::iterator_traits<IteratorT>::value_type CharT;
        static match parse (CharT ch, IteratorT &it1, IteratorT const &) 
        {
            if (ch == *it1) {
                ++it1;
                return match(1);
            }
            return match();
        }
        static match parse2 (CharT ch, IteratorT &it1, IteratorT const &it2) 
        {
            return nocase[ch].parse(it1, it2);
        }
    };

    template<typename IteratorT>
    struct trait_type_cmp<IteratorT, 
        const std::iterator_traits<IteratorT>::pointer> 
    {
    // trait is given as a string
        typedef typename std::iterator_traits<IteratorT>::pointer PointerT;
        static match parse (PointerT pch, IteratorT &it1, IteratorT const &it2) 
        {
            typedef typename std::iterator_traits<IteratorT>::value_type CharT;
            return strlit<CharT>(pch).parse(it1, it2);
        }
        static match parse2 (PointerT pch, IteratorT &it1, 
                IteratorT const &it2) 
        {
            return parse (pch, it1, it2);
        }
    };
*/
    template<typename TraitsT>
    struct traits_cmp {
    // tests for decimal separator
        template<typename IteratorT>
        static bool is_ds(IteratorT &it1, IteratorT const &it2, unsigned &count)
        {
            typedef trait_type_cmp<IteratorT> 
                trait_type;
            match mexpr = 
                trait_type::parse(TraitsT::decimal_sep_char, it1, it2);
            if (mexpr) {
                count += mexpr.length();
                return true;
            }
            return false;
        }

    // tests for thousands separator
        template<typename IteratorT>
        static bool is_ts(IteratorT &it1, IteratorT const &it2, unsigned &count)
        {
            if (TraitsT::thousands_sep_char != 0) {
                typedef trait_type_cmp<IteratorT> trait_type;
                match mexpr = 
                    trait_type::parse(TraitsT::thousands_sep_char, it1, it2);
                if (mexpr) {
                    count += mexpr.length();
                    return true;
                }
            }
            return false;
        }

    // tests for delimiter before exponent
        template<typename IteratorT>
        static bool is_exp(IteratorT &it1, IteratorT const &it2, 
                unsigned &count)
        {
            typedef trait_type_cmp<IteratorT> trait_type;
            match mexpr = trait_type::parse2(TraitsT::exponent_char, it1, it2);
            if (mexpr) {
                count += mexpr.length();
                return true;
            }
            return false;
        }
    };

///////////////////////////////////////////////////////////////////////////////
// Helper template functors for distinction of overflow testing for signed and
// unsigned data types. The template parameter T represents the parsed data type.
    template<typename T>
    struct nochange : std::unary_function<T, T>
    {
          T operator()(const T& x) const { return x; }
    };

    template<typename T>
    struct decrement : std::unary_function<T, T>
    {
          T operator()(const T& x) const { return x-1; }
    };

// Helper template for encapsulation of radix specific conversion of an input 
// string to an integral integer-like value.
//
// The template parameter Radix represents the radix of the number contained
// in the parsed string
    template <const int Radix, typename TraitsT = numeric_parser_traits<> >
    struct extract {
    // Extract a signed integer
    // Returns a non-match, if the number to parse overflows the used integral 
    // type.
    //
    // BEWARE: the parameters 'n' and 'count' should be proper initialized 
    // before calling this function.
        template <typename IteratorT, typename T>
        static bool sint(IteratorT& first, IteratorT const& last, T& n, 
                unsigned& count, bool neg)
        {
            typedef typename remove_wrap<T>::type arg_type;
            if (!neg)
                return uint(first, last, n, count, nochange<arg_type>());

            // Intel V5.0.1 chokes without explicit template parameters
            return uint<IteratorT, T, decrement<arg_type> >(first, last, n, 
                    count, decrement<arg_type>());
        }

    // Extract an unsigned integer
    // Return a non-match, if the number to parse overflows the used integral 
    // type.
    //
    // BEWARE: the parameters 'n' and 'count' should be proper initialized 
    // before calling this functions.
        template <typename IteratorT, typename T>
        static bool uint(IteratorT& first, IteratorT const& last, T& n, 
                unsigned& count)
        {
            typedef typename remove_wrap<T>::type arg_type;
            return uint(first, last, n, count, nochange<arg_type>());
        }

        template <typename IteratorT, typename T, typename PredT>
        static bool uint(IteratorT& first, IteratorT const& last, T& n, 
                unsigned& count, const PredT &pred)
        {
            typedef remove_wrap<T>::type arg_type;

        const arg_type lim = std::numeric_limits<arg_type>::max()/Radix;

            for (/**/; first != last; ++first, ++count)
            {
            // skip thousands separator if required
            unsigned ts = 0;

                if (traits_cmp<TraitsT>::is_ts(first, last, ts)) {
                    --first;        // roll back for loop reinit
                    count += ts-1;
                    continue;
                }

            // handle only 'valid' (in the context of the actual radix) digits
                if (radix_traits<Radix>::isok(*first)) {
                    if (n > lim) {
                    // overflow! return non-match
                        n = 0;
                        count = 0;
                        return false;
                    }
                    n *= Radix;            // operation is now safe

                arg_type nextdigit = radix_traits<Radix>::uint(*first);

                    if (pred(nextdigit) > std::numeric_limits<arg_type>::max() - n) {
                    // overflow! return non-match
                        n = 0;
                        count = 0;
                        return false;
                    }
                    n += nextdigit;            // operation is now safe too
                } else
                    break;
            }
            return true;
        }
    };

} // namespace impl

///////////////////////////////////////////////////////////////////////////////
//
//  numeric_action class implementation
//
///////////////////////////////////////////////////////////////////////////////
template <typename ParserT, typename ActionT>
inline numeric_action<ParserT, ActionT>::numeric_action(ActionT const& actor_)
:   unary<ParserT>(ParserT(0)), actor(actor_) {}

//////////////////////////////////
template <typename ParserT, typename ActionT>
template <typename IteratorT>
inline match
numeric_action<ParserT, ActionT>::
    parse(IteratorT& first, IteratorT const& last) const
{
    match hit = this->subject().parse(first, last);
    if (hit)
        actor(this->subject().n);
    return hit;
}

//////////////////////////////////
template <typename ParserT, typename ActionT>
template <typename IteratorT, typename MatchTraitsT>
inline typename MatchTraitsT::match_t
numeric_action<ParserT, ActionT>::
    ast_parse(IteratorT& first, IteratorT const& last, 
            MatchTraitsT const& mt) const
{
    typename MatchTraitsT::match_t hit = 
        this->subject().ast_parse(first, last, mt);
    if (hit)
        actor(this->subject().n);

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -