Line data Source code
1 : //
2 : // Copyright (c) 2025 Vinnie Falco (vinnie dot falco at gmail dot com)
3 : //
4 : // Distributed under the Boost Software License, Version 1.0. (See accompanying
5 : // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
6 : //
7 : // Official repository: https://github.com/cppalliance/http
8 : //
9 :
10 : #include <boost/http/server/encode_url.hpp>
11 :
12 : namespace boost {
13 : namespace http {
14 :
15 : namespace {
16 :
17 : // Check if character needs encoding
18 : // Unreserved + reserved chars that are allowed in URLs
19 : bool
20 0 : is_safe( char c ) noexcept
21 : {
22 : // Unreserved: A-Z a-z 0-9 - _ . ~
23 0 : if( ( c >= 'A' && c <= 'Z' ) ||
24 0 : ( c >= 'a' && c <= 'z' ) ||
25 0 : ( c >= '0' && c <= '9' ) ||
26 0 : c == '-' || c == '_' || c == '.' || c == '~' )
27 0 : return true;
28 :
29 : // Reserved chars allowed in URLs: ! # $ & ' ( ) * + , / : ; = ? @
30 0 : switch( c )
31 : {
32 0 : case '!':
33 : case '#':
34 : case '$':
35 : case '&':
36 : case '\'':
37 : case '(':
38 : case ')':
39 : case '*':
40 : case '+':
41 : case ',':
42 : case '/':
43 : case ':':
44 : case ';':
45 : case '=':
46 : case '?':
47 : case '@':
48 0 : return true;
49 0 : default:
50 0 : return false;
51 : }
52 : }
53 :
54 : constexpr char hex_chars[] = "0123456789ABCDEF";
55 :
56 : } // (anon)
57 :
58 : std::string
59 0 : encode_url( core::string_view url )
60 : {
61 0 : std::string result;
62 0 : result.reserve( url.size() );
63 :
64 0 : for( unsigned char c : url )
65 : {
66 0 : if( is_safe( static_cast<char>( c ) ) )
67 : {
68 0 : result.push_back( static_cast<char>( c ) );
69 : }
70 : else
71 : {
72 0 : result.push_back( '%' );
73 0 : result.push_back( hex_chars[c >> 4] );
74 0 : result.push_back( hex_chars[c & 0x0F] );
75 : }
76 : }
77 :
78 0 : return result;
79 0 : }
80 :
81 : } // http
82 : } // boost
|