1 /*
2  *  Created by Phil on 13/7/2015.
3  *  Copyright 2015 Two Blue Cubes Ltd. All rights reserved.
4  *
5  *  Distributed under the Boost Software License, Version 1.0. (See accompanying
6  *  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
7  */
8 #ifndef TWOBLUECUBES_CATCH_WILDCARD_PATTERN_HPP_INCLUDED
9 #define TWOBLUECUBES_CATCH_WILDCARD_PATTERN_HPP_INCLUDED
10 
11 #include "catch_common.h"
12 
13 namespace Catch
14 {
15     class WildcardPattern {
16         enum WildcardPosition {
17             NoWildcard = 0,
18             WildcardAtStart = 1,
19             WildcardAtEnd = 2,
20             WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd
21         };
22 
23     public:
24 
WildcardPattern(std::string const & pattern,CaseSensitive::Choice caseSensitivity)25         WildcardPattern( std::string const& pattern, CaseSensitive::Choice caseSensitivity )
26         :   m_caseSensitivity( caseSensitivity ),
27             m_wildcard( NoWildcard ),
28             m_pattern( adjustCase( pattern ) )
29         {
30             if( startsWith( m_pattern, '*' ) ) {
31                 m_pattern = m_pattern.substr( 1 );
32                 m_wildcard = WildcardAtStart;
33             }
34             if( endsWith( m_pattern, '*' ) ) {
35                 m_pattern = m_pattern.substr( 0, m_pattern.size()-1 );
36                 m_wildcard = static_cast<WildcardPosition>( m_wildcard | WildcardAtEnd );
37             }
38         }
39         virtual ~WildcardPattern();
matches(std::string const & str) const40         virtual bool matches( std::string const& str ) const {
41             switch( m_wildcard ) {
42                 case NoWildcard:
43                     return m_pattern == adjustCase( str );
44                 case WildcardAtStart:
45                     return endsWith( adjustCase( str ), m_pattern );
46                 case WildcardAtEnd:
47                     return startsWith( adjustCase( str ), m_pattern );
48                 case WildcardAtBothEnds:
49                     return contains( adjustCase( str ), m_pattern );
50             }
51 
52 #ifdef __clang__
53 #pragma clang diagnostic push
54 #pragma clang diagnostic ignored "-Wunreachable-code"
55 #endif
56             throw std::logic_error( "Unknown enum" );
57 #ifdef __clang__
58 #pragma clang diagnostic pop
59 #endif
60         }
61     private:
adjustCase(std::string const & str) const62         std::string adjustCase( std::string const& str ) const {
63             return m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str;
64         }
65         CaseSensitive::Choice m_caseSensitivity;
66         WildcardPosition m_wildcard;
67         std::string m_pattern;
68     };
69 }
70 
71 #endif // TWOBLUECUBES_CATCH_WILDCARD_PATTERN_HPP_INCLUDED
72