1 /*******************************************************************************
2  * tlx/string/parse_uri.hpp
3  *
4  * Part of tlx - http://panthema.net/tlx
5  *
6  * Copyright (C) 2020 Timo Bingmann <tb@panthema.net>
7  *
8  * All rights reserved. Published under the Boost Software License, Version 1.0
9  ******************************************************************************/
10 
11 #ifndef TLX_STRING_PARSE_URI_HEADER
12 #define TLX_STRING_PARSE_URI_HEADER
13 
14 #include <tlx/container/string_view.hpp>
15 
16 namespace tlx {
17 
18 //! \addtogroup tlx_string
19 //! \{
20 
21 /*!
22  * Parse a URI like "/path1/path2?query=string&submit=submit#fragment" into the
23  * parts path, query_string, and fragment. The parts are returned as
24  * tlx::string_views to avoid copying data.
25  */
26 static inline
parse_uri(const char * uri,tlx::string_view * path,tlx::string_view * query_string,tlx::string_view * fragment)27 void parse_uri(const char* uri, tlx::string_view* path,
28                tlx::string_view* query_string, tlx::string_view* fragment) {
29     const char* c = uri;
30 
31     // find path part
32     const char* begin = c;
33     while (!(*c == '?' || *c == '#' || *c == 0)) {
34         ++c;
35     }
36     *path = tlx::string_view(begin, c - begin);
37 
38     // find query string
39     begin = c;
40     if (*c == '?') {
41         begin = ++c;
42         while (!(*c == '#' || *c == 0)) {
43             ++c;
44         }
45     }
46     *query_string = tlx::string_view(begin, c - begin);
47 
48     // find fragment
49     begin = c;
50     if (*c == '#') {
51         begin = ++c;
52         while (*c != 0) {
53             ++c;
54         }
55     }
56     *fragment = tlx::string_view(begin, c - begin);
57 }
58 
59 /*!
60  * Parse a URI like "/path1/path2?query=string&submit=submit#fragment" into the
61  * parts path, query_string, and fragment. The parts are returned as
62  * tlx::string_views to avoid copying data.
63  */
64 static inline
parse_uri(const std::string & uri,tlx::string_view * path,tlx::string_view * query_string,tlx::string_view * fragment)65 void parse_uri(const std::string& uri, tlx::string_view* path,
66                tlx::string_view* query_string, tlx::string_view* fragment) {
67     return parse_uri(uri.c_str(), path, query_string, fragment);
68 }
69 
70 //! \}
71 
72 } // namespace tlx
73 
74 #endif // !TLX_STRING_PARSE_URI_HEADER
75 
76 /******************************************************************************/
77