<commit_before>// Copyright (c) 2014-2018 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/

#ifndef TAO_PEGTL_CONTRIB_UNESCAPE_HPP
#define TAO_PEGTL_CONTRIB_UNESCAPE_HPP

#include <cassert>
#include <string>

#include "../ascii.hpp"
#include "../config.hpp"
#include "../parse_error.hpp"

namespace tao
{
   namespace TAO_PEGTL_NAMESPACE
   {
      namespace unescape
      {
         struct state
         {
            std::string unescaped;
         };

         // Utility functions for the unescape actions.

         inline bool utf8_append_utf32( std::string& string, const unsigned utf32 )
         {
            if( utf32 <= 0x7f ) {
               string += char( utf32 & 0xff );
               return true;
            }
            if( utf32 <= 0x7ff ) {
               char tmp[] = { char( ( ( utf32 & 0x7c0 ) >> 6 ) | 0xc0 ),
                              char( ( ( utf32 & 0x03f ) ) | 0x80 ) };
               string.append( tmp, sizeof( tmp ) );
               return true;
            }
            if( utf32 <= 0xffff ) {
               if( utf32 >= 0xd800 && utf32 <= 0xdfff ) {
                  // nope, this is a UTF-16 surrogate
                  return false;
               }
               char tmp[] = { char( ( ( utf32 & 0xf000 ) >> 12 ) | 0xe0 ),
                              char( ( ( utf32 & 0x0fc0 ) >> 6 ) | 0x80 ),
                              char( ( ( utf32 & 0x003f ) ) | 0x80 ) };
               string.append( tmp, sizeof( tmp ) );
               return true;
            }
            if( utf32 <= 0x10ffff ) {
               char tmp[] = { char( ( ( utf32 & 0x1c0000 ) >> 18 ) | 0xf0 ),
                              char( ( ( utf32 & 0x03f000 ) >> 12 ) | 0x80 ),
                              char( ( ( utf32 & 0x000fc0 ) >> 6 ) | 0x80 ),
                              char( ( ( utf32 & 0x00003f ) ) | 0x80 ) };
               string.append( tmp, sizeof( tmp ) );
               return true;
            }
            return false;
         }

         // This function MUST only be called for characters matching tao::TAO_PEGTL_NAMESPACE::ascii::xdigit!
         template< typename I >
         I unhex_char( const char c )
         {
            switch( c ) {
               case '0':
               case '1':
               case '2':
               case '3':
               case '4':
               case '5':
               case '6':
               case '7':
               case '8':
               case '9':
                  return I( c - '0' );
               case 'a':
               case 'b':
               case 'c':
               case 'd':
               case 'e':
               case 'f':
                  return I( c - 'a' + 10 );
               case 'A':
               case 'B':
               case 'C':
               case 'D':
               case 'E':
               case 'F':
                  return I( c - 'A' + 10 );
            }
            throw std::runtime_error( "invalid character in unhex" );  // NOLINT, LCOV_EXCL_LINE
         }

         template< typename I >
         I unhex_string( const char* begin, const char* end )
         {
            I r = 0;
            while( begin != end ) {
               r <<= 4;
               r += unhex_char< I >( *begin++ );
            }
            return r;
         }

         // Actions for common unescape situations.

         struct append_all
         {
            template< typename Input, typename State >
            static void apply( const Input& in, State& st )
            {
               st.unescaped.append( in.begin(), in.size() );
            }
         };

         // This action MUST be called for a character matching T which MUST be tao::TAO_PEGTL_NAMESPACE::one< ... >.
         template< typename T, char... Rs >
         struct unescape_c
         {
            template< typename Input, typename State >
            static void apply( const Input& in, State& st )
            {
               assert( in.size() == 1 );
               st.unescaped += apply_one( *in.begin(), static_cast< const T* >( nullptr ) );
            }

            template< char... Qs >
            static char apply_one( const char c, const one< Qs... >* /*unused*/ )
            {
               static_assert( sizeof...( Qs ) == sizeof...( Rs ), "size mismatch between escaped characters and their mappings" );
               return apply_two( c, { Qs... }, { Rs... } );
            }

            static char apply_two( const char c, const std::initializer_list< char >& q, const std::initializer_list< char >& r )
            {
               for( std::size_t i = 0; i < q.size(); ++i ) {
                  if( *( q.begin() + i ) == c ) {
                     return *( r.begin() + i );
                  }
               }
               throw std::runtime_error( "invalid character in unescape" );  // NOLINT, LCOV_EXCL_LINE
            }
         };

         // See src/example/pegtl/unescape.cpp for why the following two actions
         // skip the first input character. They also MUST be called
         // with non-empty matched inputs!

         struct unescape_u
         {
            template< typename Input, typename State >
            static void apply( const Input& in, State& st )
            {
               assert( !in.empty() );  // First character MUST be present, usually 'u' or 'U'.
               if( !utf8_append_utf32( st.unescaped, unhex_string< unsigned >( in.begin() + 1, in.end() ) ) ) {
                  throw parse_error( "invalid escaped unicode code point", in );
               }
            }
         };

         struct unescape_x
         {
            template< typename Input, typename State >
            static void apply( const Input& in, State& st )
            {
               assert( !in.empty() );  // First character MUST be present, usually 'x'.
               st.unescaped += unhex_string< char >( in.begin() + 1, in.end() );
            }
         };

         // The unescape_j action is similar to unescape_u, however unlike
         // unescape_u it
         // (a) assumes exactly 4 hexdigits per escape sequence,
         // (b) accepts multiple consecutive escaped 16-bit values.
         // When applied to more than one escape sequence, unescape_j
         // translates UTF-16 surrogate pairs in the input into a single
         // UTF-8 sequence in st.unescaped, as required for JSON by RFC 8259.

         struct unescape_j
         {
            template< typename Input, typename State >
            static void apply( const Input& in, State& st )
            {
               assert( ( ( in.size() + 1 ) % 6 ) == 0 );  // Expects multiple "\\u1234", starting with the first "u".
               for( const char* b = in.begin() + 1; b < in.end(); b += 6 ) {
                  const auto c = unhex_string< unsigned >( b, b + 4 );
                  if( ( 0xd800 <= c ) && ( c <= 0xdbff ) && ( b + 6 < in.end() ) ) {
                     const auto d = unhex_string< unsigned >( b + 6, b + 10 );
                     if( ( 0xdc00 <= d ) && ( d <= 0xdfff ) ) {
                        b += 6;
                        // note: no need to check the result code, as we are always >= 0x10000 and < 0x110000.
                        utf8_append_utf32( st.unescaped, ( ( ( c & 0x03ff ) << 10 ) | ( d & 0x03ff ) ) + 0x10000 );
                        continue;
                     }
                  }
                  if( !utf8_append_utf32( st.unescaped, c ) ) {
                     throw parse_error( "invalid escaped unicode code point", in );
                  }
               }
            }
         };

      }  // namespace unescape

   }  // namespace TAO_PEGTL_NAMESPACE

}  // namespace tao

#endif
<commit_msg>Improve exception for invalid escape characters<commit_after>// Copyright (c) 2014-2018 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/

#ifndef TAO_PEGTL_CONTRIB_UNESCAPE_HPP
#define TAO_PEGTL_CONTRIB_UNESCAPE_HPP

#include <cassert>
#include <string>

#include "../ascii.hpp"
#include "../config.hpp"
#include "../parse_error.hpp"

namespace tao
{
   namespace TAO_PEGTL_NAMESPACE
   {
      namespace unescape
      {
         struct state
         {
            std::string unescaped;
         };

         // Utility functions for the unescape actions.

         inline bool utf8_append_utf32( std::string& string, const unsigned utf32 )
         {
            if( utf32 <= 0x7f ) {
               string += char( utf32 & 0xff );
               return true;
            }
            if( utf32 <= 0x7ff ) {
               char tmp[] = { char( ( ( utf32 & 0x7c0 ) >> 6 ) | 0xc0 ),
                              char( ( ( utf32 & 0x03f ) ) | 0x80 ) };
               string.append( tmp, sizeof( tmp ) );
               return true;
            }
            if( utf32 <= 0xffff ) {
               if( utf32 >= 0xd800 && utf32 <= 0xdfff ) {
                  // nope, this is a UTF-16 surrogate
                  return false;
               }
               char tmp[] = { char( ( ( utf32 & 0xf000 ) >> 12 ) | 0xe0 ),
                              char( ( ( utf32 & 0x0fc0 ) >> 6 ) | 0x80 ),
                              char( ( ( utf32 & 0x003f ) ) | 0x80 ) };
               string.append( tmp, sizeof( tmp ) );
               return true;
            }
            if( utf32 <= 0x10ffff ) {
               char tmp[] = { char( ( ( utf32 & 0x1c0000 ) >> 18 ) | 0xf0 ),
                              char( ( ( utf32 & 0x03f000 ) >> 12 ) | 0x80 ),
                              char( ( ( utf32 & 0x000fc0 ) >> 6 ) | 0x80 ),
                              char( ( ( utf32 & 0x00003f ) ) | 0x80 ) };
               string.append( tmp, sizeof( tmp ) );
               return true;
            }
            return false;
         }

         // This function MUST only be called for characters matching tao::TAO_PEGTL_NAMESPACE::ascii::xdigit!
         template< typename I >
         I unhex_char( const char c )
         {
            switch( c ) {
               case '0':
               case '1':
               case '2':
               case '3':
               case '4':
               case '5':
               case '6':
               case '7':
               case '8':
               case '9':
                  return I( c - '0' );
               case 'a':
               case 'b':
               case 'c':
               case 'd':
               case 'e':
               case 'f':
                  return I( c - 'a' + 10 );
               case 'A':
               case 'B':
               case 'C':
               case 'D':
               case 'E':
               case 'F':
                  return I( c - 'A' + 10 );
            }
            throw std::runtime_error( "invalid character in unhex" );  // NOLINT, LCOV_EXCL_LINE
         }

         template< typename I >
         I unhex_string( const char* begin, const char* end )
         {
            I r = 0;
            while( begin != end ) {
               r <<= 4;
               r += unhex_char< I >( *begin++ );
            }
            return r;
         }

         // Actions for common unescape situations.

         struct append_all
         {
            template< typename Input, typename State >
            static void apply( const Input& in, State& st )
            {
               st.unescaped.append( in.begin(), in.size() );
            }
         };

         // This action MUST be called for a character matching T which MUST be tao::TAO_PEGTL_NAMESPACE::one< ... >.
         template< typename T, char... Rs >
         struct unescape_c
         {
            template< typename Input, typename State >
            static void apply( const Input& in, State& st )
            {
               assert( in.size() == 1 );
               st.unescaped += apply_one( in, static_cast< const T* >( nullptr ) );
            }

            template< typename Input, char... Qs >
            static char apply_one( const Input& in, const one< Qs... >* /*unused*/ )
            {
               static_assert( sizeof...( Qs ) == sizeof...( Rs ), "size mismatch between escaped characters and their mappings" );
               return apply_two( in, { Qs... }, { Rs... } );
            }

            template< typename Input >
            static char apply_two( const Input& in, const std::initializer_list< char >& q, const std::initializer_list< char >& r )
            {
               const char c = *in.begin();
               for( std::size_t i = 0; i < q.size(); ++i ) {
                  if( *( q.begin() + i ) == c ) {
                     return *( r.begin() + i );
                  }
               }
               throw parse_error( "invalid character in unescape", in );  // NOLINT, LCOV_EXCL_LINE
            }
         };

         // See src/example/pegtl/unescape.cpp for why the following two actions
         // skip the first input character. They also MUST be called
         // with non-empty matched inputs!

         struct unescape_u
         {
            template< typename Input, typename State >
            static void apply( const Input& in, State& st )
            {
               assert( !in.empty() );  // First character MUST be present, usually 'u' or 'U'.
               if( !utf8_append_utf32( st.unescaped, unhex_string< unsigned >( in.begin() + 1, in.end() ) ) ) {
                  throw parse_error( "invalid escaped unicode code point", in );
               }
            }
         };

         struct unescape_x
         {
            template< typename Input, typename State >
            static void apply( const Input& in, State& st )
            {
               assert( !in.empty() );  // First character MUST be present, usually 'x'.
               st.unescaped += unhex_string< char >( in.begin() + 1, in.end() );
            }
         };

         // The unescape_j action is similar to unescape_u, however unlike
         // unescape_u it
         // (a) assumes exactly 4 hexdigits per escape sequence,
         // (b) accepts multiple consecutive escaped 16-bit values.
         // When applied to more than one escape sequence, unescape_j
         // translates UTF-16 surrogate pairs in the input into a single
         // UTF-8 sequence in st.unescaped, as required for JSON by RFC 8259.

         struct unescape_j
         {
            template< typename Input, typename State >
            static void apply( const Input& in, State& st )
            {
               assert( ( ( in.size() + 1 ) % 6 ) == 0 );  // Expects multiple "\\u1234", starting with the first "u".
               for( const char* b = in.begin() + 1; b < in.end(); b += 6 ) {
                  const auto c = unhex_string< unsigned >( b, b + 4 );
                  if( ( 0xd800 <= c ) && ( c <= 0xdbff ) && ( b + 6 < in.end() ) ) {
                     const auto d = unhex_string< unsigned >( b + 6, b + 10 );
                     if( ( 0xdc00 <= d ) && ( d <= 0xdfff ) ) {
                        b += 6;
                        // note: no need to check the result code, as we are always >= 0x10000 and < 0x110000.
                        utf8_append_utf32( st.unescaped, ( ( ( c & 0x03ff ) << 10 ) | ( d & 0x03ff ) ) + 0x10000 );
                        continue;
                     }
                  }
                  if( !utf8_append_utf32( st.unescaped, c ) ) {
                     throw parse_error( "invalid escaped unicode code point", in );
                  }
               }
            }
         };

      }  // namespace unescape

   }  // namespace TAO_PEGTL_NAMESPACE

}  // namespace tao

#endif
<|endoftext|>


<commit_before>// Copyright (c) 2014-2018 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/

#ifndef TAO_PEGTL_CONTRIB_UNESCAPE_HPP
#define TAO_PEGTL_CONTRIB_UNESCAPE_HPP

#include <cassert>
#include <string>

#include "../ascii.hpp"
#include "../config.hpp"
#include "../parse_error.hpp"

namespace tao
{
   namespace TAO_PEGTL_NAMESPACE
   {
      namespace unescape
      {
         struct state
         {
            std::string unescaped;
         };

         // Utility functions for the unescape actions.

         inline bool utf8_append_utf32( std::string& string, const unsigned utf32 )
         {
            if( utf32 <= 0x7f ) {
               string += char( utf32 & 0xff );
               return true;
            }
            if( utf32 <= 0x7ff ) {
               char tmp[] = { char( ( ( utf32 & 0x7c0 ) >> 6 ) | 0xc0 ),
                              char( ( ( utf32 & 0x03f ) ) | 0x80 ) };
               string.append( tmp, sizeof( tmp ) );
               return true;
            }
            if( utf32 <= 0xffff ) {
               if( utf32 >= 0xd800 && utf32 <= 0xdfff ) {
                  // nope, this is a UTF-16 surrogate
                  return false;
               }
               char tmp[] = { char( ( ( utf32 & 0xf000 ) >> 12 ) | 0xe0 ),
                              char( ( ( utf32 & 0x0fc0 ) >> 6 ) | 0x80 ),
                              char( ( ( utf32 & 0x003f ) ) | 0x80 ) };
               string.append( tmp, sizeof( tmp ) );
               return true;
            }
            if( utf32 <= 0x10ffff ) {
               char tmp[] = { char( ( ( utf32 & 0x1c0000 ) >> 18 ) | 0xf0 ),
                              char( ( ( utf32 & 0x03f000 ) >> 12 ) | 0x80 ),
                              char( ( ( utf32 & 0x000fc0 ) >> 6 ) | 0x80 ),
                              char( ( ( utf32 & 0x00003f ) ) | 0x80 ) };
               string.append( tmp, sizeof( tmp ) );
               return true;
            }
            return false;
         }

         // This function MUST only be called for characters matching tao::TAO_PEGTL_NAMESPACE::ascii::xdigit!
         template< typename I >
         I unhex_char( const char c )
         {
            switch( c ) {
               case '0':
               case '1':
               case '2':
               case '3':
               case '4':
               case '5':
               case '6':
               case '7':
               case '8':
               case '9':
                  return I( c - '0' );
               case 'a':
               case 'b':
               case 'c':
               case 'd':
               case 'e':
               case 'f':
                  return I( c - 'a' + 10 );
               case 'A':
               case 'B':
               case 'C':
               case 'D':
               case 'E':
               case 'F':
                  return I( c - 'A' + 10 );
               default:
                  throw std::runtime_error( "invalid character in unhex" );  // NOLINT, LCOV_EXCL_LINE
            }
         }

         template< typename I >
         I unhex_string( const char* begin, const char* end )
         {
            I r = 0;
            while( begin != end ) {
               r <<= 4;
               r += unhex_char< I >( *begin++ );
            }
            return r;
         }

         // Actions for common unescape situations.

         struct append_all
         {
            template< typename Input, typename State >
            static void apply( const Input& in, State& st )
            {
               st.unescaped.append( in.begin(), in.size() );
            }
         };

         // This action MUST be called for a character matching T which MUST be tao::TAO_PEGTL_NAMESPACE::one< ... >.
         template< typename T, char... Rs >
         struct unescape_c
         {
            template< typename Input, typename State >
            static void apply( const Input& in, State& st )
            {
               assert( in.size() == 1 );
               st.unescaped += apply_one( in, static_cast< const T* >( nullptr ) );
            }

            template< typename Input, char... Qs >
            static char apply_one( const Input& in, const one< Qs... >* /*unused*/ )
            {
               static_assert( sizeof...( Qs ) == sizeof...( Rs ), "size mismatch between escaped characters and their mappings" );
               return apply_two( in, { Qs... }, { Rs... } );
            }

            template< typename Input >
            static char apply_two( const Input& in, const std::initializer_list< char >& q, const std::initializer_list< char >& r )
            {
               const char c = *in.begin();
               for( std::size_t i = 0; i < q.size(); ++i ) {
                  if( *( q.begin() + i ) == c ) {
                     return *( r.begin() + i );
                  }
               }
               throw parse_error( "invalid character in unescape", in );  // NOLINT, LCOV_EXCL_LINE
            }
         };

         // See src/example/pegtl/unescape.cpp for why the following two actions
         // skip the first input character. They also MUST be called
         // with non-empty matched inputs!

         struct unescape_u
         {
            template< typename Input, typename State >
            static void apply( const Input& in, State& st )
            {
               assert( !in.empty() );  // First character MUST be present, usually 'u' or 'U'.
               if( !utf8_append_utf32( st.unescaped, unhex_string< unsigned >( in.begin() + 1, in.end() ) ) ) {
                  throw parse_error( "invalid escaped unicode code point", in );
               }
            }
         };

         struct unescape_x
         {
            template< typename Input, typename State >
            static void apply( const Input& in, State& st )
            {
               assert( !in.empty() );  // First character MUST be present, usually 'x'.
               st.unescaped += unhex_string< char >( in.begin() + 1, in.end() );
            }
         };

         // The unescape_j action is similar to unescape_u, however unlike
         // unescape_u it
         // (a) assumes exactly 4 hexdigits per escape sequence,
         // (b) accepts multiple consecutive escaped 16-bit values.
         // When applied to more than one escape sequence, unescape_j
         // translates UTF-16 surrogate pairs in the input into a single
         // UTF-8 sequence in st.unescaped, as required for JSON by RFC 8259.

         struct unescape_j
         {
            template< typename Input, typename State >
            static void apply( const Input& in, State& st )
            {
               assert( ( ( in.size() + 1 ) % 6 ) == 0 );  // Expects multiple "\\u1234", starting with the first "u".
               for( const char* b = in.begin() + 1; b < in.end(); b += 6 ) {
                  const auto c = unhex_string< unsigned >( b, b + 4 );
                  if( ( 0xd800 <= c ) && ( c <= 0xdbff ) && ( b + 6 < in.end() ) ) {
                     const auto d = unhex_string< unsigned >( b + 6, b + 10 );
                     if( ( 0xdc00 <= d ) && ( d <= 0xdfff ) ) {
                        b += 6;
                        // note: no need to check the result code, as we are always >= 0x10000 and < 0x110000.
                        utf8_append_utf32( st.unescaped, ( ( ( c & 0x03ff ) << 10 ) | ( d & 0x03ff ) ) + 0x10000 );
                        continue;
                     }
                  }
                  if( !utf8_append_utf32( st.unescaped, c ) ) {
                     throw parse_error( "invalid escaped unicode code point", in );
                  }
               }
            }
         };

      }  // namespace unescape

   }  // namespace TAO_PEGTL_NAMESPACE

}  // namespace tao

#endif
<commit_msg>Fix coverage<commit_after>// Copyright (c) 2014-2018 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/

#ifndef TAO_PEGTL_CONTRIB_UNESCAPE_HPP
#define TAO_PEGTL_CONTRIB_UNESCAPE_HPP

#include <cassert>
#include <string>

#include "../ascii.hpp"
#include "../config.hpp"
#include "../parse_error.hpp"

namespace tao
{
   namespace TAO_PEGTL_NAMESPACE
   {
      namespace unescape
      {
         struct state
         {
            std::string unescaped;
         };

         // Utility functions for the unescape actions.

         inline bool utf8_append_utf32( std::string& string, const unsigned utf32 )
         {
            if( utf32 <= 0x7f ) {
               string += char( utf32 & 0xff );
               return true;
            }
            if( utf32 <= 0x7ff ) {
               char tmp[] = { char( ( ( utf32 & 0x7c0 ) >> 6 ) | 0xc0 ),
                              char( ( ( utf32 & 0x03f ) ) | 0x80 ) };
               string.append( tmp, sizeof( tmp ) );
               return true;
            }
            if( utf32 <= 0xffff ) {
               if( utf32 >= 0xd800 && utf32 <= 0xdfff ) {
                  // nope, this is a UTF-16 surrogate
                  return false;
               }
               char tmp[] = { char( ( ( utf32 & 0xf000 ) >> 12 ) | 0xe0 ),
                              char( ( ( utf32 & 0x0fc0 ) >> 6 ) | 0x80 ),
                              char( ( ( utf32 & 0x003f ) ) | 0x80 ) };
               string.append( tmp, sizeof( tmp ) );
               return true;
            }
            if( utf32 <= 0x10ffff ) {
               char tmp[] = { char( ( ( utf32 & 0x1c0000 ) >> 18 ) | 0xf0 ),
                              char( ( ( utf32 & 0x03f000 ) >> 12 ) | 0x80 ),
                              char( ( ( utf32 & 0x000fc0 ) >> 6 ) | 0x80 ),
                              char( ( ( utf32 & 0x00003f ) ) | 0x80 ) };
               string.append( tmp, sizeof( tmp ) );
               return true;
            }
            return false;
         }

         // This function MUST only be called for characters matching tao::TAO_PEGTL_NAMESPACE::ascii::xdigit!
         template< typename I >
         I unhex_char( const char c )
         {
            switch( c ) {
               case '0':
               case '1':
               case '2':
               case '3':
               case '4':
               case '5':
               case '6':
               case '7':
               case '8':
               case '9':
                  return I( c - '0' );
               case 'a':
               case 'b':
               case 'c':
               case 'd':
               case 'e':
               case 'f':
                  return I( c - 'a' + 10 );
               case 'A':
               case 'B':
               case 'C':
               case 'D':
               case 'E':
               case 'F':
                  return I( c - 'A' + 10 );
               default:                                                      // LCOV_EXCL_LINE
                  throw std::runtime_error( "invalid character in unhex" );  // NOLINT, LCOV_EXCL_LINE
            }
         }

         template< typename I >
         I unhex_string( const char* begin, const char* end )
         {
            I r = 0;
            while( begin != end ) {
               r <<= 4;
               r += unhex_char< I >( *begin++ );
            }
            return r;
         }

         // Actions for common unescape situations.

         struct append_all
         {
            template< typename Input, typename State >
            static void apply( const Input& in, State& st )
            {
               st.unescaped.append( in.begin(), in.size() );
            }
         };

         // This action MUST be called for a character matching T which MUST be tao::TAO_PEGTL_NAMESPACE::one< ... >.
         template< typename T, char... Rs >
         struct unescape_c
         {
            template< typename Input, typename State >
            static void apply( const Input& in, State& st )
            {
               assert( in.size() == 1 );
               st.unescaped += apply_one( in, static_cast< const T* >( nullptr ) );
            }

            template< typename Input, char... Qs >
            static char apply_one( const Input& in, const one< Qs... >* /*unused*/ )
            {
               static_assert( sizeof...( Qs ) == sizeof...( Rs ), "size mismatch between escaped characters and their mappings" );
               return apply_two( in, { Qs... }, { Rs... } );
            }

            template< typename Input >
            static char apply_two( const Input& in, const std::initializer_list< char >& q, const std::initializer_list< char >& r )
            {
               const char c = *in.begin();
               for( std::size_t i = 0; i < q.size(); ++i ) {
                  if( *( q.begin() + i ) == c ) {
                     return *( r.begin() + i );
                  }
               }
               throw parse_error( "invalid character in unescape", in );  // NOLINT, LCOV_EXCL_LINE
            }
         };

         // See src/example/pegtl/unescape.cpp for why the following two actions
         // skip the first input character. They also MUST be called
         // with non-empty matched inputs!

         struct unescape_u
         {
            template< typename Input, typename State >
            static void apply( const Input& in, State& st )
            {
               assert( !in.empty() );  // First character MUST be present, usually 'u' or 'U'.
               if( !utf8_append_utf32( st.unescaped, unhex_string< unsigned >( in.begin() + 1, in.end() ) ) ) {
                  throw parse_error( "invalid escaped unicode code point", in );
               }
            }
         };

         struct unescape_x
         {
            template< typename Input, typename State >
            static void apply( const Input& in, State& st )
            {
               assert( !in.empty() );  // First character MUST be present, usually 'x'.
               st.unescaped += unhex_string< char >( in.begin() + 1, in.end() );
            }
         };

         // The unescape_j action is similar to unescape_u, however unlike
         // unescape_u it
         // (a) assumes exactly 4 hexdigits per escape sequence,
         // (b) accepts multiple consecutive escaped 16-bit values.
         // When applied to more than one escape sequence, unescape_j
         // translates UTF-16 surrogate pairs in the input into a single
         // UTF-8 sequence in st.unescaped, as required for JSON by RFC 8259.

         struct unescape_j
         {
            template< typename Input, typename State >
            static void apply( const Input& in, State& st )
            {
               assert( ( ( in.size() + 1 ) % 6 ) == 0 );  // Expects multiple "\\u1234", starting with the first "u".
               for( const char* b = in.begin() + 1; b < in.end(); b += 6 ) {
                  const auto c = unhex_string< unsigned >( b, b + 4 );
                  if( ( 0xd800 <= c ) && ( c <= 0xdbff ) && ( b + 6 < in.end() ) ) {
                     const auto d = unhex_string< unsigned >( b + 6, b + 10 );
                     if( ( 0xdc00 <= d ) && ( d <= 0xdfff ) ) {
                        b += 6;
                        // note: no need to check the result code, as we are always >= 0x10000 and < 0x110000.
                        utf8_append_utf32( st.unescaped, ( ( ( c & 0x03ff ) << 10 ) | ( d & 0x03ff ) ) + 0x10000 );
                        continue;
                     }
                  }
                  if( !utf8_append_utf32( st.unescaped, c ) ) {
                     throw parse_error( "invalid escaped unicode code point", in );
                  }
               }
            }
         };

      }  // namespace unescape

   }  // namespace TAO_PEGTL_NAMESPACE

}  // namespace tao

#endif
<|endoftext|>


<commit_before>#ifndef NETWORK_CONNECTION_HPP
#define NETWORK_CONNECTION_HPP

#include<string>
#include<functional>
#include<boost/asio.hpp>
#include<memory>
#include<mutex>
#include<string>
#include<thread>
#include<condition_variable>
#include<atomic>

using boost::asio::ip::tcp;

namespace network {

	using ResponseHandler = std::function<void(std::string)>;
	using SocketP = std::shared_ptr<tcp::socket>;
	using ULock = std::unique_lock<std::recursive_mutex>;

	/**
		* @brief A representation of a single network connection to which you can write
		* and from which you can read.
		* @todo Add a constructor for creating accepting connections.
		* @todo Implement all the functions.
		*/
	class Connection {
		public:
			/**
				* @brief Destroys the object and closes the connection.
				*/
			~Connection();

			/**
				* @brief Returns whether the connection has been in some way closed and will
				* get no more messages.
				*/
			bool isClosed() const;

			/**
				* @brief Sets a function to call after we got the next full response.
				* @param[in] handler The function to handle the response.
				* @return Whether it was possible to set the handler -- it is impossible if
				* the Connection is currently used for some other communication.
				*/
			bool setResponseHandler(ResponseHandler handler);

			/**
				* @brief Sends the specified message to the other side of this connection.
				* @param[in] message The message to be send.
				* @param[in] handler The handler to set for receiving responces after
				* sending the message. This should be empty, if no response is anticipated.
				* @return Whether it was possible to send the message -- it is impossible if
				* the Connection is currently used for some other communication.
				*/
			bool sendMessage(std::string message, ResponseHandler handler);

			/**
				* @brief Blocks until the next communication sequence ends or the connection
				* is closed for some reason.
				*/
			void wait();

			/**
				* @brief Closes the connection.
				*/
			void close();

			/**
				* @brief Create a connection to the specified address.
				* @param[in] address The address to which to connect.
				* @todo Either specify properly the format of the address string or change
				* the arguments for this function and then specify it anyway, but for the
				* new arguments.
				*/
			static std::shared_ptr<Connection> connectTo(std::string address, std::string portNumber);

			/**
				* @brief Run io_service and start all connections.
				*/
			static void runAll();

		private:
			/**
				* @brief Takes care whole network services.
				*/
			static boost::asio::io_service io_service;

			static const int BUF_SIZE = 2048;
			static boost::asio::io_service::work work;
			static std::shared_ptr<std::thread> netThread;

			char buffer[BUF_SIZE];
			SocketP sockPointer;
			ResponseHandler	curHandler;
			std::recursive_mutex mtx;
			std::condition_variable_any cv;
			std::atomic<int> dreamLevel;

			/**
				* @brief Constructs object from specified socket.
				*/
			Connection(SocketP sockpointer);

			static void runIOservice();

			void sendHandler(const boost::system::error_code& err, std::size_t bytes_transferred, ResponseHandler handler);
			void execResponseHandler(const boost::system::error_code& err, std::size_t bytes_transferred);

		friend class Acceptor;
	};

}

#endif
<commit_msg>delete doc from private fileds<commit_after>#ifndef NETWORK_CONNECTION_HPP
#define NETWORK_CONNECTION_HPP

#include<string>
#include<functional>
#include<boost/asio.hpp>
#include<memory>
#include<mutex>
#include<string>
#include<thread>
#include<condition_variable>
#include<atomic>

using boost::asio::ip::tcp;

namespace network {

	using ResponseHandler = std::function<void(std::string)>;
	using SocketP = std::shared_ptr<tcp::socket>;
	using ULock = std::unique_lock<std::recursive_mutex>;

	/**
		* @brief A representation of a single network connection to which you can write
		* and from which you can read.
		* @todo Add a constructor for creating accepting connections.
		* @todo Implement all the functions.
		*/
	class Connection {
		public:
			/**
				* @brief Destroys the object and closes the connection.
				*/
			~Connection();

			/**
				* @brief Returns whether the connection has been in some way closed and will
				* get no more messages.
				*/
			bool isClosed() const;

			/**
				* @brief Sets a function to call after we got the next full response.
				* @param[in] handler The function to handle the response.
				* @return Whether it was possible to set the handler -- it is impossible if
				* the Connection is currently used for some other communication.
				*/
			bool setResponseHandler(ResponseHandler handler);

			/**
				* @brief Sends the specified message to the other side of this connection.
				* @param[in] message The message to be send.
				* @param[in] handler The handler to set for receiving responces after
				* sending the message. This should be empty, if no response is anticipated.
				* @return Whether it was possible to send the message -- it is impossible if
				* the Connection is currently used for some other communication.
				*/
			bool sendMessage(std::string message, ResponseHandler handler);

			/**
				* @brief Blocks until the next communication sequence ends or the connection
				* is closed for some reason.
				*/
			void wait();

			/**
				* @brief Closes the connection.
				*/
			void close();

			/**
				* @brief Create a connection to the specified address.
				* @param[in] address The address to which to connect.
				* @todo Either specify properly the format of the address string or change
				* the arguments for this function and then specify it anyway, but for the
				* new arguments.
				*/
			static std::shared_ptr<Connection> connectTo(std::string address, std::string portNumber);

			/**
				* @brief Run io_service and start all connections.
				*/
			static void runAll();

		private:
			static boost::asio::io_service io_service;
			static const int BUF_SIZE = 2048;
			static boost::asio::io_service::work work;
			static std::shared_ptr<std::thread> netThread;

			char buffer[BUF_SIZE];
			SocketP sockPointer;
			ResponseHandler	curHandler;
			std::recursive_mutex mtx;
			std::condition_variable_any cv;
			std::atomic<int> dreamLevel;

			Connection(SocketP sockpointer);

			static void runIOservice();

			void sendHandler(const boost::system::error_code& err, std::size_t bytes_transferred, ResponseHandler handler);
			void execResponseHandler(const boost::system::error_code& err, std::size_t bytes_transferred);

		friend class Acceptor;
	};

}

#endif
<|endoftext|>


<commit_before>#ifndef PYTHONIC_INCLUDE_TYPES_NONE_HPP
#define PYTHONIC_INCLUDE_TYPES_NONE_HPP

#include "pythonic/include/types/assignable.hpp"

PYTHONIC_NS_BEGIN

namespace types
{

  static const intptr_t NONE_ID = 0x1331;

  struct none_type {
    none_type();
    intptr_t id() const;
  };

  template <class T, bool is_fundamental = std::is_fundamental<T>::value>
  struct none;

  /* Type adapator to simulate an option type
   *
   * see http://en.wikipedia.org/wiki/Option_type
   */
  template <class T>
  struct none<T, false> : T {

    bool is_none; // set to true if the type is none

    none(none_type const &);

    template <class... Types>
    none(Types &&... args);

    bool operator==(none_type const &) const;

    template <class O>
    bool operator==(O const &t) const;

    operator bool() const;

    intptr_t id() const;
  };

  /* specialization of none for integral types we cannot derive from
  */
  template <class T>
  struct none<T, true> {
    T data;
    template <class T1>
    friend std::ostream &operator<<(std::ostream &, none<T1> const &);
    template <class T1>
    friend T1 operator+(none<T1> const &t0, T1 const &t1);
    template <class T1>
    friend T1 operator+(T1 const &t0, none<T1> const &t1);
    template <class T1>
    friend none<T1> operator+(none<T1> const &t0, none<T1> const &t1);
    template <class T1>
    friend bool operator>(none<T1, true> const &t0, T1 const &t1);
    template <class T1>
    friend bool operator>(T1 const &t0, none<T1> const &t1);
    template <class T1>
    friend none<bool> operator>(none<T1> const &t0, none<T1> const &t1);
    template <class T1>
    friend bool operator>=(none<T1> const &t0, T1 const &t1);
    template <class T1>
    friend bool operator>=(T1 const &t0, none<T1> const &t1);
    template <class T1>
    friend none<bool> operator>=(none<T1> const &t0, none<T1> const &t1);
    template <class T1>
    friend bool operator<(none<T1> const &t0, T1 const &t1);
    template <class T1>
    friend bool operator<(T1 const &t0, none<T1> const &t1);
    template <class T1>
    friend none<bool> operator<(none<T1> const &t0, none<T1> const &t1);
    template <class T1>
    friend bool operator<=(none<T1> const &t0, T1 const &t1);
    template <class T1>
    friend bool operator<=(T1 const &t0, none<T1> const &t1);
    template <class T1>
    friend none<bool> operator<=(none<T1> const &t0, none<T1> const &t1);
    template <class T1>
    friend T1 operator-(none<T1> const &t0, T1 const &t1);
    template <class T1>
    friend T1 operator-(T1 const &t0, none<T1> const &t1);
    template <class T1>
    friend none<T1> operator-(none<T1> const &t0, none<T1> const &t1);
    template <class T1>
    friend T1 operator*(none<T1> const &t0, T1 const &t1);
    template <class T1>
    friend T1 operator*(T1 const &t0, none<T1> const &t1);
    template <class T1>
    friend none<T1> operator*(none<T1> const &t0, none<T1> const &t1);
    template <class T1>
    friend T1 operator/(none<T1> const &t0, T1 const &t1);
    template <class T1>
    friend T1 operator/(T1 const &t0, none<T1> const &t1);
    template <class T1>
    friend none<T1> operator/(none<T1> const &t0, none<T1> const &t1);

  public:
    bool is_none;
    none();
    none(none_type const &);
    none(T const &data);
    bool operator==(none_type const &) const;
    template <class O>
    bool operator==(O const &t) const;
    operator bool() const;
    operator size_t() const;
    operator long() const;
    operator long long() const;
    operator double() const;
    T &operator=(T const &t);
    intptr_t id() const;
  };
  template <class T>
  T operator+(none<T, true> const &t0, T const &t1);
  template <class T>
  T operator+(T const &t0, none<T, true> const &t1);
  template <class T>
  none<T, true> operator+(none<T, true> const &t0, none<T, true> const &t1);
  template <class T>
  bool operator>(none<T, true> const &t0, T const &t1);
  template <class T>
  bool operator>(T const &t0, none<T, true> const &t1);
  template <class T>
  none<bool> operator>(none<T, true> const &t0, none<T, true> const &t1);
  template <class T>
  bool operator>=(none<T, true> const &t0, T const &t1);
  template <class T>
  bool operator>=(T const &t0, none<T, true> const &t1);
  template <class T>
  none<bool> operator>=(none<T, true> const &t0, none<T, true> const &t1);
  template <class T>
  bool operator<(none<T, true> const &t0, T const &t1);
  template <class T>
  bool operator<(T const &t0, none<T, true> const &t1);
  template <class T>
  none<bool> operator<(none<T, true> const &t0, none<T, true> const &t1);
  template <class T>
  bool operator<=(none<T, true> const &t0, T const &t1);
  template <class T>
  bool operator<=(T const &t0, none<T, true> const &t1);
  template <class T>
  none<bool> operator<=(none<T, true> const &t0, none<T, true> const &t1);
  template <class T>
  T operator-(none<T, true> const &t0, T const &t1);
  template <class T>
  T operator-(T const &t0, none<T, true> const &t1);
  template <class T>
  none<T, true> operator-(none<T, true> const &t0, none<T, true> const &t1);
  template <class T>
  T operator*(none<T, true> const &t0, T const &t1);
  template <class T>
  T operator*(T const &t0, none<T, true> const &t1);
  template <class T>
  none<T, true> operator*(none<T, true> const &t0, none<T, true> const &t1);
  template <class T>
  T operator/(none<T, true> const &t0, T const &t1);
  template <class T>
  T operator/(T const &t0, none<T, true> const &t1);
  template <class T>
  none<T, true> operator/(none<T, true> const &t0, none<T, true> const &t1);
  template <class T>
  std::ostream &operator<<(std::ostream &os, none<T, true> const &v);

  template <class T>
  struct is_none {
    static const bool value = false;
  };

  template <class T>
  struct is_none<none<T>> {
    static const bool value = true;
  };
}

template <class T>
struct assignable<types::none<T>> {
  using type = types::none<typename assignable<T>::type>;
};
PYTHONIC_NS_END

/* type inference stuff { */
#include "pythonic/include/types/combined.hpp"

template <class T0, class T1>
struct __combined<pythonic::types::none<T0>, T1>
    : std::enable_if<!pythonic::types::is_none<T1>::value,
                     pythonic::dummy>::type {
  using type = pythonic::types::none<typename __combined<T0, T1>::type>;
};

template <class T0, class T1>
struct __combined<T1, pythonic::types::none<T0>>
    : std::enable_if<!pythonic::types::is_none<T0>::value,
                     pythonic::dummy>::type {
  using type = pythonic::types::none<typename __combined<T0, T1>::type>;
};

template <class T0, class T1>
struct __combined<pythonic::types::none<T1>, pythonic::types::none<T0>> {
  using type = pythonic::types::none<typename __combined<T0, T1>::type>;
};

template <class T>
struct __combined<typename std::enable_if<!pythonic::types::is_none<T>::value,
                                          pythonic::types::none_type>::type,
                  T> {
  using type = pythonic::types::none<T>;
};

template <class T>
struct __combined<T,
                  typename std::enable_if<!pythonic::types::is_none<T>::value,
                                          pythonic::types::none_type>::type> {
  using type = pythonic::types::none<T>;
};

template <>
struct __combined<pythonic::types::none_type, pythonic::types::none_type> {
  using type = pythonic::types::none_type;
};

/* } */

#ifdef ENABLE_PYTHON_MODULE

#include "pythonic/python/core.hpp"

PYTHONIC_NS_BEGIN
template <>
struct to_python<types::none_type> {
  static PyObject *convert(types::none_type);
};

template <class T>
struct to_python<types::none<T>> {
  static PyObject *convert(types::none<T> const &n);
};

template <>
struct from_python<types::none_type> {

  static bool is_convertible(PyObject *obj);

  static types::none_type convert(PyObject *obj);
};
PYTHONIC_NS_END

#endif
#endif
<commit_msg>Fix NoneType friends<commit_after>#ifndef PYTHONIC_INCLUDE_TYPES_NONE_HPP
#define PYTHONIC_INCLUDE_TYPES_NONE_HPP

#include "pythonic/include/types/assignable.hpp"

PYTHONIC_NS_BEGIN

namespace types
{

  static const intptr_t NONE_ID = 0x1331;

  struct none_type {
    none_type();
    intptr_t id() const;
  };

  template <class T, bool is_fundamental = std::is_fundamental<T>::value>
  struct none;

  /* Type adapator to simulate an option type
   *
   * see http://en.wikipedia.org/wiki/Option_type
   */
  template <class T>
  struct none<T, false> : T {

    bool is_none; // set to true if the type is none

    none(none_type const &);

    template <class... Types>
    none(Types &&... args);

    bool operator==(none_type const &) const;

    template <class O>
    bool operator==(O const &t) const;

    operator bool() const;

    intptr_t id() const;
  };

  /* specialization of none for integral types we cannot derive from
  */
  template <class T>
  struct none<T, true> {
    T data;
    template <class T1>
    friend std::ostream &operator<<(std::ostream &, none<T1, true> const &);
    template <class T1>
    friend T1 operator+(none<T1, true> const &t0, T1 const &t1);
    template <class T1>
    friend T1 operator+(T1 const &t0, none<T1, true> const &t1);
    template <class T1>
    friend none<T1, true> operator+(none<T1, true> const &t0,
                                    none<T1, true> const &t1);
    template <class T1>
    friend bool operator>(none<T1, true> const &t0, T1 const &t1);
    template <class T1>
    friend bool operator>(T1 const &t0, none<T1, true> const &t1);
    template <class T1>
    friend none<bool> operator>(none<T1, true> const &t0,
                                none<T1, true> const &t1);
    template <class T1>
    friend bool operator>=(none<T1, true> const &t0, T1 const &t1);
    template <class T1>
    friend bool operator>=(T1 const &t0, none<T1, true> const &t1);
    template <class T1>
    friend none<bool> operator>=(none<T1, true> const &t0,
                                 none<T1, true> const &t1);
    template <class T1>
    friend bool operator<(none<T1, true> const &t0, T1 const &t1);
    template <class T1>
    friend bool operator<(T1 const &t0, none<T1, true> const &t1);
    template <class T1>
    friend none<bool> operator<(none<T1, true> const &t0,
                                none<T1, true> const &t1);
    template <class T1>
    friend bool operator<=(none<T1, true> const &t0, T1 const &t1);
    template <class T1>
    friend bool operator<=(T1 const &t0, none<T1, true> const &t1);
    template <class T1>
    friend none<bool> operator<=(none<T1, true> const &t0,
                                 none<T1, true> const &t1);
    template <class T1>
    friend T1 operator-(none<T1, true> const &t0, T1 const &t1);
    template <class T1>
    friend T1 operator-(T1 const &t0, none<T1, true> const &t1);
    template <class T1>
    friend none<T1, true> operator-(none<T1, true> const &t0,
                                    none<T1, true> const &t1);
    template <class T1>
    friend T1 operator*(none<T1, true> const &t0, T1 const &t1);
    template <class T1>
    friend T1 operator*(T1 const &t0, none<T1, true> const &t1);
    template <class T1>
    friend none<T1, true> operator*(none<T1, true> const &t0,
                                    none<T1, true> const &t1);
    template <class T1>
    friend T1 operator/(none<T1, true> const &t0, T1 const &t1);
    template <class T1>
    friend T1 operator/(T1 const &t0, none<T1, true> const &t1);
    template <class T1>
    friend none<T1, true> operator/(none<T1, true> const &t0,
                                    none<T1, true> const &t1);

  public:
    bool is_none;
    none();
    none(none_type const &);
    none(T const &data);
    bool operator==(none_type const &) const;
    template <class O>
    bool operator==(O const &t) const;
    operator bool() const;
    operator size_t() const;
    operator long() const;
    operator long long() const;
    operator double() const;
    T &operator=(T const &t);
    intptr_t id() const;
  };
  template <class T>
  T operator+(none<T, true> const &t0, T const &t1);
  template <class T>
  T operator+(T const &t0, none<T, true> const &t1);
  template <class T>
  none<T, true> operator+(none<T, true> const &t0, none<T, true> const &t1);
  template <class T>
  bool operator>(none<T, true> const &t0, T const &t1);
  template <class T>
  bool operator>(T const &t0, none<T, true> const &t1);
  template <class T>
  none<bool> operator>(none<T, true> const &t0, none<T, true> const &t1);
  template <class T>
  bool operator>=(none<T, true> const &t0, T const &t1);
  template <class T>
  bool operator>=(T const &t0, none<T, true> const &t1);
  template <class T>
  none<bool> operator>=(none<T, true> const &t0, none<T, true> const &t1);
  template <class T>
  bool operator<(none<T, true> const &t0, T const &t1);
  template <class T>
  bool operator<(T const &t0, none<T, true> const &t1);
  template <class T>
  none<bool> operator<(none<T, true> const &t0, none<T, true> const &t1);
  template <class T>
  bool operator<=(none<T, true> const &t0, T const &t1);
  template <class T>
  bool operator<=(T const &t0, none<T, true> const &t1);
  template <class T>
  none<bool> operator<=(none<T, true> const &t0, none<T, true> const &t1);
  template <class T>
  T operator-(none<T, true> const &t0, T const &t1);
  template <class T>
  T operator-(T const &t0, none<T, true> const &t1);
  template <class T>
  none<T, true> operator-(none<T, true> const &t0, none<T, true> const &t1);
  template <class T>
  T operator*(none<T, true> const &t0, T const &t1);
  template <class T>
  T operator*(T const &t0, none<T, true> const &t1);
  template <class T>
  none<T, true> operator*(none<T, true> const &t0, none<T, true> const &t1);
  template <class T>
  T operator/(none<T, true> const &t0, T const &t1);
  template <class T>
  T operator/(T const &t0, none<T, true> const &t1);
  template <class T>
  none<T, true> operator/(none<T, true> const &t0, none<T, true> const &t1);
  template <class T>
  std::ostream &operator<<(std::ostream &os, none<T, true> const &v);

  template <class T>
  struct is_none {
    static const bool value = false;
  };

  template <class T>
  struct is_none<none<T>> {
    static const bool value = true;
  };
}

template <class T>
struct assignable<types::none<T>> {
  using type = types::none<typename assignable<T>::type>;
};
PYTHONIC_NS_END

/* type inference stuff { */
#include "pythonic/include/types/combined.hpp"

template <class T0, class T1>
struct __combined<pythonic::types::none<T0>, T1>
    : std::enable_if<!pythonic::types::is_none<T1>::value,
                     pythonic::dummy>::type {
  using type = pythonic::types::none<typename __combined<T0, T1>::type>;
};

template <class T0, class T1>
struct __combined<T1, pythonic::types::none<T0>>
    : std::enable_if<!pythonic::types::is_none<T0>::value,
                     pythonic::dummy>::type {
  using type = pythonic::types::none<typename __combined<T0, T1>::type>;
};

template <class T0, class T1>
struct __combined<pythonic::types::none<T1>, pythonic::types::none<T0>> {
  using type = pythonic::types::none<typename __combined<T0, T1>::type>;
};

template <class T>
struct __combined<typename std::enable_if<!pythonic::types::is_none<T>::value,
                                          pythonic::types::none_type>::type,
                  T> {
  using type = pythonic::types::none<T>;
};

template <class T>
struct __combined<T,
                  typename std::enable_if<!pythonic::types::is_none<T>::value,
                                          pythonic::types::none_type>::type> {
  using type = pythonic::types::none<T>;
};

template <>
struct __combined<pythonic::types::none_type, pythonic::types::none_type> {
  using type = pythonic::types::none_type;
};

/* } */

#ifdef ENABLE_PYTHON_MODULE

#include "pythonic/python/core.hpp"

PYTHONIC_NS_BEGIN
template <>
struct to_python<types::none_type> {
  static PyObject *convert(types::none_type);
};

template <class T>
struct to_python<types::none<T>> {
  static PyObject *convert(types::none<T> const &n);
};

template <>
struct from_python<types::none_type> {

  static bool is_convertible(PyObject *obj);

  static types::none_type convert(PyObject *obj);
};
PYTHONIC_NS_END

#endif
#endif
<|endoftext|>


<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (testabilitydriver@nokia.com)
**
** This file is part of Testability Driver Qt Agent
**
** If you have questions regarding the use of this file, please contact
** Nokia at testabilitydriver@nokia.com .
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "tasnativeutils.h"

#include <taslogger.h>

#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xatom.h>
#include <signal.h>

int pidOfXWindow(Display* display, Window win)
{
    int pid = -1;
    Atom atom;
    Atom actual_type;
    int actual_format;
    unsigned long nitems;
    unsigned long bytes_after;
    unsigned char *prop = 0;
    int status;
    if (win != None && win != 0) {
        atom = XInternAtom(display, "_NET_WM_PID", True);
        if (atom != None) {
            status = XGetWindowProperty(display, win, atom, 0, 1024,
                                        False, AnyPropertyType,
                                        &actual_type,
                                        &actual_format, &nitems,
                                        &bytes_after,
                                        &prop);
            if (status!=0 || !prop || actual_format == None) {
                //NOP
            } else {
                pid = prop[1] * 256;
                pid += prop[0];
            }
        }

    }
    if (prop) XFree(prop);
    return pid;
}

//#include <cstdio>

/*!
  \class TasNativeUtils
  \brief Provides platform dependent operations.
*/

// Window id of the currently active window

bool  dockWindow(Display* dpy, Window window)
{
    unsigned long nitems, after;
    int format;
    Atom type = None;
    unsigned char* data = NULL;
    Atom _NET_WM_WINDOW_TYPE_DOCK = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE_DOCK",
                                           False);
    Atom WINDOW_TYPE = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE", False);

    Atom curr_type;

    if (Success == XGetWindowProperty(dpy, window, WINDOW_TYPE, 0, 0x7FFFFFFF, False, AnyPropertyType,
                                      &type, &format, &nitems, &after, &data)) {
        if (!data) {
            return false;
        }
        for (int i = 0; i < (int)nitems; ++i) {
            curr_type = ((Atom*)data)[i];
            if (curr_type == _NET_WM_WINDOW_TYPE_DOCK) {
                XFree(data);
                return true;
            }
        }

    }

    if (data) XFree(data);
    return false;
}

long getstate(Display* display, Window window)
{
    static const long WM_STATE_ELEMENTS = 2L;

    unsigned long nitems;
    unsigned long leftover;
    Atom xa_WM_STATE, actual_type;
    int actual_format;
    int status;
    unsigned char* p = NULL;

    xa_WM_STATE = XInternAtom(display, "WM_STATE", True);

    if (window == None || window == 0) {
        return -1;
    }
    status = XGetWindowProperty(display, window,
                                xa_WM_STATE, 0L, WM_STATE_ELEMENTS,
                                False, xa_WM_STATE, &actual_type, &actual_format,
                                &nitems, &leftover, &p);
    long value = -1;

    if (status == 0) {
        if (p != NULL) {
            // Take first 8 bits
            // Wonder if this is the same on a 64 bit system?
            value = * (const unsigned long *) p & 0xffffffff;
            XFree(p);
        }

        return value;
    }

    if (p) XFree(p);
    return -1;
}

Window queryStack(Display* dpy, Window root, const QList<QString>& pids)
{
    Atom STACK = XInternAtom(dpy, "_NET_CLIENT_LIST_STACKING", False);
    unsigned long nitems, after;
    int format;
    Atom type = None;
    unsigned char* data = NULL;
    Window child;
    int i;

    if (!STACK) {
        return root;
    }
    if (Success == XGetWindowProperty(dpy, root, STACK, 0, 0x7FFFFFFF, False, XA_WINDOW,
                                      &type, &format, &nitems, &after, &data)) {
        for (i = (nitems-1); i >= 0; --i) {
            child = ((Window*)data)[i];
            if (!dockWindow(dpy, child) && getstate(dpy, child) == 1 &&
                pids.contains(QString::number(pidOfXWindow(dpy, child)))) {

                if (data) XFree(data);
                return child;
            }
        }

    }
    if (data) XFree(data);
    return None;

}

Window tryChildren(Display *dpy, Window win)
{
    Window root, parent;
    Window *children;
    unsigned int nchildren;
    int i;
    Window inf = 0;
    Window child;
    if (!XQueryTree(dpy, win, &root, &parent, &children, &nchildren)) {
        return 0;
    }
    // Traverse bottom-up direction
//    for (i = 0; !inf && (i < nchildren); i++) {
    for (i = nchildren-1; !inf && (i >= 0); i--) {
        // NormalState per ICCM
        if (getstate(dpy, children[i]) == 1) {
            inf = children[i];
        } else {
            child = tryChildren(dpy, children[i]);
            if (child) {
                inf = child;
            }
        }
    }
    if (children) {
        XFree(children);
    }

    return inf;
}

Window findActiveWindow(Display *dpy, Window win)
{
    Window inf;
    if (getstate(dpy, win) == 1) {
        return win;
    }
    inf = tryChildren(dpy, win);
    if (!inf)
        inf = win;
    return inf;
}

// Ignore errors related to the Window calls (of course, the pid is not resolved)
int errorHandler(Display*, XErrorEvent* e)
{
    TasLogger::logger()->warning("TasNativeUtils::errorHandler received X Error during request");
    if (e->error_code == BadWindow) {
        // More verbose on the most common one
        TasLogger::logger()->warning("TasNativeUtils::errorHandler BadWindow");
    } else {
        TasLogger::logger()->warning("TasNativeUtils::errorHandler code " +
                                   QString::number(e->error_code));
    }
    // XGetErrorText contains more info, if necessary
    return 0;
}

// Meego specific window attribute
// Try that before anything else.
int pidOfMeegoWindow(Display* display, Window root)
{
    unsigned long nitems, after;
    int format;
    Atom type = None;
    unsigned char* data = NULL;
    int pid = -1;
    Window child;

    Atom atom = XInternAtom(display, "_MEEGOTOUCH_CURRENT_APP_WINDOW", True);
    if (atom != None) {
        if (Success == XGetWindowProperty(display, root, atom, 0, 0x7FFFFFFF, False, XA_WINDOW,
                                          &type, &format, &nitems, &after, &data)) {
            if (nitems > 0) {
                child = ((Window*)data)[0];
                pid = pidOfXWindow(display,child);
                if (data) XFree(data);
            }
        }
    }
    return pid;
}

int TasNativeUtils::pidOfActiveWindow(const QHash<QString, TasClient*> clients)
{
    const QList<QString>& pids = clients.keys();
    TasLogger::logger()->debug("TasNativeUtils::pidOfActiveWindow Querying for active window");
    int pid = -1;
    Display* display = 0;
    display = XOpenDisplay(0);
    XSetErrorHandler(errorHandler);
    if (!display) return -1;

    int screen = XDefaultScreen(display);
    int window = RootWindow(display, screen);

    // First try to use whatever MeeGo tells us
    pid = pidOfMeegoWindow(display, window);
    if (pid != -1) {
        TasLogger::logger()->debug("TasNativeUtils::pidOfActiveWindow Found MeeGo pid: " + QString::number(pid));
     } else {
        Window win = queryStack(display, window, pids);
        pid = pidOfXWindow(display, win);
    }
    XCloseDisplay(display);

    TasLogger::logger()->debug("TasNativeUtils::pidOfActiveWindow Resolved " + QString::number(pid));
    return pid;
}

int TasNativeUtils::bringAppToForeground(TasClient& app)
{
    Q_UNUSED(app);
    return -1;
}

void TasNativeUtils::changeOrientation(QString)
{}

bool TasNativeUtils::killProcess(quint64 pid)
{
    kill(pid, 9);
    return true;
}

bool TasNativeUtils::verifyProcess(quint64 pid)
{
    // kill(pid,0) ?
    char path[256];
    sprintf(path, "/proc/%d", int(pid));
    return access(path, F_OK) != -1;
}

bool TasNativeUtils::processExitStatus(quint64 pid, int &status)
{
    if (verifyProcess(pid)) return false;
    status = 0;
    return true;
}

<commit_msg>close display in meego query<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (testabilitydriver@nokia.com)
**
** This file is part of Testability Driver Qt Agent
**
** If you have questions regarding the use of this file, please contact
** Nokia at testabilitydriver@nokia.com .
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "tasnativeutils.h"

#include <taslogger.h>

#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xatom.h>
#include <signal.h>

int pidOfXWindow(Display* display, Window win)
{
    int pid = -1;
    Atom atom;
    Atom actual_type;
    int actual_format;
    unsigned long nitems;
    unsigned long bytes_after;
    unsigned char *prop = 0;
    int status;
    if (win != None && win != 0) {
        atom = XInternAtom(display, "_NET_WM_PID", True);
        if (atom != None) {
            status = XGetWindowProperty(display, win, atom, 0, 1024,
                                        False, AnyPropertyType,
                                        &actual_type,
                                        &actual_format, &nitems,
                                        &bytes_after,
                                        &prop);
            if (status!=0 || !prop || actual_format == None) {
                //NOP
            } else {
                pid = prop[1] * 256;
                pid += prop[0];
            }
        }

    }
    if (prop) XFree(prop);
    return pid;
}

//#include <cstdio>

/*!
  \class TasNativeUtils
  \brief Provides platform dependent operations.
*/

// Window id of the currently active window

bool  dockWindow(Display* dpy, Window window)
{
    unsigned long nitems, after;
    int format;
    Atom type = None;
    unsigned char* data = NULL;
    Atom _NET_WM_WINDOW_TYPE_DOCK = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE_DOCK",
                                           False);
    Atom WINDOW_TYPE = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE", False);

    Atom curr_type;

    if (Success == XGetWindowProperty(dpy, window, WINDOW_TYPE, 0, 0x7FFFFFFF, False, AnyPropertyType,
                                      &type, &format, &nitems, &after, &data)) {
        if (!data) {
            return false;
        }
        for (int i = 0; i < (int)nitems; ++i) {
            curr_type = ((Atom*)data)[i];
            if (curr_type == _NET_WM_WINDOW_TYPE_DOCK) {
                XFree(data);
                return true;
            }
        }

    }

    if (data) XFree(data);
    return false;
}

long getstate(Display* display, Window window)
{
    static const long WM_STATE_ELEMENTS = 2L;

    unsigned long nitems;
    unsigned long leftover;
    Atom xa_WM_STATE, actual_type;
    int actual_format;
    int status;
    unsigned char* p = NULL;

    xa_WM_STATE = XInternAtom(display, "WM_STATE", True);

    if (window == None || window == 0) {
        return -1;
    }
    status = XGetWindowProperty(display, window,
                                xa_WM_STATE, 0L, WM_STATE_ELEMENTS,
                                False, xa_WM_STATE, &actual_type, &actual_format,
                                &nitems, &leftover, &p);
    long value = -1;

    if (status == 0) {
        if (p != NULL) {
            // Take first 8 bits
            // Wonder if this is the same on a 64 bit system?
            value = * (const unsigned long *) p & 0xffffffff;
            XFree(p);
        }

        return value;
    }

    if (p) XFree(p);
    return -1;
}

Window queryStack(Display* dpy, Window root, const QList<QString>& pids)
{
    Atom STACK = XInternAtom(dpy, "_NET_CLIENT_LIST_STACKING", False);
    unsigned long nitems, after;
    int format;
    Atom type = None;
    unsigned char* data = NULL;
    Window child;
    int i;

    if (!STACK) {
        return root;
    }
    if (Success == XGetWindowProperty(dpy, root, STACK, 0, 0x7FFFFFFF, False, XA_WINDOW,
                                      &type, &format, &nitems, &after, &data)) {
        for (i = (nitems-1); i >= 0; --i) {
            child = ((Window*)data)[i];
            if (!dockWindow(dpy, child) && getstate(dpy, child) == 1 &&
                pids.contains(QString::number(pidOfXWindow(dpy, child)))) {

                if (data) XFree(data);
                return child;
            }
        }

    }
    if (data) XFree(data);
    return None;

}

Window tryChildren(Display *dpy, Window win)
{
    Window root, parent;
    Window *children;
    unsigned int nchildren;
    int i;
    Window inf = 0;
    Window child;
    if (!XQueryTree(dpy, win, &root, &parent, &children, &nchildren)) {
        return 0;
    }
    // Traverse bottom-up direction
//    for (i = 0; !inf && (i < nchildren); i++) {
    for (i = nchildren-1; !inf && (i >= 0); i--) {
        // NormalState per ICCM
        if (getstate(dpy, children[i]) == 1) {
            inf = children[i];
        } else {
            child = tryChildren(dpy, children[i]);
            if (child) {
                inf = child;
            }
        }
    }
    if (children) {
        XFree(children);
    }

    return inf;
}

Window findActiveWindow(Display *dpy, Window win)
{
    Window inf;
    if (getstate(dpy, win) == 1) {
        return win;
    }
    inf = tryChildren(dpy, win);
    if (!inf)
        inf = win;
    return inf;
}

// Ignore errors related to the Window calls (of course, the pid is not resolved)
int errorHandler(Display*, XErrorEvent* e)
{
    TasLogger::logger()->warning("TasNativeUtils::errorHandler received X Error during request");
    if (e->error_code == BadWindow) {
        // More verbose on the most common one
        TasLogger::logger()->warning("TasNativeUtils::errorHandler BadWindow");
    } else {
        TasLogger::logger()->warning("TasNativeUtils::errorHandler code " +
                                   QString::number(e->error_code));
    }
    // XGetErrorText contains more info, if necessary
    return 0;
}

// Meego specific window attribute
// Try that before anything else.
int pidOfMeegoWindow(Display* display, Window root)
{
    unsigned long nitems, after;
    int format;
    Atom type = None;
    unsigned char* data = NULL;
    int pid = -1;
    Window child;

    Atom atom = XInternAtom(display, "_MEEGOTOUCH_CURRENT_APP_WINDOW", True);
    if (atom != None) {
        if (Success == XGetWindowProperty(display, root, atom, 0, 0x7FFFFFFF, False, XA_WINDOW,
                                          &type, &format, &nitems, &after, &data)) {
            if (nitems > 0) {
                child = ((Window*)data)[0];
                pid = pidOfXWindow(display,child);
                if (data) XFree(data);
            }
        }
    }
    return pid;
}

int TasNativeUtils::pidOfActiveWindow(const QHash<QString, TasClient*> clients)
{
    const QList<QString>& pids = clients.keys();
    TasLogger::logger()->debug("TasNativeUtils::pidOfActiveWindow Querying for active window");
    int pid = -1;
    Display* display = 0;
    display = XOpenDisplay(0);
    XSetErrorHandler(errorHandler);
    if (!display) return -1;

    int screen = XDefaultScreen(display);
    int window = RootWindow(display, screen);

    // First try to use whatever MeeGo tells us
    pid = pidOfMeegoWindow(display, window);
    if (pid != -1) {
        TasLogger::logger()->debug("TasNativeUtils::pidOfActiveWindow Found MeeGo pid: " + QString::number(pid));
    } else {
        Window win = queryStack(display, window, pids);
        pid = pidOfXWindow(display, win);
    }
    XCloseDisplay(display);

    TasLogger::logger()->debug("TasNativeUtils::pidOfActiveWindow Resolved " + QString::number(pid));
    return pid;
}

int TasNativeUtils::bringAppToForeground(TasClient& app)
{
    Q_UNUSED(app);
    return -1;
}

void TasNativeUtils::changeOrientation(QString)
{}

bool TasNativeUtils::killProcess(quint64 pid)
{
    kill(pid, 9);
    return true;
}

bool TasNativeUtils::verifyProcess(quint64 pid)
{
    // kill(pid,0) ?
    char path[256];
    sprintf(path, "/proc/%d", int(pid));
    return access(path, F_OK) != -1;
}

bool TasNativeUtils::processExitStatus(quint64 pid, int &status)
{
    if (verifyProcess(pid)) return false;
    status = 0;
    return true;
}

<|endoftext|>


<commit_before>#include <ros/ros.h>
#include <geometry_msgs/Twist.h>
#include <sensor_msgs/PointCloud2.h>
#include <sensor_msgs/PointCloud.h>
#include <sensor_msgs/point_cloud_conversion.h>
#include <tf/transform_listener.h>
#include <octomap/octomap.h>
#include <octomap/OcTree.h>
#include <octomap_msgs/Octomap.h>
#include <octomap_msgs/conversions.h>

#include <string>
#include <math.h>
#include <vector>

#include "dmath/geometry.h"

class ArtificialPotentialField{
public:
    ArtificialPotentialField(ros::NodeHandle &node) :
        base_link_("base_link"),
        cmd_pub_(node.advertise<geometry_msgs::Twist>("cmd_vel", 10)),
        obs_sub_(node.subscribe("/camera/depth/points", 10, &ArtificialPotentialField::obstacleCallback, this))

    {
        collision_map_.stamp = ros::Duration(0);
    }

    void spin(){
        ros::Rate r(10);

        ros::Duration(1).sleep();
        geometry_msgs::Twist cmd;
        cmd.linear.z = 0.15;
        cmd_pub_.publish(cmd);
        ros::Duration(3).sleep();

        cmd.linear.z = 0;
        cmd_pub_.publish(cmd);
        ros::Duration(3).sleep();

        const double force = 0.0025;

        while(ros::ok()){
            if(collision_map_.stamp != ros::Duration(0)){
                std::vector<dmath::Vector3D> obstacles;
                octomap::OcTree tree = octomap_msgs::msgToMap(collision_map_);
                octomap::OcTree::leaf_iterator const end_it = tree->end_leafs();
                for(octomap::OcTree::leaf_iterator it = tree->begin_leafs(0); it != end_it; it++){
                    obstacles.push_back(dmath::Vector3D(it.getX(), it.getY(), it.getZ()));
                }

                dmath::Vector3D Fs;
                for(int i=0; i < obstacles.size(); i++){
                    Fs += get_potential_force(obstacles[i], 0, 0.005, 1.0, 1.5);
                }

                //dmath::Vector3D g;
                //Fs += get_potential_force(g, 2, 0, 1.5, 1);

                dmath::Vector3D vel = Fs * force;
                cmd.linear.x = vel.y;
                cmd.linear.y = vel.x;
                cmd.linear.z = vel.z;

                ROS_INFO_STREAM("cmd = " << cmd);
                cmd_pub_.publish(cmd);
            }
            r.sleep();
            ros::spinOnce();
        }
    }

private:
    dmath::Vector3D get_potential_force(const dmath::Vector3D &dest_lc, double A = 1, double B = 1, double n = 1, double m = 1){
        dmath::Vector3D u = dest_lc;
        u = normalize(u);

        const double d = magnitude(dest_lc);
        double U = 0;
        if(fabs(d) > dmath::tol){
            U = -A/pow(d, n) + B/pow(d, m);
        }

        return U * u;
    }

    void obstacleCallback(const octomap_msgs::OctomapPtr &obs_msg){
        collision_map_ = *obs_msg;
    }

    octomap_msgs::Octomap collision_map_;
    ros::Publisher cmd_pub_;
    ros::Subscriber obs_sub_;
    tf::TransformListener tf_listener_;
    std::string base_link_;
};

int main(int argc, char *argv[]){
    ros::init(argc, argv, "apf_planner");

    ros::NodeHandle node;
    ArtificialPotentialField apf(node);
    apf.spin();

    return 0;
}

<commit_msg>Fix type error<commit_after>#include <ros/ros.h>
#include <geometry_msgs/Twist.h>
#include <sensor_msgs/PointCloud2.h>
#include <sensor_msgs/PointCloud.h>
#include <sensor_msgs/point_cloud_conversion.h>
#include <tf/transform_listener.h>
#include <octomap/octomap.h>
#include <octomap/OcTree.h>
#include <octomap_msgs/Octomap.h>
#include <octomap_msgs/conversions.h>

#include <string>
#include <math.h>
#include <vector>

#include "dmath/geometry.h"

class ArtificialPotentialField{
public:
    ArtificialPotentialField(ros::NodeHandle &node) :
        base_link_("base_link"),
        cmd_pub_(node.advertise<geometry_msgs::Twist>("cmd_vel", 10)),
        obs_sub_(node.subscribe("/camera/depth/points", 10, &ArtificialPotentialField::obstacleCallback, this))

    {
        collision_map_.header.stamp = ros::Time(0);
    }

    void spin(){
        ros::Rate r(10);

        ros::Duration(1).sleep();
        geometry_msgs::Twist cmd;
        cmd.linear.z = 0.15;
        cmd_pub_.publish(cmd);
        ros::Duration(3).sleep();

        cmd.linear.z = 0;
        cmd_pub_.publish(cmd);
        ros::Duration(3).sleep();

        const double force = 0.0025;

        while(ros::ok()){
            if(collision_map_.header.stamp != ros::Time(0)){
                std::vector<dmath::Vector3D> obstacles;
                octomap::OcTree tree = octomap_msgs::msgToMap(collision_map_);
                octomap::OcTree::leaf_iterator const end_it = tree->end_leafs();
                for(octomap::OcTree::leaf_iterator it = tree->begin_leafs(0); it != end_it; it++){
                    obstacles.push_back(dmath::Vector3D(it.getX(), it.getY(), it.getZ()));
                }

                dmath::Vector3D Fs;
                for(int i=0; i < obstacles.size(); i++){
                    Fs += get_potential_force(obstacles[i], 0, 0.005, 1.0, 1.5);
                }

                //dmath::Vector3D g;
                //Fs += get_potential_force(g, 2, 0, 1.5, 1);

                dmath::Vector3D vel = Fs * force;
                cmd.linear.x = vel.y;
                cmd.linear.y = vel.x;
                cmd.linear.z = vel.z;

                ROS_INFO_STREAM("cmd = " << cmd);
                cmd_pub_.publish(cmd);
            }
            r.sleep();
            ros::spinOnce();
        }
    }

private:
    dmath::Vector3D get_potential_force(const dmath::Vector3D &dest_lc, double A = 1, double B = 1, double n = 1, double m = 1){
        dmath::Vector3D u = dest_lc;
        u = normalize(u);

        const double d = magnitude(dest_lc);
        double U = 0;
        if(fabs(d) > dmath::tol){
            U = -A/pow(d, n) + B/pow(d, m);
        }

        return U * u;
    }

    void obstacleCallback(const octomap_msgs::OctomapPtr &obs_msg){
        collision_map_ = *obs_msg;
    }

    octomap_msgs::Octomap collision_map_;
    ros::Publisher cmd_pub_;
    ros::Subscriber obs_sub_;
    tf::TransformListener tf_listener_;
    std::string base_link_;
};

int main(int argc, char *argv[]){
    ros::init(argc, argv, "apf_planner");

    ros::NodeHandle node;
    ArtificialPotentialField apf(node);
    apf.spin();

    return 0;
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: baslibnode.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 02:22:00 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef SCRIPTING_BASLIBNODE_HXX
#include "baslibnode.hxx"
#endif

#ifndef SCRIPTING_BASMODNODE_HXX
#include "basmodnode.hxx"
#endif

#ifndef _COM_SUN_STAR_SCRIPT_BROWSE_BROWSENODETYPES_HPP_
#include <com/sun/star/script/browse/BrowseNodeTypes.hpp>
#endif

#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _BASMGR_HXX
#include <basic/basmgr.hxx>
#endif
#ifndef _SB_SBSTAR_HXX
#include <basic/sbstar.hxx>
#endif

using namespace ::com::sun::star;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::script;

//.........................................................................
namespace basprov
{
//.........................................................................

    // =============================================================================
    // BasicLibraryNodeImpl
    // =============================================================================

    BasicLibraryNodeImpl::BasicLibraryNodeImpl( const Reference< XComponentContext >& rxContext,
         const ::rtl::OUString& sScriptingContext, BasicManager* pBasicManager,
        const Reference< script::XLibraryContainer >& xLibContainer, const ::rtl::OUString& sLibName, bool isAppScript )
        :m_xContext( rxContext )
    ,m_sScriptingContext( sScriptingContext )
        ,m_pBasicManager( pBasicManager )
        ,m_xLibContainer( xLibContainer )
        ,m_sLibName( sLibName )
        ,m_bIsAppScript( isAppScript )
    {
        if ( m_xLibContainer.is() )
        {
            Any aElement = m_xLibContainer->getByName( m_sLibName );
            aElement >>= m_xLibrary;
        }
    }

    // -----------------------------------------------------------------------------

    BasicLibraryNodeImpl::~BasicLibraryNodeImpl()
    {
    }

    // -----------------------------------------------------------------------------
    // XBrowseNode
    // -----------------------------------------------------------------------------

    ::rtl::OUString BasicLibraryNodeImpl::getName(  ) throw (RuntimeException)
    {
        ::vos::OGuard aGuard( Application::GetSolarMutex() );

        return m_sLibName;
    }

    // -----------------------------------------------------------------------------

    Sequence< Reference< browse::XBrowseNode > > BasicLibraryNodeImpl::getChildNodes(  ) throw (RuntimeException)
    {
        ::vos::OGuard aGuard( Application::GetSolarMutex() );

        Sequence< Reference< browse::XBrowseNode > > aChildNodes;

        if ( m_xLibContainer.is() && m_xLibContainer->hasByName( m_sLibName ) && !m_xLibContainer->isLibraryLoaded( m_sLibName ) )
            m_xLibContainer->loadLibrary( m_sLibName );

        if ( m_pBasicManager )
        {
            StarBASIC* pBasic = m_pBasicManager->GetLib( m_sLibName );
            if ( pBasic && m_xLibrary.is() )
            {
                Sequence< ::rtl::OUString > aNames = m_xLibrary->getElementNames();
                sal_Int32 nCount = aNames.getLength();
                const ::rtl::OUString* pNames = aNames.getConstArray();
                aChildNodes.realloc( nCount );
                Reference< browse::XBrowseNode >* pChildNodes = aChildNodes.getArray();

                for ( sal_Int32 i = 0 ; i < nCount ; ++i )
                {
                    SbModule* pModule = pBasic->FindModule( pNames[i] );
                    if ( pModule )
                        pChildNodes[i] = static_cast< browse::XBrowseNode* >( new BasicModuleNodeImpl( m_xContext, m_sScriptingContext, pModule, m_bIsAppScript ) );
                }
            }
        }

        return aChildNodes;
    }

    // -----------------------------------------------------------------------------

    sal_Bool BasicLibraryNodeImpl::hasChildNodes(  ) throw (RuntimeException)
    {
        ::vos::OGuard aGuard( Application::GetSolarMutex() );

        sal_Bool bReturn = sal_False;
        if ( m_xLibrary.is() )
            bReturn = m_xLibrary->hasElements();

        return bReturn;
    }

    // -----------------------------------------------------------------------------

    sal_Int16 BasicLibraryNodeImpl::getType(  ) throw (RuntimeException)
    {
        ::vos::OGuard aGuard( Application::GetSolarMutex() );

        return browse::BrowseNodeTypes::CONTAINER;
    }

    // -----------------------------------------------------------------------------

//.........................................................................
}   // namespace basprov
//.........................................................................
<commit_msg>INTEGRATION: CWS pchfix02 (1.8.36); FILE MERGED 2006/09/01 17:35:33 kaib 1.8.36.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: baslibnode.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-16 12:25:28 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_scripting.hxx"

#ifndef SCRIPTING_BASLIBNODE_HXX
#include "baslibnode.hxx"
#endif

#ifndef SCRIPTING_BASMODNODE_HXX
#include "basmodnode.hxx"
#endif

#ifndef _COM_SUN_STAR_SCRIPT_BROWSE_BROWSENODETYPES_HPP_
#include <com/sun/star/script/browse/BrowseNodeTypes.hpp>
#endif

#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _BASMGR_HXX
#include <basic/basmgr.hxx>
#endif
#ifndef _SB_SBSTAR_HXX
#include <basic/sbstar.hxx>
#endif

using namespace ::com::sun::star;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::script;

//.........................................................................
namespace basprov
{
//.........................................................................

    // =============================================================================
    // BasicLibraryNodeImpl
    // =============================================================================

    BasicLibraryNodeImpl::BasicLibraryNodeImpl( const Reference< XComponentContext >& rxContext,
         const ::rtl::OUString& sScriptingContext, BasicManager* pBasicManager,
        const Reference< script::XLibraryContainer >& xLibContainer, const ::rtl::OUString& sLibName, bool isAppScript )
        :m_xContext( rxContext )
    ,m_sScriptingContext( sScriptingContext )
        ,m_pBasicManager( pBasicManager )
        ,m_xLibContainer( xLibContainer )
        ,m_sLibName( sLibName )
        ,m_bIsAppScript( isAppScript )
    {
        if ( m_xLibContainer.is() )
        {
            Any aElement = m_xLibContainer->getByName( m_sLibName );
            aElement >>= m_xLibrary;
        }
    }

    // -----------------------------------------------------------------------------

    BasicLibraryNodeImpl::~BasicLibraryNodeImpl()
    {
    }

    // -----------------------------------------------------------------------------
    // XBrowseNode
    // -----------------------------------------------------------------------------

    ::rtl::OUString BasicLibraryNodeImpl::getName(  ) throw (RuntimeException)
    {
        ::vos::OGuard aGuard( Application::GetSolarMutex() );

        return m_sLibName;
    }

    // -----------------------------------------------------------------------------

    Sequence< Reference< browse::XBrowseNode > > BasicLibraryNodeImpl::getChildNodes(  ) throw (RuntimeException)
    {
        ::vos::OGuard aGuard( Application::GetSolarMutex() );

        Sequence< Reference< browse::XBrowseNode > > aChildNodes;

        if ( m_xLibContainer.is() && m_xLibContainer->hasByName( m_sLibName ) && !m_xLibContainer->isLibraryLoaded( m_sLibName ) )
            m_xLibContainer->loadLibrary( m_sLibName );

        if ( m_pBasicManager )
        {
            StarBASIC* pBasic = m_pBasicManager->GetLib( m_sLibName );
            if ( pBasic && m_xLibrary.is() )
            {
                Sequence< ::rtl::OUString > aNames = m_xLibrary->getElementNames();
                sal_Int32 nCount = aNames.getLength();
                const ::rtl::OUString* pNames = aNames.getConstArray();
                aChildNodes.realloc( nCount );
                Reference< browse::XBrowseNode >* pChildNodes = aChildNodes.getArray();

                for ( sal_Int32 i = 0 ; i < nCount ; ++i )
                {
                    SbModule* pModule = pBasic->FindModule( pNames[i] );
                    if ( pModule )
                        pChildNodes[i] = static_cast< browse::XBrowseNode* >( new BasicModuleNodeImpl( m_xContext, m_sScriptingContext, pModule, m_bIsAppScript ) );
                }
            }
        }

        return aChildNodes;
    }

    // -----------------------------------------------------------------------------

    sal_Bool BasicLibraryNodeImpl::hasChildNodes(  ) throw (RuntimeException)
    {
        ::vos::OGuard aGuard( Application::GetSolarMutex() );

        sal_Bool bReturn = sal_False;
        if ( m_xLibrary.is() )
            bReturn = m_xLibrary->hasElements();

        return bReturn;
    }

    // -----------------------------------------------------------------------------

    sal_Int16 BasicLibraryNodeImpl::getType(  ) throw (RuntimeException)
    {
        ::vos::OGuard aGuard( Application::GetSolarMutex() );

        return browse::BrowseNodeTypes::CONTAINER;
    }

    // -----------------------------------------------------------------------------

//.........................................................................
}   // namespace basprov
//.........................................................................
<|endoftext|>


<commit_before>#include <Galaxy.h>
#include <numeric>

double Galaxy::get_mass() const
{
  return std::accumulate(stars.begin(), stars.end(), 0.0,
         [](double mass , Star const& star) {
           return mass + star.get_mass();
         });
}

<commit_msg>intended error to test jenkins<commit_after>#include <Galaxy.h>
#include <numeric>

double Galaxy::get_mass() const
{
  return std::accumulate(stars.begin(), stars.end(), 1.0,
         [](double mass , Star const& star) {
           return mass + star.get_mass();
         });
}

<|endoftext|>