changeset 126:93b15955460c dev

sync
author Sebastien Jodogne <s.jodogne@gmail.com>
date Thu, 23 Jun 2016 10:09:16 +0200
parents 8fe231bd64d1
children 1a21c9da983a
files Orthanc/Core/Toolbox.cpp Orthanc/Core/Toolbox.h
diffstat 2 files changed, 62 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/Orthanc/Core/Toolbox.cpp	Wed Jun 22 17:21:04 2016 +0200
+++ b/Orthanc/Core/Toolbox.cpp	Thu Jun 23 10:09:16 2016 +0200
@@ -1506,4 +1506,63 @@
 
     return fopen(path.c_str(), m);
   }
+
+  
+
+  static bool IsUnreservedCharacter(char c)
+  {
+    // This function checks whether "c" is an unserved character
+    // wrt. an URI percent-encoding
+    // https://en.wikipedia.org/wiki/Percent-encoding#Percent-encoding%5Fin%5Fa%5FURI
+
+    return ((c >= 'A' && c <= 'Z') ||
+            (c >= 'a' && c <= 'z') ||
+            (c >= '0' && c <= '9') ||
+            c == '-' ||
+            c == '_' ||
+            c == '.' ||
+            c == '~');
+  }
+
+  void Toolbox::UriEncode(std::string& target,
+                          const std::string& source)
+  {
+    // Estimate the length of the percent-encoded URI
+    size_t length = 0;
+
+    for (size_t i = 0; i < source.size(); i++)
+    {
+      if (IsUnreservedCharacter(source[i]))
+      {
+        length += 1;
+      }
+      else
+      {
+        // This character must be percent-encoded
+        length += 3;
+      }
+    }
+
+    target.clear();
+    target.reserve(length);
+
+    for (size_t i = 0; i < source.size(); i++)
+    {
+      if (IsUnreservedCharacter(source[i]))
+      {
+        target.push_back(source[i]);
+      }
+      else
+      {
+        // This character must be percent-encoded
+        uint8_t byte = static_cast<uint8_t>(source[i]);
+        uint8_t a = byte >> 4;
+        uint8_t b = byte & 0x0f;
+
+        target.push_back('%');
+        target.push_back(a < 10 ? a + '0' : a - 10 + 'A');
+        target.push_back(b < 10 ? b + '0' : b - 10 + 'A');
+      }
+    }
+  }  
 }
--- a/Orthanc/Core/Toolbox.h	Wed Jun 22 17:21:04 2016 +0200
+++ b/Orthanc/Core/Toolbox.h	Thu Jun 23 10:09:16 2016 +0200
@@ -199,5 +199,8 @@
 
     FILE* OpenFile(const std::string& path,
                    FileMode mode);
+
+    void UriEncode(std::string& target,
+                   const std::string& source);
   }
 }