aboutsummaryrefslogtreecommitdiff
path: root/web/mime-url-encoding.cxx
blob: e202f08afe248c9b7d06ee420651383062b8117f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// file      : web/mime-url-encoding.cxx -*- C++ -*-
// license   : MIT; see accompanying LICENSE file

#include <web/mime-url-encoding.hxx>

#include <string>
#include <iterator> // back_inserter

#include <libbutl/url.mxx>

using namespace std;
using namespace butl;

namespace web
{
  inline static bool
  encode_query (char& c)
  {
    if (c == ' ')
    {
      c = '+';
      return false;
    }

    return !url::unreserved (c);
  }

  string
  mime_url_encode (const char* v, bool query)
  {
    return query ? url::encode (v, encode_query) : url::encode (v);
  }

  string
  mime_url_encode (const string& v, bool query)
  {
    return query ? url::encode (v, encode_query) : url::encode (v);
  }

  string
  mime_url_decode (const char* b, const char* e, bool trim, bool query)
  {
    if (trim)
    {
      for (; b != e && *b == ' '; ++b) ;

      if (b == e)
        return string ();

      while (*--e == ' ');
      ++e;
    }

    string r;
    if (!query)
      url::decode (b, e, back_inserter (r));
    else
      url::decode (b, e, back_inserter (r),
                   [] (char& c)
                   {
                     if (c == '+')
                       c = ' ';
                   });
    return r;
  }
}