Further simplify StringBuilder usage by standardizing hex formating to a single hex...
authorweinig@apple.com <weinig@apple.com@268f45cc-cd09-0410-ab3c-d52691b4dbfc>
Mon, 6 Jan 2020 00:20:57 +0000 (00:20 +0000)
committerweinig@apple.com <weinig@apple.com@268f45cc-cd09-0410-ab3c-d52691b4dbfc>
Mon, 6 Jan 2020 00:20:57 +0000 (00:20 +0000)
https://bugs.webkit.org/show_bug.cgi?id=205759

Reviewed by Dean Jackson.

Source/JavaScriptCore:

* heap/HeapSnapshotBuilder.cpp:
(JSC::HeapSnapshotBuilder::json):
* runtime/JSGlobalObjectFunctions.cpp:
(JSC::encode):
(JSC::globalFuncEscape):
Replace appendUnsignedAsHex() and appendByteAsHex() with append(hex()).

Source/WebCore:

* Modules/websockets/WebSocket.cpp:
(WebCore::encodeProtocolString):
* css/CSSMarkup.cpp:
(WebCore::serializeCharacterAsCodePoint):
* css/parser/CSSParserToken.cpp:
(WebCore::CSSParserToken::serialize const):
* platform/graphics/Color.cpp:
(WebCore::Color::serialized const):
* platform/graphics/gstreamer/MediaPlayerPrivateGStreamer.cpp:
(WebCore::MediaPlayerPrivateGStreamer::processMpegTsSection):
* platform/graphics/opengl/GraphicsContext3DOpenGLCommon.cpp:
(WebCore::generateHashedName):
* platform/network/curl/CurlCacheEntry.cpp:
(WebCore::CurlCacheEntry::generateBaseFilename):
* rendering/RenderTreeAsText.cpp:
(WebCore::quoteAndEscapeNonPrintables):
Replace appendByteAsHex()/appendUnsignedAsHex()/appendUnsignedAsHexFixedSize() with append(hex()).

* platform/network/FormDataBuilder.cpp:
(WebCore::FormDataBuilder::appendFormURLEncoded):
This was the last non-StringBuilder/makeString use of appendByteAsHex. Rather than keep appendByteAsHex
around, it is replaced with direct appends of the character buffer hex() produces.

Source/WebKit:

* UIProcess/DeviceIdHashSaltStorage.cpp:
(WebKit::DeviceIdHashSaltStorage::completeDeviceIdHashSaltForOriginCall):
* UIProcess/WebBackForwardList.cpp:
(WebKit::WebBackForwardList::loggingString):
Replace appendUnsignedAsHex() with append(hex()).

Source/WTF:

Removes appendByteAsHex, appendUnsignedAsHex and appendUnsignedAsHexFixedSize with the
following mappings:

    appendByteAsHex(value, builder, case)
      -> builder.append(hex(static_cast<unsigned char>(value), 2, case))
    appendUnsignedAsHex(value, builder, case)
      -> builder.append(hex(value, case))
    appendUnsignedAsHexFixedSize(value, builder, size, case)
      -> builder.append(hex(value, size, case))

Adds new API test for HexNumber.cpp

* wtf/HexNumber.h:
(WTF::appendByteAsHex): Deleted.
(WTF::appendUnsignedAsHex): Deleted.
(WTF::appendUnsignedAsHexFixedSize): Deleted.
Remove now unused helper functions.

* wtf/FileSystem.cpp:
(WTF::FileSystemImpl::encodeForFileName):
Replace appendByteAsHex with direct use of hex(x, 2). The static_cast is needed
since there was an implicit down cast when appendByteAsHex was used.

* wtf/Logger.cpp:
(WTF::Logger::LogSiteIdentifier::toString const):
(WTF::>::toString):
* wtf/UUID.cpp:
(WTF::createCanonicalUUIDString):
Replace appendUnsignedAsHex/appendUnsignedAsHexFixedSize with hex(). Use makeString()
rather StringBuilder to simplify things further.

* wtf/text/WTFString.cpp:
(asciiDebug):
Replace appendUnsignedAsHexFixedSize with append(hex()).

Tools:

* TestWebKitAPI/CMakeLists.txt:
* TestWebKitAPI/TestWebKitAPI.xcodeproj/project.pbxproj:
* TestWebKitAPI/Tests/WTF/HexNumber.cpp: Added.
Add testing for hex formatting of integers.

git-svn-id: http://svn.webkit.org/repository/webkit/trunk@254046 268f45cc-cd09-0410-ab3c-d52691b4dbfc

26 files changed:
Source/JavaScriptCore/ChangeLog
Source/JavaScriptCore/heap/HeapSnapshotBuilder.cpp
Source/JavaScriptCore/runtime/JSGlobalObjectFunctions.cpp
Source/WTF/ChangeLog
Source/WTF/wtf/FileSystem.cpp
Source/WTF/wtf/HexNumber.h
Source/WTF/wtf/Logger.cpp
Source/WTF/wtf/UUID.cpp
Source/WTF/wtf/text/WTFString.cpp
Source/WebCore/ChangeLog
Source/WebCore/Modules/websockets/WebSocket.cpp
Source/WebCore/css/CSSMarkup.cpp
Source/WebCore/css/parser/CSSParserToken.cpp
Source/WebCore/platform/graphics/Color.cpp
Source/WebCore/platform/graphics/gstreamer/MediaPlayerPrivateGStreamer.cpp
Source/WebCore/platform/graphics/opengl/GraphicsContext3DOpenGLCommon.cpp
Source/WebCore/platform/network/FormDataBuilder.cpp
Source/WebCore/platform/network/curl/CurlCacheEntry.cpp
Source/WebCore/rendering/RenderTreeAsText.cpp
Source/WebKit/ChangeLog
Source/WebKit/UIProcess/DeviceIdHashSaltStorage.cpp
Source/WebKit/UIProcess/WebBackForwardList.cpp
Tools/ChangeLog
Tools/TestWebKitAPI/CMakeLists.txt
Tools/TestWebKitAPI/TestWebKitAPI.xcodeproj/project.pbxproj
Tools/TestWebKitAPI/Tests/WTF/HexNumber.cpp [new file with mode: 0644]

index 8a6c3a9..6b17d44 100644 (file)
@@ -1,3 +1,17 @@
+2020-01-05  Sam Weinig  <weinig@apple.com>
+
+        Further simplify StringBuilder usage by standardizing hex formating to a single hex() function
+        https://bugs.webkit.org/show_bug.cgi?id=205759
+
+        Reviewed by Dean Jackson.
+
+        * heap/HeapSnapshotBuilder.cpp:
+        (JSC::HeapSnapshotBuilder::json):
+        * runtime/JSGlobalObjectFunctions.cpp:
+        (JSC::encode):
+        (JSC::globalFuncEscape):
+        Replace appendUnsignedAsHex() and appendByteAsHex() with append(hex()).
+
 2020-01-05  Ross Kirsling  <ross.kirsling@sony.com>
 
         JavaScript: Invalid date parse for ISO 8601 strings when no timezone given
index 866ada3..ce039ba 100644 (file)
@@ -464,9 +464,9 @@ String HeapSnapshotBuilder::json(Function<bool (const HeapSnapshotNode&)> allowN
             json.append(',');
             json.appendNumber(labelIndex);
             json.appendLiteral(",\"0x");
-            appendUnsignedAsHex(reinterpret_cast<uintptr_t>(node.cell), json, Lowercase);
+            json.append(hex(reinterpret_cast<uintptr_t>(node.cell), Lowercase));
             json.appendLiteral("\",\"0x");
-            appendUnsignedAsHex(reinterpret_cast<uintptr_t>(wrappedAddress), json, Lowercase);
+            json.append(hex(reinterpret_cast<uintptr_t>(wrappedAddress), Lowercase));
             json.append('"');
         }
     };
index b8113dc..9ba8c70 100644 (file)
@@ -145,7 +145,7 @@ static JSValue encode(JSGlobalObject* globalObject, const Bitmap<256>& doNotEsca
             // 4-d-vi-2. Let S be a String containing three code units "%XY" where XY are two uppercase hexadecimal digits encoding the value of jOctet.
             // 4-d-vi-3. Let R be a new String value computed by concatenating the previous value of R and S.
             builder.append('%');
-            appendByteAsHex(utf8OctetsBuffer[index], builder);
+            builder.append(hex(utf8OctetsBuffer[index], 2));
         }
     }
 
@@ -608,7 +608,7 @@ EncodedJSValue JSC_HOST_CALL globalFuncEscape(JSGlobalObject* globalObject, Call
                     builder.append(*c);
                 else {
                     builder.append('%');
-                    appendByteAsHex(u, builder);
+                    builder.append(hex(u, 2));
                 }
             }
             return jsString(vm, builder.toString());
@@ -619,13 +619,13 @@ EncodedJSValue JSC_HOST_CALL globalFuncEscape(JSGlobalObject* globalObject, Call
             UChar u = c[0];
             if (u >= doNotEscape.size()) {
                 builder.appendLiteral("%u");
-                appendByteAsHex(u >> 8, builder);
-                appendByteAsHex(u & 0xFF, builder);
+                builder.append(hex(static_cast<unsigned char>(u >> 8), 2));
+                builder.append(hex(static_cast<unsigned char>(u & 0xFF), 2));
             } else if (doNotEscape.get(static_cast<LChar>(u)))
                 builder.append(*c);
             else {
                 builder.append('%');
-                appendByteAsHex(u, builder);
+                builder.append(hex(static_cast<unsigned char>(u), 2));
             }
         }
 
index 329467e..02bee5b 100644 (file)
@@ -1,3 +1,45 @@
+2020-01-05  Sam Weinig  <weinig@apple.com>
+
+        Further simplify StringBuilder usage by standardizing hex formating to a single hex() function
+        https://bugs.webkit.org/show_bug.cgi?id=205759
+
+        Reviewed by Dean Jackson.
+
+        Removes appendByteAsHex, appendUnsignedAsHex and appendUnsignedAsHexFixedSize with the
+        following mappings:
+
+            appendByteAsHex(value, builder, case) 
+              -> builder.append(hex(static_cast<unsigned char>(value), 2, case))
+            appendUnsignedAsHex(value, builder, case) 
+              -> builder.append(hex(value, case))
+            appendUnsignedAsHexFixedSize(value, builder, size, case)
+              -> builder.append(hex(value, size, case))
+        
+        Adds new API test for HexNumber.cpp
+
+        * wtf/HexNumber.h:
+        (WTF::appendByteAsHex): Deleted.
+        (WTF::appendUnsignedAsHex): Deleted.
+        (WTF::appendUnsignedAsHexFixedSize): Deleted.
+        Remove now unused helper functions.
+        
+        * wtf/FileSystem.cpp:
+        (WTF::FileSystemImpl::encodeForFileName):
+        Replace appendByteAsHex with direct use of hex(x, 2). The static_cast is needed
+        since there was an implicit down cast when appendByteAsHex was used.
+        * wtf/Logger.cpp:
+        (WTF::Logger::LogSiteIdentifier::toString const):
+        (WTF::>::toString):
+        * wtf/UUID.cpp:
+        (WTF::createCanonicalUUIDString):
+        Replace appendUnsignedAsHex/appendUnsignedAsHexFixedSize with hex(). Use makeString() 
+        rather StringBuilder to simplify things further.
+
+        * wtf/text/WTFString.cpp:
+        (asciiDebug):
+        Replace appendUnsignedAsHexFixedSize with append(hex()).
+
 2020-01-05  Ross Kirsling  <ross.kirsling@sony.com>
 
         JavaScript: Invalid date parse for ISO 8601 strings when no timezone given
index e072086..72f953e 100644 (file)
@@ -125,11 +125,11 @@ String encodeForFileName(const String& inputString)
         if (shouldEscapeUChar(character, previousCharacter, nextCharacter)) {
             if (character <= 255) {
                 result.append('%');
-                appendByteAsHex(character, result);
+                result.append(hex(static_cast<unsigned char>(character), 2));
             } else {
                 result.appendLiteral("%+");
-                appendByteAsHex(character >> 8, result);
-                appendByteAsHex(character, result);
+                result.append(hex(static_cast<unsigned char>(character >> 8), 2));
+                result.append(hex(static_cast<unsigned char>(character), 2));
             }
         } else
             result.append(character);
index 2e97642..e10ce57 100644 (file)
@@ -47,45 +47,21 @@ inline std::pair<LChar*, unsigned> appendHex(std::array<LChar, arraySize>& buffe
 
 } // namespace Internal
 
-template<typename T>
-inline void appendByteAsHex(unsigned char byte, T& destination, HexConversionMode mode = Uppercase)
-{
-    auto* hexDigits = Internal::hexDigitsForMode(mode);
-    destination.append(hexDigits[byte >> 4]);
-    destination.append(hexDigits[byte & 0xF]);
-}
-
-// FIXME: Consider renaming to appendHex.
-template<typename NumberType, typename DestinationType>
-inline void appendUnsignedAsHex(NumberType number, DestinationType& destination, HexConversionMode mode = Uppercase)
-{
-    appendUnsignedAsHexFixedSize(number, destination, 0, mode);
-}
-
-// FIXME: Consider renaming to appendHex.
-// Same as appendUnsignedAsHex, but zero-padding to get at least the desired number of digits.
-template<typename NumberType>
-inline void appendUnsignedAsHexFixedSize(NumberType number, StringBuilder& destination, unsigned minimumDigits, HexConversionMode mode = Uppercase)
-{
-    // Each byte can generate up to two digits.
-    std::array<LChar, sizeof(NumberType) * 2> buffer;
-    auto result = Internal::appendHex(buffer, number, minimumDigits, mode);
-    destination.appendCharacters(result.first, result.second);
-}
-
 struct HexNumberBuffer {
     WTF_MAKE_STRUCT_FAST_ALLOCATED;
 
-    std::array<LChar, 16> characters;
+    std::array<LChar, 16> buffer;
     unsigned length;
+
+    const LChar* characters() const { return &*(buffer.end() - length); }
 };
 
 template<typename NumberType> HexNumberBuffer hex(NumberType number, unsigned minimumDigits = 0, HexConversionMode mode = Uppercase)
 {
     // Each byte can generate up to two digits.
     HexNumberBuffer buffer;
-    static_assert(sizeof(buffer.characters) >= sizeof(NumberType) * 2, "number too large for hexNumber");
-    auto result = Internal::appendHex(buffer.characters, number, minimumDigits, mode);
+    static_assert(sizeof(buffer.buffer) >= sizeof(NumberType) * 2, "number too large for hexNumber");
+    auto result = Internal::appendHex(buffer.buffer, number, minimumDigits, mode);
     buffer.length = result.second;
     return buffer;
 }
@@ -107,15 +83,12 @@ public:
     template<typename CharacterType> void writeTo(CharacterType* destination) const { StringImpl::copyCharacters(destination, characters(), length()); }
 
 private:
-    const LChar* characters() const { return &*(m_buffer.characters.end() - length()); }
+    const LChar* characters() const { return m_buffer.characters(); }
 
     const HexNumberBuffer& m_buffer;
 };
 
 } // namespace WTF
 
-using WTF::appendByteAsHex;
-using WTF::appendUnsignedAsHex;
-using WTF::appendUnsignedAsHexFixedSize;
 using WTF::hex;
 using WTF::Lowercase;
index b1424b7..7ff1230 100644 (file)
@@ -33,29 +33,14 @@ namespace WTF {
 
 String Logger::LogSiteIdentifier::toString() const
 {
-    StringBuilder builder;
-
-    if (className) {
-        builder.append(className);
-        builder.appendLiteral("::");
-    }
-    builder.append(methodName);
-    builder.append('(');
-    appendUnsignedAsHex(objectPtr, builder);
-    builder.appendLiteral(") ");
-    return builder.toString();
+    if (className)
+        return makeString(className, "::", methodName, '(', hex(objectPtr), ") ");
+    return makeString(methodName, '(', hex(objectPtr), ") ");
 }
 
 String LogArgument<const void*>::toString(const void* argument)
 {
-    StringBuilder builder;
-    builder.append('(');
-    appendUnsignedAsHex(reinterpret_cast<uintptr_t>(argument), builder);
-    builder.append(')');
-    return builder.toString();
+    return makeString('(', hex(reinterpret_cast<uintptr_t>(argument)), ')');
 }
 
 } // namespace WTF
-
-using WTF::Logger;
-using WTF::JSONLogValue;
index 15ca00a..699e3dc 100644 (file)
@@ -48,20 +48,19 @@ String createCanonicalUUIDString()
     cryptographicallyRandomValues(reinterpret_cast<unsigned char*>(randomData), sizeof(randomData));
 
     // Format as Version 4 UUID.
-    StringBuilder builder;
-    builder.reserveCapacity(36);
-    appendUnsignedAsHexFixedSize(randomData[0], builder, 8, Lowercase);
-    builder.append('-');
-    appendUnsignedAsHexFixedSize(randomData[1] >> 16, builder, 4, Lowercase);
-    builder.appendLiteral("-4");
-    appendUnsignedAsHexFixedSize(randomData[1] & 0x00000fff, builder, 3, Lowercase);
-    builder.append('-');
-    appendUnsignedAsHexFixedSize((randomData[2] >> 30) | 0x8, builder, 1, Lowercase);
-    appendUnsignedAsHexFixedSize((randomData[2] >> 16) & 0x00000fff, builder, 3, Lowercase);
-    builder.append('-');
-    appendUnsignedAsHexFixedSize(randomData[2] & 0x0000ffff, builder, 4, Lowercase);
-    appendUnsignedAsHexFixedSize(randomData[3], builder, 8, Lowercase);
-    return builder.toString();
+    return makeString(
+        hex(randomData[0], 8, Lowercase),
+        '-',
+        hex(randomData[1] >> 16, 4, Lowercase),
+        "-4",
+        hex(randomData[1] & 0x00000fff, 3, Lowercase),
+        '-',
+        hex((randomData[2] >> 30) | 0x8, 1, Lowercase),
+        hex((randomData[2] >> 16) & 0x00000fff, 3, Lowercase),
+        '-',
+        hex(randomData[2] & 0x0000ffff, 4, Lowercase),
+        hex(randomData[3], 8, Lowercase)
+    );
 }
 
 String bootSessionUUIDString()
index a0f7855..cfe3ead 100644 (file)
@@ -1120,7 +1120,7 @@ Vector<char> asciiDebug(StringImpl* impl)
         } else {
             buffer.append('\\');
             buffer.append('u');
-            appendUnsignedAsHexFixedSize(ch, buffer, 4);
+            buffer.append(hex(ch, 4));
         }
     }
     CString narrowString = buffer.toString().ascii();
index a654dc4..e7912f7 100644 (file)
@@ -1,3 +1,33 @@
+2020-01-05  Sam Weinig  <weinig@apple.com>
+
+        Further simplify StringBuilder usage by standardizing hex formating to a single hex() function
+        https://bugs.webkit.org/show_bug.cgi?id=205759
+
+        Reviewed by Dean Jackson.
+
+        * Modules/websockets/WebSocket.cpp:
+        (WebCore::encodeProtocolString):
+        * css/CSSMarkup.cpp:
+        (WebCore::serializeCharacterAsCodePoint):
+        * css/parser/CSSParserToken.cpp:
+        (WebCore::CSSParserToken::serialize const):
+        * platform/graphics/Color.cpp:
+        (WebCore::Color::serialized const):
+        * platform/graphics/gstreamer/MediaPlayerPrivateGStreamer.cpp:
+        (WebCore::MediaPlayerPrivateGStreamer::processMpegTsSection):
+        * platform/graphics/opengl/GraphicsContext3DOpenGLCommon.cpp:
+        (WebCore::generateHashedName):
+        * platform/network/curl/CurlCacheEntry.cpp:
+        (WebCore::CurlCacheEntry::generateBaseFilename):
+        * rendering/RenderTreeAsText.cpp:
+        (WebCore::quoteAndEscapeNonPrintables):
+        Replace appendByteAsHex()/appendUnsignedAsHex()/appendUnsignedAsHexFixedSize() with append(hex()).
+
+        * platform/network/FormDataBuilder.cpp:
+        (WebCore::FormDataBuilder::appendFormURLEncoded):
+        This was the last non-StringBuilder/makeString use of appendByteAsHex. Rather than keep appendByteAsHex
+        around, it is replaced with direct appends of the character buffer hex() produces.
+
 2020-01-05  Zalan Bujtas  <zalan@apple.com>
 
         [SLL] Generate runs for preserved new lines
index 94403f2..c5bc829 100644 (file)
@@ -103,7 +103,7 @@ static String encodeProtocolString(const String& protocol)
     for (size_t i = 0; i < protocol.length(); i++) {
         if (protocol[i] < 0x20 || protocol[i] > 0x7E) {
             builder.appendLiteral("\\u");
-            appendUnsignedAsHexFixedSize(protocol[i], builder, 4);
+            builder.append(hex(protocol[i], 4));
         } else if (protocol[i] == 0x5c)
             builder.appendLiteral("\\\\");
         else
index 3887715..5e98d3a 100644 (file)
@@ -79,7 +79,7 @@ static void serializeCharacter(UChar32 c, StringBuilder& appendTo)
 static void serializeCharacterAsCodePoint(UChar32 c, StringBuilder& appendTo)
 {
     appendTo.append('\\');
-    appendUnsignedAsHex(c, appendTo, Lowercase);
+    appendTo.append(hex(c, Lowercase));
     appendTo.append(' ');
 }
 
index 9e60c83..e820907 100644 (file)
@@ -434,9 +434,9 @@ void CSSParserToken::serialize(StringBuilder& builder) const
         break;
     case UnicodeRangeToken:
         builder.appendLiteral("U+");
-        appendUnsignedAsHex(unicodeRangeStart(), builder);
+        builder.append(hex(unicodeRangeStart()));
         builder.append('-');
-        appendUnsignedAsHex(unicodeRangeEnd(), builder);
+        builder.append(hex(unicodeRangeEnd()));
         break;
     case StringToken:
         serializeString(value().toString(), builder);
index ea2d348..8805b6c 100644 (file)
@@ -314,15 +314,8 @@ String Color::serialized() const
     if (isExtended())
         return asExtended().cssText();
 
-    if (isOpaque()) {
-        StringBuilder builder;
-        builder.reserveCapacity(7);
-        builder.append('#');
-        appendByteAsHex(red(), builder, Lowercase);
-        appendByteAsHex(green(), builder, Lowercase);
-        appendByteAsHex(blue(), builder, Lowercase);
-        return builder.toString();
-    }
+    if (isOpaque())
+        return makeString('#', hex(red(), 2, Lowercase), hex(green(), 2, Lowercase), hex(blue(), 2, Lowercase));
 
     return cssText();
 }
index 980078b..871e450 100644 (file)
@@ -2349,14 +2349,14 @@ void MediaPlayerPrivateGStreamer::processMpegTsSection(GstMpegtsSection* section
                 // following the "ES_info_length" field. The text track in-band metadata track dispatch type must be
                 // set to the concatenation of the stream type byte and the zero or more descriptor bytes bytes,
                 // expressed in hexadecimal using uppercase ASCII hex digits.
-                String inbandMetadataTrackDispatchType;
-                appendUnsignedAsHexFixedSize(stream->stream_type, inbandMetadataTrackDispatchType, 2);
+                StringBuilder inbandMetadataTrackDispatchType;
+                inbandMetadataTrackDispatchType.append(hex(stream->stream_type, 2));
                 for (unsigned j = 0; j < stream->descriptors->len; ++j) {
                     const GstMpegtsDescriptor* descriptor = static_cast<const GstMpegtsDescriptor*>(g_ptr_array_index(stream->descriptors, j));
                     for (unsigned k = 0; k < descriptor->length; ++k)
-                        appendByteAsHex(descriptor->data[k], inbandMetadataTrackDispatchType);
+                        inbandMetadataTrackDispatchType.append(hex(descriptor->data[k], 2));
                 }
-                track->setInBandMetadataTrackDispatchType(inbandMetadataTrackDispatchType);
+                track->setInBandMetadataTrackDispatchType(inbandMetadataTrackDispatchType.toString());
 
                 m_metadataTracks.add(pid, track);
                 m_player->addTextTrack(*track);
index b6dde01..1bf061a 100644 (file)
@@ -985,10 +985,7 @@ static String generateHashedName(const String& name)
     if (name.isEmpty())
         return name;
     uint64_t number = nameHashForShader(name.utf8().data(), name.length());
-    StringBuilder builder;
-    builder.appendLiteral("webgl_");
-    appendUnsignedAsHex(number, builder, Lowercase);
-    return builder.toString();
+    return makeString("webgl_", hex(number, Lowercase));
 }
 
 Optional<String> GraphicsContext3D::mappedSymbolInShaderSourceMap(Platform3DObject shader, ANGLEShaderSymbolType symbolType, const String& name)
index 9a3c4b5..56b9a5c 100644 (file)
@@ -98,7 +98,9 @@ static void appendFormURLEncoded(Vector<char>& buffer, const uint8_t* string, si
             append(buffer, "%0D%0A"); // FIXME: Unclear exactly where this rule about normalizing line endings to CRLF comes from.
         else if (character != '\r') {
             append(buffer, '%');
-            appendByteAsHex(character, buffer);
+            auto hexBuffer = hex(character, 2);
+            append(buffer, hexBuffer.characters()[0]);
+            append(buffer, hexBuffer.characters()[1]);
         }
     }
 }
index 5518e35..2461093 100644 (file)
@@ -218,8 +218,10 @@ void CurlCacheEntry::generateBaseFilename(const CString& url)
     md5.checksum(sum);
     uint8_t* rawdata = sum.data();
 
+    StringBuilder baseNameBuilder;
     for (size_t i = 0; i < MD5::hashSize; i++)
-        appendByteAsHex(rawdata[i], m_basename, Lowercase);
+        baseNameBuilder.append(hex(rawdata[i], Lowercase));
+    m_basename = baseNameBuilder.toString();
 }
 
 bool CurlCacheEntry::loadFileToBuffer(const String& filepath, Vector<char>& buffer)
index ebe3bb4..bb43c1a 100644 (file)
@@ -160,7 +160,7 @@ String quoteAndEscapeNonPrintables(StringView s)
                 result.append(c);
             else {
                 result.appendLiteral("\\x{");
-                appendUnsignedAsHex(c, result);
+                result.append(hex(c));
                 result.append('}');
             }
         }
index 0429b1a..f93c5b9 100644 (file)
@@ -1,3 +1,16 @@
+2020-01-05  Sam Weinig  <weinig@apple.com>
+
+        Further simplify StringBuilder usage by standardizing hex formating to a single hex() function
+        https://bugs.webkit.org/show_bug.cgi?id=205759
+
+        Reviewed by Dean Jackson.
+
+        * UIProcess/DeviceIdHashSaltStorage.cpp:
+        (WebKit::DeviceIdHashSaltStorage::completeDeviceIdHashSaltForOriginCall):
+        * UIProcess/WebBackForwardList.cpp:
+        (WebKit::WebBackForwardList::loggingString):
+        Replace appendUnsignedAsHex() with append(hex()).
+
 2020-01-05  Simon Fraser  <simon.fraser@apple.com>
 
         DumpRenderTree doesn't always call updateRendering() when a test completes
index 6aa247b..cc04e55 100644 (file)
@@ -215,7 +215,7 @@ void DeviceIdHashSaltStorage::completeDeviceIdHashSaltForOriginCall(SecurityOrig
         StringBuilder builder;
         builder.reserveCapacity(hashSaltSize);
         for (unsigned i = 0; i < randomDataSize; i++)
-            appendUnsignedAsHex(randomData[i], builder);
+            builder.append(hex(randomData[i]));
 
         String deviceIdHashSalt = builder.toString();
 
index 6aecd82..37f4cbd 100644 (file)
@@ -484,7 +484,7 @@ const char* WebBackForwardList::loggingString()
     StringBuilder builder;
 
     builder.appendLiteral("WebBackForwardList 0x");
-    appendUnsignedAsHex(reinterpret_cast<uintptr_t>(this), builder);
+    builder.append(hex(reinterpret_cast<uintptr_t>(this)));
     builder.appendLiteral(" - ");
     builder.appendNumber(m_entries.size());
     builder.appendLiteral(" entries, has current index ");
index f6053c7..7c579dd 100644 (file)
@@ -1,3 +1,15 @@
+2020-01-05  Sam Weinig  <weinig@apple.com>
+
+        Further simplify StringBuilder usage by standardizing hex formating to a single hex() function
+        https://bugs.webkit.org/show_bug.cgi?id=205759
+
+        Reviewed by Dean Jackson.
+
+        * TestWebKitAPI/CMakeLists.txt:
+        * TestWebKitAPI/TestWebKitAPI.xcodeproj/project.pbxproj:
+        * TestWebKitAPI/Tests/WTF/HexNumber.cpp: Added.
+        Add testing for hex formatting of integers.
+
 2020-01-05  Simon Fraser  <simon.fraser@apple.com>
 
         DumpRenderTree doesn't always call updateRendering() when a test completes
index c917036..a57c73d 100644 (file)
@@ -45,6 +45,7 @@ set(TestWTF_SOURCES
     Tests/WTF/HashMap.cpp
     Tests/WTF/HashSet.cpp
     Tests/WTF/Hasher.cpp
+    Tests/WTF/HexNumber.cpp
     Tests/WTF/IntegerToStringConversion.cpp
     Tests/WTF/IteratorRange.cpp
     Tests/WTF/JSONValue.cpp
index fedfcf2..68d0060 100644 (file)
                7C882E091C80C630006BF731 /* UserContentWorldPlugIn.mm in Sources */ = {isa = PBXBuildFile; fileRef = 7C882E041C80C624006BF731 /* UserContentWorldPlugIn.mm */; };
                7C882E0A1C80C764006BF731 /* UserContentWorld.mm in Sources */ = {isa = PBXBuildFile; fileRef = 7C882E031C80C624006BF731 /* UserContentWorld.mm */; };
                7C89D2AC1A69B80D003A5FDE /* WKPageConfiguration.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7C89D2AA1A69B80D003A5FDE /* WKPageConfiguration.cpp */; };
+               7C8BFF7123C0107A00C009B3 /* HexNumber.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7C8BFF7023C0106700C009B3 /* HexNumber.cpp */; };
                7C9ED98B17A19F4B00E4DC33 /* attributedStringStrikethrough.html in Copy Resources */ = {isa = PBXBuildFile; fileRef = 7C9ED98A17A19D0600E4DC33 /* attributedStringStrikethrough.html */; };
                7CB184C61AA3F2100066EDFD /* ContentExtensions.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7CB184C41AA3F2100066EDFD /* ContentExtensions.cpp */; };
                7CBD5A2322DE42A6004A9E32 /* WTFStringUtilities.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7CBD5A2222DE42A6004A9E32 /* WTFStringUtilities.cpp */; };
                7C882E041C80C624006BF731 /* UserContentWorldPlugIn.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = UserContentWorldPlugIn.mm; sourceTree = "<group>"; };
                7C882E051C80C624006BF731 /* UserContentWorldProtocol.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = UserContentWorldProtocol.h; sourceTree = "<group>"; };
                7C89D2AA1A69B80D003A5FDE /* WKPageConfiguration.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = WKPageConfiguration.cpp; sourceTree = "<group>"; };
+               7C8BFF7023C0106700C009B3 /* HexNumber.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = HexNumber.cpp; sourceTree = "<group>"; };
                7C8DDAA91735DE1D00EA5AC0 /* CloseThenTerminate.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = CloseThenTerminate.cpp; sourceTree = "<group>"; };
                7C9ED98A17A19D0600E4DC33 /* attributedStringStrikethrough.html */ = {isa = PBXFileReference; lastKnownFileType = text.html; path = attributedStringStrikethrough.html; sourceTree = "<group>"; };
                7CB184C41AA3F2100066EDFD /* ContentExtensions.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ContentExtensions.cpp; sourceTree = "<group>"; };
                                933D631B1FCB76180032ECD6 /* Hasher.cpp */,
                                0BCD833414857CE400EA2003 /* HashMap.cpp */,
                                26B2DFF815BDE599004F691D /* HashSet.cpp */,
+                               7C8BFF7023C0106700C009B3 /* HexNumber.cpp */,
                                266FAFD215E5775200F61D5B /* IntegerToStringConversion.cpp */,
                                7CEB62A92236086C0069CBB0 /* IteratorRange.cpp */,
                                7A0509401FB9F04400B33FB8 /* JSONValue.cpp */,
                                933D631D1FCB76200032ECD6 /* Hasher.cpp in Sources */,
                                7C83DED21D0A590C00FEBCF3 /* HashMap.cpp in Sources */,
                                7C83DED41D0A590C00FEBCF3 /* HashSet.cpp in Sources */,
+                               7C8BFF7123C0107A00C009B3 /* HexNumber.cpp in Sources */,
                                7C83DEE01D0A590C00FEBCF3 /* IntegerToStringConversion.cpp in Sources */,
                                53FCDE6B229EFFB900598ECF /* IsoHeap.cpp in Sources */,
                                7CEB62AB223609DE0069CBB0 /* IteratorRange.cpp in Sources */,
diff --git a/Tools/TestWebKitAPI/Tests/WTF/HexNumber.cpp b/Tools/TestWebKitAPI/Tests/WTF/HexNumber.cpp
new file mode 100644 (file)
index 0000000..9e6dc9d
--- /dev/null
@@ -0,0 +1,110 @@
+/*
+ * Copyright (C) 2020 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "WTFStringUtilities.h"
+
+#include <wtf/HexNumber.h>
+
+namespace TestWebKitAPI {
+
+// Not using builder.toString() or builder.toStringPreserveCapacity() because they all
+// change internal state of builder.
+#define expectBuilderContent(expected, builder) \
+    { \
+        if (builder.is8Bit()) \
+            EXPECT_EQ(String(expected), String(builder.characters8(), builder.length())); \
+        else \
+            EXPECT_EQ(String(expected), String(builder.characters16(), builder.length())); \
+    } \
+
+TEST(WTF, HexNumber)
+{
+    uint32_t integer = 10;
+    uint32_t largeInteger = 64206;
+    unsigned char byte = 128;
+
+    {
+        StringBuilder builder;
+        builder.append(hex(integer));
+        expectBuilderContent("A", builder);
+    }
+
+    {
+        StringBuilder builder;
+        builder.append(hex(integer, Lowercase));
+        expectBuilderContent("a", builder);
+    }
+
+    {
+        StringBuilder builder;
+        builder.append(hex(integer, 1, Lowercase));
+        expectBuilderContent("a", builder);
+    }
+
+    {
+        StringBuilder builder;
+        builder.append(hex(integer, 2, Lowercase));
+        expectBuilderContent("0a", builder);
+    }
+
+    {
+        StringBuilder builder;
+        builder.append(hex(integer, 3, Lowercase));
+        expectBuilderContent("00a", builder);
+    }
+
+    {
+        StringBuilder builder;
+        builder.append(hex(integer, 4, Lowercase));
+        expectBuilderContent("000a", builder);
+    }
+
+    {
+        StringBuilder builder;
+        builder.append(hex(largeInteger));
+        expectBuilderContent("FACE", builder);
+    }
+
+    {
+        StringBuilder builder;
+        builder.append(hex(largeInteger, 2));
+        expectBuilderContent("FACE", builder);
+    }
+
+    {
+        StringBuilder builder;
+        builder.append(hex(byte));
+        expectBuilderContent("80", builder);
+    }
+
+    {
+        StringBuilder builder;
+        builder.append(hex(static_cast<unsigned char>(integer), 2));
+        expectBuilderContent("0A", builder);
+    }
+}
+
+} // namespace