comparison Core/Toolbox.cpp @ 2043:35ccba7adae9

Toolbox::UriEncode
author Sebastien Jodogne <s.jodogne@gmail.com>
date Thu, 23 Jun 2016 10:08:27 +0200
parents 08ce34cfacad
children 54417b0831c4
comparison
equal deleted inserted replaced
2042:5b93382f88e1 2043:35ccba7adae9
1504 throw OrthancException(ErrorCode_ParameterOutOfRange); 1504 throw OrthancException(ErrorCode_ParameterOutOfRange);
1505 } 1505 }
1506 1506
1507 return fopen(path.c_str(), m); 1507 return fopen(path.c_str(), m);
1508 } 1508 }
1509
1510
1511
1512 static bool IsUnreservedCharacter(char c)
1513 {
1514 // This function checks whether "c" is an unserved character
1515 // wrt. an URI percent-encoding
1516 // https://en.wikipedia.org/wiki/Percent-encoding#Percent-encoding%5Fin%5Fa%5FURI
1517
1518 return ((c >= 'A' && c <= 'Z') ||
1519 (c >= 'a' && c <= 'z') ||
1520 (c >= '0' && c <= '9') ||
1521 c == '-' ||
1522 c == '_' ||
1523 c == '.' ||
1524 c == '~');
1525 }
1526
1527 void Toolbox::UriEncode(std::string& target,
1528 const std::string& source)
1529 {
1530 // Estimate the length of the percent-encoded URI
1531 size_t length = 0;
1532
1533 for (size_t i = 0; i < source.size(); i++)
1534 {
1535 if (IsUnreservedCharacter(source[i]))
1536 {
1537 length += 1;
1538 }
1539 else
1540 {
1541 // This character must be percent-encoded
1542 length += 3;
1543 }
1544 }
1545
1546 target.clear();
1547 target.reserve(length);
1548
1549 for (size_t i = 0; i < source.size(); i++)
1550 {
1551 if (IsUnreservedCharacter(source[i]))
1552 {
1553 target.push_back(source[i]);
1554 }
1555 else
1556 {
1557 // This character must be percent-encoded
1558 uint8_t byte = static_cast<uint8_t>(source[i]);
1559 uint8_t a = byte >> 4;
1560 uint8_t b = byte & 0x0f;
1561
1562 target.push_back('%');
1563 target.push_back(a < 10 ? a + '0' : a - 10 + 'A');
1564 target.push_back(b < 10 ? b + '0' : b - 10 + 'A');
1565 }
1566 }
1567 }
1509 } 1568 }