haikuwebkit/Source/WTF/wtf/SaturatedArithmetic.h

126 lines
5.2 KiB
C
Raw Permalink Normal View History

Add saturation arithmetic support to FractionalLayoutUnit https://bugs.webkit.org/show_bug.cgi?id=94364 Reviewed by Benjamin Poulain. Source/WebCore: Add experimental saturation arithmetic support to FractionalLayoutUnit, guarded by a flag. The idea here is to saturate (or clamp) rather than overflow when computing positions and sizes. No new tests for WebCore, not enabled by default. * platform/FractionalLayoutUnit.h: (WebCore::FractionalLayoutUnit::intMinForLayoutUnit): Use INT_MIN instead of -INT_MAX to compute minimum value as the two are not the same. (WebCore::FractionalLayoutUnit::FractionalLayoutUnit): (WebCore::FractionalLayoutUnit::fromFloatCeil): (WebCore::FractionalLayoutUnit::fromFloatFloor): (WebCore::FractionalLayoutUnit::fromFloatRound): (WebCore::FractionalLayoutUnit::setValue): Add range checks. (WebCore::operator*): (WebCore::operator+): (WebCore::operator-): (WebCore::operator+=): (WebCore::operator-=): Use the saturatedAddition and saturatedSubtraction functions, which have been optimized to reduce branching, instead of range checks for the most common operators. Source/WTF: Add support functions for saturated addition and subtraction. Test: TestWebKitAPI/Tests/WTF/SaturatedArithmeticOperations.cpp * GNUmakefile.list.am: * WTF.gypi: * WTF.pro: * WTF.vcproj/WTF.vcproj: * WTF.xcodeproj/project.pbxproj: * WTF/wtf/CMakeLists.txt: Add SaturatedArithmetic.h to build files. * wtf/SaturatedArithmetic.h: Added. (saturatedAddition): (saturatedSubtraction): Support functions for saturated addition/subtraction. Compares the signed bit of the values instead of using range checks to reduce branching. * wtf/Platform.h: Add ENABLE_SATURATED_LAYOUT_ARITHMETIC flag. Tools: Add test for new saturatedArithmetic functions. * TestWebKitAPI/CMakeLists.txt: * TestWebKitAPI/GNUmakefile.am: * TestWebKitAPI/TestWebKitAPI.gypi: * TestWebKitAPI/TestWebKitAPI.xcodeproj/project.pbxproj: * TestWebKitAPI/Tests/WTF/SaturatedArithmeticOperations.cpp: Added. (TestWebKitAPI): (TestWebKitAPI::TEST): * TestWebKitAPI/win/TestWebKitAPI.vcproj: Canonical link: https://commits.webkit.org/112729@main git-svn-id: https://svn.webkit.org/repository/webkit/trunk@126509 268f45cc-cd09-0410-ab3c-d52691b4dbfc
2012-08-24 00:14:00 +00:00
/*
* Copyright (c) 2012, Google Inc. All rights reserved.
Move CFStringRef and NSString support from StringBuilder into StringConcatenateCF https://bugs.webkit.org/show_bug.cgi?id=225839 Reviewed by Sam Weinig. Source/JavaScriptCore: * inspector/ConsoleMessage.cpp: (Inspector::ConsoleMessage::ConsoleMessage): Use StringBuilder::clear instead of StringBuilder::resize; no advantage to the latter after calling StringBuilder::toString. * runtime/JSONObject.cpp: (JSC::Stringifier::Holder::appendNextProperty): Update for name change of StringBuilder::resize to StringBuilder::shrink. * runtime/TypeSet.cpp: (JSC::StructureShape::stringRepresentation): Ditto. Source/WebCore: * Modules/airplay/WebMediaSessionManager.cpp: (WebCore::mediaProducerStateString): Use StringBuilder exclusively instead of mixing it with makeString. Also updated for StringBuilder::shrink name. * html/HTMLTextFormControlElement.cpp: (WebCore::stripTrailingNewline): Updated for StringBuilder::shrink name. * page/CaptionUserPreferencesMediaAF.cpp: (WebCore::CaptionUserPreferencesMediaAF::captionsTextColor const): Tweaked coding style a bit. (WebCore::appendCSS): Use variadic StringBuilder::append instead of many separate calls. (WebCore::CaptionUserPreferencesMediaAF::captionsDefaultFontCSS const): Tweaked coding style a bit, and use variadic StrinBuilder::append calls to reduce the number of calls and streamline the code. (WebCore::CaptionUserPreferencesMediaAF::captionsStyleSheetOverride const): Ditto. Also removed unnecessary checks that strings are empty before appending. * page/scrolling/ScrollingCoordinator.cpp: (WebCore::ScrollingCoordinator::synchronousScrollingReasonsAsText): Updated for StringBuilder::shrink name. * platform/LayoutUnit.h: Updated for saturatedSum/Difference names. * platform/network/cocoa/NetworkStorageSessionCocoa.mm: (WebCore::NetworkStorageSession::cookiesForSession const): Tweaked codin style a bit, and use variadic StrinBuilder::append calls to reduce the number of calls and streamline the code. * rendering/RenderCounter.cpp: (WebCore::planCounter): Updated for saturatedSum name. * style/StyleBuilderCustom.h: (WebCore::Style::BuilderCustom::applyValueCounter): Ditto. * svg/SVGPathStringBuilder.cpp: (WebCore::SVGPathStringBuilder::result): Updated for StringBuilder::shrink name. * testing/Internals.cpp: (WebCore::Internals::pageMediaState): Ditto. * xml/XSLTProcessorLibxslt.cpp: (WebCore::saveResultToString): Ditto. Source/WebKit: * UIProcess/WebsiteData/Cocoa/WebsiteDataStoreCocoa.mm: (WebKit::WebsiteDataStore::platformSetNetworkParameters): Use makeString instead of StringBuilder. Source/WTF: The new header makes CFStringRef and NSString work with string concatenation, which means it now works with the variadic StringBuilder::append and makeString, and still works with the single-argument StringBuilder::append. More efficient that the old version because it does not allocate a temporary WTF::String for the 16-bit character path. Also made many other small improvements to the StringBuilder implementation. * WTF.xcodeproj/project.pbxproj: Added StringConcatenateCF.h. * wtf/CheckedArithmetic.h: Removed ConditionalCrashOnOverflow, which was only here for use by StringBuilder, which does not use CheckedArithmetic any more. * wtf/PlatformFTW.cmake: Added StringConcatenateCF.h.. * wtf/PlatformMac.cmake: Ditto. * wtf/PlatformWin.cmake: Ditto. * wtf/SaturatedArithmetic.h: Moved the contents of this file inside the WTF namespace. (WTF::signedAddInt32Overflows): Renamed this function. The type here is important, and we are not doing anything to prevent type conversion or create ambiguity, so it's good to be explicit in the function name. (WTF::saturatedSum<int32_t>): Renamed this from saturatedAddition for clarity. The function returns a sum, so that's a better name than calling it "addition". Also, it's clearer to be explicit about the return type. (WTF::signedSubtractInt32Overflows): Renamed. Same reason as above. (WTF::saturatedDifference<int32_t>): Ditto. (WTF::saturatedSum): Added. Does unsigned integer saturated addition. This one can be written in a portable manner and still get really efficient code on at least Intel and ARM64. (WTF::saturatedSum): Added a function template that lets callers pass larger number of arguments to saturatedSum, rather than exactly two. * wtf/text/StringBuilder.cpp: (WTF::expandedCapacity): Renamed to use the term capacity rather than length for the new required capacity. (WTF::StringBuilder::didOverflow): Implement the new approach to overflow, meaning we need to write the CRASH() here explicitly and in the non-crashing mode, set m_length. (WTF::StringBuilder::reifyString const): Changed the overflow check into a RELEASE_ASSERT. This is now responsible for doing the check that callers were doing earlier, so we want it in production builds. Also simplified this since our m_length member is a simple integer now, and removed the unused m_isReified. (WTF::StringBuilder::shrink): Renamed this to shrink to match the Vector::shrink function, since this has never supported making the builder larger. Removed unnecessary overflow checks, since shrinking cannot cause overflow. (WTF::StringBuilder::allocateBuffer): Replaced two separate functions with a single simpler function template. Removed extra overflow checks because the StringImpl::tryCreateUninitialized function already does the only overflow check we need. Also move to StringImpl::copyCharacters for copying characters rather than using std::memcpy directly. Removed code to set m_is8Bit and m_bufferCharacters. (WTF::StringBuilder::reallocateBuffer): Replaced two separate functions with a function template and a cover that calls the appropriate instance of the template for places where we aren't already in character-type-specific code paths. This version now supports allocating a buffer for the first time in cases where we have m_string and not m_buffer, which used to be handled at the higher level. Removed code to set m_bufferCharacters. (WTF::StringBuilder::reserveCapacity): Rewrote for simplicity. By relying on the overflow checking inside reallocateBuffer and allocateBuffer we no longer need checking of the passed-in value at this level. (WTF::StringBuilder::extendBufferForAppending): Removed the version of this that takes additionalLength since it's potentially confusing to have a family of functions that have the same name and take the same type of argument, but interpret it subtly differently. Streamlined the code using std::exchange. This function now also includes the logic from the function named extendBufferForAppendingWithoutOverflowCheck, which was subtly misnamed since that was not the only semantic difference. Also removed the ALWAYS_INLINE because the compiler will do the right thing without such heavy handed advice. (WTF::StringBuilder::extendBufferForAppendingSlowCase): Streamlined this by using std::exchange and removed additional overflow checks at this level since reallocateBuffer already does them. Also added a check for the case where the new total length is 0, which would not be handled correctly and efficiently by reallocateBuffer. (WTF::StringBuilder::extendBufferForAppendingLChar): Renamed this from extendBufferForAppending8, since it's now identical to calling extendBufferForAppending<LChar>, except for inlining and linkage. (WTF::StringBuilder::extendBufferForAppendingWithUpconvert): Renamed this from extendBufferForAppending16. It is different from the other extendBuffer functions because is supports upconverting from LChar to UChar. Like the others it relies on allocateBuffer for the overflow checking. (WTF::StringBuilder::appendCharacters): Removed an unnecessary assertion that the characters pointer is non-null; that will fail in an obvious way without an assertion. Simplified the logic and removed some invariant assertions that don't help us much. Changed overflow checking by using saturatedSum to compute the new length. In overflow cases, the new sum will be larger than the maximum string length, but will fit in an unsigned, so we can pass it down to lower levels and let functions like reallocateBuffer do the actual overflow checking. Also use StringImpl::copyCharacters. (WTF::StringBuilder::append): Removed the CFStringRef overload. (WTF::StringBuilder::shouldShrinkToFit const): Rename this from canShrink. Simplify the function a bit and remove the vague FIXME that says "this should be tuned". That may be so, but the FIXME is not really driving us to action. (WTF::StringBuilder::shrinkToFit): Simplify by using the new reallocateBuffer and std::exchange. Removed unneeded assertion about overflow that doesn't help us maintain the invariant. (WTF::StringBuilder::isAllASCII const): Was tempted to remove this function, but for now just made it use the StringView version for brevity. * wtf/text/StringBuilder.h: Removed many unneeded includes, and notably included SaturatedArithmetic.h instead of CheckedArithmetic.h because we now use the former instead of the latter. Changed the overflow checking implementation to work more simply based on saturated addition rather than Checked. This allowed us to get rid of dependency on our own unique mode for Checked, called ConditionalCrashOnOverflow. Removed a comment about making a templatized version of StringBuilder. We can do it if we like, but does not seem urgent. Moved fucntion bodies out of the class definition so it's easier to see what's going on in the class. Since m_length is now an ordinary integer, the check for overflowed simply checks to see if the length is larger than the maximum string length. When we encounter overflow that is not about length computation, we set the length to the maximum integer to indicate the failure. Deleted the append overloads for CFStringRef and NSString. Removed m_bufferCharacters, m_is8Bit, and m_isReified. (WTF::StringBuilder::StringBuilder): Simplified the constructor since we only have to initialize the m_shouldCrashOnOverflow member. (WTF::StringBuilder::clear): Fixed a mistake where this was not resetting the m_isReified flag. (WTF::StringBuilder::swap): Updated for changes in the data members. (WTF::StringBuilder::operator StringView const): Moved out of line. Made sure to call the length() function so we crash if this is called after overflow. (WTF::StringBuilder::append): Remove some of the unnecessary checks and special cases in the various versions of append. Most of the checking is done inside appendCharacters, with only a few exceptions. (WTF::StringBuilder::appendSubstring): Moved out of the class definition without making significant changes. (WTF::StringBuilder::appendCharacter): Ditto. (WTF::StringBuilder::toString): Greatly simplified this function by relying on overflow checking in the reifyString function instead of doing it here and removing unneeded invariant assertions. (WTF::StringBuilder::toStringPreserveCapacity const): Ditto. (WTF::StringBuilder::toAtomString const): Rewrote this to streamline, removing explicit overflow checks. (WTF::StringBuilder::length const): Moved out of the class definition without making significant changes. (WTF::StringBuilder::capacity const): Ditto. (WTF::StringBuilder::operator[] const): Ditto. (WTF::StringBuilder::characters const): Implemented this operation in the function template. Now rather than having this call the characters8 and characters16 functions, they can call it. (WTF::StringBuilder::getBufferCharacters<LChar>): Deleted. (WTF::StringBuilder::getBufferCharacters<UChar>): Deleted. (WTF::StringBuilder::appendFromAdapters): Use saturatedSum to compute the required length, which allows the extendBuffer functions to do overflow checking without having to take special checked integer types for arguments. (WTF::StringBuilder::equal): Implement using StringView. * wtf/text/StringBuilderJSON.cpp: (WTF::StringBuilder::appendQuotedJSONString): Simplified the checked arithmetic for computing the required capacity. Updated since we removed m_bufferCharacters and changed the type of m_length. * wtf/text/cf/StringConcatenateCF.h: Added. Specializes StringTypeAdapter for both CFStringRef and NSString *. If CFStringGetCStringPtr works for Latin-1, then does the 8-bit code path, otherwise the 16-bit. * wtf/text/cocoa/TextStreamCocoa.mm: Include StringConcatenateCF.h, since it's now needed to use CFStringRef with StringBuilder. Tools: * TestWebKitAPI/Tests/WTF/SaturatedArithmeticOperations.cpp: Updated tests for changes to SaturatedArithmetic.h. * TestWebKitAPI/Tests/WTF/StringBuilder.cpp: Updated tests for changes to StringBuilder. * TestWebKitAPI/Tests/WebKit/GetUserMedia.mm: (TestWebKitAPI::wkMediaCaptureStateString): Ditto. * WebKitTestRunner/InjectedBundle/InjectedBundlePage.cpp: Added include of StringConcatenateCF.h. Added StringTypeAdapter for WKStringRef. (WTR::styleDecToStr): Use ASCIILiteral instead of StringBuilder. (WTR::string): Removed unneeded toWTFString since the WKStringRef StringTypeAdapter takes care of it. (WTR::string): Renamed from frameToStr. Use makeString. (WTR::dumpResourceURL): Use append instead of appendLiteral. (WTR::dumpFrameDescriptionSuitableForTestResult): Deleted. (WTR::dumpLoadEvent): Use makeString. (WTR::string): Renamed from a longer name. Return a String instead of building in a StringBuilder. Use makeString. (WTR::string): Ditto. (WTR::dumpErrorDescriptionSuitableForTestResult): Removed unneeded toWTFString. (WTR::dumpFrameScrollPosition): Ditto. (WTR::dumpDescendantFramesText): Ditto. (WTR::InjectedBundlePage::dumpDOMAsWebArchive): Removed an unneeded local variable. (WTR::InjectedBundlePage::dump): Removed unneeded toWTFString. (WTR::InjectedBundlePage::didReceiveTitleForFrame): Ditto. (WTR::InjectedBundlePage::didFinishDocumentLoadForFrame): Updated for functon name change. (WTR::InjectedBundlePage::willSendRequestForFrame): Ditto. Also use variadic append. Also use makeString. (WTR::InjectedBundlePage::didReceiveResponseForResource): Ditto. (WTR::InjectedBundlePage::didFinishLoadForResource): Ditto. (WTR::InjectedBundlePage::didFailLoadForResource): Ditto. (WTR::InjectedBundlePage::decidePolicyForNavigationAction): Ditto. (WTR::InjectedBundlePage::decidePolicyForResponse): Ditto. (WTR::InjectedBundlePage::willAddMessageToConsole): Ditto. (WTR::InjectedBundlePage::willSetStatusbarText): Ditto. (WTR::InjectedBundlePage::willRunJavaScriptPrompt): Ditto. (WTR::InjectedBundlePage::didExceedDatabaseQuota): Ditto. (WTR::InjectedBundlePage::shouldInsertNode): Ditto. (WTR::InjectedBundlePage::shouldInsertText): Ditto. (WTR::InjectedBundlePage::shouldDeleteRange): Ditto. (WTR::InjectedBundlePage::shouldChangeSelectedRange): Ditto. (WTR::InjectedBundlePage::shouldApplyStyle): Ditto. (WTR::InjectedBundlePage::didBeginEditing): Ditto. (WTR::InjectedBundlePage::didEndEditing): Ditto. (WTR::InjectedBundlePage::didChange): Ditto. (WTR::InjectedBundlePage::didChangeSelection): Ditto. (WTR::InjectedBundlePage::dumpHistory): Ditto. Canonical link: https://commits.webkit.org/237916@main git-svn-id: https://svn.webkit.org/repository/webkit/trunk@277744 268f45cc-cd09-0410-ab3c-d52691b4dbfc
2021-05-19 19:37:21 +00:00
* Copyright (C) 2014-2021 Apple Inc. All rights reserved.
Add saturation arithmetic support to FractionalLayoutUnit https://bugs.webkit.org/show_bug.cgi?id=94364 Reviewed by Benjamin Poulain. Source/WebCore: Add experimental saturation arithmetic support to FractionalLayoutUnit, guarded by a flag. The idea here is to saturate (or clamp) rather than overflow when computing positions and sizes. No new tests for WebCore, not enabled by default. * platform/FractionalLayoutUnit.h: (WebCore::FractionalLayoutUnit::intMinForLayoutUnit): Use INT_MIN instead of -INT_MAX to compute minimum value as the two are not the same. (WebCore::FractionalLayoutUnit::FractionalLayoutUnit): (WebCore::FractionalLayoutUnit::fromFloatCeil): (WebCore::FractionalLayoutUnit::fromFloatFloor): (WebCore::FractionalLayoutUnit::fromFloatRound): (WebCore::FractionalLayoutUnit::setValue): Add range checks. (WebCore::operator*): (WebCore::operator+): (WebCore::operator-): (WebCore::operator+=): (WebCore::operator-=): Use the saturatedAddition and saturatedSubtraction functions, which have been optimized to reduce branching, instead of range checks for the most common operators. Source/WTF: Add support functions for saturated addition and subtraction. Test: TestWebKitAPI/Tests/WTF/SaturatedArithmeticOperations.cpp * GNUmakefile.list.am: * WTF.gypi: * WTF.pro: * WTF.vcproj/WTF.vcproj: * WTF.xcodeproj/project.pbxproj: * WTF/wtf/CMakeLists.txt: Add SaturatedArithmetic.h to build files. * wtf/SaturatedArithmetic.h: Added. (saturatedAddition): (saturatedSubtraction): Support functions for saturated addition/subtraction. Compares the signed bit of the values instead of using range checks to reduce branching. * wtf/Platform.h: Add ENABLE_SATURATED_LAYOUT_ARITHMETIC flag. Tools: Add test for new saturatedArithmetic functions. * TestWebKitAPI/CMakeLists.txt: * TestWebKitAPI/GNUmakefile.am: * TestWebKitAPI/TestWebKitAPI.gypi: * TestWebKitAPI/TestWebKitAPI.xcodeproj/project.pbxproj: * TestWebKitAPI/Tests/WTF/SaturatedArithmeticOperations.cpp: Added. (TestWebKitAPI): (TestWebKitAPI::TEST): * TestWebKitAPI/win/TestWebKitAPI.vcproj: Canonical link: https://commits.webkit.org/112729@main git-svn-id: https://svn.webkit.org/repository/webkit/trunk@126509 268f45cc-cd09-0410-ab3c-d52691b4dbfc
2012-08-24 00:14:00 +00:00
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * 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.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND 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 THE COPYRIGHT
* OWNER OR 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.
*/
Use pragma once in WTF https://bugs.webkit.org/show_bug.cgi?id=190527 Reviewed by Chris Dumez. Source/WTF: We also need to consistently include wtf headers from within wtf so we can build wtf without symbol redefinition errors from including the copy in Source and the copy in the build directory. * wtf/ASCIICType.h: * wtf/Assertions.cpp: * wtf/Assertions.h: * wtf/Atomics.h: * wtf/AutomaticThread.cpp: * wtf/AutomaticThread.h: * wtf/BackwardsGraph.h: * wtf/Bag.h: * wtf/BagToHashMap.h: * wtf/BitVector.cpp: * wtf/BitVector.h: * wtf/Bitmap.h: * wtf/BloomFilter.h: * wtf/Box.h: * wtf/BubbleSort.h: * wtf/BumpPointerAllocator.h: * wtf/ByteOrder.h: * wtf/CPUTime.cpp: * wtf/CallbackAggregator.h: * wtf/CheckedArithmetic.h: * wtf/CheckedBoolean.h: * wtf/ClockType.cpp: * wtf/ClockType.h: * wtf/CommaPrinter.h: * wtf/CompilationThread.cpp: * wtf/CompilationThread.h: * wtf/Compiler.h: * wtf/ConcurrentPtrHashSet.cpp: * wtf/ConcurrentVector.h: * wtf/Condition.h: * wtf/CountingLock.cpp: * wtf/CrossThreadTaskHandler.cpp: * wtf/CryptographicUtilities.cpp: * wtf/CryptographicUtilities.h: * wtf/CryptographicallyRandomNumber.cpp: * wtf/CryptographicallyRandomNumber.h: * wtf/CurrentTime.cpp: * wtf/DataLog.cpp: * wtf/DataLog.h: * wtf/DateMath.cpp: * wtf/DateMath.h: * wtf/DecimalNumber.cpp: * wtf/DecimalNumber.h: * wtf/Deque.h: * wtf/DisallowCType.h: * wtf/Dominators.h: * wtf/DoublyLinkedList.h: * wtf/FastBitVector.cpp: * wtf/FastMalloc.cpp: * wtf/FastMalloc.h: * wtf/FeatureDefines.h: * wtf/FilePrintStream.cpp: * wtf/FilePrintStream.h: * wtf/FlipBytes.h: * wtf/FunctionDispatcher.cpp: * wtf/FunctionDispatcher.h: * wtf/GetPtr.h: * wtf/Gigacage.cpp: * wtf/GlobalVersion.cpp: * wtf/GraphNodeWorklist.h: * wtf/GregorianDateTime.cpp: * wtf/GregorianDateTime.h: * wtf/HashFunctions.h: * wtf/HashMap.h: * wtf/HashMethod.h: * wtf/HashSet.h: * wtf/HashTable.cpp: * wtf/HashTraits.h: * wtf/Indenter.h: * wtf/IndexSparseSet.h: * wtf/InlineASM.h: * wtf/Insertion.h: * wtf/IteratorAdaptors.h: * wtf/IteratorRange.h: * wtf/JSONValues.cpp: * wtf/JSValueMalloc.cpp: * wtf/LEBDecoder.h: * wtf/Language.cpp: * wtf/ListDump.h: * wtf/Lock.cpp: * wtf/Lock.h: * wtf/LockAlgorithm.h: * wtf/LockedPrintStream.cpp: * wtf/Locker.h: * wtf/MD5.cpp: * wtf/MD5.h: * wtf/MainThread.cpp: * wtf/MainThread.h: * wtf/MallocPtr.h: * wtf/MathExtras.h: * wtf/MediaTime.cpp: * wtf/MediaTime.h: * wtf/MemoryPressureHandler.cpp: * wtf/MessageQueue.h: * wtf/MetaAllocator.cpp: * wtf/MetaAllocator.h: * wtf/MetaAllocatorHandle.h: * wtf/MonotonicTime.cpp: * wtf/MonotonicTime.h: * wtf/NakedPtr.h: * wtf/NoLock.h: * wtf/NoTailCalls.h: * wtf/Noncopyable.h: * wtf/NumberOfCores.cpp: * wtf/NumberOfCores.h: * wtf/OSAllocator.h: * wtf/OSAllocatorPosix.cpp: * wtf/OSRandomSource.cpp: * wtf/OSRandomSource.h: * wtf/ObjcRuntimeExtras.h: * wtf/OrderMaker.h: * wtf/PackedIntVector.h: * wtf/PageAllocation.h: * wtf/PageBlock.cpp: * wtf/PageBlock.h: * wtf/PageReservation.h: * wtf/ParallelHelperPool.cpp: * wtf/ParallelHelperPool.h: * wtf/ParallelJobs.h: * wtf/ParallelJobsLibdispatch.h: * wtf/ParallelVectorIterator.h: * wtf/ParkingLot.cpp: * wtf/ParkingLot.h: * wtf/Platform.h: * wtf/PointerComparison.h: * wtf/Poisoned.cpp: * wtf/PrintStream.cpp: * wtf/PrintStream.h: * wtf/ProcessID.h: * wtf/ProcessPrivilege.cpp: * wtf/RAMSize.cpp: * wtf/RAMSize.h: * wtf/RandomDevice.cpp: * wtf/RandomNumber.cpp: * wtf/RandomNumber.h: * wtf/RandomNumberSeed.h: * wtf/RangeSet.h: * wtf/RawPointer.h: * wtf/ReadWriteLock.cpp: * wtf/RedBlackTree.h: * wtf/Ref.h: * wtf/RefCountedArray.h: * wtf/RefCountedLeakCounter.cpp: * wtf/RefCountedLeakCounter.h: * wtf/RefCounter.h: * wtf/RefPtr.h: * wtf/RetainPtr.h: * wtf/RunLoop.cpp: * wtf/RunLoop.h: * wtf/RunLoopTimer.h: * wtf/RunLoopTimerCF.cpp: * wtf/SHA1.cpp: * wtf/SHA1.h: * wtf/SaturatedArithmetic.h: (saturatedSubtraction): * wtf/SchedulePair.h: * wtf/SchedulePairCF.cpp: * wtf/SchedulePairMac.mm: * wtf/ScopedLambda.h: * wtf/Seconds.cpp: * wtf/Seconds.h: * wtf/SegmentedVector.h: * wtf/SentinelLinkedList.h: * wtf/SharedTask.h: * wtf/SimpleStats.h: * wtf/SingleRootGraph.h: * wtf/SinglyLinkedList.h: * wtf/SixCharacterHash.cpp: * wtf/SixCharacterHash.h: * wtf/SmallPtrSet.h: * wtf/Spectrum.h: * wtf/StackBounds.cpp: * wtf/StackBounds.h: * wtf/StackStats.cpp: * wtf/StackStats.h: * wtf/StackTrace.cpp: * wtf/StdLibExtras.h: * wtf/StreamBuffer.h: * wtf/StringHashDumpContext.h: * wtf/StringPrintStream.cpp: * wtf/StringPrintStream.h: * wtf/ThreadGroup.cpp: * wtf/ThreadMessage.cpp: * wtf/ThreadSpecific.h: * wtf/Threading.cpp: * wtf/Threading.h: * wtf/ThreadingPrimitives.h: * wtf/ThreadingPthreads.cpp: * wtf/TimeWithDynamicClockType.cpp: * wtf/TimeWithDynamicClockType.h: * wtf/TimingScope.cpp: * wtf/TinyLRUCache.h: * wtf/TinyPtrSet.h: * wtf/TriState.h: * wtf/TypeCasts.h: * wtf/UUID.cpp: * wtf/UnionFind.h: * wtf/VMTags.h: * wtf/ValueCheck.h: * wtf/Vector.h: * wtf/VectorTraits.h: * wtf/WallTime.cpp: * wtf/WallTime.h: * wtf/WeakPtr.h: * wtf/WeakRandom.h: * wtf/WordLock.cpp: * wtf/WordLock.h: * wtf/WorkQueue.cpp: * wtf/WorkQueue.h: * wtf/WorkerPool.cpp: * wtf/cf/LanguageCF.cpp: * wtf/cf/RunLoopCF.cpp: * wtf/cocoa/Entitlements.mm: * wtf/cocoa/MachSendRight.cpp: * wtf/cocoa/MainThreadCocoa.mm: * wtf/cocoa/MemoryFootprintCocoa.cpp: * wtf/cocoa/WorkQueueCocoa.cpp: * wtf/dtoa.cpp: * wtf/dtoa.h: * wtf/ios/WebCoreThread.cpp: * wtf/ios/WebCoreThread.h: * wtf/mac/AppKitCompatibilityDeclarations.h: * wtf/mac/DeprecatedSymbolsUsedBySafari.mm: * wtf/mbmalloc.cpp: * wtf/persistence/PersistentCoders.cpp: * wtf/persistence/PersistentDecoder.cpp: * wtf/persistence/PersistentEncoder.cpp: * wtf/spi/cf/CFBundleSPI.h: * wtf/spi/darwin/CommonCryptoSPI.h: * wtf/text/ASCIIFastPath.h: * wtf/text/ASCIILiteral.cpp: * wtf/text/AtomicString.cpp: * wtf/text/AtomicString.h: * wtf/text/AtomicStringHash.h: * wtf/text/AtomicStringImpl.cpp: * wtf/text/AtomicStringImpl.h: * wtf/text/AtomicStringTable.cpp: * wtf/text/AtomicStringTable.h: * wtf/text/Base64.cpp: * wtf/text/CString.cpp: * wtf/text/CString.h: * wtf/text/ConversionMode.h: * wtf/text/ExternalStringImpl.cpp: * wtf/text/IntegerToStringConversion.h: * wtf/text/LChar.h: * wtf/text/LineEnding.cpp: * wtf/text/StringBuffer.h: * wtf/text/StringBuilder.cpp: * wtf/text/StringBuilder.h: * wtf/text/StringBuilderJSON.cpp: * wtf/text/StringCommon.h: * wtf/text/StringConcatenate.h: * wtf/text/StringHash.h: * wtf/text/StringImpl.cpp: * wtf/text/StringImpl.h: * wtf/text/StringOperators.h: * wtf/text/StringView.cpp: * wtf/text/StringView.h: * wtf/text/SymbolImpl.cpp: * wtf/text/SymbolRegistry.cpp: * wtf/text/SymbolRegistry.h: * wtf/text/TextBreakIterator.cpp: * wtf/text/TextBreakIterator.h: * wtf/text/TextBreakIteratorInternalICU.h: * wtf/text/TextPosition.h: * wtf/text/TextStream.cpp: * wtf/text/UniquedStringImpl.h: * wtf/text/WTFString.cpp: * wtf/text/WTFString.h: * wtf/text/cocoa/StringCocoa.mm: * wtf/text/cocoa/StringViewCocoa.mm: * wtf/text/cocoa/TextBreakIteratorInternalICUCocoa.cpp: * wtf/text/icu/UTextProvider.cpp: * wtf/text/icu/UTextProvider.h: * wtf/text/icu/UTextProviderLatin1.cpp: * wtf/text/icu/UTextProviderLatin1.h: * wtf/text/icu/UTextProviderUTF16.cpp: * wtf/text/icu/UTextProviderUTF16.h: * wtf/threads/BinarySemaphore.cpp: * wtf/threads/BinarySemaphore.h: * wtf/threads/Signals.cpp: * wtf/unicode/CharacterNames.h: * wtf/unicode/Collator.h: * wtf/unicode/CollatorDefault.cpp: * wtf/unicode/UTF8.cpp: * wtf/unicode/UTF8.h: Tools: Put WorkQueue in namespace DRT so it does not conflict with WTF::WorkQueue. * DumpRenderTree/TestRunner.cpp: (TestRunner::queueLoadHTMLString): (TestRunner::queueLoadAlternateHTMLString): (TestRunner::queueBackNavigation): (TestRunner::queueForwardNavigation): (TestRunner::queueLoadingScript): (TestRunner::queueNonLoadingScript): (TestRunner::queueReload): * DumpRenderTree/WorkQueue.cpp: (WorkQueue::singleton): Deleted. (WorkQueue::WorkQueue): Deleted. (WorkQueue::queue): Deleted. (WorkQueue::dequeue): Deleted. (WorkQueue::count): Deleted. (WorkQueue::clear): Deleted. (WorkQueue::processWork): Deleted. * DumpRenderTree/WorkQueue.h: (WorkQueue::setFrozen): Deleted. * DumpRenderTree/WorkQueueItem.h: * DumpRenderTree/mac/DumpRenderTree.mm: (runTest): * DumpRenderTree/mac/FrameLoadDelegate.mm: (-[FrameLoadDelegate processWork:]): (-[FrameLoadDelegate webView:locationChangeDone:forDataSource:]): * DumpRenderTree/mac/TestRunnerMac.mm: (TestRunner::notifyDone): (TestRunner::forceImmediateCompletion): (TestRunner::queueLoad): * DumpRenderTree/win/DumpRenderTree.cpp: (runTest): * DumpRenderTree/win/FrameLoadDelegate.cpp: (FrameLoadDelegate::processWork): (FrameLoadDelegate::locationChangeDone): * DumpRenderTree/win/TestRunnerWin.cpp: (TestRunner::notifyDone): (TestRunner::forceImmediateCompletion): (TestRunner::queueLoad): Canonical link: https://commits.webkit.org/205473@main git-svn-id: https://svn.webkit.org/repository/webkit/trunk@237099 268f45cc-cd09-0410-ab3c-d52691b4dbfc
2018-10-15 14:24:49 +00:00
#pragma once
Add saturation arithmetic support to FractionalLayoutUnit https://bugs.webkit.org/show_bug.cgi?id=94364 Reviewed by Benjamin Poulain. Source/WebCore: Add experimental saturation arithmetic support to FractionalLayoutUnit, guarded by a flag. The idea here is to saturate (or clamp) rather than overflow when computing positions and sizes. No new tests for WebCore, not enabled by default. * platform/FractionalLayoutUnit.h: (WebCore::FractionalLayoutUnit::intMinForLayoutUnit): Use INT_MIN instead of -INT_MAX to compute minimum value as the two are not the same. (WebCore::FractionalLayoutUnit::FractionalLayoutUnit): (WebCore::FractionalLayoutUnit::fromFloatCeil): (WebCore::FractionalLayoutUnit::fromFloatFloor): (WebCore::FractionalLayoutUnit::fromFloatRound): (WebCore::FractionalLayoutUnit::setValue): Add range checks. (WebCore::operator*): (WebCore::operator+): (WebCore::operator-): (WebCore::operator+=): (WebCore::operator-=): Use the saturatedAddition and saturatedSubtraction functions, which have been optimized to reduce branching, instead of range checks for the most common operators. Source/WTF: Add support functions for saturated addition and subtraction. Test: TestWebKitAPI/Tests/WTF/SaturatedArithmeticOperations.cpp * GNUmakefile.list.am: * WTF.gypi: * WTF.pro: * WTF.vcproj/WTF.vcproj: * WTF.xcodeproj/project.pbxproj: * WTF/wtf/CMakeLists.txt: Add SaturatedArithmetic.h to build files. * wtf/SaturatedArithmetic.h: Added. (saturatedAddition): (saturatedSubtraction): Support functions for saturated addition/subtraction. Compares the signed bit of the values instead of using range checks to reduce branching. * wtf/Platform.h: Add ENABLE_SATURATED_LAYOUT_ARITHMETIC flag. Tools: Add test for new saturatedArithmetic functions. * TestWebKitAPI/CMakeLists.txt: * TestWebKitAPI/GNUmakefile.am: * TestWebKitAPI/TestWebKitAPI.gypi: * TestWebKitAPI/TestWebKitAPI.xcodeproj/project.pbxproj: * TestWebKitAPI/Tests/WTF/SaturatedArithmeticOperations.cpp: Added. (TestWebKitAPI): (TestWebKitAPI::TEST): * TestWebKitAPI/win/TestWebKitAPI.vcproj: Canonical link: https://commits.webkit.org/112729@main git-svn-id: https://svn.webkit.org/repository/webkit/trunk@126509 268f45cc-cd09-0410-ab3c-d52691b4dbfc
2012-08-24 00:14:00 +00:00
#include <limits>
#include <stdint.h>
#include <stdlib.h>
Use pragma once in WTF https://bugs.webkit.org/show_bug.cgi?id=190527 Reviewed by Chris Dumez. Source/WTF: We also need to consistently include wtf headers from within wtf so we can build wtf without symbol redefinition errors from including the copy in Source and the copy in the build directory. * wtf/ASCIICType.h: * wtf/Assertions.cpp: * wtf/Assertions.h: * wtf/Atomics.h: * wtf/AutomaticThread.cpp: * wtf/AutomaticThread.h: * wtf/BackwardsGraph.h: * wtf/Bag.h: * wtf/BagToHashMap.h: * wtf/BitVector.cpp: * wtf/BitVector.h: * wtf/Bitmap.h: * wtf/BloomFilter.h: * wtf/Box.h: * wtf/BubbleSort.h: * wtf/BumpPointerAllocator.h: * wtf/ByteOrder.h: * wtf/CPUTime.cpp: * wtf/CallbackAggregator.h: * wtf/CheckedArithmetic.h: * wtf/CheckedBoolean.h: * wtf/ClockType.cpp: * wtf/ClockType.h: * wtf/CommaPrinter.h: * wtf/CompilationThread.cpp: * wtf/CompilationThread.h: * wtf/Compiler.h: * wtf/ConcurrentPtrHashSet.cpp: * wtf/ConcurrentVector.h: * wtf/Condition.h: * wtf/CountingLock.cpp: * wtf/CrossThreadTaskHandler.cpp: * wtf/CryptographicUtilities.cpp: * wtf/CryptographicUtilities.h: * wtf/CryptographicallyRandomNumber.cpp: * wtf/CryptographicallyRandomNumber.h: * wtf/CurrentTime.cpp: * wtf/DataLog.cpp: * wtf/DataLog.h: * wtf/DateMath.cpp: * wtf/DateMath.h: * wtf/DecimalNumber.cpp: * wtf/DecimalNumber.h: * wtf/Deque.h: * wtf/DisallowCType.h: * wtf/Dominators.h: * wtf/DoublyLinkedList.h: * wtf/FastBitVector.cpp: * wtf/FastMalloc.cpp: * wtf/FastMalloc.h: * wtf/FeatureDefines.h: * wtf/FilePrintStream.cpp: * wtf/FilePrintStream.h: * wtf/FlipBytes.h: * wtf/FunctionDispatcher.cpp: * wtf/FunctionDispatcher.h: * wtf/GetPtr.h: * wtf/Gigacage.cpp: * wtf/GlobalVersion.cpp: * wtf/GraphNodeWorklist.h: * wtf/GregorianDateTime.cpp: * wtf/GregorianDateTime.h: * wtf/HashFunctions.h: * wtf/HashMap.h: * wtf/HashMethod.h: * wtf/HashSet.h: * wtf/HashTable.cpp: * wtf/HashTraits.h: * wtf/Indenter.h: * wtf/IndexSparseSet.h: * wtf/InlineASM.h: * wtf/Insertion.h: * wtf/IteratorAdaptors.h: * wtf/IteratorRange.h: * wtf/JSONValues.cpp: * wtf/JSValueMalloc.cpp: * wtf/LEBDecoder.h: * wtf/Language.cpp: * wtf/ListDump.h: * wtf/Lock.cpp: * wtf/Lock.h: * wtf/LockAlgorithm.h: * wtf/LockedPrintStream.cpp: * wtf/Locker.h: * wtf/MD5.cpp: * wtf/MD5.h: * wtf/MainThread.cpp: * wtf/MainThread.h: * wtf/MallocPtr.h: * wtf/MathExtras.h: * wtf/MediaTime.cpp: * wtf/MediaTime.h: * wtf/MemoryPressureHandler.cpp: * wtf/MessageQueue.h: * wtf/MetaAllocator.cpp: * wtf/MetaAllocator.h: * wtf/MetaAllocatorHandle.h: * wtf/MonotonicTime.cpp: * wtf/MonotonicTime.h: * wtf/NakedPtr.h: * wtf/NoLock.h: * wtf/NoTailCalls.h: * wtf/Noncopyable.h: * wtf/NumberOfCores.cpp: * wtf/NumberOfCores.h: * wtf/OSAllocator.h: * wtf/OSAllocatorPosix.cpp: * wtf/OSRandomSource.cpp: * wtf/OSRandomSource.h: * wtf/ObjcRuntimeExtras.h: * wtf/OrderMaker.h: * wtf/PackedIntVector.h: * wtf/PageAllocation.h: * wtf/PageBlock.cpp: * wtf/PageBlock.h: * wtf/PageReservation.h: * wtf/ParallelHelperPool.cpp: * wtf/ParallelHelperPool.h: * wtf/ParallelJobs.h: * wtf/ParallelJobsLibdispatch.h: * wtf/ParallelVectorIterator.h: * wtf/ParkingLot.cpp: * wtf/ParkingLot.h: * wtf/Platform.h: * wtf/PointerComparison.h: * wtf/Poisoned.cpp: * wtf/PrintStream.cpp: * wtf/PrintStream.h: * wtf/ProcessID.h: * wtf/ProcessPrivilege.cpp: * wtf/RAMSize.cpp: * wtf/RAMSize.h: * wtf/RandomDevice.cpp: * wtf/RandomNumber.cpp: * wtf/RandomNumber.h: * wtf/RandomNumberSeed.h: * wtf/RangeSet.h: * wtf/RawPointer.h: * wtf/ReadWriteLock.cpp: * wtf/RedBlackTree.h: * wtf/Ref.h: * wtf/RefCountedArray.h: * wtf/RefCountedLeakCounter.cpp: * wtf/RefCountedLeakCounter.h: * wtf/RefCounter.h: * wtf/RefPtr.h: * wtf/RetainPtr.h: * wtf/RunLoop.cpp: * wtf/RunLoop.h: * wtf/RunLoopTimer.h: * wtf/RunLoopTimerCF.cpp: * wtf/SHA1.cpp: * wtf/SHA1.h: * wtf/SaturatedArithmetic.h: (saturatedSubtraction): * wtf/SchedulePair.h: * wtf/SchedulePairCF.cpp: * wtf/SchedulePairMac.mm: * wtf/ScopedLambda.h: * wtf/Seconds.cpp: * wtf/Seconds.h: * wtf/SegmentedVector.h: * wtf/SentinelLinkedList.h: * wtf/SharedTask.h: * wtf/SimpleStats.h: * wtf/SingleRootGraph.h: * wtf/SinglyLinkedList.h: * wtf/SixCharacterHash.cpp: * wtf/SixCharacterHash.h: * wtf/SmallPtrSet.h: * wtf/Spectrum.h: * wtf/StackBounds.cpp: * wtf/StackBounds.h: * wtf/StackStats.cpp: * wtf/StackStats.h: * wtf/StackTrace.cpp: * wtf/StdLibExtras.h: * wtf/StreamBuffer.h: * wtf/StringHashDumpContext.h: * wtf/StringPrintStream.cpp: * wtf/StringPrintStream.h: * wtf/ThreadGroup.cpp: * wtf/ThreadMessage.cpp: * wtf/ThreadSpecific.h: * wtf/Threading.cpp: * wtf/Threading.h: * wtf/ThreadingPrimitives.h: * wtf/ThreadingPthreads.cpp: * wtf/TimeWithDynamicClockType.cpp: * wtf/TimeWithDynamicClockType.h: * wtf/TimingScope.cpp: * wtf/TinyLRUCache.h: * wtf/TinyPtrSet.h: * wtf/TriState.h: * wtf/TypeCasts.h: * wtf/UUID.cpp: * wtf/UnionFind.h: * wtf/VMTags.h: * wtf/ValueCheck.h: * wtf/Vector.h: * wtf/VectorTraits.h: * wtf/WallTime.cpp: * wtf/WallTime.h: * wtf/WeakPtr.h: * wtf/WeakRandom.h: * wtf/WordLock.cpp: * wtf/WordLock.h: * wtf/WorkQueue.cpp: * wtf/WorkQueue.h: * wtf/WorkerPool.cpp: * wtf/cf/LanguageCF.cpp: * wtf/cf/RunLoopCF.cpp: * wtf/cocoa/Entitlements.mm: * wtf/cocoa/MachSendRight.cpp: * wtf/cocoa/MainThreadCocoa.mm: * wtf/cocoa/MemoryFootprintCocoa.cpp: * wtf/cocoa/WorkQueueCocoa.cpp: * wtf/dtoa.cpp: * wtf/dtoa.h: * wtf/ios/WebCoreThread.cpp: * wtf/ios/WebCoreThread.h: * wtf/mac/AppKitCompatibilityDeclarations.h: * wtf/mac/DeprecatedSymbolsUsedBySafari.mm: * wtf/mbmalloc.cpp: * wtf/persistence/PersistentCoders.cpp: * wtf/persistence/PersistentDecoder.cpp: * wtf/persistence/PersistentEncoder.cpp: * wtf/spi/cf/CFBundleSPI.h: * wtf/spi/darwin/CommonCryptoSPI.h: * wtf/text/ASCIIFastPath.h: * wtf/text/ASCIILiteral.cpp: * wtf/text/AtomicString.cpp: * wtf/text/AtomicString.h: * wtf/text/AtomicStringHash.h: * wtf/text/AtomicStringImpl.cpp: * wtf/text/AtomicStringImpl.h: * wtf/text/AtomicStringTable.cpp: * wtf/text/AtomicStringTable.h: * wtf/text/Base64.cpp: * wtf/text/CString.cpp: * wtf/text/CString.h: * wtf/text/ConversionMode.h: * wtf/text/ExternalStringImpl.cpp: * wtf/text/IntegerToStringConversion.h: * wtf/text/LChar.h: * wtf/text/LineEnding.cpp: * wtf/text/StringBuffer.h: * wtf/text/StringBuilder.cpp: * wtf/text/StringBuilder.h: * wtf/text/StringBuilderJSON.cpp: * wtf/text/StringCommon.h: * wtf/text/StringConcatenate.h: * wtf/text/StringHash.h: * wtf/text/StringImpl.cpp: * wtf/text/StringImpl.h: * wtf/text/StringOperators.h: * wtf/text/StringView.cpp: * wtf/text/StringView.h: * wtf/text/SymbolImpl.cpp: * wtf/text/SymbolRegistry.cpp: * wtf/text/SymbolRegistry.h: * wtf/text/TextBreakIterator.cpp: * wtf/text/TextBreakIterator.h: * wtf/text/TextBreakIteratorInternalICU.h: * wtf/text/TextPosition.h: * wtf/text/TextStream.cpp: * wtf/text/UniquedStringImpl.h: * wtf/text/WTFString.cpp: * wtf/text/WTFString.h: * wtf/text/cocoa/StringCocoa.mm: * wtf/text/cocoa/StringViewCocoa.mm: * wtf/text/cocoa/TextBreakIteratorInternalICUCocoa.cpp: * wtf/text/icu/UTextProvider.cpp: * wtf/text/icu/UTextProvider.h: * wtf/text/icu/UTextProviderLatin1.cpp: * wtf/text/icu/UTextProviderLatin1.h: * wtf/text/icu/UTextProviderUTF16.cpp: * wtf/text/icu/UTextProviderUTF16.h: * wtf/threads/BinarySemaphore.cpp: * wtf/threads/BinarySemaphore.h: * wtf/threads/Signals.cpp: * wtf/unicode/CharacterNames.h: * wtf/unicode/Collator.h: * wtf/unicode/CollatorDefault.cpp: * wtf/unicode/UTF8.cpp: * wtf/unicode/UTF8.h: Tools: Put WorkQueue in namespace DRT so it does not conflict with WTF::WorkQueue. * DumpRenderTree/TestRunner.cpp: (TestRunner::queueLoadHTMLString): (TestRunner::queueLoadAlternateHTMLString): (TestRunner::queueBackNavigation): (TestRunner::queueForwardNavigation): (TestRunner::queueLoadingScript): (TestRunner::queueNonLoadingScript): (TestRunner::queueReload): * DumpRenderTree/WorkQueue.cpp: (WorkQueue::singleton): Deleted. (WorkQueue::WorkQueue): Deleted. (WorkQueue::queue): Deleted. (WorkQueue::dequeue): Deleted. (WorkQueue::count): Deleted. (WorkQueue::clear): Deleted. (WorkQueue::processWork): Deleted. * DumpRenderTree/WorkQueue.h: (WorkQueue::setFrozen): Deleted. * DumpRenderTree/WorkQueueItem.h: * DumpRenderTree/mac/DumpRenderTree.mm: (runTest): * DumpRenderTree/mac/FrameLoadDelegate.mm: (-[FrameLoadDelegate processWork:]): (-[FrameLoadDelegate webView:locationChangeDone:forDataSource:]): * DumpRenderTree/mac/TestRunnerMac.mm: (TestRunner::notifyDone): (TestRunner::forceImmediateCompletion): (TestRunner::queueLoad): * DumpRenderTree/win/DumpRenderTree.cpp: (runTest): * DumpRenderTree/win/FrameLoadDelegate.cpp: (FrameLoadDelegate::processWork): (FrameLoadDelegate::locationChangeDone): * DumpRenderTree/win/TestRunnerWin.cpp: (TestRunner::notifyDone): (TestRunner::forceImmediateCompletion): (TestRunner::queueLoad): Canonical link: https://commits.webkit.org/205473@main git-svn-id: https://svn.webkit.org/repository/webkit/trunk@237099 268f45cc-cd09-0410-ab3c-d52691b4dbfc
2018-10-15 14:24:49 +00:00
#include <wtf/Compiler.h>
Add saturation arithmetic support to FractionalLayoutUnit https://bugs.webkit.org/show_bug.cgi?id=94364 Reviewed by Benjamin Poulain. Source/WebCore: Add experimental saturation arithmetic support to FractionalLayoutUnit, guarded by a flag. The idea here is to saturate (or clamp) rather than overflow when computing positions and sizes. No new tests for WebCore, not enabled by default. * platform/FractionalLayoutUnit.h: (WebCore::FractionalLayoutUnit::intMinForLayoutUnit): Use INT_MIN instead of -INT_MAX to compute minimum value as the two are not the same. (WebCore::FractionalLayoutUnit::FractionalLayoutUnit): (WebCore::FractionalLayoutUnit::fromFloatCeil): (WebCore::FractionalLayoutUnit::fromFloatFloor): (WebCore::FractionalLayoutUnit::fromFloatRound): (WebCore::FractionalLayoutUnit::setValue): Add range checks. (WebCore::operator*): (WebCore::operator+): (WebCore::operator-): (WebCore::operator+=): (WebCore::operator-=): Use the saturatedAddition and saturatedSubtraction functions, which have been optimized to reduce branching, instead of range checks for the most common operators. Source/WTF: Add support functions for saturated addition and subtraction. Test: TestWebKitAPI/Tests/WTF/SaturatedArithmeticOperations.cpp * GNUmakefile.list.am: * WTF.gypi: * WTF.pro: * WTF.vcproj/WTF.vcproj: * WTF.xcodeproj/project.pbxproj: * WTF/wtf/CMakeLists.txt: Add SaturatedArithmetic.h to build files. * wtf/SaturatedArithmetic.h: Added. (saturatedAddition): (saturatedSubtraction): Support functions for saturated addition/subtraction. Compares the signed bit of the values instead of using range checks to reduce branching. * wtf/Platform.h: Add ENABLE_SATURATED_LAYOUT_ARITHMETIC flag. Tools: Add test for new saturatedArithmetic functions. * TestWebKitAPI/CMakeLists.txt: * TestWebKitAPI/GNUmakefile.am: * TestWebKitAPI/TestWebKitAPI.gypi: * TestWebKitAPI/TestWebKitAPI.xcodeproj/project.pbxproj: * TestWebKitAPI/Tests/WTF/SaturatedArithmeticOperations.cpp: Added. (TestWebKitAPI): (TestWebKitAPI::TEST): * TestWebKitAPI/win/TestWebKitAPI.vcproj: Canonical link: https://commits.webkit.org/112729@main git-svn-id: https://svn.webkit.org/repository/webkit/trunk@126509 268f45cc-cd09-0410-ab3c-d52691b4dbfc
2012-08-24 00:14:00 +00:00
Move CFStringRef and NSString support from StringBuilder into StringConcatenateCF https://bugs.webkit.org/show_bug.cgi?id=225839 Reviewed by Sam Weinig. Source/JavaScriptCore: * inspector/ConsoleMessage.cpp: (Inspector::ConsoleMessage::ConsoleMessage): Use StringBuilder::clear instead of StringBuilder::resize; no advantage to the latter after calling StringBuilder::toString. * runtime/JSONObject.cpp: (JSC::Stringifier::Holder::appendNextProperty): Update for name change of StringBuilder::resize to StringBuilder::shrink. * runtime/TypeSet.cpp: (JSC::StructureShape::stringRepresentation): Ditto. Source/WebCore: * Modules/airplay/WebMediaSessionManager.cpp: (WebCore::mediaProducerStateString): Use StringBuilder exclusively instead of mixing it with makeString. Also updated for StringBuilder::shrink name. * html/HTMLTextFormControlElement.cpp: (WebCore::stripTrailingNewline): Updated for StringBuilder::shrink name. * page/CaptionUserPreferencesMediaAF.cpp: (WebCore::CaptionUserPreferencesMediaAF::captionsTextColor const): Tweaked coding style a bit. (WebCore::appendCSS): Use variadic StringBuilder::append instead of many separate calls. (WebCore::CaptionUserPreferencesMediaAF::captionsDefaultFontCSS const): Tweaked coding style a bit, and use variadic StrinBuilder::append calls to reduce the number of calls and streamline the code. (WebCore::CaptionUserPreferencesMediaAF::captionsStyleSheetOverride const): Ditto. Also removed unnecessary checks that strings are empty before appending. * page/scrolling/ScrollingCoordinator.cpp: (WebCore::ScrollingCoordinator::synchronousScrollingReasonsAsText): Updated for StringBuilder::shrink name. * platform/LayoutUnit.h: Updated for saturatedSum/Difference names. * platform/network/cocoa/NetworkStorageSessionCocoa.mm: (WebCore::NetworkStorageSession::cookiesForSession const): Tweaked codin style a bit, and use variadic StrinBuilder::append calls to reduce the number of calls and streamline the code. * rendering/RenderCounter.cpp: (WebCore::planCounter): Updated for saturatedSum name. * style/StyleBuilderCustom.h: (WebCore::Style::BuilderCustom::applyValueCounter): Ditto. * svg/SVGPathStringBuilder.cpp: (WebCore::SVGPathStringBuilder::result): Updated for StringBuilder::shrink name. * testing/Internals.cpp: (WebCore::Internals::pageMediaState): Ditto. * xml/XSLTProcessorLibxslt.cpp: (WebCore::saveResultToString): Ditto. Source/WebKit: * UIProcess/WebsiteData/Cocoa/WebsiteDataStoreCocoa.mm: (WebKit::WebsiteDataStore::platformSetNetworkParameters): Use makeString instead of StringBuilder. Source/WTF: The new header makes CFStringRef and NSString work with string concatenation, which means it now works with the variadic StringBuilder::append and makeString, and still works with the single-argument StringBuilder::append. More efficient that the old version because it does not allocate a temporary WTF::String for the 16-bit character path. Also made many other small improvements to the StringBuilder implementation. * WTF.xcodeproj/project.pbxproj: Added StringConcatenateCF.h. * wtf/CheckedArithmetic.h: Removed ConditionalCrashOnOverflow, which was only here for use by StringBuilder, which does not use CheckedArithmetic any more. * wtf/PlatformFTW.cmake: Added StringConcatenateCF.h.. * wtf/PlatformMac.cmake: Ditto. * wtf/PlatformWin.cmake: Ditto. * wtf/SaturatedArithmetic.h: Moved the contents of this file inside the WTF namespace. (WTF::signedAddInt32Overflows): Renamed this function. The type here is important, and we are not doing anything to prevent type conversion or create ambiguity, so it's good to be explicit in the function name. (WTF::saturatedSum<int32_t>): Renamed this from saturatedAddition for clarity. The function returns a sum, so that's a better name than calling it "addition". Also, it's clearer to be explicit about the return type. (WTF::signedSubtractInt32Overflows): Renamed. Same reason as above. (WTF::saturatedDifference<int32_t>): Ditto. (WTF::saturatedSum): Added. Does unsigned integer saturated addition. This one can be written in a portable manner and still get really efficient code on at least Intel and ARM64. (WTF::saturatedSum): Added a function template that lets callers pass larger number of arguments to saturatedSum, rather than exactly two. * wtf/text/StringBuilder.cpp: (WTF::expandedCapacity): Renamed to use the term capacity rather than length for the new required capacity. (WTF::StringBuilder::didOverflow): Implement the new approach to overflow, meaning we need to write the CRASH() here explicitly and in the non-crashing mode, set m_length. (WTF::StringBuilder::reifyString const): Changed the overflow check into a RELEASE_ASSERT. This is now responsible for doing the check that callers were doing earlier, so we want it in production builds. Also simplified this since our m_length member is a simple integer now, and removed the unused m_isReified. (WTF::StringBuilder::shrink): Renamed this to shrink to match the Vector::shrink function, since this has never supported making the builder larger. Removed unnecessary overflow checks, since shrinking cannot cause overflow. (WTF::StringBuilder::allocateBuffer): Replaced two separate functions with a single simpler function template. Removed extra overflow checks because the StringImpl::tryCreateUninitialized function already does the only overflow check we need. Also move to StringImpl::copyCharacters for copying characters rather than using std::memcpy directly. Removed code to set m_is8Bit and m_bufferCharacters. (WTF::StringBuilder::reallocateBuffer): Replaced two separate functions with a function template and a cover that calls the appropriate instance of the template for places where we aren't already in character-type-specific code paths. This version now supports allocating a buffer for the first time in cases where we have m_string and not m_buffer, which used to be handled at the higher level. Removed code to set m_bufferCharacters. (WTF::StringBuilder::reserveCapacity): Rewrote for simplicity. By relying on the overflow checking inside reallocateBuffer and allocateBuffer we no longer need checking of the passed-in value at this level. (WTF::StringBuilder::extendBufferForAppending): Removed the version of this that takes additionalLength since it's potentially confusing to have a family of functions that have the same name and take the same type of argument, but interpret it subtly differently. Streamlined the code using std::exchange. This function now also includes the logic from the function named extendBufferForAppendingWithoutOverflowCheck, which was subtly misnamed since that was not the only semantic difference. Also removed the ALWAYS_INLINE because the compiler will do the right thing without such heavy handed advice. (WTF::StringBuilder::extendBufferForAppendingSlowCase): Streamlined this by using std::exchange and removed additional overflow checks at this level since reallocateBuffer already does them. Also added a check for the case where the new total length is 0, which would not be handled correctly and efficiently by reallocateBuffer. (WTF::StringBuilder::extendBufferForAppendingLChar): Renamed this from extendBufferForAppending8, since it's now identical to calling extendBufferForAppending<LChar>, except for inlining and linkage. (WTF::StringBuilder::extendBufferForAppendingWithUpconvert): Renamed this from extendBufferForAppending16. It is different from the other extendBuffer functions because is supports upconverting from LChar to UChar. Like the others it relies on allocateBuffer for the overflow checking. (WTF::StringBuilder::appendCharacters): Removed an unnecessary assertion that the characters pointer is non-null; that will fail in an obvious way without an assertion. Simplified the logic and removed some invariant assertions that don't help us much. Changed overflow checking by using saturatedSum to compute the new length. In overflow cases, the new sum will be larger than the maximum string length, but will fit in an unsigned, so we can pass it down to lower levels and let functions like reallocateBuffer do the actual overflow checking. Also use StringImpl::copyCharacters. (WTF::StringBuilder::append): Removed the CFStringRef overload. (WTF::StringBuilder::shouldShrinkToFit const): Rename this from canShrink. Simplify the function a bit and remove the vague FIXME that says "this should be tuned". That may be so, but the FIXME is not really driving us to action. (WTF::StringBuilder::shrinkToFit): Simplify by using the new reallocateBuffer and std::exchange. Removed unneeded assertion about overflow that doesn't help us maintain the invariant. (WTF::StringBuilder::isAllASCII const): Was tempted to remove this function, but for now just made it use the StringView version for brevity. * wtf/text/StringBuilder.h: Removed many unneeded includes, and notably included SaturatedArithmetic.h instead of CheckedArithmetic.h because we now use the former instead of the latter. Changed the overflow checking implementation to work more simply based on saturated addition rather than Checked. This allowed us to get rid of dependency on our own unique mode for Checked, called ConditionalCrashOnOverflow. Removed a comment about making a templatized version of StringBuilder. We can do it if we like, but does not seem urgent. Moved fucntion bodies out of the class definition so it's easier to see what's going on in the class. Since m_length is now an ordinary integer, the check for overflowed simply checks to see if the length is larger than the maximum string length. When we encounter overflow that is not about length computation, we set the length to the maximum integer to indicate the failure. Deleted the append overloads for CFStringRef and NSString. Removed m_bufferCharacters, m_is8Bit, and m_isReified. (WTF::StringBuilder::StringBuilder): Simplified the constructor since we only have to initialize the m_shouldCrashOnOverflow member. (WTF::StringBuilder::clear): Fixed a mistake where this was not resetting the m_isReified flag. (WTF::StringBuilder::swap): Updated for changes in the data members. (WTF::StringBuilder::operator StringView const): Moved out of line. Made sure to call the length() function so we crash if this is called after overflow. (WTF::StringBuilder::append): Remove some of the unnecessary checks and special cases in the various versions of append. Most of the checking is done inside appendCharacters, with only a few exceptions. (WTF::StringBuilder::appendSubstring): Moved out of the class definition without making significant changes. (WTF::StringBuilder::appendCharacter): Ditto. (WTF::StringBuilder::toString): Greatly simplified this function by relying on overflow checking in the reifyString function instead of doing it here and removing unneeded invariant assertions. (WTF::StringBuilder::toStringPreserveCapacity const): Ditto. (WTF::StringBuilder::toAtomString const): Rewrote this to streamline, removing explicit overflow checks. (WTF::StringBuilder::length const): Moved out of the class definition without making significant changes. (WTF::StringBuilder::capacity const): Ditto. (WTF::StringBuilder::operator[] const): Ditto. (WTF::StringBuilder::characters const): Implemented this operation in the function template. Now rather than having this call the characters8 and characters16 functions, they can call it. (WTF::StringBuilder::getBufferCharacters<LChar>): Deleted. (WTF::StringBuilder::getBufferCharacters<UChar>): Deleted. (WTF::StringBuilder::appendFromAdapters): Use saturatedSum to compute the required length, which allows the extendBuffer functions to do overflow checking without having to take special checked integer types for arguments. (WTF::StringBuilder::equal): Implement using StringView. * wtf/text/StringBuilderJSON.cpp: (WTF::StringBuilder::appendQuotedJSONString): Simplified the checked arithmetic for computing the required capacity. Updated since we removed m_bufferCharacters and changed the type of m_length. * wtf/text/cf/StringConcatenateCF.h: Added. Specializes StringTypeAdapter for both CFStringRef and NSString *. If CFStringGetCStringPtr works for Latin-1, then does the 8-bit code path, otherwise the 16-bit. * wtf/text/cocoa/TextStreamCocoa.mm: Include StringConcatenateCF.h, since it's now needed to use CFStringRef with StringBuilder. Tools: * TestWebKitAPI/Tests/WTF/SaturatedArithmeticOperations.cpp: Updated tests for changes to SaturatedArithmetic.h. * TestWebKitAPI/Tests/WTF/StringBuilder.cpp: Updated tests for changes to StringBuilder. * TestWebKitAPI/Tests/WebKit/GetUserMedia.mm: (TestWebKitAPI::wkMediaCaptureStateString): Ditto. * WebKitTestRunner/InjectedBundle/InjectedBundlePage.cpp: Added include of StringConcatenateCF.h. Added StringTypeAdapter for WKStringRef. (WTR::styleDecToStr): Use ASCIILiteral instead of StringBuilder. (WTR::string): Removed unneeded toWTFString since the WKStringRef StringTypeAdapter takes care of it. (WTR::string): Renamed from frameToStr. Use makeString. (WTR::dumpResourceURL): Use append instead of appendLiteral. (WTR::dumpFrameDescriptionSuitableForTestResult): Deleted. (WTR::dumpLoadEvent): Use makeString. (WTR::string): Renamed from a longer name. Return a String instead of building in a StringBuilder. Use makeString. (WTR::string): Ditto. (WTR::dumpErrorDescriptionSuitableForTestResult): Removed unneeded toWTFString. (WTR::dumpFrameScrollPosition): Ditto. (WTR::dumpDescendantFramesText): Ditto. (WTR::InjectedBundlePage::dumpDOMAsWebArchive): Removed an unneeded local variable. (WTR::InjectedBundlePage::dump): Removed unneeded toWTFString. (WTR::InjectedBundlePage::didReceiveTitleForFrame): Ditto. (WTR::InjectedBundlePage::didFinishDocumentLoadForFrame): Updated for functon name change. (WTR::InjectedBundlePage::willSendRequestForFrame): Ditto. Also use variadic append. Also use makeString. (WTR::InjectedBundlePage::didReceiveResponseForResource): Ditto. (WTR::InjectedBundlePage::didFinishLoadForResource): Ditto. (WTR::InjectedBundlePage::didFailLoadForResource): Ditto. (WTR::InjectedBundlePage::decidePolicyForNavigationAction): Ditto. (WTR::InjectedBundlePage::decidePolicyForResponse): Ditto. (WTR::InjectedBundlePage::willAddMessageToConsole): Ditto. (WTR::InjectedBundlePage::willSetStatusbarText): Ditto. (WTR::InjectedBundlePage::willRunJavaScriptPrompt): Ditto. (WTR::InjectedBundlePage::didExceedDatabaseQuota): Ditto. (WTR::InjectedBundlePage::shouldInsertNode): Ditto. (WTR::InjectedBundlePage::shouldInsertText): Ditto. (WTR::InjectedBundlePage::shouldDeleteRange): Ditto. (WTR::InjectedBundlePage::shouldChangeSelectedRange): Ditto. (WTR::InjectedBundlePage::shouldApplyStyle): Ditto. (WTR::InjectedBundlePage::didBeginEditing): Ditto. (WTR::InjectedBundlePage::didEndEditing): Ditto. (WTR::InjectedBundlePage::didChange): Ditto. (WTR::InjectedBundlePage::didChangeSelection): Ditto. (WTR::InjectedBundlePage::dumpHistory): Ditto. Canonical link: https://commits.webkit.org/237916@main git-svn-id: https://svn.webkit.org/repository/webkit/trunk@277744 268f45cc-cd09-0410-ab3c-d52691b4dbfc
2021-05-19 19:37:21 +00:00
namespace WTF {
// FIXME: Enhance this so it fails to compile calls where either of the arguments can be outside the range of the integral type instead of quietly converting.
template<typename SignedIntegralType> std::enable_if_t<std::is_integral_v<SignedIntegralType> && std::is_signed_v<SignedIntegralType>, SignedIntegralType> saturatedSum(SignedIntegralType, SignedIntegralType);
template<typename UnsignedIntegralType> constexpr std::enable_if_t<std::is_integral_v<UnsignedIntegralType> && !std::is_signed_v<UnsignedIntegralType>, UnsignedIntegralType> saturatedSum(UnsignedIntegralType, UnsignedIntegralType);
template<typename IntegralType> IntegralType saturatedDifference(IntegralType, IntegralType);
inline bool signedAddInt32Overflows(int32_t a, int32_t b, int32_t& result)
Add saturation arithmetic support to FractionalLayoutUnit https://bugs.webkit.org/show_bug.cgi?id=94364 Reviewed by Benjamin Poulain. Source/WebCore: Add experimental saturation arithmetic support to FractionalLayoutUnit, guarded by a flag. The idea here is to saturate (or clamp) rather than overflow when computing positions and sizes. No new tests for WebCore, not enabled by default. * platform/FractionalLayoutUnit.h: (WebCore::FractionalLayoutUnit::intMinForLayoutUnit): Use INT_MIN instead of -INT_MAX to compute minimum value as the two are not the same. (WebCore::FractionalLayoutUnit::FractionalLayoutUnit): (WebCore::FractionalLayoutUnit::fromFloatCeil): (WebCore::FractionalLayoutUnit::fromFloatFloor): (WebCore::FractionalLayoutUnit::fromFloatRound): (WebCore::FractionalLayoutUnit::setValue): Add range checks. (WebCore::operator*): (WebCore::operator+): (WebCore::operator-): (WebCore::operator+=): (WebCore::operator-=): Use the saturatedAddition and saturatedSubtraction functions, which have been optimized to reduce branching, instead of range checks for the most common operators. Source/WTF: Add support functions for saturated addition and subtraction. Test: TestWebKitAPI/Tests/WTF/SaturatedArithmeticOperations.cpp * GNUmakefile.list.am: * WTF.gypi: * WTF.pro: * WTF.vcproj/WTF.vcproj: * WTF.xcodeproj/project.pbxproj: * WTF/wtf/CMakeLists.txt: Add SaturatedArithmetic.h to build files. * wtf/SaturatedArithmetic.h: Added. (saturatedAddition): (saturatedSubtraction): Support functions for saturated addition/subtraction. Compares the signed bit of the values instead of using range checks to reduce branching. * wtf/Platform.h: Add ENABLE_SATURATED_LAYOUT_ARITHMETIC flag. Tools: Add test for new saturatedArithmetic functions. * TestWebKitAPI/CMakeLists.txt: * TestWebKitAPI/GNUmakefile.am: * TestWebKitAPI/TestWebKitAPI.gypi: * TestWebKitAPI/TestWebKitAPI.xcodeproj/project.pbxproj: * TestWebKitAPI/Tests/WTF/SaturatedArithmeticOperations.cpp: Added. (TestWebKitAPI): (TestWebKitAPI::TEST): * TestWebKitAPI/win/TestWebKitAPI.vcproj: Canonical link: https://commits.webkit.org/112729@main git-svn-id: https://svn.webkit.org/repository/webkit/trunk@126509 268f45cc-cd09-0410-ab3c-d52691b4dbfc
2012-08-24 00:14:00 +00:00
{
#if COMPILER_HAS_CLANG_BUILTIN(__builtin_sadd_overflow) && !(defined __clang_major__ && __clang_major__ < 7)
return __builtin_sadd_overflow(a, b, &result);
#else
Add saturation arithmetic support to FractionalLayoutUnit https://bugs.webkit.org/show_bug.cgi?id=94364 Reviewed by Benjamin Poulain. Source/WebCore: Add experimental saturation arithmetic support to FractionalLayoutUnit, guarded by a flag. The idea here is to saturate (or clamp) rather than overflow when computing positions and sizes. No new tests for WebCore, not enabled by default. * platform/FractionalLayoutUnit.h: (WebCore::FractionalLayoutUnit::intMinForLayoutUnit): Use INT_MIN instead of -INT_MAX to compute minimum value as the two are not the same. (WebCore::FractionalLayoutUnit::FractionalLayoutUnit): (WebCore::FractionalLayoutUnit::fromFloatCeil): (WebCore::FractionalLayoutUnit::fromFloatFloor): (WebCore::FractionalLayoutUnit::fromFloatRound): (WebCore::FractionalLayoutUnit::setValue): Add range checks. (WebCore::operator*): (WebCore::operator+): (WebCore::operator-): (WebCore::operator+=): (WebCore::operator-=): Use the saturatedAddition and saturatedSubtraction functions, which have been optimized to reduce branching, instead of range checks for the most common operators. Source/WTF: Add support functions for saturated addition and subtraction. Test: TestWebKitAPI/Tests/WTF/SaturatedArithmeticOperations.cpp * GNUmakefile.list.am: * WTF.gypi: * WTF.pro: * WTF.vcproj/WTF.vcproj: * WTF.xcodeproj/project.pbxproj: * WTF/wtf/CMakeLists.txt: Add SaturatedArithmetic.h to build files. * wtf/SaturatedArithmetic.h: Added. (saturatedAddition): (saturatedSubtraction): Support functions for saturated addition/subtraction. Compares the signed bit of the values instead of using range checks to reduce branching. * wtf/Platform.h: Add ENABLE_SATURATED_LAYOUT_ARITHMETIC flag. Tools: Add test for new saturatedArithmetic functions. * TestWebKitAPI/CMakeLists.txt: * TestWebKitAPI/GNUmakefile.am: * TestWebKitAPI/TestWebKitAPI.gypi: * TestWebKitAPI/TestWebKitAPI.xcodeproj/project.pbxproj: * TestWebKitAPI/Tests/WTF/SaturatedArithmeticOperations.cpp: Added. (TestWebKitAPI): (TestWebKitAPI::TEST): * TestWebKitAPI/win/TestWebKitAPI.vcproj: Canonical link: https://commits.webkit.org/112729@main git-svn-id: https://svn.webkit.org/repository/webkit/trunk@126509 268f45cc-cd09-0410-ab3c-d52691b4dbfc
2012-08-24 00:14:00 +00:00
uint32_t ua = a;
uint32_t ub = b;
uint32_t uresult = ua + ub;
result = static_cast<int32_t>(uresult);
Add saturation arithmetic support to FractionalLayoutUnit https://bugs.webkit.org/show_bug.cgi?id=94364 Reviewed by Benjamin Poulain. Source/WebCore: Add experimental saturation arithmetic support to FractionalLayoutUnit, guarded by a flag. The idea here is to saturate (or clamp) rather than overflow when computing positions and sizes. No new tests for WebCore, not enabled by default. * platform/FractionalLayoutUnit.h: (WebCore::FractionalLayoutUnit::intMinForLayoutUnit): Use INT_MIN instead of -INT_MAX to compute minimum value as the two are not the same. (WebCore::FractionalLayoutUnit::FractionalLayoutUnit): (WebCore::FractionalLayoutUnit::fromFloatCeil): (WebCore::FractionalLayoutUnit::fromFloatFloor): (WebCore::FractionalLayoutUnit::fromFloatRound): (WebCore::FractionalLayoutUnit::setValue): Add range checks. (WebCore::operator*): (WebCore::operator+): (WebCore::operator-): (WebCore::operator+=): (WebCore::operator-=): Use the saturatedAddition and saturatedSubtraction functions, which have been optimized to reduce branching, instead of range checks for the most common operators. Source/WTF: Add support functions for saturated addition and subtraction. Test: TestWebKitAPI/Tests/WTF/SaturatedArithmeticOperations.cpp * GNUmakefile.list.am: * WTF.gypi: * WTF.pro: * WTF.vcproj/WTF.vcproj: * WTF.xcodeproj/project.pbxproj: * WTF/wtf/CMakeLists.txt: Add SaturatedArithmetic.h to build files. * wtf/SaturatedArithmetic.h: Added. (saturatedAddition): (saturatedSubtraction): Support functions for saturated addition/subtraction. Compares the signed bit of the values instead of using range checks to reduce branching. * wtf/Platform.h: Add ENABLE_SATURATED_LAYOUT_ARITHMETIC flag. Tools: Add test for new saturatedArithmetic functions. * TestWebKitAPI/CMakeLists.txt: * TestWebKitAPI/GNUmakefile.am: * TestWebKitAPI/TestWebKitAPI.gypi: * TestWebKitAPI/TestWebKitAPI.xcodeproj/project.pbxproj: * TestWebKitAPI/Tests/WTF/SaturatedArithmeticOperations.cpp: Added. (TestWebKitAPI): (TestWebKitAPI::TEST): * TestWebKitAPI/win/TestWebKitAPI.vcproj: Canonical link: https://commits.webkit.org/112729@main git-svn-id: https://svn.webkit.org/repository/webkit/trunk@126509 268f45cc-cd09-0410-ab3c-d52691b4dbfc
2012-08-24 00:14:00 +00:00
// Can only overflow if the signed bit of the two values match. If the signed
// bit of the result and one of the values differ it did overflow.
return !((ua ^ ub) >> 31) && (uresult ^ ua) >> 31;
#endif
}
Add saturation arithmetic support to FractionalLayoutUnit https://bugs.webkit.org/show_bug.cgi?id=94364 Reviewed by Benjamin Poulain. Source/WebCore: Add experimental saturation arithmetic support to FractionalLayoutUnit, guarded by a flag. The idea here is to saturate (or clamp) rather than overflow when computing positions and sizes. No new tests for WebCore, not enabled by default. * platform/FractionalLayoutUnit.h: (WebCore::FractionalLayoutUnit::intMinForLayoutUnit): Use INT_MIN instead of -INT_MAX to compute minimum value as the two are not the same. (WebCore::FractionalLayoutUnit::FractionalLayoutUnit): (WebCore::FractionalLayoutUnit::fromFloatCeil): (WebCore::FractionalLayoutUnit::fromFloatFloor): (WebCore::FractionalLayoutUnit::fromFloatRound): (WebCore::FractionalLayoutUnit::setValue): Add range checks. (WebCore::operator*): (WebCore::operator+): (WebCore::operator-): (WebCore::operator+=): (WebCore::operator-=): Use the saturatedAddition and saturatedSubtraction functions, which have been optimized to reduce branching, instead of range checks for the most common operators. Source/WTF: Add support functions for saturated addition and subtraction. Test: TestWebKitAPI/Tests/WTF/SaturatedArithmeticOperations.cpp * GNUmakefile.list.am: * WTF.gypi: * WTF.pro: * WTF.vcproj/WTF.vcproj: * WTF.xcodeproj/project.pbxproj: * WTF/wtf/CMakeLists.txt: Add SaturatedArithmetic.h to build files. * wtf/SaturatedArithmetic.h: Added. (saturatedAddition): (saturatedSubtraction): Support functions for saturated addition/subtraction. Compares the signed bit of the values instead of using range checks to reduce branching. * wtf/Platform.h: Add ENABLE_SATURATED_LAYOUT_ARITHMETIC flag. Tools: Add test for new saturatedArithmetic functions. * TestWebKitAPI/CMakeLists.txt: * TestWebKitAPI/GNUmakefile.am: * TestWebKitAPI/TestWebKitAPI.gypi: * TestWebKitAPI/TestWebKitAPI.xcodeproj/project.pbxproj: * TestWebKitAPI/Tests/WTF/SaturatedArithmeticOperations.cpp: Added. (TestWebKitAPI): (TestWebKitAPI::TEST): * TestWebKitAPI/win/TestWebKitAPI.vcproj: Canonical link: https://commits.webkit.org/112729@main git-svn-id: https://svn.webkit.org/repository/webkit/trunk@126509 268f45cc-cd09-0410-ab3c-d52691b4dbfc
2012-08-24 00:14:00 +00:00
Move CFStringRef and NSString support from StringBuilder into StringConcatenateCF https://bugs.webkit.org/show_bug.cgi?id=225839 Reviewed by Sam Weinig. Source/JavaScriptCore: * inspector/ConsoleMessage.cpp: (Inspector::ConsoleMessage::ConsoleMessage): Use StringBuilder::clear instead of StringBuilder::resize; no advantage to the latter after calling StringBuilder::toString. * runtime/JSONObject.cpp: (JSC::Stringifier::Holder::appendNextProperty): Update for name change of StringBuilder::resize to StringBuilder::shrink. * runtime/TypeSet.cpp: (JSC::StructureShape::stringRepresentation): Ditto. Source/WebCore: * Modules/airplay/WebMediaSessionManager.cpp: (WebCore::mediaProducerStateString): Use StringBuilder exclusively instead of mixing it with makeString. Also updated for StringBuilder::shrink name. * html/HTMLTextFormControlElement.cpp: (WebCore::stripTrailingNewline): Updated for StringBuilder::shrink name. * page/CaptionUserPreferencesMediaAF.cpp: (WebCore::CaptionUserPreferencesMediaAF::captionsTextColor const): Tweaked coding style a bit. (WebCore::appendCSS): Use variadic StringBuilder::append instead of many separate calls. (WebCore::CaptionUserPreferencesMediaAF::captionsDefaultFontCSS const): Tweaked coding style a bit, and use variadic StrinBuilder::append calls to reduce the number of calls and streamline the code. (WebCore::CaptionUserPreferencesMediaAF::captionsStyleSheetOverride const): Ditto. Also removed unnecessary checks that strings are empty before appending. * page/scrolling/ScrollingCoordinator.cpp: (WebCore::ScrollingCoordinator::synchronousScrollingReasonsAsText): Updated for StringBuilder::shrink name. * platform/LayoutUnit.h: Updated for saturatedSum/Difference names. * platform/network/cocoa/NetworkStorageSessionCocoa.mm: (WebCore::NetworkStorageSession::cookiesForSession const): Tweaked codin style a bit, and use variadic StrinBuilder::append calls to reduce the number of calls and streamline the code. * rendering/RenderCounter.cpp: (WebCore::planCounter): Updated for saturatedSum name. * style/StyleBuilderCustom.h: (WebCore::Style::BuilderCustom::applyValueCounter): Ditto. * svg/SVGPathStringBuilder.cpp: (WebCore::SVGPathStringBuilder::result): Updated for StringBuilder::shrink name. * testing/Internals.cpp: (WebCore::Internals::pageMediaState): Ditto. * xml/XSLTProcessorLibxslt.cpp: (WebCore::saveResultToString): Ditto. Source/WebKit: * UIProcess/WebsiteData/Cocoa/WebsiteDataStoreCocoa.mm: (WebKit::WebsiteDataStore::platformSetNetworkParameters): Use makeString instead of StringBuilder. Source/WTF: The new header makes CFStringRef and NSString work with string concatenation, which means it now works with the variadic StringBuilder::append and makeString, and still works with the single-argument StringBuilder::append. More efficient that the old version because it does not allocate a temporary WTF::String for the 16-bit character path. Also made many other small improvements to the StringBuilder implementation. * WTF.xcodeproj/project.pbxproj: Added StringConcatenateCF.h. * wtf/CheckedArithmetic.h: Removed ConditionalCrashOnOverflow, which was only here for use by StringBuilder, which does not use CheckedArithmetic any more. * wtf/PlatformFTW.cmake: Added StringConcatenateCF.h.. * wtf/PlatformMac.cmake: Ditto. * wtf/PlatformWin.cmake: Ditto. * wtf/SaturatedArithmetic.h: Moved the contents of this file inside the WTF namespace. (WTF::signedAddInt32Overflows): Renamed this function. The type here is important, and we are not doing anything to prevent type conversion or create ambiguity, so it's good to be explicit in the function name. (WTF::saturatedSum<int32_t>): Renamed this from saturatedAddition for clarity. The function returns a sum, so that's a better name than calling it "addition". Also, it's clearer to be explicit about the return type. (WTF::signedSubtractInt32Overflows): Renamed. Same reason as above. (WTF::saturatedDifference<int32_t>): Ditto. (WTF::saturatedSum): Added. Does unsigned integer saturated addition. This one can be written in a portable manner and still get really efficient code on at least Intel and ARM64. (WTF::saturatedSum): Added a function template that lets callers pass larger number of arguments to saturatedSum, rather than exactly two. * wtf/text/StringBuilder.cpp: (WTF::expandedCapacity): Renamed to use the term capacity rather than length for the new required capacity. (WTF::StringBuilder::didOverflow): Implement the new approach to overflow, meaning we need to write the CRASH() here explicitly and in the non-crashing mode, set m_length. (WTF::StringBuilder::reifyString const): Changed the overflow check into a RELEASE_ASSERT. This is now responsible for doing the check that callers were doing earlier, so we want it in production builds. Also simplified this since our m_length member is a simple integer now, and removed the unused m_isReified. (WTF::StringBuilder::shrink): Renamed this to shrink to match the Vector::shrink function, since this has never supported making the builder larger. Removed unnecessary overflow checks, since shrinking cannot cause overflow. (WTF::StringBuilder::allocateBuffer): Replaced two separate functions with a single simpler function template. Removed extra overflow checks because the StringImpl::tryCreateUninitialized function already does the only overflow check we need. Also move to StringImpl::copyCharacters for copying characters rather than using std::memcpy directly. Removed code to set m_is8Bit and m_bufferCharacters. (WTF::StringBuilder::reallocateBuffer): Replaced two separate functions with a function template and a cover that calls the appropriate instance of the template for places where we aren't already in character-type-specific code paths. This version now supports allocating a buffer for the first time in cases where we have m_string and not m_buffer, which used to be handled at the higher level. Removed code to set m_bufferCharacters. (WTF::StringBuilder::reserveCapacity): Rewrote for simplicity. By relying on the overflow checking inside reallocateBuffer and allocateBuffer we no longer need checking of the passed-in value at this level. (WTF::StringBuilder::extendBufferForAppending): Removed the version of this that takes additionalLength since it's potentially confusing to have a family of functions that have the same name and take the same type of argument, but interpret it subtly differently. Streamlined the code using std::exchange. This function now also includes the logic from the function named extendBufferForAppendingWithoutOverflowCheck, which was subtly misnamed since that was not the only semantic difference. Also removed the ALWAYS_INLINE because the compiler will do the right thing without such heavy handed advice. (WTF::StringBuilder::extendBufferForAppendingSlowCase): Streamlined this by using std::exchange and removed additional overflow checks at this level since reallocateBuffer already does them. Also added a check for the case where the new total length is 0, which would not be handled correctly and efficiently by reallocateBuffer. (WTF::StringBuilder::extendBufferForAppendingLChar): Renamed this from extendBufferForAppending8, since it's now identical to calling extendBufferForAppending<LChar>, except for inlining and linkage. (WTF::StringBuilder::extendBufferForAppendingWithUpconvert): Renamed this from extendBufferForAppending16. It is different from the other extendBuffer functions because is supports upconverting from LChar to UChar. Like the others it relies on allocateBuffer for the overflow checking. (WTF::StringBuilder::appendCharacters): Removed an unnecessary assertion that the characters pointer is non-null; that will fail in an obvious way without an assertion. Simplified the logic and removed some invariant assertions that don't help us much. Changed overflow checking by using saturatedSum to compute the new length. In overflow cases, the new sum will be larger than the maximum string length, but will fit in an unsigned, so we can pass it down to lower levels and let functions like reallocateBuffer do the actual overflow checking. Also use StringImpl::copyCharacters. (WTF::StringBuilder::append): Removed the CFStringRef overload. (WTF::StringBuilder::shouldShrinkToFit const): Rename this from canShrink. Simplify the function a bit and remove the vague FIXME that says "this should be tuned". That may be so, but the FIXME is not really driving us to action. (WTF::StringBuilder::shrinkToFit): Simplify by using the new reallocateBuffer and std::exchange. Removed unneeded assertion about overflow that doesn't help us maintain the invariant. (WTF::StringBuilder::isAllASCII const): Was tempted to remove this function, but for now just made it use the StringView version for brevity. * wtf/text/StringBuilder.h: Removed many unneeded includes, and notably included SaturatedArithmetic.h instead of CheckedArithmetic.h because we now use the former instead of the latter. Changed the overflow checking implementation to work more simply based on saturated addition rather than Checked. This allowed us to get rid of dependency on our own unique mode for Checked, called ConditionalCrashOnOverflow. Removed a comment about making a templatized version of StringBuilder. We can do it if we like, but does not seem urgent. Moved fucntion bodies out of the class definition so it's easier to see what's going on in the class. Since m_length is now an ordinary integer, the check for overflowed simply checks to see if the length is larger than the maximum string length. When we encounter overflow that is not about length computation, we set the length to the maximum integer to indicate the failure. Deleted the append overloads for CFStringRef and NSString. Removed m_bufferCharacters, m_is8Bit, and m_isReified. (WTF::StringBuilder::StringBuilder): Simplified the constructor since we only have to initialize the m_shouldCrashOnOverflow member. (WTF::StringBuilder::clear): Fixed a mistake where this was not resetting the m_isReified flag. (WTF::StringBuilder::swap): Updated for changes in the data members. (WTF::StringBuilder::operator StringView const): Moved out of line. Made sure to call the length() function so we crash if this is called after overflow. (WTF::StringBuilder::append): Remove some of the unnecessary checks and special cases in the various versions of append. Most of the checking is done inside appendCharacters, with only a few exceptions. (WTF::StringBuilder::appendSubstring): Moved out of the class definition without making significant changes. (WTF::StringBuilder::appendCharacter): Ditto. (WTF::StringBuilder::toString): Greatly simplified this function by relying on overflow checking in the reifyString function instead of doing it here and removing unneeded invariant assertions. (WTF::StringBuilder::toStringPreserveCapacity const): Ditto. (WTF::StringBuilder::toAtomString const): Rewrote this to streamline, removing explicit overflow checks. (WTF::StringBuilder::length const): Moved out of the class definition without making significant changes. (WTF::StringBuilder::capacity const): Ditto. (WTF::StringBuilder::operator[] const): Ditto. (WTF::StringBuilder::characters const): Implemented this operation in the function template. Now rather than having this call the characters8 and characters16 functions, they can call it. (WTF::StringBuilder::getBufferCharacters<LChar>): Deleted. (WTF::StringBuilder::getBufferCharacters<UChar>): Deleted. (WTF::StringBuilder::appendFromAdapters): Use saturatedSum to compute the required length, which allows the extendBuffer functions to do overflow checking without having to take special checked integer types for arguments. (WTF::StringBuilder::equal): Implement using StringView. * wtf/text/StringBuilderJSON.cpp: (WTF::StringBuilder::appendQuotedJSONString): Simplified the checked arithmetic for computing the required capacity. Updated since we removed m_bufferCharacters and changed the type of m_length. * wtf/text/cf/StringConcatenateCF.h: Added. Specializes StringTypeAdapter for both CFStringRef and NSString *. If CFStringGetCStringPtr works for Latin-1, then does the 8-bit code path, otherwise the 16-bit. * wtf/text/cocoa/TextStreamCocoa.mm: Include StringConcatenateCF.h, since it's now needed to use CFStringRef with StringBuilder. Tools: * TestWebKitAPI/Tests/WTF/SaturatedArithmeticOperations.cpp: Updated tests for changes to SaturatedArithmetic.h. * TestWebKitAPI/Tests/WTF/StringBuilder.cpp: Updated tests for changes to StringBuilder. * TestWebKitAPI/Tests/WebKit/GetUserMedia.mm: (TestWebKitAPI::wkMediaCaptureStateString): Ditto. * WebKitTestRunner/InjectedBundle/InjectedBundlePage.cpp: Added include of StringConcatenateCF.h. Added StringTypeAdapter for WKStringRef. (WTR::styleDecToStr): Use ASCIILiteral instead of StringBuilder. (WTR::string): Removed unneeded toWTFString since the WKStringRef StringTypeAdapter takes care of it. (WTR::string): Renamed from frameToStr. Use makeString. (WTR::dumpResourceURL): Use append instead of appendLiteral. (WTR::dumpFrameDescriptionSuitableForTestResult): Deleted. (WTR::dumpLoadEvent): Use makeString. (WTR::string): Renamed from a longer name. Return a String instead of building in a StringBuilder. Use makeString. (WTR::string): Ditto. (WTR::dumpErrorDescriptionSuitableForTestResult): Removed unneeded toWTFString. (WTR::dumpFrameScrollPosition): Ditto. (WTR::dumpDescendantFramesText): Ditto. (WTR::InjectedBundlePage::dumpDOMAsWebArchive): Removed an unneeded local variable. (WTR::InjectedBundlePage::dump): Removed unneeded toWTFString. (WTR::InjectedBundlePage::didReceiveTitleForFrame): Ditto. (WTR::InjectedBundlePage::didFinishDocumentLoadForFrame): Updated for functon name change. (WTR::InjectedBundlePage::willSendRequestForFrame): Ditto. Also use variadic append. Also use makeString. (WTR::InjectedBundlePage::didReceiveResponseForResource): Ditto. (WTR::InjectedBundlePage::didFinishLoadForResource): Ditto. (WTR::InjectedBundlePage::didFailLoadForResource): Ditto. (WTR::InjectedBundlePage::decidePolicyForNavigationAction): Ditto. (WTR::InjectedBundlePage::decidePolicyForResponse): Ditto. (WTR::InjectedBundlePage::willAddMessageToConsole): Ditto. (WTR::InjectedBundlePage::willSetStatusbarText): Ditto. (WTR::InjectedBundlePage::willRunJavaScriptPrompt): Ditto. (WTR::InjectedBundlePage::didExceedDatabaseQuota): Ditto. (WTR::InjectedBundlePage::shouldInsertNode): Ditto. (WTR::InjectedBundlePage::shouldInsertText): Ditto. (WTR::InjectedBundlePage::shouldDeleteRange): Ditto. (WTR::InjectedBundlePage::shouldChangeSelectedRange): Ditto. (WTR::InjectedBundlePage::shouldApplyStyle): Ditto. (WTR::InjectedBundlePage::didBeginEditing): Ditto. (WTR::InjectedBundlePage::didEndEditing): Ditto. (WTR::InjectedBundlePage::didChange): Ditto. (WTR::InjectedBundlePage::didChangeSelection): Ditto. (WTR::InjectedBundlePage::dumpHistory): Ditto. Canonical link: https://commits.webkit.org/237916@main git-svn-id: https://svn.webkit.org/repository/webkit/trunk@277744 268f45cc-cd09-0410-ab3c-d52691b4dbfc
2021-05-19 19:37:21 +00:00
template<> inline int32_t saturatedSum<int32_t>(int32_t a, int32_t b)
{
int32_t result;
#if CPU(ARM_THUMB2)
asm("qadd %[sum], %[addend], %[augend]"
: [sum]"=r"(result)
: [augend]"r"(a), [addend]"r"(b)
: /* Nothing is clobbered. */
);
#else
Move CFStringRef and NSString support from StringBuilder into StringConcatenateCF https://bugs.webkit.org/show_bug.cgi?id=225839 Reviewed by Sam Weinig. Source/JavaScriptCore: * inspector/ConsoleMessage.cpp: (Inspector::ConsoleMessage::ConsoleMessage): Use StringBuilder::clear instead of StringBuilder::resize; no advantage to the latter after calling StringBuilder::toString. * runtime/JSONObject.cpp: (JSC::Stringifier::Holder::appendNextProperty): Update for name change of StringBuilder::resize to StringBuilder::shrink. * runtime/TypeSet.cpp: (JSC::StructureShape::stringRepresentation): Ditto. Source/WebCore: * Modules/airplay/WebMediaSessionManager.cpp: (WebCore::mediaProducerStateString): Use StringBuilder exclusively instead of mixing it with makeString. Also updated for StringBuilder::shrink name. * html/HTMLTextFormControlElement.cpp: (WebCore::stripTrailingNewline): Updated for StringBuilder::shrink name. * page/CaptionUserPreferencesMediaAF.cpp: (WebCore::CaptionUserPreferencesMediaAF::captionsTextColor const): Tweaked coding style a bit. (WebCore::appendCSS): Use variadic StringBuilder::append instead of many separate calls. (WebCore::CaptionUserPreferencesMediaAF::captionsDefaultFontCSS const): Tweaked coding style a bit, and use variadic StrinBuilder::append calls to reduce the number of calls and streamline the code. (WebCore::CaptionUserPreferencesMediaAF::captionsStyleSheetOverride const): Ditto. Also removed unnecessary checks that strings are empty before appending. * page/scrolling/ScrollingCoordinator.cpp: (WebCore::ScrollingCoordinator::synchronousScrollingReasonsAsText): Updated for StringBuilder::shrink name. * platform/LayoutUnit.h: Updated for saturatedSum/Difference names. * platform/network/cocoa/NetworkStorageSessionCocoa.mm: (WebCore::NetworkStorageSession::cookiesForSession const): Tweaked codin style a bit, and use variadic StrinBuilder::append calls to reduce the number of calls and streamline the code. * rendering/RenderCounter.cpp: (WebCore::planCounter): Updated for saturatedSum name. * style/StyleBuilderCustom.h: (WebCore::Style::BuilderCustom::applyValueCounter): Ditto. * svg/SVGPathStringBuilder.cpp: (WebCore::SVGPathStringBuilder::result): Updated for StringBuilder::shrink name. * testing/Internals.cpp: (WebCore::Internals::pageMediaState): Ditto. * xml/XSLTProcessorLibxslt.cpp: (WebCore::saveResultToString): Ditto. Source/WebKit: * UIProcess/WebsiteData/Cocoa/WebsiteDataStoreCocoa.mm: (WebKit::WebsiteDataStore::platformSetNetworkParameters): Use makeString instead of StringBuilder. Source/WTF: The new header makes CFStringRef and NSString work with string concatenation, which means it now works with the variadic StringBuilder::append and makeString, and still works with the single-argument StringBuilder::append. More efficient that the old version because it does not allocate a temporary WTF::String for the 16-bit character path. Also made many other small improvements to the StringBuilder implementation. * WTF.xcodeproj/project.pbxproj: Added StringConcatenateCF.h. * wtf/CheckedArithmetic.h: Removed ConditionalCrashOnOverflow, which was only here for use by StringBuilder, which does not use CheckedArithmetic any more. * wtf/PlatformFTW.cmake: Added StringConcatenateCF.h.. * wtf/PlatformMac.cmake: Ditto. * wtf/PlatformWin.cmake: Ditto. * wtf/SaturatedArithmetic.h: Moved the contents of this file inside the WTF namespace. (WTF::signedAddInt32Overflows): Renamed this function. The type here is important, and we are not doing anything to prevent type conversion or create ambiguity, so it's good to be explicit in the function name. (WTF::saturatedSum<int32_t>): Renamed this from saturatedAddition for clarity. The function returns a sum, so that's a better name than calling it "addition". Also, it's clearer to be explicit about the return type. (WTF::signedSubtractInt32Overflows): Renamed. Same reason as above. (WTF::saturatedDifference<int32_t>): Ditto. (WTF::saturatedSum): Added. Does unsigned integer saturated addition. This one can be written in a portable manner and still get really efficient code on at least Intel and ARM64. (WTF::saturatedSum): Added a function template that lets callers pass larger number of arguments to saturatedSum, rather than exactly two. * wtf/text/StringBuilder.cpp: (WTF::expandedCapacity): Renamed to use the term capacity rather than length for the new required capacity. (WTF::StringBuilder::didOverflow): Implement the new approach to overflow, meaning we need to write the CRASH() here explicitly and in the non-crashing mode, set m_length. (WTF::StringBuilder::reifyString const): Changed the overflow check into a RELEASE_ASSERT. This is now responsible for doing the check that callers were doing earlier, so we want it in production builds. Also simplified this since our m_length member is a simple integer now, and removed the unused m_isReified. (WTF::StringBuilder::shrink): Renamed this to shrink to match the Vector::shrink function, since this has never supported making the builder larger. Removed unnecessary overflow checks, since shrinking cannot cause overflow. (WTF::StringBuilder::allocateBuffer): Replaced two separate functions with a single simpler function template. Removed extra overflow checks because the StringImpl::tryCreateUninitialized function already does the only overflow check we need. Also move to StringImpl::copyCharacters for copying characters rather than using std::memcpy directly. Removed code to set m_is8Bit and m_bufferCharacters. (WTF::StringBuilder::reallocateBuffer): Replaced two separate functions with a function template and a cover that calls the appropriate instance of the template for places where we aren't already in character-type-specific code paths. This version now supports allocating a buffer for the first time in cases where we have m_string and not m_buffer, which used to be handled at the higher level. Removed code to set m_bufferCharacters. (WTF::StringBuilder::reserveCapacity): Rewrote for simplicity. By relying on the overflow checking inside reallocateBuffer and allocateBuffer we no longer need checking of the passed-in value at this level. (WTF::StringBuilder::extendBufferForAppending): Removed the version of this that takes additionalLength since it's potentially confusing to have a family of functions that have the same name and take the same type of argument, but interpret it subtly differently. Streamlined the code using std::exchange. This function now also includes the logic from the function named extendBufferForAppendingWithoutOverflowCheck, which was subtly misnamed since that was not the only semantic difference. Also removed the ALWAYS_INLINE because the compiler will do the right thing without such heavy handed advice. (WTF::StringBuilder::extendBufferForAppendingSlowCase): Streamlined this by using std::exchange and removed additional overflow checks at this level since reallocateBuffer already does them. Also added a check for the case where the new total length is 0, which would not be handled correctly and efficiently by reallocateBuffer. (WTF::StringBuilder::extendBufferForAppendingLChar): Renamed this from extendBufferForAppending8, since it's now identical to calling extendBufferForAppending<LChar>, except for inlining and linkage. (WTF::StringBuilder::extendBufferForAppendingWithUpconvert): Renamed this from extendBufferForAppending16. It is different from the other extendBuffer functions because is supports upconverting from LChar to UChar. Like the others it relies on allocateBuffer for the overflow checking. (WTF::StringBuilder::appendCharacters): Removed an unnecessary assertion that the characters pointer is non-null; that will fail in an obvious way without an assertion. Simplified the logic and removed some invariant assertions that don't help us much. Changed overflow checking by using saturatedSum to compute the new length. In overflow cases, the new sum will be larger than the maximum string length, but will fit in an unsigned, so we can pass it down to lower levels and let functions like reallocateBuffer do the actual overflow checking. Also use StringImpl::copyCharacters. (WTF::StringBuilder::append): Removed the CFStringRef overload. (WTF::StringBuilder::shouldShrinkToFit const): Rename this from canShrink. Simplify the function a bit and remove the vague FIXME that says "this should be tuned". That may be so, but the FIXME is not really driving us to action. (WTF::StringBuilder::shrinkToFit): Simplify by using the new reallocateBuffer and std::exchange. Removed unneeded assertion about overflow that doesn't help us maintain the invariant. (WTF::StringBuilder::isAllASCII const): Was tempted to remove this function, but for now just made it use the StringView version for brevity. * wtf/text/StringBuilder.h: Removed many unneeded includes, and notably included SaturatedArithmetic.h instead of CheckedArithmetic.h because we now use the former instead of the latter. Changed the overflow checking implementation to work more simply based on saturated addition rather than Checked. This allowed us to get rid of dependency on our own unique mode for Checked, called ConditionalCrashOnOverflow. Removed a comment about making a templatized version of StringBuilder. We can do it if we like, but does not seem urgent. Moved fucntion bodies out of the class definition so it's easier to see what's going on in the class. Since m_length is now an ordinary integer, the check for overflowed simply checks to see if the length is larger than the maximum string length. When we encounter overflow that is not about length computation, we set the length to the maximum integer to indicate the failure. Deleted the append overloads for CFStringRef and NSString. Removed m_bufferCharacters, m_is8Bit, and m_isReified. (WTF::StringBuilder::StringBuilder): Simplified the constructor since we only have to initialize the m_shouldCrashOnOverflow member. (WTF::StringBuilder::clear): Fixed a mistake where this was not resetting the m_isReified flag. (WTF::StringBuilder::swap): Updated for changes in the data members. (WTF::StringBuilder::operator StringView const): Moved out of line. Made sure to call the length() function so we crash if this is called after overflow. (WTF::StringBuilder::append): Remove some of the unnecessary checks and special cases in the various versions of append. Most of the checking is done inside appendCharacters, with only a few exceptions. (WTF::StringBuilder::appendSubstring): Moved out of the class definition without making significant changes. (WTF::StringBuilder::appendCharacter): Ditto. (WTF::StringBuilder::toString): Greatly simplified this function by relying on overflow checking in the reifyString function instead of doing it here and removing unneeded invariant assertions. (WTF::StringBuilder::toStringPreserveCapacity const): Ditto. (WTF::StringBuilder::toAtomString const): Rewrote this to streamline, removing explicit overflow checks. (WTF::StringBuilder::length const): Moved out of the class definition without making significant changes. (WTF::StringBuilder::capacity const): Ditto. (WTF::StringBuilder::operator[] const): Ditto. (WTF::StringBuilder::characters const): Implemented this operation in the function template. Now rather than having this call the characters8 and characters16 functions, they can call it. (WTF::StringBuilder::getBufferCharacters<LChar>): Deleted. (WTF::StringBuilder::getBufferCharacters<UChar>): Deleted. (WTF::StringBuilder::appendFromAdapters): Use saturatedSum to compute the required length, which allows the extendBuffer functions to do overflow checking without having to take special checked integer types for arguments. (WTF::StringBuilder::equal): Implement using StringView. * wtf/text/StringBuilderJSON.cpp: (WTF::StringBuilder::appendQuotedJSONString): Simplified the checked arithmetic for computing the required capacity. Updated since we removed m_bufferCharacters and changed the type of m_length. * wtf/text/cf/StringConcatenateCF.h: Added. Specializes StringTypeAdapter for both CFStringRef and NSString *. If CFStringGetCStringPtr works for Latin-1, then does the 8-bit code path, otherwise the 16-bit. * wtf/text/cocoa/TextStreamCocoa.mm: Include StringConcatenateCF.h, since it's now needed to use CFStringRef with StringBuilder. Tools: * TestWebKitAPI/Tests/WTF/SaturatedArithmeticOperations.cpp: Updated tests for changes to SaturatedArithmetic.h. * TestWebKitAPI/Tests/WTF/StringBuilder.cpp: Updated tests for changes to StringBuilder. * TestWebKitAPI/Tests/WebKit/GetUserMedia.mm: (TestWebKitAPI::wkMediaCaptureStateString): Ditto. * WebKitTestRunner/InjectedBundle/InjectedBundlePage.cpp: Added include of StringConcatenateCF.h. Added StringTypeAdapter for WKStringRef. (WTR::styleDecToStr): Use ASCIILiteral instead of StringBuilder. (WTR::string): Removed unneeded toWTFString since the WKStringRef StringTypeAdapter takes care of it. (WTR::string): Renamed from frameToStr. Use makeString. (WTR::dumpResourceURL): Use append instead of appendLiteral. (WTR::dumpFrameDescriptionSuitableForTestResult): Deleted. (WTR::dumpLoadEvent): Use makeString. (WTR::string): Renamed from a longer name. Return a String instead of building in a StringBuilder. Use makeString. (WTR::string): Ditto. (WTR::dumpErrorDescriptionSuitableForTestResult): Removed unneeded toWTFString. (WTR::dumpFrameScrollPosition): Ditto. (WTR::dumpDescendantFramesText): Ditto. (WTR::InjectedBundlePage::dumpDOMAsWebArchive): Removed an unneeded local variable. (WTR::InjectedBundlePage::dump): Removed unneeded toWTFString. (WTR::InjectedBundlePage::didReceiveTitleForFrame): Ditto. (WTR::InjectedBundlePage::didFinishDocumentLoadForFrame): Updated for functon name change. (WTR::InjectedBundlePage::willSendRequestForFrame): Ditto. Also use variadic append. Also use makeString. (WTR::InjectedBundlePage::didReceiveResponseForResource): Ditto. (WTR::InjectedBundlePage::didFinishLoadForResource): Ditto. (WTR::InjectedBundlePage::didFailLoadForResource): Ditto. (WTR::InjectedBundlePage::decidePolicyForNavigationAction): Ditto. (WTR::InjectedBundlePage::decidePolicyForResponse): Ditto. (WTR::InjectedBundlePage::willAddMessageToConsole): Ditto. (WTR::InjectedBundlePage::willSetStatusbarText): Ditto. (WTR::InjectedBundlePage::willRunJavaScriptPrompt): Ditto. (WTR::InjectedBundlePage::didExceedDatabaseQuota): Ditto. (WTR::InjectedBundlePage::shouldInsertNode): Ditto. (WTR::InjectedBundlePage::shouldInsertText): Ditto. (WTR::InjectedBundlePage::shouldDeleteRange): Ditto. (WTR::InjectedBundlePage::shouldChangeSelectedRange): Ditto. (WTR::InjectedBundlePage::shouldApplyStyle): Ditto. (WTR::InjectedBundlePage::didBeginEditing): Ditto. (WTR::InjectedBundlePage::didEndEditing): Ditto. (WTR::InjectedBundlePage::didChange): Ditto. (WTR::InjectedBundlePage::didChangeSelection): Ditto. (WTR::InjectedBundlePage::dumpHistory): Ditto. Canonical link: https://commits.webkit.org/237916@main git-svn-id: https://svn.webkit.org/repository/webkit/trunk@277744 268f45cc-cd09-0410-ab3c-d52691b4dbfc
2021-05-19 19:37:21 +00:00
if (signedAddInt32Overflows(a, b, result))
result = std::numeric_limits<int32_t>::max() + (static_cast<uint32_t>(a) >> 31);
#endif
Add saturation arithmetic support to FractionalLayoutUnit https://bugs.webkit.org/show_bug.cgi?id=94364 Reviewed by Benjamin Poulain. Source/WebCore: Add experimental saturation arithmetic support to FractionalLayoutUnit, guarded by a flag. The idea here is to saturate (or clamp) rather than overflow when computing positions and sizes. No new tests for WebCore, not enabled by default. * platform/FractionalLayoutUnit.h: (WebCore::FractionalLayoutUnit::intMinForLayoutUnit): Use INT_MIN instead of -INT_MAX to compute minimum value as the two are not the same. (WebCore::FractionalLayoutUnit::FractionalLayoutUnit): (WebCore::FractionalLayoutUnit::fromFloatCeil): (WebCore::FractionalLayoutUnit::fromFloatFloor): (WebCore::FractionalLayoutUnit::fromFloatRound): (WebCore::FractionalLayoutUnit::setValue): Add range checks. (WebCore::operator*): (WebCore::operator+): (WebCore::operator-): (WebCore::operator+=): (WebCore::operator-=): Use the saturatedAddition and saturatedSubtraction functions, which have been optimized to reduce branching, instead of range checks for the most common operators. Source/WTF: Add support functions for saturated addition and subtraction. Test: TestWebKitAPI/Tests/WTF/SaturatedArithmeticOperations.cpp * GNUmakefile.list.am: * WTF.gypi: * WTF.pro: * WTF.vcproj/WTF.vcproj: * WTF.xcodeproj/project.pbxproj: * WTF/wtf/CMakeLists.txt: Add SaturatedArithmetic.h to build files. * wtf/SaturatedArithmetic.h: Added. (saturatedAddition): (saturatedSubtraction): Support functions for saturated addition/subtraction. Compares the signed bit of the values instead of using range checks to reduce branching. * wtf/Platform.h: Add ENABLE_SATURATED_LAYOUT_ARITHMETIC flag. Tools: Add test for new saturatedArithmetic functions. * TestWebKitAPI/CMakeLists.txt: * TestWebKitAPI/GNUmakefile.am: * TestWebKitAPI/TestWebKitAPI.gypi: * TestWebKitAPI/TestWebKitAPI.xcodeproj/project.pbxproj: * TestWebKitAPI/Tests/WTF/SaturatedArithmeticOperations.cpp: Added. (TestWebKitAPI): (TestWebKitAPI::TEST): * TestWebKitAPI/win/TestWebKitAPI.vcproj: Canonical link: https://commits.webkit.org/112729@main git-svn-id: https://svn.webkit.org/repository/webkit/trunk@126509 268f45cc-cd09-0410-ab3c-d52691b4dbfc
2012-08-24 00:14:00 +00:00
return result;
}
Move CFStringRef and NSString support from StringBuilder into StringConcatenateCF https://bugs.webkit.org/show_bug.cgi?id=225839 Reviewed by Sam Weinig. Source/JavaScriptCore: * inspector/ConsoleMessage.cpp: (Inspector::ConsoleMessage::ConsoleMessage): Use StringBuilder::clear instead of StringBuilder::resize; no advantage to the latter after calling StringBuilder::toString. * runtime/JSONObject.cpp: (JSC::Stringifier::Holder::appendNextProperty): Update for name change of StringBuilder::resize to StringBuilder::shrink. * runtime/TypeSet.cpp: (JSC::StructureShape::stringRepresentation): Ditto. Source/WebCore: * Modules/airplay/WebMediaSessionManager.cpp: (WebCore::mediaProducerStateString): Use StringBuilder exclusively instead of mixing it with makeString. Also updated for StringBuilder::shrink name. * html/HTMLTextFormControlElement.cpp: (WebCore::stripTrailingNewline): Updated for StringBuilder::shrink name. * page/CaptionUserPreferencesMediaAF.cpp: (WebCore::CaptionUserPreferencesMediaAF::captionsTextColor const): Tweaked coding style a bit. (WebCore::appendCSS): Use variadic StringBuilder::append instead of many separate calls. (WebCore::CaptionUserPreferencesMediaAF::captionsDefaultFontCSS const): Tweaked coding style a bit, and use variadic StrinBuilder::append calls to reduce the number of calls and streamline the code. (WebCore::CaptionUserPreferencesMediaAF::captionsStyleSheetOverride const): Ditto. Also removed unnecessary checks that strings are empty before appending. * page/scrolling/ScrollingCoordinator.cpp: (WebCore::ScrollingCoordinator::synchronousScrollingReasonsAsText): Updated for StringBuilder::shrink name. * platform/LayoutUnit.h: Updated for saturatedSum/Difference names. * platform/network/cocoa/NetworkStorageSessionCocoa.mm: (WebCore::NetworkStorageSession::cookiesForSession const): Tweaked codin style a bit, and use variadic StrinBuilder::append calls to reduce the number of calls and streamline the code. * rendering/RenderCounter.cpp: (WebCore::planCounter): Updated for saturatedSum name. * style/StyleBuilderCustom.h: (WebCore::Style::BuilderCustom::applyValueCounter): Ditto. * svg/SVGPathStringBuilder.cpp: (WebCore::SVGPathStringBuilder::result): Updated for StringBuilder::shrink name. * testing/Internals.cpp: (WebCore::Internals::pageMediaState): Ditto. * xml/XSLTProcessorLibxslt.cpp: (WebCore::saveResultToString): Ditto. Source/WebKit: * UIProcess/WebsiteData/Cocoa/WebsiteDataStoreCocoa.mm: (WebKit::WebsiteDataStore::platformSetNetworkParameters): Use makeString instead of StringBuilder. Source/WTF: The new header makes CFStringRef and NSString work with string concatenation, which means it now works with the variadic StringBuilder::append and makeString, and still works with the single-argument StringBuilder::append. More efficient that the old version because it does not allocate a temporary WTF::String for the 16-bit character path. Also made many other small improvements to the StringBuilder implementation. * WTF.xcodeproj/project.pbxproj: Added StringConcatenateCF.h. * wtf/CheckedArithmetic.h: Removed ConditionalCrashOnOverflow, which was only here for use by StringBuilder, which does not use CheckedArithmetic any more. * wtf/PlatformFTW.cmake: Added StringConcatenateCF.h.. * wtf/PlatformMac.cmake: Ditto. * wtf/PlatformWin.cmake: Ditto. * wtf/SaturatedArithmetic.h: Moved the contents of this file inside the WTF namespace. (WTF::signedAddInt32Overflows): Renamed this function. The type here is important, and we are not doing anything to prevent type conversion or create ambiguity, so it's good to be explicit in the function name. (WTF::saturatedSum<int32_t>): Renamed this from saturatedAddition for clarity. The function returns a sum, so that's a better name than calling it "addition". Also, it's clearer to be explicit about the return type. (WTF::signedSubtractInt32Overflows): Renamed. Same reason as above. (WTF::saturatedDifference<int32_t>): Ditto. (WTF::saturatedSum): Added. Does unsigned integer saturated addition. This one can be written in a portable manner and still get really efficient code on at least Intel and ARM64. (WTF::saturatedSum): Added a function template that lets callers pass larger number of arguments to saturatedSum, rather than exactly two. * wtf/text/StringBuilder.cpp: (WTF::expandedCapacity): Renamed to use the term capacity rather than length for the new required capacity. (WTF::StringBuilder::didOverflow): Implement the new approach to overflow, meaning we need to write the CRASH() here explicitly and in the non-crashing mode, set m_length. (WTF::StringBuilder::reifyString const): Changed the overflow check into a RELEASE_ASSERT. This is now responsible for doing the check that callers were doing earlier, so we want it in production builds. Also simplified this since our m_length member is a simple integer now, and removed the unused m_isReified. (WTF::StringBuilder::shrink): Renamed this to shrink to match the Vector::shrink function, since this has never supported making the builder larger. Removed unnecessary overflow checks, since shrinking cannot cause overflow. (WTF::StringBuilder::allocateBuffer): Replaced two separate functions with a single simpler function template. Removed extra overflow checks because the StringImpl::tryCreateUninitialized function already does the only overflow check we need. Also move to StringImpl::copyCharacters for copying characters rather than using std::memcpy directly. Removed code to set m_is8Bit and m_bufferCharacters. (WTF::StringBuilder::reallocateBuffer): Replaced two separate functions with a function template and a cover that calls the appropriate instance of the template for places where we aren't already in character-type-specific code paths. This version now supports allocating a buffer for the first time in cases where we have m_string and not m_buffer, which used to be handled at the higher level. Removed code to set m_bufferCharacters. (WTF::StringBuilder::reserveCapacity): Rewrote for simplicity. By relying on the overflow checking inside reallocateBuffer and allocateBuffer we no longer need checking of the passed-in value at this level. (WTF::StringBuilder::extendBufferForAppending): Removed the version of this that takes additionalLength since it's potentially confusing to have a family of functions that have the same name and take the same type of argument, but interpret it subtly differently. Streamlined the code using std::exchange. This function now also includes the logic from the function named extendBufferForAppendingWithoutOverflowCheck, which was subtly misnamed since that was not the only semantic difference. Also removed the ALWAYS_INLINE because the compiler will do the right thing without such heavy handed advice. (WTF::StringBuilder::extendBufferForAppendingSlowCase): Streamlined this by using std::exchange and removed additional overflow checks at this level since reallocateBuffer already does them. Also added a check for the case where the new total length is 0, which would not be handled correctly and efficiently by reallocateBuffer. (WTF::StringBuilder::extendBufferForAppendingLChar): Renamed this from extendBufferForAppending8, since it's now identical to calling extendBufferForAppending<LChar>, except for inlining and linkage. (WTF::StringBuilder::extendBufferForAppendingWithUpconvert): Renamed this from extendBufferForAppending16. It is different from the other extendBuffer functions because is supports upconverting from LChar to UChar. Like the others it relies on allocateBuffer for the overflow checking. (WTF::StringBuilder::appendCharacters): Removed an unnecessary assertion that the characters pointer is non-null; that will fail in an obvious way without an assertion. Simplified the logic and removed some invariant assertions that don't help us much. Changed overflow checking by using saturatedSum to compute the new length. In overflow cases, the new sum will be larger than the maximum string length, but will fit in an unsigned, so we can pass it down to lower levels and let functions like reallocateBuffer do the actual overflow checking. Also use StringImpl::copyCharacters. (WTF::StringBuilder::append): Removed the CFStringRef overload. (WTF::StringBuilder::shouldShrinkToFit const): Rename this from canShrink. Simplify the function a bit and remove the vague FIXME that says "this should be tuned". That may be so, but the FIXME is not really driving us to action. (WTF::StringBuilder::shrinkToFit): Simplify by using the new reallocateBuffer and std::exchange. Removed unneeded assertion about overflow that doesn't help us maintain the invariant. (WTF::StringBuilder::isAllASCII const): Was tempted to remove this function, but for now just made it use the StringView version for brevity. * wtf/text/StringBuilder.h: Removed many unneeded includes, and notably included SaturatedArithmetic.h instead of CheckedArithmetic.h because we now use the former instead of the latter. Changed the overflow checking implementation to work more simply based on saturated addition rather than Checked. This allowed us to get rid of dependency on our own unique mode for Checked, called ConditionalCrashOnOverflow. Removed a comment about making a templatized version of StringBuilder. We can do it if we like, but does not seem urgent. Moved fucntion bodies out of the class definition so it's easier to see what's going on in the class. Since m_length is now an ordinary integer, the check for overflowed simply checks to see if the length is larger than the maximum string length. When we encounter overflow that is not about length computation, we set the length to the maximum integer to indicate the failure. Deleted the append overloads for CFStringRef and NSString. Removed m_bufferCharacters, m_is8Bit, and m_isReified. (WTF::StringBuilder::StringBuilder): Simplified the constructor since we only have to initialize the m_shouldCrashOnOverflow member. (WTF::StringBuilder::clear): Fixed a mistake where this was not resetting the m_isReified flag. (WTF::StringBuilder::swap): Updated for changes in the data members. (WTF::StringBuilder::operator StringView const): Moved out of line. Made sure to call the length() function so we crash if this is called after overflow. (WTF::StringBuilder::append): Remove some of the unnecessary checks and special cases in the various versions of append. Most of the checking is done inside appendCharacters, with only a few exceptions. (WTF::StringBuilder::appendSubstring): Moved out of the class definition without making significant changes. (WTF::StringBuilder::appendCharacter): Ditto. (WTF::StringBuilder::toString): Greatly simplified this function by relying on overflow checking in the reifyString function instead of doing it here and removing unneeded invariant assertions. (WTF::StringBuilder::toStringPreserveCapacity const): Ditto. (WTF::StringBuilder::toAtomString const): Rewrote this to streamline, removing explicit overflow checks. (WTF::StringBuilder::length const): Moved out of the class definition without making significant changes. (WTF::StringBuilder::capacity const): Ditto. (WTF::StringBuilder::operator[] const): Ditto. (WTF::StringBuilder::characters const): Implemented this operation in the function template. Now rather than having this call the characters8 and characters16 functions, they can call it. (WTF::StringBuilder::getBufferCharacters<LChar>): Deleted. (WTF::StringBuilder::getBufferCharacters<UChar>): Deleted. (WTF::StringBuilder::appendFromAdapters): Use saturatedSum to compute the required length, which allows the extendBuffer functions to do overflow checking without having to take special checked integer types for arguments. (WTF::StringBuilder::equal): Implement using StringView. * wtf/text/StringBuilderJSON.cpp: (WTF::StringBuilder::appendQuotedJSONString): Simplified the checked arithmetic for computing the required capacity. Updated since we removed m_bufferCharacters and changed the type of m_length. * wtf/text/cf/StringConcatenateCF.h: Added. Specializes StringTypeAdapter for both CFStringRef and NSString *. If CFStringGetCStringPtr works for Latin-1, then does the 8-bit code path, otherwise the 16-bit. * wtf/text/cocoa/TextStreamCocoa.mm: Include StringConcatenateCF.h, since it's now needed to use CFStringRef with StringBuilder. Tools: * TestWebKitAPI/Tests/WTF/SaturatedArithmeticOperations.cpp: Updated tests for changes to SaturatedArithmetic.h. * TestWebKitAPI/Tests/WTF/StringBuilder.cpp: Updated tests for changes to StringBuilder. * TestWebKitAPI/Tests/WebKit/GetUserMedia.mm: (TestWebKitAPI::wkMediaCaptureStateString): Ditto. * WebKitTestRunner/InjectedBundle/InjectedBundlePage.cpp: Added include of StringConcatenateCF.h. Added StringTypeAdapter for WKStringRef. (WTR::styleDecToStr): Use ASCIILiteral instead of StringBuilder. (WTR::string): Removed unneeded toWTFString since the WKStringRef StringTypeAdapter takes care of it. (WTR::string): Renamed from frameToStr. Use makeString. (WTR::dumpResourceURL): Use append instead of appendLiteral. (WTR::dumpFrameDescriptionSuitableForTestResult): Deleted. (WTR::dumpLoadEvent): Use makeString. (WTR::string): Renamed from a longer name. Return a String instead of building in a StringBuilder. Use makeString. (WTR::string): Ditto. (WTR::dumpErrorDescriptionSuitableForTestResult): Removed unneeded toWTFString. (WTR::dumpFrameScrollPosition): Ditto. (WTR::dumpDescendantFramesText): Ditto. (WTR::InjectedBundlePage::dumpDOMAsWebArchive): Removed an unneeded local variable. (WTR::InjectedBundlePage::dump): Removed unneeded toWTFString. (WTR::InjectedBundlePage::didReceiveTitleForFrame): Ditto. (WTR::InjectedBundlePage::didFinishDocumentLoadForFrame): Updated for functon name change. (WTR::InjectedBundlePage::willSendRequestForFrame): Ditto. Also use variadic append. Also use makeString. (WTR::InjectedBundlePage::didReceiveResponseForResource): Ditto. (WTR::InjectedBundlePage::didFinishLoadForResource): Ditto. (WTR::InjectedBundlePage::didFailLoadForResource): Ditto. (WTR::InjectedBundlePage::decidePolicyForNavigationAction): Ditto. (WTR::InjectedBundlePage::decidePolicyForResponse): Ditto. (WTR::InjectedBundlePage::willAddMessageToConsole): Ditto. (WTR::InjectedBundlePage::willSetStatusbarText): Ditto. (WTR::InjectedBundlePage::willRunJavaScriptPrompt): Ditto. (WTR::InjectedBundlePage::didExceedDatabaseQuota): Ditto. (WTR::InjectedBundlePage::shouldInsertNode): Ditto. (WTR::InjectedBundlePage::shouldInsertText): Ditto. (WTR::InjectedBundlePage::shouldDeleteRange): Ditto. (WTR::InjectedBundlePage::shouldChangeSelectedRange): Ditto. (WTR::InjectedBundlePage::shouldApplyStyle): Ditto. (WTR::InjectedBundlePage::didBeginEditing): Ditto. (WTR::InjectedBundlePage::didEndEditing): Ditto. (WTR::InjectedBundlePage::didChange): Ditto. (WTR::InjectedBundlePage::didChangeSelection): Ditto. (WTR::InjectedBundlePage::dumpHistory): Ditto. Canonical link: https://commits.webkit.org/237916@main git-svn-id: https://svn.webkit.org/repository/webkit/trunk@277744 268f45cc-cd09-0410-ab3c-d52691b4dbfc
2021-05-19 19:37:21 +00:00
inline bool signedSubtractInt32Overflows(int32_t a, int32_t b, int32_t& result)
Add saturation arithmetic support to FractionalLayoutUnit https://bugs.webkit.org/show_bug.cgi?id=94364 Reviewed by Benjamin Poulain. Source/WebCore: Add experimental saturation arithmetic support to FractionalLayoutUnit, guarded by a flag. The idea here is to saturate (or clamp) rather than overflow when computing positions and sizes. No new tests for WebCore, not enabled by default. * platform/FractionalLayoutUnit.h: (WebCore::FractionalLayoutUnit::intMinForLayoutUnit): Use INT_MIN instead of -INT_MAX to compute minimum value as the two are not the same. (WebCore::FractionalLayoutUnit::FractionalLayoutUnit): (WebCore::FractionalLayoutUnit::fromFloatCeil): (WebCore::FractionalLayoutUnit::fromFloatFloor): (WebCore::FractionalLayoutUnit::fromFloatRound): (WebCore::FractionalLayoutUnit::setValue): Add range checks. (WebCore::operator*): (WebCore::operator+): (WebCore::operator-): (WebCore::operator+=): (WebCore::operator-=): Use the saturatedAddition and saturatedSubtraction functions, which have been optimized to reduce branching, instead of range checks for the most common operators. Source/WTF: Add support functions for saturated addition and subtraction. Test: TestWebKitAPI/Tests/WTF/SaturatedArithmeticOperations.cpp * GNUmakefile.list.am: * WTF.gypi: * WTF.pro: * WTF.vcproj/WTF.vcproj: * WTF.xcodeproj/project.pbxproj: * WTF/wtf/CMakeLists.txt: Add SaturatedArithmetic.h to build files. * wtf/SaturatedArithmetic.h: Added. (saturatedAddition): (saturatedSubtraction): Support functions for saturated addition/subtraction. Compares the signed bit of the values instead of using range checks to reduce branching. * wtf/Platform.h: Add ENABLE_SATURATED_LAYOUT_ARITHMETIC flag. Tools: Add test for new saturatedArithmetic functions. * TestWebKitAPI/CMakeLists.txt: * TestWebKitAPI/GNUmakefile.am: * TestWebKitAPI/TestWebKitAPI.gypi: * TestWebKitAPI/TestWebKitAPI.xcodeproj/project.pbxproj: * TestWebKitAPI/Tests/WTF/SaturatedArithmeticOperations.cpp: Added. (TestWebKitAPI): (TestWebKitAPI::TEST): * TestWebKitAPI/win/TestWebKitAPI.vcproj: Canonical link: https://commits.webkit.org/112729@main git-svn-id: https://svn.webkit.org/repository/webkit/trunk@126509 268f45cc-cd09-0410-ab3c-d52691b4dbfc
2012-08-24 00:14:00 +00:00
{
#if COMPILER_HAS_CLANG_BUILTIN(__builtin_ssub_overflow) && !(defined __clang_major__ && __clang_major__ < 7)
return __builtin_ssub_overflow(a, b, &result);
#else
Add saturation arithmetic support to FractionalLayoutUnit https://bugs.webkit.org/show_bug.cgi?id=94364 Reviewed by Benjamin Poulain. Source/WebCore: Add experimental saturation arithmetic support to FractionalLayoutUnit, guarded by a flag. The idea here is to saturate (or clamp) rather than overflow when computing positions and sizes. No new tests for WebCore, not enabled by default. * platform/FractionalLayoutUnit.h: (WebCore::FractionalLayoutUnit::intMinForLayoutUnit): Use INT_MIN instead of -INT_MAX to compute minimum value as the two are not the same. (WebCore::FractionalLayoutUnit::FractionalLayoutUnit): (WebCore::FractionalLayoutUnit::fromFloatCeil): (WebCore::FractionalLayoutUnit::fromFloatFloor): (WebCore::FractionalLayoutUnit::fromFloatRound): (WebCore::FractionalLayoutUnit::setValue): Add range checks. (WebCore::operator*): (WebCore::operator+): (WebCore::operator-): (WebCore::operator+=): (WebCore::operator-=): Use the saturatedAddition and saturatedSubtraction functions, which have been optimized to reduce branching, instead of range checks for the most common operators. Source/WTF: Add support functions for saturated addition and subtraction. Test: TestWebKitAPI/Tests/WTF/SaturatedArithmeticOperations.cpp * GNUmakefile.list.am: * WTF.gypi: * WTF.pro: * WTF.vcproj/WTF.vcproj: * WTF.xcodeproj/project.pbxproj: * WTF/wtf/CMakeLists.txt: Add SaturatedArithmetic.h to build files. * wtf/SaturatedArithmetic.h: Added. (saturatedAddition): (saturatedSubtraction): Support functions for saturated addition/subtraction. Compares the signed bit of the values instead of using range checks to reduce branching. * wtf/Platform.h: Add ENABLE_SATURATED_LAYOUT_ARITHMETIC flag. Tools: Add test for new saturatedArithmetic functions. * TestWebKitAPI/CMakeLists.txt: * TestWebKitAPI/GNUmakefile.am: * TestWebKitAPI/TestWebKitAPI.gypi: * TestWebKitAPI/TestWebKitAPI.xcodeproj/project.pbxproj: * TestWebKitAPI/Tests/WTF/SaturatedArithmeticOperations.cpp: Added. (TestWebKitAPI): (TestWebKitAPI::TEST): * TestWebKitAPI/win/TestWebKitAPI.vcproj: Canonical link: https://commits.webkit.org/112729@main git-svn-id: https://svn.webkit.org/repository/webkit/trunk@126509 268f45cc-cd09-0410-ab3c-d52691b4dbfc
2012-08-24 00:14:00 +00:00
uint32_t ua = a;
uint32_t ub = b;
uint32_t uresult = ua - ub;
result = static_cast<int32_t>(uresult);
Add saturation arithmetic support to FractionalLayoutUnit https://bugs.webkit.org/show_bug.cgi?id=94364 Reviewed by Benjamin Poulain. Source/WebCore: Add experimental saturation arithmetic support to FractionalLayoutUnit, guarded by a flag. The idea here is to saturate (or clamp) rather than overflow when computing positions and sizes. No new tests for WebCore, not enabled by default. * platform/FractionalLayoutUnit.h: (WebCore::FractionalLayoutUnit::intMinForLayoutUnit): Use INT_MIN instead of -INT_MAX to compute minimum value as the two are not the same. (WebCore::FractionalLayoutUnit::FractionalLayoutUnit): (WebCore::FractionalLayoutUnit::fromFloatCeil): (WebCore::FractionalLayoutUnit::fromFloatFloor): (WebCore::FractionalLayoutUnit::fromFloatRound): (WebCore::FractionalLayoutUnit::setValue): Add range checks. (WebCore::operator*): (WebCore::operator+): (WebCore::operator-): (WebCore::operator+=): (WebCore::operator-=): Use the saturatedAddition and saturatedSubtraction functions, which have been optimized to reduce branching, instead of range checks for the most common operators. Source/WTF: Add support functions for saturated addition and subtraction. Test: TestWebKitAPI/Tests/WTF/SaturatedArithmeticOperations.cpp * GNUmakefile.list.am: * WTF.gypi: * WTF.pro: * WTF.vcproj/WTF.vcproj: * WTF.xcodeproj/project.pbxproj: * WTF/wtf/CMakeLists.txt: Add SaturatedArithmetic.h to build files. * wtf/SaturatedArithmetic.h: Added. (saturatedAddition): (saturatedSubtraction): Support functions for saturated addition/subtraction. Compares the signed bit of the values instead of using range checks to reduce branching. * wtf/Platform.h: Add ENABLE_SATURATED_LAYOUT_ARITHMETIC flag. Tools: Add test for new saturatedArithmetic functions. * TestWebKitAPI/CMakeLists.txt: * TestWebKitAPI/GNUmakefile.am: * TestWebKitAPI/TestWebKitAPI.gypi: * TestWebKitAPI/TestWebKitAPI.xcodeproj/project.pbxproj: * TestWebKitAPI/Tests/WTF/SaturatedArithmeticOperations.cpp: Added. (TestWebKitAPI): (TestWebKitAPI::TEST): * TestWebKitAPI/win/TestWebKitAPI.vcproj: Canonical link: https://commits.webkit.org/112729@main git-svn-id: https://svn.webkit.org/repository/webkit/trunk@126509 268f45cc-cd09-0410-ab3c-d52691b4dbfc
2012-08-24 00:14:00 +00:00
// Can only overflow if the signed bit of the two values do not match. If the
// signed bit of the result and the first value differ it did overflow.
return (ua ^ ub) >> 31 && (uresult ^ ua) >> 31;
#endif
}
Add saturation arithmetic support to FractionalLayoutUnit https://bugs.webkit.org/show_bug.cgi?id=94364 Reviewed by Benjamin Poulain. Source/WebCore: Add experimental saturation arithmetic support to FractionalLayoutUnit, guarded by a flag. The idea here is to saturate (or clamp) rather than overflow when computing positions and sizes. No new tests for WebCore, not enabled by default. * platform/FractionalLayoutUnit.h: (WebCore::FractionalLayoutUnit::intMinForLayoutUnit): Use INT_MIN instead of -INT_MAX to compute minimum value as the two are not the same. (WebCore::FractionalLayoutUnit::FractionalLayoutUnit): (WebCore::FractionalLayoutUnit::fromFloatCeil): (WebCore::FractionalLayoutUnit::fromFloatFloor): (WebCore::FractionalLayoutUnit::fromFloatRound): (WebCore::FractionalLayoutUnit::setValue): Add range checks. (WebCore::operator*): (WebCore::operator+): (WebCore::operator-): (WebCore::operator+=): (WebCore::operator-=): Use the saturatedAddition and saturatedSubtraction functions, which have been optimized to reduce branching, instead of range checks for the most common operators. Source/WTF: Add support functions for saturated addition and subtraction. Test: TestWebKitAPI/Tests/WTF/SaturatedArithmeticOperations.cpp * GNUmakefile.list.am: * WTF.gypi: * WTF.pro: * WTF.vcproj/WTF.vcproj: * WTF.xcodeproj/project.pbxproj: * WTF/wtf/CMakeLists.txt: Add SaturatedArithmetic.h to build files. * wtf/SaturatedArithmetic.h: Added. (saturatedAddition): (saturatedSubtraction): Support functions for saturated addition/subtraction. Compares the signed bit of the values instead of using range checks to reduce branching. * wtf/Platform.h: Add ENABLE_SATURATED_LAYOUT_ARITHMETIC flag. Tools: Add test for new saturatedArithmetic functions. * TestWebKitAPI/CMakeLists.txt: * TestWebKitAPI/GNUmakefile.am: * TestWebKitAPI/TestWebKitAPI.gypi: * TestWebKitAPI/TestWebKitAPI.xcodeproj/project.pbxproj: * TestWebKitAPI/Tests/WTF/SaturatedArithmeticOperations.cpp: Added. (TestWebKitAPI): (TestWebKitAPI::TEST): * TestWebKitAPI/win/TestWebKitAPI.vcproj: Canonical link: https://commits.webkit.org/112729@main git-svn-id: https://svn.webkit.org/repository/webkit/trunk@126509 268f45cc-cd09-0410-ab3c-d52691b4dbfc
2012-08-24 00:14:00 +00:00
Move CFStringRef and NSString support from StringBuilder into StringConcatenateCF https://bugs.webkit.org/show_bug.cgi?id=225839 Reviewed by Sam Weinig. Source/JavaScriptCore: * inspector/ConsoleMessage.cpp: (Inspector::ConsoleMessage::ConsoleMessage): Use StringBuilder::clear instead of StringBuilder::resize; no advantage to the latter after calling StringBuilder::toString. * runtime/JSONObject.cpp: (JSC::Stringifier::Holder::appendNextProperty): Update for name change of StringBuilder::resize to StringBuilder::shrink. * runtime/TypeSet.cpp: (JSC::StructureShape::stringRepresentation): Ditto. Source/WebCore: * Modules/airplay/WebMediaSessionManager.cpp: (WebCore::mediaProducerStateString): Use StringBuilder exclusively instead of mixing it with makeString. Also updated for StringBuilder::shrink name. * html/HTMLTextFormControlElement.cpp: (WebCore::stripTrailingNewline): Updated for StringBuilder::shrink name. * page/CaptionUserPreferencesMediaAF.cpp: (WebCore::CaptionUserPreferencesMediaAF::captionsTextColor const): Tweaked coding style a bit. (WebCore::appendCSS): Use variadic StringBuilder::append instead of many separate calls. (WebCore::CaptionUserPreferencesMediaAF::captionsDefaultFontCSS const): Tweaked coding style a bit, and use variadic StrinBuilder::append calls to reduce the number of calls and streamline the code. (WebCore::CaptionUserPreferencesMediaAF::captionsStyleSheetOverride const): Ditto. Also removed unnecessary checks that strings are empty before appending. * page/scrolling/ScrollingCoordinator.cpp: (WebCore::ScrollingCoordinator::synchronousScrollingReasonsAsText): Updated for StringBuilder::shrink name. * platform/LayoutUnit.h: Updated for saturatedSum/Difference names. * platform/network/cocoa/NetworkStorageSessionCocoa.mm: (WebCore::NetworkStorageSession::cookiesForSession const): Tweaked codin style a bit, and use variadic StrinBuilder::append calls to reduce the number of calls and streamline the code. * rendering/RenderCounter.cpp: (WebCore::planCounter): Updated for saturatedSum name. * style/StyleBuilderCustom.h: (WebCore::Style::BuilderCustom::applyValueCounter): Ditto. * svg/SVGPathStringBuilder.cpp: (WebCore::SVGPathStringBuilder::result): Updated for StringBuilder::shrink name. * testing/Internals.cpp: (WebCore::Internals::pageMediaState): Ditto. * xml/XSLTProcessorLibxslt.cpp: (WebCore::saveResultToString): Ditto. Source/WebKit: * UIProcess/WebsiteData/Cocoa/WebsiteDataStoreCocoa.mm: (WebKit::WebsiteDataStore::platformSetNetworkParameters): Use makeString instead of StringBuilder. Source/WTF: The new header makes CFStringRef and NSString work with string concatenation, which means it now works with the variadic StringBuilder::append and makeString, and still works with the single-argument StringBuilder::append. More efficient that the old version because it does not allocate a temporary WTF::String for the 16-bit character path. Also made many other small improvements to the StringBuilder implementation. * WTF.xcodeproj/project.pbxproj: Added StringConcatenateCF.h. * wtf/CheckedArithmetic.h: Removed ConditionalCrashOnOverflow, which was only here for use by StringBuilder, which does not use CheckedArithmetic any more. * wtf/PlatformFTW.cmake: Added StringConcatenateCF.h.. * wtf/PlatformMac.cmake: Ditto. * wtf/PlatformWin.cmake: Ditto. * wtf/SaturatedArithmetic.h: Moved the contents of this file inside the WTF namespace. (WTF::signedAddInt32Overflows): Renamed this function. The type here is important, and we are not doing anything to prevent type conversion or create ambiguity, so it's good to be explicit in the function name. (WTF::saturatedSum<int32_t>): Renamed this from saturatedAddition for clarity. The function returns a sum, so that's a better name than calling it "addition". Also, it's clearer to be explicit about the return type. (WTF::signedSubtractInt32Overflows): Renamed. Same reason as above. (WTF::saturatedDifference<int32_t>): Ditto. (WTF::saturatedSum): Added. Does unsigned integer saturated addition. This one can be written in a portable manner and still get really efficient code on at least Intel and ARM64. (WTF::saturatedSum): Added a function template that lets callers pass larger number of arguments to saturatedSum, rather than exactly two. * wtf/text/StringBuilder.cpp: (WTF::expandedCapacity): Renamed to use the term capacity rather than length for the new required capacity. (WTF::StringBuilder::didOverflow): Implement the new approach to overflow, meaning we need to write the CRASH() here explicitly and in the non-crashing mode, set m_length. (WTF::StringBuilder::reifyString const): Changed the overflow check into a RELEASE_ASSERT. This is now responsible for doing the check that callers were doing earlier, so we want it in production builds. Also simplified this since our m_length member is a simple integer now, and removed the unused m_isReified. (WTF::StringBuilder::shrink): Renamed this to shrink to match the Vector::shrink function, since this has never supported making the builder larger. Removed unnecessary overflow checks, since shrinking cannot cause overflow. (WTF::StringBuilder::allocateBuffer): Replaced two separate functions with a single simpler function template. Removed extra overflow checks because the StringImpl::tryCreateUninitialized function already does the only overflow check we need. Also move to StringImpl::copyCharacters for copying characters rather than using std::memcpy directly. Removed code to set m_is8Bit and m_bufferCharacters. (WTF::StringBuilder::reallocateBuffer): Replaced two separate functions with a function template and a cover that calls the appropriate instance of the template for places where we aren't already in character-type-specific code paths. This version now supports allocating a buffer for the first time in cases where we have m_string and not m_buffer, which used to be handled at the higher level. Removed code to set m_bufferCharacters. (WTF::StringBuilder::reserveCapacity): Rewrote for simplicity. By relying on the overflow checking inside reallocateBuffer and allocateBuffer we no longer need checking of the passed-in value at this level. (WTF::StringBuilder::extendBufferForAppending): Removed the version of this that takes additionalLength since it's potentially confusing to have a family of functions that have the same name and take the same type of argument, but interpret it subtly differently. Streamlined the code using std::exchange. This function now also includes the logic from the function named extendBufferForAppendingWithoutOverflowCheck, which was subtly misnamed since that was not the only semantic difference. Also removed the ALWAYS_INLINE because the compiler will do the right thing without such heavy handed advice. (WTF::StringBuilder::extendBufferForAppendingSlowCase): Streamlined this by using std::exchange and removed additional overflow checks at this level since reallocateBuffer already does them. Also added a check for the case where the new total length is 0, which would not be handled correctly and efficiently by reallocateBuffer. (WTF::StringBuilder::extendBufferForAppendingLChar): Renamed this from extendBufferForAppending8, since it's now identical to calling extendBufferForAppending<LChar>, except for inlining and linkage. (WTF::StringBuilder::extendBufferForAppendingWithUpconvert): Renamed this from extendBufferForAppending16. It is different from the other extendBuffer functions because is supports upconverting from LChar to UChar. Like the others it relies on allocateBuffer for the overflow checking. (WTF::StringBuilder::appendCharacters): Removed an unnecessary assertion that the characters pointer is non-null; that will fail in an obvious way without an assertion. Simplified the logic and removed some invariant assertions that don't help us much. Changed overflow checking by using saturatedSum to compute the new length. In overflow cases, the new sum will be larger than the maximum string length, but will fit in an unsigned, so we can pass it down to lower levels and let functions like reallocateBuffer do the actual overflow checking. Also use StringImpl::copyCharacters. (WTF::StringBuilder::append): Removed the CFStringRef overload. (WTF::StringBuilder::shouldShrinkToFit const): Rename this from canShrink. Simplify the function a bit and remove the vague FIXME that says "this should be tuned". That may be so, but the FIXME is not really driving us to action. (WTF::StringBuilder::shrinkToFit): Simplify by using the new reallocateBuffer and std::exchange. Removed unneeded assertion about overflow that doesn't help us maintain the invariant. (WTF::StringBuilder::isAllASCII const): Was tempted to remove this function, but for now just made it use the StringView version for brevity. * wtf/text/StringBuilder.h: Removed many unneeded includes, and notably included SaturatedArithmetic.h instead of CheckedArithmetic.h because we now use the former instead of the latter. Changed the overflow checking implementation to work more simply based on saturated addition rather than Checked. This allowed us to get rid of dependency on our own unique mode for Checked, called ConditionalCrashOnOverflow. Removed a comment about making a templatized version of StringBuilder. We can do it if we like, but does not seem urgent. Moved fucntion bodies out of the class definition so it's easier to see what's going on in the class. Since m_length is now an ordinary integer, the check for overflowed simply checks to see if the length is larger than the maximum string length. When we encounter overflow that is not about length computation, we set the length to the maximum integer to indicate the failure. Deleted the append overloads for CFStringRef and NSString. Removed m_bufferCharacters, m_is8Bit, and m_isReified. (WTF::StringBuilder::StringBuilder): Simplified the constructor since we only have to initialize the m_shouldCrashOnOverflow member. (WTF::StringBuilder::clear): Fixed a mistake where this was not resetting the m_isReified flag. (WTF::StringBuilder::swap): Updated for changes in the data members. (WTF::StringBuilder::operator StringView const): Moved out of line. Made sure to call the length() function so we crash if this is called after overflow. (WTF::StringBuilder::append): Remove some of the unnecessary checks and special cases in the various versions of append. Most of the checking is done inside appendCharacters, with only a few exceptions. (WTF::StringBuilder::appendSubstring): Moved out of the class definition without making significant changes. (WTF::StringBuilder::appendCharacter): Ditto. (WTF::StringBuilder::toString): Greatly simplified this function by relying on overflow checking in the reifyString function instead of doing it here and removing unneeded invariant assertions. (WTF::StringBuilder::toStringPreserveCapacity const): Ditto. (WTF::StringBuilder::toAtomString const): Rewrote this to streamline, removing explicit overflow checks. (WTF::StringBuilder::length const): Moved out of the class definition without making significant changes. (WTF::StringBuilder::capacity const): Ditto. (WTF::StringBuilder::operator[] const): Ditto. (WTF::StringBuilder::characters const): Implemented this operation in the function template. Now rather than having this call the characters8 and characters16 functions, they can call it. (WTF::StringBuilder::getBufferCharacters<LChar>): Deleted. (WTF::StringBuilder::getBufferCharacters<UChar>): Deleted. (WTF::StringBuilder::appendFromAdapters): Use saturatedSum to compute the required length, which allows the extendBuffer functions to do overflow checking without having to take special checked integer types for arguments. (WTF::StringBuilder::equal): Implement using StringView. * wtf/text/StringBuilderJSON.cpp: (WTF::StringBuilder::appendQuotedJSONString): Simplified the checked arithmetic for computing the required capacity. Updated since we removed m_bufferCharacters and changed the type of m_length. * wtf/text/cf/StringConcatenateCF.h: Added. Specializes StringTypeAdapter for both CFStringRef and NSString *. If CFStringGetCStringPtr works for Latin-1, then does the 8-bit code path, otherwise the 16-bit. * wtf/text/cocoa/TextStreamCocoa.mm: Include StringConcatenateCF.h, since it's now needed to use CFStringRef with StringBuilder. Tools: * TestWebKitAPI/Tests/WTF/SaturatedArithmeticOperations.cpp: Updated tests for changes to SaturatedArithmetic.h. * TestWebKitAPI/Tests/WTF/StringBuilder.cpp: Updated tests for changes to StringBuilder. * TestWebKitAPI/Tests/WebKit/GetUserMedia.mm: (TestWebKitAPI::wkMediaCaptureStateString): Ditto. * WebKitTestRunner/InjectedBundle/InjectedBundlePage.cpp: Added include of StringConcatenateCF.h. Added StringTypeAdapter for WKStringRef. (WTR::styleDecToStr): Use ASCIILiteral instead of StringBuilder. (WTR::string): Removed unneeded toWTFString since the WKStringRef StringTypeAdapter takes care of it. (WTR::string): Renamed from frameToStr. Use makeString. (WTR::dumpResourceURL): Use append instead of appendLiteral. (WTR::dumpFrameDescriptionSuitableForTestResult): Deleted. (WTR::dumpLoadEvent): Use makeString. (WTR::string): Renamed from a longer name. Return a String instead of building in a StringBuilder. Use makeString. (WTR::string): Ditto. (WTR::dumpErrorDescriptionSuitableForTestResult): Removed unneeded toWTFString. (WTR::dumpFrameScrollPosition): Ditto. (WTR::dumpDescendantFramesText): Ditto. (WTR::InjectedBundlePage::dumpDOMAsWebArchive): Removed an unneeded local variable. (WTR::InjectedBundlePage::dump): Removed unneeded toWTFString. (WTR::InjectedBundlePage::didReceiveTitleForFrame): Ditto. (WTR::InjectedBundlePage::didFinishDocumentLoadForFrame): Updated for functon name change. (WTR::InjectedBundlePage::willSendRequestForFrame): Ditto. Also use variadic append. Also use makeString. (WTR::InjectedBundlePage::didReceiveResponseForResource): Ditto. (WTR::InjectedBundlePage::didFinishLoadForResource): Ditto. (WTR::InjectedBundlePage::didFailLoadForResource): Ditto. (WTR::InjectedBundlePage::decidePolicyForNavigationAction): Ditto. (WTR::InjectedBundlePage::decidePolicyForResponse): Ditto. (WTR::InjectedBundlePage::willAddMessageToConsole): Ditto. (WTR::InjectedBundlePage::willSetStatusbarText): Ditto. (WTR::InjectedBundlePage::willRunJavaScriptPrompt): Ditto. (WTR::InjectedBundlePage::didExceedDatabaseQuota): Ditto. (WTR::InjectedBundlePage::shouldInsertNode): Ditto. (WTR::InjectedBundlePage::shouldInsertText): Ditto. (WTR::InjectedBundlePage::shouldDeleteRange): Ditto. (WTR::InjectedBundlePage::shouldChangeSelectedRange): Ditto. (WTR::InjectedBundlePage::shouldApplyStyle): Ditto. (WTR::InjectedBundlePage::didBeginEditing): Ditto. (WTR::InjectedBundlePage::didEndEditing): Ditto. (WTR::InjectedBundlePage::didChange): Ditto. (WTR::InjectedBundlePage::didChangeSelection): Ditto. (WTR::InjectedBundlePage::dumpHistory): Ditto. Canonical link: https://commits.webkit.org/237916@main git-svn-id: https://svn.webkit.org/repository/webkit/trunk@277744 268f45cc-cd09-0410-ab3c-d52691b4dbfc
2021-05-19 19:37:21 +00:00
// FIXME: Enhance this so it fails to compile calls where either of the arguments can be outside the range of int32_t instead of quietly converting.
template<> inline int32_t saturatedDifference<int32_t>(int32_t a, int32_t b)
{
int32_t result;
#if CPU(ARM_THUMB2)
asm("qsub %[difference], %[minuend], %[subtrahend]"
: [difference]"=r"(result)
: [minuend]"r"(a), [subtrahend]"r"(b)
: /* Nothing is clobbered. */
);
#else
Move CFStringRef and NSString support from StringBuilder into StringConcatenateCF https://bugs.webkit.org/show_bug.cgi?id=225839 Reviewed by Sam Weinig. Source/JavaScriptCore: * inspector/ConsoleMessage.cpp: (Inspector::ConsoleMessage::ConsoleMessage): Use StringBuilder::clear instead of StringBuilder::resize; no advantage to the latter after calling StringBuilder::toString. * runtime/JSONObject.cpp: (JSC::Stringifier::Holder::appendNextProperty): Update for name change of StringBuilder::resize to StringBuilder::shrink. * runtime/TypeSet.cpp: (JSC::StructureShape::stringRepresentation): Ditto. Source/WebCore: * Modules/airplay/WebMediaSessionManager.cpp: (WebCore::mediaProducerStateString): Use StringBuilder exclusively instead of mixing it with makeString. Also updated for StringBuilder::shrink name. * html/HTMLTextFormControlElement.cpp: (WebCore::stripTrailingNewline): Updated for StringBuilder::shrink name. * page/CaptionUserPreferencesMediaAF.cpp: (WebCore::CaptionUserPreferencesMediaAF::captionsTextColor const): Tweaked coding style a bit. (WebCore::appendCSS): Use variadic StringBuilder::append instead of many separate calls. (WebCore::CaptionUserPreferencesMediaAF::captionsDefaultFontCSS const): Tweaked coding style a bit, and use variadic StrinBuilder::append calls to reduce the number of calls and streamline the code. (WebCore::CaptionUserPreferencesMediaAF::captionsStyleSheetOverride const): Ditto. Also removed unnecessary checks that strings are empty before appending. * page/scrolling/ScrollingCoordinator.cpp: (WebCore::ScrollingCoordinator::synchronousScrollingReasonsAsText): Updated for StringBuilder::shrink name. * platform/LayoutUnit.h: Updated for saturatedSum/Difference names. * platform/network/cocoa/NetworkStorageSessionCocoa.mm: (WebCore::NetworkStorageSession::cookiesForSession const): Tweaked codin style a bit, and use variadic StrinBuilder::append calls to reduce the number of calls and streamline the code. * rendering/RenderCounter.cpp: (WebCore::planCounter): Updated for saturatedSum name. * style/StyleBuilderCustom.h: (WebCore::Style::BuilderCustom::applyValueCounter): Ditto. * svg/SVGPathStringBuilder.cpp: (WebCore::SVGPathStringBuilder::result): Updated for StringBuilder::shrink name. * testing/Internals.cpp: (WebCore::Internals::pageMediaState): Ditto. * xml/XSLTProcessorLibxslt.cpp: (WebCore::saveResultToString): Ditto. Source/WebKit: * UIProcess/WebsiteData/Cocoa/WebsiteDataStoreCocoa.mm: (WebKit::WebsiteDataStore::platformSetNetworkParameters): Use makeString instead of StringBuilder. Source/WTF: The new header makes CFStringRef and NSString work with string concatenation, which means it now works with the variadic StringBuilder::append and makeString, and still works with the single-argument StringBuilder::append. More efficient that the old version because it does not allocate a temporary WTF::String for the 16-bit character path. Also made many other small improvements to the StringBuilder implementation. * WTF.xcodeproj/project.pbxproj: Added StringConcatenateCF.h. * wtf/CheckedArithmetic.h: Removed ConditionalCrashOnOverflow, which was only here for use by StringBuilder, which does not use CheckedArithmetic any more. * wtf/PlatformFTW.cmake: Added StringConcatenateCF.h.. * wtf/PlatformMac.cmake: Ditto. * wtf/PlatformWin.cmake: Ditto. * wtf/SaturatedArithmetic.h: Moved the contents of this file inside the WTF namespace. (WTF::signedAddInt32Overflows): Renamed this function. The type here is important, and we are not doing anything to prevent type conversion or create ambiguity, so it's good to be explicit in the function name. (WTF::saturatedSum<int32_t>): Renamed this from saturatedAddition for clarity. The function returns a sum, so that's a better name than calling it "addition". Also, it's clearer to be explicit about the return type. (WTF::signedSubtractInt32Overflows): Renamed. Same reason as above. (WTF::saturatedDifference<int32_t>): Ditto. (WTF::saturatedSum): Added. Does unsigned integer saturated addition. This one can be written in a portable manner and still get really efficient code on at least Intel and ARM64. (WTF::saturatedSum): Added a function template that lets callers pass larger number of arguments to saturatedSum, rather than exactly two. * wtf/text/StringBuilder.cpp: (WTF::expandedCapacity): Renamed to use the term capacity rather than length for the new required capacity. (WTF::StringBuilder::didOverflow): Implement the new approach to overflow, meaning we need to write the CRASH() here explicitly and in the non-crashing mode, set m_length. (WTF::StringBuilder::reifyString const): Changed the overflow check into a RELEASE_ASSERT. This is now responsible for doing the check that callers were doing earlier, so we want it in production builds. Also simplified this since our m_length member is a simple integer now, and removed the unused m_isReified. (WTF::StringBuilder::shrink): Renamed this to shrink to match the Vector::shrink function, since this has never supported making the builder larger. Removed unnecessary overflow checks, since shrinking cannot cause overflow. (WTF::StringBuilder::allocateBuffer): Replaced two separate functions with a single simpler function template. Removed extra overflow checks because the StringImpl::tryCreateUninitialized function already does the only overflow check we need. Also move to StringImpl::copyCharacters for copying characters rather than using std::memcpy directly. Removed code to set m_is8Bit and m_bufferCharacters. (WTF::StringBuilder::reallocateBuffer): Replaced two separate functions with a function template and a cover that calls the appropriate instance of the template for places where we aren't already in character-type-specific code paths. This version now supports allocating a buffer for the first time in cases where we have m_string and not m_buffer, which used to be handled at the higher level. Removed code to set m_bufferCharacters. (WTF::StringBuilder::reserveCapacity): Rewrote for simplicity. By relying on the overflow checking inside reallocateBuffer and allocateBuffer we no longer need checking of the passed-in value at this level. (WTF::StringBuilder::extendBufferForAppending): Removed the version of this that takes additionalLength since it's potentially confusing to have a family of functions that have the same name and take the same type of argument, but interpret it subtly differently. Streamlined the code using std::exchange. This function now also includes the logic from the function named extendBufferForAppendingWithoutOverflowCheck, which was subtly misnamed since that was not the only semantic difference. Also removed the ALWAYS_INLINE because the compiler will do the right thing without such heavy handed advice. (WTF::StringBuilder::extendBufferForAppendingSlowCase): Streamlined this by using std::exchange and removed additional overflow checks at this level since reallocateBuffer already does them. Also added a check for the case where the new total length is 0, which would not be handled correctly and efficiently by reallocateBuffer. (WTF::StringBuilder::extendBufferForAppendingLChar): Renamed this from extendBufferForAppending8, since it's now identical to calling extendBufferForAppending<LChar>, except for inlining and linkage. (WTF::StringBuilder::extendBufferForAppendingWithUpconvert): Renamed this from extendBufferForAppending16. It is different from the other extendBuffer functions because is supports upconverting from LChar to UChar. Like the others it relies on allocateBuffer for the overflow checking. (WTF::StringBuilder::appendCharacters): Removed an unnecessary assertion that the characters pointer is non-null; that will fail in an obvious way without an assertion. Simplified the logic and removed some invariant assertions that don't help us much. Changed overflow checking by using saturatedSum to compute the new length. In overflow cases, the new sum will be larger than the maximum string length, but will fit in an unsigned, so we can pass it down to lower levels and let functions like reallocateBuffer do the actual overflow checking. Also use StringImpl::copyCharacters. (WTF::StringBuilder::append): Removed the CFStringRef overload. (WTF::StringBuilder::shouldShrinkToFit const): Rename this from canShrink. Simplify the function a bit and remove the vague FIXME that says "this should be tuned". That may be so, but the FIXME is not really driving us to action. (WTF::StringBuilder::shrinkToFit): Simplify by using the new reallocateBuffer and std::exchange. Removed unneeded assertion about overflow that doesn't help us maintain the invariant. (WTF::StringBuilder::isAllASCII const): Was tempted to remove this function, but for now just made it use the StringView version for brevity. * wtf/text/StringBuilder.h: Removed many unneeded includes, and notably included SaturatedArithmetic.h instead of CheckedArithmetic.h because we now use the former instead of the latter. Changed the overflow checking implementation to work more simply based on saturated addition rather than Checked. This allowed us to get rid of dependency on our own unique mode for Checked, called ConditionalCrashOnOverflow. Removed a comment about making a templatized version of StringBuilder. We can do it if we like, but does not seem urgent. Moved fucntion bodies out of the class definition so it's easier to see what's going on in the class. Since m_length is now an ordinary integer, the check for overflowed simply checks to see if the length is larger than the maximum string length. When we encounter overflow that is not about length computation, we set the length to the maximum integer to indicate the failure. Deleted the append overloads for CFStringRef and NSString. Removed m_bufferCharacters, m_is8Bit, and m_isReified. (WTF::StringBuilder::StringBuilder): Simplified the constructor since we only have to initialize the m_shouldCrashOnOverflow member. (WTF::StringBuilder::clear): Fixed a mistake where this was not resetting the m_isReified flag. (WTF::StringBuilder::swap): Updated for changes in the data members. (WTF::StringBuilder::operator StringView const): Moved out of line. Made sure to call the length() function so we crash if this is called after overflow. (WTF::StringBuilder::append): Remove some of the unnecessary checks and special cases in the various versions of append. Most of the checking is done inside appendCharacters, with only a few exceptions. (WTF::StringBuilder::appendSubstring): Moved out of the class definition without making significant changes. (WTF::StringBuilder::appendCharacter): Ditto. (WTF::StringBuilder::toString): Greatly simplified this function by relying on overflow checking in the reifyString function instead of doing it here and removing unneeded invariant assertions. (WTF::StringBuilder::toStringPreserveCapacity const): Ditto. (WTF::StringBuilder::toAtomString const): Rewrote this to streamline, removing explicit overflow checks. (WTF::StringBuilder::length const): Moved out of the class definition without making significant changes. (WTF::StringBuilder::capacity const): Ditto. (WTF::StringBuilder::operator[] const): Ditto. (WTF::StringBuilder::characters const): Implemented this operation in the function template. Now rather than having this call the characters8 and characters16 functions, they can call it. (WTF::StringBuilder::getBufferCharacters<LChar>): Deleted. (WTF::StringBuilder::getBufferCharacters<UChar>): Deleted. (WTF::StringBuilder::appendFromAdapters): Use saturatedSum to compute the required length, which allows the extendBuffer functions to do overflow checking without having to take special checked integer types for arguments. (WTF::StringBuilder::equal): Implement using StringView. * wtf/text/StringBuilderJSON.cpp: (WTF::StringBuilder::appendQuotedJSONString): Simplified the checked arithmetic for computing the required capacity. Updated since we removed m_bufferCharacters and changed the type of m_length. * wtf/text/cf/StringConcatenateCF.h: Added. Specializes StringTypeAdapter for both CFStringRef and NSString *. If CFStringGetCStringPtr works for Latin-1, then does the 8-bit code path, otherwise the 16-bit. * wtf/text/cocoa/TextStreamCocoa.mm: Include StringConcatenateCF.h, since it's now needed to use CFStringRef with StringBuilder. Tools: * TestWebKitAPI/Tests/WTF/SaturatedArithmeticOperations.cpp: Updated tests for changes to SaturatedArithmetic.h. * TestWebKitAPI/Tests/WTF/StringBuilder.cpp: Updated tests for changes to StringBuilder. * TestWebKitAPI/Tests/WebKit/GetUserMedia.mm: (TestWebKitAPI::wkMediaCaptureStateString): Ditto. * WebKitTestRunner/InjectedBundle/InjectedBundlePage.cpp: Added include of StringConcatenateCF.h. Added StringTypeAdapter for WKStringRef. (WTR::styleDecToStr): Use ASCIILiteral instead of StringBuilder. (WTR::string): Removed unneeded toWTFString since the WKStringRef StringTypeAdapter takes care of it. (WTR::string): Renamed from frameToStr. Use makeString. (WTR::dumpResourceURL): Use append instead of appendLiteral. (WTR::dumpFrameDescriptionSuitableForTestResult): Deleted. (WTR::dumpLoadEvent): Use makeString. (WTR::string): Renamed from a longer name. Return a String instead of building in a StringBuilder. Use makeString. (WTR::string): Ditto. (WTR::dumpErrorDescriptionSuitableForTestResult): Removed unneeded toWTFString. (WTR::dumpFrameScrollPosition): Ditto. (WTR::dumpDescendantFramesText): Ditto. (WTR::InjectedBundlePage::dumpDOMAsWebArchive): Removed an unneeded local variable. (WTR::InjectedBundlePage::dump): Removed unneeded toWTFString. (WTR::InjectedBundlePage::didReceiveTitleForFrame): Ditto. (WTR::InjectedBundlePage::didFinishDocumentLoadForFrame): Updated for functon name change. (WTR::InjectedBundlePage::willSendRequestForFrame): Ditto. Also use variadic append. Also use makeString. (WTR::InjectedBundlePage::didReceiveResponseForResource): Ditto. (WTR::InjectedBundlePage::didFinishLoadForResource): Ditto. (WTR::InjectedBundlePage::didFailLoadForResource): Ditto. (WTR::InjectedBundlePage::decidePolicyForNavigationAction): Ditto. (WTR::InjectedBundlePage::decidePolicyForResponse): Ditto. (WTR::InjectedBundlePage::willAddMessageToConsole): Ditto. (WTR::InjectedBundlePage::willSetStatusbarText): Ditto. (WTR::InjectedBundlePage::willRunJavaScriptPrompt): Ditto. (WTR::InjectedBundlePage::didExceedDatabaseQuota): Ditto. (WTR::InjectedBundlePage::shouldInsertNode): Ditto. (WTR::InjectedBundlePage::shouldInsertText): Ditto. (WTR::InjectedBundlePage::shouldDeleteRange): Ditto. (WTR::InjectedBundlePage::shouldChangeSelectedRange): Ditto. (WTR::InjectedBundlePage::shouldApplyStyle): Ditto. (WTR::InjectedBundlePage::didBeginEditing): Ditto. (WTR::InjectedBundlePage::didEndEditing): Ditto. (WTR::InjectedBundlePage::didChange): Ditto. (WTR::InjectedBundlePage::didChangeSelection): Ditto. (WTR::InjectedBundlePage::dumpHistory): Ditto. Canonical link: https://commits.webkit.org/237916@main git-svn-id: https://svn.webkit.org/repository/webkit/trunk@277744 268f45cc-cd09-0410-ab3c-d52691b4dbfc
2021-05-19 19:37:21 +00:00
if (signedSubtractInt32Overflows(a, b, result))
result = std::numeric_limits<int32_t>::max() + (static_cast<uint32_t>(a) >> 31);
#endif
Add saturation arithmetic support to FractionalLayoutUnit https://bugs.webkit.org/show_bug.cgi?id=94364 Reviewed by Benjamin Poulain. Source/WebCore: Add experimental saturation arithmetic support to FractionalLayoutUnit, guarded by a flag. The idea here is to saturate (or clamp) rather than overflow when computing positions and sizes. No new tests for WebCore, not enabled by default. * platform/FractionalLayoutUnit.h: (WebCore::FractionalLayoutUnit::intMinForLayoutUnit): Use INT_MIN instead of -INT_MAX to compute minimum value as the two are not the same. (WebCore::FractionalLayoutUnit::FractionalLayoutUnit): (WebCore::FractionalLayoutUnit::fromFloatCeil): (WebCore::FractionalLayoutUnit::fromFloatFloor): (WebCore::FractionalLayoutUnit::fromFloatRound): (WebCore::FractionalLayoutUnit::setValue): Add range checks. (WebCore::operator*): (WebCore::operator+): (WebCore::operator-): (WebCore::operator+=): (WebCore::operator-=): Use the saturatedAddition and saturatedSubtraction functions, which have been optimized to reduce branching, instead of range checks for the most common operators. Source/WTF: Add support functions for saturated addition and subtraction. Test: TestWebKitAPI/Tests/WTF/SaturatedArithmeticOperations.cpp * GNUmakefile.list.am: * WTF.gypi: * WTF.pro: * WTF.vcproj/WTF.vcproj: * WTF.xcodeproj/project.pbxproj: * WTF/wtf/CMakeLists.txt: Add SaturatedArithmetic.h to build files. * wtf/SaturatedArithmetic.h: Added. (saturatedAddition): (saturatedSubtraction): Support functions for saturated addition/subtraction. Compares the signed bit of the values instead of using range checks to reduce branching. * wtf/Platform.h: Add ENABLE_SATURATED_LAYOUT_ARITHMETIC flag. Tools: Add test for new saturatedArithmetic functions. * TestWebKitAPI/CMakeLists.txt: * TestWebKitAPI/GNUmakefile.am: * TestWebKitAPI/TestWebKitAPI.gypi: * TestWebKitAPI/TestWebKitAPI.xcodeproj/project.pbxproj: * TestWebKitAPI/Tests/WTF/SaturatedArithmeticOperations.cpp: Added. (TestWebKitAPI): (TestWebKitAPI::TEST): * TestWebKitAPI/win/TestWebKitAPI.vcproj: Canonical link: https://commits.webkit.org/112729@main git-svn-id: https://svn.webkit.org/repository/webkit/trunk@126509 268f45cc-cd09-0410-ab3c-d52691b4dbfc
2012-08-24 00:14:00 +00:00
return result;
}
Move CFStringRef and NSString support from StringBuilder into StringConcatenateCF https://bugs.webkit.org/show_bug.cgi?id=225839 Reviewed by Sam Weinig. Source/JavaScriptCore: * inspector/ConsoleMessage.cpp: (Inspector::ConsoleMessage::ConsoleMessage): Use StringBuilder::clear instead of StringBuilder::resize; no advantage to the latter after calling StringBuilder::toString. * runtime/JSONObject.cpp: (JSC::Stringifier::Holder::appendNextProperty): Update for name change of StringBuilder::resize to StringBuilder::shrink. * runtime/TypeSet.cpp: (JSC::StructureShape::stringRepresentation): Ditto. Source/WebCore: * Modules/airplay/WebMediaSessionManager.cpp: (WebCore::mediaProducerStateString): Use StringBuilder exclusively instead of mixing it with makeString. Also updated for StringBuilder::shrink name. * html/HTMLTextFormControlElement.cpp: (WebCore::stripTrailingNewline): Updated for StringBuilder::shrink name. * page/CaptionUserPreferencesMediaAF.cpp: (WebCore::CaptionUserPreferencesMediaAF::captionsTextColor const): Tweaked coding style a bit. (WebCore::appendCSS): Use variadic StringBuilder::append instead of many separate calls. (WebCore::CaptionUserPreferencesMediaAF::captionsDefaultFontCSS const): Tweaked coding style a bit, and use variadic StrinBuilder::append calls to reduce the number of calls and streamline the code. (WebCore::CaptionUserPreferencesMediaAF::captionsStyleSheetOverride const): Ditto. Also removed unnecessary checks that strings are empty before appending. * page/scrolling/ScrollingCoordinator.cpp: (WebCore::ScrollingCoordinator::synchronousScrollingReasonsAsText): Updated for StringBuilder::shrink name. * platform/LayoutUnit.h: Updated for saturatedSum/Difference names. * platform/network/cocoa/NetworkStorageSessionCocoa.mm: (WebCore::NetworkStorageSession::cookiesForSession const): Tweaked codin style a bit, and use variadic StrinBuilder::append calls to reduce the number of calls and streamline the code. * rendering/RenderCounter.cpp: (WebCore::planCounter): Updated for saturatedSum name. * style/StyleBuilderCustom.h: (WebCore::Style::BuilderCustom::applyValueCounter): Ditto. * svg/SVGPathStringBuilder.cpp: (WebCore::SVGPathStringBuilder::result): Updated for StringBuilder::shrink name. * testing/Internals.cpp: (WebCore::Internals::pageMediaState): Ditto. * xml/XSLTProcessorLibxslt.cpp: (WebCore::saveResultToString): Ditto. Source/WebKit: * UIProcess/WebsiteData/Cocoa/WebsiteDataStoreCocoa.mm: (WebKit::WebsiteDataStore::platformSetNetworkParameters): Use makeString instead of StringBuilder. Source/WTF: The new header makes CFStringRef and NSString work with string concatenation, which means it now works with the variadic StringBuilder::append and makeString, and still works with the single-argument StringBuilder::append. More efficient that the old version because it does not allocate a temporary WTF::String for the 16-bit character path. Also made many other small improvements to the StringBuilder implementation. * WTF.xcodeproj/project.pbxproj: Added StringConcatenateCF.h. * wtf/CheckedArithmetic.h: Removed ConditionalCrashOnOverflow, which was only here for use by StringBuilder, which does not use CheckedArithmetic any more. * wtf/PlatformFTW.cmake: Added StringConcatenateCF.h.. * wtf/PlatformMac.cmake: Ditto. * wtf/PlatformWin.cmake: Ditto. * wtf/SaturatedArithmetic.h: Moved the contents of this file inside the WTF namespace. (WTF::signedAddInt32Overflows): Renamed this function. The type here is important, and we are not doing anything to prevent type conversion or create ambiguity, so it's good to be explicit in the function name. (WTF::saturatedSum<int32_t>): Renamed this from saturatedAddition for clarity. The function returns a sum, so that's a better name than calling it "addition". Also, it's clearer to be explicit about the return type. (WTF::signedSubtractInt32Overflows): Renamed. Same reason as above. (WTF::saturatedDifference<int32_t>): Ditto. (WTF::saturatedSum): Added. Does unsigned integer saturated addition. This one can be written in a portable manner and still get really efficient code on at least Intel and ARM64. (WTF::saturatedSum): Added a function template that lets callers pass larger number of arguments to saturatedSum, rather than exactly two. * wtf/text/StringBuilder.cpp: (WTF::expandedCapacity): Renamed to use the term capacity rather than length for the new required capacity. (WTF::StringBuilder::didOverflow): Implement the new approach to overflow, meaning we need to write the CRASH() here explicitly and in the non-crashing mode, set m_length. (WTF::StringBuilder::reifyString const): Changed the overflow check into a RELEASE_ASSERT. This is now responsible for doing the check that callers were doing earlier, so we want it in production builds. Also simplified this since our m_length member is a simple integer now, and removed the unused m_isReified. (WTF::StringBuilder::shrink): Renamed this to shrink to match the Vector::shrink function, since this has never supported making the builder larger. Removed unnecessary overflow checks, since shrinking cannot cause overflow. (WTF::StringBuilder::allocateBuffer): Replaced two separate functions with a single simpler function template. Removed extra overflow checks because the StringImpl::tryCreateUninitialized function already does the only overflow check we need. Also move to StringImpl::copyCharacters for copying characters rather than using std::memcpy directly. Removed code to set m_is8Bit and m_bufferCharacters. (WTF::StringBuilder::reallocateBuffer): Replaced two separate functions with a function template and a cover that calls the appropriate instance of the template for places where we aren't already in character-type-specific code paths. This version now supports allocating a buffer for the first time in cases where we have m_string and not m_buffer, which used to be handled at the higher level. Removed code to set m_bufferCharacters. (WTF::StringBuilder::reserveCapacity): Rewrote for simplicity. By relying on the overflow checking inside reallocateBuffer and allocateBuffer we no longer need checking of the passed-in value at this level. (WTF::StringBuilder::extendBufferForAppending): Removed the version of this that takes additionalLength since it's potentially confusing to have a family of functions that have the same name and take the same type of argument, but interpret it subtly differently. Streamlined the code using std::exchange. This function now also includes the logic from the function named extendBufferForAppendingWithoutOverflowCheck, which was subtly misnamed since that was not the only semantic difference. Also removed the ALWAYS_INLINE because the compiler will do the right thing without such heavy handed advice. (WTF::StringBuilder::extendBufferForAppendingSlowCase): Streamlined this by using std::exchange and removed additional overflow checks at this level since reallocateBuffer already does them. Also added a check for the case where the new total length is 0, which would not be handled correctly and efficiently by reallocateBuffer. (WTF::StringBuilder::extendBufferForAppendingLChar): Renamed this from extendBufferForAppending8, since it's now identical to calling extendBufferForAppending<LChar>, except for inlining and linkage. (WTF::StringBuilder::extendBufferForAppendingWithUpconvert): Renamed this from extendBufferForAppending16. It is different from the other extendBuffer functions because is supports upconverting from LChar to UChar. Like the others it relies on allocateBuffer for the overflow checking. (WTF::StringBuilder::appendCharacters): Removed an unnecessary assertion that the characters pointer is non-null; that will fail in an obvious way without an assertion. Simplified the logic and removed some invariant assertions that don't help us much. Changed overflow checking by using saturatedSum to compute the new length. In overflow cases, the new sum will be larger than the maximum string length, but will fit in an unsigned, so we can pass it down to lower levels and let functions like reallocateBuffer do the actual overflow checking. Also use StringImpl::copyCharacters. (WTF::StringBuilder::append): Removed the CFStringRef overload. (WTF::StringBuilder::shouldShrinkToFit const): Rename this from canShrink. Simplify the function a bit and remove the vague FIXME that says "this should be tuned". That may be so, but the FIXME is not really driving us to action. (WTF::StringBuilder::shrinkToFit): Simplify by using the new reallocateBuffer and std::exchange. Removed unneeded assertion about overflow that doesn't help us maintain the invariant. (WTF::StringBuilder::isAllASCII const): Was tempted to remove this function, but for now just made it use the StringView version for brevity. * wtf/text/StringBuilder.h: Removed many unneeded includes, and notably included SaturatedArithmetic.h instead of CheckedArithmetic.h because we now use the former instead of the latter. Changed the overflow checking implementation to work more simply based on saturated addition rather than Checked. This allowed us to get rid of dependency on our own unique mode for Checked, called ConditionalCrashOnOverflow. Removed a comment about making a templatized version of StringBuilder. We can do it if we like, but does not seem urgent. Moved fucntion bodies out of the class definition so it's easier to see what's going on in the class. Since m_length is now an ordinary integer, the check for overflowed simply checks to see if the length is larger than the maximum string length. When we encounter overflow that is not about length computation, we set the length to the maximum integer to indicate the failure. Deleted the append overloads for CFStringRef and NSString. Removed m_bufferCharacters, m_is8Bit, and m_isReified. (WTF::StringBuilder::StringBuilder): Simplified the constructor since we only have to initialize the m_shouldCrashOnOverflow member. (WTF::StringBuilder::clear): Fixed a mistake where this was not resetting the m_isReified flag. (WTF::StringBuilder::swap): Updated for changes in the data members. (WTF::StringBuilder::operator StringView const): Moved out of line. Made sure to call the length() function so we crash if this is called after overflow. (WTF::StringBuilder::append): Remove some of the unnecessary checks and special cases in the various versions of append. Most of the checking is done inside appendCharacters, with only a few exceptions. (WTF::StringBuilder::appendSubstring): Moved out of the class definition without making significant changes. (WTF::StringBuilder::appendCharacter): Ditto. (WTF::StringBuilder::toString): Greatly simplified this function by relying on overflow checking in the reifyString function instead of doing it here and removing unneeded invariant assertions. (WTF::StringBuilder::toStringPreserveCapacity const): Ditto. (WTF::StringBuilder::toAtomString const): Rewrote this to streamline, removing explicit overflow checks. (WTF::StringBuilder::length const): Moved out of the class definition without making significant changes. (WTF::StringBuilder::capacity const): Ditto. (WTF::StringBuilder::operator[] const): Ditto. (WTF::StringBuilder::characters const): Implemented this operation in the function template. Now rather than having this call the characters8 and characters16 functions, they can call it. (WTF::StringBuilder::getBufferCharacters<LChar>): Deleted. (WTF::StringBuilder::getBufferCharacters<UChar>): Deleted. (WTF::StringBuilder::appendFromAdapters): Use saturatedSum to compute the required length, which allows the extendBuffer functions to do overflow checking without having to take special checked integer types for arguments. (WTF::StringBuilder::equal): Implement using StringView. * wtf/text/StringBuilderJSON.cpp: (WTF::StringBuilder::appendQuotedJSONString): Simplified the checked arithmetic for computing the required capacity. Updated since we removed m_bufferCharacters and changed the type of m_length. * wtf/text/cf/StringConcatenateCF.h: Added. Specializes StringTypeAdapter for both CFStringRef and NSString *. If CFStringGetCStringPtr works for Latin-1, then does the 8-bit code path, otherwise the 16-bit. * wtf/text/cocoa/TextStreamCocoa.mm: Include StringConcatenateCF.h, since it's now needed to use CFStringRef with StringBuilder. Tools: * TestWebKitAPI/Tests/WTF/SaturatedArithmeticOperations.cpp: Updated tests for changes to SaturatedArithmetic.h. * TestWebKitAPI/Tests/WTF/StringBuilder.cpp: Updated tests for changes to StringBuilder. * TestWebKitAPI/Tests/WebKit/GetUserMedia.mm: (TestWebKitAPI::wkMediaCaptureStateString): Ditto. * WebKitTestRunner/InjectedBundle/InjectedBundlePage.cpp: Added include of StringConcatenateCF.h. Added StringTypeAdapter for WKStringRef. (WTR::styleDecToStr): Use ASCIILiteral instead of StringBuilder. (WTR::string): Removed unneeded toWTFString since the WKStringRef StringTypeAdapter takes care of it. (WTR::string): Renamed from frameToStr. Use makeString. (WTR::dumpResourceURL): Use append instead of appendLiteral. (WTR::dumpFrameDescriptionSuitableForTestResult): Deleted. (WTR::dumpLoadEvent): Use makeString. (WTR::string): Renamed from a longer name. Return a String instead of building in a StringBuilder. Use makeString. (WTR::string): Ditto. (WTR::dumpErrorDescriptionSuitableForTestResult): Removed unneeded toWTFString. (WTR::dumpFrameScrollPosition): Ditto. (WTR::dumpDescendantFramesText): Ditto. (WTR::InjectedBundlePage::dumpDOMAsWebArchive): Removed an unneeded local variable. (WTR::InjectedBundlePage::dump): Removed unneeded toWTFString. (WTR::InjectedBundlePage::didReceiveTitleForFrame): Ditto. (WTR::InjectedBundlePage::didFinishDocumentLoadForFrame): Updated for functon name change. (WTR::InjectedBundlePage::willSendRequestForFrame): Ditto. Also use variadic append. Also use makeString. (WTR::InjectedBundlePage::didReceiveResponseForResource): Ditto. (WTR::InjectedBundlePage::didFinishLoadForResource): Ditto. (WTR::InjectedBundlePage::didFailLoadForResource): Ditto. (WTR::InjectedBundlePage::decidePolicyForNavigationAction): Ditto. (WTR::InjectedBundlePage::decidePolicyForResponse): Ditto. (WTR::InjectedBundlePage::willAddMessageToConsole): Ditto. (WTR::InjectedBundlePage::willSetStatusbarText): Ditto. (WTR::InjectedBundlePage::willRunJavaScriptPrompt): Ditto. (WTR::InjectedBundlePage::didExceedDatabaseQuota): Ditto. (WTR::InjectedBundlePage::shouldInsertNode): Ditto. (WTR::InjectedBundlePage::shouldInsertText): Ditto. (WTR::InjectedBundlePage::shouldDeleteRange): Ditto. (WTR::InjectedBundlePage::shouldChangeSelectedRange): Ditto. (WTR::InjectedBundlePage::shouldApplyStyle): Ditto. (WTR::InjectedBundlePage::didBeginEditing): Ditto. (WTR::InjectedBundlePage::didEndEditing): Ditto. (WTR::InjectedBundlePage::didChange): Ditto. (WTR::InjectedBundlePage::didChangeSelection): Ditto. (WTR::InjectedBundlePage::dumpHistory): Ditto. Canonical link: https://commits.webkit.org/237916@main git-svn-id: https://svn.webkit.org/repository/webkit/trunk@277744 268f45cc-cd09-0410-ab3c-d52691b4dbfc
2021-05-19 19:37:21 +00:00
template<typename UnsignedIntegralType> constexpr std::enable_if_t<std::is_integral_v<UnsignedIntegralType> && !std::is_signed_v<UnsignedIntegralType>, UnsignedIntegralType> saturatedSum(UnsignedIntegralType a, UnsignedIntegralType b)
{
auto sum = a + b;
return sum < a ? std::numeric_limits<UnsignedIntegralType>::max() : sum;
}
template<typename IntegralType, typename... ArgumentTypes> constexpr uint32_t saturatedSum(IntegralType value, ArgumentTypes... arguments)
{
return saturatedSum<IntegralType>(value, saturatedSum<IntegralType>(arguments...));
}
}
using WTF::saturatedSum;
using WTF::saturatedDifference;