From 191ccbe7fe3fd81cde5dd1f9a6f837f2ca237151 Mon Sep 17 00:00:00 2001 From: Alexandru Marc Date: Fri, 25 Oct 2024 16:42:33 +0300 Subject: [PATCH] Backed out changeset d92f391b3b0c (bug 1922838) for backing out bug 1915351 --- accessible/atk/AccessibleWrap.cpp | 2 +- accessible/atk/nsMaiInterfaceText.cpp | 2 +- accessible/base/ARIAMap.cpp | 8 +- accessible/base/Logging.cpp | 4 +- accessible/base/TextAttrs.cpp | 4 +- accessible/base/TextLeafRange.cpp | 2 +- accessible/base/nsAccessibilityService.cpp | 23 ++-- accessible/base/nsAccessibilityService.h | 2 +- accessible/generic/DocAccessible.cpp | 2 +- accessible/generic/RootAccessible.cpp | 4 +- accessible/ipc/RemoteAccessible.cpp | 4 +- accessible/mac/mozAccessible.mm | 2 +- accessible/windows/ia2/ia2Accessible.cpp | 8 +- accessible/windows/msaa/LazyInstantiator.cpp | 5 +- accessible/windows/msaa/MsaaAccessible.cpp | 2 +- accessible/windows/uia/uiaRawElmProvider.cpp | 2 +- browser/app/nsBrowserApp.cpp | 3 +- browser/app/winlauncher/ErrorHandler.cpp | 25 ++-- browser/app/winlauncher/LaunchUnelevated.cpp | 2 +- browser/app/winlauncher/SameBinary.h | 8 +- .../winlauncher/freestanding/DllBlocklist.cpp | 4 +- .../winlauncher/test/TestCrossProcessWin.cpp | 5 +- .../app/winlauncher/test/TestSameBinary.cpp | 4 +- .../shell/WindowsDefaultBrowser.cpp | 2 +- .../components/shell/WindowsUserChoice.cpp | 2 +- .../components/shell/nsGNOMEShellService.cpp | 6 +- .../shell/nsWindowsShellService.cpp | 6 +- caps/BasePrincipal.cpp | 2 +- caps/BasePrincipal.h | 2 +- caps/nsScriptSecurityManager.cpp | 2 +- docshell/base/nsAboutRedirector.cpp | 2 +- dom/base/CCGCScheduler.cpp | 5 +- dom/base/DOMException.cpp | 4 +- dom/base/Document.cpp | 2 +- dom/base/FragmentOrElement.cpp | 4 +- dom/base/nsContentUtils.cpp | 19 +-- dom/base/nsGlobalWindowInner.cpp | 2 +- dom/base/nsINode.cpp | 4 +- dom/base/nsMimeTypeArray.cpp | 2 +- dom/base/nsMimeTypeArray.h | 2 +- dom/base/nsNameSpaceManager.cpp | 2 +- dom/base/nsPluginArray.cpp | 6 +- dom/base/nsPluginArray.h | 2 +- dom/base/nsTreeSanitizer.cpp | 22 ++-- dom/base/usecounters.py | 4 +- dom/bindings/BindingUtils.cpp | 2 +- dom/bindings/BindingUtils.h | 15 +-- dom/bindings/Codegen.py | 6 +- dom/bindings/TypedArray.h | 8 +- dom/canvas/WebGLStrongTypes.h | 14 +-- dom/crypto/CryptoKey.cpp | 8 +- dom/crypto/WebCryptoCommon.h | 2 +- dom/events/Clipboard.cpp | 2 +- dom/events/DataTransfer.cpp | 8 +- dom/events/DataTransfer.h | 2 +- dom/events/DataTransferItem.cpp | 4 +- dom/events/KeyEventHandler.cpp | 2 +- dom/events/UIEvent.cpp | 4 +- dom/gamepad/GamepadServiceTest.cpp | 20 +-- dom/gamepad/linux/udev.h | 4 +- dom/gamepad/windows/WindowsGamepad.cpp | 13 +- dom/html/HTMLInputElement.cpp | 12 +- dom/html/TextTrackManager.cpp | 4 +- dom/indexedDB/ActorsParent.cpp | 2 +- dom/ipc/ContentParent.cpp | 4 +- dom/mathml/MathMLElement.cpp | 8 +- dom/media/AsyncLogger.h | 4 +- dom/media/eme/clearkey/ArrayUtils.h | 22 ++++ dom/media/eme/clearkey/ClearKeyStorage.cpp | 1 + dom/media/eme/clearkey/ClearKeyUtils.cpp | 3 +- dom/media/eme/clearkey/moz.build | 1 + dom/media/encoder/OpusTrackEncoder.cpp | 2 +- dom/media/gmp/GMPDiskStorage.cpp | 4 +- dom/media/gmp/rlz/win/lib/machine_id_win.cc | 2 +- dom/media/gtest/TestGMPUtils.cpp | 6 +- dom/media/gtest/TestMP4Demuxer.cpp | 4 +- dom/media/gtest/TestVPXDecoding.cpp | 2 +- dom/media/gtest/TestWebMBuffered.cpp | 2 +- dom/media/gtest/mp4_demuxer/TestParser.cpp | 10 +- dom/media/mediasession/MediaSession.cpp | 8 +- .../mediasource/gtest/TestContainerParser.cpp | 4 +- dom/media/ogg/OggCodecState.cpp | 2 +- .../platforms/agnostic/bytestreams/Adts.cpp | 4 +- .../platforms/agnostic/bytestreams/AnnexB.cpp | 10 +- .../bytestreams/gtest/TestByteStreams.cpp | 24 ++-- dom/media/platforms/apple/AppleVTDecoder.cpp | 28 ++--- dom/media/platforms/apple/AppleVTEncoder.cpp | 24 ++-- .../platforms/ffmpeg/FFmpegRuntimeLinker.cpp | 4 +- dom/media/platforms/omx/OmxCoreLibLinker.cpp | 2 +- dom/media/webaudio/DelayBuffer.cpp | 2 +- dom/media/webaudio/blink/HRTFElevation.cpp | 2 +- .../blink/IRC_Composite_C_R0195-incl.cpp | 22 ++-- dom/media/webaudio/blink/ReverbConvolver.cpp | 2 +- .../webrtc/transport/transportlayerdtls.cpp | 2 +- .../recognition/SpeechRecognition.cpp | 4 +- .../synth/speechd/SpeechDispatcherService.cpp | 2 +- .../synth/test/nsFakeSynthServices.cpp | 2 +- dom/midi/MIDIUtils.cpp | 4 +- dom/permission/PermissionUtils.cpp | 6 +- dom/security/nsContentSecurityUtils.cpp | 2 +- dom/serviceworkers/ServiceWorkerRegistrar.cpp | 2 +- dom/svg/SVGAElement.cpp | 2 +- dom/svg/SVGCircleElement.cpp | 2 +- dom/svg/SVGClipPathElement.cpp | 2 +- dom/svg/SVGContentUtils.h | 2 +- dom/svg/SVGEllipseElement.cpp | 2 +- dom/svg/SVGFEBlendElement.cpp | 4 +- dom/svg/SVGFEColorMatrixElement.cpp | 6 +- dom/svg/SVGFEComponentTransferElement.cpp | 2 +- dom/svg/SVGFECompositeElement.cpp | 6 +- dom/svg/SVGFEConvolveMatrixElement.cpp | 16 +-- dom/svg/SVGFEDisplacementMapElement.cpp | 6 +- dom/svg/SVGFEDistantLightElement.cpp | 2 +- dom/svg/SVGFEDropShadowElement.cpp | 6 +- dom/svg/SVGFEFloodElement.cpp | 2 +- dom/svg/SVGFEGaussianBlurElement.cpp | 4 +- dom/svg/SVGFEImageElement.cpp | 2 +- dom/svg/SVGFEMergeElement.cpp | 2 +- dom/svg/SVGFEMergeNodeElement.cpp | 2 +- dom/svg/SVGFEMorphologyElement.cpp | 6 +- dom/svg/SVGFEOffsetElement.cpp | 4 +- dom/svg/SVGFEPointLightElement.cpp | 2 +- dom/svg/SVGFESpotLightElement.cpp | 2 +- dom/svg/SVGFETileElement.cpp | 2 +- dom/svg/SVGFETurbulenceElement.cpp | 10 +- dom/svg/SVGFilterElement.cpp | 6 +- dom/svg/SVGFilters.cpp | 14 +-- dom/svg/SVGForeignObjectElement.cpp | 2 +- dom/svg/SVGGradientElement.cpp | 8 +- dom/svg/SVGImageElement.cpp | 4 +- dom/svg/SVGLineElement.cpp | 2 +- dom/svg/SVGMPathElement.cpp | 2 +- dom/svg/SVGMarkerElement.cpp | 4 +- dom/svg/SVGMaskElement.cpp | 4 +- dom/svg/SVGNumberList.cpp | 3 +- dom/svg/SVGPathSegUtils.cpp | 2 +- dom/svg/SVGPatternElement.cpp | 6 +- dom/svg/SVGPointList.cpp | 2 +- dom/svg/SVGPreserveAspectRatio.cpp | 4 +- dom/svg/SVGRectElement.cpp | 2 +- dom/svg/SVGSVGElement.cpp | 2 +- dom/svg/SVGScriptElement.cpp | 2 +- dom/svg/SVGTSpanElement.cpp | 4 +- dom/svg/SVGTests.cpp | 9 +- dom/svg/SVGTextElement.cpp | 4 +- dom/svg/SVGTextPathElement.cpp | 6 +- dom/svg/SVGTextPositioningElement.cpp | 4 +- dom/svg/SVGTransformListParser.cpp | 8 +- dom/svg/SVGUseElement.cpp | 4 +- dom/svg/SVGViewElement.cpp | 2 +- dom/svg/SVGViewportElement.cpp | 2 +- dom/workers/RuntimeService.cpp | 2 +- dom/worklet/Worklet.cpp | 2 +- dom/xhr/XMLHttpRequestMainThread.cpp | 2 +- dom/xslt/xpath/txCoreFunctionCall.cpp | 2 +- dom/xslt/xslt/txStylesheetCompileHandlers.cpp | 10 +- dom/xslt/xslt/txXSLTNumber.cpp | 2 +- editor/libeditor/CompositionTransaction.cpp | 2 +- editor/libeditor/EditorCommands.cpp | 6 +- editor/libeditor/HTMLEditUtils.cpp | 2 +- editor/libeditor/HTMLEditorDataTransfer.cpp | 10 +- extensions/auth/nsAuthGSSAPI.cpp | 6 +- .../pref/autoconfig/src/nsReadConfig.cpp | 4 +- gfx/gl/GLBlitHelper.cpp | 2 +- gfx/gl/GLContextFeatures.cpp | 2 +- gfx/gl/GLContextProviderEGL.cpp | 2 +- gfx/gl/GLReadTexImageHelper.cpp | 2 +- gfx/layers/opengl/CompositorOGL.cpp | 6 +- gfx/src/DriverCrashGuard.cpp | 2 +- gfx/src/FilterSupport.cpp | 4 +- gfx/src/nsFont.cpp | 8 +- gfx/tests/gtest/TestSkipChars.cpp | 14 ++- gfx/thebes/CoreTextFontList.cpp | 4 +- gfx/thebes/DeviceManagerDx.cpp | 2 +- gfx/thebes/gfxASurface.cpp | 4 +- gfx/thebes/gfxCoreTextShaper.cpp | 8 +- gfx/thebes/gfxDWriteFontList.cpp | 8 +- gfx/thebes/gfxFT2FontList.cpp | 21 ++-- gfx/thebes/gfxFcPlatformFontList.cpp | 18 +-- gfx/thebes/gfxFont.cpp | 14 +-- gfx/thebes/gfxFontUtils.cpp | 8 +- gfx/thebes/gfxGDIFontList.cpp | 2 +- gfx/thebes/gfxGraphiteShaper.cpp | 2 +- gfx/thebes/gfxHarfBuzzShaper.cpp | 2 +- gfx/thebes/gfxMacPlatformFontList.mm | 2 +- gfx/thebes/gfxMathTable.cpp | 5 +- gfx/thebes/gfxPlatformFontList.cpp | 14 +-- gfx/thebes/gfxTextRun.cpp | 4 +- gfx/thebes/gfxUserFontSet.cpp | 2 +- gfx/vr/VRManager.cpp | 14 +-- gfx/vr/service/VRService.cpp | 6 +- image/decoders/icon/nsIconURI.cpp | 8 +- image/decoders/icon/win/nsIconChannel.cpp | 4 +- intl/locale/nsLanguageAtomService.cpp | 4 +- intl/locale/tests/gtest/TestOSPreferences.cpp | 2 +- intl/lwbrk/LineBreaker.cpp | 4 +- intl/strres/nsStringBundle.cpp | 2 +- .../unicharutil/tools/genSpecialCasingData.pl | 2 +- intl/unicharutil/util/nsSpecialCasingData.cpp | 2 +- intl/unicharutil/util/nsUnicodeProperties.cpp | 2 +- ipc/glue/IPCMessageUtilsSpecializations.h | 4 +- ipc/glue/URIUtils.cpp | 1 + ipc/glue/WindowsMessageLoop.cpp | 4 +- ipc/mscom/Utils.cpp | 8 +- js/src/jit/JitcodeMap.cpp | 2 +- js/src/shell/OSObject.cpp | 6 +- js/src/vm/GeckoProfiler.cpp | 2 +- js/src/vm/JSFunction.cpp | 2 +- js/xpconnect/loader/mozJSModuleLoader.cpp | 15 +-- js/xpconnect/wrappers/FilteringWrapper.cpp | 5 +- layout/base/PresShell.cpp | 2 +- layout/base/RestyleManager.cpp | 9 +- layout/base/StaticPresData.cpp | 2 +- layout/base/nsCSSFrameConstructor.cpp | 12 +- layout/base/nsLayoutUtils.h | 4 +- layout/base/nsPresArena.cpp | 8 +- layout/base/nsPresContext.h | 3 +- layout/base/nsRefreshDriver.cpp | 2 +- layout/generic/MathMLTextRunFactory.cpp | 12 +- layout/generic/TextOverflow.cpp | 2 +- layout/generic/nsBlockFrame.cpp | 2 +- layout/generic/nsFrameSelection.cpp | 10 +- layout/generic/nsGridContainerFrame.cpp | 2 +- layout/generic/nsIFrame.h | 4 +- layout/generic/nsPageFrame.cpp | 2 +- layout/generic/nsPageSequenceFrame.cpp | 2 +- layout/generic/nsTextFrame.cpp | 2 +- layout/generic/nsTextRunTransformations.cpp | 2 +- layout/painting/nsCSSRendering.cpp | 6 +- layout/style/CounterStyleManager.cpp | 2 +- layout/style/nsCSSPropertyIDSet.h | 12 +- layout/style/nsCSSProps.cpp | 2 +- layout/style/nsComputedDOMStyle.cpp | 12 +- layout/style/test/ListCSSProperties.cpp | 12 +- layout/tables/nsTableFrame.cpp | 2 +- media/psshparser/gtest/TestPsshParser.cpp | 18 +-- memory/build/mozjemalloc.cpp | 2 +- mfbt/Array.h | 3 - mfbt/ArrayUtils.h | 70 ++++++++++- mfbt/BitSet.h | 4 +- mfbt/EnumeratedArray.h | 3 - mfbt/tests/TestAlgorithm.cpp | 12 +- mfbt/tests/TestBinarySearch.cpp | 3 +- mfbt/tests/TestEnumeratedArray.cpp | 2 +- mfbt/tests/TestSplayTree.cpp | 4 +- mfbt/tests/TestUtf8.cpp | 33 ++--- .../baseprofiler/core/ProfilingCategory.cpp | 2 +- mozglue/baseprofiler/lul/LulMain.cpp | 2 +- mozglue/misc/NativeNt.h | 6 +- mozglue/misc/StackWalk.cpp | 10 +- mozglue/misc/decimal/moz-decimal-utils.h | 2 +- mozglue/tests/TestPEExportSection.cpp | 3 +- mozglue/tests/TestTimeStampWin.cpp | 2 +- netwerk/dns/DNS.cpp | 2 +- netwerk/protocol/http/Http2Session.cpp | 2 +- netwerk/protocol/http/HttpBaseChannel.cpp | 2 +- .../protocol/res/ExtensionProtocolHandler.cpp | 2 +- .../converters/nsDirIndexParser.cpp | 2 +- netwerk/wifi/nsWifiAccessPoint.h | 4 +- parser/html/nsHtml5AttributeName.cpp | 2 +- parser/html/nsHtml5ElementName.cpp | 2 +- parser/html/nsHtml5NamedCharacters.cpp | 2 +- parser/html/nsHtml5Tokenizer.cpp | 20 +-- parser/html/nsHtml5TreeBuilder.cpp | 2 +- parser/htmlparser/nsExpatDriver.cpp | 6 +- security/certverifier/CertVerifier.cpp | 7 +- security/certverifier/ExtendedValidation.cpp | 8 +- security/certverifier/OCSPCache.cpp | 2 +- security/manager/ssl/AppTrustDomain.cpp | 29 +++-- security/manager/ssl/EnterpriseRoots.cpp | 4 +- security/manager/ssl/KeychainSecret.cpp | 12 +- security/manager/ssl/NSSSocketControl.cpp | 2 +- .../manager/ssl/PublicKeyPinningService.cpp | 2 +- .../ssl/RootCertificateTelemetryUtils.cpp | 2 +- security/manager/ssl/nsNSSCallbacks.cpp | 2 +- security/manager/ssl/nsNSSIOLayer.cpp | 14 +-- .../tests/unit/tlsserver/cmd/FaultyServer.cpp | 2 +- security/sandbox/linux/SandboxInfo.cpp | 2 +- .../sandbox/linux/launch/SandboxLaunch.cpp | 2 +- storage/SQLCollations.cpp | 2 +- storage/mozStorageSQLFunctions.cpp | 2 +- storage/test/gtest/test_binding_params.cpp | 8 +- .../tests/gtest/TestAboutThirdParty.cpp | 4 +- .../ClearDataCallback.cpp | 2 +- .../formautofill/FormAutofillNative.cpp | 6 +- .../tests/gtest/places_test_harness_tail.h | 2 +- toolkit/components/remote/nsXRemoteClient.cpp | 6 +- toolkit/components/remote/nsXRemoteServer.cpp | 4 +- .../ApplicationReputation.cpp | 29 +++-- .../test/gtest/TestExecutableLists.cpp | 5 +- .../resistfingerprinting/nsRFPService.cpp | 11 +- .../tests/gtest/TestCombinedStacks.cpp | 6 +- .../components/terminator/nsTerminator.cpp | 2 +- .../url-classifier/nsUrlClassifierUtils.cpp | 4 +- .../tests/gtest/TestChunkSet.cpp | 42 +++---- .../tests/gtest/TestFindFullHash.cpp | 10 +- .../mozapps/defaultagent/DefaultBrowser.cpp | 5 +- toolkit/mozapps/defaultagent/DefaultPDF.cpp | 5 +- .../defaultagent/SetDefaultBrowser.cpp | 8 +- toolkit/mozapps/defaultagent/Telemetry.cpp | 5 +- .../update/tests/TestAUSReadStrings.cpp | 12 +- .../nsWindowsSystemProxySettings.cpp | 5 +- toolkit/xre/GeckoArgs.cpp | 16 +-- toolkit/xre/LauncherRegistryInfo.cpp | 11 +- toolkit/xre/dllservices/ModuleEvaluator.cpp | 2 +- .../mozglue/WindowsDllBlocklistCommon.h | 4 +- .../mozglue/interceptor/PatcherDetour.h | 2 +- .../mozglue/interceptor/PatcherNopSpace.h | 7 +- .../tests/TestDllInterceptorCrossProcess.cpp | 2 +- .../tests/gtest/TestDLLBlocklist.cpp | 2 +- .../tests/gtest/TestUntrustedModules.cpp | 6 +- toolkit/xre/nsUpdateDriver.cpp | 4 +- .../test/gtest/TestAssembleCommandLineWin.cpp | 10 +- toolkit/xre/test/gtest/TestGeckoArgs.cpp | 16 +-- .../core/ProfilerCodeAddressService.cpp | 7 +- tools/profiler/core/platform.cpp | 13 +- tools/profiler/lul/LulMain.cpp | 2 +- tools/profiler/tests/gtest/GeckoProfiler.cpp | 114 +++++++++--------- .../exthandler/nsExternalHelperAppService.cpp | 8 +- uriloader/exthandler/win/nsMIMEInfoWin.cpp | 5 +- widget/GfxInfoBase.cpp | 2 +- widget/ScrollbarDrawing.cpp | 2 +- widget/ScrollbarDrawingWin11.cpp | 2 +- widget/Theme.cpp | 4 +- widget/WidgetEventImpl.cpp | 24 ++-- widget/cocoa/nsChildView.mm | 2 +- widget/cocoa/nsCocoaUtils.mm | 6 +- widget/cocoa/nsNativeThemeCocoa.mm | 4 +- widget/cocoa/nsPrintDialogX.mm | 4 +- widget/gtk/DBusMenu.cpp | 2 +- widget/gtk/NativeKeyBindings.cpp | 4 +- widget/gtk/nsClipboard.cpp | 4 +- widget/gtk/nsDragService.cpp | 2 +- widget/gtk/nsGtkKeyUtils.cpp | 6 +- widget/gtk/nsPrintDialogGTK.cpp | 12 +- widget/gtk/nsWindow.cpp | 4 +- widget/nsBaseWidget.cpp | 6 +- widget/nsPaper.h | 3 +- widget/nsXPLookAndFeel.cpp | 8 +- widget/windows/GfxInfo.cpp | 9 +- widget/windows/KeyboardLayout.cpp | 26 ++-- widget/windows/TSFTextStore.cpp | 2 +- widget/windows/TaskbarWindowPreview.cpp | 2 +- widget/windows/WinMouseScrollHandler.cpp | 4 +- widget/windows/WinUtils.cpp | 10 +- widget/windows/nsColorPicker.cpp | 5 +- widget/windows/nsPrintSettingsWin.cpp | 2 +- widget/windows/nsWindow.cpp | 2 +- xpcom/base/AppShutdown.cpp | 2 +- xpcom/base/nsISupportsImpl.h | 17 ++- xpcom/base/nsSystemInfo.cpp | 15 ++- xpcom/build/PoisonIOInterposerMac.cpp | 2 +- xpcom/components/ManifestParser.cpp | 2 +- xpcom/components/StaticComponents.cpp.in | 6 +- xpcom/io/Base64.cpp | 10 +- xpcom/io/nsEscape.cpp | 2 +- xpcom/io/nsLocalFileWin.cpp | 14 +-- xpcom/reflect/xptinfo/xptcodegen.py | 2 +- xpcom/rust/gtest/bench-collections/Bench.cpp | 4 +- xpcom/tests/gtest/TestAtoms.cpp | 10 +- xpcom/tests/gtest/TestDeadlockDetector.cpp | 4 +- xpcom/tests/gtest/TestEscape.cpp | 10 +- .../tests/gtest/TestNSPRLogModulesParser.cpp | 8 +- xpcom/tests/gtest/TestObserverArray.cpp | 4 +- xpcom/tests/gtest/TestTArray.cpp | 14 +-- xpcom/tests/gtest/TestTArray2.cpp | 95 +++++++-------- xpcom/tests/gtest/TestThreadUtils.cpp | 4 +- xpcom/tests/gtest/TestUTF.cpp | 14 +-- .../tests/windows/TestPoisonIOInterposer.cpp | 2 +- xpcom/threads/TimerThread.cpp | 4 +- 370 files changed, 1277 insertions(+), 1115 deletions(-) create mode 100644 dom/media/eme/clearkey/ArrayUtils.h diff --git a/accessible/atk/AccessibleWrap.cpp b/accessible/atk/AccessibleWrap.cpp index 9ada605b29afe1..0f17fc59ee9cad 100644 --- a/accessible/atk/AccessibleWrap.cpp +++ b/accessible/atk/AccessibleWrap.cpp @@ -391,7 +391,7 @@ static GType GetMaiAtkType(uint16_t interfacesBits) { type = g_type_register_static(MAI_TYPE_ATK_OBJECT, atkTypeName, &tinfo, GTypeFlags(0)); - for (uint32_t index = 0; index < std::size(atk_if_infos); index++) { + for (uint32_t index = 0; index < ArrayLength(atk_if_infos); index++) { if (interfacesBits & (1 << index)) { g_type_add_interface_static(type, GetAtkTypeForMai((MaiInterfaceType)index), diff --git a/accessible/atk/nsMaiInterfaceText.cpp b/accessible/atk/nsMaiInterfaceText.cpp index 08a6b891e7eba7..b5c0dcc38d402f 100644 --- a/accessible/atk/nsMaiInterfaceText.cpp +++ b/accessible/atk/nsMaiInterfaceText.cpp @@ -550,7 +550,7 @@ void textInterfaceInitCB(AtkTextIface* aIface) { } // Cache the string values of the atk text attribute names. - for (uint32_t i = 0; i < std::size(sAtkTextAttrNames); i++) { + for (uint32_t i = 0; i < ArrayLength(sAtkTextAttrNames); i++) { sAtkTextAttrNames[i] = atk_text_attribute_get_name(static_cast(i)); } diff --git a/accessible/base/ARIAMap.cpp b/accessible/base/ARIAMap.cpp index fd5a30d24189a8..a557405497560b 100644 --- a/accessible/base/ARIAMap.cpp +++ b/accessible/base/ARIAMap.cpp @@ -1531,7 +1531,7 @@ uint8_t aria::GetFirstValidRoleMapIndexExcluding( return Compare(role, aEntry.ARIARoleString(), nsCaseInsensitiveStringComparator); }; - if (BinarySearchIf(sWAIRoleMaps, 0, std::size(sWAIRoleMaps), comparator, + if (BinarySearchIf(sWAIRoleMaps, 0, ArrayLength(sWAIRoleMaps), comparator, &idx)) { return idx; } @@ -1581,7 +1581,7 @@ bool aria::IsRoleMapIndexValid(uint8_t aRoleMapIndex) { case LANDMARK_ROLE_MAP_ENTRY_INDEX: return true; } - return aRoleMapIndex < std::size(sWAIRoleMaps); + return aRoleMapIndex < ArrayLength(sWAIRoleMaps); } uint64_t aria::UniversalStatesFor(mozilla::dom::Element* aElement) { @@ -1593,7 +1593,7 @@ uint64_t aria::UniversalStatesFor(mozilla::dom::Element* aElement) { } uint8_t aria::AttrCharacteristicsFor(nsAtom* aAtom) { - for (uint32_t i = 0; i < std::size(gWAIUnivAttrMap); i++) { + for (uint32_t i = 0; i < ArrayLength(gWAIUnivAttrMap); i++) { if (gWAIUnivAttrMap[i].attributeName == aAtom) { return gWAIUnivAttrMap[i].characteristics; } @@ -1615,7 +1615,7 @@ const nsRoleMapEntry* aria::GetRoleMap(const nsStaticAtom* aAriaRole) { return Compare(role, aEntry.ARIARoleString()); }; size_t idx; - if (BinarySearchIf(sWAIRoleMaps, 0, std::size(sWAIRoleMaps), comparator, + if (BinarySearchIf(sWAIRoleMaps, 0, ArrayLength(sWAIRoleMaps), comparator, &idx)) { return GetRoleMapFromIndex(idx); } diff --git a/accessible/base/Logging.cpp b/accessible/base/Logging.cpp index e266ba18ea36e5..2925aa28bf4953 100644 --- a/accessible/base/Logging.cpp +++ b/accessible/base/Logging.cpp @@ -74,7 +74,7 @@ static void EnableLogging(const char* aModulesStr) { const char* token = aModulesStr; while (*token != '\0') { size_t tokenLen = strcspn(token, ","); - for (unsigned int idx = 0; idx < std::size(sModuleMap); idx++) { + for (unsigned int idx = 0; idx < ArrayLength(sModuleMap); idx++) { if (strncmp(token, sModuleMap[idx].mStr, tokenLen) == 0) { #if !defined(MOZ_PROFILING) && (!defined(DEBUG) || defined(MOZ_OPTIMIZE)) // Stack tracing on profiling enabled or debug not optimized builds. @@ -977,7 +977,7 @@ bool logging::IsEnabledAll(uint32_t aModules) { } bool logging::IsEnabled(const nsAString& aModuleStr) { - for (unsigned int idx = 0; idx < std::size(sModuleMap); idx++) { + for (unsigned int idx = 0; idx < ArrayLength(sModuleMap); idx++) { if (aModuleStr.EqualsASCII(sModuleMap[idx].mStr)) { return sModules & sModuleMap[idx].mModule; } diff --git a/accessible/base/TextAttrs.cpp b/accessible/base/TextAttrs.cpp index f6389d7af07f65..e1ca62e549baf7 100644 --- a/accessible/base/TextAttrs.cpp +++ b/accessible/base/TextAttrs.cpp @@ -127,14 +127,14 @@ void TextAttrsMgr::GetAttributes(AccAttributes* aAttributes, // Expose text attributes if applicable. if (aAttributes) { - for (uint32_t idx = 0; idx < std::size(attrArray); idx++) { + for (uint32_t idx = 0; idx < ArrayLength(attrArray); idx++) { attrArray[idx]->Expose(aAttributes, mIncludeDefAttrs); } } // Expose text attributes range where they are applied if applicable. if (aStartOffset) { - GetRange(attrArray, std::size(attrArray), aStartOffset, aEndOffset); + GetRange(attrArray, ArrayLength(attrArray), aStartOffset, aEndOffset); } } diff --git a/accessible/base/TextLeafRange.cpp b/accessible/base/TextLeafRange.cpp index 772ac61b2f568b..6effcb1897afd1 100644 --- a/accessible/base/TextLeafRange.cpp +++ b/accessible/base/TextLeafRange.cpp @@ -470,7 +470,7 @@ FindDOMTextOffsetAttributes(LocalAccessible* aAcc, int32_t aRenderedStart, {SelectionType::eSpellCheck, nsGkAtoms::spelling}, {SelectionType::eTargetText, nsGkAtoms::mark}, }; - result.SetCapacity(std::size(kSelectionTypesToAttributes)); + result.SetCapacity(ArrayLength(kSelectionTypesToAttributes)); for (auto [selType, attr] : kSelectionTypesToAttributes) { dom::Selection* domSel = frameSel->GetSelection(selType); if (!domSel) { diff --git a/accessible/base/nsAccessibilityService.cpp b/accessible/base/nsAccessibilityService.cpp index 9503bd7aab1425..ca61594820d3dc 100644 --- a/accessible/base/nsAccessibilityService.cpp +++ b/accessible/base/nsAccessibilityService.cpp @@ -453,9 +453,9 @@ uint64_t nsAccessibilityService::gCacheDomains = nsAccessibilityService::kDefaultCacheDomains; nsAccessibilityService::nsAccessibilityService() - : mHTMLMarkupMap(std::size(sHTMLMarkupMapList)), - mMathMLMarkupMap(std::size(sMathMLMarkupMapList)), - mXULMarkupMap(std::size(sXULMarkupMapList)) {} + : mHTMLMarkupMap(ArrayLength(sHTMLMarkupMapList)), + mMathMLMarkupMap(ArrayLength(sMathMLMarkupMapList)), + mXULMarkupMap(ArrayLength(sXULMarkupMapList)) {} nsAccessibilityService::~nsAccessibilityService() { NS_ASSERTION(IsShutdown(), "Accessibility wasn't shutdown!"); @@ -1082,10 +1082,10 @@ already_AddRefed nsAccessibilityService::GetStringStates( void nsAccessibilityService::GetStringEventType(uint32_t aEventType, nsAString& aString) { static_assert( - nsIAccessibleEvent::EVENT_LAST_ENTRY == std::size(kEventTypeNames), + nsIAccessibleEvent::EVENT_LAST_ENTRY == ArrayLength(kEventTypeNames), "nsIAccessibleEvent constants are out of sync to kEventTypeNames"); - if (aEventType >= std::size(kEventTypeNames)) { + if (aEventType >= ArrayLength(kEventTypeNames)) { aString.AssignLiteral("unknown"); return; } @@ -1095,10 +1095,11 @@ void nsAccessibilityService::GetStringEventType(uint32_t aEventType, void nsAccessibilityService::GetStringEventType(uint32_t aEventType, nsACString& aString) { - MOZ_ASSERT(nsIAccessibleEvent::EVENT_LAST_ENTRY == std::size(kEventTypeNames), - "nsIAccessibleEvent constants are out of sync to kEventTypeNames"); + MOZ_ASSERT( + nsIAccessibleEvent::EVENT_LAST_ENTRY == ArrayLength(kEventTypeNames), + "nsIAccessibleEvent constants are out of sync to kEventTypeNames"); - if (aEventType >= std::size(kEventTypeNames)) { + if (aEventType >= ArrayLength(kEventTypeNames)) { aString.AssignLiteral("unknown"); return; } @@ -1536,7 +1537,7 @@ bool nsAccessibilityService::Init(uint64_t aCacheDomains) { eventListenerService->AddListenerChangeListener(this); - for (uint32_t i = 0; i < std::size(sHTMLMarkupMapList); i++) { + for (uint32_t i = 0; i < ArrayLength(sHTMLMarkupMapList); i++) { mHTMLMarkupMap.InsertOrUpdate(sHTMLMarkupMapList[i].tag, &sHTMLMarkupMapList[i]); } @@ -1544,7 +1545,7 @@ bool nsAccessibilityService::Init(uint64_t aCacheDomains) { mMathMLMarkupMap.InsertOrUpdate(info.tag, &info); } - for (uint32_t i = 0; i < std::size(sXULMarkupMapList); i++) { + for (uint32_t i = 0; i < ArrayLength(sXULMarkupMapList); i++) { mXULMarkupMap.InsertOrUpdate(sXULMarkupMapList[i].tag, &sXULMarkupMapList[i]); } @@ -1755,7 +1756,7 @@ void nsAccessibilityService::MarkupAttributes( if (!markupMap) return; dom::Element* el = aAcc->IsLocal() ? aAcc->AsLocal()->Elm() : nullptr; - for (uint32_t i = 0; i < std::size(markupMap->attrs); i++) { + for (uint32_t i = 0; i < ArrayLength(markupMap->attrs); i++) { const MarkupAttrInfo* info = markupMap->attrs + i; if (!info->name) break; diff --git a/accessible/base/nsAccessibilityService.h b/accessible/base/nsAccessibilityService.h index cf751ac500676d..d5d667caef8967 100644 --- a/accessible/base/nsAccessibilityService.h +++ b/accessible/base/nsAccessibilityService.h @@ -311,7 +311,7 @@ class nsAccessibilityService final : public mozilla::a11y::DocManager, const mozilla::a11y::MarkupMapInfo* markupMap = GetMarkupMapInfoFor(aSource); if (markupMap) { - for (size_t i = 0; i < std::size(markupMap->attrs); i++) { + for (size_t i = 0; i < mozilla::ArrayLength(markupMap->attrs); i++) { const mozilla::a11y::MarkupAttrInfo* info = markupMap->attrs + i; if (info->name == aAtom) { return info->value; diff --git a/accessible/generic/DocAccessible.cpp b/accessible/generic/DocAccessible.cpp index ccb718fb586b6d..d62045216cbff0 100644 --- a/accessible/generic/DocAccessible.cpp +++ b/accessible/generic/DocAccessible.cpp @@ -65,7 +65,7 @@ static nsStaticAtom* const kRelationAttrs[] = { nsGkAtoms::aria_errormessage, nsGkAtoms::_for, nsGkAtoms::control, nsGkAtoms::popovertarget}; -static const uint32_t kRelationAttrsLen = std::size(kRelationAttrs); +static const uint32_t kRelationAttrsLen = ArrayLength(kRelationAttrs); static nsStaticAtom* const kSingleElementRelationIdlAttrs[] = { nsGkAtoms::popovertarget}; diff --git a/accessible/generic/RootAccessible.cpp b/accessible/generic/RootAccessible.cpp index 0e21e0c32ae35b..aea5d4c84ca5e9 100644 --- a/accessible/generic/RootAccessible.cpp +++ b/accessible/generic/RootAccessible.cpp @@ -153,7 +153,7 @@ nsresult RootAccessible::AddEventListeners() { if (nstarget) { for (const char *const *e = kEventTypes, *const *e_end = - std::end(kEventTypes); + ArrayEnd(kEventTypes); e < e_end; ++e) { nsresult rv = nstarget->AddEventListener(NS_ConvertASCIItoUTF16(*e), this, true, true); @@ -169,7 +169,7 @@ nsresult RootAccessible::RemoveEventListeners() { nsCOMPtr target = window ? window->GetParentTarget() : nullptr; if (target) { for (const char *const *e = kEventTypes, *const *e_end = - std::end(kEventTypes); + ArrayEnd(kEventTypes); e < e_end; ++e) { target->RemoveEventListener(NS_ConvertASCIItoUTF16(*e), this, true); } diff --git a/accessible/ipc/RemoteAccessible.cpp b/accessible/ipc/RemoteAccessible.cpp index 73529abc547977..8c32baa75e1574 100644 --- a/accessible/ipc/RemoteAccessible.cpp +++ b/accessible/ipc/RemoteAccessible.cpp @@ -1234,7 +1234,7 @@ nsTArray RemoteAccessible::PreProcessRelations(AccAttributes* aFields) { if (!DomainsAreActive(CacheDomain::Relations)) { return {}; } - nsTArray updateTracker(std::size(kRelationTypeAtoms)); + nsTArray updateTracker(ArrayLength(kRelationTypeAtoms)); for (auto const& data : kRelationTypeAtoms) { if (data.mValidTag) { // The relation we're currently processing only applies to particular @@ -1310,7 +1310,7 @@ void RemoteAccessible::PostProcessRelations(const nsTArray& aToUpdate) { return; } size_t updateCount = aToUpdate.Length(); - MOZ_ASSERT(updateCount == std::size(kRelationTypeAtoms), + MOZ_ASSERT(updateCount == ArrayLength(kRelationTypeAtoms), "Did not note update status for every relation type!"); for (size_t i = 0; i < updateCount; i++) { if (aToUpdate.ElementAt(i)) { diff --git a/accessible/mac/mozAccessible.mm b/accessible/mac/mozAccessible.mm index 4c27e771c0ae33..315274c8799433 100644 --- a/accessible/mac/mozAccessible.mm +++ b/accessible/mac/mozAccessible.mm @@ -468,7 +468,7 @@ - (NSString*)moxRoleDescription { if (subrole) { size_t idx = 0; - if (BinarySearchIf(sRoleDescrMap, 0, std::size(sRoleDescrMap), + if (BinarySearchIf(sRoleDescrMap, 0, ArrayLength(sRoleDescrMap), RoleDescrComparator(subrole), &idx)) { return utils::LocalizedString(sRoleDescrMap[idx].description); } diff --git a/accessible/windows/ia2/ia2Accessible.cpp b/accessible/windows/ia2/ia2Accessible.cpp index 783a7e9945eba6..5bc421d086d462 100644 --- a/accessible/windows/ia2/ia2Accessible.cpp +++ b/accessible/windows/ia2/ia2Accessible.cpp @@ -77,7 +77,7 @@ ia2Accessible::get_nRelations(long* aNRelations) { return CO_E_OBJNOTCONNECTED; } - for (uint32_t idx = 0; idx < std::size(sRelationTypePairs); idx++) { + for (uint32_t idx = 0; idx < ArrayLength(sRelationTypePairs); idx++) { if (sRelationTypePairs[idx].second == IA2_RELATION_NULL) continue; Relation rel = acc->RelationByType(sRelationTypePairs[idx].first); @@ -98,7 +98,7 @@ ia2Accessible::get_relation(long aRelationIndex, } long relIdx = 0; - for (uint32_t idx = 0; idx < std::size(sRelationTypePairs); idx++) { + for (uint32_t idx = 0; idx < ArrayLength(sRelationTypePairs); idx++) { if (sRelationTypePairs[idx].second == IA2_RELATION_NULL) continue; RelationType relationType = sRelationTypePairs[idx].first; @@ -131,7 +131,7 @@ ia2Accessible::get_relations(long aMaxRelations, } for (uint32_t idx = 0; - idx < std::size(sRelationTypePairs) && *aNRelations < aMaxRelations; + idx < ArrayLength(sRelationTypePairs) && *aNRelations < aMaxRelations; idx++) { if (sRelationTypePairs[idx].second == IA2_RELATION_NULL) continue; @@ -484,7 +484,7 @@ ia2Accessible::get_relationTargetsOfType(BSTR aType, long aMaxTargets, *aNTargets = 0; Maybe relationType; - for (uint32_t idx = 0; idx < std::size(sRelationTypePairs); idx++) { + for (uint32_t idx = 0; idx < ArrayLength(sRelationTypePairs); idx++) { if (wcscmp(aType, sRelationTypePairs[idx].second) == 0) { relationType.emplace(sRelationTypePairs[idx].first); break; diff --git a/accessible/windows/msaa/LazyInstantiator.cpp b/accessible/windows/msaa/LazyInstantiator.cpp index 65d554d2888531..3ace26d9c02236 100644 --- a/accessible/windows/msaa/LazyInstantiator.cpp +++ b/accessible/windows/msaa/LazyInstantiator.cpp @@ -210,7 +210,7 @@ bool LazyInstantiator::IsBlockedInjection() { return false; } - for (size_t index = 0, len = std::size(gBlockedInprocDlls); index < len; + for (size_t index = 0, len = ArrayLength(gBlockedInprocDlls); index < len; ++index) { const DllBlockInfo& blockedDll = gBlockedInprocDlls[index]; HMODULE module = ::GetModuleHandleW(blockedDll.mName); @@ -247,7 +247,8 @@ bool LazyInstantiator::ShouldInstantiate(const DWORD aClientPid) { nsAutoString leafName; rv = clientExe->GetLeafName(leafName); if (NS_SUCCEEDED(rv)) { - for (size_t i = 0, len = std::size(gBlockedRemoteClients); i < len; ++i) { + for (size_t i = 0, len = ArrayLength(gBlockedRemoteClients); i < len; + ++i) { if (leafName.EqualsIgnoreCase(gBlockedRemoteClients[i])) { // If client exe is in our blocklist, do not instantiate. return false; diff --git a/accessible/windows/msaa/MsaaAccessible.cpp b/accessible/windows/msaa/MsaaAccessible.cpp index 294c12462a9860..ba6e536d4bf2bc 100644 --- a/accessible/windows/msaa/MsaaAccessible.cpp +++ b/accessible/windows/msaa/MsaaAccessible.cpp @@ -216,7 +216,7 @@ void MsaaAccessible::FireWinEvent(Accessible* aTarget, uint32_t aEventType) { nsIAccessibleEvent::EVENT_LAST_ENTRY, "MSAA event map skewed"); - if (aEventType == 0 || aEventType >= std::size(gWinEventMap)) { + if (aEventType == 0 || aEventType >= ArrayLength(gWinEventMap)) { MOZ_ASSERT_UNREACHABLE("invalid event type"); return; } diff --git a/accessible/windows/uia/uiaRawElmProvider.cpp b/accessible/windows/uia/uiaRawElmProvider.cpp index 70f3bbdc7cd741..a3ee83dc688656 100644 --- a/accessible/windows/uia/uiaRawElmProvider.cpp +++ b/accessible/windows/uia/uiaRawElmProvider.cpp @@ -318,7 +318,7 @@ uiaRawElmProvider::GetRuntimeId(__RPC__deref_out_opt SAFEARRAY** aRuntimeIds) { *aRuntimeIds = SafeArrayCreateVector(VT_I4, 0, 2); if (!*aRuntimeIds) return E_OUTOFMEMORY; - for (LONG i = 0; i < (LONG)std::size(ids); i++) + for (LONG i = 0; i < (LONG)ArrayLength(ids); i++) SafeArrayPutElement(*aRuntimeIds, &i, (void*)&(ids[i])); return S_OK; diff --git a/browser/app/nsBrowserApp.cpp b/browser/app/nsBrowserApp.cpp index cae769cbb64706..517972b3855b21 100644 --- a/browser/app/nsBrowserApp.cpp +++ b/browser/app/nsBrowserApp.cpp @@ -92,7 +92,8 @@ __attribute__((constructor)) static void SSE2Check() { // Using write() in order to avoid jemalloc-based buffering. Ignoring return // values, since there isn't much we could do on failure and there is no // point in trying to recover from errors. - MOZ_UNUSED(write(STDERR_FILENO, sSSE2Message, std::size(sSSE2Message) - 1)); + MOZ_UNUSED( + write(STDERR_FILENO, sSSE2Message, MOZ_ARRAY_LENGTH(sSSE2Message) - 1)); // _exit() instead of exit() to avoid running the usual "at exit" code. _exit(255); } diff --git a/browser/app/winlauncher/ErrorHandler.cpp b/browser/app/winlauncher/ErrorHandler.cpp index 706842446bf8ea..72796da7f4df28 100644 --- a/browser/app/winlauncher/ErrorHandler.cpp +++ b/browser/app/winlauncher/ErrorHandler.cpp @@ -305,7 +305,7 @@ static bool AddWscInfo(mozilla::JSONWriter& aJson) { const CLSID clsid = __uuidof(WSCProductList); const IID iid = __uuidof(IWSCProductList); - for (uint32_t index = 0; index < std::size(gProvKeys); ++index) { + for (uint32_t index = 0; index < mozilla::ArrayLength(gProvKeys); ++index) { // NB: A separate instance of IWSCProductList is needed for each distinct // security provider type; MSDN says that we cannot reuse the same object // and call Initialize() to pave over the previous data. @@ -368,11 +368,11 @@ static bool AddModuleInfo(const nsAutoHandle& aSnapshot, wchar_t leaf[_MAX_FNAME] = {}; if (::_wsplitpath_s(module.szExePath, nullptr, 0, nullptr, 0, leaf, - std::size(leaf), nullptr, 0)) { + mozilla::ArrayLength(leaf), nullptr, 0)) { return false; } - if (_wcslwr_s(leaf, std::size(leaf))) { + if (_wcslwr_s(leaf, mozilla::ArrayLength(leaf))) { return false; } @@ -487,7 +487,8 @@ static bool PrepPing(const PingThreadContext& aContext, const std::wstring& aId, tm gmTm; if (!gmtime_s(&gmTm, &now)) { char isoTimeBuf[32] = {}; - if (strftime(isoTimeBuf, std::size(isoTimeBuf), "%FT%T.000Z", &gmTm)) { + if (strftime(isoTimeBuf, mozilla::ArrayLength(isoTimeBuf), "%FT%T.000Z", + &gmTm)) { aJson.StringProperty("creationDate", isoTimeBuf); } } @@ -532,7 +533,7 @@ static bool PrepPing(const PingThreadContext& aContext, const std::wstring& aId, WCHAR localeName[LOCALE_NAME_MAX_LENGTH] = {}; int localeNameLen = - ::GetUserDefaultLocaleName(localeName, std::size(localeName)); + ::GetUserDefaultLocaleName(localeName, mozilla::ArrayLength(localeName)); if (localeNameLen) { auto localeNameUtf8 = WideToUTF8(localeName, localeNameLen - 1); if (localeNameUtf8) { @@ -646,19 +647,19 @@ static bool DoSendPing(const PingThreadContext& aContext) { wchar_t drive[_MAX_DRIVE] = {}; wchar_t dir[_MAX_DIR] = {}; - if (_wsplitpath_s(exePath.get(), drive, std::size(drive), dir, std::size(dir), - nullptr, 0, nullptr, 0)) { + if (_wsplitpath_s(exePath.get(), drive, mozilla::ArrayLength(drive), dir, + mozilla::ArrayLength(dir), nullptr, 0, nullptr, 0)) { return false; } wchar_t pingSenderPath[MAX_PATH + 1] = {}; - if (_wmakepath_s(pingSenderPath, std::size(pingSenderPath), drive, dir, - L"pingsender", L"exe")) { + if (_wmakepath_s(pingSenderPath, mozilla::ArrayLength(pingSenderPath), drive, + dir, L"pingsender", L"exe")) { return false; } // Construct the telemetry URL - wchar_t urlBuf[std::size(kUrl) + kGuidCharLenNoBracesNoNul] = {}; + wchar_t urlBuf[mozilla::ArrayLength(kUrl) + kGuidCharLenNoBracesNoNul] = {}; if (wcscpy_s(urlBuf, kUrl)) { return false; } @@ -671,8 +672,8 @@ static bool DoSendPing(const PingThreadContext& aContext) { wchar_t* pingSenderArgv[] = {pingSenderPath, urlBuf, const_cast(fileName.c_str())}; - mozilla::UniquePtr pingSenderCmdLine( - mozilla::MakeCommandLine(std::size(pingSenderArgv), pingSenderArgv)); + mozilla::UniquePtr pingSenderCmdLine(mozilla::MakeCommandLine( + mozilla::ArrayLength(pingSenderArgv), pingSenderArgv)); // Now start pingsender to handle the rest PROCESS_INFORMATION pi; diff --git a/browser/app/winlauncher/LaunchUnelevated.cpp b/browser/app/winlauncher/LaunchUnelevated.cpp index c480e77e85c3bd..3cf6ac837c9332 100644 --- a/browser/app/winlauncher/LaunchUnelevated.cpp +++ b/browser/app/winlauncher/LaunchUnelevated.cpp @@ -109,7 +109,7 @@ static mozilla::LauncherResult IsAdminByAppCompat( wchar_t* tokenContext = nullptr; const wchar_t* token = wcstok_s(valueData.get(), kDelimiters, &tokenContext); while (token) { - if (!_wcsnicmp(token, kRunAsAdmin, std::size(kRunAsAdmin))) { + if (!_wcsnicmp(token, kRunAsAdmin, mozilla::ArrayLength(kRunAsAdmin))) { return true; } token = wcstok_s(nullptr, kDelimiters, &tokenContext); diff --git a/browser/app/winlauncher/SameBinary.h b/browser/app/winlauncher/SameBinary.h index f7dd756ec2d636..e8fa78600f32ab 100644 --- a/browser/app/winlauncher/SameBinary.h +++ b/browser/app/winlauncher/SameBinary.h @@ -24,7 +24,7 @@ class ProcessImagePath final { // Initialize with an NT path string of a given process handle explicit ProcessImagePath(const nsAutoHandle& aProcess) : mType(PathType::eNtPath), mLastError(Ok()) { - DWORD len = std::size(mPathBuffer); + DWORD len = mozilla::ArrayLength(mPathBuffer); if (!::QueryFullProcessImageNameW(aProcess.get(), PROCESS_NAME_NATIVE, mPathBuffer, &len)) { mLastError = LAUNCHER_ERROR_FROM_LAST(); @@ -35,9 +35,9 @@ class ProcessImagePath final { // Initizlize with a DOS path string of a given imagebase address explicit ProcessImagePath(HMODULE aImageBase) : mType(PathType::eDosPath), mLastError(Ok()) { - DWORD len = - ::GetModuleFileNameW(aImageBase, mPathBuffer, std::size(mPathBuffer)); - if (!len || len == std::size(mPathBuffer)) { + DWORD len = ::GetModuleFileNameW(aImageBase, mPathBuffer, + mozilla::ArrayLength(mPathBuffer)); + if (!len || len == mozilla::ArrayLength(mPathBuffer)) { mLastError = LAUNCHER_ERROR_FROM_LAST(); return; } diff --git a/browser/app/winlauncher/freestanding/DllBlocklist.cpp b/browser/app/winlauncher/freestanding/DllBlocklist.cpp index f6f8f1540bee9f..f8f9560acba188 100644 --- a/browser/app/winlauncher/freestanding/DllBlocklist.cpp +++ b/browser/app/winlauncher/freestanding/DllBlocklist.cpp @@ -117,10 +117,10 @@ void NativeNtBlockSet::Write(WritableBuffer& aBuffer) { parts[1] = (entry->mVersion >> 32) & 0xFFFF; parts[2] = (entry->mVersion >> 16) & 0xFFFF; parts[3] = entry->mVersion & 0xFFFF; - for (size_t p = 0; p < std::size(parts); ++p) { + for (size_t p = 0; p < mozilla::ArrayLength(parts); ++p) { _ltoa_s(parts[p], buf, sizeof(buf), 10); aBuffer.Write(buf, strlen(buf)); - if (p != std::size(parts) - 1) { + if (p != mozilla::ArrayLength(parts) - 1) { aBuffer.Write(".", 1); } } diff --git a/browser/app/winlauncher/test/TestCrossProcessWin.cpp b/browser/app/winlauncher/test/TestCrossProcessWin.cpp index a129df721d6b86..e002edae506d1b 100644 --- a/browser/app/winlauncher/test/TestCrossProcessWin.cpp +++ b/browser/app/winlauncher/test/TestCrossProcessWin.cpp @@ -79,7 +79,7 @@ class TempFile final { public: TempFile() : mFullPath{0} { wchar_t tempDir[MAX_PATH + 1]; - DWORD len = ::GetTempPathW(std::size(tempDir), tempDir); + DWORD len = ::GetTempPathW(ArrayLength(tempDir), tempDir); if (!len) { return; } @@ -537,7 +537,8 @@ class ChildProcess final { ChildProcess(const wchar_t* aExecutable, const wchar_t* aOption) : mProcessId(0) { const wchar_t* childArgv[] = {aExecutable, aOption}; - auto cmdLine(mozilla::MakeCommandLine(std::size(childArgv), childArgv)); + auto cmdLine( + mozilla::MakeCommandLine(mozilla::ArrayLength(childArgv), childArgv)); STARTUPINFOW si = {sizeof(si)}; PROCESS_INFORMATION pi; diff --git a/browser/app/winlauncher/test/TestSameBinary.cpp b/browser/app/winlauncher/test/TestSameBinary.cpp index 4297336612f1e1..2adc85f4ec2df8 100644 --- a/browser/app/winlauncher/test/TestSameBinary.cpp +++ b/browser/app/winlauncher/test/TestSameBinary.cpp @@ -158,8 +158,8 @@ static nsReturnRef CreateSelfProcess(int argc, wchar_t* argv[]) { wchar_t* extraArgs[] = {strPid}; - auto cmdLine = - mozilla::MakeCommandLine(argc, argv, std::size(extraArgs), extraArgs); + auto cmdLine = mozilla::MakeCommandLine( + argc, argv, mozilla::ArrayLength(extraArgs), extraArgs); if (!cmdLine) { PrintErrorMsg("MakeCommandLine failed"); return empty.out(); diff --git a/browser/components/shell/WindowsDefaultBrowser.cpp b/browser/components/shell/WindowsDefaultBrowser.cpp index f39425829e8469..4e73e9d0225321 100644 --- a/browser/components/shell/WindowsDefaultBrowser.cpp +++ b/browser/components/shell/WindowsDefaultBrowser.cpp @@ -29,7 +29,7 @@ static bool IsWindowsLogonConnected() { WCHAR userName[UNLEN + 1]; - DWORD size = std::size(userName); + DWORD size = mozilla::ArrayLength(userName); if (!GetUserNameW(userName, &size)) { return false; } diff --git a/browser/components/shell/WindowsUserChoice.cpp b/browser/components/shell/WindowsUserChoice.cpp index 2a7b3e185864a0..d533a1d8b36959 100644 --- a/browser/components/shell/WindowsUserChoice.cpp +++ b/browser/components/shell/WindowsUserChoice.cpp @@ -400,7 +400,7 @@ bool CheckBrowserUserChoiceHashes() { const wchar_t* exts[] = {L"https", L"http", L".html", L".htm"}; - for (size_t i = 0; i < std::size(exts); ++i) { + for (size_t i = 0; i < ArrayLength(exts); ++i) { switch (CheckUserChoiceHash(exts[i], userSid.get())) { case CheckUserChoiceHashResult::OK_V1: break; diff --git a/browser/components/shell/nsGNOMEShellService.cpp b/browser/components/shell/nsGNOMEShellService.cpp index 9f50c46db5c7a1..987e8ae78bbd2f 100644 --- a/browser/components/shell/nsGNOMEShellService.cpp +++ b/browser/components/shell/nsGNOMEShellService.cpp @@ -206,7 +206,7 @@ nsGNOMEShellService::IsDefaultBrowser(bool aForAllTypes, nsAutoCString handler; nsCOMPtr gioApp; - for (unsigned int i = 0; i < std::size(appProtocols); ++i) { + for (unsigned int i = 0; i < ArrayLength(appProtocols); ++i) { if (!appProtocols[i].essential) continue; if (!IsDefaultForSchemeHelper(nsDependentCString(appProtocols[i].name), @@ -298,7 +298,7 @@ nsGNOMEShellService::SetDefaultBrowser(bool aForAllUsers) { } // set handler for the protocols - for (unsigned int i = 0; i < std::size(appProtocols); ++i) { + for (unsigned int i = 0; i < ArrayLength(appProtocols); ++i) { appInfo->SetAsDefaultForURIScheme( nsDependentCString(appProtocols[i].name)); } @@ -306,7 +306,7 @@ nsGNOMEShellService::SetDefaultBrowser(bool aForAllUsers) { // set handler for .html and xhtml files and MIME types: // Add mime types for html, xhtml extension and set app to just created // appinfo. - for (unsigned int i = 0; i < std::size(appTypes); ++i) { + for (unsigned int i = 0; i < ArrayLength(appTypes); ++i) { appInfo->SetAsDefaultForMimeType( nsDependentCString(appTypes[i].mimeType)); appInfo->SetAsDefaultForFileExtensions( diff --git a/browser/components/shell/nsWindowsShellService.cpp b/browser/components/shell/nsWindowsShellService.cpp index 8dc5a6ab7135c3..9a9a48d32bbca4 100644 --- a/browser/components/shell/nsWindowsShellService.cpp +++ b/browser/components/shell/nsWindowsShellService.cpp @@ -1169,7 +1169,7 @@ static nsresult GetMatchingShortcut(int aCSIDL, const nsAString& aAUMID, static_assert(MAXPATHLEN == MAX_PATH); wchar_t storedExePath[MAX_PATH] = {}; // With no flags GetPath gets a long path - hr = link->GetPath(storedExePath, std::size(storedExePath), nullptr, 0); + hr = link->GetPath(storedExePath, ArrayLength(storedExePath), nullptr, 0); if (FAILED(hr) || hr == S_FALSE) { continue; } @@ -1394,7 +1394,7 @@ static bool IsCurrentAppPinnedToTaskbarSync(const nsAString& aumid) { static_assert(MAXPATHLEN == MAX_PATH); wchar_t storedExePath[MAX_PATH] = {}; // With no flags GetPath gets a long path - hr = link->GetPath(storedExePath, std::size(storedExePath), nullptr, 0); + hr = link->GetPath(storedExePath, ArrayLength(storedExePath), nullptr, 0); if (FAILED(hr) || hr == S_FALSE) { continue; } @@ -2579,7 +2579,7 @@ nsWindowsShellService::ClassifyShortcut(const nsAString& aPath, {FOLDERID_UserPinned, u"\\TaskBar\\", u"Taskbar"}, {FOLDERID_UserPinned, u"\\StartMenu\\", u"StartMenu"}}; - for (size_t i = 0; i < std::size(folders); ++i) { + for (size_t i = 0; i < ArrayLength(folders); ++i) { nsAutoString knownPath; // These flags are chosen to avoid I/O, see bug 1363398. diff --git a/caps/BasePrincipal.cpp b/caps/BasePrincipal.cpp index ff983897020317..1cd6e4ae3d5090 100644 --- a/caps/BasePrincipal.cpp +++ b/caps/BasePrincipal.cpp @@ -372,7 +372,7 @@ nsresult BasePrincipal::ToJSON(nsACString& aJSON) { } nsresult BasePrincipal::ToJSON(JSONWriter& aWriter) { - static_assert(eKindMax < std::size(JSONEnumKeyStrings)); + static_assert(eKindMax < ArrayLength(JSONEnumKeyStrings)); aWriter.Start(JSONWriter::CollectionStyle::SingleLineStyle); diff --git a/caps/BasePrincipal.h b/caps/BasePrincipal.h index c5f0a811232929..79ab9891c2ee26 100644 --- a/caps/BasePrincipal.h +++ b/caps/BasePrincipal.h @@ -361,7 +361,7 @@ class BasePrincipal : public nsJSPrincipals { protected: template static inline constexpr const Span& JSONEnumKeyString() { - static_assert(EnumValue < std::size(JSONEnumKeyStrings)); + static_assert(EnumValue < ArrayLength(JSONEnumKeyStrings)); return JSONEnumKeyStrings[EnumValue]; } template diff --git a/caps/nsScriptSecurityManager.cpp b/caps/nsScriptSecurityManager.cpp index ee3ced1ed7c02c..292302df820d3f 100644 --- a/caps/nsScriptSecurityManager.cpp +++ b/caps/nsScriptSecurityManager.cpp @@ -1213,7 +1213,7 @@ nsScriptSecurityManager::CheckLoadURIStrWithPrincipal( // available. uint32_t flags[] = {nsIURIFixup::FIXUP_FLAG_NONE, nsIURIFixup::FIXUP_FLAG_FIX_SCHEME_TYPOS}; - for (uint32_t i = 0; i < std::size(flags); ++i) { + for (uint32_t i = 0; i < ArrayLength(flags); ++i) { uint32_t fixupFlags = flags[i]; if (aPrincipal->OriginAttributesRef().IsPrivateBrowsing()) { fixupFlags |= nsIURIFixup::FIXUP_FLAG_PRIVATE_CONTEXT; diff --git a/docshell/base/nsAboutRedirector.cpp b/docshell/base/nsAboutRedirector.cpp index 213f5085f483cb..b21078b00b14cd 100644 --- a/docshell/base/nsAboutRedirector.cpp +++ b/docshell/base/nsAboutRedirector.cpp @@ -212,7 +212,7 @@ static const RedirEntry kRedirMap[] = { nsIAboutModule::URI_MUST_LOAD_IN_CHILD}, {"crashgpu", "about:blank", nsIAboutModule::HIDE_FROM_ABOUTABOUT}, {"crashextensions", "about:blank", nsIAboutModule::HIDE_FROM_ABOUTABOUT}}; -static const int kRedirTotal = std::size(kRedirMap); +static const int kRedirTotal = mozilla::ArrayLength(kRedirMap); NS_IMETHODIMP nsAboutRedirector::NewChannel(nsIURI* aURI, nsILoadInfo* aLoadInfo, diff --git a/dom/base/CCGCScheduler.cpp b/dom/base/CCGCScheduler.cpp index 88d8cb6362151c..d25279e49495ba 100644 --- a/dom/base/CCGCScheduler.cpp +++ b/dom/base/CCGCScheduler.cpp @@ -782,8 +782,9 @@ CCRunnerStep CCGCScheduler::AdvanceCCRunner(TimeStamp aDeadline, TimeStamp aNow, {false, false}, /* CCRunnerState::StartCycleCollection */ {false, false}, /* CCRunnerState::CycleCollecting */ {false, false}}; /* CCRunnerState::Canceled */ - static_assert(std::size(stateDescriptors) == size_t(CCRunnerState::NumStates), - "need one state descriptor per state"); + static_assert( + ArrayLength(stateDescriptors) == size_t(CCRunnerState::NumStates), + "need one state descriptor per state"); const StateDescriptor& desc = stateDescriptors[int(mCCRunnerState)]; // Make sure we initialized the state machine. diff --git a/dom/base/DOMException.cpp b/dom/base/DOMException.cpp index b73e2199feb22d..8bb60054a5112d 100644 --- a/dom/base/DOMException.cpp +++ b/dom/base/DOMException.cpp @@ -99,7 +99,7 @@ static void NSResultToNameAndMessage(nsresult aNSResult, nsCString& aName, aName.Truncate(); aMessage.Truncate(); *aCode = 0; - for (uint32_t idx = 0; idx < std::size(sDOMErrorMsgMap); idx++) { + for (uint32_t idx = 0; idx < ArrayLength(sDOMErrorMsgMap); idx++) { if (aNSResult == sDOMErrorMsgMap[idx].mNSResult) { aName.Rebind(sDOMErrorMsgMap[idx].mName, strlen(sDOMErrorMsgMap[idx].mName)); @@ -355,7 +355,7 @@ already_AddRefed DOMException::Constructor( if (aName.WasPassed()) { CopyUTF16toUTF8(aName.Value(), name); - for (uint32_t idx = 0; idx < std::size(sDOMErrorMsgMap); idx++) { + for (uint32_t idx = 0; idx < ArrayLength(sDOMErrorMsgMap); idx++) { if (name.EqualsASCII(sDOMErrorMsgMap[idx].mName)) { exceptionResult = sDOMErrorMsgMap[idx].mNSResult; exceptionCode = sDOMErrorMsgMap[idx].mCode; diff --git a/dom/base/Document.cpp b/dom/base/Document.cpp index 09b50a9a11f498..dbaba76985d397 100644 --- a/dom/base/Document.cpp +++ b/dom/base/Document.cpp @@ -2533,7 +2533,7 @@ NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INTERNAL(Document) static const char* kNSURIs[] = {"([none])", "(xmlns)", "(xml)", "(xhtml)", "(XLink)", "(XSLT)", "(MathML)", "(RDF)", "(XUL)"}; - if (nsid < std::size(kNSURIs)) { + if (nsid < ArrayLength(kNSURIs)) { SprintfLiteral(name, "Document %s %s %s", loadedAsData.get(), kNSURIs[nsid], uri.get()); } else { diff --git a/dom/base/FragmentOrElement.cpp b/dom/base/FragmentOrElement.cpp index 995e9d792a2568..a122dd1bf74ece 100644 --- a/dom/base/FragmentOrElement.cpp +++ b/dom/base/FragmentOrElement.cpp @@ -1819,13 +1819,13 @@ static inline bool IsVoidTag(nsAtom* aTag) { static bool sInitialized = false; if (!sInitialized) { sInitialized = true; - for (uint32_t i = 0; i < std::size(voidElements); ++i) { + for (uint32_t i = 0; i < ArrayLength(voidElements); ++i) { sFilter.add(voidElements[i]); } } if (sFilter.mightContain(aTag)) { - for (uint32_t i = 0; i < std::size(voidElements); ++i) { + for (uint32_t i = 0; i < ArrayLength(voidElements); ++i) { if (aTag == voidElements[i]) { return true; } diff --git a/dom/base/nsContentUtils.cpp b/dom/base/nsContentUtils.cpp index e2739c817d8cbf..80df23b73f132c 100644 --- a/dom/base/nsContentUtils.cpp +++ b/dom/base/nsContentUtils.cpp @@ -1022,13 +1022,13 @@ bool nsContentUtils::InitializeEventTable() { {nullptr}}; sAtomEventTable = - new nsTHashMap, EventNameMapping>(std::size(eventArray)); - sStringEventTable = - new nsTHashMap(std::size(eventArray)); + new nsTHashMap, EventNameMapping>(ArrayLength(eventArray)); + sStringEventTable = new nsTHashMap( + ArrayLength(eventArray)); sUserDefinedEvents = new nsTArray>(64); // Subtract one from the length because of the trailing null - for (uint32_t i = 0; i < std::size(eventArray) - 1; ++i) { + for (uint32_t i = 0; i < ArrayLength(eventArray) - 1; ++i) { MOZ_ASSERT(!sAtomEventTable->Contains(eventArray[i].mAtom), "Double-defining event name; fix your EventNameList.h"); sAtomEventTable->InsertOrUpdate(eventArray[i].mAtom, eventArray[i]); @@ -1053,7 +1053,7 @@ void nsContentUtils::InitializeTouchEventTable() { #undef EVENT {nullptr}}; // Subtract one from the length because of the trailing null - for (uint32_t i = 0; i < std::size(touchEventArray) - 1; ++i) { + for (uint32_t i = 0; i < ArrayLength(touchEventArray) - 1; ++i) { sAtomEventTable->InsertOrUpdate(touchEventArray[i].mAtom, touchEventArray[i]); sStringEventTable->InsertOrUpdate( @@ -6149,7 +6149,7 @@ const nsDependentString nsContentUtils::GetLocalizedEllipsis() { nsAutoString tmp; Preferences::GetLocalizedString("intl.ellipsis", tmp); uint32_t len = - std::min(uint32_t(tmp.Length()), uint32_t(std::size(sBuf) - 1)); + std::min(uint32_t(tmp.Length()), uint32_t(ArrayLength(sBuf) - 1)); CopyUnicodeTo(tmp, 0, sBuf, len); } if (!sBuf[0]) sBuf[0] = char16_t(0x2026); @@ -9455,8 +9455,8 @@ static void AppendEncodedCharacters(const nsTextFragment* aText, // eg < in it. We subtract 1 for the null terminator, then 1 more for the // existing character that will be replaced. constexpr uint32_t maxCharExtraSpace = - std::max({std::size("<"), std::size(">"), std::size("&"), - std::size(" ")}) - + std::max({ArrayLength("<"), ArrayLength(">"), + ArrayLength("&"), ArrayLength(" ")}) - 2; static_assert(maxCharExtraSpace < 100, "Possible underflow"); CheckedInt maxExtraSpace = @@ -9496,7 +9496,8 @@ static CheckedInt ExtraSpaceNeededForAttrEncoding( // & in it. We subtract 1 for the null terminator, then 1 more for the // existing character that will be replaced. constexpr uint32_t maxCharExtraSpace = - std::max({std::size("""), std::size("&"), std::size(" ")}) - + std::max({ArrayLength("""), ArrayLength("&"), + ArrayLength(" ")}) - 2; static_assert(maxCharExtraSpace < 100, "Possible underflow"); return CheckedInt(numEncodedChars) * maxCharExtraSpace; diff --git a/dom/base/nsGlobalWindowInner.cpp b/dom/base/nsGlobalWindowInner.cpp index 4c1c7ff6b45a40..e875d3efcf4bbf 100644 --- a/dom/base/nsGlobalWindowInner.cpp +++ b/dom/base/nsGlobalWindowInner.cpp @@ -3136,7 +3136,7 @@ bool nsGlobalWindowInner::ResolveComponentsShim( // Define a bunch of shims from the Ci.nsIDOMFoo to window.Foo for DOM // interfaces with constants. - for (uint32_t i = 0; i < std::size(kInterfaceShimMap); ++i) { + for (uint32_t i = 0; i < ArrayLength(kInterfaceShimMap); ++i) { // Grab the names from the table. const char* geckoName = kInterfaceShimMap[i].geckoName; const char* domName = kInterfaceShimMap[i].domName; diff --git a/dom/base/nsINode.cpp b/dom/base/nsINode.cpp index b7622840addf26..03990e9ed30f4d 100644 --- a/dom/base/nsINode.cpp +++ b/dom/base/nsINode.cpp @@ -910,11 +910,11 @@ static const char* NodeTypeAsString(nsINode* aNode) { "a DocumentFragment", "a Notation", }; - static_assert(std::size(NodeTypeStrings) == nsINode::MAX_NODE_TYPE + 1, + static_assert(ArrayLength(NodeTypeStrings) == nsINode::MAX_NODE_TYPE + 1, "Max node type out of range for our array"); uint16_t nodeType = aNode->NodeType(); - MOZ_RELEASE_ASSERT(nodeType < std::size(NodeTypeStrings), + MOZ_RELEASE_ASSERT(nodeType < ArrayLength(NodeTypeStrings), "Uknown out-of-range node type"); return NodeTypeStrings[nodeType]; } diff --git a/dom/base/nsMimeTypeArray.cpp b/dom/base/nsMimeTypeArray.cpp index bf5f3f5ec21b97..376c7e106576c0 100644 --- a/dom/base/nsMimeTypeArray.cpp +++ b/dom/base/nsMimeTypeArray.cpp @@ -43,7 +43,7 @@ nsPIDOMWindowInner* nsMimeTypeArray::GetParentObject() const { } nsMimeType* nsMimeTypeArray::IndexedGetter(uint32_t aIndex, bool& aFound) { - if (!ForceNoPlugins() && aIndex < std::size(mMimeTypes)) { + if (!ForceNoPlugins() && aIndex < ArrayLength(mMimeTypes)) { aFound = true; return mMimeTypes[aIndex]; } diff --git a/dom/base/nsMimeTypeArray.h b/dom/base/nsMimeTypeArray.h index ce54abb8b62a67..207f5dc5424d9a 100644 --- a/dom/base/nsMimeTypeArray.h +++ b/dom/base/nsMimeTypeArray.h @@ -35,7 +35,7 @@ class nsMimeTypeArray final : public nsISupports, public nsWrapperCache { JS::Handle aGivenProto) override; // MimeTypeArray WebIDL methods - uint32_t Length() { return ForceNoPlugins() ? 0 : std::size(mMimeTypes); } + uint32_t Length() { return ForceNoPlugins() ? 0 : ArrayLength(mMimeTypes); } nsMimeType* Item(uint32_t aIndex) { bool unused; diff --git a/dom/base/nsNameSpaceManager.cpp b/dom/base/nsNameSpaceManager.cpp index 6ba0e7dddaafd2..5c9543ea222396 100644 --- a/dom/base/nsNameSpaceManager.cpp +++ b/dom/base/nsNameSpaceManager.cpp @@ -167,7 +167,7 @@ const char* nsNameSpaceManager::GetNameSpaceDisplayName(uint32_t aNameSpaceID) { static const char* kNSURIs[] = {"([none])", "(xmlns)", "(xml)", "(xhtml)", "(XLink)", "(XSLT)", "(MathML)", "(RDF)", "(XUL)", "(SVG)"}; - if (aNameSpaceID < std::size(kNSURIs)) { + if (aNameSpaceID < ArrayLength(kNSURIs)) { return kNSURIs[aNameSpaceID]; } return ""; diff --git a/dom/base/nsPluginArray.cpp b/dom/base/nsPluginArray.cpp index b5ce8b5c113483..7517f0506cf65c 100644 --- a/dom/base/nsPluginArray.cpp +++ b/dom/base/nsPluginArray.cpp @@ -36,12 +36,12 @@ nsPluginArray::nsPluginArray(nsPIDOMWindowInner* aWindow) : mWindow(aWindow) { mPlugins[0] = MakeRefPtr(this, aWindow, kMainPluginName); mozilla::Array, 2> mimeTypes; - for (uint32_t i = 0; i < std::size(kMimeTypeNames); ++i) { + for (uint32_t i = 0; i < ArrayLength(kMimeTypeNames); ++i) { mimeTypes[i] = MakeRefPtr(mPlugins[0], kMimeTypeNames[i]); } mMimeTypeArray = MakeRefPtr(aWindow, mimeTypes); - for (uint32_t i = 0; i < std::size(kExtraPluginNames); ++i) { + for (uint32_t i = 0; i < ArrayLength(kExtraPluginNames); ++i) { mPlugins[i + 1] = MakeRefPtr(this, aWindow, kExtraPluginNames[i]); } @@ -60,7 +60,7 @@ JSObject* nsPluginArray::WrapObject(JSContext* aCx, } nsPluginElement* nsPluginArray::IndexedGetter(uint32_t aIndex, bool& aFound) { - if (!ForceNoPlugins() && aIndex < std::size(mPlugins)) { + if (!ForceNoPlugins() && aIndex < ArrayLength(mPlugins)) { aFound = true; return mPlugins[aIndex]; } diff --git a/dom/base/nsPluginArray.h b/dom/base/nsPluginArray.h index b3e70642f1b4a2..7b1cc6544075ab 100644 --- a/dom/base/nsPluginArray.h +++ b/dom/base/nsPluginArray.h @@ -39,7 +39,7 @@ class nsPluginArray final : public nsSupportsWeakReference, nsMimeTypeArray* MimeTypeArray() { return mMimeTypeArray; } // PluginArray WebIDL methods - uint32_t Length() { return ForceNoPlugins() ? 0 : std::size(mPlugins); } + uint32_t Length() { return ForceNoPlugins() ? 0 : ArrayLength(mPlugins); } nsPluginElement* Item(uint32_t aIndex) { bool unused; diff --git a/dom/base/nsTreeSanitizer.cpp b/dom/base/nsTreeSanitizer.cpp index cb2c125747906a..f59249cbde9169 100644 --- a/dom/base/nsTreeSanitizer.cpp +++ b/dom/base/nsTreeSanitizer.cpp @@ -2352,61 +2352,61 @@ void nsTreeSanitizer::LogMessage(const char* aMessage, Document* aDoc, void nsTreeSanitizer::InitializeStatics() { MOZ_ASSERT(!sElementsHTML, "Initializing a second time."); - sElementsHTML = new AtomsTable(std::size(kElementsHTML)); + sElementsHTML = new AtomsTable(ArrayLength(kElementsHTML)); for (uint32_t i = 0; kElementsHTML[i]; i++) { sElementsHTML->Insert(kElementsHTML[i]); } - sAttributesHTML = new AtomsTable(std::size(kAttributesHTML)); + sAttributesHTML = new AtomsTable(ArrayLength(kAttributesHTML)); for (uint32_t i = 0; kAttributesHTML[i]; i++) { sAttributesHTML->Insert(kAttributesHTML[i]); } - sPresAttributesHTML = new AtomsTable(std::size(kPresAttributesHTML)); + sPresAttributesHTML = new AtomsTable(ArrayLength(kPresAttributesHTML)); for (uint32_t i = 0; kPresAttributesHTML[i]; i++) { sPresAttributesHTML->Insert(kPresAttributesHTML[i]); } - sElementsSVG = new AtomsTable(std::size(kElementsSVG)); + sElementsSVG = new AtomsTable(ArrayLength(kElementsSVG)); for (uint32_t i = 0; kElementsSVG[i]; i++) { sElementsSVG->Insert(kElementsSVG[i]); } - sAttributesSVG = new AtomsTable(std::size(kAttributesSVG)); + sAttributesSVG = new AtomsTable(ArrayLength(kAttributesSVG)); for (uint32_t i = 0; kAttributesSVG[i]; i++) { sAttributesSVG->Insert(kAttributesSVG[i]); } - sElementsMathML = new AtomsTable(std::size(kElementsMathML)); + sElementsMathML = new AtomsTable(ArrayLength(kElementsMathML)); for (uint32_t i = 0; kElementsMathML[i]; i++) { sElementsMathML->Insert(kElementsMathML[i]); } - sAttributesMathML = new AtomsTable(std::size(kAttributesMathML)); + sAttributesMathML = new AtomsTable(ArrayLength(kAttributesMathML)); for (uint32_t i = 0; kAttributesMathML[i]; i++) { sAttributesMathML->Insert(kAttributesMathML[i]); } sBaselineAttributeAllowlist = - new AtomsTable(std::size(kBaselineAttributeAllowlist)); + new AtomsTable(ArrayLength(kBaselineAttributeAllowlist)); for (const auto* atom : kBaselineAttributeAllowlist) { sBaselineAttributeAllowlist->Insert(atom); } sBaselineElementAllowlist = - new AtomsTable(std::size(kBaselineElementAllowlist)); + new AtomsTable(ArrayLength(kBaselineElementAllowlist)); for (const auto* atom : kBaselineElementAllowlist) { sBaselineElementAllowlist->Insert(atom); } sDefaultConfigurationAttributeAllowlist = - new AtomsTable(std::size(kDefaultConfigurationAttributeAllowlist)); + new AtomsTable(ArrayLength(kDefaultConfigurationAttributeAllowlist)); for (const auto* atom : kDefaultConfigurationAttributeAllowlist) { sDefaultConfigurationAttributeAllowlist->Insert(atom); } sDefaultConfigurationElementAllowlist = - new AtomsTable(std::size(kDefaultConfigurationElementAllowlist)); + new AtomsTable(ArrayLength(kDefaultConfigurationElementAllowlist)); for (const auto* atom : kDefaultConfigurationElementAllowlist) { sDefaultConfigurationElementAllowlist->Insert(atom); } diff --git a/dom/base/usecounters.py b/dom/base/usecounters.py index 976415099ab8fb..0071be7dffc731 100644 --- a/dom/base/usecounters.py +++ b/dom/base/usecounters.py @@ -729,7 +729,7 @@ def metric_map(f, *inputs): f.write("\n".join(static_asserts)) f.write( """\ - MOZ_ASSERT(size_t(aUseCounter) < std::size(kEntries)); + MOZ_ASSERT(size_t(aUseCounter) < ArrayLength(kEntries)); const auto& entry = kEntries[size_t(aUseCounter)]; (aIsPage ? entry.page_metric : entry.doc_metric).Add(); return entry.name; @@ -771,7 +771,7 @@ def metric_map(f, *inputs): f.write("\n".join(static_asserts)) f.write( """\ - MOZ_ASSERT(size_t(aUseCounter) < std::size(kEntries)); + MOZ_ASSERT(size_t(aUseCounter) < ArrayLength(kEntries)); const auto& entry = kEntries[size_t(aUseCounter)]; switch (aKind) { case WorkerKind::WorkerKindDedicated: diff --git a/dom/bindings/BindingUtils.cpp b/dom/bindings/BindingUtils.cpp index f0da2f41d67833..a21a3dea46f2b2 100644 --- a/dom/bindings/BindingUtils.cpp +++ b/dom/bindings/BindingUtils.cpp @@ -130,7 +130,7 @@ static const JSErrorFormatString ErrorFormatString[] = { static const JSErrorFormatString* GetErrorMessage(void* aUserRef, const unsigned aErrorNumber) { - MOZ_ASSERT(aErrorNumber < std::size(ErrorFormatString)); + MOZ_ASSERT(aErrorNumber < ArrayLength(ErrorFormatString)); return &ErrorFormatString[aErrorNumber]; } diff --git a/dom/bindings/BindingUtils.h b/dom/bindings/BindingUtils.h index 9f57c9a1ba85ee..074916e29d2060 100644 --- a/dom/bindings/BindingUtils.h +++ b/dom/bindings/BindingUtils.h @@ -482,7 +482,7 @@ class ProtoAndIfaceCache { JS::Heap& EntrySlotMustExist(size_t i) { return (*this)[i]; } void Trace(JSTracer* aTracer) { - for (size_t i = 0; i < std::size(*this); ++i) { + for (size_t i = 0; i < ArrayLength(*this); ++i) { JS::TraceEdge(aTracer, &(*this)[i], "protoAndIfaceCache[i]"); } } @@ -497,7 +497,7 @@ class ProtoAndIfaceCache { PageTableCache() { memset(mPages.begin(), 0, sizeof(mPages)); } ~PageTableCache() { - for (size_t i = 0; i < std::size(mPages); ++i) { + for (size_t i = 0; i < ArrayLength(mPages); ++i) { delete mPages[i]; } } @@ -539,10 +539,10 @@ class ProtoAndIfaceCache { } void Trace(JSTracer* trc) { - for (size_t i = 0; i < std::size(mPages); ++i) { + for (size_t i = 0; i < ArrayLength(mPages); ++i) { Page* p = mPages[i]; if (p) { - for (size_t j = 0; j < std::size(*p); ++j) { + for (size_t j = 0; j < ArrayLength(*p); ++j) { JS::TraceEdge(trc, &(*p)[j], "protoAndIfaceCache[i]"); } } @@ -551,7 +551,7 @@ class ProtoAndIfaceCache { size_t SizeOfIncludingThis(MallocSizeOf aMallocSizeOf) { size_t n = aMallocSizeOf(this); - for (size_t i = 0; i < std::size(mPages); ++i) { + for (size_t i = 0; i < ArrayLength(mPages); ++i) { n += aMallocSizeOf(mPages[i]); } return n; @@ -1495,8 +1495,9 @@ inline Maybe StringToEnum(const StringT& aString) { template inline constexpr const nsLiteralCString& GetEnumString(Enum stringId) { - MOZ_RELEASE_ASSERT(static_cast(stringId) < - std::size(binding_detail::EnumStrings::Values)); + MOZ_RELEASE_ASSERT( + static_cast(stringId) < + mozilla::ArrayLength(binding_detail::EnumStrings::Values)); return binding_detail::EnumStrings::Values[static_cast( stringId)]; } diff --git a/dom/bindings/Codegen.py b/dom/bindings/Codegen.py index f213869dedd8d4..c0f5b4a6b0e790 100644 --- a/dom/bindings/Codegen.py +++ b/dom/bindings/Codegen.py @@ -6893,7 +6893,7 @@ def incrementNestingLevel(): defaultCode = fill( """ static const char data[] = { ${data} }; - $${declName} = JS_NewStringCopyN(cx, data, std::size(data) - 1); + $${declName} = JS_NewStringCopyN(cx, data, ArrayLength(data) - 1); if (!$${declName}) { $*{exceptionCode} } @@ -12434,7 +12434,7 @@ def __init__(self, enum): def definition_body(self): return fill( """ - MOZ_ASSERT(uint32_t(aArgument) < std::size(${strings})); + MOZ_ASSERT(uint32_t(aArgument) < ArrayLength(${strings})); JSString* resultStr = JS_NewStringCopyN(aCx, ${strings}[uint32_t(aArgument)].BeginReading(), ${strings}[uint32_t(aArgument)].Length()); @@ -12528,7 +12528,7 @@ def declare(self): static_assert(static_cast<${ty}>(dom::${name}::${minValue}) == 0, "We rely on this in ContiguousEnumValues"); - static_assert(std::size(dom::binding_detail::EnumStrings::Values) - 1 == UnderlyingValue(value), + static_assert(mozilla::ArrayLength(dom::binding_detail::EnumStrings::Values) - 1 == UnderlyingValue(value), "Mismatch between enum strings and enum count"); }; """, diff --git a/dom/bindings/TypedArray.h b/dom/bindings/TypedArray.h index 73f1e05dfdbd36..d3128e18ddfae0 100644 --- a/dom/bindings/TypedArray.h +++ b/dom/bindings/TypedArray.h @@ -163,12 +163,12 @@ namespace mozilla::dom { * … // Getting offset value from somewhere. * uint32_t data[3]; * if (!aUint32Array.CopyDataTo(data, [&](const size_t& aLength) { - * if (aLength - offset != std::size(data)) { + * if (aLength - offset != ArrayLength(data)) { * aError.ThrowTypeError("Typed array doesn't contain the right" * " amount of data"); * return Maybe>(); * } - * return Some(std::make_pair(offset, std::size(data))); + * return Some(std::make_pair(offset, ArrayLength(data))); * }) { * return; * } @@ -213,12 +213,12 @@ namespace mozilla::dom { * Maybe> buffer = * aUint8Array.CreateFromData>([&]( * const size_t& aLength) { - * if (aLength - offset != std::size(data)) { + * if (aLength - offset != ArrayLength(data)) { * aError.ThrowTypeError( * "Typed array doesn't contain the right amount" of data"); * return Maybe>(); * } - * return Some(std::make_pair(offset, std::size(data))); + * return Some(std::make_pair(offset, ArrayLength(data))); * }); * if (buffer.isNothing()) { * return; diff --git a/dom/canvas/WebGLStrongTypes.h b/dom/canvas/WebGLStrongTypes.h index 7c3847d4c7b43a..097cd57b29bfed 100644 --- a/dom/canvas/WebGLStrongTypes.h +++ b/dom/canvas/WebGLStrongTypes.h @@ -185,13 +185,13 @@ bool operator!=(StrongGLenum
a, GLenum b) { #define STRONG_GLENUM_BEGIN(NAME) const uint16_t NAME##Values[] = { #define STRONG_GLENUM_VALUE(VALUE) LOCAL_GL_##VALUE -#define STRONG_GLENUM_END(NAME) \ - } \ - ; \ - struct NAME##Details { \ - static size_t valuesCount() { return std::size(NAME##Values); } \ - static const uint16_t* values() { return NAME##Values; } \ - }; \ +#define STRONG_GLENUM_END(NAME) \ + } \ + ; \ + struct NAME##Details { \ + static size_t valuesCount() { return MOZ_ARRAY_LENGTH(NAME##Values); } \ + static const uint16_t* values() { return NAME##Values; } \ + }; \ typedef StrongGLenum NAME; //////////////////////////////////////////////////////////////////////////////// diff --git a/dom/crypto/CryptoKey.cpp b/dom/crypto/CryptoKey.cpp index f2f13c1cb4a13d..9d1c57b52e0d8f 100644 --- a/dom/crypto/CryptoKey.cpp +++ b/dom/crypto/CryptoKey.cpp @@ -358,7 +358,7 @@ nsresult CryptoKey::AddPublicKeyData(SECKEYPublicKey* aPublicKey) { }; mPrivateKey = - PrivateKeyFromPrivateKeyTemplate(keyTemplate, std::size(keyTemplate)); + PrivateKeyFromPrivateKeyTemplate(keyTemplate, ArrayLength(keyTemplate)); NS_ENSURE_TRUE(mPrivateKey, NS_ERROR_DOM_OPERATION_ERR); return NS_OK; @@ -716,7 +716,7 @@ UniqueSECKEYPrivateKey CryptoKey::PrivateKeyFromJwk(const JsonWebKey& aJwk) { }; return PrivateKeyFromPrivateKeyTemplate(keyTemplate, - std::size(keyTemplate)); + ArrayLength(keyTemplate)); } if (aJwk.mKty.EqualsLiteral(JWK_TYPE_RSA)) { @@ -757,7 +757,7 @@ UniqueSECKEYPrivateKey CryptoKey::PrivateKeyFromJwk(const JsonWebKey& aJwk) { }; return PrivateKeyFromPrivateKeyTemplate(keyTemplate, - std::size(keyTemplate)); + ArrayLength(keyTemplate)); } if (aJwk.mKty.EqualsLiteral(JWK_TYPE_OKP)) { @@ -823,7 +823,7 @@ UniqueSECKEYPrivateKey CryptoKey::PrivateKeyFromJwk(const JsonWebKey& aJwk) { }; return PrivateKeyFromPrivateKeyTemplate(keyTemplate, - std::size(keyTemplate)); + ArrayLength(keyTemplate)); } return nullptr; diff --git a/dom/crypto/WebCryptoCommon.h b/dom/crypto/WebCryptoCommon.h index 73f441e8037ed2..1fb097aef1181f 100644 --- a/dom/crypto/WebCryptoCommon.h +++ b/dom/crypto/WebCryptoCommon.h @@ -132,7 +132,7 @@ struct JSStructuredCloneWriter; static const uint8_t id_ecDH[] = {0x2b, 0x81, 0x04, 0x70}; const SECItem SEC_OID_DATA_EC_DH = { siBuffer, (unsigned char*)id_ecDH, - static_cast(std::size(id_ecDH))}; + static_cast(mozilla::ArrayLength(id_ecDH))}; namespace mozilla::dom { diff --git a/dom/events/Clipboard.cpp b/dom/events/Clipboard.cpp index 93a5a0617a80f3..b15afb6d2a2279 100644 --- a/dom/events/Clipboard.cpp +++ b/dom/events/Clipboard.cpp @@ -292,7 +292,7 @@ void Clipboard::RequestRead(Promise* aPromise, ReadRequestType aType, return; } - AutoTArray types; + AutoTArray types; types.AppendElements(Span(kMandatoryDataTypes)); callback = MakeRefPtr(global, std::move(p)); diff --git a/dom/events/DataTransfer.cpp b/dom/events/DataTransfer.cpp index 8938cd449287b5..cd812e5343ad2c 100644 --- a/dom/events/DataTransfer.cpp +++ b/dom/events/DataTransfer.cpp @@ -287,7 +287,7 @@ void DataTransfer::SetEffectAllowed(const nsAString& aEffectAllowed) { static_assert(nsIDragService::DRAGDROP_ACTION_LINK == 4, "DRAGDROP_ACTION_LINK constant is wrong"); - for (uint32_t e = 0; e < std::size(sEffects); e++) { + for (uint32_t e = 0; e < ArrayLength(sEffects); e++) { if (aEffectAllowed.EqualsASCII(sEffects[e])) { mEffectAllowed = e; break; @@ -727,7 +727,7 @@ void DataTransfer::GetExternalClipboardFormats(const bool& aPlainTextOnly, formats, *mClipboardType, wc, getter_AddRefs(clipboardDataSnapshot)); } } else { - AutoTArray formats; + AutoTArray formats; formats.AppendElements( Span(kNonPlainTextExternalFormats)); if (doContentAnalysis) { @@ -750,7 +750,7 @@ void DataTransfer::GetExternalClipboardFormats(const bool& aPlainTextOnly, // Order is important for DataTransfer; ensure the returned list items follow // the sequence specified in kNonPlainTextExternalFormats. - AutoTArray flavors; + AutoTArray flavors; clipboardDataSnapshot->GetFlavorList(flavors); for (const auto& format : kNonPlainTextExternalFormats) { if (flavors.Contains(format)) { @@ -1443,7 +1443,7 @@ void DataTransfer::CacheExternalDragFormats() { FillInExternalCustomTypes(c, sysPrincipal); } - for (uint32_t f = 0; f < std::size(formats); f++) { + for (uint32_t f = 0; f < ArrayLength(formats); f++) { // IsDataFlavorSupported doesn't take an index as an argument and just // checks if any of the items support a particular flavor, even though // the GetData method does take an index. Here, we just assume that diff --git a/dom/events/DataTransfer.h b/dom/events/DataTransfer.h index 8330c85fbbd09d..c7450c7455e32b 100644 --- a/dom/events/DataTransfer.h +++ b/dom/events/DataTransfer.h @@ -268,7 +268,7 @@ class DataTransfer final : public nsISupports, public nsWrapperCache { */ uint32_t DropEffectInt() const { return mDropEffect; } void SetDropEffectInt(uint32_t aDropEffectInt) { - MOZ_RELEASE_ASSERT(aDropEffectInt < std::size(sEffects), + MOZ_RELEASE_ASSERT(aDropEffectInt < ArrayLength(sEffects), "Bogus drop effect value"); mDropEffect = aDropEffectInt; } diff --git a/dom/events/DataTransferItem.cpp b/dom/events/DataTransferItem.cpp index 24077ea1414128..73437b18b88dbf 100644 --- a/dom/events/DataTransferItem.cpp +++ b/dom/events/DataTransferItem.cpp @@ -94,7 +94,7 @@ void DataTransferItem::SetData(nsIVariant* aData) { MOZ_ASSERT(!mType.EqualsASCII(kNativeImageMime)); mKind = KIND_STRING; - for (uint32_t i = 0; i < std::size(kFileMimeNameMap); ++i) { + for (uint32_t i = 0; i < ArrayLength(kFileMimeNameMap); ++i) { if (mType.EqualsASCII(kFileMimeNameMap[i].mMimeName)) { mKind = KIND_FILE; break; @@ -406,7 +406,7 @@ already_AddRefed DataTransferItem::GetAsEntry( already_AddRefed DataTransferItem::CreateFileFromInputStream( nsIInputStream* aStream) { const char* key = nullptr; - for (uint32_t i = 0; i < std::size(kFileMimeNameMap); ++i) { + for (uint32_t i = 0; i < ArrayLength(kFileMimeNameMap); ++i) { if (mType.EqualsASCII(kFileMimeNameMap[i].mMimeName)) { key = kFileMimeNameMap[i].mFileName; break; diff --git a/dom/events/KeyEventHandler.cpp b/dom/events/KeyEventHandler.cpp index 662de2af95fbb8..3f3ca808e81506 100644 --- a/dom/events/KeyEventHandler.cpp +++ b/dom/events/KeyEventHandler.cpp @@ -487,7 +487,7 @@ int32_t KeyEventHandler::GetMatchingKeyCode(const nsAString& aKeyName) { uint32_t keyNameLength = keyName.Length(); const char* keyNameStr = keyName.get(); - for (unsigned long i = 0; i < std::size(gKeyCodes) - 1; ++i) { + for (unsigned long i = 0; i < ArrayLength(gKeyCodes) - 1; ++i) { if (keyNameLength == gKeyCodes[i].strlength && !nsCRT::strcmp(gKeyCodes[i].str, keyNameStr)) { return gKeyCodes[i].keycode; diff --git a/dom/events/UIEvent.cpp b/dom/events/UIEvent.cpp index 9332071b4562d6..ce43eb08f5967f 100644 --- a/dom/events/UIEvent.cpp +++ b/dom/events/UIEvent.cpp @@ -225,7 +225,7 @@ bool UIEvent::Deserialize(IPC::MessageReader* aReader) { // XXX Following struct and array are used only in // UIEvent::ComputeModifierState(), but if we define them in it, -// we fail to build on Mac at calling std::size(). +// we fail to build on Mac at calling mozilla::ArrayLength(). struct ModifierPair { Modifier modifier; const char* name; @@ -263,7 +263,7 @@ Modifiers UIEvent::ComputeModifierState(const nsAString& aModifiersList) { aModifiersList.BeginReading(listStart); aModifiersList.EndReading(listEnd); - for (uint32_t i = 0; i < std::size(kPairs); i++) { + for (uint32_t i = 0; i < ArrayLength(kPairs); i++) { nsAString::const_iterator start(listStart), end(listEnd); if (!FindInReadable(NS_ConvertASCIItoUTF16(kPairs[i].name), start, end)) { continue; diff --git a/dom/gamepad/GamepadServiceTest.cpp b/dom/gamepad/GamepadServiceTest.cpp index 6b4deed3313974..18998dcc4b00f9 100644 --- a/dom/gamepad/GamepadServiceTest.cpp +++ b/dom/gamepad/GamepadServiceTest.cpp @@ -270,13 +270,13 @@ already_AddRefed GamepadServiceTest::NewPoseMove( GamepadCapabilityFlags::Cap_LinearAcceleration; if (!aOrient.IsNull()) { DebugOnly ok = aOrient.Value().CopyDataTo(poseState.orientation); - MOZ_ASSERT(ok, - "aOrient.Value().Length() != std::size(poseState.orientation)"); + MOZ_ASSERT( + ok, "aOrient.Value().Length() != ArrayLength(poseState.orientation)"); poseState.isOrientationValid = true; } if (!aPos.IsNull()) { DebugOnly ok = aPos.Value().CopyDataTo(poseState.position); - MOZ_ASSERT(ok, "aPos.Value().Length() != std::size(poseState.position)"); + MOZ_ASSERT(ok, "aPos.Value().Length() != ArrayLength(poseState.position)"); poseState.isPositionValid = true; } if (!aAngVelocity.IsNull()) { @@ -284,28 +284,28 @@ already_AddRefed GamepadServiceTest::NewPoseMove( aAngVelocity.Value().CopyDataTo(poseState.angularVelocity); MOZ_ASSERT(ok, "aAngVelocity.Value().Length() != " - "std::size(poseState.angularVelocity)"); + "ArrayLength(poseState.angularVelocity)"); } if (!aAngAcceleration.IsNull()) { DebugOnly ok = aAngAcceleration.Value().CopyDataTo(poseState.angularAcceleration); MOZ_ASSERT(ok, "aAngAcceleration.Value().Length() != " - "std::size(poseState.angularAcceleration)"); + "ArrayLength(poseState.angularAcceleration)"); } if (!aLinVelocity.IsNull()) { DebugOnly ok = aLinVelocity.Value().CopyDataTo(poseState.linearVelocity); MOZ_ASSERT(ok, "aLinVelocity.Value().Length() != " - "std::size(poseState.linearVelocity)"); + "ArrayLength(poseState.linearVelocity)"); } if (!aLinAcceleration.IsNull()) { DebugOnly ok = aLinAcceleration.Value().CopyDataTo(poseState.linearAcceleration); MOZ_ASSERT(ok, "aLinAcceleration.Value().Length() != " - "std::size(poseState.linearAcceleration)"); + "ArrayLength(poseState.linearAcceleration)"); } GamepadPoseInformation a(poseState); @@ -339,12 +339,12 @@ already_AddRefed GamepadServiceTest::NewTouch( touchState.touchId = aTouchId; touchState.surfaceId = aSurfaceId; DebugOnly ok = aPos.CopyDataTo(touchState.position); - MOZ_ASSERT(ok, "aPos.Length() != std::size(touchState.position)"); + MOZ_ASSERT(ok, "aPos.Length() != ArrayLength(touchState.position)"); if (!aSurfDim.IsNull()) { ok = aSurfDim.Value().CopyDataTo(touchState.surfaceDimensions); - MOZ_ASSERT(ok, - "aSurfDim.Length() != std::size(touchState.surfaceDimensions)"); + MOZ_ASSERT( + ok, "aSurfDim.Length() != ArrayLength(touchState.surfaceDimensions)"); touchState.isSurfaceDimensionsValid = true; } diff --git a/dom/gamepad/linux/udev.h b/dom/gamepad/linux/udev.h index 6a2fbd6961484c..4e3f0b78659509 100644 --- a/dom/gamepad/linux/udev.h +++ b/dom/gamepad/linux/udev.h @@ -33,7 +33,7 @@ class udev_lib { const char* lib_names[] = {"libudev.so.0", "libudev.so.1"}; // Check whether a library is already loaded so we don't load two // conflicting libs. - for (unsigned i = 0; i < std::size(lib_names); i++) { + for (unsigned i = 0; i < ArrayLength(lib_names); i++) { lib = dlopen(lib_names[i], RTLD_NOLOAD | RTLD_LAZY | RTLD_GLOBAL); if (lib) { break; @@ -42,7 +42,7 @@ class udev_lib { // If nothing loads the first time through, it means no version of libudev // was already loaded. if (!lib) { - for (unsigned i = 0; i < std::size(lib_names); i++) { + for (unsigned i = 0; i < ArrayLength(lib_names); i++) { lib = dlopen(lib_names[i], RTLD_LAZY | RTLD_GLOBAL); if (lib) { break; diff --git a/dom/gamepad/windows/WindowsGamepad.cpp b/dom/gamepad/windows/WindowsGamepad.cpp index fc7306bb745ac4..d5584eaea8bd00 100644 --- a/dom/gamepad/windows/WindowsGamepad.cpp +++ b/dom/gamepad/windows/WindowsGamepad.cpp @@ -31,6 +31,7 @@ namespace { using namespace mozilla; using namespace mozilla::dom; +using mozilla::ArrayLength; // USB HID usage tables, page 1, 0x30 = X const uint32_t kAxisMinimumUsageNumber = 0x30; @@ -91,7 +92,7 @@ const struct { {XINPUT_GAMEPAD_B, 1}, {XINPUT_GAMEPAD_X, 2}, {XINPUT_GAMEPAD_Y, 3}}; -const size_t kNumMappings = std::size(kXIButtonMap); +const size_t kNumMappings = ArrayLength(kXIButtonMap); enum GamepadType { kNoGamepad = 0, kRawInputGamepad, kXInputGamepad }; @@ -163,7 +164,7 @@ class XInputLoader { // xinput1_3.dll shipped with the DirectX SDK const wchar_t* dlls[] = {L"xinput1_4.dll", L"xinput9_1_0.dll", L"xinput1_3.dll"}; - const size_t kNumDLLs = std::size(dlls); + const size_t kNumDLLs = ArrayLength(dlls); for (size_t i = 0; i < kNumDLLs; ++i) { module = LoadLibraryW(dlls[i]); if (module) { @@ -228,7 +229,7 @@ double ScaleAxis(ULONG value, LONG min, LONG max) { * know how to handle. */ bool SupportedUsage(USHORT page, USHORT usage) { - for (unsigned i = 0; i < std::size(kUsagePages); i++) { + for (unsigned i = 0; i < ArrayLength(kUsagePages); i++) { if (page == kUsagePages[i].usagePage && usage == kUsagePages[i].usage) { return true; } @@ -674,7 +675,7 @@ bool WindowsGamepadService::GetRawGamepad(HANDLE handle) { } if (gamepad_name.Length() == 0 || !gamepad_name[0]) { const char kUnknown[] = "Unknown Gamepad"; - gamepad_name.SetLength(std::size(kUnknown)); + gamepad_name.SetLength(ArrayLength(kUnknown)); strcpy_s(gamepad_name.Elements(), gamepad_name.Length(), kUnknown); } @@ -986,8 +987,8 @@ void WindowsGamepadService::DevicesChanged(bool aIsStablizing) { } bool RegisterRawInput(HWND hwnd, bool enable) { - nsTArray rid(std::size(kUsagePages)); - rid.SetLength(std::size(kUsagePages)); + nsTArray rid(ArrayLength(kUsagePages)); + rid.SetLength(ArrayLength(kUsagePages)); for (unsigned i = 0; i < rid.Length(); i++) { rid[i].usUsagePage = kUsagePages[i].usagePage; diff --git a/dom/html/HTMLInputElement.cpp b/dom/html/HTMLInputElement.cpp index 59039bf4ccb18c..dc9ca2064a12eb 100644 --- a/dom/html/HTMLInputElement.cpp +++ b/dom/html/HTMLInputElement.cpp @@ -178,7 +178,7 @@ static const nsAttrValue::EnumTable kInputTypeTable[] = { // Default type is 'text'. static const nsAttrValue::EnumTable* kInputDefaultType = - &kInputTypeTable[std::size(kInputTypeTable) - 2]; + &kInputTypeTable[ArrayLength(kInputTypeTable) - 2]; static const nsAttrValue::EnumTable kCaptureTable[] = { {"user", nsIFilePicker::captureUser}, @@ -5418,12 +5418,12 @@ bool HTMLInputElement::ParseAttribute(int32_t aNamespaceID, nsAtom* aAttribute, FormControlType(kInputDefaultType->value) == FormControlType::InputText, "Someone forgot to update kInputDefaultType when adding a new " "input type."); - MOZ_ASSERT(kInputTypeTable[std::size(kInputTypeTable) - 1].tag == nullptr, + MOZ_ASSERT(kInputTypeTable[ArrayLength(kInputTypeTable) - 1].tag == nullptr, "Last entry in the table must be the nullptr guard"); - MOZ_ASSERT( - FormControlType(kInputTypeTable[std::size(kInputTypeTable) - 2].value) == - FormControlType::InputText, - "Next to last entry in the table must be the \"text\" entry"); + MOZ_ASSERT(FormControlType( + kInputTypeTable[ArrayLength(kInputTypeTable) - 2].value) == + FormControlType::InputText, + "Next to last entry in the table must be the \"text\" entry"); if (aNamespaceID == kNameSpaceID_None) { if (aAttribute == nsGkAtoms::type) { diff --git a/dom/html/TextTrackManager.cpp b/dom/html/TextTrackManager.cpp index 3b3acb6e7798ba..7aacb5bf736eba 100644 --- a/dom/html/TextTrackManager.cpp +++ b/dom/html/TextTrackManager.cpp @@ -336,7 +336,7 @@ void TextTrackManager::HonorUserPreferencesForTrackSelection() { // Steps 1 - 3: Perform automatic track selection for different TextTrack // Kinds. - PerformTrackSelection(ttKinds, std::size(ttKinds)); + PerformTrackSelection(ttKinds, ArrayLength(ttKinds)); PerformTrackSelection(TextTrackKind::Descriptions); PerformTrackSelection(TextTrackKind::Chapters); @@ -363,7 +363,7 @@ bool TextTrackManager::TrackIsDefault(TextTrack* aTextTrack) { void TextTrackManager::PerformTrackSelection(TextTrackKind aTextTrackKind) { TextTrackKind ttKinds[] = {aTextTrackKind}; - PerformTrackSelection(ttKinds, std::size(ttKinds)); + PerformTrackSelection(ttKinds, ArrayLength(ttKinds)); } void TextTrackManager::PerformTrackSelection(TextTrackKind aTextTrackKinds[], diff --git a/dom/indexedDB/ActorsParent.cpp b/dom/indexedDB/ActorsParent.cpp index c36bd5761f18ab..de05ff461a7aec 100644 --- a/dom/indexedDB/ActorsParent.cpp +++ b/dom/indexedDB/ActorsParent.cpp @@ -13234,7 +13234,7 @@ nsresult Maintenance::DirectoryWork() { PERSISTENCE_TYPE_TEMPORARY, PERSISTENCE_TYPE_PRIVATE}; static_assert( - std::size(kPersistenceTypes) == size_t(PERSISTENCE_TYPE_INVALID), + ArrayLength(kPersistenceTypes) == size_t(PERSISTENCE_TYPE_INVALID), "Something changed with available persistence types!"); constexpr auto idbDirName = diff --git a/dom/ipc/ContentParent.cpp b/dom/ipc/ContentParent.cpp index aefff801195fd3..6573d5194469a2 100644 --- a/dom/ipc/ContentParent.cpp +++ b/dom/ipc/ContentParent.cpp @@ -1598,7 +1598,7 @@ void ContentParent::Init() { nsCOMPtr obs = mozilla::services::GetObserverService(); if (obs) { - size_t length = std::size(sObserverTopics); + size_t length = ArrayLength(sObserverTopics); for (size_t i = 0; i < length; ++i) { obs->AddObserver(this, sObserverTopics[i], false); } @@ -1963,7 +1963,7 @@ void ContentParent::ActorDestroy(ActorDestroyReason why) { nsCOMPtr obs = mozilla::services::GetObserverService(); if (obs) { - size_t length = std::size(sObserverTopics); + size_t length = ArrayLength(sObserverTopics); for (size_t i = 0; i < length; ++i) { obs->RemoveObserver(static_cast(this), sObserverTopics[i]); } diff --git a/dom/mathml/MathMLElement.cpp b/dom/mathml/MathMLElement.cpp index 9fa861c12ef41d..c214207aba943a 100644 --- a/dom/mathml/MathMLElement.cpp +++ b/dom/mathml/MathMLElement.cpp @@ -594,9 +594,9 @@ void MathMLElement::MapGlobalMathMLAttributesInto( !aBuilder.PropertyIsSet(eCSSProperty_direction)) { auto str = value->GetStringValue(); static const char dirs[][4] = {"ltr", "rtl"}; - static const StyleDirection dirValues[std::size(dirs)] = { + static const StyleDirection dirValues[MOZ_ARRAY_LENGTH(dirs)] = { StyleDirection::Ltr, StyleDirection::Rtl}; - for (uint32_t i = 0; i < std::size(dirs); ++i) { + for (uint32_t i = 0; i < ArrayLength(dirs); ++i) { if (str.LowerCaseEqualsASCII(dirs[i])) { aBuilder.SetKeywordValue(eCSSProperty_direction, dirValues[i]); break; @@ -611,9 +611,9 @@ void MathMLElement::MapGlobalMathMLAttributesInto( !aBuilder.PropertyIsSet(eCSSProperty_math_style)) { auto str = value->GetStringValue(); static const char displaystyles[][6] = {"false", "true"}; - static const StyleMathStyle mathStyle[std::size(displaystyles)] = { + static const StyleMathStyle mathStyle[MOZ_ARRAY_LENGTH(displaystyles)] = { StyleMathStyle::Compact, StyleMathStyle::Normal}; - for (uint32_t i = 0; i < std::size(displaystyles); ++i) { + for (uint32_t i = 0; i < ArrayLength(displaystyles); ++i) { if (str.LowerCaseEqualsASCII(displaystyles[i])) { aBuilder.SetKeywordValue(eCSSProperty_math_style, mathStyle[i]); break; diff --git a/dom/media/AsyncLogger.h b/dom/media/AsyncLogger.h index 7c37bd5ed9fbb1..2dedabea7c2b68 100644 --- a/dom/media/AsyncLogger.h +++ b/dom/media/AsyncLogger.h @@ -162,7 +162,7 @@ class AsyncLogger { msg->data.mTimestamp = TimeStamp::Now(); msg->data.mDurationUs = 0; // unused, duration is end - begin - StringWriter writer(msg->data.mName, std::size(msg->data.mName)); + StringWriter writer(msg->data.mName, ArrayLength(msg->data.mName)); size_t commentIndex; DebugOnly truncated = writer.AppendCString(aName, &commentIndex); @@ -188,7 +188,7 @@ class AsyncLogger { msg->data.mTimestamp = TimeStamp::Now(); msg->data.mDurationUs = (static_cast(aFrames) / aSampleRate) * 1e6; - size_t len = std::min(strlen(aName), std::size(msg->data.mName)); + size_t len = std::min(strlen(aName), ArrayLength(msg->data.mName)); memcpy(msg->data.mName, aName, len); msg->data.mName[len] = 0; mMessageQueueProfiler.Push(msg); diff --git a/dom/media/eme/clearkey/ArrayUtils.h b/dom/media/eme/clearkey/ArrayUtils.h new file mode 100644 index 00000000000000..ae5f33b68e4252 --- /dev/null +++ b/dom/media/eme/clearkey/ArrayUtils.h @@ -0,0 +1,22 @@ +/* + * Copyright 2015, Mozilla Foundation and contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __ArrayUtils_h__ +#define __ArrayUtils_h__ + +#define MOZ_ARRAY_LENGTH(array_) (sizeof(array_) / sizeof(array_[0])) + +#endif diff --git a/dom/media/eme/clearkey/ClearKeyStorage.cpp b/dom/media/eme/clearkey/ClearKeyStorage.cpp index 6a553fdc3d567d..1375d33c5750be 100644 --- a/dom/media/eme/clearkey/ClearKeyStorage.cpp +++ b/dom/media/eme/clearkey/ClearKeyStorage.cpp @@ -25,6 +25,7 @@ #include "content_decryption_module.h" +#include "ArrayUtils.h" #include "ClearKeyUtils.h" using namespace cdm; diff --git a/dom/media/eme/clearkey/ClearKeyUtils.cpp b/dom/media/eme/clearkey/ClearKeyUtils.cpp index 4020acc38874b8..3f9588bdf92ffc 100644 --- a/dom/media/eme/clearkey/ClearKeyUtils.cpp +++ b/dom/media/eme/clearkey/ClearKeyUtils.cpp @@ -34,6 +34,7 @@ #include "prerror.h" #include "secmodt.h" +#include "ArrayUtils.h" #include "BigEndian.h" #include "ClearKeyBase64.h" #include "mozilla/Sprintf.h" @@ -258,7 +259,7 @@ static bool EncodeBase64Web(vector aBinary, string& aEncoded) { size_t idx = static_cast(out[i]); // out of bounds index for 'sAlphabet' - assert(idx < std::size(sAlphabet)); + assert(idx < MOZ_ARRAY_LENGTH(sAlphabet)); out[i] = sAlphabet[idx]; } diff --git a/dom/media/eme/clearkey/moz.build b/dom/media/eme/clearkey/moz.build index c36dcf8985f6c0..57160624ea59ec 100644 --- a/dom/media/eme/clearkey/moz.build +++ b/dom/media/eme/clearkey/moz.build @@ -3,6 +3,7 @@ # file, You can obtain one at http://mozilla.org/MPL/2.0/. EXPORTS += [ + "ArrayUtils.h", "BigEndian.h", "ClearKeyBase64.h", "ClearKeyDecryptionManager.h", diff --git a/dom/media/encoder/OpusTrackEncoder.cpp b/dom/media/encoder/OpusTrackEncoder.cpp index 379a8c02ffee04..1238ef8ea01cce 100644 --- a/dom/media/encoder/OpusTrackEncoder.cpp +++ b/dom/media/encoder/OpusTrackEncoder.cpp @@ -118,7 +118,7 @@ bool IsSampleRateSupported(TrackRate aSampleRate) { AutoTArray supportedSamplingRates; supportedSamplingRates.AppendElements( kOpusSupportedInputSamplingRates, - std::size(kOpusSupportedInputSamplingRates)); + ArrayLength(kOpusSupportedInputSamplingRates)); return supportedSamplingRates.Contains(aSampleRate); } diff --git a/dom/media/gmp/GMPDiskStorage.cpp b/dom/media/gmp/GMPDiskStorage.cpp index 6b622c3161be34..6437cb300d2bd0 100644 --- a/dom/media/gmp/GMPDiskStorage.cpp +++ b/dom/media/gmp/GMPDiskStorage.cpp @@ -260,8 +260,8 @@ class GMPDiskStorage : public GMPStorage { int32_t bytesWritten = 0; char buf[sizeof(uint32_t)] = {0}; LittleEndian::writeUint32(buf, aRecordName.Length()); - bytesWritten = PR_Write(record->mFileDesc, buf, std::size(buf)); - if (bytesWritten != std::size(buf)) { + bytesWritten = PR_Write(record->mFileDesc, buf, MOZ_ARRAY_LENGTH(buf)); + if (bytesWritten != MOZ_ARRAY_LENGTH(buf)) { NS_WARNING("Failed to write GMPStorage record name length."); return GMPRecordCorrupted; } diff --git a/dom/media/gmp/rlz/win/lib/machine_id_win.cc b/dom/media/gmp/rlz/win/lib/machine_id_win.cc index 5f4b3557310aa2..85f1d6cf54a89e 100644 --- a/dom/media/gmp/rlz/win/lib/machine_id_win.cc +++ b/dom/media/gmp/rlz/win/lib/machine_id_win.cc @@ -113,7 +113,7 @@ bool GetRawMachineId(std::vector* sid_bytes, int* volume_id) { // Calculate the Windows SID. wchar_t computer_name[MAX_COMPUTERNAME_LENGTH + 1] = {0}; - DWORD size = std::size(computer_name); + DWORD size = mozilla::ArrayLength(computer_name); if (GetComputerNameW(computer_name, &size)) { char sid_buffer[SECURITY_MAX_SID_SIZE]; diff --git a/dom/media/gtest/TestGMPUtils.cpp b/dom/media/gtest/TestGMPUtils.cpp index 416d4626503fe4..589b47b581a302 100644 --- a/dom/media/gtest/TestGMPUtils.cpp +++ b/dom/media/gtest/TestGMPUtils.cpp @@ -34,14 +34,14 @@ TEST(GeckoMediaPlugins, TestSplitAt) const char* input = "1,2,3,4"; const char* delims = ","; const char* tokens[] = {"1", "2", "3", "4"}; - TestSplitAt(input, delims, std::size(tokens), tokens); + TestSplitAt(input, delims, MOZ_ARRAY_LENGTH(tokens), tokens); } { const char* input = "a simple, comma, seperated, list"; const char* delims = ","; const char* tokens[] = {"a simple", " comma", " seperated", " list"}; - TestSplitAt(input, delims, std::size(tokens), tokens); + TestSplitAt(input, delims, MOZ_ARRAY_LENGTH(tokens), tokens); } { @@ -52,7 +52,7 @@ TEST(GeckoMediaPlugins, TestSplitAt) "line4"; const char* delims = "\r\n"; const char* tokens[] = {"line1", "line2", "line3", "line4"}; - TestSplitAt(input, delims, std::size(tokens), tokens); + TestSplitAt(input, delims, MOZ_ARRAY_LENGTH(tokens), tokens); } } diff --git a/dom/media/gtest/TestMP4Demuxer.cpp b/dom/media/gtest/TestMP4Demuxer.cpp index e69d4790e7951c..1a1bde803531d2 100644 --- a/dom/media/gtest/TestMP4Demuxer.cpp +++ b/dom/media/gtest/TestMP4Demuxer.cpp @@ -328,7 +328,7 @@ TEST(MP4Demuxer, CENCFragVideo) nsCString text = ToCryptoString(binding->mSamples[i]->mCrypto); EXPECT_STREQ(video[i++], text.get()); } - EXPECT_EQ(std::size(video), binding->mSamples.Length()); + EXPECT_EQ(ArrayLength(video), binding->mSamples.Length()); binding->mTaskQueue->BeginShutdown(); }, DO_FAIL); @@ -543,7 +543,7 @@ TEST(MP4Demuxer, CENCFragAudio) nsCString text = ToCryptoString(binding->mSamples[i]->mCrypto); EXPECT_STREQ(audio[i++], text.get()); } - EXPECT_EQ(std::size(audio), binding->mSamples.Length()); + EXPECT_EQ(ArrayLength(audio), binding->mSamples.Length()); binding->mTaskQueue->BeginShutdown(); }, DO_FAIL); diff --git a/dom/media/gtest/TestVPXDecoding.cpp b/dom/media/gtest/TestVPXDecoding.cpp index 9be4517140907e..d58ca24cc7127f 100644 --- a/dom/media/gtest/TestVPXDecoding.cpp +++ b/dom/media/gtest/TestVPXDecoding.cpp @@ -71,7 +71,7 @@ static const TestFileData testFiles[] = { TEST(libvpx, test_cases) { - for (size_t test = 0; test < std::size(testFiles); ++test) { + for (size_t test = 0; test < ArrayLength(testFiles); ++test) { nsTArray data; ReadVPXFile(testFiles[test].mFilename, data); ASSERT_GT(data.Length(), 0u); diff --git a/dom/media/gtest/TestWebMBuffered.cpp b/dom/media/gtest/TestWebMBuffered.cpp index 4cbbe15d12903b..35ba00fec746e5 100644 --- a/dom/media/gtest/TestWebMBuffered.cpp +++ b/dom/media/gtest/TestWebMBuffered.cpp @@ -44,7 +44,7 @@ TEST(WebMBuffered, BasicTests) EXPECT_EQ(parser.mCurrentOffset, 0); unsigned char buf[] = {0x1a, 0x45, 0xdf, 0xa3}; - EXPECT_EQ(parser.Append(buf, std::size(buf), mapping), NS_OK); + EXPECT_EQ(parser.Append(buf, ArrayLength(buf), mapping), NS_OK); EXPECT_TRUE(mapping.IsEmpty()); EXPECT_EQ(parser.mStartOffset, 0); EXPECT_EQ(parser.mCurrentOffset, 4); diff --git a/dom/media/gtest/mp4_demuxer/TestParser.cpp b/dom/media/gtest/mp4_demuxer/TestParser.cpp index a60db92c17a953..db4dd6839aceb2 100644 --- a/dom/media/gtest/mp4_demuxer/TestParser.cpp +++ b/dom/media/gtest/mp4_demuxer/TestParser.cpp @@ -260,7 +260,7 @@ TEST(MP4Metadata, test_case_mp4) size_t length = 0; tests = testFiles; - length = std::size(testFiles); + length = ArrayLength(testFiles); for (size_t test = 0; test < length; ++test) { nsTArray buffer = ReadTestFile(tests[test].mFilename); @@ -382,7 +382,7 @@ TEST(MP4Metadata, test_case_mp4) #if 0 TEST(MP4Metadata, test_case_mp4_subsets) { static const size_t step = 1u; - for (size_t test = 0; test < std::size(testFiles); ++test) { + for (size_t test = 0; test < ArrayLength(testFiles); ++test) { nsTArray buffer = ReadTestFile(testFiles[test].mFilename); ASSERT_FALSE(buffer.IsEmpty()); ASSERT_LE(step, buffer.Length()); @@ -423,7 +423,7 @@ TEST(MoofParser, test_case_mp4) size_t length = 0; tests = testFiles; - length = std::size(testFiles); + length = ArrayLength(testFiles); for (size_t test = 0; test < length; ++test) { nsTArray buffer = ReadTestFile(tests[test].mFilename); @@ -469,7 +469,7 @@ TEST(MoofParser, test_case_mp4) TEST(MoofParser, test_case_sample_description_entries) { const TestFileData* tests = testFiles; - size_t length = std::size(testFiles); + size_t length = ArrayLength(testFiles); for (size_t test = 0; test < length; ++test) { nsTArray buffer = ReadTestFile(tests[test].mFilename); @@ -670,7 +670,7 @@ TEST(MoofParser, test_case_moofs_missing_trafs) #if 0 TEST(MoofParser, test_case_mp4_subsets) { const size_t step = 1u; - for (size_t test = 0; test < std::size(testFiles); ++test) { + for (size_t test = 0; test < ArrayLength(testFiles); ++test) { nsTArray buffer = ReadTestFile(testFiles[test].mFilename); ASSERT_FALSE(buffer.IsEmpty()); ASSERT_LE(step, buffer.Length()); diff --git a/dom/media/mediasession/MediaSession.cpp b/dom/media/mediasession/MediaSession.cpp index f8a33995d6f665..eaca17e29b122e 100644 --- a/dom/media/mediasession/MediaSession.cpp +++ b/dom/media/mediasession/MediaSession.cpp @@ -135,7 +135,7 @@ MediaSessionPlaybackState MediaSession::PlaybackState() const { void MediaSession::SetActionHandler(MediaSessionAction aAction, MediaSessionActionHandler* aHandler) { - MOZ_ASSERT(size_t(aAction) < std::size(mActionHandlers)); + MOZ_ASSERT(size_t(aAction) < ArrayLength(mActionHandlers)); // If the media session changes its supported action, then we would propagate // this information to the chrome process in order to run the media session // actions update algorithm. @@ -151,7 +151,7 @@ void MediaSession::SetActionHandler(MediaSessionAction aAction, MediaSessionActionHandler* MediaSession::GetActionHandler( MediaSessionAction aAction) const { - MOZ_ASSERT(size_t(aAction) < std::size(mActionHandlers)); + MOZ_ASSERT(size_t(aAction) < ArrayLength(mActionHandlers)); return mActionHandlers[aAction]; } @@ -236,7 +236,7 @@ void MediaSession::DispatchNotifyHandler( } bool MediaSession::IsSupportedAction(MediaSessionAction aAction) const { - MOZ_ASSERT(size_t(aAction) < std::size(mActionHandlers)); + MOZ_ASSERT(size_t(aAction) < ArrayLength(mActionHandlers)); return mActionHandlers[aAction] != nullptr; } @@ -284,7 +284,7 @@ void MediaSession::NotifyMediaSessionAttributes() { if (mMediaMetadata) { NotifyMetadataUpdated(); } - for (size_t idx = 0; idx < std::size(mActionHandlers); idx++) { + for (size_t idx = 0; idx < ArrayLength(mActionHandlers); idx++) { MediaSessionAction action = static_cast(idx); if (mActionHandlers[action]) { NotifyEnableSupportedAction(action); diff --git a/dom/media/mediasource/gtest/TestContainerParser.cpp b/dom/media/mediasource/gtest/TestContainerParser.cpp index 5f3c4b57ba0a58..dd5a87b64be1be 100644 --- a/dom/media/mediasource/gtest/TestContainerParser.cpp +++ b/dom/media/mediasource/gtest/TestContainerParser.cpp @@ -18,7 +18,7 @@ TEST(ContainerParser, MIMETypes) const char* containerTypes[] = {"video/webm", "audio/webm", "video/mp4", "audio/mp4", "audio/aac"}; UniquePtr parser; - for (size_t i = 0; i < std::size(containerTypes); ++i) { + for (size_t i = 0; i < ArrayLength(containerTypes); ++i) { Maybe containerType = MakeMediaContainerType(containerTypes[i]); ASSERT_TRUE(containerType.isSome()); @@ -30,7 +30,7 @@ TEST(ContainerParser, MIMETypes) already_AddRefed make_adts_header() { const uint8_t test[] = {0xff, 0xf1, 0x50, 0x80, 0x03, 0x1f, 0xfc}; RefPtr buffer(new MediaByteBuffer); - buffer->AppendElements(test, std::size(test)); + buffer->AppendElements(test, ArrayLength(test)); return buffer.forget(); } diff --git a/dom/media/ogg/OggCodecState.cpp b/dom/media/ogg/OggCodecState.cpp index fe74f3872183dd..db3d99f9599e5d 100644 --- a/dom/media/ogg/OggCodecState.cpp +++ b/dom/media/ogg/OggCodecState.cpp @@ -1404,7 +1404,7 @@ bool SkeletonState::DecodeFisbone(ogg_packet* aPacket) { while (msgLength > 1) { if (*msgProbe == '\r' && *(msgProbe + 1) == '\n') { nsAutoCString strMsg(msgHead, msgProbe - msgHead); - for (size_t i = 0; i < std::size(kFieldTypeMaps); i++) { + for (size_t i = 0; i < ArrayLength(kFieldTypeMaps); i++) { if (strMsg.Find(kFieldTypeMaps[i].mPatternToRecognize) != -1) { // The content of message header fields follows [RFC2822], and the // mandatory message field must be encoded in US-ASCII, others diff --git a/dom/media/platforms/agnostic/bytestreams/Adts.cpp b/dom/media/platforms/agnostic/bytestreams/Adts.cpp index 259f5a2d8aae1f..b5ea92b863cbc5 100644 --- a/dom/media/platforms/agnostic/bytestreams/Adts.cpp +++ b/dom/media/platforms/agnostic/bytestreams/Adts.cpp @@ -69,7 +69,7 @@ bool ConvertSample(uint16_t aChannelCount, uint8_t aFrequencyIndex, header[6] = 0xfc; UniquePtr writer(aSample->CreateWriter()); - if (!writer->Prepend(&header[0], std::size(header))) { + if (!writer->Prepend(&header[0], ArrayLength(header))) { return false; } @@ -176,7 +176,7 @@ bool FrameHeader::Parse(const Span& aData) { static const uint32_t SAMPLE_RATES[] = {96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350}; - if (mSamplingIndex >= std::size(SAMPLE_RATES)) { + if (mSamplingIndex >= ArrayLength(SAMPLE_RATES)) { LOG(("ADTS: Init() failure: invalid sample-rate index value: %" PRIu32 ".", mSamplingIndex)); // This marks the header as invalid. diff --git a/dom/media/platforms/agnostic/bytestreams/AnnexB.cpp b/dom/media/platforms/agnostic/bytestreams/AnnexB.cpp index 09c1bb7116d720..4721ddefc3e7e0 100644 --- a/dom/media/platforms/agnostic/bytestreams/AnnexB.cpp +++ b/dom/media/platforms/agnostic/bytestreams/AnnexB.cpp @@ -50,7 +50,7 @@ Result AnnexB::ConvertAVCCSampleToAnnexB( MOZ_TRY_VAR(nalLen, reader.ReadU32()); const uint8_t* p = reader.Read(nalLen); - if (!writer.Write(kAnnexBDelimiter, std::size(kAnnexBDelimiter))) { + if (!writer.Write(kAnnexBDelimiter, ArrayLength(kAnnexBDelimiter))) { return Err(NS_ERROR_OUT_OF_MEMORY); } if (!p) { @@ -122,7 +122,7 @@ Result AnnexB::ConvertHVCCSampleToAnnexB( uint32_t nalLen; MOZ_TRY_VAR(nalLen, reader.ReadU32()); const uint8_t* p = reader.Read(nalLen); - if (!writer.Write(kAnnexBDelimiter, std::size(kAnnexBDelimiter))) { + if (!writer.Write(kAnnexBDelimiter, ArrayLength(kAnnexBDelimiter))) { LOG("Failed to write kAnnexBDelimiter, OOM?"); return Err(NS_ERROR_OUT_OF_MEMORY); } @@ -218,7 +218,7 @@ already_AddRefed AnnexB::ConvertHVCCExtraDataToAnnexB( const HVCCConfig hvcc = rv.unwrap(); RefPtr annexB = new mozilla::MediaByteBuffer; for (const auto& nalu : hvcc.mNALUs) { - annexB->AppendElements(kAnnexBDelimiter, std::size(kAnnexBDelimiter)); + annexB->AppendElements(kAnnexBDelimiter, ArrayLength(kAnnexBDelimiter)); annexB->AppendElements(nalu.mNALU.Elements(), nalu.mNALU.Length()); LOGV("Insert NALU (type=%hhu, size=%zu) to AnnexB (size=%zu)", nalu.mNalUnitType, nalu.mNALU.Length(), annexB->Length()); @@ -236,7 +236,7 @@ Result AnnexB::ConvertSPSOrPPS( if (!ptr) { return Err(NS_ERROR_FAILURE); } - aAnnexB->AppendElements(kAnnexBDelimiter, std::size(kAnnexBDelimiter)); + aAnnexB->AppendElements(kAnnexBDelimiter, ArrayLength(kAnnexBDelimiter)); aAnnexB->AppendElements(ptr, length); } return Ok(); @@ -404,7 +404,7 @@ bool AnnexB::ConvertSampleToAVCC(mozilla::MediaRawData* aSample, }; // XXX(Bug 1631371) Check if this should use a fallible operation as it // pretended earlier. - extradata->AppendElements(kFakeExtraData, std::size(kFakeExtraData)); + extradata->AppendElements(kFakeExtraData, ArrayLength(kFakeExtraData)); aSample->mExtraData = std::move(extradata); return true; } diff --git a/dom/media/platforms/agnostic/bytestreams/gtest/TestByteStreams.cpp b/dom/media/platforms/agnostic/bytestreams/gtest/TestByteStreams.cpp index f74cf26ae4432a..e5b8c3c72212fc 100644 --- a/dom/media/platforms/agnostic/bytestreams/gtest/TestByteStreams.cpp +++ b/dom/media/platforms/agnostic/bytestreams/gtest/TestByteStreams.cpp @@ -118,7 +118,7 @@ static already_AddRefed GetHVCCSample(uint32_t aSampleSize) { EXPECT_FALSE(true) << "Samples should be requested with sane sizes"; } auto extradata = MakeRefPtr(); - extradata->AppendElements(sHvccBytesBuffer, std::size(sHvccBytesBuffer)); + extradata->AppendElements(sHvccBytesBuffer, ArrayLength(sHvccBytesBuffer)); // Write the NAL size. nsTArray sampleData; @@ -145,7 +145,7 @@ static already_AddRefed GetHVCCSample( EXPECT_FALSE(true) << "Samples should be requested with sane sizes"; } auto extradata = MakeRefPtr(); - extradata->AppendElements(sHvccBytesBuffer, std::size(sHvccBytesBuffer)); + extradata->AppendElements(sHvccBytesBuffer, ArrayLength(sHvccBytesBuffer)); // Write the NAL size. nsTArray sampleData; @@ -346,7 +346,7 @@ TEST(H264, AVCCParsingSuccess) 0xe0 /* num SPS (0) */, 0 /* num PPS (0) */ }; - extradata->AppendElements(avccBytesBuffer, std::size(avccBytesBuffer)); + extradata->AppendElements(avccBytesBuffer, ArrayLength(avccBytesBuffer)); auto rv = AVCCConfig::Parse(extradata); EXPECT_TRUE(rv.isOk()); const auto avcc = rv.unwrap(); @@ -372,7 +372,7 @@ TEST(H264, AVCCParsingFailure) 0xe0 /* num SPS (0) */, 0 /* num PPS (0) */ }; - extradata->AppendElements(avccBytesBuffer, std::size(avccBytesBuffer)); + extradata->AppendElements(avccBytesBuffer, ArrayLength(avccBytesBuffer)); auto avcc = AVCCConfig::Parse(extradata); EXPECT_TRUE(avcc.isErr()); } @@ -387,7 +387,7 @@ TEST(H264, AVCCParsingFailure) 0xfc | 3 /* nal size - 1 */, 0xe0 /* num SPS (0) */, }; - extradata->AppendElements(avccBytesBuffer, std::size(avccBytesBuffer)); + extradata->AppendElements(avccBytesBuffer, ArrayLength(avccBytesBuffer)); auto avcc = AVCCConfig::Parse(extradata); EXPECT_TRUE(avcc.isErr()); } @@ -424,7 +424,7 @@ TEST(H265, HVCCParsingSuccess) , 0 /* numOfArrays */, }; - extradata->AppendElements(hvccBytesBuffer, std::size(hvccBytesBuffer)); + extradata->AppendElements(hvccBytesBuffer, ArrayLength(hvccBytesBuffer)); auto rv = HVCCConfig::Parse(extradata); EXPECT_TRUE(rv.isOk()); auto hvcc = rv.unwrap(); @@ -513,7 +513,7 @@ TEST(H265, HVCCParsingSuccess) 0 /* NALU header 2/2 */, 0 /* rbsp */, }; - extradata->AppendElements(hvccBytesBuffer, std::size(hvccBytesBuffer)); + extradata->AppendElements(hvccBytesBuffer, ArrayLength(hvccBytesBuffer)); auto rv = HVCCConfig::Parse(extradata); EXPECT_TRUE(rv.isOk()); auto hvcc = rv.unwrap(); @@ -571,7 +571,7 @@ TEST(H265, HVCCParsingFailure) , 0 /* numOfArrays */, }; - extradata->AppendElements(hvccBytesBuffer, std::size(hvccBytesBuffer)); + extradata->AppendElements(hvccBytesBuffer, ArrayLength(hvccBytesBuffer)); auto avcc = HVCCConfig::Parse(extradata); EXPECT_TRUE(avcc.isErr()); } @@ -593,7 +593,7 @@ TEST(H265, HVCCParsingFailure) 0 /* general_constraint_indicator_flags 6/6 */, 0x5A /* general_level_idc */ }; - extradata->AppendElements(hvccBytesBuffer, std::size(hvccBytesBuffer)); + extradata->AppendElements(hvccBytesBuffer, ArrayLength(hvccBytesBuffer)); auto avcc = HVCCConfig::Parse(extradata); EXPECT_TRUE(avcc.isErr()); } @@ -652,7 +652,7 @@ TEST(H265, HVCCToAnnexB) 0 /* NALU header 2/2 */, 0 /* rbsp */, }; - extradata->AppendElements(hvccBytesBuffer, std::size(hvccBytesBuffer)); + extradata->AppendElements(hvccBytesBuffer, ArrayLength(hvccBytesBuffer)); // We convert hvcc extra-data to annexb format, then parse each nalu to see if // they are still correct or not. @@ -709,7 +709,7 @@ static const uint8_t sSps[] = { TEST(H265, ExtractHVCCExtraData) { - RefPtr rawData{GetHVCCSample(sSps, std::size(sSps))}; + RefPtr rawData{GetHVCCSample(sSps, ArrayLength(sSps))}; RefPtr extradata = H265::ExtractHVCCExtraData(rawData); EXPECT_TRUE(extradata); auto rv = HVCCConfig::Parse(extradata); @@ -725,7 +725,7 @@ TEST(H265, ExtractHVCCExtraData) TEST(H265, DecodeSPSFromSPSNALU) { - H265NALU nalu{sSps, std::size(sSps)}; + H265NALU nalu{sSps, ArrayLength(sSps)}; auto rv = H265::DecodeSPSFromSPSNALU(nalu); EXPECT_TRUE(rv.isOk()); auto sps = rv.unwrap(); diff --git a/dom/media/platforms/apple/AppleVTDecoder.cpp b/dom/media/platforms/apple/AppleVTDecoder.cpp index 6c937eace9c1e3..55ca055c541e52 100644 --- a/dom/media/platforms/apple/AppleVTDecoder.cpp +++ b/dom/media/platforms/apple/AppleVTDecoder.cpp @@ -666,11 +666,11 @@ CFDictionaryRef AppleVTDecoder::CreateDecoderExtensions() { : CFSTR("av1C"); ; const void* atomsValue[] = {data}; - static_assert(std::size(atomsKey) == std::size(atomsValue), + static_assert(ArrayLength(atomsKey) == ArrayLength(atomsValue), "Non matching keys/values array size"); AutoCFRelease atoms = CFDictionaryCreate( - kCFAllocatorDefault, atomsKey, atomsValue, std::size(atomsKey), + kCFAllocatorDefault, atomsKey, atomsValue, ArrayLength(atomsKey), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); const void* extensionKeys[] = { @@ -680,11 +680,11 @@ CFDictionaryRef AppleVTDecoder::CreateDecoderExtensions() { const void* extensionValues[] = {kCVImageBufferChromaLocation_Left, kCVImageBufferChromaLocation_Left, atoms}; - static_assert(std::size(extensionKeys) == std::size(extensionValues), + static_assert(ArrayLength(extensionKeys) == ArrayLength(extensionValues), "Non matching keys/values array size"); return CFDictionaryCreate(kCFAllocatorDefault, extensionKeys, extensionValues, - std::size(extensionKeys), + ArrayLength(extensionKeys), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); } @@ -699,12 +699,12 @@ CFDictionaryRef AppleVTDecoder::CreateDecoderSpecification() { // This GPU is blacklisted for hardware decoding. specValues[0] = kCFBooleanFalse; } - static_assert(std::size(specKeys) == std::size(specValues), + static_assert(ArrayLength(specKeys) == ArrayLength(specValues), "Non matching keys/values array size"); - return CFDictionaryCreate(kCFAllocatorDefault, specKeys, specValues, - std::size(specKeys), &kCFTypeDictionaryKeyCallBacks, - &kCFTypeDictionaryValueCallBacks); + return CFDictionaryCreate( + kCFAllocatorDefault, specKeys, specValues, ArrayLength(specKeys), + &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); } CFDictionaryRef AppleVTDecoder::CreateOutputConfiguration() { @@ -715,11 +715,11 @@ CFDictionaryRef AppleVTDecoder::CreateOutputConfiguration() { kCFAllocatorDefault, kCFNumberSInt32Type, &PixelFormatTypeValue); const void* outputKeys[] = {kCVPixelBufferPixelFormatTypeKey}; const void* outputValues[] = {PixelFormatTypeNumber}; - static_assert(std::size(outputKeys) == std::size(outputValues), + static_assert(ArrayLength(outputKeys) == ArrayLength(outputValues), "Non matching keys/values array size"); return CFDictionaryCreate( - kCFAllocatorDefault, outputKeys, outputValues, std::size(outputKeys), + kCFAllocatorDefault, outputKeys, outputValues, ArrayLength(outputKeys), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); } @@ -737,13 +737,13 @@ CFDictionaryRef AppleVTDecoder::CreateOutputConfiguration() { // Construct IOSurface Properties const void* IOSurfaceKeys[] = {kIOSurfaceIsGlobal}; const void* IOSurfaceValues[] = {kCFBooleanTrue}; - static_assert(std::size(IOSurfaceKeys) == std::size(IOSurfaceValues), + static_assert(ArrayLength(IOSurfaceKeys) == ArrayLength(IOSurfaceValues), "Non matching keys/values array size"); // Contruct output configuration. AutoCFRelease IOSurfaceProperties = CFDictionaryCreate( kCFAllocatorDefault, IOSurfaceKeys, IOSurfaceValues, - std::size(IOSurfaceKeys), &kCFTypeDictionaryKeyCallBacks, + ArrayLength(IOSurfaceKeys), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); const void* outputKeys[] = {kCVPixelBufferIOSurfacePropertiesKey, @@ -751,11 +751,11 @@ CFDictionaryRef AppleVTDecoder::CreateOutputConfiguration() { kCVPixelBufferOpenGLCompatibilityKey}; const void* outputValues[] = {IOSurfaceProperties, PixelFormatTypeNumber, kCFBooleanTrue}; - static_assert(std::size(outputKeys) == std::size(outputValues), + static_assert(ArrayLength(outputKeys) == ArrayLength(outputValues), "Non matching keys/values array size"); return CFDictionaryCreate( - kCFAllocatorDefault, outputKeys, outputValues, std::size(outputKeys), + kCFAllocatorDefault, outputKeys, outputValues, ArrayLength(outputKeys), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); } diff --git a/dom/media/platforms/apple/AppleVTEncoder.cpp b/dom/media/platforms/apple/AppleVTEncoder.cpp index 39629e231b2e27..4d9502f50bd060 100644 --- a/dom/media/platforms/apple/AppleVTEncoder.cpp +++ b/dom/media/platforms/apple/AppleVTEncoder.cpp @@ -41,11 +41,11 @@ static CFDictionaryRef BuildEncoderSpec(const bool aHardwareNotAllowed, kVTVideoEncoderSpecification_EnableLowLatencyRateControl}; const void* values[] = {kCFBooleanTrue, kCFBooleanTrue}; - static_assert(std::size(keys) == std::size(values), + static_assert(ArrayLength(keys) == ArrayLength(values), "Non matching keys/values array size"); - return CFDictionaryCreate(kCFAllocatorDefault, keys, values, - std::size(keys), &kCFTypeDictionaryKeyCallBacks, - &kCFTypeDictionaryValueCallBacks); + return CFDictionaryCreate( + kCFAllocatorDefault, keys, values, ArrayLength(keys), + &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); } } const void* keys[] = { @@ -53,10 +53,10 @@ static CFDictionaryRef BuildEncoderSpec(const bool aHardwareNotAllowed, const void* values[] = {aHardwareNotAllowed ? kCFBooleanFalse : kCFBooleanTrue}; - static_assert(std::size(keys) == std::size(values), + static_assert(ArrayLength(keys) == ArrayLength(values), "Non matching keys/values array size"); - return CFDictionaryCreate(kCFAllocatorDefault, keys, values, std::size(keys), - &kCFTypeDictionaryKeyCallBacks, + return CFDictionaryCreate(kCFAllocatorDefault, keys, values, + ArrayLength(keys), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); } @@ -360,11 +360,11 @@ CFDictionaryRef AppleVTEncoder::BuildSourceImageBufferAttributes() { CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &fmt)); const void* values[] = {kCFBooleanTrue, ioSurfaceProps, pixelFormat}; - MOZ_ASSERT(std::size(keys) == std::size(values), + MOZ_ASSERT(ArrayLength(keys) == ArrayLength(values), "Non matching keys/values array size"); - return CFDictionaryCreate(kCFAllocatorDefault, keys, values, std::size(keys), - &kCFTypeDictionaryKeyCallBacks, + return CFDictionaryCreate(kCFAllocatorDefault, keys, values, + ArrayLength(keys), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); } @@ -636,9 +636,9 @@ RefPtr AppleVTEncoder::ProcessEncode( if (aSample->mKeyframe) { CFTypeRef keys[] = {kVTEncodeFrameOptionKey_ForceKeyFrame}; CFTypeRef values[] = {kCFBooleanTrue}; - MOZ_ASSERT(std::size(keys) == std::size(values)); + MOZ_ASSERT(ArrayLength(keys) == ArrayLength(values)); frameProps = CFDictionaryCreate( - kCFAllocatorDefault, keys, values, std::size(keys), + kCFAllocatorDefault, keys, values, ArrayLength(keys), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); }; diff --git a/dom/media/platforms/ffmpeg/FFmpegRuntimeLinker.cpp b/dom/media/platforms/ffmpeg/FFmpegRuntimeLinker.cpp index 01e78090453c09..6a7bdbce11ae51 100644 --- a/dom/media/platforms/ffmpeg/FFmpegRuntimeLinker.cpp +++ b/dom/media/platforms/ffmpeg/FFmpegRuntimeLinker.cpp @@ -76,7 +76,7 @@ bool FFmpegRuntimeLinker::Init() { // more precise error if possible. sLinkStatus = LinkStatus_NOT_FOUND; - for (size_t i = 0; i < std::size(sLibs); i++) { + for (size_t i = 0; i < ArrayLength(sLibs); i++) { const char* lib = sLibs[i]; PRLibSpec lspec; lspec.type = PR_LibSpec_Pathname; @@ -139,7 +139,7 @@ bool FFmpegRuntimeLinker::Init() { } FFMPEGV_LOG("H264/AAC codecs unsupported without ["); - for (size_t i = 0; i < std::size(sLibs); i++) { + for (size_t i = 0; i < ArrayLength(sLibs); i++) { FFMPEGV_LOG("%s %s", i ? "," : " ", sLibs[i]); } FFMPEGV_LOG(" ]\n"); diff --git a/dom/media/platforms/omx/OmxCoreLibLinker.cpp b/dom/media/platforms/omx/OmxCoreLibLinker.cpp index ab68af1279c8d9..a0ee61ec4224be 100644 --- a/dom/media/platforms/omx/OmxCoreLibLinker.cpp +++ b/dom/media/platforms/omx/OmxCoreLibLinker.cpp @@ -74,7 +74,7 @@ bool OmxCoreLibLinker::Link() { } // try known paths - for (size_t i = 0; i < std::size(sLibNames); i++) { + for (size_t i = 0; i < ArrayLength(sLibNames); i++) { if (TryLinkingLibrary(sLibNames[i])) { sLinkStatus = LinkStatus_SUCCEEDED; return true; diff --git a/dom/media/webaudio/DelayBuffer.cpp b/dom/media/webaudio/DelayBuffer.cpp index b013a41d55a985..52c8d4184bf2f8 100644 --- a/dom/media/webaudio/DelayBuffer.cpp +++ b/dom/media/webaudio/DelayBuffer.cpp @@ -130,7 +130,7 @@ void DelayBuffer::ReadChannels(const float aPerFrameDelays[WEBAUDIO_BLOCK_SIZE], positions[1] = PositionForDelay(floorDelay) + i; positions[0] = positions[1] - 1; - for (unsigned tick = 0; tick < std::size(positions); ++tick) { + for (unsigned tick = 0; tick < ArrayLength(positions); ++tick) { int readChunk = ChunkForPosition(positions[tick]); // The zero check on interpolationFactor is important because, when // currentDelay is integer, positions[0] may be outside the range diff --git a/dom/media/webaudio/blink/HRTFElevation.cpp b/dom/media/webaudio/blink/HRTFElevation.cpp index 658f6307b03c81..38ac0f8614ac74 100644 --- a/dom/media/webaudio/blink/HRTFElevation.cpp +++ b/dom/media/webaudio/blink/HRTFElevation.cpp @@ -40,7 +40,7 @@ namespace WebCore { const int elevationSpacing = irc_composite_c_r0195_elevation_interval; const int firstElevation = irc_composite_c_r0195_first_elevation; -const int numberOfElevations = std::size(irc_composite_c_r0195); +const int numberOfElevations = MOZ_ARRAY_LENGTH(irc_composite_c_r0195); const unsigned HRTFElevation::NumberOfTotalAzimuths = 360 / 15 * 8; diff --git a/dom/media/webaudio/blink/IRC_Composite_C_R0195-incl.cpp b/dom/media/webaudio/blink/IRC_Composite_C_R0195-incl.cpp index b3710ac7bc2918..37d731d3a28210 100644 --- a/dom/media/webaudio/blink/IRC_Composite_C_R0195-incl.cpp +++ b/dom/media/webaudio/blink/IRC_Composite_C_R0195-incl.cpp @@ -20,6 +20,8 @@ #include "mozilla/ArrayUtils.h" +using mozilla::ArrayLength; + const int16_t irc_composite_c_r0195_p315[][256] = {/* IRC_Composite_C_R0195_T000_P315.wav */ {-37, 37, -38, 39, -39, 40, -41, 42, -42, 43, -43, @@ -4553,16 +4555,16 @@ struct Elevation { * elevation. */ const Elevation irc_composite_c_r0195[] = { - {irc_composite_c_r0195_p315, std::size(irc_composite_c_r0195_p315)}, - {irc_composite_c_r0195_p330, std::size(irc_composite_c_r0195_p330)}, - {irc_composite_c_r0195_p345, std::size(irc_composite_c_r0195_p345)}, - {irc_composite_c_r0195_p000, std::size(irc_composite_c_r0195_p000)}, - {irc_composite_c_r0195_p015, std::size(irc_composite_c_r0195_p015)}, - {irc_composite_c_r0195_p030, std::size(irc_composite_c_r0195_p030)}, - {irc_composite_c_r0195_p045, std::size(irc_composite_c_r0195_p045)}, - {irc_composite_c_r0195_p060, std::size(irc_composite_c_r0195_p060)}, - {irc_composite_c_r0195_p075, std::size(irc_composite_c_r0195_p075)}, - {irc_composite_c_r0195_p090, std::size(irc_composite_c_r0195_p090)}}; + {irc_composite_c_r0195_p315, MOZ_ARRAY_LENGTH(irc_composite_c_r0195_p315)}, + {irc_composite_c_r0195_p330, MOZ_ARRAY_LENGTH(irc_composite_c_r0195_p330)}, + {irc_composite_c_r0195_p345, MOZ_ARRAY_LENGTH(irc_composite_c_r0195_p345)}, + {irc_composite_c_r0195_p000, MOZ_ARRAY_LENGTH(irc_composite_c_r0195_p000)}, + {irc_composite_c_r0195_p015, MOZ_ARRAY_LENGTH(irc_composite_c_r0195_p015)}, + {irc_composite_c_r0195_p030, MOZ_ARRAY_LENGTH(irc_composite_c_r0195_p030)}, + {irc_composite_c_r0195_p045, MOZ_ARRAY_LENGTH(irc_composite_c_r0195_p045)}, + {irc_composite_c_r0195_p060, MOZ_ARRAY_LENGTH(irc_composite_c_r0195_p060)}, + {irc_composite_c_r0195_p075, MOZ_ARRAY_LENGTH(irc_composite_c_r0195_p075)}, + {irc_composite_c_r0195_p090, MOZ_ARRAY_LENGTH(irc_composite_c_r0195_p090)}}; const int irc_composite_c_r0195_first_elevation = -45; /* degrees */ const int irc_composite_c_r0195_elevation_interval = 15; /* degrees */ diff --git a/dom/media/webaudio/blink/ReverbConvolver.cpp b/dom/media/webaudio/blink/ReverbConvolver.cpp index 4bc4283bbe0ae3..dcaf6e746779d2 100644 --- a/dom/media/webaudio/blink/ReverbConvolver.cpp +++ b/dom/media/webaudio/blink/ReverbConvolver.cpp @@ -136,7 +136,7 @@ ReverbConvolver::ReverbConvolver(const float* impulseResponseData, // performed in blocks 3 + 8 * n and size 1024 at 1 + 4 * n. const uint32_t phaseLookup[] = {14, 0, 10, 4}; stagePhase = WEBAUDIO_BLOCK_SIZE * - phaseLookup[m_stages.Length() % std::size(phaseLookup)]; + phaseLookup[m_stages.Length() % ArrayLength(phaseLookup)]; } else if (fftSize > maxFFTSize) { fftSize = maxFFTSize; // A prime offset spreads out FFTs in a way that all diff --git a/dom/media/webrtc/transport/transportlayerdtls.cpp b/dom/media/webrtc/transport/transportlayerdtls.cpp index a84d65c0940e30..8093263470587f 100644 --- a/dom/media/webrtc/transport/transportlayerdtls.cpp +++ b/dom/media/webrtc/transport/transportlayerdtls.cpp @@ -598,7 +598,7 @@ bool TransportLayerDtls::Setup() { } rv = SSL_NamedGroupConfig(ssl_fd.get(), NamedGroupPreferences, - std::size(NamedGroupPreferences)); + mozilla::ArrayLength(NamedGroupPreferences)); if (rv != SECSuccess) { MOZ_MTLOG(ML_ERROR, "Couldn't set named groups"); return false; diff --git a/dom/media/webspeech/recognition/SpeechRecognition.cpp b/dom/media/webspeech/recognition/SpeechRecognition.cpp index 48b1dfb18270b0..e06d76bf29afd2 100644 --- a/dom/media/webspeech/recognition/SpeechRecognition.cpp +++ b/dom/media/webspeech/recognition/SpeechRecognition.cpp @@ -1131,7 +1131,7 @@ const char* SpeechRecognition::GetName(FSMState aId) { }; MOZ_ASSERT(aId < STATE_COUNT); - MOZ_ASSERT(std::size(names) == STATE_COUNT); + MOZ_ASSERT(ArrayLength(names) == STATE_COUNT); return names[aId]; } @@ -1146,7 +1146,7 @@ const char* SpeechRecognition::GetName(SpeechEvent* aEvent) { "EVENT_RECOGNITIONSERVICE_ERROR"}; MOZ_ASSERT(aEvent->mType < EVENT_COUNT); - MOZ_ASSERT(std::size(names) == EVENT_COUNT); + MOZ_ASSERT(ArrayLength(names) == EVENT_COUNT); return names[aEvent->mType]; } diff --git a/dom/media/webspeech/synth/speechd/SpeechDispatcherService.cpp b/dom/media/webspeech/synth/speechd/SpeechDispatcherService.cpp index 66d5f9c9184c17..c0944cf24f1eb0 100644 --- a/dom/media/webspeech/synth/speechd/SpeechDispatcherService.cpp +++ b/dom/media/webspeech/synth/speechd/SpeechDispatcherService.cpp @@ -334,7 +334,7 @@ void SpeechDispatcherService::Setup() { return; } - for (uint32_t i = 0; i < std::size(kSpeechDispatcherSymbols); i++) { + for (uint32_t i = 0; i < ArrayLength(kSpeechDispatcherSymbols); i++) { *kSpeechDispatcherSymbols[i].function = PR_FindFunctionSymbol( speechdLib, kSpeechDispatcherSymbols[i].functionName); diff --git a/dom/media/webspeech/synth/test/nsFakeSynthServices.cpp b/dom/media/webspeech/synth/test/nsFakeSynthServices.cpp index cc0604309ef4b5..075e8aa87892cc 100644 --- a/dom/media/webspeech/synth/test/nsFakeSynthServices.cpp +++ b/dom/media/webspeech/synth/test/nsFakeSynthServices.cpp @@ -240,7 +240,7 @@ static void AddVoices(nsISpeechService* aService, const VoiceDetails* aVoices, void nsFakeSynthServices::Init() { mSynthService = new FakeSpeechSynth(); - AddVoices(mSynthService, sVoices, std::size(sVoices)); + AddVoices(mSynthService, sVoices, ArrayLength(sVoices)); } // nsIObserver diff --git a/dom/midi/MIDIUtils.cpp b/dom/midi/MIDIUtils.cpp index e0f7fc18853261..645889a167f2f7 100644 --- a/dom/midi/MIDIUtils.cpp +++ b/dom/midi/MIDIUtils.cpp @@ -86,7 +86,7 @@ bool IsValidMessage(const MIDIMessage* aMsg) { // much about message validity other than that. if ((cmd & kSystemMessage) == kSystemMessage) { if (cmd - kSystemMessage >= - static_cast(std::size(kSystemLengths))) { + static_cast(ArrayLength(kSystemLengths))) { NS_WARNING("System Message Command byte not valid!"); return false; } @@ -96,7 +96,7 @@ bool IsValidMessage(const MIDIMessage* aMsg) { // of the first byte. Shift this down to give the index of the expected packet // length. uint8_t cmdIndex = (cmd - kCommandByte) >> 4; - if (cmdIndex >= std::size(kCommandLengths)) { + if (cmdIndex >= ArrayLength(kCommandLengths)) { // If our index is bigger than our array length, command byte is unknown; NS_WARNING("Unknown MIDI command!"); return false; diff --git a/dom/permission/PermissionUtils.cpp b/dom/permission/PermissionUtils.cpp index 8982957942036b..b59bd9c45f573e 100644 --- a/dom/permission/PermissionUtils.cpp +++ b/dom/permission/PermissionUtils.cpp @@ -29,11 +29,11 @@ static const nsLiteralCString kPermissionTypes[] = { const size_t kPermissionNameCount = ContiguousEnumSize::value; -static_assert(std::size(kPermissionTypes) == kPermissionNameCount, +static_assert(MOZ_ARRAY_LENGTH(kPermissionTypes) == kPermissionNameCount, "kPermissionTypes and PermissionName count should match"); const nsLiteralCString& PermissionNameToType(PermissionName aName) { - MOZ_ASSERT((size_t)aName < std::size(kPermissionTypes)); + MOZ_ASSERT((size_t)aName < ArrayLength(kPermissionTypes)); return kPermissionTypes[static_cast(aName)]; } @@ -50,7 +50,7 @@ Maybe TypeToPermissionName(const nsACString& aType) { return Some(PermissionName::Storage_access); } - for (size_t i = 0; i < std::size(kPermissionTypes); ++i) { + for (size_t i = 0; i < ArrayLength(kPermissionTypes); ++i) { if (kPermissionTypes[i].Equals(aType)) { return Some(static_cast(i)); } diff --git a/dom/security/nsContentSecurityUtils.cpp b/dom/security/nsContentSecurityUtils.cpp index 0f1494f8f632ab..ff65b2ed99b36a 100644 --- a/dom/security/nsContentSecurityUtils.cpp +++ b/dom/security/nsContentSecurityUtils.cpp @@ -367,7 +367,7 @@ FilenameTypeAndDetails nsContentSecurityUtils::FilenameToFilenameType( ? kMozillaExtensionFile : kOtherExtensionFile; const auto& extensionNameAndPath = - Substring(regexResults[0], std::size("extensions/") - 1); + Substring(regexResults[0], ArrayLength("extensions/") - 1); return FilenameTypeAndDetails( type, Some(OptimizeFileName(extensionNameAndPath))); } diff --git a/dom/serviceworkers/ServiceWorkerRegistrar.cpp b/dom/serviceworkers/ServiceWorkerRegistrar.cpp index fb509b3beeb628..8c5fd2671329eb 100644 --- a/dom/serviceworkers/ServiceWorkerRegistrar.cpp +++ b/dom/serviceworkers/ServiceWorkerRegistrar.cpp @@ -1095,7 +1095,7 @@ void ServiceWorkerRegistrar::MaybeResetGeneration() { bool ServiceWorkerRegistrar::IsSupportedVersion( const nsACString& aVersion) const { - uint32_t numVersions = std::size(gSupportedRegistrarVersions); + uint32_t numVersions = ArrayLength(gSupportedRegistrarVersions); for (uint32_t i = 0; i < numVersions; i++) { if (aVersion.EqualsASCII(gSupportedRegistrarVersions[i])) { return true; diff --git a/dom/svg/SVGAElement.cpp b/dom/svg/SVGAElement.cpp index 7366dc75e810d4..b7ffbb624a69c9 100644 --- a/dom/svg/SVGAElement.cpp +++ b/dom/svg/SVGAElement.cpp @@ -253,7 +253,7 @@ void SVGAElement::AfterSetAttr(int32_t aNameSpaceID, nsAtom* aName, SVGElement::StringAttributesInfo SVGAElement::GetStringInfo() { return StringAttributesInfo(mStringAttributes, sStringInfo, - std::size(sStringInfo)); + ArrayLength(sStringInfo)); } void SVGAElement::DidAnimateAttribute(int32_t aNameSpaceID, diff --git a/dom/svg/SVGCircleElement.cpp b/dom/svg/SVGCircleElement.cpp index 6f74419820391e..c3f4beb40d33e3 100644 --- a/dom/svg/SVGCircleElement.cpp +++ b/dom/svg/SVGCircleElement.cpp @@ -82,7 +82,7 @@ bool SVGCircleElement::HasValidDimensions() const { SVGElement::LengthAttributesInfo SVGCircleElement::GetLengthInfo() { return LengthAttributesInfo(mLengthAttributes, sLengthInfo, - std::size(sLengthInfo)); + ArrayLength(sLengthInfo)); } //---------------------------------------------------------------------- diff --git a/dom/svg/SVGClipPathElement.cpp b/dom/svg/SVGClipPathElement.cpp index 09b8411227cec7..a10624079d289e 100644 --- a/dom/svg/SVGClipPathElement.cpp +++ b/dom/svg/SVGClipPathElement.cpp @@ -38,7 +38,7 @@ SVGClipPathElement::ClipPathUnits() { } SVGElement::EnumAttributesInfo SVGClipPathElement::GetEnumInfo() { - return EnumAttributesInfo(mEnumAttributes, sEnumInfo, std::size(sEnumInfo)); + return EnumAttributesInfo(mEnumAttributes, sEnumInfo, ArrayLength(sEnumInfo)); } bool SVGClipPathElement::IsUnitsObjectBoundingBox() const { diff --git a/dom/svg/SVGContentUtils.h b/dom/svg/SVGContentUtils.h index e4d8d6defe9c0d..798201753e95b3 100644 --- a/dom/svg/SVGContentUtils.h +++ b/dom/svg/SVGContentUtils.h @@ -81,7 +81,7 @@ class SVGContentUtils { * initialize the values in the buffer, since mDashPattern is const). */ Float* InitDashPattern(size_t aDashCount) { - if (aDashCount <= std::size(mSmallArray)) { + if (aDashCount <= MOZ_ARRAY_LENGTH(mSmallArray)) { mDashPattern = mSmallArray; return mSmallArray; } diff --git a/dom/svg/SVGEllipseElement.cpp b/dom/svg/SVGEllipseElement.cpp index b8ae920a2fc406..b81d4659159e9f 100644 --- a/dom/svg/SVGEllipseElement.cpp +++ b/dom/svg/SVGEllipseElement.cpp @@ -96,7 +96,7 @@ bool SVGEllipseElement::HasValidDimensions() const { SVGElement::LengthAttributesInfo SVGEllipseElement::GetLengthInfo() { return LengthAttributesInfo(mLengthAttributes, sLengthInfo, - std::size(sLengthInfo)); + ArrayLength(sLengthInfo)); } //---------------------------------------------------------------------- diff --git a/dom/svg/SVGFEBlendElement.cpp b/dom/svg/SVGFEBlendElement.cpp index 27481e9ecf010e..a152bd78974a7b 100644 --- a/dom/svg/SVGFEBlendElement.cpp +++ b/dom/svg/SVGFEBlendElement.cpp @@ -103,12 +103,12 @@ nsresult SVGFEBlendElement::BindToTree(BindContext& aCtx, nsINode& aParent) { // SVGElement methods SVGElement::EnumAttributesInfo SVGFEBlendElement::GetEnumInfo() { - return EnumAttributesInfo(mEnumAttributes, sEnumInfo, std::size(sEnumInfo)); + return EnumAttributesInfo(mEnumAttributes, sEnumInfo, ArrayLength(sEnumInfo)); } SVGElement::StringAttributesInfo SVGFEBlendElement::GetStringInfo() { return StringAttributesInfo(mStringAttributes, sStringInfo, - std::size(sStringInfo)); + ArrayLength(sStringInfo)); } } // namespace mozilla::dom diff --git a/dom/svg/SVGFEColorMatrixElement.cpp b/dom/svg/SVGFEColorMatrixElement.cpp index f9de1116b798a9..76fee0c9d65214 100644 --- a/dom/svg/SVGFEColorMatrixElement.cpp +++ b/dom/svg/SVGFEColorMatrixElement.cpp @@ -120,18 +120,18 @@ nsresult SVGFEColorMatrixElement::BindToTree(BindContext& aCtx, // SVGElement methods SVGElement::EnumAttributesInfo SVGFEColorMatrixElement::GetEnumInfo() { - return EnumAttributesInfo(mEnumAttributes, sEnumInfo, std::size(sEnumInfo)); + return EnumAttributesInfo(mEnumAttributes, sEnumInfo, ArrayLength(sEnumInfo)); } SVGElement::StringAttributesInfo SVGFEColorMatrixElement::GetStringInfo() { return StringAttributesInfo(mStringAttributes, sStringInfo, - std::size(sStringInfo)); + ArrayLength(sStringInfo)); } SVGElement::NumberListAttributesInfo SVGFEColorMatrixElement::GetNumberListInfo() { return NumberListAttributesInfo(mNumberListAttributes, sNumberListInfo, - std::size(sNumberListInfo)); + ArrayLength(sNumberListInfo)); } } // namespace mozilla::dom diff --git a/dom/svg/SVGFEComponentTransferElement.cpp b/dom/svg/SVGFEComponentTransferElement.cpp index b9156e011d6dc3..fd9c44fc74355e 100644 --- a/dom/svg/SVGFEComponentTransferElement.cpp +++ b/dom/svg/SVGFEComponentTransferElement.cpp @@ -43,7 +43,7 @@ already_AddRefed SVGFEComponentTransferElement::In1() { SVGElement::StringAttributesInfo SVGFEComponentTransferElement::GetStringInfo() { return StringAttributesInfo(mStringAttributes, sStringInfo, - std::size(sStringInfo)); + ArrayLength(sStringInfo)); } //-------------------------------------------- diff --git a/dom/svg/SVGFECompositeElement.cpp b/dom/svg/SVGFECompositeElement.cpp index 9d19760ae12fc3..dee3d95a5f7138 100644 --- a/dom/svg/SVGFECompositeElement.cpp +++ b/dom/svg/SVGFECompositeElement.cpp @@ -132,16 +132,16 @@ nsresult SVGFECompositeElement::BindToTree(BindContext& aCtx, SVGElement::NumberAttributesInfo SVGFECompositeElement::GetNumberInfo() { return NumberAttributesInfo(mNumberAttributes, sNumberInfo, - std::size(sNumberInfo)); + ArrayLength(sNumberInfo)); } SVGElement::EnumAttributesInfo SVGFECompositeElement::GetEnumInfo() { - return EnumAttributesInfo(mEnumAttributes, sEnumInfo, std::size(sEnumInfo)); + return EnumAttributesInfo(mEnumAttributes, sEnumInfo, ArrayLength(sEnumInfo)); } SVGElement::StringAttributesInfo SVGFECompositeElement::GetStringInfo() { return StringAttributesInfo(mStringAttributes, sStringInfo, - std::size(sStringInfo)); + ArrayLength(sStringInfo)); } } // namespace mozilla::dom diff --git a/dom/svg/SVGFEConvolveMatrixElement.cpp b/dom/svg/SVGFEConvolveMatrixElement.cpp index 5550fa53a985db..6a1bf9cd9c29ea 100644 --- a/dom/svg/SVGFEConvolveMatrixElement.cpp +++ b/dom/svg/SVGFEConvolveMatrixElement.cpp @@ -230,44 +230,44 @@ nsresult SVGFEConvolveMatrixElement::BindToTree(BindContext& aCtx, SVGElement::NumberAttributesInfo SVGFEConvolveMatrixElement::GetNumberInfo() { return NumberAttributesInfo(mNumberAttributes, sNumberInfo, - std::size(sNumberInfo)); + ArrayLength(sNumberInfo)); } SVGElement::NumberPairAttributesInfo SVGFEConvolveMatrixElement::GetNumberPairInfo() { return NumberPairAttributesInfo(mNumberPairAttributes, sNumberPairInfo, - std::size(sNumberPairInfo)); + ArrayLength(sNumberPairInfo)); } SVGElement::IntegerAttributesInfo SVGFEConvolveMatrixElement::GetIntegerInfo() { return IntegerAttributesInfo(mIntegerAttributes, sIntegerInfo, - std::size(sIntegerInfo)); + ArrayLength(sIntegerInfo)); } SVGElement::IntegerPairAttributesInfo SVGFEConvolveMatrixElement::GetIntegerPairInfo() { return IntegerPairAttributesInfo(mIntegerPairAttributes, sIntegerPairInfo, - std::size(sIntegerPairInfo)); + ArrayLength(sIntegerPairInfo)); } SVGElement::BooleanAttributesInfo SVGFEConvolveMatrixElement::GetBooleanInfo() { return BooleanAttributesInfo(mBooleanAttributes, sBooleanInfo, - std::size(sBooleanInfo)); + ArrayLength(sBooleanInfo)); } SVGElement::EnumAttributesInfo SVGFEConvolveMatrixElement::GetEnumInfo() { - return EnumAttributesInfo(mEnumAttributes, sEnumInfo, std::size(sEnumInfo)); + return EnumAttributesInfo(mEnumAttributes, sEnumInfo, ArrayLength(sEnumInfo)); } SVGElement::StringAttributesInfo SVGFEConvolveMatrixElement::GetStringInfo() { return StringAttributesInfo(mStringAttributes, sStringInfo, - std::size(sStringInfo)); + ArrayLength(sStringInfo)); } SVGElement::NumberListAttributesInfo SVGFEConvolveMatrixElement::GetNumberListInfo() { return NumberListAttributesInfo(mNumberListAttributes, sNumberListInfo, - std::size(sNumberListInfo)); + ArrayLength(sNumberListInfo)); } } // namespace mozilla::dom diff --git a/dom/svg/SVGFEDisplacementMapElement.cpp b/dom/svg/SVGFEDisplacementMapElement.cpp index 211e8b741381cb..c80d0d20e3ec5c 100644 --- a/dom/svg/SVGFEDisplacementMapElement.cpp +++ b/dom/svg/SVGFEDisplacementMapElement.cpp @@ -124,16 +124,16 @@ nsresult SVGFEDisplacementMapElement::BindToTree(BindContext& aCtx, SVGElement::NumberAttributesInfo SVGFEDisplacementMapElement::GetNumberInfo() { return NumberAttributesInfo(mNumberAttributes, sNumberInfo, - std::size(sNumberInfo)); + ArrayLength(sNumberInfo)); } SVGElement::EnumAttributesInfo SVGFEDisplacementMapElement::GetEnumInfo() { - return EnumAttributesInfo(mEnumAttributes, sEnumInfo, std::size(sEnumInfo)); + return EnumAttributesInfo(mEnumAttributes, sEnumInfo, ArrayLength(sEnumInfo)); } SVGElement::StringAttributesInfo SVGFEDisplacementMapElement::GetStringInfo() { return StringAttributesInfo(mStringAttributes, sStringInfo, - std::size(sStringInfo)); + ArrayLength(sStringInfo)); } } // namespace mozilla::dom diff --git a/dom/svg/SVGFEDistantLightElement.cpp b/dom/svg/SVGFEDistantLightElement.cpp index 2904fa56f6245b..e2e4edd3c6fea6 100644 --- a/dom/svg/SVGFEDistantLightElement.cpp +++ b/dom/svg/SVGFEDistantLightElement.cpp @@ -61,7 +61,7 @@ already_AddRefed SVGFEDistantLightElement::Elevation() { SVGElement::NumberAttributesInfo SVGFEDistantLightElement::GetNumberInfo() { return NumberAttributesInfo(mNumberAttributes, sNumberInfo, - std::size(sNumberInfo)); + ArrayLength(sNumberInfo)); } } // namespace mozilla::dom diff --git a/dom/svg/SVGFEDropShadowElement.cpp b/dom/svg/SVGFEDropShadowElement.cpp index 7226ab07d5dd93..8dd04831cf50e9 100644 --- a/dom/svg/SVGFEDropShadowElement.cpp +++ b/dom/svg/SVGFEDropShadowElement.cpp @@ -133,18 +133,18 @@ void SVGFEDropShadowElement::GetSourceImageNames( SVGElement::NumberAttributesInfo SVGFEDropShadowElement::GetNumberInfo() { return NumberAttributesInfo(mNumberAttributes, sNumberInfo, - std::size(sNumberInfo)); + ArrayLength(sNumberInfo)); } SVGElement::NumberPairAttributesInfo SVGFEDropShadowElement::GetNumberPairInfo() { return NumberPairAttributesInfo(mNumberPairAttributes, sNumberPairInfo, - std::size(sNumberPairInfo)); + ArrayLength(sNumberPairInfo)); } SVGElement::StringAttributesInfo SVGFEDropShadowElement::GetStringInfo() { return StringAttributesInfo(mStringAttributes, sStringInfo, - std::size(sStringInfo)); + ArrayLength(sStringInfo)); } } // namespace mozilla::dom diff --git a/dom/svg/SVGFEFloodElement.cpp b/dom/svg/SVGFEFloodElement.cpp index 7f97a5b59cf289..af2c59034f71e0 100644 --- a/dom/svg/SVGFEFloodElement.cpp +++ b/dom/svg/SVGFEFloodElement.cpp @@ -77,7 +77,7 @@ nsresult SVGFEFloodElement::BindToTree(BindContext& aCtx, nsINode& aParent) { SVGElement::StringAttributesInfo SVGFEFloodElement::GetStringInfo() { return StringAttributesInfo(mStringAttributes, sStringInfo, - std::size(sStringInfo)); + ArrayLength(sStringInfo)); } } // namespace mozilla::dom diff --git a/dom/svg/SVGFEGaussianBlurElement.cpp b/dom/svg/SVGFEGaussianBlurElement.cpp index 58344fb60106b3..09d1f231ad5b79 100644 --- a/dom/svg/SVGFEGaussianBlurElement.cpp +++ b/dom/svg/SVGFEGaussianBlurElement.cpp @@ -105,12 +105,12 @@ nsresult SVGFEGaussianBlurElement::BindToTree(BindContext& aCtx, SVGElement::NumberPairAttributesInfo SVGFEGaussianBlurElement::GetNumberPairInfo() { return NumberPairAttributesInfo(mNumberPairAttributes, sNumberPairInfo, - std::size(sNumberPairInfo)); + ArrayLength(sNumberPairInfo)); } SVGElement::StringAttributesInfo SVGFEGaussianBlurElement::GetStringInfo() { return StringAttributesInfo(mStringAttributes, sStringInfo, - std::size(sStringInfo)); + ArrayLength(sStringInfo)); } } // namespace mozilla::dom diff --git a/dom/svg/SVGFEImageElement.cpp b/dom/svg/SVGFEImageElement.cpp index 664e4d42acd74b..1d2e21d0f7e81a 100644 --- a/dom/svg/SVGFEImageElement.cpp +++ b/dom/svg/SVGFEImageElement.cpp @@ -319,7 +319,7 @@ SVGFEImageElement::GetAnimatedPreserveAspectRatio() { SVGElement::StringAttributesInfo SVGFEImageElement::GetStringInfo() { return StringAttributesInfo(mStringAttributes, sStringInfo, - std::size(sStringInfo)); + ArrayLength(sStringInfo)); } //---------------------------------------------------------------------- diff --git a/dom/svg/SVGFEMergeElement.cpp b/dom/svg/SVGFEMergeElement.cpp index 08db71a9497669..49ee61fc7870ed 100644 --- a/dom/svg/SVGFEMergeElement.cpp +++ b/dom/svg/SVGFEMergeElement.cpp @@ -55,7 +55,7 @@ nsresult SVGFEMergeElement::BindToTree(BindContext& aCtx, nsINode& aParent) { SVGElement::StringAttributesInfo SVGFEMergeElement::GetStringInfo() { return StringAttributesInfo(mStringAttributes, sStringInfo, - std::size(sStringInfo)); + ArrayLength(sStringInfo)); } } // namespace mozilla::dom diff --git a/dom/svg/SVGFEMergeNodeElement.cpp b/dom/svg/SVGFEMergeNodeElement.cpp index bbc0f6c3434edc..6e1835de4a608f 100644 --- a/dom/svg/SVGFEMergeNodeElement.cpp +++ b/dom/svg/SVGFEMergeNodeElement.cpp @@ -41,7 +41,7 @@ already_AddRefed SVGFEMergeNodeElement::In1() { SVGElement::StringAttributesInfo SVGFEMergeNodeElement::GetStringInfo() { return StringAttributesInfo(mStringAttributes, sStringInfo, - std::size(sStringInfo)); + ArrayLength(sStringInfo)); } } // namespace mozilla::dom diff --git a/dom/svg/SVGFEMorphologyElement.cpp b/dom/svg/SVGFEMorphologyElement.cpp index a897035c04be52..63e0172575dccb 100644 --- a/dom/svg/SVGFEMorphologyElement.cpp +++ b/dom/svg/SVGFEMorphologyElement.cpp @@ -125,16 +125,16 @@ nsresult SVGFEMorphologyElement::BindToTree(BindContext& aCtx, SVGElement::NumberPairAttributesInfo SVGFEMorphologyElement::GetNumberPairInfo() { return NumberPairAttributesInfo(mNumberPairAttributes, sNumberPairInfo, - std::size(sNumberPairInfo)); + ArrayLength(sNumberPairInfo)); } SVGElement::EnumAttributesInfo SVGFEMorphologyElement::GetEnumInfo() { - return EnumAttributesInfo(mEnumAttributes, sEnumInfo, std::size(sEnumInfo)); + return EnumAttributesInfo(mEnumAttributes, sEnumInfo, ArrayLength(sEnumInfo)); } SVGElement::StringAttributesInfo SVGFEMorphologyElement::GetStringInfo() { return StringAttributesInfo(mStringAttributes, sStringInfo, - std::size(sStringInfo)); + ArrayLength(sStringInfo)); } } // namespace mozilla::dom diff --git a/dom/svg/SVGFEOffsetElement.cpp b/dom/svg/SVGFEOffsetElement.cpp index 6b0038ce0b6fc8..1f8050a7cde169 100644 --- a/dom/svg/SVGFEOffsetElement.cpp +++ b/dom/svg/SVGFEOffsetElement.cpp @@ -87,12 +87,12 @@ nsresult SVGFEOffsetElement::BindToTree(BindContext& aCtx, nsINode& aParent) { SVGElement::NumberAttributesInfo SVGFEOffsetElement::GetNumberInfo() { return NumberAttributesInfo(mNumberAttributes, sNumberInfo, - std::size(sNumberInfo)); + ArrayLength(sNumberInfo)); } SVGElement::StringAttributesInfo SVGFEOffsetElement::GetStringInfo() { return StringAttributesInfo(mStringAttributes, sStringInfo, - std::size(sStringInfo)); + ArrayLength(sStringInfo)); } } // namespace mozilla::dom diff --git a/dom/svg/SVGFEPointLightElement.cpp b/dom/svg/SVGFEPointLightElement.cpp index 92055e92d4ca6c..3d2ac7494d3982 100644 --- a/dom/svg/SVGFEPointLightElement.cpp +++ b/dom/svg/SVGFEPointLightElement.cpp @@ -68,7 +68,7 @@ already_AddRefed SVGFEPointLightElement::Z() { SVGElement::NumberAttributesInfo SVGFEPointLightElement::GetNumberInfo() { return NumberAttributesInfo(mNumberAttributes, sNumberInfo, - std::size(sNumberInfo)); + ArrayLength(sNumberInfo)); } } // namespace mozilla::dom diff --git a/dom/svg/SVGFESpotLightElement.cpp b/dom/svg/SVGFESpotLightElement.cpp index bee228dcfc18e4..6008ee3f27aa24 100644 --- a/dom/svg/SVGFESpotLightElement.cpp +++ b/dom/svg/SVGFESpotLightElement.cpp @@ -109,7 +109,7 @@ SVGFESpotLightElement::LimitingConeAngle() { SVGElement::NumberAttributesInfo SVGFESpotLightElement::GetNumberInfo() { return NumberAttributesInfo(mNumberAttributes, sNumberInfo, - std::size(sNumberInfo)); + ArrayLength(sNumberInfo)); } } // namespace mozilla::dom diff --git a/dom/svg/SVGFETileElement.cpp b/dom/svg/SVGFETileElement.cpp index b4b7a487e49a41..2833885b1e8ac6 100644 --- a/dom/svg/SVGFETileElement.cpp +++ b/dom/svg/SVGFETileElement.cpp @@ -60,7 +60,7 @@ bool SVGFETileElement::AttributeAffectsRendering(int32_t aNameSpaceID, SVGElement::StringAttributesInfo SVGFETileElement::GetStringInfo() { return StringAttributesInfo(mStringAttributes, sStringInfo, - std::size(sStringInfo)); + ArrayLength(sStringInfo)); } nsresult SVGFETileElement::BindToTree(BindContext& aCtx, nsINode& aParent) { diff --git a/dom/svg/SVGFETurbulenceElement.cpp b/dom/svg/SVGFETurbulenceElement.cpp index 8ad5cbd9d4aa49..e7ccb54057874c 100644 --- a/dom/svg/SVGFETurbulenceElement.cpp +++ b/dom/svg/SVGFETurbulenceElement.cpp @@ -168,27 +168,27 @@ nsresult SVGFETurbulenceElement::BindToTree(BindContext& aCtx, SVGElement::NumberAttributesInfo SVGFETurbulenceElement::GetNumberInfo() { return NumberAttributesInfo(mNumberAttributes, sNumberInfo, - std::size(sNumberInfo)); + ArrayLength(sNumberInfo)); } SVGElement::NumberPairAttributesInfo SVGFETurbulenceElement::GetNumberPairInfo() { return NumberPairAttributesInfo(mNumberPairAttributes, sNumberPairInfo, - std::size(sNumberPairInfo)); + ArrayLength(sNumberPairInfo)); } SVGElement::IntegerAttributesInfo SVGFETurbulenceElement::GetIntegerInfo() { return IntegerAttributesInfo(mIntegerAttributes, sIntegerInfo, - std::size(sIntegerInfo)); + ArrayLength(sIntegerInfo)); } SVGElement::EnumAttributesInfo SVGFETurbulenceElement::GetEnumInfo() { - return EnumAttributesInfo(mEnumAttributes, sEnumInfo, std::size(sEnumInfo)); + return EnumAttributesInfo(mEnumAttributes, sEnumInfo, ArrayLength(sEnumInfo)); } SVGElement::StringAttributesInfo SVGFETurbulenceElement::GetStringInfo() { return StringAttributesInfo(mStringAttributes, sStringInfo, - std::size(sStringInfo)); + ArrayLength(sStringInfo)); } } // namespace mozilla::dom diff --git a/dom/svg/SVGFilterElement.cpp b/dom/svg/SVGFilterElement.cpp index 9ecbc2ea6d668c..8140aa2164b9f6 100644 --- a/dom/svg/SVGFilterElement.cpp +++ b/dom/svg/SVGFilterElement.cpp @@ -102,16 +102,16 @@ bool SVGFilterElement::HasValidDimensions() const { SVGElement::LengthAttributesInfo SVGFilterElement::GetLengthInfo() { return LengthAttributesInfo(mLengthAttributes, sLengthInfo, - std::size(sLengthInfo)); + ArrayLength(sLengthInfo)); } SVGElement::EnumAttributesInfo SVGFilterElement::GetEnumInfo() { - return EnumAttributesInfo(mEnumAttributes, sEnumInfo, std::size(sEnumInfo)); + return EnumAttributesInfo(mEnumAttributes, sEnumInfo, ArrayLength(sEnumInfo)); } SVGElement::StringAttributesInfo SVGFilterElement::GetStringInfo() { return StringAttributesInfo(mStringAttributes, sStringInfo, - std::size(sStringInfo)); + ArrayLength(sStringInfo)); } } // namespace mozilla::dom diff --git a/dom/svg/SVGFilters.cpp b/dom/svg/SVGFilters.cpp index 07d3370498ee83..4b2c8608d4afe2 100644 --- a/dom/svg/SVGFilters.cpp +++ b/dom/svg/SVGFilters.cpp @@ -131,7 +131,7 @@ Size SVGFilterPrimitiveElement::GetKernelUnitLength( SVGElement::LengthAttributesInfo SVGFilterPrimitiveElement::GetLengthInfo() { return LengthAttributesInfo(mLengthAttributes, sLengthInfo, - std::size(sLengthInfo)); + ArrayLength(sLengthInfo)); } SVGElement::NumberListInfo @@ -253,18 +253,18 @@ void SVGComponentTransferFunctionElement::ComputeAttributes( SVGElement::NumberListAttributesInfo SVGComponentTransferFunctionElement::GetNumberListInfo() { return NumberListAttributesInfo(mNumberListAttributes, sNumberListInfo, - std::size(sNumberListInfo)); + ArrayLength(sNumberListInfo)); } SVGElement::EnumAttributesInfo SVGComponentTransferFunctionElement::GetEnumInfo() { - return EnumAttributesInfo(mEnumAttributes, sEnumInfo, std::size(sEnumInfo)); + return EnumAttributesInfo(mEnumAttributes, sEnumInfo, ArrayLength(sEnumInfo)); } SVGElement::NumberAttributesInfo SVGComponentTransferFunctionElement::GetNumberInfo() { return NumberAttributesInfo(mNumberAttributes, sNumberInfo, - std::size(sNumberInfo)); + ArrayLength(sNumberInfo)); } /* virtual */ @@ -422,17 +422,17 @@ bool SVGFELightingElement::AttributeAffectsRendering(int32_t aNameSpaceID, SVGElement::NumberAttributesInfo SVGFELightingElement::GetNumberInfo() { return NumberAttributesInfo(mNumberAttributes, sNumberInfo, - std::size(sNumberInfo)); + ArrayLength(sNumberInfo)); } SVGElement::NumberPairAttributesInfo SVGFELightingElement::GetNumberPairInfo() { return NumberPairAttributesInfo(mNumberPairAttributes, sNumberPairInfo, - std::size(sNumberPairInfo)); + ArrayLength(sNumberPairInfo)); } SVGElement::StringAttributesInfo SVGFELightingElement::GetStringInfo() { return StringAttributesInfo(mStringAttributes, sStringInfo, - std::size(sStringInfo)); + ArrayLength(sStringInfo)); } } // namespace mozilla::dom diff --git a/dom/svg/SVGForeignObjectElement.cpp b/dom/svg/SVGForeignObjectElement.cpp index 03a7d15eb94cf6..6d707393866212 100644 --- a/dom/svg/SVGForeignObjectElement.cpp +++ b/dom/svg/SVGForeignObjectElement.cpp @@ -105,7 +105,7 @@ SVGForeignObjectElement::IsAttributeMapped(const nsAtom* name) const { SVGElement::LengthAttributesInfo SVGForeignObjectElement::GetLengthInfo() { return LengthAttributesInfo(mLengthAttributes, sLengthInfo, - std::size(sLengthInfo)); + ArrayLength(sLengthInfo)); } nsCSSPropertyID SVGForeignObjectElement::GetCSSPropertyIdForAttrEnum( diff --git a/dom/svg/SVGGradientElement.cpp b/dom/svg/SVGGradientElement.cpp index 90238fc45d0195..192c8550c398bc 100644 --- a/dom/svg/SVGGradientElement.cpp +++ b/dom/svg/SVGGradientElement.cpp @@ -53,12 +53,12 @@ SVGGradientElement::SVGGradientElement( // SVGElement methods SVGElement::EnumAttributesInfo SVGGradientElement::GetEnumInfo() { - return EnumAttributesInfo(mEnumAttributes, sEnumInfo, std::size(sEnumInfo)); + return EnumAttributesInfo(mEnumAttributes, sEnumInfo, ArrayLength(sEnumInfo)); } SVGElement::StringAttributesInfo SVGGradientElement::GetStringInfo() { return StringAttributesInfo(mStringAttributes, sStringInfo, - std::size(sStringInfo)); + ArrayLength(sStringInfo)); } already_AddRefed @@ -145,7 +145,7 @@ SVGAnimatedTransformList* SVGGradientElement::GetAnimatedTransformList( SVGElement::LengthAttributesInfo SVGLinearGradientElement::GetLengthInfo() { return LengthAttributesInfo(mLengthAttributes, sLengthInfo, - std::size(sLengthInfo)); + ArrayLength(sLengthInfo)); } //-------------------------- Radial Gradients ---------------------------- @@ -218,7 +218,7 @@ bool SVGGradientElement::IsAttributeMapped(const nsAtom* aAttribute) const { SVGElement::LengthAttributesInfo SVGRadialGradientElement::GetLengthInfo() { return LengthAttributesInfo(mLengthAttributes, sLengthInfo, - std::size(sLengthInfo)); + ArrayLength(sLengthInfo)); } } // namespace mozilla::dom diff --git a/dom/svg/SVGImageElement.cpp b/dom/svg/SVGImageElement.cpp index a4fd143393cc7a..e2c59b3486ec24 100644 --- a/dom/svg/SVGImageElement.cpp +++ b/dom/svg/SVGImageElement.cpp @@ -303,7 +303,7 @@ bool SVGImageElement::HasValidDimensions() const { SVGElement::LengthAttributesInfo SVGImageElement::GetLengthInfo() { return LengthAttributesInfo(mLengthAttributes, sLengthInfo, - std::size(sLengthInfo)); + ArrayLength(sLengthInfo)); } SVGAnimatedPreserveAspectRatio* @@ -313,7 +313,7 @@ SVGImageElement::GetAnimatedPreserveAspectRatio() { SVGElement::StringAttributesInfo SVGImageElement::GetStringInfo() { return StringAttributesInfo(mStringAttributes, sStringInfo, - std::size(sStringInfo)); + ArrayLength(sStringInfo)); } void SVGImageElement::DidAnimateAttribute(int32_t aNameSpaceID, diff --git a/dom/svg/SVGLineElement.cpp b/dom/svg/SVGLineElement.cpp index 4bfe1235e4a0eb..7834bd14ad055f 100644 --- a/dom/svg/SVGLineElement.cpp +++ b/dom/svg/SVGLineElement.cpp @@ -81,7 +81,7 @@ already_AddRefed SVGLineElement::Y2() { SVGElement::LengthAttributesInfo SVGLineElement::GetLengthInfo() { return LengthAttributesInfo(mLengthAttributes, sLengthInfo, - std::size(sLengthInfo)); + ArrayLength(sLengthInfo)); } //---------------------------------------------------------------------- diff --git a/dom/svg/SVGMPathElement.cpp b/dom/svg/SVGMPathElement.cpp index 0397644b7fb732..8ff21f61cdd79d 100644 --- a/dom/svg/SVGMPathElement.cpp +++ b/dom/svg/SVGMPathElement.cpp @@ -95,7 +95,7 @@ void SVGMPathElement::AfterSetAttr(int32_t aNamespaceID, nsAtom* aName, SVGElement::StringAttributesInfo SVGMPathElement::GetStringInfo() { return StringAttributesInfo(mStringAttributes, sStringInfo, - std::size(sStringInfo)); + ArrayLength(sStringInfo)); } //---------------------------------------------------------------------- diff --git a/dom/svg/SVGMarkerElement.cpp b/dom/svg/SVGMarkerElement.cpp index 6b2e5499c6bbae..4cd876da0a3974 100644 --- a/dom/svg/SVGMarkerElement.cpp +++ b/dom/svg/SVGMarkerElement.cpp @@ -133,11 +133,11 @@ bool SVGMarkerElement::HasValidDimensions() const { SVGElement::LengthAttributesInfo SVGMarkerElement::GetLengthInfo() { return LengthAttributesInfo(mLengthAttributes, sLengthInfo, - std::size(sLengthInfo)); + ArrayLength(sLengthInfo)); } SVGElement::EnumAttributesInfo SVGMarkerElement::GetEnumInfo() { - return EnumAttributesInfo(mEnumAttributes, sEnumInfo, std::size(sEnumInfo)); + return EnumAttributesInfo(mEnumAttributes, sEnumInfo, ArrayLength(sEnumInfo)); } SVGAnimatedOrient* SVGMarkerElement::GetAnimatedOrient() { return &mOrient; } diff --git a/dom/svg/SVGMaskElement.cpp b/dom/svg/SVGMaskElement.cpp index 9a9583d566f42a..24aaa723823c8e 100644 --- a/dom/svg/SVGMaskElement.cpp +++ b/dom/svg/SVGMaskElement.cpp @@ -93,11 +93,11 @@ bool SVGMaskElement::HasValidDimensions() const { SVGElement::LengthAttributesInfo SVGMaskElement::GetLengthInfo() { return LengthAttributesInfo(mLengthAttributes, sLengthInfo, - std::size(sLengthInfo)); + ArrayLength(sLengthInfo)); } SVGElement::EnumAttributesInfo SVGMaskElement::GetEnumInfo() { - return EnumAttributesInfo(mEnumAttributes, sEnumInfo, std::size(sEnumInfo)); + return EnumAttributesInfo(mEnumAttributes, sEnumInfo, ArrayLength(sEnumInfo)); } } // namespace mozilla::dom diff --git a/dom/svg/SVGNumberList.cpp b/dom/svg/SVGNumberList.cpp index cbb9aa80c26e77..465379118c17eb 100644 --- a/dom/svg/SVGNumberList.cpp +++ b/dom/svg/SVGNumberList.cpp @@ -29,7 +29,8 @@ void SVGNumberList::GetValueAsString(nsAString& aValue) const { for (uint32_t i = 0; i < mNumbers.Length(); ++i) { // Would like to use aValue.AppendPrintf("%f", mNumbers[i]), but it's not // possible to always avoid trailing zeros. - nsTextFormatter::snprintf(buf, std::size(buf), u"%g", double(mNumbers[i])); + nsTextFormatter::snprintf(buf, ArrayLength(buf), u"%g", + double(mNumbers[i])); // We ignore OOM, since it's not useful for us to return an error. aValue.Append(buf); if (i != last) { diff --git a/dom/svg/SVGPathSegUtils.cpp b/dom/svg/SVGPathSegUtils.cpp index 65e08446ed73f1..a08af4e93c1743 100644 --- a/dom/svg/SVGPathSegUtils.cpp +++ b/dom/svg/SVGPathSegUtils.cpp @@ -6,7 +6,7 @@ #include "SVGPathSegUtils.h" -#include "mozilla/ArrayUtils.h" // std::size +#include "mozilla/ArrayUtils.h" // MOZ_ARRAY_LENGTH #include "mozilla/ServoStyleConsts.h" // StylePathCommand #include "gfx2DGlue.h" #include "SVGPathDataParser.h" diff --git a/dom/svg/SVGPatternElement.cpp b/dom/svg/SVGPatternElement.cpp index 073dba59408710..0cb9bf664e4e5d 100644 --- a/dom/svg/SVGPatternElement.cpp +++ b/dom/svg/SVGPatternElement.cpp @@ -138,11 +138,11 @@ bool SVGPatternElement::HasValidDimensions() const { SVGElement::LengthAttributesInfo SVGPatternElement::GetLengthInfo() { return LengthAttributesInfo(mLengthAttributes, sLengthInfo, - std::size(sLengthInfo)); + ArrayLength(sLengthInfo)); } SVGElement::EnumAttributesInfo SVGPatternElement::GetEnumInfo() { - return EnumAttributesInfo(mEnumAttributes, sEnumInfo, std::size(sEnumInfo)); + return EnumAttributesInfo(mEnumAttributes, sEnumInfo, ArrayLength(sEnumInfo)); } SVGAnimatedViewBox* SVGPatternElement::GetAnimatedViewBox() { @@ -156,7 +156,7 @@ SVGPatternElement::GetAnimatedPreserveAspectRatio() { SVGElement::StringAttributesInfo SVGPatternElement::GetStringInfo() { return StringAttributesInfo(mStringAttributes, sStringInfo, - std::size(sStringInfo)); + ArrayLength(sStringInfo)); } } // namespace mozilla::dom diff --git a/dom/svg/SVGPointList.cpp b/dom/svg/SVGPointList.cpp index bd77fc8e68b954..a498fa2a259e07 100644 --- a/dom/svg/SVGPointList.cpp +++ b/dom/svg/SVGPointList.cpp @@ -28,7 +28,7 @@ void SVGPointList::GetValueAsString(nsAString& aValue) const { for (uint32_t i = 0; i < mItems.Length(); ++i) { // Would like to use aValue.AppendPrintf("%f,%f", item.mX, item.mY), // but it's not possible to always avoid trailing zeros. - nsTextFormatter::snprintf(buf, std::size(buf), u"%g,%g", + nsTextFormatter::snprintf(buf, ArrayLength(buf), u"%g,%g", double(mItems[i].mX), double(mItems[i].mY)); // We ignore OOM, since it's not useful for us to return an error. aValue.Append(buf); diff --git a/dom/svg/SVGPreserveAspectRatio.cpp b/dom/svg/SVGPreserveAspectRatio.cpp index 964824496268a2..0cd947e867e9f2 100644 --- a/dom/svg/SVGPreserveAspectRatio.cpp +++ b/dom/svg/SVGPreserveAspectRatio.cpp @@ -26,7 +26,7 @@ static const char* sAlignStrings[] = { static const char* sMeetOrSliceStrings[] = {"meet", "slice"}; static uint16_t GetAlignForString(const nsAString& aAlignString) { - for (uint32_t i = 0; i < std::size(sAlignStrings); i++) { + for (uint32_t i = 0; i < ArrayLength(sAlignStrings); i++) { if (aAlignString.EqualsASCII(sAlignStrings[i])) { return (i + SVG_ALIGN_MIN_VALID); } @@ -36,7 +36,7 @@ static uint16_t GetAlignForString(const nsAString& aAlignString) { } static uint16_t GetMeetOrSliceForString(const nsAString& aMeetOrSlice) { - for (uint32_t i = 0; i < std::size(sMeetOrSliceStrings); i++) { + for (uint32_t i = 0; i < ArrayLength(sMeetOrSliceStrings); i++) { if (aMeetOrSlice.EqualsASCII(sMeetOrSliceStrings[i])) { return (i + SVG_MEETORSLICE_MIN_VALID); } diff --git a/dom/svg/SVGRectElement.cpp b/dom/svg/SVGRectElement.cpp index c581acd55d263d..ff10098c4bbe50 100644 --- a/dom/svg/SVGRectElement.cpp +++ b/dom/svg/SVGRectElement.cpp @@ -108,7 +108,7 @@ bool SVGRectElement::HasValidDimensions() const { SVGElement::LengthAttributesInfo SVGRectElement::GetLengthInfo() { return LengthAttributesInfo(mLengthAttributes, sLengthInfo, - std::size(sLengthInfo)); + ArrayLength(sLengthInfo)); } //---------------------------------------------------------------------- diff --git a/dom/svg/SVGSVGElement.cpp b/dom/svg/SVGSVGElement.cpp index 80c33f369ad7a2..072dfd411f7ed6 100644 --- a/dom/svg/SVGSVGElement.cpp +++ b/dom/svg/SVGSVGElement.cpp @@ -460,7 +460,7 @@ void SVGSVGElement::InvalidateTransformNotifyFrame() { } SVGElement::EnumAttributesInfo SVGSVGElement::GetEnumInfo() { - return EnumAttributesInfo(mEnumAttributes, sEnumInfo, std::size(sEnumInfo)); + return EnumAttributesInfo(mEnumAttributes, sEnumInfo, ArrayLength(sEnumInfo)); } void SVGSVGElement::SetImageOverridePreserveAspectRatio( diff --git a/dom/svg/SVGScriptElement.cpp b/dom/svg/SVGScriptElement.cpp index 04a4723d579c4b..d4ecc05015941e 100644 --- a/dom/svg/SVGScriptElement.cpp +++ b/dom/svg/SVGScriptElement.cpp @@ -182,7 +182,7 @@ bool SVGScriptElement::HasScriptContent() { SVGElement::StringAttributesInfo SVGScriptElement::GetStringInfo() { return StringAttributesInfo(mStringAttributes, sStringInfo, - std::size(sStringInfo)); + ArrayLength(sStringInfo)); } //---------------------------------------------------------------------- diff --git a/dom/svg/SVGTSpanElement.cpp b/dom/svg/SVGTSpanElement.cpp index 3712c913080a0d..36bb5c4c014a9a 100644 --- a/dom/svg/SVGTSpanElement.cpp +++ b/dom/svg/SVGTSpanElement.cpp @@ -24,12 +24,12 @@ SVGTSpanElement::SVGTSpanElement( : SVGTSpanElementBase(std::move(aNodeInfo)) {} SVGElement::EnumAttributesInfo SVGTSpanElement::GetEnumInfo() { - return EnumAttributesInfo(mEnumAttributes, sEnumInfo, std::size(sEnumInfo)); + return EnumAttributesInfo(mEnumAttributes, sEnumInfo, ArrayLength(sEnumInfo)); } SVGElement::LengthAttributesInfo SVGTSpanElement::GetLengthInfo() { return LengthAttributesInfo(mLengthAttributes, sLengthInfo, - std::size(sLengthInfo)); + ArrayLength(sLengthInfo)); } //---------------------------------------------------------------------- diff --git a/dom/svg/SVGTests.cpp b/dom/svg/SVGTests.cpp index 29b18c5bebf7bd..e7a9823ff36080 100644 --- a/dom/svg/SVGTests.cpp +++ b/dom/svg/SVGTests.cpp @@ -51,7 +51,7 @@ bool SVGTests::HasExtension(const nsAString& aExtension) const { bool SVGTests::IsConditionalProcessingAttribute( const nsAtom* aAttribute) const { - for (uint32_t i = 0; i < std::size(sStringListNames); i++) { + for (uint32_t i = 0; i < ArrayLength(sStringListNames); i++) { if (aAttribute == sStringListNames[i]) { return true; } @@ -197,7 +197,7 @@ bool SVGTests::PassesConditionalProcessingTests() const { bool SVGTests::ParseConditionalProcessingAttribute(nsAtom* aAttribute, const nsAString& aValue, nsAttrValue& aResult) { - for (uint32_t i = 0; i < std::size(sStringListNames); i++) { + for (uint32_t i = 0; i < ArrayLength(sStringListNames); i++) { if (aAttribute == sStringListNames[i]) { nsresult rv = mStringListAttributes[i].SetValue(aValue); if (NS_FAILED(rv)) { @@ -212,7 +212,7 @@ bool SVGTests::ParseConditionalProcessingAttribute(nsAtom* aAttribute, } void SVGTests::UnsetAttr(const nsAtom* aAttribute) { - for (uint32_t i = 0; i < std::size(sStringListNames); i++) { + for (uint32_t i = 0; i < ArrayLength(sStringListNames); i++) { if (aAttribute == sStringListNames[i]) { mStringListAttributes[i].Clear(); mPassesConditionalProcessingTests = Nothing(); @@ -227,7 +227,8 @@ nsStaticAtom* SVGTests::GetAttrName(uint8_t aAttrEnum) const { } void SVGTests::GetAttrValue(uint8_t aAttrEnum, nsAttrValue& aValue) const { - MOZ_ASSERT(aAttrEnum < std::size(sStringListNames), "aAttrEnum out of range"); + MOZ_ASSERT(aAttrEnum < ArrayLength(sStringListNames), + "aAttrEnum out of range"); aValue.SetTo(mStringListAttributes[aAttrEnum], nullptr); } diff --git a/dom/svg/SVGTextElement.cpp b/dom/svg/SVGTextElement.cpp index dc88d90814e33e..ca02d93cc2f978 100644 --- a/dom/svg/SVGTextElement.cpp +++ b/dom/svg/SVGTextElement.cpp @@ -24,12 +24,12 @@ SVGTextElement::SVGTextElement( : SVGTextElementBase(std::move(aNodeInfo)) {} SVGElement::EnumAttributesInfo SVGTextElement::GetEnumInfo() { - return EnumAttributesInfo(mEnumAttributes, sEnumInfo, std::size(sEnumInfo)); + return EnumAttributesInfo(mEnumAttributes, sEnumInfo, ArrayLength(sEnumInfo)); } SVGElement::LengthAttributesInfo SVGTextElement::GetLengthInfo() { return LengthAttributesInfo(mLengthAttributes, sLengthInfo, - std::size(sLengthInfo)); + ArrayLength(sLengthInfo)); } //---------------------------------------------------------------------- diff --git a/dom/svg/SVGTextPathElement.cpp b/dom/svg/SVGTextPathElement.cpp index ea465e876eb2b0..05b87f0e68281e 100644 --- a/dom/svg/SVGTextPathElement.cpp +++ b/dom/svg/SVGTextPathElement.cpp @@ -110,16 +110,16 @@ already_AddRefed SVGTextPathElement::Side() { SVGElement::LengthAttributesInfo SVGTextPathElement::GetLengthInfo() { return LengthAttributesInfo(mLengthAttributes, sLengthInfo, - std::size(sLengthInfo)); + ArrayLength(sLengthInfo)); } SVGElement::EnumAttributesInfo SVGTextPathElement::GetEnumInfo() { - return EnumAttributesInfo(mEnumAttributes, sEnumInfo, std::size(sEnumInfo)); + return EnumAttributesInfo(mEnumAttributes, sEnumInfo, ArrayLength(sEnumInfo)); } SVGElement::StringAttributesInfo SVGTextPathElement::GetStringInfo() { return StringAttributesInfo(mStringAttributes, sStringInfo, - std::size(sStringInfo)); + ArrayLength(sStringInfo)); } } // namespace mozilla::dom diff --git a/dom/svg/SVGTextPositioningElement.cpp b/dom/svg/SVGTextPositioningElement.cpp index bde9e8b71e66e6..7baa060e305ce3 100644 --- a/dom/svg/SVGTextPositioningElement.cpp +++ b/dom/svg/SVGTextPositioningElement.cpp @@ -23,7 +23,7 @@ SVGElement::LengthListInfo SVGTextPositioningElement::sLengthListInfo[4] = { SVGElement::LengthListAttributesInfo SVGTextPositioningElement::GetLengthListInfo() { return LengthListAttributesInfo(mLengthListAttributes, sLengthListInfo, - std::size(sLengthListInfo)); + ArrayLength(sLengthListInfo)); } SVGElement::NumberListInfo SVGTextPositioningElement::sNumberListInfo[1] = { @@ -32,7 +32,7 @@ SVGElement::NumberListInfo SVGTextPositioningElement::sNumberListInfo[1] = { SVGElement::NumberListAttributesInfo SVGTextPositioningElement::GetNumberListInfo() { return NumberListAttributesInfo(mNumberListAttributes, sNumberListInfo, - std::size(sNumberListInfo)); + ArrayLength(sNumberListInfo)); } //---------------------------------------------------------------------- diff --git a/dom/svg/SVGTransformListParser.cpp b/dom/svg/SVGTransformListParser.cpp index 7d2c36e354fd38..07993784d18031 100644 --- a/dom/svg/SVGTransformListParser.cpp +++ b/dom/svg/SVGTransformListParser.cpp @@ -126,7 +126,7 @@ bool SVGTransformListParser::ParseTranslate() { float t[2]; uint32_t count; - if (!ParseArguments(t, std::size(t), &count)) { + if (!ParseArguments(t, ArrayLength(t), &count)) { return false; } @@ -151,7 +151,7 @@ bool SVGTransformListParser::ParseScale() { float s[2]; uint32_t count; - if (!ParseArguments(s, std::size(s), &count)) { + if (!ParseArguments(s, ArrayLength(s), &count)) { return false; } @@ -176,7 +176,7 @@ bool SVGTransformListParser::ParseRotate() { float r[3]; uint32_t count; - if (!ParseArguments(r, std::size(r), &count)) { + if (!ParseArguments(r, ArrayLength(r), &count)) { return false; } @@ -235,7 +235,7 @@ bool SVGTransformListParser::ParseMatrix() { float m[6]; uint32_t count; - if (!ParseArguments(m, std::size(m), &count) || count != 6) { + if (!ParseArguments(m, ArrayLength(m), &count) || count != 6) { return false; } diff --git a/dom/svg/SVGUseElement.cpp b/dom/svg/SVGUseElement.cpp index 97b945d77c2d0d..7cb661f5416146 100644 --- a/dom/svg/SVGUseElement.cpp +++ b/dom/svg/SVGUseElement.cpp @@ -626,12 +626,12 @@ bool SVGUseElement::HasValidDimensions() const { SVGElement::LengthAttributesInfo SVGUseElement::GetLengthInfo() { return LengthAttributesInfo(mLengthAttributes, sLengthInfo, - std::size(sLengthInfo)); + ArrayLength(sLengthInfo)); } SVGElement::StringAttributesInfo SVGUseElement::GetStringInfo() { return StringAttributesInfo(mStringAttributes, sStringInfo, - std::size(sStringInfo)); + ArrayLength(sStringInfo)); } SVGUseFrame* SVGUseElement::GetFrame() const { diff --git a/dom/svg/SVGViewElement.cpp b/dom/svg/SVGViewElement.cpp index 007845b46d55d4..b7ea5a75411761 100644 --- a/dom/svg/SVGViewElement.cpp +++ b/dom/svg/SVGViewElement.cpp @@ -66,7 +66,7 @@ SVGViewElement::PreserveAspectRatio() { // SVGElement methods SVGElement::EnumAttributesInfo SVGViewElement::GetEnumInfo() { - return EnumAttributesInfo(mEnumAttributes, sEnumInfo, std::size(sEnumInfo)); + return EnumAttributesInfo(mEnumAttributes, sEnumInfo, ArrayLength(sEnumInfo)); } SVGAnimatedViewBox* SVGViewElement::GetAnimatedViewBox() { return &mViewBox; } diff --git a/dom/svg/SVGViewportElement.cpp b/dom/svg/SVGViewportElement.cpp index 33327addfee658..4a71785149ef15 100644 --- a/dom/svg/SVGViewportElement.cpp +++ b/dom/svg/SVGViewportElement.cpp @@ -309,7 +309,7 @@ SVGViewBox SVGViewportElement::GetViewBoxWithSynthesis( SVGElement::LengthAttributesInfo SVGViewportElement::GetLengthInfo() { return LengthAttributesInfo(mLengthAttributes, sLengthInfo, - std::size(sLengthInfo)); + ArrayLength(sLengthInfo)); } } // namespace mozilla::dom diff --git a/dom/workers/RuntimeService.cpp b/dom/workers/RuntimeService.cpp index 996b5699166711..9ffc693fbade04 100644 --- a/dom/workers/RuntimeService.cpp +++ b/dom/workers/RuntimeService.cpp @@ -381,7 +381,7 @@ void LoadJSGCMemoryOptions(const char* aPrefName, void* /* aClosure */) { #undef PREF auto pref = kWorkerPrefs; - auto end = kWorkerPrefs + std::size(kWorkerPrefs); + auto end = kWorkerPrefs + ArrayLength(kWorkerPrefs); if (gRuntimeServiceDuringInit) { // During init, we want to update every pref in kWorkerPrefs. diff --git a/dom/worklet/Worklet.cpp b/dom/worklet/Worklet.cpp index 6a24959061c9eb..7c37bdbba960cd 100644 --- a/dom/worklet/Worklet.cpp +++ b/dom/worklet/Worklet.cpp @@ -67,7 +67,7 @@ static bool LoadLocalizedStrings(nsTArray& aStrings) { ResolveError::InvalidBareSpecifier}; static_assert( - std::size(errors) == static_cast(ResolveError::Length), + ArrayLength(errors) == static_cast(ResolveError::Length), "The array 'errors' has missing entries in the enum class ResolveError."); for (auto i : errors) { diff --git a/dom/xhr/XMLHttpRequestMainThread.cpp b/dom/xhr/XMLHttpRequestMainThread.cpp index 59352f1e71613b..a32d20f0d9211d 100644 --- a/dom/xhr/XMLHttpRequestMainThread.cpp +++ b/dom/xhr/XMLHttpRequestMainThread.cpp @@ -1204,7 +1204,7 @@ bool XMLHttpRequestMainThread::IsSafeHeader( const char* kCrossOriginSafeHeaders[] = { "cache-control", "content-language", "content-type", "content-length", "expires", "last-modified", "pragma"}; - for (uint32_t i = 0; i < std::size(kCrossOriginSafeHeaders); ++i) { + for (uint32_t i = 0; i < ArrayLength(kCrossOriginSafeHeaders); ++i) { if (aHeader.LowerCaseEqualsASCII(kCrossOriginSafeHeaders[i])) { return true; } diff --git a/dom/xslt/xpath/txCoreFunctionCall.cpp b/dom/xslt/xpath/txCoreFunctionCall.cpp index 38f0a8d2907aa2..6e2285ed1802ed 100644 --- a/dom/xslt/xpath/txCoreFunctionCall.cpp +++ b/dom/xslt/xpath/txCoreFunctionCall.cpp @@ -647,7 +647,7 @@ bool txCoreFunctionCall::isSensitiveTo(ContextSensitivity aContext) { // static bool txCoreFunctionCall::getTypeFromAtom(nsAtom* aName, eType& aType) { uint32_t i; - for (i = 0; i < std::size(descriptTable); ++i) { + for (i = 0; i < ArrayLength(descriptTable); ++i) { if (aName == descriptTable[i].mName) { aType = static_cast(i); diff --git a/dom/xslt/xslt/txStylesheetCompileHandlers.cpp b/dom/xslt/xslt/txStylesheetCompileHandlers.cpp index 63a47c18617182..ddc9f6fb381dde 100644 --- a/dom/xslt/xslt/txStylesheetCompileHandlers.cpp +++ b/dom/xslt/xslt/txStylesheetCompileHandlers.cpp @@ -2296,11 +2296,11 @@ const txElementHandler* txHandlerTable::find(int32_t aNamespaceID, &gTx##_name##TableData.mOtherHandler); \ if (!gTx##_name##Handler) return false -#define INIT_HANDLER_WITH_ELEMENT_HANDLERS(_name) \ - INIT_HANDLER(_name); \ - \ - rv = gTx##_name##Handler->init(gTx##_name##ElementHandlers, \ - std::size(gTx##_name##ElementHandlers)); \ +#define INIT_HANDLER_WITH_ELEMENT_HANDLERS(_name) \ + INIT_HANDLER(_name); \ + \ + rv = gTx##_name##Handler->init(gTx##_name##ElementHandlers, \ + ArrayLength(gTx##_name##ElementHandlers)); \ if (NS_FAILED(rv)) return false #define SHUTDOWN_HANDLER(_name) \ diff --git a/dom/xslt/xslt/txXSLTNumber.cpp b/dom/xslt/xslt/txXSLTNumber.cpp index bf6d8dd725ca06..9ae449f27f44a0 100644 --- a/dom/xslt/xslt/txXSLTNumber.cpp +++ b/dom/xslt/xslt/txXSLTNumber.cpp @@ -731,7 +731,7 @@ bool txXSLTNumber::isAlphaNumeric(char16_t ch) { }; CharRange search = {ch, ch}; - const CharRange* end = std::end(alphanumericRanges); + const CharRange* end = mozilla::ArrayEnd(alphanumericRanges); const CharRange* element = std::lower_bound(&alphanumericRanges[0], end, search); if (element == end) { diff --git a/editor/libeditor/CompositionTransaction.cpp b/editor/libeditor/CompositionTransaction.cpp index 5f777325b7975f..81df0425586587 100644 --- a/editor/libeditor/CompositionTransaction.cpp +++ b/editor/libeditor/CompositionTransaction.cpp @@ -305,7 +305,7 @@ nsresult CompositionTransaction::SetIMESelection( } IgnoredErrorResult ignoredError; - for (uint32_t i = 0; i < std::size(kIMESelections); ++i) { + for (uint32_t i = 0; i < ArrayLength(kIMESelections); ++i) { RefPtr selectionOfIME = selectionController->GetSelection(kIMESelections[i]); if (!selectionOfIME) { diff --git a/editor/libeditor/EditorCommands.cpp b/editor/libeditor/EditorCommands.cpp index 7cdb1aeaa053fc..45f9e3198f727c 100644 --- a/editor/libeditor/EditorCommands.cpp +++ b/editor/libeditor/EditorCommands.cpp @@ -754,7 +754,7 @@ nsresult SelectionMoveCommands::DoCommand(Command aCommand, } // scroll commands - for (size_t i = 0; i < std::size(scrollCommands); i++) { + for (size_t i = 0; i < ArrayLength(scrollCommands); i++) { const ScrollCommand& cmd = scrollCommands[i]; if (aCommand == cmd.mReverseScroll) { return (selectionController->*(cmd.scroll))(false); @@ -765,7 +765,7 @@ nsresult SelectionMoveCommands::DoCommand(Command aCommand, } // caret movement/selection commands - for (size_t i = 0; i < std::size(moveCommands); i++) { + for (size_t i = 0; i < ArrayLength(moveCommands); i++) { const MoveCommand& cmd = moveCommands[i]; if (aCommand == cmd.mReverseMove) { return (selectionController->*(cmd.move))(false, false); @@ -782,7 +782,7 @@ nsresult SelectionMoveCommands::DoCommand(Command aCommand, } // physical-direction movement/selection - for (size_t i = 0; i < std::size(physicalCommands); i++) { + for (size_t i = 0; i < ArrayLength(physicalCommands); i++) { const PhysicalCommand& cmd = physicalCommands[i]; if (aCommand == cmd.mMove) { nsresult rv = diff --git a/editor/libeditor/HTMLEditUtils.cpp b/editor/libeditor/HTMLEditUtils.cpp index a9ac76daee901c..002852325d4552 100644 --- a/editor/libeditor/HTMLEditUtils.cpp +++ b/editor/libeditor/HTMLEditUtils.cpp @@ -1404,7 +1404,7 @@ bool HTMLEditUtils::CanNodeContain(nsHTMLTag aParentTagId, eHTMLTag_input, eHTMLTag_select, eHTMLTag_textarea}; uint32_t j; - for (j = 0; j < std::size(kButtonExcludeKids); ++j) { + for (j = 0; j < ArrayLength(kButtonExcludeKids); ++j) { if (kButtonExcludeKids[j] == aChildTagId) { return false; } diff --git a/editor/libeditor/HTMLEditorDataTransfer.cpp b/editor/libeditor/HTMLEditorDataTransfer.cpp index 1629b4d9124d4e..f27135869bcda9 100644 --- a/editor/libeditor/HTMLEditorDataTransfer.cpp +++ b/editor/libeditor/HTMLEditorDataTransfer.cpp @@ -1645,7 +1645,7 @@ nsresult HTMLEditor::ParseCFHTML(const nsCString& aCfhtml, if (endHTML == -1) { return NS_OK; } - endHTML += std::size(endFragmentMarker) - 1; + endHTML += ArrayLength(endFragmentMarker) - 1; } // create context string @@ -2734,7 +2734,7 @@ bool HTMLEditor::CanPaste(nsIClipboard::ClipboardType aClipboardType) const { // Use the flavors depending on the current editor mask if (IsPlaintextMailComposer() || editingHost->IsContentEditablePlainTextOnly()) { - AutoTArray flavors; + AutoTArray flavors; flavors.AppendElements(Span(textEditorFlavors)); bool haveFlavors; nsresult rv = clipboard->HasDataMatchingFlavors(flavors, aClipboardType, @@ -2744,7 +2744,7 @@ bool HTMLEditor::CanPaste(nsIClipboard::ClipboardType aClipboardType) const { return NS_SUCCEEDED(rv) && haveFlavors; } - AutoTArray flavors; + AutoTArray flavors; flavors.AppendElements(Span(textHtmlEditorFlavors)); bool haveFlavors; rv = clipboard->HasDataMatchingFlavors(flavors, aClipboardType, &haveFlavors); @@ -2778,10 +2778,10 @@ bool HTMLEditor::CanPasteTransferable(nsITransferable* aTransferable) { if (IsPlaintextMailComposer() || editingHost->IsContentEditablePlainTextOnly()) { flavors = textEditorFlavors; - length = std::size(textEditorFlavors); + length = ArrayLength(textEditorFlavors); } else { flavors = textHtmlEditorFlavors; - length = std::size(textHtmlEditorFlavors); + length = ArrayLength(textHtmlEditorFlavors); } for (size_t i = 0; i < length; i++, flavors++) { diff --git a/extensions/auth/nsAuthGSSAPI.cpp b/extensions/auth/nsAuthGSSAPI.cpp index bccf49d7a986d3..a5ead72d8b237c 100644 --- a/extensions/auth/nsAuthGSSAPI.cpp +++ b/extensions/auth/nsAuthGSSAPI.cpp @@ -135,7 +135,7 @@ static nsresult gssInit() { "libcom_err.so", "libkrb5.so", "libgssapi.so"}; PRLibSpec libSpec; - for (size_t i = 0; i < std::size(verLibNames); ++i) { + for (size_t i = 0; i < ArrayLength(verLibNames); ++i) { libSpec.type = PR_LibSpec_Pathname; libSpec.value.pathname = verLibNames[i]; lib = PR_LoadLibraryWithFlags(libSpec, PR_LD_GLOBAL); @@ -151,7 +151,7 @@ static nsresult gssInit() { "libgssapi.so.1" /* Heimdal - Suse9, CITI - FC, MDK, Suse10*/ }; - for (size_t i = 0; i < std::size(verLibNames) && !lib; ++i) { + for (size_t i = 0; i < ArrayLength(verLibNames) && !lib; ++i) { lib = PR_LoadLibrary(verLibNames[i]); /* The CITI libgssapi library calls exit() during @@ -168,7 +168,7 @@ static nsresult gssInit() { } } - for (size_t i = 0; i < std::size(libNames) && !lib; ++i) { + for (size_t i = 0; i < ArrayLength(libNames) && !lib; ++i) { char* libName = PR_GetLibraryName(nullptr, libNames[i]); if (libName) { lib = PR_LoadLibrary(libName); diff --git a/extensions/pref/autoconfig/src/nsReadConfig.cpp b/extensions/pref/autoconfig/src/nsReadConfig.cpp index 0d23881aa4f33e..3da68faac60093 100644 --- a/extensions/pref/autoconfig/src/nsReadConfig.cpp +++ b/extensions/pref/autoconfig/src/nsReadConfig.cpp @@ -154,8 +154,8 @@ nsresult nsReadConfig::readConfigFile() { MOZ_LOG(MCD, LogLevel::Debug, ("general.config.filename = %s\n", lockFileName.get())); - for (size_t index = 0, len = std::size(gBlockedConfigs); index < len; - ++index) { + for (size_t index = 0, len = mozilla::ArrayLength(gBlockedConfigs); + index < len; ++index) { if (lockFileName == gBlockedConfigs[index]) { // This is NS_OK because we don't want to show an error to the user return rv; diff --git a/gfx/gl/GLBlitHelper.cpp b/gfx/gl/GLBlitHelper.cpp index 86d09d4717bc6c..cbf876b08e04e5 100644 --- a/gfx/gl/GLBlitHelper.cpp +++ b/gfx/gl/GLBlitHelper.cpp @@ -724,7 +724,7 @@ GLBlitHelper::GLBlitHelper(GLContext* const gl) } \n\ "; const char* const parts[] = {mDrawBlitProg_VersionLine.get(), kVertSource}; - mGL->fShaderSource(mDrawBlitProg_VertShader, std::size(parts), parts, + mGL->fShaderSource(mDrawBlitProg_VertShader, ArrayLength(parts), parts, nullptr); mGL->fCompileShader(mDrawBlitProg_VertShader); } diff --git a/gfx/gl/GLContextFeatures.cpp b/gfx/gl/GLContextFeatures.cpp index 2ca00f74e01791..20b9f9decb3ed6 100644 --- a/gfx/gl/GLContextFeatures.cpp +++ b/gfx/gl/GLContextFeatures.cpp @@ -532,7 +532,7 @@ static const FeatureInfo sFeatureInfoArr[] = { GLContext::Extensions_End}}}; static inline const FeatureInfo& GetFeatureInfo(GLFeature feature) { - static_assert(std::size(sFeatureInfoArr) == size_t(GLFeature::EnumMax), + static_assert(MOZ_ARRAY_LENGTH(sFeatureInfoArr) == size_t(GLFeature::EnumMax), "Mismatched lengths for sFeatureInfoInfos and GLFeature enums"); MOZ_ASSERT(feature < GLFeature::EnumMax, diff --git a/gfx/gl/GLContextProviderEGL.cpp b/gfx/gl/GLContextProviderEGL.cpp index 577679789afd98..2959e10cd5b67a 100644 --- a/gfx/gl/GLContextProviderEGL.cpp +++ b/gfx/gl/GLContextProviderEGL.cpp @@ -881,7 +881,7 @@ bool CreateConfig(EglDisplay& aEgl, EGLConfig* aConfig, int32_t aDepth, bool aEnableDepthBuffer, bool aUseGles, bool aAllowFallback) { EGLConfig configs[64]; std::vector attribs; - EGLint ncfg = std::size(configs); + EGLint ncfg = ArrayLength(configs); switch (aDepth) { case 16: diff --git a/gfx/gl/GLReadTexImageHelper.cpp b/gfx/gl/GLReadTexImageHelper.cpp index 484ba34e26c75f..db30b54f02c51f 100644 --- a/gfx/gl/GLReadTexImageHelper.cpp +++ b/gfx/gl/GLReadTexImageHelper.cpp @@ -104,7 +104,7 @@ GLuint GLReadTexImageHelper::TextureImageProgramFor(GLenum aTextureTarget, } /* This might be overkill, but assure that we don't access out-of-bounds */ - MOZ_ASSERT((size_t)variant < std::size(mPrograms)); + MOZ_ASSERT((size_t)variant < ArrayLength(mPrograms)); if (!mPrograms[variant]) { GLuint vs = mGL->fCreateShader(LOCAL_GL_VERTEX_SHADER); const GLchar* vsSourcePtr = &readTextureImageVS[0]; diff --git a/gfx/layers/opengl/CompositorOGL.cpp b/gfx/layers/opengl/CompositorOGL.cpp index fd27eb7134c910..2fff7a0b493da6 100644 --- a/gfx/layers/opengl/CompositorOGL.cpp +++ b/gfx/layers/opengl/CompositorOGL.cpp @@ -422,7 +422,7 @@ bool CompositorOGL::Initialize(nsCString* const out_failureReason) { mGLContext->fGenFramebuffers(1, &testFBO); GLuint testTexture = 0; - for (uint32_t i = 0; i < std::size(textureTargets); i++) { + for (uint32_t i = 0; i < ArrayLength(textureTargets); i++) { GLenum target = textureTargets[i]; if (!target) continue; @@ -802,8 +802,8 @@ Maybe CompositorOGL::BeginFrame(const nsIntRegion& aInvalidRegion, if (regionToClear.IsEmpty() && mGLContext->IsSupported(GLFeature::invalidate_framebuffer)) { GLenum attachments[] = {LOCAL_GL_COLOR}; - mGLContext->fInvalidateFramebuffer(LOCAL_GL_FRAMEBUFFER, - std::size(attachments), attachments); + mGLContext->fInvalidateFramebuffer( + LOCAL_GL_FRAMEBUFFER, MOZ_ARRAY_LENGTH(attachments), attachments); } else { clearBits |= LOCAL_GL_COLOR_BUFFER_BIT; } diff --git a/gfx/src/DriverCrashGuard.cpp b/gfx/src/DriverCrashGuard.cpp index 6b550fb9fc8f45..c54a07b9ec9c1c 100644 --- a/gfx/src/DriverCrashGuard.cpp +++ b/gfx/src/DriverCrashGuard.cpp @@ -29,7 +29,7 @@ static const char* sCrashGuardNames[] = { "glcontext", "wmfvpxvideo", }; -static_assert(std::size(sCrashGuardNames) == NUM_CRASH_GUARD_TYPES, +static_assert(MOZ_ARRAY_LENGTH(sCrashGuardNames) == NUM_CRASH_GUARD_TYPES, "CrashGuardType updated without a name string"); static inline void BuildCrashGuardPrefName(CrashGuardType aType, diff --git a/gfx/src/FilterSupport.cpp b/gfx/src/FilterSupport.cpp index 86b45c7a7b93e3..d46de042f75b89 100644 --- a/gfx/src/FilterSupport.cpp +++ b/gfx/src/FilterSupport.cpp @@ -934,9 +934,9 @@ static already_AddRefed FilterNodeFromPrimitiveDescription( static const float allZero[4] = {0, 0, 0, 0}; filter = mDT->CreateFilter(FilterType::ARITHMETIC_COMBINE); // All-zero coefficients sometimes occur in junk filters. - if (!filter || (coefficients.Length() == std::size(allZero) && + if (!filter || (coefficients.Length() == ArrayLength(allZero) && ArrayEqual(coefficients.Elements(), allZero, - std::size(allZero)))) { + ArrayLength(allZero)))) { return nullptr; } filter->SetAttribute(ATT_ARITHMETIC_COMBINE_COEFFICIENTS, diff --git a/gfx/src/nsFont.cpp b/gfx/src/nsFont.cpp index 4fea995f089b10..6a95d738572a79 100644 --- a/gfx/src/nsFont.cpp +++ b/gfx/src/nsFont.cpp @@ -82,7 +82,8 @@ const gfxFontFeature eastAsianDefaults[] = { {TRUETYPE_TAG('p', 'w', 'i', 'd'), 1}, {TRUETYPE_TAG('r', 'u', 'b', 'y'), 1}}; -static_assert(std::size(eastAsianDefaults) == StyleFontVariantEastAsian::COUNT, +static_assert(MOZ_ARRAY_LENGTH(eastAsianDefaults) == + StyleFontVariantEastAsian::COUNT, "eastAsianDefaults[] should be correct"); // StyleFontVariantLigatures::xxx values @@ -97,7 +98,7 @@ const gfxFontFeature ligDefaults[] = { {TRUETYPE_TAG('c', 'a', 'l', 't'), 1}, {TRUETYPE_TAG('c', 'a', 'l', 't'), 0}}; -static_assert(std::size(ligDefaults) == StyleFontVariantLigatures::COUNT, +static_assert(MOZ_ARRAY_LENGTH(ligDefaults) == StyleFontVariantLigatures::COUNT, "ligDefaults[] should be correct"); // StyleFontVariantNumeric::xxx values @@ -111,7 +112,8 @@ const gfxFontFeature numericDefaults[] = { {TRUETYPE_TAG('z', 'e', 'r', 'o'), 1}, {TRUETYPE_TAG('o', 'r', 'd', 'n'), 1}}; -static_assert(std::size(numericDefaults) == StyleFontVariantNumeric::COUNT, +static_assert(MOZ_ARRAY_LENGTH(numericDefaults) == + StyleFontVariantNumeric::COUNT, "numericDefaults[] should be correct"); template diff --git a/gfx/tests/gtest/TestSkipChars.cpp b/gfx/tests/gtest/TestSkipChars.cpp index be05733a1b74b8..8f31777619042e 100644 --- a/gfx/tests/gtest/TestSkipChars.cpp +++ b/gfx/tests/gtest/TestSkipChars.cpp @@ -71,7 +71,7 @@ static bool TestIterator() { 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27}; - for (uint32_t i = 0; i < std::size(expectSkipped1); i++) { + for (uint32_t i = 0; i < mozilla::ArrayLength(expectSkipped1); i++) { EXPECT_TRUE(iter1.ConvertOriginalToSkipped(i) == expectSkipped1[i]) << "[4] Check mapping of original to skipped for " << i; } @@ -80,7 +80,7 @@ static bool TestIterator() { 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 21, 22, 23, 24, 25, 26, 27, 28}; - for (uint32_t i = 0; i < std::size(expectOriginal1); i++) { + for (uint32_t i = 0; i < mozilla::ArrayLength(expectOriginal1); i++) { EXPECT_TRUE(iter1.ConvertSkippedToOriginal(i) == expectOriginal1[i]) << "[5] Check mapping of skipped to original for " << i; } @@ -90,7 +90,8 @@ static bool TestIterator() { false, false, false, false, false, false, false, false, false, true, false, false, false, false, false, false, false, false, false}; - for (uint32_t i = 0; i < std::size(expectIsOriginalSkipped1); i++) { + for (uint32_t i = 0; i < mozilla::ArrayLength(expectIsOriginalSkipped1); + i++) { iter1.SetOriginalOffset(i); EXPECT_TRUE(iter1.IsOriginalCharSkipped() == expectIsOriginalSkipped1[i]) << "[5.a] Check IsOriginalCharSkipped for " << i; @@ -120,14 +121,14 @@ static bool TestIterator() { uint32_t expectSkipped2[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2}; - for (uint32_t i = 0; i < std::size(expectSkipped2); i++) { + for (uint32_t i = 0; i < mozilla::ArrayLength(expectSkipped2); i++) { EXPECT_TRUE(iter2.ConvertOriginalToSkipped(i) == expectSkipped2[i]) << "[9] Check mapping of original to skipped for " << i; } int32_t expectOriginal2[] = {9, 19, 29}; - for (uint32_t i = 0; i < std::size(expectOriginal2); i++) { + for (uint32_t i = 0; i < mozilla::ArrayLength(expectOriginal2); i++) { EXPECT_TRUE(iter2.ConvertSkippedToOriginal(i) == expectOriginal2[i]) << "[10] Check mapping of skipped to original for " << i; } @@ -137,7 +138,8 @@ static bool TestIterator() { true, true, true, true, true, true, true, true, true, false, true, true, true, true, true, true, true, true, true}; - for (uint32_t i = 0; i < std::size(expectIsOriginalSkipped2); i++) { + for (uint32_t i = 0; i < mozilla::ArrayLength(expectIsOriginalSkipped2); + i++) { iter2.SetOriginalOffset(i); EXPECT_TRUE(iter2.IsOriginalCharSkipped() == expectIsOriginalSkipped2[i]) << "[10.a] Check IsOriginalCharSkipped for " << i; diff --git a/gfx/thebes/CoreTextFontList.cpp b/gfx/thebes/CoreTextFontList.cpp index a38e33489709d9..e83435b638fdb2 100644 --- a/gfx/thebes/CoreTextFontList.cpp +++ b/gfx/thebes/CoreTextFontList.cpp @@ -788,7 +788,7 @@ static inline int32_t CoreTextWeightToCSSWeight(CGFloat aCTWeight) { // clang-format on }; const auto* begin = &kCoreTextToCSSWeights[0]; - const auto* end = begin + std::size(kCoreTextToCSSWeights); + const auto* end = begin + ArrayLength(kCoreTextToCSSWeights); auto m = std::upper_bound(begin, end, aCTWeight, [](CGFloat aValue, const Mapping& aMapping) { return aValue <= aMapping.first; @@ -1251,7 +1251,7 @@ void CoreTextFontList::InitSharedFontListForPlatform() { nsTArray families; families.SetCapacity(CFArrayGetCount(familyNames) #if USE_DEPRECATED_FONT_FAMILY_NAMES - + std::size(kDeprecatedFontFamilies) + + ArrayLength(kDeprecatedFontFamilies) #endif ); for (CFIndex i = 0; i < CFArrayGetCount(familyNames); ++i) { diff --git a/gfx/thebes/DeviceManagerDx.cpp b/gfx/thebes/DeviceManagerDx.cpp index 2985db25b516de..cfd1169e959ee6 100644 --- a/gfx/thebes/DeviceManagerDx.cpp +++ b/gfx/thebes/DeviceManagerDx.cpp @@ -905,7 +905,7 @@ bool DeviceManagerDx::CreateDevice(IDXGIAdapter* aAdapter, // problematic. D3D11_MESSAGE_ID blockIDs[] = { D3D11_MESSAGE_ID_DEVICE_DRAW_CONSTANT_BUFFER_TOO_SMALL}; - filter.DenyList.NumIDs = std::size(blockIDs); + filter.DenyList.NumIDs = MOZ_ARRAY_LENGTH(blockIDs); filter.DenyList.pIDList = blockIDs; infoQueue->PushStorageFilter(&filter); diff --git a/gfx/thebes/gfxASurface.cpp b/gfx/thebes/gfxASurface.cpp index bbf064098595ff..d5c78d09389082 100644 --- a/gfx/thebes/gfxASurface.cpp +++ b/gfx/thebes/gfxASurface.cpp @@ -340,7 +340,7 @@ static const SurfaceMemoryReporterAttrs sSurfaceMemoryReporterAttrs[] = { {"gfx-surface-subsurface", nullptr}, }; -static_assert(std::size(sSurfaceMemoryReporterAttrs) == +static_assert(MOZ_ARRAY_LENGTH(sSurfaceMemoryReporterAttrs) == size_t(gfxSurfaceType::Max), "sSurfaceMemoryReporterAttrs exceeds max capacity"); static_assert(uint32_t(CAIRO_SURFACE_TYPE_SKIA) == @@ -375,7 +375,7 @@ class SurfaceMemoryReporter final : public nsIMemoryReporter { NS_IMETHOD CollectReports(nsIHandleReportCallback* aHandleReport, nsISupports* aData, bool aAnonymize) override { - const size_t len = std::size(sSurfaceMemoryReporterAttrs); + const size_t len = ArrayLength(sSurfaceMemoryReporterAttrs); for (size_t i = 0; i < len; i++) { int64_t amount = sSurfaceMemoryUsed[i]; diff --git a/gfx/thebes/gfxCoreTextShaper.cpp b/gfx/thebes/gfxCoreTextShaper.cpp index ad0d000f137903..c0a1c83875f9cb 100644 --- a/gfx/thebes/gfxCoreTextShaper.cpp +++ b/gfx/thebes/gfxCoreTextShaper.cpp @@ -39,7 +39,7 @@ CFDictionaryRef gfxCoreTextShaper::CreateAttrDict(bool aRightToLeft) { CFTypeRef attrs[] = {kCTFontAttributeName, kCTWritingDirectionAttributeName}; CFTypeRef values[] = {mCTFont[0], dirArray}; CFDictionaryRef attrDict = ::CFDictionaryCreate( - kCFAllocatorDefault, attrs, values, std::size(attrs), + kCFAllocatorDefault, attrs, values, ArrayLength(attrs), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); ::CFRelease(dirArray); return attrDict; @@ -571,7 +571,7 @@ CTFontDescriptorRef gfxCoreTextShaper::CreateFontFeaturesDescriptor( CFTypeRef values[] = {type, selector}; featureSettings[i] = ::CFDictionaryCreate( kCFAllocatorDefault, (const void**)keys, (const void**)values, - std::size(keys), &kCFTypeDictionaryKeyCallBacks, + ArrayLength(keys), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); ::CFRelease(selector); @@ -580,7 +580,7 @@ CTFontDescriptorRef gfxCoreTextShaper::CreateFontFeaturesDescriptor( CFArrayRef featuresArray = ::CFArrayCreate(kCFAllocatorDefault, (const void**)featureSettings, - aCount, // not std::size(featureSettings), as we + aCount, // not ArrayLength(featureSettings), as we // may not have used all the allocated slots &kCFTypeArrayCallBacks); @@ -592,7 +592,7 @@ CTFontDescriptorRef gfxCoreTextShaper::CreateFontFeaturesDescriptor( const CFTypeRef attrValues[] = {featuresArray}; CFDictionaryRef attributesDict = ::CFDictionaryCreate( kCFAllocatorDefault, (const void**)attrKeys, (const void**)attrValues, - std::size(attrKeys), &kCFTypeDictionaryKeyCallBacks, + ArrayLength(attrKeys), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); ::CFRelease(featuresArray); diff --git a/gfx/thebes/gfxDWriteFontList.cpp b/gfx/thebes/gfxDWriteFontList.cpp index 38ee6678e5f934..6de30f023cccdc 100644 --- a/gfx/thebes/gfxDWriteFontList.cpp +++ b/gfx/thebes/gfxDWriteFontList.cpp @@ -1162,9 +1162,9 @@ nsTArray> gfxDWriteFontList::GetFilteredPlatformFontLists() { nsTArray> fontLists; - fontLists.AppendElement(std::make_pair(kBaseFonts, std::size(kBaseFonts))); + fontLists.AppendElement(std::make_pair(kBaseFonts, ArrayLength(kBaseFonts))); fontLists.AppendElement( - std::make_pair(kLangPackFonts, std::size(kLangPackFonts))); + std::make_pair(kLangPackFonts, ArrayLength(kLangPackFonts))); return fontLists; } @@ -1966,7 +1966,7 @@ nsresult gfxDWriteFontList::GetFontSubstitutes() { for (i = 0, rv = ERROR_SUCCESS; rv != ERROR_NO_MORE_ITEMS; i++) { aliasName[0] = 0; - lenAlias = std::size(aliasName); + lenAlias = ArrayLength(aliasName); actualName[0] = 0; lenActual = sizeof(actualName); rv = RegEnumValueW(hKey, i, aliasName, &lenAlias, nullptr, &valueType, @@ -2035,7 +2035,7 @@ static const FontSubstitution sDirectWriteSubs[] = { {"Script", "Mistral"}}; void gfxDWriteFontList::GetDirectWriteSubstitutes() { - for (uint32_t i = 0; i < std::size(sDirectWriteSubs); ++i) { + for (uint32_t i = 0; i < ArrayLength(sDirectWriteSubs); ++i) { const FontSubstitution& sub(sDirectWriteSubs[i]); nsAutoCString substituteName(sub.aliasName); BuildKeyNameFromFontName(substituteName); diff --git a/gfx/thebes/gfxFT2FontList.cpp b/gfx/thebes/gfxFT2FontList.cpp index 9c9811213ea871..1d5550badb895d 100644 --- a/gfx/thebes/gfxFT2FontList.cpp +++ b/gfx/thebes/gfxFT2FontList.cpp @@ -317,7 +317,7 @@ static void SetPropertiesFromFace(gfxFontEntry* aFontEntry, const OS2Table* os2 = reinterpret_cast(data); os2weight = os2->usWeightClass; uint16_t os2width = os2->usWidthClass; - if (os2width < std::size(kOS2WidthToStretch)) { + if (os2width < ArrayLength(kOS2WidthToStretch)) { stretch = kOS2WidthToStretch[os2width]; } } @@ -1254,7 +1254,7 @@ void gfxFT2FontList::FindFontsInOmnijar(FontNameCache* aCache) { "res/fonts/*.ttf$", }; RefPtr reader = Omnijar::GetReader(Omnijar::Type::GRE); - for (unsigned i = 0; i < std::size(sJarSearchPaths); i++) { + for (unsigned i = 0; i < ArrayLength(sJarSearchPaths); i++) { nsZipFind* find; if (NS_SUCCEEDED(reader->FindInit(sJarSearchPaths[i], &find))) { const char* path; @@ -1353,24 +1353,25 @@ gfxFT2FontList::GetFilteredPlatformFontLists() { } fontLists.AppendElement( - std::make_pair(kBaseFonts_Android, std::size(kBaseFonts_Android))); + std::make_pair(kBaseFonts_Android, ArrayLength(kBaseFonts_Android))); if (fontVisibilityDevice == Device::Android_sub_9) { fontLists.AppendElement(std::make_pair(kBaseFonts_Android5_8, - std::size(kBaseFonts_Android5_8))); + ArrayLength(kBaseFonts_Android5_8))); } else { fontLists.AppendElement(std::make_pair( - kBaseFonts_Android9_Higher, std::size(kBaseFonts_Android9_Higher))); + kBaseFonts_Android9_Higher, ArrayLength(kBaseFonts_Android9_Higher))); if (fontVisibilityDevice == Device::Android_9_11) { fontLists.AppendElement(std::make_pair( - kBaseFonts_Android9_11, std::size(kBaseFonts_Android9_11))); + kBaseFonts_Android9_11, ArrayLength(kBaseFonts_Android9_11))); } else { - fontLists.AppendElement(std::make_pair( - kBaseFonts_Android12_Higher, std::size(kBaseFonts_Android12_Higher))); + fontLists.AppendElement( + std::make_pair(kBaseFonts_Android12_Higher, + ArrayLength(kBaseFonts_Android12_Higher))); fontLists.AppendElement( std::make_pair(kLangPack_MFR_Android12_Higher, - std::size(kLangPack_MFR_Android12_Higher))); + ArrayLength(kLangPack_MFR_Android12_Higher))); } } @@ -1712,7 +1713,7 @@ void gfxFT2FontList::FindFontsInDir(const nsCString& aDir, if (strcasecmp(ext, ".ttf") == 0 || strcasecmp(ext, ".otf") == 0 || strcasecmp(ext, ".woff") == 0 || strcasecmp(ext, ".ttc") == 0) { bool isStdFont = false; - for (unsigned int i = 0; i < std::size(sStandardFonts) && !isStdFont; + for (unsigned int i = 0; i < ArrayLength(sStandardFonts) && !isStdFont; i++) { isStdFont = strcmp(sStandardFonts[i], ent->d_name) == 0; } diff --git a/gfx/thebes/gfxFcPlatformFontList.cpp b/gfx/thebes/gfxFcPlatformFontList.cpp index 6839d40ed986af..30c202d6eea22f 100644 --- a/gfx/thebes/gfxFcPlatformFontList.cpp +++ b/gfx/thebes/gfxFcPlatformFontList.cpp @@ -2058,29 +2058,29 @@ gfxFcPlatformFontList::GetFilteredPlatformFontLists() { case Device::Linux_Ubuntu_any: case Device::Linux_Ubuntu_22: fontLists.AppendElement(std::make_pair( - kBaseFonts_Ubuntu_22_04, std::size(kBaseFonts_Ubuntu_22_04))); + kBaseFonts_Ubuntu_22_04, ArrayLength(kBaseFonts_Ubuntu_22_04))); fontLists.AppendElement(std::make_pair( - kLangFonts_Ubuntu_22_04, std::size(kLangFonts_Ubuntu_22_04))); + kLangFonts_Ubuntu_22_04, ArrayLength(kLangFonts_Ubuntu_22_04))); // For Ubuntu_any, we fall through to also check the 20_04 lists. [[fallthrough]]; case Device::Linux_Ubuntu_20: fontLists.AppendElement(std::make_pair( - kBaseFonts_Ubuntu_20_04, std::size(kBaseFonts_Ubuntu_20_04))); + kBaseFonts_Ubuntu_20_04, ArrayLength(kBaseFonts_Ubuntu_20_04))); fontLists.AppendElement(std::make_pair( - kLangFonts_Ubuntu_20_04, std::size(kLangFonts_Ubuntu_20_04))); + kLangFonts_Ubuntu_20_04, ArrayLength(kLangFonts_Ubuntu_20_04))); break; case Device::Linux_Fedora_any: case Device::Linux_Fedora_39: - fontLists.AppendElement(std::make_pair(kBaseFonts_Fedora_39, - std::size(kBaseFonts_Fedora_39))); + fontLists.AppendElement(std::make_pair( + kBaseFonts_Fedora_39, ArrayLength(kBaseFonts_Fedora_39))); // For Fedora_any, fall through to also check Fedora 38 list. [[fallthrough]]; case Device::Linux_Fedora_38: - fontLists.AppendElement(std::make_pair(kBaseFonts_Fedora_38, - std::size(kBaseFonts_Fedora_38))); + fontLists.AppendElement(std::make_pair( + kBaseFonts_Fedora_38, ArrayLength(kBaseFonts_Fedora_38))); break; default: @@ -2794,7 +2794,7 @@ void gfxFcPlatformFontList::GetSampleLangForGroup( const MozLangGroupData* mozLangGroup = nullptr; // -- look it up in the list of moz lang groups - for (unsigned int i = 0; i < std::size(MozLangGroups); ++i) { + for (unsigned int i = 0; i < ArrayLength(MozLangGroups); ++i) { if (aLanguage == MozLangGroups[i].mozLangGroup) { mozLangGroup = &MozLangGroups[i]; break; diff --git a/gfx/thebes/gfxFont.cpp b/gfx/thebes/gfxFont.cpp index 4661bc986bfad7..6399ef6739477a 100644 --- a/gfx/thebes/gfxFont.cpp +++ b/gfx/thebes/gfxFont.cpp @@ -1136,14 +1136,14 @@ static void CollectLookupsByFeature(hb_face_t* aFace, hb_tag_t aTableTag, offset = 0; do { - len = std::size(lookups); + len = ArrayLength(lookups); hb_ot_layout_feature_get_lookups(aFace, aTableTag, aFeatureIndex, offset, &len, lookups); for (i = 0; i < len; i++) { hb_set_add(aLookups, lookups[i]); } offset += len; - } while (len == std::size(lookups)); + } while (len == ArrayLength(lookups)); } static void CollectLookupsByLanguage( @@ -1162,7 +1162,7 @@ static void CollectLookupsByLanguage( offset = 0; do { - len = std::size(featureIndexes); + len = ArrayLength(featureIndexes); hb_ot_layout_language_get_feature_indexes(aFace, aTableTag, aScriptIndex, aLangIndex, offset, &len, featureIndexes); @@ -1184,7 +1184,7 @@ static void CollectLookupsByLanguage( CollectLookupsByFeature(aFace, aTableTag, featureIndex, lookups); } offset += len; - } while (len == std::size(featureIndexes)); + } while (len == ArrayLength(featureIndexes)); } static bool HasLookupRuleWithGlyphByScript( @@ -1389,7 +1389,7 @@ void gfxFont::CheckForFeaturesInvolvingSpace() const { // Set up the default-features hashset on first use. if (!sDefaultFeatures) { - uint32_t numDefaultFeatures = std::size(defaultFeatures); + uint32_t numDefaultFeatures = ArrayLength(defaultFeatures); auto* set = new nsTHashSet(numDefaultFeatures); for (uint32_t i = 0; i < numDefaultFeatures; i++) { set->Insert(defaultFeatures[i]); @@ -1404,7 +1404,7 @@ void gfxFont::CheckForFeaturesInvolvingSpace() const { uint32_t len, offset = 0; do { - len = std::size(scriptTags); + len = ArrayLength(scriptTags); hb_ot_layout_table_get_script_tags(face, HB_OT_TAG_GSUB, offset, &len, scriptTags); for (uint32_t i = 0; i < len; i++) { @@ -1426,7 +1426,7 @@ void gfxFont::CheckForFeaturesInvolvingSpace() const { } } offset += len; - } while (len == std::size(scriptTags)); + } while (len == ArrayLength(scriptTags)); } // spaces in default features of default script? diff --git a/gfx/thebes/gfxFontUtils.cpp b/gfx/thebes/gfxFontUtils.cpp index a1146e8e3df0de..46f33f4696cd52 100644 --- a/gfx/thebes/gfxFontUtils.cpp +++ b/gfx/thebes/gfxFontUtils.cpp @@ -1026,7 +1026,7 @@ nsresult gfxFontUtils::RenameFont(const nsAString& aName, NAME_ID_POSTSCRIPT}; // calculate new name table size - uint16_t nameCount = std::size(neededNameIDs); + uint16_t nameCount = ArrayLength(neededNameIDs); // leave room for null-terminator uint32_t nameStrLength = (aName.Length() + 1) * sizeof(char16_t); @@ -1380,7 +1380,7 @@ const Encoding* gfxFontUtils::GetCharsetForFontName(uint16_t aPlatform, for (uint32_t i = 0; i < 2; ++i) { size_t idx; if (BinarySearchIf(gMacFontNameCharsets, 0, - std::size(gMacFontNameCharsets), + ArrayLength(gMacFontNameCharsets), MacCharsetMappingComparator(searchValue), &idx)) { return gMacFontNameCharsets[idx].mEncoding; } @@ -1391,13 +1391,13 @@ const Encoding* gfxFontUtils::GetCharsetForFontName(uint16_t aPlatform, } break; case PLATFORM_ID_ISO: - if (aScript < std::size(gISOFontNameCharsets)) { + if (aScript < ArrayLength(gISOFontNameCharsets)) { return gISOFontNameCharsets[aScript]; } break; case PLATFORM_ID_MICROSOFT: - if (aScript < std::size(gMSFontNameCharsets)) { + if (aScript < ArrayLength(gMSFontNameCharsets)) { return gMSFontNameCharsets[aScript]; } break; diff --git a/gfx/thebes/gfxGDIFontList.cpp b/gfx/thebes/gfxGDIFontList.cpp index efddf769c3bed3..4dca4506c0ac61 100644 --- a/gfx/thebes/gfxGDIFontList.cpp +++ b/gfx/thebes/gfxGDIFontList.cpp @@ -543,7 +543,7 @@ nsresult gfxGDIFontList::GetFontSubstitutes() { for (i = 0, rv = ERROR_SUCCESS; rv != ERROR_NO_MORE_ITEMS; i++) { aliasName[0] = 0; - lenAlias = std::size(aliasName); + lenAlias = ArrayLength(aliasName); actualName[0] = 0; lenActual = sizeof(actualName); rv = RegEnumValueW(hKey, i, aliasName, &lenAlias, nullptr, &valueType, diff --git a/gfx/thebes/gfxGraphiteShaper.cpp b/gfx/thebes/gfxGraphiteShaper.cpp index 8fbab4ccaea564..4b9b33c455ed4d 100644 --- a/gfx/thebes/gfxGraphiteShaper.cpp +++ b/gfx/thebes/gfxGraphiteShaper.cpp @@ -487,7 +487,7 @@ uint32_t gfxGraphiteShaper::GetGraphiteTagForLang(const nsCString& aLang) { if (!sLanguageTags) { // store the registered IANA tags in a hash for convenient validation - sLanguageTags = new nsTHashSet(std::size(sLanguageTagList)); + sLanguageTags = new nsTHashSet(ArrayLength(sLanguageTagList)); for (const uint32_t* tag = sLanguageTagList; *tag != 0; ++tag) { sLanguageTags->Insert(*tag); } diff --git a/gfx/thebes/gfxHarfBuzzShaper.cpp b/gfx/thebes/gfxHarfBuzzShaper.cpp index bc94f3df69c5b3..18bc08a6bf2c85 100644 --- a/gfx/thebes/gfxHarfBuzzShaper.cpp +++ b/gfx/thebes/gfxHarfBuzzShaper.cpp @@ -288,7 +288,7 @@ hb_codepoint_t gfxHarfBuzzShaper::GetVerticalPresentationForm( {0xff5d, 0xfe38} // FULLWIDTH RIGHT CURLY BRACKET }; const uint16_t* charPair = static_cast( - bsearch(&aUnicode, sVerticalForms, std::size(sVerticalForms), + bsearch(&aUnicode, sVerticalForms, ArrayLength(sVerticalForms), sizeof(sVerticalForms[0]), VertFormsGlyphCompare)); return charPair ? charPair[1] : 0; } diff --git a/gfx/thebes/gfxMacPlatformFontList.mm b/gfx/thebes/gfxMacPlatformFontList.mm index 0a813191991a09..6d2a6666df10db 100644 --- a/gfx/thebes/gfxMacPlatformFontList.mm +++ b/gfx/thebes/gfxMacPlatformFontList.mm @@ -182,7 +182,7 @@ void FindStyleVariationsLocked(FontInfoData* aFontInfoData = nullptr) gfxMacPlatformFontList::GetFilteredPlatformFontLists() { nsTArray> fontLists; - fontLists.AppendElement(std::make_pair(kBaseFonts, std::size(kBaseFonts))); + fontLists.AppendElement(std::make_pair(kBaseFonts, ArrayLength(kBaseFonts))); return fontLists; } diff --git a/gfx/thebes/gfxMathTable.cpp b/gfx/thebes/gfxMathTable.cpp index 29b1cc71d99341..6a27efff21d932 100644 --- a/gfx/thebes/gfxMathTable.cpp +++ b/gfx/thebes/gfxMathTable.cpp @@ -110,10 +110,11 @@ void gfxMathTable::UpdateMathVariantCache(uint32_t aGlyphID, // stored from top to bottom in nsMathMLChar. hb_ot_math_glyph_part_t parts[5]; - count = std::size(parts); + count = MOZ_ARRAY_LENGTH(parts); unsigned int offset = 0; if (hb_ot_math_get_glyph_assembly(mHBFont, aGlyphID, direction, offset, - &count, parts, NULL) > std::size(parts)) + &count, parts, + NULL) > MOZ_ARRAY_LENGTH(parts)) return; // Not supported: Too many pieces. if (count <= 0) return; // Not supported: No pieces. diff --git a/gfx/thebes/gfxPlatformFontList.cpp b/gfx/thebes/gfxPlatformFontList.cpp index 554e4e347c27f6..e2161f92b5dcd8 100644 --- a/gfx/thebes/gfxPlatformFontList.cpp +++ b/gfx/thebes/gfxPlatformFontList.cpp @@ -172,7 +172,7 @@ static const char* gPrefLangNames[] = { #undef FONT_PREF_LANG }; -static_assert(std::size(gPrefLangNames) == uint32_t(eFontPrefLang_Count), +static_assert(MOZ_ARRAY_LENGTH(gPrefLangNames) == uint32_t(eFontPrefLang_Count), "size of pref lang name array doesn't match pref lang enum size"); class gfxFontListPrefObserver final : public nsIObserver { @@ -329,8 +329,8 @@ gfxPlatformFontList::gfxPlatformFontList(bool aNeedFullnamePostscriptNames) RegisterStrongMemoryReporter(new MemoryReporter()); // initialize lang group pref font defaults (i.e. serif/sans-serif) - mDefaultGenericsLangGroup.AppendElements(std::size(gPrefLangNames)); - for (uint32_t i = 0; i < std::size(gPrefLangNames); i++) { + mDefaultGenericsLangGroup.AppendElements(ArrayLength(gPrefLangNames)); + for (uint32_t i = 0; i < ArrayLength(gPrefLangNames); i++) { nsAutoCString prefDefaultFontType("font.default."); prefDefaultFontType.Append(GetPrefLangName(eFontPrefLang(i))); nsAutoCString serifOrSans; @@ -2203,7 +2203,7 @@ static nsAtom* PrefLangToLangGroups(uint32_t aIndex) { #undef FONT_PREF_LANG }; - return aIndex < std::size(gPrefLangToLangGroups) + return aIndex < ArrayLength(gPrefLangToLangGroups) ? gPrefLangToLangGroups[aIndex] : nsGkAtoms::Unicode; } @@ -2212,7 +2212,7 @@ eFontPrefLang gfxPlatformFontList::GetFontPrefLangFor(const char* aLang) { if (!aLang || !aLang[0]) { return eFontPrefLang_Others; } - for (uint32_t i = 0; i < std::size(gPrefLangNames); ++i) { + for (uint32_t i = 0; i < ArrayLength(gPrefLangNames); ++i) { if (!nsCRT::strcasecmp(gPrefLangNames[i], aLang)) { return eFontPrefLang(i); } @@ -2242,7 +2242,7 @@ nsAtom* gfxPlatformFontList::GetLangGroupForPrefLang(eFontPrefLang aLang) { } const char* gfxPlatformFontList::GetPrefLangName(eFontPrefLang aLang) { - if (uint32_t(aLang) < std::size(gPrefLangNames)) { + if (uint32_t(aLang) < ArrayLength(gPrefLangNames)) { return gPrefLangNames[uint32_t(aLang)]; } return nullptr; @@ -2560,7 +2560,7 @@ StyleGenericFontFamily gfxPlatformFontList::GetDefaultGeneric( AutoLock lock(mLock); - if (uint32_t(aLang) < std::size(gPrefLangNames)) { + if (uint32_t(aLang) < ArrayLength(gPrefLangNames)) { return mDefaultGenericsLangGroup[uint32_t(aLang)]; } return StyleGenericFontFamily::Serif; diff --git a/gfx/thebes/gfxTextRun.cpp b/gfx/thebes/gfxTextRun.cpp index 1af311deec4bc7..e49a1ec3b2f040 100644 --- a/gfx/thebes/gfxTextRun.cpp +++ b/gfx/thebes/gfxTextRun.cpp @@ -2928,9 +2928,9 @@ gfxTextRun* gfxFontGroup::GetEllipsisTextRun( RefPtr firstFont = GetFirstValidFont(); nsString ellipsis = firstFont->HasCharacter(kEllipsisChar[0]) - ? nsDependentString(kEllipsisChar, std::size(kEllipsisChar) - 1) + ? nsDependentString(kEllipsisChar, ArrayLength(kEllipsisChar) - 1) : nsDependentString(kASCIIPeriodsChar, - std::size(kASCIIPeriodsChar) - 1); + ArrayLength(kASCIIPeriodsChar) - 1); RefPtr refDT = aRefDrawTargetGetter.GetRefDrawTarget(); Parameters params = {refDT, nullptr, nullptr, diff --git a/gfx/thebes/gfxUserFontSet.cpp b/gfx/thebes/gfxUserFontSet.cpp index cd1787d19318ef..f36d1286801b3e 100644 --- a/gfx/thebes/gfxUserFontSet.cpp +++ b/gfx/thebes/gfxUserFontSet.cpp @@ -299,7 +299,7 @@ void gfxUserFontEntry::GetFamilyNameAndURIForLogging(uint32_t aSrcIndex, if (aURI.Length() > kMaxURILengthForLogging) { aURI.Replace(kMaxURILengthForLogging / 2, aURI.Length() - kMaxURILengthForLogging, kEllipsis, - std::size(kEllipsis)); + ArrayLength(kEllipsis)); } } else { aURI.AppendLiteral("(invalid URI)"); diff --git a/gfx/vr/VRManager.cpp b/gfx/vr/VRManager.cpp index 6acc73a5b4b265..32296dfeaab113 100644 --- a/gfx/vr/VRManager.cpp +++ b/gfx/vr/VRManager.cpp @@ -861,7 +861,7 @@ void VRManager::StopAllHaptics() { if (mState != VRManagerState::Active) { return; } - for (size_t i = 0; i < std::size(mBrowserState.hapticState); i++) { + for (size_t i = 0; i < mozilla::ArrayLength(mBrowserState.hapticState); i++) { ClearHapticSlot(i); } PushState(); @@ -886,7 +886,7 @@ void VRManager::VibrateHaptic(GamepadHandle aGamepadHandle, TimeStamp now = TimeStamp::Now(); size_t bestSlotIndex = 0; // Default to an empty slot, or the slot holding the oldest haptic pulse - for (size_t i = 0; i < std::size(mBrowserState.hapticState); i++) { + for (size_t i = 0; i < mozilla::ArrayLength(mBrowserState.hapticState); i++) { const VRHapticState& state = mBrowserState.hapticState[i]; if (state.inputFrameID == 0) { // Unused slot, use it @@ -900,7 +900,7 @@ void VRManager::VibrateHaptic(GamepadHandle aGamepadHandle, } } // Override the last pulse on the same actuator if present. - for (size_t i = 0; i < std::size(mBrowserState.hapticState); i++) { + for (size_t i = 0; i < mozilla::ArrayLength(mBrowserState.hapticState); i++) { const VRHapticState& state = mBrowserState.hapticState[i]; if (state.inputFrameID == 0) { // This is an empty slot -- no match @@ -949,7 +949,7 @@ void VRManager::StopVibrateHaptic(GamepadHandle aGamepadHandle) { kVRControllerMaxCount * mDisplayInfo.mDisplayID; uint32_t controllerIndex = aGamepadHandle.GetValue() - controllerBaseIndex; - for (size_t i = 0; i < std::size(mBrowserState.hapticState); i++) { + for (size_t i = 0; i < mozilla::ArrayLength(mBrowserState.hapticState); i++) { VRHapticState& state = mBrowserState.hapticState[i]; if (state.controllerIndex == controllerIndex) { memset(&state, 0, sizeof(VRHapticState)); @@ -1198,7 +1198,7 @@ void VRManager::UpdateHaptics(double aDeltaTime) { } bool bNeedPush = false; // Check for any haptic pulses that have ended and clear them - for (size_t i = 0; i < std::size(mBrowserState.hapticState); i++) { + for (size_t i = 0; i < mozilla::ArrayLength(mBrowserState.hapticState); i++) { const VRHapticState& state = mBrowserState.hapticState[i]; if (state.inputFrameID == 0) { // Nothing in this slot @@ -1217,7 +1217,7 @@ void VRManager::UpdateHaptics(double aDeltaTime) { } void VRManager::ClearHapticSlot(size_t aSlot) { - MOZ_ASSERT(aSlot < std::size(mBrowserState.hapticState)); + MOZ_ASSERT(aSlot < mozilla::ArrayLength(mBrowserState.hapticState)); memset(&mBrowserState.hapticState[aSlot], 0, sizeof(VRHapticState)); mHapticPulseRemaining[aSlot] = 0.0f; if (aSlot < mHapticPromises.Length() && mHapticPromises[aSlot]) { @@ -1269,7 +1269,7 @@ void VRManager::StopPresentation() { // Indicate that we have stopped immersive mode mBrowserState.presentationActive = false; memset(mBrowserState.layerState, 0, - sizeof(VRLayerState) * std::size(mBrowserState.layerState)); + sizeof(VRLayerState) * mozilla::ArrayLength(mBrowserState.layerState)); PushState(true); diff --git a/gfx/vr/service/VRService.cpp b/gfx/vr/service/VRService.cpp index 23934e0a448cbb..2b774c25319a96 100644 --- a/gfx/vr/service/VRService.cpp +++ b/gfx/vr/service/VRService.cpp @@ -356,7 +356,7 @@ void VRService::ServiceImmersiveMode() { mSession->StartFrame(mSystemState); mSystemState.sensorState.inputFrameID++; size_t historyIndex = - mSystemState.sensorState.inputFrameID % std::size(mFrameStartTime); + mSystemState.sensorState.inputFrameID % ArrayLength(mFrameStartTime); mFrameStartTime[historyIndex] = TimeStamp::Now(); PushState(mSystemState); } @@ -371,7 +371,7 @@ void VRService::UpdateHaptics() { MOZ_ASSERT(IsInServiceThread()); MOZ_ASSERT(mSession); - for (size_t i = 0; i < std::size(mBrowserState.hapticState); i++) { + for (size_t i = 0; i < ArrayLength(mBrowserState.hapticState); i++) { VRHapticState& state = mBrowserState.hapticState[i]; VRHapticState& lastState = mLastHapticState[i]; // Note that VRHapticState is asserted to be a POD type, thus memcmp is safe @@ -391,7 +391,7 @@ void VRService::UpdateHaptics() { now = TimeStamp::Now(); } // This is a new haptic pulse, or we are overriding a prior one - size_t historyIndex = state.inputFrameID % std::size(mFrameStartTime); + size_t historyIndex = state.inputFrameID % ArrayLength(mFrameStartTime); float startOffset = (float)(now - mFrameStartTime[historyIndex]).ToSeconds(); diff --git a/image/decoders/icon/nsIconURI.cpp b/image/decoders/icon/nsIconURI.cpp index 1a5611ce338f40..1136cb9584c78e 100644 --- a/image/decoders/icon/nsIconURI.cpp +++ b/image/decoders/icon/nsIconURI.cpp @@ -230,7 +230,7 @@ nsresult nsMozIconURI::SetSpecInternal(const nsACString& aSpec) { extractAttributeValue(iconSpec.get(), "size=", sizeString); if (!sizeString.IsEmpty()) { const char* sizeStr = sizeString.get(); - for (uint32_t i = 0; i < std::size(kSizeStrings); i++) { + for (uint32_t i = 0; i < ArrayLength(kSizeStrings); i++) { if (nsCRT::strcasecmp(sizeStr, kSizeStrings[i]) == 0) { mIconSize = i; break; @@ -247,7 +247,7 @@ nsresult nsMozIconURI::SetSpecInternal(const nsACString& aSpec) { extractAttributeValue(iconSpec.get(), "state=", stateString); if (!stateString.IsEmpty()) { const char* stateStr = stateString.get(); - for (uint32_t i = 0; i < std::size(kStateStrings); i++) { + for (uint32_t i = 0; i < ArrayLength(kStateStrings); i++) { if (nsCRT::strcasecmp(stateStr, kStateStrings[i]) == 0) { mIconState = i; break; @@ -613,13 +613,13 @@ bool nsMozIconURI::Deserialize(const URIParams& aParams) { mStockIcon = params.stockIcon(); if (params.iconSize() < -1 || - params.iconSize() >= (int32_t)std::size(kSizeStrings)) { + params.iconSize() >= (int32_t)ArrayLength(kSizeStrings)) { return false; } mIconSize = params.iconSize(); if (params.iconState() < -1 || - params.iconState() >= (int32_t)std::size(kStateStrings)) { + params.iconState() >= (int32_t)ArrayLength(kStateStrings)) { return false; } mIconState = params.iconState(); diff --git a/image/decoders/icon/win/nsIconChannel.cpp b/image/decoders/icon/win/nsIconChannel.cpp index 4489709f1bb2c9..b8ddcd89045004 100644 --- a/image/decoders/icon/win/nsIconChannel.cpp +++ b/image/decoders/icon/win/nsIconChannel.cpp @@ -190,7 +190,7 @@ static bool GetSpecialFolderIcon(nsIFile* aFile, int aFolder, UINT aInfoFlags, nsAutoString fileNativePathStr; aFile->GetPath(fileNativePathStr); ::GetShortPathNameW(fileNativePathStr.get(), fileNativePath, - std::size(fileNativePath)); + ArrayLength(fileNativePath)); struct IdListDeleter { void operator()(ITEMIDLIST* ptr) { ::CoTaskMemFree(ptr); } @@ -206,7 +206,7 @@ static bool GetSpecialFolderIcon(nsIFile* aFile, int aFolder, UINT aInfoFlags, wchar_t specialNativePath[MAX_PATH]; ::SHGetPathFromIDListW(idList.get(), specialNativePath); ::GetShortPathNameW(specialNativePath, specialNativePath, - std::size(specialNativePath)); + ArrayLength(specialNativePath)); if (wcsicmp(fileNativePath, specialNativePath) != 0) { return false; diff --git a/intl/locale/nsLanguageAtomService.cpp b/intl/locale/nsLanguageAtomService.cpp index b0ca91c8c82d19..6c57fb8743bc1e 100644 --- a/intl/locale/nsLanguageAtomService.cpp +++ b/intl/locale/nsLanguageAtomService.cpp @@ -110,7 +110,7 @@ already_AddRefed nsLanguageAtomService::LookupCharSet( aEncoding->Name(charset); nsAutoCString group; if (NS_FAILED(nsUConvPropertySearch::SearchPropertyValue( - encodingsGroups, std::size(encodingsGroups), charset, group))) { + encodingsGroups, ArrayLength(encodingsGroups), charset, group))) { return RefPtr(nsGkAtoms::Unicode).forget(); } return NS_Atomize(group); @@ -223,7 +223,7 @@ nsStaticAtom* nsLanguageAtomService::GetUncachedLanguageGroup( Span scriptAsSpan = loc.Script().Span(); nsDependentCSubstring script(scriptAsSpan.data(), scriptAsSpan.size()); if (BinarySearchIf( - kScriptLangGroup, 0, std::size(kScriptLangGroup), + kScriptLangGroup, 0, ArrayLength(kScriptLangGroup), [script](const auto& entry) -> int { return Compare(script, nsDependentCString(entry.mTag)); }, diff --git a/intl/locale/tests/gtest/TestOSPreferences.cpp b/intl/locale/tests/gtest/TestOSPreferences.cpp index 6307edddc21eaf..7e3b71582b1206 100644 --- a/intl/locale/tests/gtest/TestOSPreferences.cpp +++ b/intl/locale/tests/gtest/TestOSPreferences.cpp @@ -71,7 +71,7 @@ TEST(Intl_Locale_OSPreferences, GetDateTimePattern) {4, 1, ""}, {3, 2, "cs"}, {2, 3, ""}, {1, 4, "ja"}}; - for (unsigned i = 0; i < std::size(tests); i++) { + for (unsigned i = 0; i < mozilla::ArrayLength(tests); i++) { const Test& t = tests[i]; if (NS_SUCCEEDED(osprefs->GetDateTimePattern( t.dateStyle, t.timeStyle, nsDependentCString(t.locale), pattern))) { diff --git a/intl/lwbrk/LineBreaker.cpp b/intl/lwbrk/LineBreaker.cpp index 5fe44dc2c7d88c..d2cac2d9be7b44 100644 --- a/intl/lwbrk/LineBreaker.cpp +++ b/intl/lwbrk/LineBreaker.cpp @@ -452,11 +452,11 @@ static int8_t GetClass(uint32_t u, LineBreakRule aLevel, /* E_MODIFIER = 41, [EM] */ CLASS_CHARACTER, /* ZWJ = 42, [ZWJ]*/ CLASS_CHARACTER}; - static_assert(U_LB_COUNT == std::size(sUnicodeLineBreakToClass), + static_assert(U_LB_COUNT == mozilla::ArrayLength(sUnicodeLineBreakToClass), "Gecko vs ICU LineBreak class mismatch"); auto cls = GetLineBreakClass(u); - MOZ_ASSERT(cls < std::size(sUnicodeLineBreakToClass)); + MOZ_ASSERT(cls < mozilla::ArrayLength(sUnicodeLineBreakToClass)); // Overrides based on rules for the different line-break values given in // https://drafts.csswg.org/css-text-3/#line-break-property diff --git a/intl/strres/nsStringBundle.cpp b/intl/strres/nsStringBundle.cpp index 3fc8219029130d..969a65ec8b55c1 100644 --- a/intl/strres/nsStringBundle.cpp +++ b/intl/strres/nsStringBundle.cpp @@ -84,7 +84,7 @@ static const char kContentBundles[][52] = { static bool IsContentBundle(const nsCString& aUrl) { size_t index; return BinarySearchIf( - kContentBundles, 0, std::size(kContentBundles), + kContentBundles, 0, MOZ_ARRAY_LENGTH(kContentBundles), [&](const char* aElem) { return Compare(aUrl, nsDependentCString(aElem)); }, diff --git a/intl/unicharutil/tools/genSpecialCasingData.pl b/intl/unicharutil/tools/genSpecialCasingData.pl index 609202a599bbd7..98006886839920 100755 --- a/intl/unicharutil/tools/genSpecialCasingData.pl +++ b/intl/unicharutil/tools/genSpecialCasingData.pl @@ -112,7 +112,7 @@ Special##which(uint32_t aChar) \\ { \\ const void* p = bsearch(&aChar, CaseSpecials_##which, \\ - std::size(CaseSpecials_##which), \\ + mozilla::ArrayLength(CaseSpecials_##which), \\ sizeof(MultiCharMapping), CompareMCM); \\ return static_cast(p); \\ } diff --git a/intl/unicharutil/util/nsSpecialCasingData.cpp b/intl/unicharutil/util/nsSpecialCasingData.cpp index 06593eb99db8b4..9908406a3593f7 100644 --- a/intl/unicharutil/util/nsSpecialCasingData.cpp +++ b/intl/unicharutil/util/nsSpecialCasingData.cpp @@ -186,7 +186,7 @@ static int CompareMCM(const void* aKey, const void* aElement) Special##which(uint32_t aChar) \ { \ const void* p = bsearch(&aChar, CaseSpecials_##which, \ - std::size(CaseSpecials_##which), \ + mozilla::ArrayLength(CaseSpecials_##which), \ sizeof(MultiCharMapping), CompareMCM); \ return static_cast(p); \ } diff --git a/intl/unicharutil/util/nsUnicodeProperties.cpp b/intl/unicharutil/util/nsUnicodeProperties.cpp index bc9d95aaf33526..7960e76cd81d24 100644 --- a/intl/unicharutil/util/nsUnicodeProperties.cpp +++ b/intl/unicharutil/util/nsUnicodeProperties.cpp @@ -190,7 +190,7 @@ uint32_t CountGraphemeClusters(Span aText) { uint32_t GetNaked(uint32_t aCh) { uint32_t index = aCh >> 8; - if (index >= std::size(BASE_CHAR_MAPPING_BLOCK_INDEX)) { + if (index >= MOZ_ARRAY_LENGTH(BASE_CHAR_MAPPING_BLOCK_INDEX)) { return aCh; } index = BASE_CHAR_MAPPING_BLOCK_INDEX[index]; diff --git a/ipc/glue/IPCMessageUtilsSpecializations.h b/ipc/glue/IPCMessageUtilsSpecializations.h index 6bf58afd292a2a..ec0620d0572d16 100644 --- a/ipc/glue/IPCMessageUtilsSpecializations.h +++ b/ipc/glue/IPCMessageUtilsSpecializations.h @@ -351,7 +351,7 @@ struct ParamTraits { WriteParam(aWriter, aParam.m0); WriteParam(aWriter, aParam.m1); WriteParam(aWriter, aParam.m2); - for (unsigned int i = 0; i < std::size(aParam.m3); i++) { + for (unsigned int i = 0; i < mozilla::ArrayLength(aParam.m3); i++) { WriteParam(aWriter, aParam.m3[i]); } } @@ -362,7 +362,7 @@ struct ParamTraits { !ReadParam(aReader, &(aResult->m2))) return false; - for (unsigned int i = 0; i < std::size(aResult->m3); i++) + for (unsigned int i = 0; i < mozilla::ArrayLength(aResult->m3); i++) if (!ReadParam(aReader, &(aResult->m3[i]))) return false; return true; diff --git a/ipc/glue/URIUtils.cpp b/ipc/glue/URIUtils.cpp index 62e4d07a7241bb..690509ceccbd28 100644 --- a/ipc/glue/URIUtils.cpp +++ b/ipc/glue/URIUtils.cpp @@ -25,6 +25,7 @@ #include "nsIURIMutator.h" using namespace mozilla::ipc; +using mozilla::ArrayLength; namespace { diff --git a/ipc/glue/WindowsMessageLoop.cpp b/ipc/glue/WindowsMessageLoop.cpp index a222c01a7bbaf7..0c7ca6977c9b13 100644 --- a/ipc/glue/WindowsMessageLoop.cpp +++ b/ipc/glue/WindowsMessageLoop.cpp @@ -133,8 +133,8 @@ void CALLBACK WinEventHook(HWINEVENTHOOK aWinEventHook, DWORD aEvent, return; } wchar_t classBuf[256] = {0}; - int result = ::GetClassNameW(aHwnd, classBuf, std::size(classBuf)); - if (result != (std::size(kCOMWindowClassName) - 1) || + int result = ::GetClassNameW(aHwnd, classBuf, MOZ_ARRAY_LENGTH(classBuf)); + if (result != (MOZ_ARRAY_LENGTH(kCOMWindowClassName) - 1) || wcsncmp(kCOMWindowClassName, classBuf, result)) { // Not a class we're interested in return; diff --git a/ipc/mscom/Utils.cpp b/ipc/mscom/Utils.cpp index 679f4921d632c5..d93e012587e941 100644 --- a/ipc/mscom/Utils.cpp +++ b/ipc/mscom/Utils.cpp @@ -144,8 +144,9 @@ long BuildRegGuidPath(REFGUID aGuid, const GuidType aGuidType, wchar_t* aBuf, // We exclude null terminators in these length calculations because we include // the stringified GUID's null terminator at the end. Since kClsid and kAppid // have identical lengths, we just choose one to compute this length. - constexpr size_t kSubkeyBaseLen = std::size(kSubkeyBase) - 1; - constexpr size_t kSubkeyLen = kSubkeyBaseLen + std::size(kClsid) - 1; + constexpr size_t kSubkeyBaseLen = mozilla::ArrayLength(kSubkeyBase) - 1; + constexpr size_t kSubkeyLen = + kSubkeyBaseLen + mozilla::ArrayLength(kClsid) - 1; // Guid length as formatted for the registry (including curlies and dashes), // but excluding null terminator. constexpr size_t kGuidLen = kGuidRegFormatCharLenInclNul - 1; @@ -312,7 +313,8 @@ void DiagnosticNameForIID(REFIID aIid, nsACString& aOutString) { void GUIDToString(REFGUID aGuid, wchar_t (&aOutBuf)[kGuidRegFormatCharLenInclNul]) { - DebugOnly result = ::StringFromGUID2(aGuid, aOutBuf, std::size(aOutBuf)); + DebugOnly result = + ::StringFromGUID2(aGuid, aOutBuf, ArrayLength(aOutBuf)); MOZ_ASSERT(result); } diff --git a/js/src/jit/JitcodeMap.cpp b/js/src/jit/JitcodeMap.cpp index ff73baa3dbdbf2..505da8474c2935 100644 --- a/js/src/jit/JitcodeMap.cpp +++ b/js/src/jit/JitcodeMap.cpp @@ -1132,7 +1132,7 @@ JS_PUBLIC_API JS::ProfiledFrameRange JS::GetProfiledFrames(JSContext* cx, if (entry) { result.depth_ = entry->callStackAtAddr(rt, addr, result.labels_, - std::size(result.labels_)); + MOZ_ARRAY_LENGTH(result.labels_)); } return result; } diff --git a/js/src/shell/OSObject.cpp b/js/src/shell/OSObject.cpp index cd01252504ad13..12375b33deb4b8 100644 --- a/js/src/shell/OSObject.cpp +++ b/js/src/shell/OSObject.cpp @@ -999,14 +999,14 @@ UniqueChars SystemErrorMessage(JSContext* cx, int errnum) { #if defined(XP_WIN) wchar_t buffer[200]; const wchar_t* errstr = buffer; - if (_wcserror_s(buffer, std::size(buffer), errnum) != 0) { + if (_wcserror_s(buffer, mozilla::ArrayLength(buffer), errnum) != 0) { errstr = L"unknown error"; } return JS::EncodeWideToUtf8(cx, errstr); #else char buffer[200]; - const char* errstr = - strerror_message(strerror_r(errno, buffer, std::size(buffer)), buffer); + const char* errstr = strerror_message( + strerror_r(errno, buffer, mozilla::ArrayLength(buffer)), buffer); if (!errstr) { errstr = "unknown error"; } diff --git a/js/src/vm/GeckoProfiler.cpp b/js/src/vm/GeckoProfiler.cpp index 328e3c73ce122a..c5b294bd0b73aa 100644 --- a/js/src/vm/GeckoProfiler.cpp +++ b/js/src/vm/GeckoProfiler.cpp @@ -547,7 +547,7 @@ const ProfilingCategoryPairInfo sProfilingCategoryPairInfo[] = { JS_PUBLIC_API const ProfilingCategoryPairInfo& GetProfilingCategoryPairInfo( ProfilingCategoryPair aCategoryPair) { static_assert( - std::size(sProfilingCategoryPairInfo) == + MOZ_ARRAY_LENGTH(sProfilingCategoryPairInfo) == uint32_t(ProfilingCategoryPair::COUNT), "sProfilingCategoryPairInfo and ProfilingCategory need to have the " "same order and the same length"); diff --git a/js/src/vm/JSFunction.cpp b/js/src/vm/JSFunction.cpp index 9e6dfa3510bab8..aa50a3ad83ffc1 100644 --- a/js/src/vm/JSFunction.cpp +++ b/js/src/vm/JSFunction.cpp @@ -10,7 +10,7 @@ #include "vm/JSFunction-inl.h" -#include "mozilla/ArrayUtils.h" +#include "mozilla/ArrayUtils.h" // mozilla::ArrayLength #include "mozilla/Maybe.h" #include "mozilla/Range.h" diff --git a/js/xpconnect/loader/mozJSModuleLoader.cpp b/js/xpconnect/loader/mozJSModuleLoader.cpp index 8aaa4a5201dcf2..1773dc69881484 100644 --- a/js/xpconnect/loader/mozJSModuleLoader.cpp +++ b/js/xpconnect/loader/mozJSModuleLoader.cpp @@ -7,9 +7,9 @@ #include "ScriptLoadRequest.h" #include "mozilla/Assertions.h" // MOZ_ASSERT, MOZ_ASSERT_IF #include "mozilla/Attributes.h" -#include "mozilla/ArrayUtils.h" -#include "mozilla/RefPtr.h" // RefPtr, mozilla::StaticRefPtr -#include "mozilla/Utf8.h" // mozilla::Utf8Unit +#include "mozilla/ArrayUtils.h" // mozilla::ArrayLength +#include "mozilla/RefPtr.h" // RefPtr, mozilla::StaticRefPtr +#include "mozilla/Utf8.h" // mozilla::Utf8Unit #include @@ -113,13 +113,14 @@ static LazyLogModule gJSCLLog("JSModuleLoader"); "%s - Symbol '%s' accessed before initialization. Cyclic import?" static constexpr char JSM_Suffix[] = ".jsm"; -static constexpr size_t JSM_SuffixLength = std::size(JSM_Suffix) - 1; +static constexpr size_t JSM_SuffixLength = mozilla::ArrayLength(JSM_Suffix) - 1; static constexpr char JSM_JS_Suffix[] = ".jsm.js"; -static constexpr size_t JSM_JS_SuffixLength = std::size(JSM_JS_Suffix) - 1; +static constexpr size_t JSM_JS_SuffixLength = + mozilla::ArrayLength(JSM_JS_Suffix) - 1; static constexpr char JS_Suffix[] = ".js"; -static constexpr size_t JS_SuffixLength = std::size(JS_Suffix) - 1; +static constexpr size_t JS_SuffixLength = mozilla::ArrayLength(JS_Suffix) - 1; static constexpr char MJS_Suffix[] = ".sys.mjs"; -static constexpr size_t MJS_SuffixLength = std::size(MJS_Suffix) - 1; +static constexpr size_t MJS_SuffixLength = mozilla::ArrayLength(MJS_Suffix) - 1; static bool IsJSM(const nsACString& aLocation) { if (aLocation.Length() < JSM_SuffixLength) { diff --git a/js/xpconnect/wrappers/FilteringWrapper.cpp b/js/xpconnect/wrappers/FilteringWrapper.cpp index 390725fc4339bd..f4812e04ba8241 100644 --- a/js/xpconnect/wrappers/FilteringWrapper.cpp +++ b/js/xpconnect/wrappers/FilteringWrapper.cpp @@ -63,8 +63,9 @@ bool AppendCrossOriginWhitelistedPropNames(JSContext* cx, MOZ_ASSERT(!props[n].isSymbol(), "Unexpected existing symbol-name prop"); } #endif - if (!props.reserve(props.length() + - std::size(sCrossOriginWhitelistedSymbolCodes))) { + if (!props.reserve( + props.length() + + mozilla::ArrayLength(sCrossOriginWhitelistedSymbolCodes))) { return false; } diff --git a/layout/base/PresShell.cpp b/layout/base/PresShell.cpp index 54f1e4f24812d2..1352ca2200928c 100644 --- a/layout/base/PresShell.cpp +++ b/layout/base/PresShell.cpp @@ -11026,7 +11026,7 @@ void ReflowCountMgr::DoGrandHTMLTotals() { static const char* title[] = {"Class", "Reflows"}; fprintf(mFD, ""); - for (uint32_t i = 0; i < std::size(title); i++) { + for (uint32_t i = 0; i < ArrayLength(title); i++) { fprintf(mFD, "
%s
", title[i]); } fprintf(mFD, "\n"); diff --git a/layout/base/RestyleManager.cpp b/layout/base/RestyleManager.cpp index accf0f60e2460c..b4700300f02a61 100644 --- a/layout/base/RestyleManager.cpp +++ b/layout/base/RestyleManager.cpp @@ -694,11 +694,12 @@ nsCString RestyleManager::ChangeHintToString(nsChangeHint aHint) { "UpdateTableCellSpans", "VisibilityChange"}; static_assert(nsChangeHint_AllHints == - static_cast((1ull << std::size(names)) - 1), + static_cast((1ull << ArrayLength(names)) - 1), "Name list doesn't match change hints."); - uint32_t hint = aHint & static_cast((1ull << std::size(names)) - 1); + uint32_t hint = + aHint & static_cast((1ull << ArrayLength(names)) - 1); uint32_t rest = - aHint & ~static_cast((1ull << std::size(names)) - 1); + aHint & ~static_cast((1ull << ArrayLength(names)) - 1); if ((hint & NS_STYLE_HINT_REFLOW) == NS_STYLE_HINT_REFLOW) { result.AppendLiteral("NS_STYLE_HINT_REFLOW"); hint = hint & ~NS_STYLE_HINT_REFLOW; @@ -713,7 +714,7 @@ nsCString RestyleManager::ChangeHintToString(nsChangeHint aHint) { hint = hint & ~NS_STYLE_HINT_VISUAL; any = true; } - for (uint32_t i = 0; i < std::size(names); i++) { + for (uint32_t i = 0; i < ArrayLength(names); i++) { if (hint & (1u << i)) { if (any) { result.AppendLiteral(" | "); diff --git a/layout/base/StaticPresData.cpp b/layout/base/StaticPresData.cpp index 9727f06803841c..4307528e0bbae6 100644 --- a/layout/base/StaticPresData.cpp +++ b/layout/base/StaticPresData.cpp @@ -117,7 +117,7 @@ void LangGroupFontPrefs::Initialize(nsStaticAtom* aLangGroupAtom) { &mDefaultSystemUiFont, }; // clang-format on - static_assert(std::size(fontTypes) == size_t(DefaultFont::COUNT), + static_assert(MOZ_ARRAY_LENGTH(fontTypes) == size_t(DefaultFont::COUNT), "FontTypes array count is not correct"); // Get attributes specific to each generic font. We do not get the user's diff --git a/layout/base/nsCSSFrameConstructor.cpp b/layout/base/nsCSSFrameConstructor.cpp index c7265e5224cbab..e1dfd73da6d4ee 100644 --- a/layout/base/nsCSSFrameConstructor.cpp +++ b/layout/base/nsCSSFrameConstructor.cpp @@ -3487,7 +3487,7 @@ nsCSSFrameConstructor::FindHTMLData(const Element& aElement, SIMPLE_TAG_CHAIN(details, nsCSSFrameConstructor::FindDetailsData), }; - return FindDataByTag(aElement, aStyle, sHTMLData, std::size(sHTMLData)); + return FindDataByTag(aElement, aStyle, sHTMLData, ArrayLength(sHTMLData)); } /* static */ @@ -3610,7 +3610,7 @@ nsCSSFrameConstructor::FindInputData(const Element& aElement, } return FindDataByInt(int32_t(controlType), aElement, aStyle, sInputData, - std::size(sInputData)); + ArrayLength(sInputData)); } /* static */ @@ -3636,7 +3636,7 @@ nsCSSFrameConstructor::FindObjectData(const Element& aElement, }; return FindDataByInt((int32_t)type, aElement, aStyle, sObjectData, - std::size(sObjectData)); + ArrayLength(sObjectData)); } /* static */ @@ -4132,7 +4132,7 @@ nsCSSFrameConstructor::FindXULTagData(const Element& aElement, {nsGkAtoms::tooltip, kPopupData}, }; - return FindDataByTag(aElement, aStyle, sXULTagData, std::size(sXULTagData)); + return FindDataByTag(aElement, aStyle, sXULTagData, ArrayLength(sXULTagData)); } /* static */ @@ -4638,7 +4638,7 @@ nsCSSFrameConstructor::FindMathMLData(const Element& aElement, SIMPLE_MATHML_CREATE(menclose_, NS_NewMathMLmencloseFrame), SIMPLE_MATHML_CREATE(semantics_, NS_NewMathMLmrowFrame)}; - return FindDataByTag(aElement, aStyle, sMathMLData, std::size(sMathMLData)); + return FindDataByTag(aElement, aStyle, sMathMLData, ArrayLength(sMathMLData)); } nsContainerFrame* nsCSSFrameConstructor::ConstructFrameWithAnonymousChild( @@ -4945,7 +4945,7 @@ nsCSSFrameConstructor::FindSVGData(const Element& aElement, SIMPLE_SVG_CREATE(feTurbulence, NS_NewSVGFELeafFrame)}; const FrameConstructionData* data = - FindDataByTag(aElement, aStyle, sSVGData, std::size(sSVGData)); + FindDataByTag(aElement, aStyle, sSVGData, ArrayLength(sSVGData)); if (!data) { data = &sContainerData; diff --git a/layout/base/nsLayoutUtils.h b/layout/base/nsLayoutUtils.h index 8166b063958066..b218b66c974e16 100644 --- a/layout/base/nsLayoutUtils.h +++ b/layout/base/nsLayoutUtils.h @@ -1784,11 +1784,11 @@ class nsLayoutUtils { mozilla::StyleBorderStyle aBorderStyle) { if (aBorderStyle == mozilla::StyleBorderStyle::Dotted) { static Float dot[] = {1.f, 1.f}; - aStrokeOptions.mDashLength = std::size(dot); + aStrokeOptions.mDashLength = MOZ_ARRAY_LENGTH(dot); aStrokeOptions.mDashPattern = dot; } else if (aBorderStyle == mozilla::StyleBorderStyle::Dashed) { static Float dash[] = {5.f, 5.f}; - aStrokeOptions.mDashLength = std::size(dash); + aStrokeOptions.mDashLength = MOZ_ARRAY_LENGTH(dash); aStrokeOptions.mDashPattern = dash; } else { aStrokeOptions.mDashLength = 0; diff --git a/layout/base/nsPresArena.cpp b/layout/base/nsPresArena.cpp index 6a54e730bf8e3e..c93da58179609e 100644 --- a/layout/base/nsPresArena.cpp +++ b/layout/base/nsPresArena.cpp @@ -25,7 +25,7 @@ using namespace mozilla; template nsPresArena::~nsPresArena() { #if defined(MOZ_HAVE_MEM_CHECKS) - for (FreeList* entry = mFreeLists; entry != std::end(mFreeLists); ++entry) { + for (FreeList* entry = mFreeLists; entry != ArrayEnd(mFreeLists); ++entry) { for (void* result : entry->mEntries) { MOZ_MAKE_MEM_UNDEFINED(result, entry->mEntrySize); } @@ -39,7 +39,7 @@ void* nsPresArena::Allocate(ObjectId aCode, size_t aSize) { MOZ_ASSERT(NS_IsMainThread()); MOZ_ASSERT(aSize > 0, "PresArena cannot allocate zero bytes"); - MOZ_ASSERT(size_t(aCode) < std::size(mFreeLists)); + MOZ_ASSERT(size_t(aCode) < ArrayLength(mFreeLists)); // We only hand out aligned sizes aSize = mPool.AlignedSize(aSize); @@ -103,7 +103,7 @@ template void nsPresArena::Free(ObjectId aCode, void* aPtr) { MOZ_ASSERT(NS_IsMainThread()); - MOZ_ASSERT(size_t(aCode) < std::size(mFreeLists)); + MOZ_ASSERT(size_t(aCode) < ArrayLength(mFreeLists)); // Try to recycle this entry. FreeList* list = &mFreeLists[size_t(aCode)]; @@ -132,7 +132,7 @@ void nsPresArena::AddSizeOfExcludingThis( size_t mallocSize = mPool.SizeOfExcludingThis(aSizes.mState.mMallocSizeOf); size_t totalSizeInFreeLists = 0; - for (const FreeList* entry = mFreeLists; entry != std::end(mFreeLists); + for (const FreeList* entry = mFreeLists; entry != ArrayEnd(mFreeLists); ++entry) { mallocSize += entry->SizeOfExcludingThis(aSizes.mState.mMallocSizeOf); diff --git a/layout/base/nsPresContext.h b/layout/base/nsPresContext.h index a7171436607445..470985f1717a50 100644 --- a/layout/base/nsPresContext.h +++ b/layout/base/nsPresContext.h @@ -885,7 +885,8 @@ class nsPresContext : public nsISupports, public mozilla::SupportsWeakPtr { // to actual nscoord values. static const nscoord kBorderWidths[] = { CSSPixelsToAppUnits(1), CSSPixelsToAppUnits(3), CSSPixelsToAppUnits(5)}; - MOZ_ASSERT(size_t(aBorderWidthKeyword) < std::size(kBorderWidths)); + MOZ_ASSERT(size_t(aBorderWidthKeyword) < + mozilla::ArrayLength(kBorderWidths)); return kBorderWidths[aBorderWidthKeyword]; } diff --git a/layout/base/nsRefreshDriver.cpp b/layout/base/nsRefreshDriver.cpp index b22f0f08854354..e40312f5b0de05 100644 --- a/layout/base/nsRefreshDriver.cpp +++ b/layout/base/nsRefreshDriver.cpp @@ -2555,7 +2555,7 @@ void nsRefreshDriver::CancelIdleTask(Task* aTask) { } bool nsRefreshDriver::TickObserverArray(uint32_t aIdx, TimeStamp aNowTime) { - MOZ_ASSERT(aIdx < std::size(mObservers)); + MOZ_ASSERT(aIdx < ArrayLength(mObservers)); for (RefPtr obs : mObservers[aIdx].EndLimitedRange()) { obs->WillRefresh(aNowTime); diff --git a/layout/generic/MathMLTextRunFactory.cpp b/layout/generic/MathMLTextRunFactory.cpp index 51cf1374c8fb01..e5c959d6c5078c 100644 --- a/layout/generic/MathMLTextRunFactory.cpp +++ b/layout/generic/MathMLTextRunFactory.cpp @@ -366,23 +366,23 @@ static uint32_t MathvarMappingSearch(uint32_t aKey, */ case StyleMathVariant::Initial: mapTable = gArabicInitialMapTable; - tableLength = std::size(gArabicInitialMapTable); + tableLength = ArrayLength(gArabicInitialMapTable); break; case StyleMathVariant::Tailed: mapTable = gArabicTailedMapTable; - tableLength = std::size(gArabicTailedMapTable); + tableLength = ArrayLength(gArabicTailedMapTable); break; case StyleMathVariant::Stretched: mapTable = gArabicStretchedMapTable; - tableLength = std::size(gArabicStretchedMapTable); + tableLength = ArrayLength(gArabicStretchedMapTable); break; case StyleMathVariant::Looped: mapTable = gArabicLoopedMapTable; - tableLength = std::size(gArabicLoopedMapTable); + tableLength = ArrayLength(gArabicLoopedMapTable); break; case StyleMathVariant::DoubleStruck: mapTable = gArabicDoubleMapTable; - tableLength = std::size(gArabicDoubleMapTable); + tableLength = ArrayLength(gArabicDoubleMapTable); break; default: // No valid transformations exist @@ -407,7 +407,7 @@ static uint32_t MathvarMappingSearch(uint32_t aKey, // mathematical block, so the spaces where they ought to be are used // as keys for a lookup table containing the correct character mappings. newChar = MathvarMappingSearch(tempChar, gLatinExceptionMapTable, - std::size(gLatinExceptionMapTable)); + ArrayLength(gLatinExceptionMapTable)); } if (newChar) { diff --git a/layout/generic/TextOverflow.cpp b/layout/generic/TextOverflow.cpp index 744b2340ca97a4..8b789a6e84426b 100644 --- a/layout/generic/TextOverflow.cpp +++ b/layout/generic/TextOverflow.cpp @@ -750,7 +750,7 @@ void TextOverflow::ProcessLine(const nsDisplayListSet& aLists, nsLineBox* aLine, // Clip and remove display items as needed at the final marker edges. nsDisplayList* lists[] = {aLists.Content(), aLists.PositionedDescendants()}; - for (uint32_t i = 0; i < std::size(lists); ++i) { + for (uint32_t i = 0; i < ArrayLength(lists); ++i) { PruneDisplayListContents(lists[i], framesToHide, insideMarkersArea); } CreateMarkers(aLine, needIStart, needIEnd, insideMarkersArea, contentArea, diff --git a/layout/generic/nsBlockFrame.cpp b/layout/generic/nsBlockFrame.cpp index 3775f1eae5d668..6bf576356ff203 100644 --- a/layout/generic/nsBlockFrame.cpp +++ b/layout/generic/nsBlockFrame.cpp @@ -8797,7 +8797,7 @@ void nsBlockFrame::VerifyOverflowSituation() { // |this|. Later next-in-flows must have the same or later parents. ChildListID childLists[] = {FrameChildListID::Float, FrameChildListID::PushedFloats}; - for (size_t i = 0; i < std::size(childLists); ++i) { + for (size_t i = 0; i < ArrayLength(childLists); ++i) { const nsFrameList& children = GetChildList(childLists[i]); for (nsIFrame* f : children) { nsIFrame* parent = this; diff --git a/layout/generic/nsFrameSelection.cpp b/layout/generic/nsFrameSelection.cpp index bf2317d1c617fe..c1d2e1c7040882 100644 --- a/layout/generic/nsFrameSelection.cpp +++ b/layout/generic/nsFrameSelection.cpp @@ -365,7 +365,7 @@ nsFrameSelection::CreateRangeExtendedToSomewhere( nsFrameSelection::nsFrameSelection(PresShell* aPresShell, nsIContent* aLimiter, const bool aAccessibleCaretEnabled) { - for (size_t i = 0; i < std::size(mDomSelections); i++) { + for (size_t i = 0; i < ArrayLength(mDomSelections); i++) { mDomSelections[i] = new Selection(kPresentSelectionTypes[i], this); } @@ -400,7 +400,7 @@ nsFrameSelection::~nsFrameSelection() = default; NS_IMPL_CYCLE_COLLECTION_CLASS(nsFrameSelection) NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsFrameSelection) - for (size_t i = 0; i < std::size(tmp->mDomSelections); ++i) { + for (size_t i = 0; i < ArrayLength(tmp->mDomSelections); ++i) { tmp->mDomSelections[i] = nullptr; } tmp->mHighlightSelections.Clear(); @@ -423,7 +423,7 @@ NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(nsFrameSelection) cb, tmp->mPresShell->GetDocument()->GetMarkedCCGeneration())) { return NS_SUCCESS_INTERRUPTED_TRAVERSE; } - for (size_t i = 0; i < std::size(tmp->mDomSelections); ++i) { + for (size_t i = 0; i < ArrayLength(tmp->mDomSelections); ++i) { NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mDomSelections[i]) } @@ -1504,7 +1504,7 @@ UniquePtr nsFrameSelection::LookUpSelection( UniquePtr details; - for (size_t j = 0; j < std::size(mDomSelections); j++) { + for (size_t j = 0; j < ArrayLength(mDomSelections); j++) { if (mDomSelections[j]) { details = mDomSelections[j]->LookUpSelection( aContent, static_cast(aContentOffset), @@ -3044,7 +3044,7 @@ void nsFrameSelection::DisconnectFromPresShell() { } StopAutoScrollTimer(); - for (size_t i = 0; i < std::size(mDomSelections); i++) { + for (size_t i = 0; i < ArrayLength(mDomSelections); i++) { mDomSelections[i]->Clear(nullptr); } mPresShell = nullptr; diff --git a/layout/generic/nsGridContainerFrame.cpp b/layout/generic/nsGridContainerFrame.cpp index f2cc3f1a6afb22..b017ecf0733c71 100644 --- a/layout/generic/nsGridContainerFrame.cpp +++ b/layout/generic/nsGridContainerFrame.cpp @@ -8702,7 +8702,7 @@ nscoord nsGridContainerFrame::MasonryLayout(GridReflowInput& aState, {BaselineAlignmentSet::LastItems, BaselineAlignmentSet::StartStretch}, {BaselineAlignmentSet::LastItems, BaselineAlignmentSet::EndStretch}, }; - for (uint32_t i = 0; i < std::size(baselineSets); ++i) { + for (uint32_t i = 0; i < ArrayLength(baselineSets); ++i) { if (i == 0 && didAlignStartAlignedFirstItems) { continue; } diff --git a/layout/generic/nsIFrame.h b/layout/generic/nsIFrame.h index e71ac9d94d2dd8..faed339ef55132 100644 --- a/layout/generic/nsIFrame.h +++ b/layout/generic/nsIFrame.h @@ -3463,7 +3463,7 @@ class nsIFrame : public nsQueryFrame { * @see mozilla::LayoutFrameType */ mozilla::LayoutFrameType Type() const { - MOZ_ASSERT(uint8_t(mClass) < std::size(sLayoutFrameTypes)); + MOZ_ASSERT(uint8_t(mClass) < mozilla::ArrayLength(sLayoutFrameTypes)); return sLayoutFrameTypes[uint8_t(mClass)]; } @@ -3476,7 +3476,7 @@ class nsIFrame : public nsQueryFrame { * @see mozilla::LayoutFrameType */ ClassFlags GetClassFlags() const { - MOZ_ASSERT(uint8_t(mClass) < std::size(sLayoutFrameClassFlags)); + MOZ_ASSERT(uint8_t(mClass) < mozilla::ArrayLength(sLayoutFrameClassFlags)); return sLayoutFrameClassFlags[uint8_t(mClass)]; } diff --git a/layout/generic/nsPageFrame.cpp b/layout/generic/nsPageFrame.cpp index 020fd0b7f50764..8185bb62960f1b 100644 --- a/layout/generic/nsPageFrame.cpp +++ b/layout/generic/nsPageFrame.cpp @@ -498,7 +498,7 @@ static void PaintMarginGuides(nsIFrame* aFrame, DrawTarget* aDrawTarget, JoinStyle::MITER_OR_BEVEL, CapStyle::BUTT, /* mitre limit (default, not used) */ 10.0f, /* set dash pattern of 2px stroke, 2px gap */ - std::size(dashes), dashes, + ArrayLength(dashes), dashes, /* dash offset */ 0.0f); DrawOptions options; diff --git a/layout/generic/nsPageSequenceFrame.cpp b/layout/generic/nsPageSequenceFrame.cpp index fe886d8c54c2a1..2b19438693ca6d 100644 --- a/layout/generic/nsPageSequenceFrame.cpp +++ b/layout/generic/nsPageSequenceFrame.cpp @@ -64,7 +64,7 @@ static const nsPagesPerSheetInfo kSupportedPagesPerSheet[] = { inline void SanityCheckPagesPerSheetInfo() { #ifdef DEBUG // Sanity-checks: - MOZ_ASSERT(std::size(kSupportedPagesPerSheet) > 0, + MOZ_ASSERT(ArrayLength(kSupportedPagesPerSheet) > 0, "Should have at least one pages-per-sheet option."); MOZ_ASSERT(kSupportedPagesPerSheet[0].mNumPages == 1, "The 0th index is reserved for default 1-page-per-sheet entry"); diff --git a/layout/generic/nsTextFrame.cpp b/layout/generic/nsTextFrame.cpp index 27564a026f649e..c483f7a4b1b58a 100644 --- a/layout/generic/nsTextFrame.cpp +++ b/layout/generic/nsTextFrame.cpp @@ -6496,7 +6496,7 @@ bool nsTextFrame::PaintTextWithSelection( MOZ_ASSERT(kPresentSelectionTypes[0] == SelectionType::eNormal, "The following for loop assumes that the first item of " "kPresentSelectionTypes is SelectionType::eNormal"); - for (size_t i = std::size(kPresentSelectionTypes) - 1; i >= 1; --i) { + for (size_t i = ArrayLength(kPresentSelectionTypes) - 1; i >= 1; --i) { SelectionType selectionType = kPresentSelectionTypes[i]; if (ToSelectionTypeMask(selectionType) & allSelectionTypeMask) { // There is some selection of this selectionType. Try to paint its diff --git a/layout/generic/nsTextRunTransformations.cpp b/layout/generic/nsTextRunTransformations.cpp index 6954e13a362d05..140223815b7a92 100644 --- a/layout/generic/nsTextRunTransformations.cpp +++ b/layout/generic/nsTextRunTransformations.cpp @@ -832,7 +832,7 @@ bool nsCaseTransformTextRunFactory::TransformString( // clang-format on size_t index; - const uint16_t len = std::size(kSmallKanas); + const uint16_t len = MOZ_ARRAY_LENGTH(kSmallKanas); if (mozilla::BinarySearch(kSmallKanas, 0, len, ch, &index)) { ch = kFullSizeKanas[index]; } diff --git a/layout/painting/nsCSSRendering.cpp b/layout/painting/nsCSSRendering.cpp index 6757b1892d05d6..27d37b954c6ecc 100644 --- a/layout/painting/nsCSSRendering.cpp +++ b/layout/painting/nsCSSRendering.cpp @@ -3285,7 +3285,7 @@ static void DrawDashedSegment(DrawTarget& aDrawTarget, nsRect aRect, dash[1] = dash[0]; strokeOptions.mDashPattern = dash; - strokeOptions.mDashLength = std::size(dash); + strokeOptions.mDashLength = MOZ_ARRAY_LENGTH(dash); if (aHorizontal) { nsPoint left = (aRect.TopLeft() + aRect.BottomLeft()) / 2; @@ -4251,7 +4251,7 @@ void nsCSSRendering::PaintDecorationLineInternal( dash[0] = dashWidth; dash[1] = dashWidth; strokeOptions.mDashPattern = dash; - strokeOptions.mDashLength = std::size(dash); + strokeOptions.mDashLength = MOZ_ARRAY_LENGTH(dash); strokeOptions.mLineCap = CapStyle::BUTT; aRect = ExpandPaintingRectForDecorationLine( aFrame, aParams.style, aRect, aParams.icoordInFrame, dashWidth * 2, @@ -4272,7 +4272,7 @@ void nsCSSRendering::PaintDecorationLineInternal( dash[1] = dashWidth; } strokeOptions.mDashPattern = dash; - strokeOptions.mDashLength = std::size(dash); + strokeOptions.mDashLength = MOZ_ARRAY_LENGTH(dash); aRect = ExpandPaintingRectForDecorationLine( aFrame, aParams.style, aRect, aParams.icoordInFrame, dashWidth * 2, aParams.vertical); diff --git a/layout/style/CounterStyleManager.cpp b/layout/style/CounterStyleManager.cpp index 4e22d10ee5e87a..ae6d1616e1d5eb 100644 --- a/layout/style/CounterStyleManager.cpp +++ b/layout/style/CounterStyleManager.cpp @@ -1821,7 +1821,7 @@ CounterStyle* CounterStyleManager::ResolveCounterStyle(nsAtom* aName) { /* static */ CounterStyle* CounterStyleManager::GetBuiltinStyle(ListStyle aStyle) { - MOZ_ASSERT(size_t(aStyle) < std::size(gBuiltinStyleTable), + MOZ_ASSERT(size_t(aStyle) < ArrayLength(gBuiltinStyleTable), "Require a valid builtin style constant"); MOZ_ASSERT(!gBuiltinStyleTable[size_t(aStyle)].IsDependentStyle(), "Cannot get dependent builtin style"); diff --git a/layout/style/nsCSSPropertyIDSet.h b/layout/style/nsCSSPropertyIDSet.h index 8b852db25c1556..44236767b1d894 100644 --- a/layout/style/nsCSSPropertyIDSet.h +++ b/layout/style/nsCSSPropertyIDSet.h @@ -114,7 +114,7 @@ class nsCSSPropertyIDSet { } bool Intersects(const nsCSSPropertyIDSet& aOther) const { - for (size_t i = 0; i < std::size(mProperties); ++i) { + for (size_t i = 0; i < mozilla::ArrayLength(mProperties); ++i) { if (mProperties[i] & aOther.mProperties[i]) { return true; } @@ -125,7 +125,7 @@ class nsCSSPropertyIDSet { void Empty() { memset(mProperties, 0, sizeof(mProperties)); } void AssertIsEmpty(const char* aText) const { - for (size_t i = 0; i < std::size(mProperties); ++i) { + for (size_t i = 0; i < mozilla::ArrayLength(mProperties); ++i) { NS_ASSERTION(mProperties[i] == 0, aText); } } @@ -135,7 +135,7 @@ class nsCSSPropertyIDSet { } bool IsEmpty() const { - for (size_t i = 0; i < std::size(mProperties); ++i) { + for (size_t i = 0; i < mozilla::ArrayLength(mProperties); ++i) { if (mProperties[i] != 0) { return false; } @@ -151,7 +151,7 @@ class nsCSSPropertyIDSet { // this set and |aOther|. nsCSSPropertyIDSet Intersect(const nsCSSPropertyIDSet& aOther) const { nsCSSPropertyIDSet result; - for (size_t i = 0; i < std::size(mProperties); ++i) { + for (size_t i = 0; i < mozilla::ArrayLength(mProperties); ++i) { result.mProperties[i] = mProperties[i] & aOther.mProperties[i]; } return result; @@ -161,14 +161,14 @@ class nsCSSPropertyIDSet { // this set or |aOther| but not both. nsCSSPropertyIDSet Xor(const nsCSSPropertyIDSet& aOther) const { nsCSSPropertyIDSet result; - for (size_t i = 0; i < std::size(mProperties); ++i) { + for (size_t i = 0; i < mozilla::ArrayLength(mProperties); ++i) { result.mProperties[i] = mProperties[i] ^ aOther.mProperties[i]; } return result; } nsCSSPropertyIDSet& operator|=(const nsCSSPropertyIDSet& aOther) { - for (size_t i = 0; i < std::size(mProperties); ++i) { + for (size_t i = 0; i < mozilla::ArrayLength(mProperties); ++i) { mProperties[i] |= aOther.mProperties[i]; } return *this; diff --git a/layout/style/nsCSSProps.cpp b/layout/style/nsCSSProps.cpp index 691a394e8fbf12..5f2f275d6e824c 100644 --- a/layout/style/nsCSSProps.cpp +++ b/layout/style/nsCSSProps.cpp @@ -108,7 +108,7 @@ void nsCSSProps::Init() { gPropertyIDLNameTable = new nsTHashMap; for (nsCSSPropertyID p = nsCSSPropertyID(0); - size_t(p) < std::size(kIDLNameTable); p = nsCSSPropertyID(p + 1)) { + size_t(p) < ArrayLength(kIDLNameTable); p = nsCSSPropertyID(p + 1)) { if (kIDLNameTable[p]) { gPropertyIDLNameTable->InsertOrUpdate( nsDependentCString(kIDLNameTable[p]), p); diff --git a/layout/style/nsComputedDOMStyle.cpp b/layout/style/nsComputedDOMStyle.cpp index af5227d992b3f2..01c1c63d1ca88b 100644 --- a/layout/style/nsComputedDOMStyle.cpp +++ b/layout/style/nsComputedDOMStyle.cpp @@ -217,11 +217,11 @@ struct ComputedStyleMap { * or is currently disabled. */ const Entry* FindEntryForProperty(nsCSSPropertyID aPropID) { - if (size_t(aPropID) >= std::size(kEntryIndices)) { + if (size_t(aPropID) >= ArrayLength(kEntryIndices)) { MOZ_ASSERT(aPropID == eCSSProperty_UNKNOWN); return nullptr; } - MOZ_ASSERT(kEntryIndices[aPropID] < std::size(kEntries)); + MOZ_ASSERT(kEntryIndices[aPropID] < ArrayLength(kEntries)); const auto& entry = kEntries[kEntryIndices[aPropID]]; if (!entry.IsEnabled()) { return nullptr; @@ -250,7 +250,7 @@ struct ComputedStyleMap { /** * A map of indexes on the nsComputedDOMStyle object to indexes into kEntries. */ - uint32_t mIndexMap[std::size(kEntries)]; + uint32_t mIndexMap[ArrayLength(kEntries)]; private: /** @@ -274,9 +274,9 @@ struct ComputedStyleMap { }; constexpr ComputedStyleMap::Entry - ComputedStyleMap::kEntries[std::size(kEntries)]; + ComputedStyleMap::kEntries[ArrayLength(kEntries)]; -constexpr size_t ComputedStyleMap::kEntryIndices[std::size(kEntries)]; +constexpr size_t ComputedStyleMap::kEntryIndices[ArrayLength(kEntries)]; void ComputedStyleMap::Update() { if (!IsDirty()) { @@ -284,7 +284,7 @@ void ComputedStyleMap::Update() { } uint32_t index = 0; - for (uint32_t i = 0; i < std::size(kEntries); i++) { + for (uint32_t i = 0; i < ArrayLength(kEntries); i++) { if (kEntries[i].IsEnumerable()) { mIndexMap[index++] = i; } diff --git a/layout/style/test/ListCSSProperties.cpp b/layout/style/test/ListCSSProperties.cpp index f0d26cfad85304..13ac6ae93db939 100644 --- a/layout/style/test/ListCSSProperties.cpp +++ b/layout/style/test/ListCSSProperties.cpp @@ -112,7 +112,7 @@ const char* gInaccessibleProperties[] = { }; inline int is_inaccessible(const char* aPropName) { - for (unsigned j = 0; j < std::size(gInaccessibleProperties); ++j) { + for (unsigned j = 0; j < MOZ_ARRAY_LENGTH(gInaccessibleProperties); ++j) { if (strcmp(aPropName, gInaccessibleProperties[j]) == 0) return 1; } return 0; @@ -167,10 +167,12 @@ void print_array(const char* aName, const PropertyInfo* aProps, int main() { print_array("gLonghandProperties", gLonghandProperties, - std::size(gLonghandProperties), gLonghandPropertiesWithDOMProp, - std::size(gLonghandPropertiesWithDOMProp)); + MOZ_ARRAY_LENGTH(gLonghandProperties), + gLonghandPropertiesWithDOMProp, + MOZ_ARRAY_LENGTH(gLonghandPropertiesWithDOMProp)); print_array("gShorthandProperties", gShorthandProperties, - std::size(gShorthandProperties), gShorthandPropertiesWithDOMProp, - std::size(gShorthandPropertiesWithDOMProp)); + MOZ_ARRAY_LENGTH(gShorthandProperties), + gShorthandPropertiesWithDOMProp, + MOZ_ARRAY_LENGTH(gShorthandPropertiesWithDOMProp)); return 0; } diff --git a/layout/tables/nsTableFrame.cpp b/layout/tables/nsTableFrame.cpp index 783011f6de847d..b40abc9f7f688f 100644 --- a/layout/tables/nsTableFrame.cpp +++ b/layout/tables/nsTableFrame.cpp @@ -5105,7 +5105,7 @@ void nsTableFrame::CalcBCBorders() { // We accumulate border widths as we process the cells, so we need // to reset it once in the beginning. bool tableBorderReset[4]; - for (uint32_t sideX = 0; sideX < std::size(tableBorderReset); sideX++) { + for (uint32_t sideX = 0; sideX < ArrayLength(tableBorderReset); sideX++) { tableBorderReset[sideX] = false; } diff --git a/media/psshparser/gtest/TestPsshParser.cpp b/media/psshparser/gtest/TestPsshParser.cpp index d8c06f6e60df18..2027090a1fb20f 100644 --- a/media/psshparser/gtest/TestPsshParser.cpp +++ b/media/psshparser/gtest/TestPsshParser.cpp @@ -131,40 +131,42 @@ TEST(PsshParser, ParseCencInitData) bool rv; rv = ParseCENCInitData(gGoogleWPTCencInitData, - std::size(gGoogleWPTCencInitData), keyIds); + MOZ_ARRAY_LENGTH(gGoogleWPTCencInitData), keyIds); EXPECT_TRUE(rv); EXPECT_EQ(1u, keyIds.size()); EXPECT_EQ(16u, keyIds[0].size()); EXPECT_EQ(0, memcmp(&keyIds[0].front(), &gGoogleWPTCencInitData[32], 16)); rv = ParseCENCInitData(gW3SpecExampleCencInitData, - std::size(gW3SpecExampleCencInitData), keyIds); + MOZ_ARRAY_LENGTH(gW3SpecExampleCencInitData), keyIds); EXPECT_TRUE(rv); EXPECT_EQ(2u, keyIds.size()); EXPECT_EQ(16u, keyIds[0].size()); EXPECT_EQ(0, memcmp(&keyIds[0].front(), &gW3SpecExampleCencInitData[32], 16)); EXPECT_EQ(0, memcmp(&keyIds[1].front(), &gW3SpecExampleCencInitData[48], 16)); - rv = ParseCENCInitData(gOverflowBoxSize, std::size(gOverflowBoxSize), keyIds); + rv = ParseCENCInitData(gOverflowBoxSize, MOZ_ARRAY_LENGTH(gOverflowBoxSize), + keyIds); EXPECT_FALSE(rv); EXPECT_EQ(0u, keyIds.size()); rv = ParseCENCInitData(gTooLargeKeyCountInitData, - std::size(gTooLargeKeyCountInitData), keyIds); + MOZ_ARRAY_LENGTH(gTooLargeKeyCountInitData), keyIds); EXPECT_FALSE(rv); EXPECT_EQ(0u, keyIds.size()); - rv = ParseCENCInitData(gNonCencInitData, std::size(gNonCencInitData), keyIds); + rv = ParseCENCInitData(gNonCencInitData, MOZ_ARRAY_LENGTH(gNonCencInitData), + keyIds); EXPECT_TRUE(rv); EXPECT_EQ(0u, keyIds.size()); - rv = ParseCENCInitData(gNonPSSHBoxZeroSize, std::size(gNonPSSHBoxZeroSize), - keyIds); + rv = ParseCENCInitData(gNonPSSHBoxZeroSize, + MOZ_ARRAY_LENGTH(gNonPSSHBoxZeroSize), keyIds); EXPECT_FALSE(rv); EXPECT_EQ(0u, keyIds.size()); rv = ParseCENCInitData(g2xGoogleWPTCencInitData, - std::size(g2xGoogleWPTCencInitData), keyIds); + MOZ_ARRAY_LENGTH(g2xGoogleWPTCencInitData), keyIds); EXPECT_TRUE(rv); EXPECT_EQ(2u, keyIds.size()); EXPECT_EQ(16u, keyIds[0].size()); diff --git a/memory/build/mozjemalloc.cpp b/memory/build/mozjemalloc.cpp index 0aec0870b4feed..52d24677a9b386 100644 --- a/memory/build/mozjemalloc.cpp +++ b/memory/build/mozjemalloc.cpp @@ -5383,7 +5383,7 @@ typedef HMODULE replace_malloc_handle_t; static replace_malloc_handle_t replace_malloc_handle() { wchar_t replace_malloc_lib[1024]; if (GetEnvironmentVariableW(L"MOZ_REPLACE_MALLOC_LIB", replace_malloc_lib, - std::size(replace_malloc_lib)) > 0) { + ArrayLength(replace_malloc_lib)) > 0) { return LoadLibraryW(replace_malloc_lib); } return nullptr; diff --git a/mfbt/Array.h b/mfbt/Array.h index 677a6ba3259ee7..21dc4b37d86782 100644 --- a/mfbt/Array.h +++ b/mfbt/Array.h @@ -75,9 +75,6 @@ class Array { constexpr const_iterator end() const { return mArr + Length; } constexpr const_iterator cend() const { return end(); } - // Method for std::size. - constexpr size_t size() const { return Length; } - // Methods for reverse iterating. reverse_iterator rbegin() { return reverse_iterator(end()); } const_reverse_iterator rbegin() const { diff --git a/mfbt/ArrayUtils.h b/mfbt/ArrayUtils.h index 7319503ef87372..78eec5dabadfbd 100644 --- a/mfbt/ArrayUtils.h +++ b/mfbt/ArrayUtils.h @@ -19,13 +19,17 @@ #ifdef __cplusplus # include -# include # include # include "mozilla/Alignment.h" namespace mozilla { +template +class Array; +template +class EnumeratedArray; + /* * Safely subtract two pointers when it is known that aEnd >= aBegin, yielding a * size_t result. @@ -44,6 +48,47 @@ MOZ_ALWAYS_INLINE size_t PointerRangeSize(T* aBegin, T* aEnd) { return (size_t(aEnd) - size_t(aBegin)) / sizeof(T); } +/* + * Compute the length of an array with constant length. (Use of this method + * with a non-array pointer will not compile.) + * + * Beware of the implicit trailing '\0' when using this with string constants. + */ +template +constexpr size_t ArrayLength(T (&aArr)[N]) { + return N; +} + +template +constexpr size_t ArrayLength(const Array& aArr) { + return N; +} + +template +constexpr size_t ArrayLength(const EnumeratedArray& aArr) { + return N; +} + +/* + * Compute the address one past the last element of a constant-length array. + * + * Beware of the implicit trailing '\0' when using this with string constants. + */ +template +constexpr T* ArrayEnd(T (&aArr)[N]) { + return aArr + ArrayLength(aArr); +} + +template +constexpr T* ArrayEnd(Array& aArr) { + return &aArr[0] + ArrayLength(aArr); +} + +template +constexpr const T* ArrayEnd(const Array& aArr) { + return &aArr[0] + ArrayLength(aArr); +} + /** * std::equal has subpar ergonomics. */ @@ -113,8 +158,31 @@ inline bool IsInRange(const T* aPtr, uintptr_t aBegin, uintptr_t aEnd) { reinterpret_cast(aEnd)); } +namespace detail { + +/* + * Helper for the MOZ_ARRAY_LENGTH() macro to make the length a typesafe + * compile-time constant even on compilers lacking constexpr support. + */ +template +char (&ArrayLengthHelper(T (&array)[N]))[N]; + +} /* namespace detail */ + } /* namespace mozilla */ #endif /* __cplusplus */ +/* + * MOZ_ARRAY_LENGTH() is an alternative to mozilla::ArrayLength() for C files + * that can't use C++ template functions and for static_assert() calls that + * can't call ArrayLength() when it is not a C++11 constexpr function. + */ +#ifdef __cplusplus +# define MOZ_ARRAY_LENGTH(array) \ + sizeof(mozilla::detail::ArrayLengthHelper(array)) +#else +# define MOZ_ARRAY_LENGTH(array) (sizeof(array) / sizeof((array)[0])) +#endif + #endif /* mozilla_ArrayUtils_h */ diff --git a/mfbt/BitSet.h b/mfbt/BitSet.h index 76d5672fac1d99..7c03fb87ce6b9b 100644 --- a/mfbt/BitSet.h +++ b/mfbt/BitSet.h @@ -107,7 +107,7 @@ class BitSet { } BitSet& operator|=(const BitSet& aOther) { - for (size_t i = 0; i < std::size(mStorage); i++) { + for (size_t i = 0; i < ArrayLength(mStorage); i++) { mStorage[i] |= aOther.mStorage[i]; } return *this; @@ -120,7 +120,7 @@ class BitSet { } BitSet& operator&=(const BitSet& aOther) { - for (size_t i = 0; i < std::size(mStorage); i++) { + for (size_t i = 0; i < ArrayLength(mStorage); i++) { mStorage[i] &= aOther.mStorage[i]; } return *this; diff --git a/mfbt/EnumeratedArray.h b/mfbt/EnumeratedArray.h index cb9b326d7f013b..21b2923d911859 100644 --- a/mfbt/EnumeratedArray.h +++ b/mfbt/EnumeratedArray.h @@ -82,9 +82,6 @@ class EnumeratedArray { const_iterator end() const { return mArray.end(); } const_iterator cend() const { return mArray.cend(); } - // Method for std::size. - constexpr size_t size() const { return mArray.size(); } - // Methods for reverse iterating. reverse_iterator rbegin() { return mArray.rbegin(); } const_reverse_iterator rbegin() const { return mArray.rbegin(); } diff --git a/mfbt/tests/TestAlgorithm.cpp b/mfbt/tests/TestAlgorithm.cpp index 0ab8418ee96d13..c5b0ffff12af65 100644 --- a/mfbt/tests/TestAlgorithm.cpp +++ b/mfbt/tests/TestAlgorithm.cpp @@ -22,20 +22,20 @@ void TestAllOf() { constexpr static int32_t arr1[3] = {1, 2, 3}; MOZ_RELEASE_ASSERT(!AllOf(begin(arr1), end(arr1), even)); MOZ_RELEASE_ASSERT(!AllOf(begin(arr1), end(arr1), odd)); - static_assert(!AllOf(arr1, arr1 + std::size(arr1), even), "1-1"); - static_assert(!AllOf(arr1, arr1 + std::size(arr1), odd), "1-2"); + static_assert(!AllOf(arr1, arr1 + ArrayLength(arr1), even), "1-1"); + static_assert(!AllOf(arr1, arr1 + ArrayLength(arr1), odd), "1-2"); constexpr static int32_t arr2[3] = {1, 3, 5}; MOZ_RELEASE_ASSERT(!AllOf(begin(arr2), end(arr2), even)); MOZ_RELEASE_ASSERT(AllOf(begin(arr2), end(arr2), odd)); - static_assert(!AllOf(arr2, arr2 + std::size(arr2), even), "2-1"); - static_assert(AllOf(arr2, arr2 + std::size(arr2), odd), "2-2"); + static_assert(!AllOf(arr2, arr2 + ArrayLength(arr2), even), "2-1"); + static_assert(AllOf(arr2, arr2 + ArrayLength(arr2), odd), "2-2"); constexpr static int32_t arr3[3] = {2, 4, 6}; MOZ_RELEASE_ASSERT(AllOf(begin(arr3), end(arr3), even)); MOZ_RELEASE_ASSERT(!AllOf(begin(arr3), end(arr3), odd)); - static_assert(AllOf(arr3, arr3 + std::size(arr3), even), "3-1"); - static_assert(!AllOf(arr3, arr3 + std::size(arr3), odd), "3-2"); + static_assert(AllOf(arr3, arr3 + ArrayLength(arr3), even), "3-1"); + static_assert(!AllOf(arr3, arr3 + ArrayLength(arr3), odd), "3-2"); } void TestAnyOf() { diff --git a/mfbt/tests/TestBinarySearch.cpp b/mfbt/tests/TestBinarySearch.cpp index e4993bc87b1974..3cd28b309fbec3 100644 --- a/mfbt/tests/TestBinarySearch.cpp +++ b/mfbt/tests/TestBinarySearch.cpp @@ -10,6 +10,7 @@ #include +using mozilla::ArrayLength; using mozilla::BinarySearch; using mozilla::BinarySearchIf; using mozilla::Vector; @@ -90,7 +91,7 @@ static void TestBinarySearch() { static void TestBinarySearchIf() { const int v1[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; - const size_t len = std::size(v1); + const size_t len = ArrayLength(v1); size_t m; A(BinarySearchIf(v1, 0, len, RangeFinder(2, 3), &m) && m == 2); diff --git a/mfbt/tests/TestEnumeratedArray.cpp b/mfbt/tests/TestEnumeratedArray.cpp index 8dd2ec59a7d0cc..d5ec9ebbb313a3 100644 --- a/mfbt/tests/TestEnumeratedArray.cpp +++ b/mfbt/tests/TestEnumeratedArray.cpp @@ -22,7 +22,7 @@ using TestArray = EnumeratedArray; void TestInitialValueByConstructor() { // Style 1 TestArray headCount(1, 2, 3); - MOZ_RELEASE_ASSERT(std::size(headCount) == 3); + MOZ_RELEASE_ASSERT(mozilla::ArrayLength(headCount) == 3); MOZ_RELEASE_ASSERT(headCount[AnimalSpecies::Cow] == 1); MOZ_RELEASE_ASSERT(headCount[AnimalSpecies::Sheep] == 2); MOZ_RELEASE_ASSERT(headCount[AnimalSpecies::Pig] == 3); diff --git a/mfbt/tests/TestSplayTree.cpp b/mfbt/tests/TestSplayTree.cpp index 82f0b31e4a11ab..8269664ce90d3f 100644 --- a/mfbt/tests/TestSplayTree.cpp +++ b/mfbt/tests/TestSplayTree.cpp @@ -121,9 +121,9 @@ int main() { MOZ_RELEASE_ASSERT(tree.empty()); - MOZ_RELEASE_ASSERT(!tree.find(SplayInt(1))); + MOZ_RELEASE_ASSERT(!tree.find(SplayInt(0))); - static const int N = std::size(gValues); + static const int N = mozilla::ArrayLength(gValues); // Insert the values, and check each one is findable just after insertion. for (int i = 0; i < N; i++) { diff --git a/mfbt/tests/TestUtf8.cpp b/mfbt/tests/TestUtf8.cpp index bfccaa67318da3..2c51d9abfb7959 100644 --- a/mfbt/tests/TestUtf8.cpp +++ b/mfbt/tests/TestUtf8.cpp @@ -14,6 +14,7 @@ #include "mozilla/IntegerRange.h" #include "mozilla/Span.h" +using mozilla::ArrayLength; using mozilla::AsChars; using mozilla::DecodeOneUtf8CodePoint; using mozilla::EnumSet; @@ -243,26 +244,27 @@ static void ExpectBadCodePoint(const Char (&aCharN)[N], static void TestIsUtf8() { // Note we include the U+0000 NULL in this one -- and that's fine. static const char asciiBytes[] = u8"How about a nice game of chess?"; - MOZ_RELEASE_ASSERT(IsUtf8(Span(asciiBytes, std::size(asciiBytes)))); + MOZ_RELEASE_ASSERT(IsUtf8(Span(asciiBytes, ArrayLength(asciiBytes)))); static const char endNonAsciiBytes[] = u8"Life is like a 🌯"; MOZ_RELEASE_ASSERT( - IsUtf8(Span(endNonAsciiBytes, std::size(endNonAsciiBytes) - 1))); + IsUtf8(Span(endNonAsciiBytes, ArrayLength(endNonAsciiBytes) - 1))); static const unsigned char badLeading[] = {0x80}; - MOZ_RELEASE_ASSERT(!IsUtf8(AsChars(Span(badLeading, std::size(badLeading))))); + MOZ_RELEASE_ASSERT( + !IsUtf8(AsChars(Span(badLeading, ArrayLength(badLeading))))); // Byte-counts // 1 static const char oneBytes[] = u8"A"; // U+0041 LATIN CAPITAL LETTER A - constexpr size_t oneBytesLen = std::size(oneBytes); + constexpr size_t oneBytesLen = ArrayLength(oneBytes); static_assert(oneBytesLen == 2, "U+0041 plus nul"); MOZ_RELEASE_ASSERT(IsUtf8(Span(oneBytes, oneBytesLen))); // 2 static const char twoBytes[] = u8"؆"; // U+0606 ARABIC-INDIC CUBE ROOT - constexpr size_t twoBytesLen = std::size(twoBytes); + constexpr size_t twoBytesLen = ArrayLength(twoBytes); static_assert(twoBytesLen == 3, "U+0606 in two bytes plus nul"); MOZ_RELEASE_ASSERT(IsUtf8(Span(twoBytes, twoBytesLen))); @@ -270,7 +272,7 @@ static void TestIsUtf8() { // 3 static const char threeBytes[] = u8"᨞"; // U+1A1E BUGINESE PALLAWA - constexpr size_t threeBytesLen = std::size(threeBytes); + constexpr size_t threeBytesLen = ArrayLength(threeBytes); static_assert(threeBytesLen == 4, "U+1A1E in three bytes plus nul"); MOZ_RELEASE_ASSERT(IsUtf8(Span(threeBytes, threeBytesLen))); @@ -279,7 +281,7 @@ static void TestIsUtf8() { // 4 static const char fourBytes[] = u8"🁡"; // U+1F061 DOMINO TILE HORIZONTAL-06-06 - constexpr size_t fourBytesLen = std::size(fourBytes); + constexpr size_t fourBytesLen = ArrayLength(fourBytes); static_assert(fourBytesLen == 5, "U+1F061 in four bytes plus nul"); MOZ_RELEASE_ASSERT(IsUtf8(Span(fourBytes, fourBytesLen))); @@ -287,7 +289,7 @@ static void TestIsUtf8() { // Max code point static const char maxCodePoint[] = u8"􏿿"; // U+10FFFF - constexpr size_t maxCodePointLen = std::size(maxCodePoint); + constexpr size_t maxCodePointLen = ArrayLength(maxCodePoint); static_assert(maxCodePointLen == 5, "U+10FFFF in four bytes plus nul"); MOZ_RELEASE_ASSERT(IsUtf8(Span(maxCodePoint, maxCodePointLen))); @@ -296,7 +298,7 @@ static void TestIsUtf8() { // One past max code point static const unsigned char onePastMaxCodePoint[] = {0xF4, 0x90, 0x80, 0x80, 0x0}; - constexpr size_t onePastMaxCodePointLen = std::size(onePastMaxCodePoint); + constexpr size_t onePastMaxCodePointLen = ArrayLength(onePastMaxCodePoint); MOZ_RELEASE_ASSERT( !IsUtf8(AsChars(Span(onePastMaxCodePoint, onePastMaxCodePointLen)))); @@ -309,21 +311,21 @@ static void TestIsUtf8() { static const unsigned char justBeforeSurrogates[] = {0xED, 0x9F, 0xBF, 0x0}; constexpr size_t justBeforeSurrogatesLen = - std::size(justBeforeSurrogates) - 1; + ArrayLength(justBeforeSurrogates) - 1; MOZ_RELEASE_ASSERT( IsUtf8(AsChars(Span(justBeforeSurrogates, justBeforeSurrogatesLen)))); ExpectValidCodePoint(justBeforeSurrogates, 0xD7FF); static const unsigned char leastSurrogate[] = {0xED, 0xA0, 0x80, 0x0}; - constexpr size_t leastSurrogateLen = std::size(leastSurrogate) - 1; + constexpr size_t leastSurrogateLen = ArrayLength(leastSurrogate) - 1; MOZ_RELEASE_ASSERT(!IsUtf8(AsChars(Span(leastSurrogate, leastSurrogateLen)))); ExpectBadCodePoint(leastSurrogate, 0xD800, 3); static const unsigned char arbitraryHighSurrogate[] = {0xED, 0xA2, 0x87, 0x0}; constexpr size_t arbitraryHighSurrogateLen = - std::size(arbitraryHighSurrogate) - 1; + ArrayLength(arbitraryHighSurrogate) - 1; MOZ_RELEASE_ASSERT(!IsUtf8( AsChars(Span(arbitraryHighSurrogate, arbitraryHighSurrogateLen)))); @@ -331,21 +333,22 @@ static void TestIsUtf8() { static const unsigned char arbitraryLowSurrogate[] = {0xED, 0xB7, 0xAF, 0x0}; constexpr size_t arbitraryLowSurrogateLen = - std::size(arbitraryLowSurrogate) - 1; + ArrayLength(arbitraryLowSurrogate) - 1; MOZ_RELEASE_ASSERT( !IsUtf8(AsChars(Span(arbitraryLowSurrogate, arbitraryLowSurrogateLen)))); ExpectBadCodePoint(arbitraryLowSurrogate, 0xDDEF, 3); static const unsigned char greatestSurrogate[] = {0xED, 0xBF, 0xBF, 0x0}; - constexpr size_t greatestSurrogateLen = std::size(greatestSurrogate) - 1; + constexpr size_t greatestSurrogateLen = ArrayLength(greatestSurrogate) - 1; MOZ_RELEASE_ASSERT( !IsUtf8(AsChars(Span(greatestSurrogate, greatestSurrogateLen)))); ExpectBadCodePoint(greatestSurrogate, 0xDFFF, 3); static const unsigned char justAfterSurrogates[] = {0xEE, 0x80, 0x80, 0x0}; - constexpr size_t justAfterSurrogatesLen = std::size(justAfterSurrogates) - 1; + constexpr size_t justAfterSurrogatesLen = + ArrayLength(justAfterSurrogates) - 1; MOZ_RELEASE_ASSERT( IsUtf8(AsChars(Span(justAfterSurrogates, justAfterSurrogatesLen)))); diff --git a/mozglue/baseprofiler/core/ProfilingCategory.cpp b/mozglue/baseprofiler/core/ProfilingCategory.cpp index 41fda0c1455663..8ff2b155551cc7 100644 --- a/mozglue/baseprofiler/core/ProfilingCategory.cpp +++ b/mozglue/baseprofiler/core/ProfilingCategory.cpp @@ -56,7 +56,7 @@ const ProfilingCategoryPairInfo sProfilingCategoryPairInfo[] = { const ProfilingCategoryPairInfo& GetProfilingCategoryPairInfo( ProfilingCategoryPair aCategoryPair) { static_assert( - std::size(sProfilingCategoryPairInfo) == + MOZ_ARRAY_LENGTH(sProfilingCategoryPairInfo) == uint32_t(ProfilingCategoryPair::COUNT), "sProfilingCategoryPairInfo and ProfilingCategory need to have the " "same order and the same length"); diff --git a/mozglue/baseprofiler/lul/LulMain.cpp b/mozglue/baseprofiler/lul/LulMain.cpp index a9bdaa52462539..75f205ac3af5cf 100644 --- a/mozglue/baseprofiler/lul/LulMain.cpp +++ b/mozglue/baseprofiler/lul/LulMain.cpp @@ -1698,7 +1698,7 @@ static __attribute__((noinline)) bool GetAndCheckStackTrace( const int MAX_TEST_FRAMES = 64; uintptr_t framePCs[MAX_TEST_FRAMES]; uintptr_t frameSPs[MAX_TEST_FRAMES]; - size_t framesAvail = std::size(framePCs); + size_t framesAvail = mozilla::ArrayLength(framePCs); size_t framesUsed = 0; size_t framePointerFramesAcquired = 0; aLUL->Unwind(&framePCs[0], &frameSPs[0], &framesUsed, diff --git a/mozglue/misc/NativeNt.h b/mozglue/misc/NativeNt.h index e28ad0f29141dd..7be901cff1dd3a 100644 --- a/mozglue/misc/NativeNt.h +++ b/mozglue/misc/NativeNt.h @@ -554,7 +554,7 @@ class MOZ_RAII PEHeaders final { WORD wLength; WORD wValueLength; WORD wType; - WCHAR szKey[16]; // std::size(L"VS_VERSION_INFO") + WCHAR szKey[16]; // ArrayLength(L"VS_VERSION_INFO") // Additional data goes here, aligned on a 4-byte boundary }; @@ -1030,8 +1030,8 @@ class MOZ_RAII PEHeaders final { const wchar_t kVersionInfoKey[] = L"VS_VERSION_INFO"; if (::RtlCompareMemory(aVerInfo->szKey, kVersionInfoKey, - std::size(kVersionInfoKey)) != - std::size(kVersionInfoKey)) { + ArrayLength(kVersionInfoKey)) != + ArrayLength(kVersionInfoKey)) { return nullptr; } diff --git a/mozglue/misc/StackWalk.cpp b/mozglue/misc/StackWalk.cpp index c1a4e48ed741fd..186082f972d171 100644 --- a/mozglue/misc/StackWalk.cpp +++ b/mozglue/misc/StackWalk.cpp @@ -728,13 +728,13 @@ MFBT_API bool MozDescribeCodeAddress(void* aPC, if (modInfoRes) { strncpy(aDetails->library, modInfo.LoadedImageName, sizeof(aDetails->library)); - aDetails->library[std::size(aDetails->library) - 1] = '\0'; + aDetails->library[mozilla::ArrayLength(aDetails->library) - 1] = '\0'; aDetails->loffset = (char*)aPC - (char*)modInfo.BaseOfImage; if (lineInfo.FileName) { strncpy(aDetails->filename, lineInfo.FileName, sizeof(aDetails->filename)); - aDetails->filename[std::size(aDetails->filename) - 1] = '\0'; + aDetails->filename[mozilla::ArrayLength(aDetails->filename) - 1] = '\0'; aDetails->lineno = lineInfo.LineNumber; } } @@ -751,7 +751,7 @@ MFBT_API bool MozDescribeCodeAddress(void* aPC, if (ok) { strncpy(aDetails->function, pSymbol->Name, sizeof(aDetails->function)); - aDetails->function[std::size(aDetails->function) - 1] = '\0'; + aDetails->function[mozilla::ArrayLength(aDetails->function) - 1] = '\0'; aDetails->foffset = static_cast(displacement); } @@ -933,7 +933,7 @@ bool MFBT_API MozDescribeCodeAddress(void* aPC, } strncpy(aDetails->library, info.dli_fname, sizeof(aDetails->library)); - aDetails->library[std::size(aDetails->library) - 1] = '\0'; + aDetails->library[mozilla::ArrayLength(aDetails->library) - 1] = '\0'; aDetails->loffset = (char*)aPC - (char*)info.dli_fbase; # if !defined(XP_FREEBSD) @@ -951,7 +951,7 @@ bool MFBT_API MozDescribeCodeAddress(void* aPC, if (aDetails->function[0] == '\0') { // Just use the mangled symbol if demangling failed. strncpy(aDetails->function, symbol, sizeof(aDetails->function)); - aDetails->function[std::size(aDetails->function) - 1] = '\0'; + aDetails->function[mozilla::ArrayLength(aDetails->function) - 1] = '\0'; } aDetails->foffset = (char*)aPC - (char*)info.dli_saddr; diff --git a/mozglue/misc/decimal/moz-decimal-utils.h b/mozglue/misc/decimal/moz-decimal-utils.h index d773710289b023..05ea61e4bdd66b 100644 --- a/mozglue/misc/decimal/moz-decimal-utils.h +++ b/mozglue/misc/decimal/moz-decimal-utils.h @@ -61,7 +61,7 @@ double mozToDouble(const String &aStr, bool *valid) { String mozToString(double aNum) { char buffer[64]; - int buffer_length = std::size(buffer); + int buffer_length = mozilla::ArrayLength(buffer); const double_conversion::DoubleToStringConverter& converter = double_conversion::DoubleToStringConverter::EcmaScriptConverter(); double_conversion::StringBuilder builder(buffer, buffer_length); diff --git a/mozglue/tests/TestPEExportSection.cpp b/mozglue/tests/TestPEExportSection.cpp index 9b05aa8b8c1e6b..cf160368d39454 100644 --- a/mozglue/tests/TestPEExportSection.cpp +++ b/mozglue/tests/TestPEExportSection.cpp @@ -350,7 +350,8 @@ class ChildProcess final { ChildProcess(const wchar_t* aExecutable, const wchar_t* aOption, const nsAutoHandle& aEvent, const nsAutoHandle& aJob) { const wchar_t* childArgv[] = {aExecutable, aOption}; - auto cmdLine(mozilla::MakeCommandLine(std::size(childArgv), childArgv)); + auto cmdLine( + mozilla::MakeCommandLine(mozilla::ArrayLength(childArgv), childArgv)); STARTUPINFOW si = {sizeof(si)}; PROCESS_INFORMATION pi; diff --git a/mozglue/tests/TestTimeStampWin.cpp b/mozglue/tests/TestTimeStampWin.cpp index cd5ca39f174397..a69e2be59f50e6 100644 --- a/mozglue/tests/TestTimeStampWin.cpp +++ b/mozglue/tests/TestTimeStampWin.cpp @@ -19,7 +19,7 @@ static nsReturnRef CreateProcessWrapper(const wchar_t* aPath) { const wchar_t* childArgv[] = {aPath, kChildArg}; mozilla::UniquePtr cmdLine( - mozilla::MakeCommandLine(std::size(childArgv), childArgv)); + mozilla::MakeCommandLine(mozilla::ArrayLength(childArgv), childArgv)); STARTUPINFOW si = {sizeof(si)}; PROCESS_INFORMATION pi; diff --git a/netwerk/dns/DNS.cpp b/netwerk/dns/DNS.cpp index d5051aa45df65f..b568295891c4ce 100644 --- a/netwerk/dns/DNS.cpp +++ b/netwerk/dns/DNS.cpp @@ -324,7 +324,7 @@ bool NetAddr::operator==(const NetAddr& other) const { } if (this->raw.family == AF_LOCAL) { return strncmp(this->local.path, other.local.path, - std::size(this->local.path)); + ArrayLength(this->local.path)); #endif } return false; diff --git a/netwerk/protocol/http/Http2Session.cpp b/netwerk/protocol/http/Http2Session.cpp index fed34a73075688..1c0f1097c4d2b3 100644 --- a/netwerk/protocol/http/Http2Session.cpp +++ b/netwerk/protocol/http/Http2Session.cpp @@ -3593,7 +3593,7 @@ nsresult Http2Session::WriteSegmentsAgain(nsAHttpSegmentWriter* writer, if (mInputFrameDataRead != mInputFrameDataSize) return NS_OK; MOZ_ASSERT(mInputFrameType != FRAME_TYPE_DATA); - if (mInputFrameType < std::size(sControlFunctions)) { + if (mInputFrameType < ArrayLength(sControlFunctions)) { rv = sControlFunctions[mInputFrameType](this); } else { // Section 4.1 requires this to be ignored; though protocol_error would diff --git a/netwerk/protocol/http/HttpBaseChannel.cpp b/netwerk/protocol/http/HttpBaseChannel.cpp index 23d2013e87bced..bb2060c1bda908 100644 --- a/netwerk/protocol/http/HttpBaseChannel.cpp +++ b/netwerk/protocol/http/HttpBaseChannel.cpp @@ -167,7 +167,7 @@ static bool IsHeaderBlacklistedForRedirectCopy(nsHttpAtom const& aHeader) { }; size_t unused; - return BinarySearchIf(blackList, 0, std::size(blackList), + return BinarySearchIf(blackList, 0, ArrayLength(blackList), HttpAtomComparator(aHeader), &unused); } diff --git a/netwerk/protocol/res/ExtensionProtocolHandler.cpp b/netwerk/protocol/res/ExtensionProtocolHandler.cpp index 5d5a6ea697b971..63271911258b53 100644 --- a/netwerk/protocol/res/ExtensionProtocolHandler.cpp +++ b/netwerk/protocol/res/ExtensionProtocolHandler.cpp @@ -548,7 +548,7 @@ nsresult ExtensionProtocolHandler::SubstituteChannel(nsIURI* aURI, } else if (readyPromise) { size_t matchIdx; if (BinarySearchIf( - sStaticFileExtensions, 0, std::size(sStaticFileExtensions), + sStaticFileExtensions, 0, ArrayLength(sStaticFileExtensions), [&ext](const char* aOther) { return Compare(ext, nsDependentCString(aOther)); }, diff --git a/netwerk/streamconv/converters/nsDirIndexParser.cpp b/netwerk/streamconv/converters/nsDirIndexParser.cpp index 6af4f7765f60dd..600f43a1aae2a4 100644 --- a/netwerk/streamconv/converters/nsDirIndexParser.cpp +++ b/netwerk/streamconv/converters/nsDirIndexParser.cpp @@ -92,7 +92,7 @@ void nsDirIndexParser::ParseFormat(const char* aFormatStr) { } } - } while (*aFormatStr && (formatNum < (std::size(mFormat) - 1))); + } while (*aFormatStr && (formatNum < (ArrayLength(mFormat) - 1))); } void nsDirIndexParser::ParseData(nsIDirIndex* aIdx, char* aDataStr, diff --git a/netwerk/wifi/nsWifiAccessPoint.h b/netwerk/wifi/nsWifiAccessPoint.h index e77079632cd499..3f83b2c0c0e02f 100644 --- a/netwerk/wifi/nsWifiAccessPoint.h +++ b/netwerk/wifi/nsWifiAccessPoint.h @@ -32,7 +32,7 @@ class nsWifiAccessPoint final : public nsIWifiAccessPoint { void setSignal(int signal) { mSignal = signal; } void setMacRaw(const char* aString) { - memcpy(mMac, aString, std::size(mMac)); + memcpy(mMac, aString, mozilla::ArrayLength(mMac)); } void setMac(const unsigned char mac_as_int[6]) { @@ -53,7 +53,7 @@ class nsWifiAccessPoint final : public nsIWifiAccessPoint { } void setSSIDRaw(const char* aSSID, size_t len) { - mSsidLen = std::min(len, std::size(mSsid)); + mSsidLen = std::min(len, mozilla::ArrayLength(mSsid)); memcpy(mSsid, aSSID, mSsidLen); } diff --git a/parser/html/nsHtml5AttributeName.cpp b/parser/html/nsHtml5AttributeName.cpp index 9854b333990bda..8b2c4f10289ba0 100644 --- a/parser/html/nsHtml5AttributeName.cpp +++ b/parser/html/nsHtml5AttributeName.cpp @@ -685,7 +685,7 @@ static int32_t const ATTRIBUTE_HASHES_DATA[] = { 2024763702, 2026741958, 2026975253, 2060302634, 2065170434, 2066743298, 2075005220}; staticJArray nsHtml5AttributeName::ATTRIBUTE_HASHES = { - ATTRIBUTE_HASHES_DATA, std::size(ATTRIBUTE_HASHES_DATA)}; + ATTRIBUTE_HASHES_DATA, MOZ_ARRAY_LENGTH(ATTRIBUTE_HASHES_DATA)}; void nsHtml5AttributeName::initializeStatics() { ALL_NO_NS = new int32_t[3]; ALL_NO_NS[0] = kNameSpaceID_None; diff --git a/parser/html/nsHtml5ElementName.cpp b/parser/html/nsHtml5ElementName.cpp index 6b2b516edea44d..4eb4049967869a 100644 --- a/parser/html/nsHtml5ElementName.cpp +++ b/parser/html/nsHtml5ElementName.cpp @@ -308,7 +308,7 @@ static int32_t const ELEMENT_HASHES_DATA[] = { 1935549734, 1939219752, 1941221172, 1965115924, 1966223078, 1967760215, 1967795910, 1968053806, 1971461414}; staticJArray nsHtml5ElementName::ELEMENT_HASHES = { - ELEMENT_HASHES_DATA, std::size(ELEMENT_HASHES_DATA)}; + ELEMENT_HASHES_DATA, MOZ_ARRAY_LENGTH(ELEMENT_HASHES_DATA)}; void nsHtml5ElementName::initializeStatics() { ELT_ANNOTATION_XML = new nsHtml5ElementName( nsGkAtoms::annotation_xml_, nsGkAtoms::annotation_xml_, diff --git a/parser/html/nsHtml5NamedCharacters.cpp b/parser/html/nsHtml5NamedCharacters.cpp index fcfe87d3e78e93..5181d7538e34a3 100644 --- a/parser/html/nsHtml5NamedCharacters.cpp +++ b/parser/html/nsHtml5NamedCharacters.cpp @@ -68,7 +68,7 @@ enum NamePositions { DUMMY_FINAL_NAME_VALUE }; -static_assert(std::size(ALL_NAMES) < 0x10000, +static_assert(MOZ_ARRAY_LENGTH(ALL_NAMES) < 0x10000, "Start positions should fit in 16 bits"); const nsHtml5CharacterName nsHtml5NamedCharacters::NAMES[] = { diff --git a/parser/html/nsHtml5Tokenizer.cpp b/parser/html/nsHtml5Tokenizer.cpp index 1a305d95cb6263..127c0a77fc7207 100644 --- a/parser/html/nsHtml5Tokenizer.cpp +++ b/parser/html/nsHtml5Tokenizer.cpp @@ -53,38 +53,38 @@ char16_t nsHtml5Tokenizer::UBLIC[] = {'u', 'b', 'l', 'i', 'c'}; char16_t nsHtml5Tokenizer::YSTEM[] = {'y', 's', 't', 'e', 'm'}; static char16_t const TITLE_ARR_DATA[] = {'t', 'i', 't', 'l', 'e'}; staticJArray nsHtml5Tokenizer::TITLE_ARR = { - TITLE_ARR_DATA, std::size(TITLE_ARR_DATA)}; + TITLE_ARR_DATA, MOZ_ARRAY_LENGTH(TITLE_ARR_DATA)}; static char16_t const SCRIPT_ARR_DATA[] = {'s', 'c', 'r', 'i', 'p', 't'}; staticJArray nsHtml5Tokenizer::SCRIPT_ARR = { - SCRIPT_ARR_DATA, std::size(SCRIPT_ARR_DATA)}; + SCRIPT_ARR_DATA, MOZ_ARRAY_LENGTH(SCRIPT_ARR_DATA)}; static char16_t const STYLE_ARR_DATA[] = {'s', 't', 'y', 'l', 'e'}; staticJArray nsHtml5Tokenizer::STYLE_ARR = { - STYLE_ARR_DATA, std::size(STYLE_ARR_DATA)}; + STYLE_ARR_DATA, MOZ_ARRAY_LENGTH(STYLE_ARR_DATA)}; static char16_t const PLAINTEXT_ARR_DATA[] = {'p', 'l', 'a', 'i', 'n', 't', 'e', 'x', 't'}; staticJArray nsHtml5Tokenizer::PLAINTEXT_ARR = { - PLAINTEXT_ARR_DATA, std::size(PLAINTEXT_ARR_DATA)}; + PLAINTEXT_ARR_DATA, MOZ_ARRAY_LENGTH(PLAINTEXT_ARR_DATA)}; static char16_t const XMP_ARR_DATA[] = {'x', 'm', 'p'}; staticJArray nsHtml5Tokenizer::XMP_ARR = { - XMP_ARR_DATA, std::size(XMP_ARR_DATA)}; + XMP_ARR_DATA, MOZ_ARRAY_LENGTH(XMP_ARR_DATA)}; static char16_t const TEXTAREA_ARR_DATA[] = {'t', 'e', 'x', 't', 'a', 'r', 'e', 'a'}; staticJArray nsHtml5Tokenizer::TEXTAREA_ARR = { - TEXTAREA_ARR_DATA, std::size(TEXTAREA_ARR_DATA)}; + TEXTAREA_ARR_DATA, MOZ_ARRAY_LENGTH(TEXTAREA_ARR_DATA)}; static char16_t const IFRAME_ARR_DATA[] = {'i', 'f', 'r', 'a', 'm', 'e'}; staticJArray nsHtml5Tokenizer::IFRAME_ARR = { - IFRAME_ARR_DATA, std::size(IFRAME_ARR_DATA)}; + IFRAME_ARR_DATA, MOZ_ARRAY_LENGTH(IFRAME_ARR_DATA)}; static char16_t const NOEMBED_ARR_DATA[] = {'n', 'o', 'e', 'm', 'b', 'e', 'd'}; staticJArray nsHtml5Tokenizer::NOEMBED_ARR = { - NOEMBED_ARR_DATA, std::size(NOEMBED_ARR_DATA)}; + NOEMBED_ARR_DATA, MOZ_ARRAY_LENGTH(NOEMBED_ARR_DATA)}; static char16_t const NOSCRIPT_ARR_DATA[] = {'n', 'o', 's', 'c', 'r', 'i', 'p', 't'}; staticJArray nsHtml5Tokenizer::NOSCRIPT_ARR = { - NOSCRIPT_ARR_DATA, std::size(NOSCRIPT_ARR_DATA)}; + NOSCRIPT_ARR_DATA, MOZ_ARRAY_LENGTH(NOSCRIPT_ARR_DATA)}; static char16_t const NOFRAMES_ARR_DATA[] = {'n', 'o', 'f', 'r', 'a', 'm', 'e', 's'}; staticJArray nsHtml5Tokenizer::NOFRAMES_ARR = { - NOFRAMES_ARR_DATA, std::size(NOFRAMES_ARR_DATA)}; + NOFRAMES_ARR_DATA, MOZ_ARRAY_LENGTH(NOFRAMES_ARR_DATA)}; nsHtml5Tokenizer::nsHtml5Tokenizer(nsHtml5TreeBuilder* tokenHandler, bool viewingXmlSource) diff --git a/parser/html/nsHtml5TreeBuilder.cpp b/parser/html/nsHtml5TreeBuilder.cpp index c225015c9b4b59..ef4de158fec524 100644 --- a/parser/html/nsHtml5TreeBuilder.cpp +++ b/parser/html/nsHtml5TreeBuilder.cpp @@ -99,7 +99,7 @@ static const char* const QUIRKY_PUBLIC_IDS_DATA[] = { "-//webtechs//dtd mozilla html 2.0//", "-//webtechs//dtd mozilla html//"}; staticJArray nsHtml5TreeBuilder::QUIRKY_PUBLIC_IDS = { - QUIRKY_PUBLIC_IDS_DATA, std::size(QUIRKY_PUBLIC_IDS_DATA)}; + QUIRKY_PUBLIC_IDS_DATA, MOZ_ARRAY_LENGTH(QUIRKY_PUBLIC_IDS_DATA)}; void nsHtml5TreeBuilder::setKeepBuffer(bool keepBuffer) { this->keepBuffer = keepBuffer; } diff --git a/parser/htmlparser/nsExpatDriver.cpp b/parser/htmlparser/nsExpatDriver.cpp index 2de40123f9a767..72f7db92963a05 100644 --- a/parser/htmlparser/nsExpatDriver.cpp +++ b/parser/htmlparser/nsExpatDriver.cpp @@ -826,8 +826,8 @@ int nsExpatDriver::HandleExternalEntityRef(const char16_t* openEntityNames, RLBOX_EXPAT_MCALL(MOZ_XML_ExternalEntityParserCreate, nullptr, *utf16); if (entParser) { auto baseURI = GetExpatBaseURI(absURI); - auto url = - TransferBuffer(Sandbox(), &baseURI[0], std::size(baseURI)); + auto url = TransferBuffer(Sandbox(), &baseURI[0], + ArrayLength(baseURI)); NS_ENSURE_TRUE(*url, 1); Sandbox()->invoke_sandbox_function(MOZ_XML_SetBase, entParser, *url); @@ -1617,7 +1617,7 @@ nsresult nsExpatDriver::Initialize(nsIURI* aURI, nsIContentSink* aSink) { auto baseURI = GetExpatBaseURI(aURI); auto uri = - TransferBuffer(Sandbox(), &baseURI[0], std::size(baseURI)); + TransferBuffer(Sandbox(), &baseURI[0], ArrayLength(baseURI)); RLBOX_EXPAT_MCALL(MOZ_XML_SetBase, *uri); // Set up the callbacks diff --git a/security/certverifier/CertVerifier.cpp b/security/certverifier/CertVerifier.cpp index 0db75af43acf05..87043de7da3c2a 100644 --- a/security/certverifier/CertVerifier.cpp +++ b/security/certverifier/CertVerifier.cpp @@ -560,10 +560,11 @@ Result CertVerifier::VerifyCert( KeySizeStatus keySizeStatuses[] = {KeySizeStatus::LargeMinimumSucceeded, KeySizeStatus::CompatibilityRisk}; - static_assert(std::size(keySizeOptions) == std::size(keySizeStatuses), - "keySize array lengths differ"); + static_assert( + MOZ_ARRAY_LENGTH(keySizeOptions) == MOZ_ARRAY_LENGTH(keySizeStatuses), + "keySize array lengths differ"); - size_t keySizeOptionsCount = std::size(keySizeStatuses); + size_t keySizeOptionsCount = MOZ_ARRAY_LENGTH(keySizeStatuses); for (size_t i = 0; i < keySizeOptionsCount && rv != Success; i++) { // invalidate any telemetry info relating to failed chains diff --git a/security/certverifier/ExtendedValidation.cpp b/security/certverifier/ExtendedValidation.cpp index 8c1e0ac36c5aa5..8b3079f82b9573 100644 --- a/security/certverifier/ExtendedValidation.cpp +++ b/security/certverifier/ExtendedValidation.cpp @@ -1286,9 +1286,9 @@ static const struct EVInfo kEVInfos[] = { // clang-format on }; -static pkix::CertPolicyId sEVInfoIds[std::size(kEVInfos)]; +static pkix::CertPolicyId sEVInfoIds[ArrayLength(kEVInfos)]; static_assert( - std::size(sEVInfoIds) == std::size(kEVInfos), + ArrayLength(sEVInfoIds) == ArrayLength(kEVInfos), "These arrays are used in parallel and must have the same length."); static pkix::CertPolicyId sCABForumEVId = {}; @@ -1304,7 +1304,7 @@ bool CertIsAuthoritativeForEVPolicy(const nsTArray& certBytes, return false; } - for (size_t i = 0; i < std::size(kEVInfos); ++i) { + for (size_t i = 0; i < ArrayLength(kEVInfos); ++i) { const EVInfo& entry = kEVInfos[i]; // This check ensures that only the specific roots we approve for EV get @@ -1338,7 +1338,7 @@ nsresult LoadExtendedValidationInfo() { sCABForumEVId.numBytes = cabforumOIDItem.len; PodCopy(sCABForumEVId.bytes, cabforumOIDItem.data, sCABForumEVId.numBytes); - for (size_t i = 0; i < std::size(kEVInfos); ++i) { + for (size_t i = 0; i < ArrayLength(kEVInfos); ++i) { const EVInfo& entry = kEVInfos[i]; SECStatus srv; diff --git a/security/certverifier/OCSPCache.cpp b/security/certverifier/OCSPCache.cpp index 8748da8459fdaf..152a153d31cde3 100644 --- a/security/certverifier/OCSPCache.cpp +++ b/security/certverifier/OCSPCache.cpp @@ -54,7 +54,7 @@ static SECStatus DigestLength(UniquePK11Context& context, uint32_t length) { array[0] = length & 255; array[1] = (length >> 8) & 255; - return PK11_DigestOp(context.get(), array, std::size(array)); + return PK11_DigestOp(context.get(), array, MOZ_ARRAY_LENGTH(array)); } // Let derIssuer be the DER encoding of the issuer of certID. diff --git a/security/manager/ssl/AppTrustDomain.cpp b/security/manager/ssl/AppTrustDomain.cpp index ab49d7eb1f3623..23ce9c6737f4ad 100644 --- a/security/manager/ssl/AppTrustDomain.cpp +++ b/security/manager/ssl/AppTrustDomain.cpp @@ -57,37 +57,40 @@ nsresult AppTrustDomain::SetTrustedRoot(AppTrustedRoot trustedRoot) { } switch (trustedRoot) { case nsIX509CertDB::AppXPCShellRoot: - mTrustedRoots.AppendElements(xpcshellRoots, std::size(xpcshellRoots)); + mTrustedRoots.AppendElements(xpcshellRoots, + MOZ_ARRAY_LENGTH(xpcshellRoots)); break; case nsIX509CertDB::AddonsPublicRoot: mTrustedRoots.AppendElements(addonsPublicRoots, - std::size(addonsPublicRoots)); + MOZ_ARRAY_LENGTH(addonsPublicRoots)); break; case nsIX509CertDB::AddonsStageRoot: mTrustedRoots.AppendElements(addonsStageRoots, - std::size(addonsStageRoots)); + MOZ_ARRAY_LENGTH(addonsStageRoots)); break; case nsIContentSignatureVerifier::ContentSignatureLocalRoot: - mTrustedRoots.AppendElements(contentSignatureLocalRoots, - std::size(contentSignatureLocalRoots)); + mTrustedRoots.AppendElements( + contentSignatureLocalRoots, + MOZ_ARRAY_LENGTH(contentSignatureLocalRoots)); break; case nsIContentSignatureVerifier::ContentSignatureProdRoot: mTrustedRoots.AppendElements(contentSignatureProdRoots, - std::size(contentSignatureProdRoots)); + MOZ_ARRAY_LENGTH(contentSignatureProdRoots)); break; case nsIContentSignatureVerifier::ContentSignatureStageRoot: - mTrustedRoots.AppendElements(contentSignatureStageRoots, - std::size(contentSignatureStageRoots)); + mTrustedRoots.AppendElements( + contentSignatureStageRoots, + MOZ_ARRAY_LENGTH(contentSignatureStageRoots)); break; case nsIContentSignatureVerifier::ContentSignatureDevRoot: mTrustedRoots.AppendElements(contentSignatureDevRoots, - std::size(contentSignatureDevRoots)); + MOZ_ARRAY_LENGTH(contentSignatureDevRoots)); break; default: @@ -99,14 +102,14 @@ nsresult AppTrustDomain::SetTrustedRoot(AppTrustedRoot trustedRoot) { // The intermediate bundled with signed XPI files may have expired and be // considered invalid, which can result in bug 1548973. if (trustedRoot == nsIX509CertDB::AddonsPublicRoot) { - mAddonsIntermediates.AppendElements(addonsPublicIntermediates, - std::size(addonsPublicIntermediates)); + mAddonsIntermediates.AppendElements( + addonsPublicIntermediates, MOZ_ARRAY_LENGTH(addonsPublicIntermediates)); } // Similarly to the above logic for production, we hardcode the intermediate // stage certificate here, so that stage is equivalent to production. if (trustedRoot == nsIX509CertDB::AddonsStageRoot) { - mAddonsIntermediates.AppendElements(addonsStageIntermediates, - std::size(addonsStageIntermediates)); + mAddonsIntermediates.AppendElements( + addonsStageIntermediates, MOZ_ARRAY_LENGTH(addonsStageIntermediates)); } return NS_OK; diff --git a/security/manager/ssl/EnterpriseRoots.cpp b/security/manager/ssl/EnterpriseRoots.cpp index f172157de2bf49..8eabb296ef8bdd 100644 --- a/security/manager/ssl/EnterpriseRoots.cpp +++ b/security/manager/ssl/EnterpriseRoots.cpp @@ -413,11 +413,11 @@ OSStatus GatherEnterpriseCertsMacOS(nsTArray& certs, // this query. Further work (below) filters such certificates out. const CFStringRef keys[] = {kSecClass, kSecMatchLimit}; const void* values[] = {kSecClassCertificate, kSecMatchLimitAll}; - static_assert(std::size(keys) == std::size(values), + static_assert(ArrayLength(keys) == ArrayLength(values), "mismatched SecItemCopyMatching key/value array sizes"); // https://developer.apple.com/documentation/corefoundation/1516782-cfdictionarycreate ScopedCFType searchDictionary(CFDictionaryCreate( - nullptr, (const void**)&keys, (const void**)&values, std::size(keys), + nullptr, (const void**)&keys, (const void**)&values, ArrayLength(keys), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); CFTypeRef items; // https://developer.apple.com/documentation/security/1398306-secitemcopymatching diff --git a/security/manager/ssl/KeychainSecret.cpp b/security/manager/ssl/KeychainSecret.cpp index 3faa5dc7107c86..4b0d2bf5fdbbc1 100644 --- a/security/manager/ssl/KeychainSecret.cpp +++ b/security/manager/ssl/KeychainSecret.cpp @@ -68,10 +68,10 @@ nsresult KeychainSecret::StoreSecret(const nsACString& aSecret, return NS_ERROR_FAILURE; } const void* values[] = {kSecClassGenericPassword, label.get(), secret.get()}; - static_assert(std::size(keys) == std::size(values), + static_assert(ArrayLength(keys) == ArrayLength(values), "mismatched SecItemAdd key/value array sizes"); ScopedCFType addDictionary(CFDictionaryCreate( - nullptr, (const void**)&keys, (const void**)&values, std::size(keys), + nullptr, (const void**)&keys, (const void**)&values, ArrayLength(keys), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); // https://developer.apple.com/documentation/security/1401659-secitemadd OSStatus osrv = SecItemAdd(addDictionary.get(), nullptr); @@ -96,10 +96,10 @@ nsresult KeychainSecret::DeleteSecret(const nsACString& aLabel) { return NS_ERROR_FAILURE; } const void* values[] = {kSecClassGenericPassword, label.get()}; - static_assert(std::size(keys) == std::size(values), + static_assert(ArrayLength(keys) == ArrayLength(values), "mismatched SecItemDelete key/value array sizes"); ScopedCFType deleteDictionary(CFDictionaryCreate( - nullptr, (const void**)&keys, (const void**)&values, std::size(keys), + nullptr, (const void**)&keys, (const void**)&values, ArrayLength(keys), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); // https://developer.apple.com/documentation/security/1395547-secitemdelete OSStatus rv = SecItemDelete(deleteDictionary.get()); @@ -132,10 +132,10 @@ nsresult KeychainSecret::RetrieveSecret(const nsACString& aLabel, } const void* values[] = {kSecClassGenericPassword, label.get(), kSecMatchLimitOne, kCFBooleanTrue, kCFBooleanTrue}; - static_assert(std::size(keys) == std::size(values), + static_assert(ArrayLength(keys) == ArrayLength(values), "mismatched SecItemCopyMatching key/value array sizes"); ScopedCFType searchDictionary(CFDictionaryCreate( - nullptr, (const void**)&keys, (const void**)&values, std::size(keys), + nullptr, (const void**)&keys, (const void**)&values, ArrayLength(keys), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); CFTypeRef item; // https://developer.apple.com/documentation/security/1398306-secitemcopymatching diff --git a/security/manager/ssl/NSSSocketControl.cpp b/security/manager/ssl/NSSSocketControl.cpp index 27ba9d10396945..e9f16f0179bd12 100644 --- a/security/manager/ssl/NSSSocketControl.cpp +++ b/security/manager/ssl/NSSSocketControl.cpp @@ -203,7 +203,7 @@ NSSSocketControl::GetAlpnEarlySelection(nsACString& aAlpnSelected) { unsigned char chosenAlpn[MAX_ALPN_LENGTH]; unsigned int chosenAlpnLen; rv = SSL_GetNextProto(mFd, &alpnState, chosenAlpn, &chosenAlpnLen, - AssertedCast(std::size(chosenAlpn))); + AssertedCast(ArrayLength(chosenAlpn))); if (rv != SECSuccess) { return NS_ERROR_NOT_AVAILABLE; diff --git a/security/manager/ssl/PublicKeyPinningService.cpp b/security/manager/ssl/PublicKeyPinningService.cpp index bb1fd8ac496f9d..e3d02ce326d4c8 100644 --- a/security/manager/ssl/PublicKeyPinningService.cpp +++ b/security/manager/ssl/PublicKeyPinningService.cpp @@ -206,7 +206,7 @@ static nsresult FindPinningInformation( ("pkpin: Querying pinsets for host: '%s'\n", evalHost)); size_t foundEntryIndex; if (BinarySearchIf(kPublicKeyPinningPreloadList, 0, - std::size(kPublicKeyPinningPreloadList), + ArrayLength(kPublicKeyPinningPreloadList), TransportSecurityPreloadBinarySearchComparator(evalHost), &foundEntryIndex)) { foundEntry = &kPublicKeyPinningPreloadList[foundEntryIndex]; diff --git a/security/manager/ssl/RootCertificateTelemetryUtils.cpp b/security/manager/ssl/RootCertificateTelemetryUtils.cpp index 48bc7c0b9a246f..0b4c9968f947bd 100644 --- a/security/manager/ssl/RootCertificateTelemetryUtils.cpp +++ b/security/manager/ssl/RootCertificateTelemetryUtils.cpp @@ -64,7 +64,7 @@ int32_t RootCABinNumber(Span cert) { digestArray.ElementAt(0), digestArray.ElementAt(1), digestArray.ElementAt(2), digestArray.ElementAt(3))); - if (mozilla::BinarySearchIf(ROOT_TABLE, 0, std::size(ROOT_TABLE), + if (mozilla::BinarySearchIf(ROOT_TABLE, 0, ArrayLength(ROOT_TABLE), BinaryHashSearchArrayComparator( digestArray.Elements(), digestArray.Length()), &idx)) { diff --git a/security/manager/ssl/nsNSSCallbacks.cpp b/security/manager/ssl/nsNSSCallbacks.cpp index 1abe27c0148372..79d95a4a208145 100644 --- a/security/manager/ssl/nsNSSCallbacks.cpp +++ b/security/manager/ssl/nsNSSCallbacks.cpp @@ -764,7 +764,7 @@ static void PreliminaryHandshakeDone(PRFileDesc* fd) { unsigned int npnlen; if (SSL_GetNextProto(fd, &state, npnbuf, &npnlen, - AssertedCast(std::size(npnbuf))) == + AssertedCast(ArrayLength(npnbuf))) == SECSuccess) { if (state == SSL_NEXT_PROTO_NEGOTIATED || state == SSL_NEXT_PROTO_SELECTED) { diff --git a/security/manager/ssl/nsNSSIOLayer.cpp b/security/manager/ssl/nsNSSIOLayer.cpp index 80134073af0a03..9892f7ec6b1bd8 100644 --- a/security/manager/ssl/nsNSSIOLayer.cpp +++ b/security/manager/ssl/nsNSSIOLayer.cpp @@ -1573,8 +1573,8 @@ static nsresult nsSSLIOLayerSetOptions(PRFileDesc* fd, bool forSTARTTLS, ssl_grp_kem_mlkem768x25519, ssl_grp_ec_curve25519, ssl_grp_ec_secp256r1, ssl_grp_ec_secp384r1, ssl_grp_ec_secp521r1, ssl_grp_ffdhe_2048, ssl_grp_ffdhe_3072}; - if (SECSuccess != - SSL_NamedGroupConfig(fd, namedGroups, std::size(namedGroups))) { + if (SECSuccess != SSL_NamedGroupConfig(fd, namedGroups, + mozilla::ArrayLength(namedGroups))) { return NS_ERROR_FAILURE; } additional_shares += 1; @@ -1584,8 +1584,8 @@ static nsresult nsSSLIOLayerSetOptions(PRFileDesc* fd, bool forSTARTTLS, ssl_grp_ec_curve25519, ssl_grp_ec_secp256r1, ssl_grp_ec_secp384r1, ssl_grp_ec_secp521r1, ssl_grp_ffdhe_2048, ssl_grp_ffdhe_3072}; // Skip the |ssl_grp_kem_mlkem768x25519| entry. - if (SECSuccess != - SSL_NamedGroupConfig(fd, namedGroups, std::size(namedGroups))) { + if (SECSuccess != SSL_NamedGroupConfig(fd, namedGroups, + mozilla::ArrayLength(namedGroups))) { return NS_ERROR_FAILURE; } } @@ -1632,9 +1632,9 @@ static nsresult nsSSLIOLayerSetOptions(PRFileDesc* fd, bool forSTARTTLS, // is properly rejected. NSS will not advertise PKCS1 or RSAE schemes (which // the |ssl_sig_rsa_pss_*| defines alias, meaning we will not currently accept // any RSA DC. - if (SECSuccess != - SSL_SignatureSchemePrefSet(fd, sEnabledSignatureSchemes, - std::size(sEnabledSignatureSchemes))) { + if (SECSuccess != SSL_SignatureSchemePrefSet( + fd, sEnabledSignatureSchemes, + mozilla::ArrayLength(sEnabledSignatureSchemes))) { return NS_ERROR_FAILURE; } diff --git a/security/manager/ssl/tests/unit/tlsserver/cmd/FaultyServer.cpp b/security/manager/ssl/tests/unit/tlsserver/cmd/FaultyServer.cpp index f2c8d8fc1cbbf3..ba48016f5847ef 100644 --- a/security/manager/ssl/tests/unit/tlsserver/cmd/FaultyServer.cpp +++ b/security/manager/ssl/tests/unit/tlsserver/cmd/FaultyServer.cpp @@ -232,7 +232,7 @@ int32_t DoSNISocketConfig(PRFileDesc* aFd, const SECItem* aSrvNameArr, case Mlkem768x25519: SSL_SecretCallback(aFd, &SecretCallbackFailMlkem768x25519, (void*)host); SSL_NamedGroupConfig(aFd, mlkemTestNamedGroups, - std::size(mlkemTestNamedGroups)); + mozilla::ArrayLength(mlkemTestNamedGroups)); break; case None: break; diff --git a/security/sandbox/linux/SandboxInfo.cpp b/security/sandbox/linux/SandboxInfo.cpp index b3bc13848396d5..b060961cb995ee 100644 --- a/security/sandbox/linux/SandboxInfo.cpp +++ b/security/sandbox/linux/SandboxInfo.cpp @@ -102,7 +102,7 @@ static bool HasUserNamespaceSupport() { "/proc/self/ns/net", "/proc/self/ns/ipc", }; - for (size_t i = 0; i < std::size(paths); ++i) { + for (size_t i = 0; i < ArrayLength(paths); ++i) { if (access(paths[i], F_OK) == -1) { MOZ_ASSERT(errno == ENOENT); return false; diff --git a/security/sandbox/linux/launch/SandboxLaunch.cpp b/security/sandbox/linux/launch/SandboxLaunch.cpp index cd64eb4b1dc8ac..0080f2378b0e79 100644 --- a/security/sandbox/linux/launch/SandboxLaunch.cpp +++ b/security/sandbox/linux/launch/SandboxLaunch.cpp @@ -515,7 +515,7 @@ MOZ_NEVER_INLINE MOZ_ASAN_IGNORE static pid_t DoClone(int aFlags, #ifdef __hppa__ void* stackPtr = miniStack; #else - void* stackPtr = std::end(miniStack); + void* stackPtr = ArrayEnd(miniStack); #endif return clone(CloneCallee, stackPtr, aFlags, aCtx); } diff --git a/storage/SQLCollations.cpp b/storage/SQLCollations.cpp index 3c3c9e8cba47c3..3cbeafe5d0be7d 100644 --- a/storage/SQLCollations.cpp +++ b/storage/SQLCollations.cpp @@ -115,7 +115,7 @@ int registerCollations(sqlite3* aDB, Service* aService) { }; int rv = SQLITE_OK; - for (size_t i = 0; SQLITE_OK == rv && i < std::size(collations); ++i) { + for (size_t i = 0; SQLITE_OK == rv && i < ArrayLength(collations); ++i) { struct Collations* p = &collations[i]; rv = ::sqlite3_create_collation(aDB, p->zName, p->enc, aService, p->xCompare); diff --git a/storage/mozStorageSQLFunctions.cpp b/storage/mozStorageSQLFunctions.cpp index 32913ed204e924..c05010c2ff1e96 100644 --- a/storage/mozStorageSQLFunctions.cpp +++ b/storage/mozStorageSQLFunctions.cpp @@ -247,7 +247,7 @@ int registerFunctions(sqlite3* aDB) { }; int rv = SQLITE_OK; - for (size_t i = 0; SQLITE_OK == rv && i < std::size(functions); ++i) { + for (size_t i = 0; SQLITE_OK == rv && i < ArrayLength(functions); ++i) { struct Functions* p = &functions[i]; rv = ::sqlite3_create_function(aDB, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, nullptr, nullptr); diff --git a/storage/test/gtest/test_binding_params.cpp b/storage/test/gtest/test_binding_params.cpp index f70c865de51449..a9ca1799f9823b 100644 --- a/storage/test/gtest/test_binding_params.cpp +++ b/storage/test/gtest/test_binding_params.cpp @@ -69,8 +69,8 @@ TEST(storage_binding_params, CString) // Roundtrip a string through the table, and ensure it comes out as expected. static const char sCharArray[] = "I'm not a \xff\x00\xac\xde\xbb ASCII string!"; - nsAutoCString inserted(sCharArray, std::size(sCharArray) - 1); - do_check_true(inserted.Length() == std::size(sCharArray) - 1); + nsAutoCString inserted(sCharArray, ArrayLength(sCharArray) - 1); + do_check_true(inserted.Length() == ArrayLength(sCharArray) - 1); { mozStorageStatementScoper scoper(insert); bool hasResult; @@ -109,8 +109,8 @@ TEST(storage_binding_params, UTFStrings) // Roundtrip a UTF8 string through the table, using UTF8 input and output. static const char sCharArray[] = R"(I'm a ûüâäç UTF8 string!)"; - nsAutoCString insertedUTF8(sCharArray, std::size(sCharArray) - 1); - do_check_true(insertedUTF8.Length() == std::size(sCharArray) - 1); + nsAutoCString insertedUTF8(sCharArray, ArrayLength(sCharArray) - 1); + do_check_true(insertedUTF8.Length() == ArrayLength(sCharArray) - 1); NS_ConvertUTF8toUTF16 insertedUTF16(insertedUTF8); do_check_true(insertedUTF8 == NS_ConvertUTF16toUTF8(insertedUTF16)); { diff --git a/toolkit/components/aboutthirdparty/tests/gtest/TestAboutThirdParty.cpp b/toolkit/components/aboutthirdparty/tests/gtest/TestAboutThirdParty.cpp index 55b8d5f64afc61..565e87e0f1dbc9 100644 --- a/toolkit/components/aboutthirdparty/tests/gtest/TestAboutThirdParty.cpp +++ b/toolkit/components/aboutthirdparty/tests/gtest/TestAboutThirdParty.cpp @@ -103,8 +103,8 @@ TEST(AboutThirdParty, InstallLocations) {u"C:\\duplicate\\sub\\file.dll"_ns, u""_ns}, }; - nsTArray locations(std::size(kDirectoriesUnsorted)); - for (size_t i = 0; i < std::size(kDirectoriesUnsorted); ++i) { + nsTArray locations(ArrayLength(kDirectoriesUnsorted)); + for (size_t i = 0; i < ArrayLength(kDirectoriesUnsorted); ++i) { locations.EmplaceBack(kDirectoriesUnsorted[i], new InstalledApplication()); } diff --git a/toolkit/components/antitracking/bouncetrackingprotection/ClearDataCallback.cpp b/toolkit/components/antitracking/bouncetrackingprotection/ClearDataCallback.cpp index ecd729cd4df765..590a365894b585 100644 --- a/toolkit/components/antitracking/bouncetrackingprotection/ClearDataCallback.cpp +++ b/toolkit/components/antitracking/bouncetrackingprotection/ClearDataCallback.cpp @@ -26,7 +26,7 @@ static constexpr nsLiteralCString kUrlClassifierFeatures[] = { "socialtracking-protection"_ns, "tracking-protection"_ns, }; -static_assert(std::size(kUrlClassifierFeatures) > 0, +static_assert(ArrayLength(kUrlClassifierFeatures) > 0, "At least one URL classifier feature must be defined"); // List of features for classifying bounce trackers that have been purged. diff --git a/toolkit/components/formautofill/FormAutofillNative.cpp b/toolkit/components/formautofill/FormAutofillNative.cpp index 7bfb634fe30f0d..08c462aa4407c1 100644 --- a/toolkit/components/formautofill/FormAutofillNative.cpp +++ b/toolkit/components/formautofill/FormAutofillNative.cpp @@ -679,10 +679,10 @@ class FormAutofillImpl { FormAutofillImpl::FormAutofillImpl() { const Rule* rulesets[] = {&kFirefoxRules[0], &kCreditCardRules[0]}; - size_t rulesetLengths[] = {std::size(kFirefoxRules), - std::size(kCreditCardRules)}; + size_t rulesetLengths[] = {ArrayLength(kFirefoxRules), + ArrayLength(kCreditCardRules)}; - for (uint32_t i = 0; i < std::size(rulesetLengths); ++i) { + for (uint32_t i = 0; i < ArrayLength(rulesetLengths); ++i) { for (uint32_t j = 0; j < rulesetLengths[i]; ++j) { nsCString& rule = mRuleMap[rulesets[i][j].key]; if (!rule.IsEmpty()) { diff --git a/toolkit/components/places/tests/gtest/places_test_harness_tail.h b/toolkit/components/places/tests/gtest/places_test_harness_tail.h index 5c05ced2188df7..27de44eaa9f169 100644 --- a/toolkit/components/places/tests/gtest/places_test_harness_tail.h +++ b/toolkit/components/places/tests/gtest/places_test_harness_tail.h @@ -21,7 +21,7 @@ class RunNextTest : public mozilla::Runnable { RunNextTest() : mozilla::Runnable("RunNextTest") {} NS_IMETHOD Run() override { MOZ_RELEASE_ASSERT(NS_IsMainThread(), "Not running on the main thread?"); - if (gTestsIndex < int(std::size(gTests))) { + if (gTestsIndex < int(mozilla::ArrayLength(gTests))) { do_test_pending(); Test& test = gTests[gTestsIndex++]; (void)fprintf(stderr, TEST_INFO_STR "Running %s.\n", test.name); diff --git a/toolkit/components/remote/nsXRemoteClient.cpp b/toolkit/components/remote/nsXRemoteClient.cpp index dadf709655888d..631df65c87a6b2 100644 --- a/toolkit/components/remote/nsXRemoteClient.cpp +++ b/toolkit/components/remote/nsXRemoteClient.cpp @@ -85,7 +85,7 @@ static const char* XAtomNames[] = { MOZILLA_VERSION_PROP, MOZILLA_LOCK_PROP, MOZILLA_RESPONSE_PROP, "WM_STATE", MOZILLA_USER_PROP, MOZILLA_PROFILE_PROP, MOZILLA_PROGRAM_PROP, MOZILLA_COMMANDLINE_PROP}; -static Atom XAtoms[std::size(XAtomNames)]; +static Atom XAtoms[MOZ_ARRAY_LENGTH(XAtomNames)]; nsresult nsXRemoteClient::Init() { MOZ_LOG(sRemoteLm, LogLevel::Debug, ("nsXRemoteClient::Init")); @@ -97,8 +97,8 @@ nsresult nsXRemoteClient::Init() { if (!mDisplay) return NS_ERROR_FAILURE; // get our atoms - XInternAtoms(mDisplay, const_cast(XAtomNames), std::size(XAtomNames), - False, XAtoms); + XInternAtoms(mDisplay, const_cast(XAtomNames), + MOZ_ARRAY_LENGTH(XAtomNames), False, XAtoms); int i = 0; mMozVersionAtom = XAtoms[i++]; diff --git a/toolkit/components/remote/nsXRemoteServer.cpp b/toolkit/components/remote/nsXRemoteServer.cpp index a6ca775cf7db71..745d8f015c40f1 100644 --- a/toolkit/components/remote/nsXRemoteServer.cpp +++ b/toolkit/components/remote/nsXRemoteServer.cpp @@ -43,7 +43,7 @@ static const char* XAtomNames[] = { MOZILLA_VERSION_PROP, MOZILLA_LOCK_PROP, MOZILLA_RESPONSE_PROP, MOZILLA_USER_PROP, MOZILLA_PROFILE_PROP, MOZILLA_PROGRAM_PROP, MOZILLA_COMMANDLINE_PROP}; -static Atom XAtoms[std::size(XAtomNames)]; +static Atom XAtoms[MOZ_ARRAY_LENGTH(XAtomNames)]; Atom nsXRemoteServer::sMozVersionAtom; Atom nsXRemoteServer::sMozLockAtom; @@ -152,7 +152,7 @@ void nsXRemoteServer::EnsureAtoms(void) { if (sMozVersionAtom) return; XInternAtoms(mozilla::DefaultXDisplay(), const_cast(XAtomNames), - std::size(XAtomNames), X11False, XAtoms); + ArrayLength(XAtomNames), X11False, XAtoms); int i = 0; sMozVersionAtom = XAtoms[i++]; diff --git a/toolkit/components/reputationservice/ApplicationReputation.cpp b/toolkit/components/reputationservice/ApplicationReputation.cpp index 4100dddee47fae..8973fc85bbffdb 100644 --- a/toolkit/components/reputationservice/ApplicationReputation.cpp +++ b/toolkit/components/reputationservice/ApplicationReputation.cpp @@ -60,6 +60,7 @@ #include "ApplicationReputationTelemetryUtils.h" +using mozilla::ArrayLength; using mozilla::BasePrincipal; using mozilla::OriginAttributes; using mozilla::Preferences; @@ -937,7 +938,7 @@ static const char* GetFileExt(const nsACString& aFilename, } static const char* GetFileExt(const nsACString& aFilename) { -#define _GetFileExt(_f, _l) GetFileExt(_f, _l, std::size(_l)) +#define _GetFileExt(_f, _l) GetFileExt(_f, _l, ArrayLength(_l)) const char* ext = _GetFileExt( aFilename, ApplicationReputationService::kBinaryFileExtensions); if (ext == nullptr && @@ -956,13 +957,15 @@ static bool IsFileType(const nsACString& aFilename, } static bool IsBinary(const nsACString& aFilename) { - return IsFileType( - aFilename, ApplicationReputationService::kBinaryFileExtensions, - std::size(ApplicationReputationService::kBinaryFileExtensions)) || + return IsFileType(aFilename, + ApplicationReputationService::kBinaryFileExtensions, + ArrayLength( + ApplicationReputationService::kBinaryFileExtensions)) || (!IsFileType( aFilename, ApplicationReputationService::kNonBinaryExecutables, - std::size(ApplicationReputationService::kNonBinaryExecutables)) && - IsFileType(aFilename, sExecutableExts, std::size(sExecutableExts))); + ArrayLength( + ApplicationReputationService::kNonBinaryExecutables)) && + IsFileType(aFilename, sExecutableExts, ArrayLength(sExecutableExts))); } ClientDownloadRequest::DownloadType PendingLookup::GetDownloadType( @@ -1057,12 +1060,12 @@ nsresult PendingLookup::LookupNext() { mozilla::Telemetry::LABELS_APPLICATION_REPUTATION_BINARY_TYPE:: BinaryFile); } else if (IsFileType(mFileName, kSafeFileExtensions, - std::size(kSafeFileExtensions))) { + ArrayLength(kSafeFileExtensions))) { AccumulateCategorical( mozilla::Telemetry::LABELS_APPLICATION_REPUTATION_BINARY_TYPE:: NonBinaryFile); } else if (IsFileType(mFileName, kMozNonBinaryExecutables, - std::size(kMozNonBinaryExecutables))) { + ArrayLength(kMozNonBinaryExecutables))) { AccumulateCategorical( mozilla::Telemetry::LABELS_APPLICATION_REPUTATION_BINARY_TYPE:: MozNonBinaryFile); @@ -1078,17 +1081,17 @@ nsresult PendingLookup::LookupNext() { } if (IsFileType(mFileName, kDmgFileExtensions, - std::size(kDmgFileExtensions))) { + ArrayLength(kDmgFileExtensions))) { AccumulateCategorical( mozilla::Telemetry::LABELS_APPLICATION_REPUTATION_BINARY_ARCHIVE:: DmgFile); } else if (IsFileType(mFileName, kRarFileExtensions, - std::size(kRarFileExtensions))) { + ArrayLength(kRarFileExtensions))) { AccumulateCategorical( mozilla::Telemetry::LABELS_APPLICATION_REPUTATION_BINARY_ARCHIVE:: RarFile); } else if (IsFileType(mFileName, kZipFileExtensions, - std::size(kZipFileExtensions))) { + ArrayLength(kZipFileExtensions))) { AccumulateCategorical( mozilla::Telemetry::LABELS_APPLICATION_REPUTATION_BINARY_ARCHIVE:: ZipFile); @@ -1558,7 +1561,7 @@ nsresult PendingLookup::ParseCertificates( nsresult PendingLookup::SendRemoteQuery() { MOZ_ASSERT(!IsFileType( mFileName, ApplicationReputationService::kNonBinaryExecutables, - std::size(ApplicationReputationService::kNonBinaryExecutables))); + ArrayLength(ApplicationReputationService::kNonBinaryExecutables))); Reason reason = Reason::NotSet; nsresult rv = SendRemoteQueryInternal(reason); if (NS_FAILED(rv)) { @@ -1979,6 +1982,6 @@ nsresult ApplicationReputationService::IsBinary(const nsACString& aFileName, nsresult ApplicationReputationService::IsExecutable(const nsACString& aFileName, bool* aExecutable) { *aExecutable = - ::IsFileType(aFileName, sExecutableExts, std::size(sExecutableExts)); + ::IsFileType(aFileName, sExecutableExts, ArrayLength(sExecutableExts)); return NS_OK; } diff --git a/toolkit/components/reputationservice/test/gtest/TestExecutableLists.cpp b/toolkit/components/reputationservice/test/gtest/TestExecutableLists.cpp index 2db14aa7430ae1..c5fadb62e07ae7 100644 --- a/toolkit/components/reputationservice/test/gtest/TestExecutableLists.cpp +++ b/toolkit/components/reputationservice/test/gtest/TestExecutableLists.cpp @@ -310,7 +310,7 @@ static const char* const kTestFileExtensions[] = { #define CheckListSorted(_list) \ { \ - for (size_t i = 1; i < std::size(_list); ++i) { \ + for (size_t i = 1; i < mozilla::ArrayLength(_list); ++i) { \ nsDependentCString str1((_list)[i - 1]); \ nsDependentCString str2((_list)[i]); \ EXPECT_LE(Compare(str1, str2), -1) \ @@ -341,7 +341,8 @@ bool _IsInList(const char* ext, const char* const _list[], const size_t len) { return false; } -#define IsInList(_ext, _list) _IsInList(_ext, _list, std::size(_list)) +#define IsInList(_ext, _list) \ + _IsInList(_ext, _list, mozilla::ArrayLength(_list)) TEST(TestExecutableLists, NonBinariesInExecutablesList) { diff --git a/toolkit/components/resistfingerprinting/nsRFPService.cpp b/toolkit/components/resistfingerprinting/nsRFPService.cpp index bd11b0136e6a00..e169118de10afb 100644 --- a/toolkit/components/resistfingerprinting/nsRFPService.cpp +++ b/toolkit/components/resistfingerprinting/nsRFPService.cpp @@ -913,11 +913,12 @@ void nsRFPService::GetSpoofedUserAgent(nsACString& userAgent, // These magic numbers are the lengths of the UA string literals below. // Assume three-digit Firefox version numbers so we have room to grow. - size_t preallocatedLength = 13 + - (isForHTTPHeader ? std::size(SPOOFED_HTTP_UA_OS) - : std::size(SPOOFED_UA_OS)) - - 1 + 5 + 3 + 10 + - std::size(LEGACY_UA_GECKO_TRAIL) - 1 + 9 + 3 + 2; + size_t preallocatedLength = + 13 + + (isForHTTPHeader ? mozilla::ArrayLength(SPOOFED_HTTP_UA_OS) + : mozilla::ArrayLength(SPOOFED_UA_OS)) - + 1 + 5 + 3 + 10 + mozilla::ArrayLength(LEGACY_UA_GECKO_TRAIL) - 1 + 9 + 3 + + 2; userAgent.SetCapacity(preallocatedLength); // "Mozilla/5.0 (%s; rv:%d.0) Gecko/%d Firefox/%d.0" diff --git a/toolkit/components/telemetry/tests/gtest/TestCombinedStacks.cpp b/toolkit/components/telemetry/tests/gtest/TestCombinedStacks.cpp index 0c6ed8c0f27d43..3e21c7378c3044 100644 --- a/toolkit/components/telemetry/tests/gtest/TestCombinedStacks.cpp +++ b/toolkit/components/telemetry/tests/gtest/TestCombinedStacks.cpp @@ -101,16 +101,16 @@ TEST(CombinedStacks, Combine) combined2.AddStack(testStacks[2]); combined2.AddStack(testStacks[3]); - EXPECT_EQ(combined1.GetModuleCount(), std::size(moduleSet1)); + EXPECT_EQ(combined1.GetModuleCount(), mozilla::ArrayLength(moduleSet1)); EXPECT_EQ(combined1.GetStackCount(), 2u); - EXPECT_EQ(combined2.GetModuleCount(), std::size(moduleSet2) - 1); + EXPECT_EQ(combined2.GetModuleCount(), mozilla::ArrayLength(moduleSet2) - 1); EXPECT_EQ(combined2.GetStackCount(), 2u); // combined1 <-- combined1 + combined2 combined1.AddStacks(combined2); EXPECT_EQ(combined1.GetModuleCount(), 5u); // {mod1, mod2, modX, modZ, base} - EXPECT_EQ(combined1.GetStackCount(), std::size(testStacks)); + EXPECT_EQ(combined1.GetStackCount(), mozilla::ArrayLength(testStacks)); for (size_t i = 0; i < combined1.GetStackCount(); ++i) { const auto& expectedStack = testStacks[i]; diff --git a/toolkit/components/terminator/nsTerminator.cpp b/toolkit/components/terminator/nsTerminator.cpp index 00557ad9e2de73..6339962022cbb7 100644 --- a/toolkit/components/terminator/nsTerminator.cpp +++ b/toolkit/components/terminator/nsTerminator.cpp @@ -209,7 +209,7 @@ void RunWatchdog(void* arg) { // the observer that triggers UpdateHeartbeat was not called // at all or in the expected order on some step. This should // give us always the last known ShutdownStep. - for (int i = std::size(sShutdownSteps) - 1; i >= 0; --i) { + for (int i = ArrayLength(sShutdownSteps) - 1; i >= 0; --i) { if (sShutdownSteps[i].mTicks > -1) { lastPhase = sShutdownSteps[i].mPhase; break; diff --git a/toolkit/components/url-classifier/nsUrlClassifierUtils.cpp b/toolkit/components/url-classifier/nsUrlClassifierUtils.cpp index 4181b189ac80cb..6a329830d6f09d 100644 --- a/toolkit/components/url-classifier/nsUrlClassifierUtils.cpp +++ b/toolkit/components/url-classifier/nsUrlClassifierUtils.cpp @@ -333,7 +333,7 @@ static const struct { NS_IMETHODIMP nsUrlClassifierUtils::ConvertThreatTypeToListNames(uint32_t aThreatType, nsACString& aListNames) { - for (uint32_t i = 0; i < std::size(THREAT_TYPE_CONV_TABLE); i++) { + for (uint32_t i = 0; i < ArrayLength(THREAT_TYPE_CONV_TABLE); i++) { if (aThreatType == THREAT_TYPE_CONV_TABLE[i].mThreatType) { if (!aListNames.IsEmpty()) { aListNames.AppendLiteral(","); @@ -348,7 +348,7 @@ nsUrlClassifierUtils::ConvertThreatTypeToListNames(uint32_t aThreatType, NS_IMETHODIMP nsUrlClassifierUtils::ConvertListNameToThreatType(const nsACString& aListName, uint32_t* aThreatType) { - for (uint32_t i = 0; i < std::size(THREAT_TYPE_CONV_TABLE); i++) { + for (uint32_t i = 0; i < ArrayLength(THREAT_TYPE_CONV_TABLE); i++) { if (aListName.EqualsASCII(THREAT_TYPE_CONV_TABLE[i].mListName)) { *aThreatType = THREAT_TYPE_CONV_TABLE[i].mThreatType; return NS_OK; diff --git a/toolkit/components/url-classifier/tests/gtest/TestChunkSet.cpp b/toolkit/components/url-classifier/tests/gtest/TestChunkSet.cpp index 4ffed5d87d6c22..6835103b303682 100644 --- a/toolkit/components/url-classifier/tests/gtest/TestChunkSet.cpp +++ b/toolkit/components/url-classifier/tests/gtest/TestChunkSet.cpp @@ -40,11 +40,11 @@ TEST(UrlClassifierChunkSet, Main) mozilla::safebrowsing::ChunkSet chunkSet; - for (size_t i = 0; i < std::size(testVals); i++) { + for (size_t i = 0; i < MOZ_ARRAY_LENGTH(testVals); i++) { chunkSet.Set(testVals[i]); } - for (size_t i = 0; i < std::size(testVals); i++) { + for (size_t i = 0; i < MOZ_ARRAY_LENGTH(testVals); i++) { ASSERT_TRUE(chunkSet.Has(testVals[i])); } @@ -53,7 +53,7 @@ TEST(UrlClassifierChunkSet, Main) ASSERT_FALSE(chunkSet.Has(9)); ASSERT_FALSE(chunkSet.Has(11)); - ASSERT_TRUE(chunkSet.Length() == std::size(testVals)); + ASSERT_TRUE(chunkSet.Length() == MOZ_ARRAY_LENGTH(testVals)); } TEST(UrlClassifierChunkSet, Merge) @@ -64,26 +64,26 @@ TEST(UrlClassifierChunkSet, Merge) mozilla::safebrowsing::ChunkSet chunkSet; mozilla::safebrowsing::ChunkSet mergeSet; - for (size_t i = 0; i < std::size(testVals); i++) { + for (size_t i = 0; i < MOZ_ARRAY_LENGTH(testVals); i++) { chunkSet.Set(testVals[i]); } - for (size_t i = 0; i < std::size(mergeVals); i++) { + for (size_t i = 0; i < MOZ_ARRAY_LENGTH(mergeVals); i++) { mergeSet.Set(mergeVals[i]); } chunkSet.Merge(mergeSet); - for (size_t i = 0; i < std::size(testVals); i++) { + for (size_t i = 0; i < MOZ_ARRAY_LENGTH(testVals); i++) { ASSERT_TRUE(chunkSet.Has(testVals[i])); } - for (size_t i = 0; i < std::size(mergeVals); i++) { + for (size_t i = 0; i < MOZ_ARRAY_LENGTH(mergeVals); i++) { ASSERT_TRUE(chunkSet.Has(mergeVals[i])); } // -1 because 14 is duplicated in both sets ASSERT_TRUE(chunkSet.Length() == - std::size(testVals) + std::size(mergeVals) - 1); + MOZ_ARRAY_LENGTH(testVals) + MOZ_ARRAY_LENGTH(mergeVals) - 1); ASSERT_FALSE(chunkSet.Has(11)); ASSERT_FALSE(chunkSet.Has(15)); @@ -102,27 +102,27 @@ TEST(UrlClassifierChunkSet, Merge2) mozilla::safebrowsing::ChunkSet mergeSet; mozilla::safebrowsing::ChunkSet mergeSet2; - for (size_t i = 0; i < std::size(testVals); i++) { + for (size_t i = 0; i < MOZ_ARRAY_LENGTH(testVals); i++) { chunkSet.Set(testVals[i]); } - for (size_t i = 0; i < std::size(mergeVals); i++) { + for (size_t i = 0; i < MOZ_ARRAY_LENGTH(mergeVals); i++) { mergeSet.Set(mergeVals[i]); } - for (size_t i = 0; i < std::size(mergeVals2); i++) { + for (size_t i = 0; i < MOZ_ARRAY_LENGTH(mergeVals2); i++) { mergeSet2.Set(mergeVals2[i]); } chunkSet.Merge(mergeSet); chunkSet.Merge(mergeSet2); - for (size_t i = 0; i < std::size(testVals); i++) { + for (size_t i = 0; i < MOZ_ARRAY_LENGTH(testVals); i++) { ASSERT_TRUE(chunkSet.Has(testVals[i])); } - for (size_t i = 0; i < std::size(mergeVals); i++) { + for (size_t i = 0; i < MOZ_ARRAY_LENGTH(mergeVals); i++) { ASSERT_TRUE(chunkSet.Has(mergeVals[i])); } - for (size_t i = 0; i < std::size(mergeVals2); i++) { + for (size_t i = 0; i < MOZ_ARRAY_LENGTH(mergeVals2); i++) { ASSERT_TRUE(chunkSet.Has(mergeVals2[i])); } @@ -226,28 +226,28 @@ TEST(UrlClassifierChunkSet, RemoveClear) mozilla::safebrowsing::ChunkSet mergeSet; mozilla::safebrowsing::ChunkSet removeSet; - for (size_t i = 0; i < std::size(testVals); i++) { + for (size_t i = 0; i < MOZ_ARRAY_LENGTH(testVals); i++) { chunkSet.Set(testVals[i]); removeSet.Set(testVals[i]); } - for (size_t i = 0; i < std::size(mergeVals); i++) { + for (size_t i = 0; i < MOZ_ARRAY_LENGTH(mergeVals); i++) { mergeSet.Set(mergeVals[i]); } ASSERT_TRUE(chunkSet.Merge(mergeSet) == NS_OK); ASSERT_TRUE(chunkSet.Remove(removeSet) == NS_OK); - for (size_t i = 0; i < std::size(mergeVals); i++) { + for (size_t i = 0; i < MOZ_ARRAY_LENGTH(mergeVals); i++) { ASSERT_TRUE(chunkSet.Has(mergeVals[i])); } - for (size_t i = 0; i < std::size(testVals); i++) { + for (size_t i = 0; i < MOZ_ARRAY_LENGTH(testVals); i++) { ASSERT_FALSE(chunkSet.Has(testVals[i])); } chunkSet.Clear(); - for (size_t i = 0; i < std::size(mergeVals); i++) { + for (size_t i = 0; i < MOZ_ARRAY_LENGTH(mergeVals); i++) { ASSERT_FALSE(chunkSet.Has(mergeVals[i])); } } @@ -260,11 +260,11 @@ TEST(UrlClassifierChunkSet, Serialize) mozilla::safebrowsing::ChunkSet chunkSet; mozilla::safebrowsing::ChunkSet mergeSet; - for (size_t i = 0; i < std::size(testVals); i++) { + for (size_t i = 0; i < MOZ_ARRAY_LENGTH(testVals); i++) { chunkSet.Set(testVals[i]); } - for (size_t i = 0; i < std::size(mergeVals); i++) { + for (size_t i = 0; i < MOZ_ARRAY_LENGTH(mergeVals); i++) { mergeSet.Set(mergeVals[i]); } diff --git a/toolkit/components/url-classifier/tests/gtest/TestFindFullHash.cpp b/toolkit/components/url-classifier/tests/gtest/TestFindFullHash.cpp index 4c17e74011c98f..f0f57850174393 100644 --- a/toolkit/components/url-classifier/tests/gtest/TestFindFullHash.cpp +++ b/toolkit/components/url-classifier/tests/gtest/TestFindFullHash.cpp @@ -60,7 +60,7 @@ TEST(UrlClassifierFindFullHash, Request) ASSERT_TRUE(r.ParseFromArray(&requestBinary[0], requestBinary.Length())); // Compare client states. - ASSERT_EQ(r.client_states_size(), (int)std::size(listStates)); + ASSERT_EQ(r.client_states_size(), (int)ArrayLength(listStates)); for (int i = 0; i < r.client_states_size(); i++) { auto s = r.client_states(i); ASSERT_TRUE(listStates[i].Equals(nsCString(s.c_str(), s.size()))); @@ -69,7 +69,7 @@ TEST(UrlClassifierFindFullHash, Request) auto threatInfo = r.threat_info(); // Compare threat types. - ASSERT_EQ(threatInfo.threat_types_size(), (int)std::size(listStates)); + ASSERT_EQ(threatInfo.threat_types_size(), (int)ArrayLength(listStates)); for (int i = 0; i < threatInfo.threat_types_size(); i++) { uint32_t expectedThreatType; rv = @@ -79,7 +79,7 @@ TEST(UrlClassifierFindFullHash, Request) } // Compare prefixes. - ASSERT_EQ(threatInfo.threat_entries_size(), (int)std::size(prefixes)); + ASSERT_EQ(threatInfo.threat_entries_size(), (int)ArrayLength(prefixes)); for (int i = 0; i < threatInfo.threat_entries_size(); i++) { auto p = threatInfo.threat_entries(i).hash(); ASSERT_TRUE(prefixes[i].Equals(nsCString(p.c_str(), p.size()))); @@ -191,7 +191,7 @@ TEST(UrlClassifierFindFullHash, ParseRequest) PopulateDuration(*negCacheDuration, EXPECTED_NEG_CACHE_DURATION); // Init matches. - for (uint32_t i = 0; i < std::size(EXPECTED_MATCH); i++) { + for (uint32_t i = 0; i < ArrayLength(EXPECTED_MATCH); i++) { auto expected = EXPECTED_MATCH[i]; auto match = r.mutable_matches()->Add(); match->set_threat_type(expected.mThreatType); @@ -212,5 +212,5 @@ TEST(UrlClassifierFindFullHash, ParseRequest) nsCString(s.c_str(), s.size()), callback); NS_ENSURE_SUCCESS_VOID(rv); - ASSERT_EQ(callbackCount, std::size(EXPECTED_MATCH)); + ASSERT_EQ(callbackCount, ArrayLength(EXPECTED_MATCH)); } diff --git a/toolkit/mozapps/defaultagent/DefaultBrowser.cpp b/toolkit/mozapps/defaultagent/DefaultBrowser.cpp index f8e4052965c841..d9543665b7992f 100644 --- a/toolkit/mozapps/defaultagent/DefaultBrowser.cpp +++ b/toolkit/mozapps/defaultagent/DefaultBrowser.cpp @@ -42,7 +42,7 @@ constexpr std::pair kStringBrowserMap[]{ {"duckduckgo", Browser::DuckDuckGo}, }; -static_assert(std::size(kStringBrowserMap) == kBrowserCount); +static_assert(mozilla::ArrayLength(kStringBrowserMap) == kBrowserCount); std::string GetStringForBrowser(Browser browser) { for (const auto& [mapString, mapBrowser] : kStringBrowserMap) { @@ -127,7 +127,8 @@ BrowserResult TryGetDefaultBrowser() { // Unknown - not a real browser. // EdgeWithEdgeHTML - duplicate friendly name with EdgeWithBlink with special // handling below. - static_assert(std::size(kFriendlyNamePrefixes) == kBrowserCount - 3); + static_assert(mozilla::ArrayLength(kFriendlyNamePrefixes) == + kBrowserCount - 3); for (const auto& [prefix, browser] : kFriendlyNamePrefixes) { // Find matching Friendly Name prefix. diff --git a/toolkit/mozapps/defaultagent/DefaultPDF.cpp b/toolkit/mozapps/defaultagent/DefaultPDF.cpp index 2723b9d577f02f..e0a9f2e85a80a1 100644 --- a/toolkit/mozapps/defaultagent/DefaultPDF.cpp +++ b/toolkit/mozapps/defaultagent/DefaultPDF.cpp @@ -37,7 +37,7 @@ constexpr std::pair kStringPdfHandlerMap[]{ {"Sumatra", PDFHandler::SumatraPDF}, }; -static_assert(std::size(kStringPdfHandlerMap) == kPDFHandlerCount); +static_assert(mozilla::ArrayLength(kStringPdfHandlerMap) == kPDFHandlerCount); std::string GetStringForPDFHandler(PDFHandler handler) { for (const auto& [mapString, mapPdf] : kStringPdfHandlerMap) { @@ -125,7 +125,8 @@ static PdfResult GetDefaultPdf() { // Unknown - removed; not a real pdf handler. // AdobeAcrobat - duplicate; `Adobe` and `Acrobat` prefixes are both seen in // telemetry. - static_assert(std::size(kFriendlyNamePrefixes) == kPDFHandlerCount - 2 + 1); + static_assert(mozilla::ArrayLength(kFriendlyNamePrefixes) == + kPDFHandlerCount - 2 + 1); PDFHandler resolvedHandler = PDFHandler::Unknown; for (const auto& [knownHandlerSubstring, handlerEnum] : diff --git a/toolkit/mozapps/defaultagent/SetDefaultBrowser.cpp b/toolkit/mozapps/defaultagent/SetDefaultBrowser.cpp index 2407391e7aeab5..c94e1af6893bb1 100644 --- a/toolkit/mozapps/defaultagent/SetDefaultBrowser.cpp +++ b/toolkit/mozapps/defaultagent/SetDefaultBrowser.cpp @@ -266,9 +266,9 @@ using LaunchExeResult = static LaunchExeResult LaunchExecutable(const wchar_t* exePath, int aArgsLength, const wchar_t* const* aArgs) { const wchar_t* args[] = {exePath}; - mozilla::UniquePtr cmdLine( - mozilla::MakeCommandLine(std::size(args), const_cast(args), - aArgsLength, const_cast(aArgs))); + mozilla::UniquePtr cmdLine(mozilla::MakeCommandLine( + mozilla::ArrayLength(args), const_cast(args), aArgsLength, + const_cast(aArgs))); PROCESS_INFORMATION pi; STARTUPINFOW si = {sizeof(si)}; @@ -302,7 +302,7 @@ static bool LaunchPowershell(const wchar_t* command, command, }; - return LaunchExecutable(powershellPath, std::size(args), args) + return LaunchExecutable(powershellPath, mozilla::ArrayLength(args), args) .map([](auto result) { auto& [exitCode, regCmdLine] = result; bool success = (exitCode == 0); diff --git a/toolkit/mozapps/defaultagent/Telemetry.cpp b/toolkit/mozapps/defaultagent/Telemetry.cpp index 6dd9bb30db1a4e..f89aac24f1de5e 100644 --- a/toolkit/mozapps/defaultagent/Telemetry.cpp +++ b/toolkit/mozapps/defaultagent/Telemetry.cpp @@ -222,8 +222,9 @@ static mozilla::WindowsError SendDesktopTelemetryPing( const wchar_t* pingsenderArgs[] = {pingsenderPath.c_str(), url.c_str(), pingFilePath.c_str()}; - mozilla::UniquePtr pingsenderCmdLine(mozilla::MakeCommandLine( - std::size(pingsenderArgs), const_cast(pingsenderArgs))); + mozilla::UniquePtr pingsenderCmdLine( + mozilla::MakeCommandLine(mozilla::ArrayLength(pingsenderArgs), + const_cast(pingsenderArgs))); PROCESS_INFORMATION pi; STARTUPINFOW si = {sizeof(si)}; diff --git a/toolkit/mozapps/update/tests/TestAUSReadStrings.cpp b/toolkit/mozapps/update/tests/TestAUSReadStrings.cpp index 002623cdd137ce..d4c090772b50aa 100644 --- a/toolkit/mozapps/update/tests/TestAUSReadStrings.cpp +++ b/toolkit/mozapps/update/tests/TestAUSReadStrings.cpp @@ -89,7 +89,7 @@ int NS_main(int argc, NS_tchar** argv) { *(++slash) = '\0'; // Test success when the ini file exists with both Title and Info in the // Strings section and the values for Title and Info. - NS_tsnprintf(inifile, std::size(inifile), NS_T("%sTestAUSReadStrings1.ini"), + NS_tsnprintf(inifile, ArrayLength(inifile), NS_T("%sTestAUSReadStrings1.ini"), argv[0]); retval = ReadStrings(inifile, &testStrings); if (retval == OK) { @@ -121,7 +121,7 @@ int NS_main(int argc, NS_tchar** argv) { // Test failure when the ini file exists without Title and with Info in the // Strings section. - NS_tsnprintf(inifile, std::size(inifile), NS_T("%sTestAUSReadStrings2.ini"), + NS_tsnprintf(inifile, ArrayLength(inifile), NS_T("%sTestAUSReadStrings2.ini"), argv[0]); retval = ReadStrings(inifile, &testStrings); if (retval != PARSE_ERROR) { @@ -131,7 +131,7 @@ int NS_main(int argc, NS_tchar** argv) { // Test failure when the ini file exists with Title and without Info in the // Strings section. - NS_tsnprintf(inifile, std::size(inifile), NS_T("%sTestAUSReadStrings3.ini"), + NS_tsnprintf(inifile, ArrayLength(inifile), NS_T("%sTestAUSReadStrings3.ini"), argv[0]); retval = ReadStrings(inifile, &testStrings); if (retval != PARSE_ERROR) { @@ -140,7 +140,7 @@ int NS_main(int argc, NS_tchar** argv) { } // Test failure when the ini file doesn't exist - NS_tsnprintf(inifile, std::size(inifile), + NS_tsnprintf(inifile, ArrayLength(inifile), NS_T("%sTestAUSReadStringsBogus.ini"), argv[0]); retval = ReadStrings(inifile, &testStrings); if (retval != READ_ERROR) { @@ -149,7 +149,7 @@ int NS_main(int argc, NS_tchar** argv) { } // Test reading a non-default section name - NS_tsnprintf(inifile, std::size(inifile), NS_T("%sTestAUSReadStrings3.ini"), + NS_tsnprintf(inifile, ArrayLength(inifile), NS_T("%sTestAUSReadStrings3.ini"), argv[0]); retval = ReadStrings(inifile, "Title\0", 1, &testStrings.title, "BogusSection2"); @@ -164,7 +164,7 @@ int NS_main(int argc, NS_tchar** argv) { } // Test reading an exceedingly long string - NS_tsnprintf(inifile, std::size(inifile), NS_T("%sTestAUSReadStrings4.ini"), + NS_tsnprintf(inifile, ArrayLength(inifile), NS_T("%sTestAUSReadStrings4.ini"), argv[0]); retval = ReadStrings(inifile, "LongValue\0", 1, &testStrings.title); const char* expectedValue = diff --git a/toolkit/system/windowsproxy/nsWindowsSystemProxySettings.cpp b/toolkit/system/windowsproxy/nsWindowsSystemProxySettings.cpp index b3c1e8698b8378..202ba77d5fd0b3 100644 --- a/toolkit/system/windowsproxy/nsWindowsSystemProxySettings.cpp +++ b/toolkit/system/windowsproxy/nsWindowsSystemProxySettings.cpp @@ -63,7 +63,8 @@ static nsresult ReadInternetOption(uint32_t aOption, uint32_t& aFlags, DWORD connFlags = 0; WCHAR connName[RAS_MaxEntryName + 1]; MOZ_SEH_TRY { - InternetGetConnectedStateExW(&connFlags, connName, std::size(connName), 0); + InternetGetConnectedStateExW(&connFlags, connName, + mozilla::ArrayLength(connName), 0); } MOZ_SEH_EXCEPT(EXCEPTION_EXECUTE_HANDLER) { return NS_ERROR_FAILURE; } @@ -75,7 +76,7 @@ static nsresult ReadInternetOption(uint32_t aOption, uint32_t& aFlags, list.dwSize = sizeof(INTERNET_PER_CONN_OPTION_LISTW); list.pszConnection = connFlags & INTERNET_CONNECTION_MODEM ? connName : nullptr; - list.dwOptionCount = std::size(options); + list.dwOptionCount = mozilla::ArrayLength(options); list.dwOptionError = 0; list.pOptions = options; diff --git a/toolkit/xre/GeckoArgs.cpp b/toolkit/xre/GeckoArgs.cpp index 5c7c35a5239a1b..230f564587119b 100644 --- a/toolkit/xre/GeckoArgs.cpp +++ b/toolkit/xre/GeckoArgs.cpp @@ -20,8 +20,8 @@ static int gInitialFileHandles[]{3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17}; void SetPassedFileHandles(Span aFiles) { - MOZ_RELEASE_ASSERT(aFiles.Length() <= std::size(gInitialFileHandles)); - for (size_t i = 0; i < std::size(gInitialFileHandles); ++i) { + MOZ_RELEASE_ASSERT(aFiles.Length() <= ArrayLength(gInitialFileHandles)); + for (size_t i = 0; i < ArrayLength(gInitialFileHandles); ++i) { if (i < aFiles.Length()) { gInitialFileHandles[i] = aFiles[i]; } else { @@ -31,8 +31,8 @@ void SetPassedFileHandles(Span aFiles) { } void SetPassedFileHandles(std::vector&& aFiles) { - MOZ_RELEASE_ASSERT(aFiles.size() <= std::size(gInitialFileHandles)); - for (size_t i = 0; i < std::size(gInitialFileHandles); ++i) { + MOZ_RELEASE_ASSERT(aFiles.size() <= ArrayLength(gInitialFileHandles)); + for (size_t i = 0; i < ArrayLength(gInitialFileHandles); ++i) { if (i < aFiles.size()) { gInitialFileHandles[i] = aFiles[i].release(); } else { @@ -43,7 +43,7 @@ void SetPassedFileHandles(std::vector&& aFiles) { void AddToFdsToRemap(const ChildProcessArgs& aArgs, std::vector>& aFdsToRemap) { - MOZ_RELEASE_ASSERT(aArgs.mFiles.size() <= std::size(gInitialFileHandles)); + MOZ_RELEASE_ASSERT(aArgs.mFiles.size() <= ArrayLength(gInitialFileHandles)); for (size_t i = 0; i < aArgs.mFiles.size(); ++i) { aFdsToRemap.push_back( std::pair{aArgs.mFiles[i].get(), gInitialFileHandles[i]}); @@ -56,7 +56,7 @@ void AddToFdsToRemap(const ChildProcessArgs& aArgs, static mach_port_t gMachSendRights[kMaxPassedMachSendRights] = {MACH_PORT_NULL}; void SetPassedMachSendRights(std::vector&& aSendRights) { - MOZ_RELEASE_ASSERT(aSendRights.size() <= std::size(gMachSendRights)); + MOZ_RELEASE_ASSERT(aSendRights.size() <= ArrayLength(gMachSendRights)); for (size_t i = 0; i < aSendRights.size(); ++i) { gMachSendRights[i] = aSendRights[i].release(); } @@ -77,7 +77,7 @@ Maybe CommandLineArg::GetCommon( #else // See the comment on gInitialFileHandles for an explanation of the // behaviour here. - MOZ_RELEASE_ASSERT(*arg < std::size(gInitialFileHandles)); + MOZ_RELEASE_ASSERT(*arg < ArrayLength(gInitialFileHandles)); return Some(UniqueFileHandle{std::exchange(gInitialFileHandles[*arg], -1)}); #endif } @@ -111,7 +111,7 @@ Maybe CommandLineArg::GetCommon( const char* aMatch, int& aArgc, char** aArgv, const CheckArgFlag aFlags) { if (Maybe arg = CommandLineArg::GetCommon(aMatch, aArgc, aArgv, aFlags)) { - MOZ_RELEASE_ASSERT(*arg < std::size(gMachSendRights)); + MOZ_RELEASE_ASSERT(*arg < ArrayLength(gMachSendRights)); return Some(UniqueMachSendRight{ std::exchange(gMachSendRights[*arg], MACH_PORT_NULL)}); } diff --git a/toolkit/xre/LauncherRegistryInfo.cpp b/toolkit/xre/LauncherRegistryInfo.cpp index 7bf370f80917cf..b80ee77f4d00c1 100644 --- a/toolkit/xre/LauncherRegistryInfo.cpp +++ b/toolkit/xre/LauncherRegistryInfo.cpp @@ -469,7 +469,8 @@ LauncherResult LauncherRegistryInfo::IsTelemetryEnabled() { const std::wstring& LauncherRegistryInfo::ResolveLauncherValueName() { if (mLauncherValueName.empty()) { mLauncherValueName.assign(mBinPath); - mLauncherValueName.append(kLauncherSuffix, std::size(kLauncherSuffix) - 1); + mLauncherValueName.append(kLauncherSuffix, + ArrayLength(kLauncherSuffix) - 1); } return mLauncherValueName; @@ -478,7 +479,7 @@ const std::wstring& LauncherRegistryInfo::ResolveLauncherValueName() { const std::wstring& LauncherRegistryInfo::ResolveBrowserValueName() { if (mBrowserValueName.empty()) { mBrowserValueName.assign(mBinPath); - mBrowserValueName.append(kBrowserSuffix, std::size(kBrowserSuffix) - 1); + mBrowserValueName.append(kBrowserSuffix, ArrayLength(kBrowserSuffix) - 1); } return mBrowserValueName; @@ -488,7 +489,7 @@ const std::wstring& LauncherRegistryInfo::ResolveImageTimestampValueName() { if (mImageValueName.empty()) { mImageValueName.assign(mBinPath); mImageValueName.append(kImageTimestampSuffix, - std::size(kImageTimestampSuffix) - 1); + ArrayLength(kImageTimestampSuffix) - 1); } return mImageValueName; @@ -498,7 +499,7 @@ const std::wstring& LauncherRegistryInfo::ResolveTelemetryValueName() { if (mTelemetryValueName.empty()) { mTelemetryValueName.assign(mBinPath); mTelemetryValueName.append(kTelemetrySuffix, - std::size(kTelemetrySuffix) - 1); + ArrayLength(kTelemetrySuffix) - 1); } return mTelemetryValueName; @@ -508,7 +509,7 @@ const std::wstring& LauncherRegistryInfo::ResolveBlocklistValueName() { if (mBlocklistValueName.empty()) { mBlocklistValueName.assign(mBinPath); mBlocklistValueName.append(kBlocklistSuffix, - std::size(kBlocklistSuffix) - 1); + ArrayLength(kBlocklistSuffix) - 1); } return mBlocklistValueName; diff --git a/toolkit/xre/dllservices/ModuleEvaluator.cpp b/toolkit/xre/dllservices/ModuleEvaluator.cpp index c3f5599141843b..00e5c2dbfe4df3 100644 --- a/toolkit/xre/dllservices/ModuleEvaluator.cpp +++ b/toolkit/xre/dllservices/ModuleEvaluator.cpp @@ -42,7 +42,7 @@ static Vector GetKeyboardLayoutDlls() { DWORD iKey = 0; wchar_t strTemp[MAX_PATH] = {}; while (true) { - DWORD strTempSize = std::size(strTemp); + DWORD strTempSize = ArrayLength(strTemp); if (RegEnumKeyExW(rawKey, iKey, strTemp, &strTempSize, nullptr, nullptr, nullptr, nullptr) != ERROR_SUCCESS) { // ERROR_NO_MORE_ITEMS or a real error: bail with what we have. diff --git a/toolkit/xre/dllservices/mozglue/WindowsDllBlocklistCommon.h b/toolkit/xre/dllservices/mozglue/WindowsDllBlocklistCommon.h index 22a8e1356c1600..b9f176ac021224 100644 --- a/toolkit/xre/dllservices/mozglue/WindowsDllBlocklistCommon.h +++ b/toolkit/xre/dllservices/mozglue/WindowsDllBlocklistCommon.h @@ -32,13 +32,13 @@ DECLARE_POINTER_TO_FIRST_DLL_BLOCKLIST_ENTRY_FOR(name, gWindowsDllBlocklist) #define DECLARE_POINTER_TO_LAST_DLL_BLOCKLIST_ENTRY_FOR(name, list) \ - const DllBlockInfo* name = &list[std::size(list) - 1] + const DllBlockInfo* name = &list[mozilla::ArrayLength(list) - 1] #define DECLARE_POINTER_TO_LAST_DLL_BLOCKLIST_ENTRY(name) \ DECLARE_POINTER_TO_LAST_DLL_BLOCKLIST_ENTRY_FOR(name, gWindowsDllBlocklist) #define DECLARE_DLL_BLOCKLIST_NUM_ENTRIES_FOR(name, list) \ - const size_t name = std::size(list) - 1 + const size_t name = mozilla::ArrayLength(list) - 1 #define DECLARE_DLL_BLOCKLIST_NUM_ENTRIES(name) \ DECLARE_DLL_BLOCKLIST_NUM_ENTRIES_FOR(name, gWindowsDllBlocklist) diff --git a/toolkit/xre/dllservices/mozglue/interceptor/PatcherDetour.h b/toolkit/xre/dllservices/mozglue/interceptor/PatcherDetour.h index 659e0f6c1844b6..bb9236d58bb1c1 100644 --- a/toolkit/xre/dllservices/mozglue/interceptor/PatcherDetour.h +++ b/toolkit/xre/dllservices/mozglue/interceptor/PatcherDetour.h @@ -959,7 +959,7 @@ class WindowsDllDetourPatcher final DetourResultCode::DETOUR_PATCHER_CREATE_TRAMPOLINE_ERROR); DetourError& lastError = *this->mVMPolicy.mLastError; size_t bytesToCapture = std::min( - std::size(lastError.mOrigBytes), + ArrayLength(lastError.mOrigBytes), static_cast(PrimitiveT::GetWorstCaseRequiredBytesToPatch())); # if defined(_M_ARM64) size_t numInstructionsToCapture = bytesToCapture / sizeof(uint32_t); diff --git a/toolkit/xre/dllservices/mozglue/interceptor/PatcherNopSpace.h b/toolkit/xre/dllservices/mozglue/interceptor/PatcherNopSpace.h index 7f42d8129fb98e..deee87e0f88655 100644 --- a/toolkit/xre/dllservices/mozglue/interceptor/PatcherNopSpace.h +++ b/toolkit/xre/dllservices/mozglue/interceptor/PatcherNopSpace.h @@ -65,7 +65,7 @@ class WindowsDllNopSpacePatcher final : public WindowsDllPatcherBase { const wchar_t* kIncompatibleDLLs[] = {L"detoured.dll", L"_etoured.dll", L"nvd3d9wrap.dll", L"nvdxgiwrap.dll"}; // See if the infringing DLLs are already loaded - for (unsigned int i = 0; i < std::size(kIncompatibleDLLs); ++i) { + for (unsigned int i = 0; i < mozilla::ArrayLength(kIncompatibleDLLs); ++i) { if (GetModuleHandleW(kIncompatibleDLLs[i])) { return false; } @@ -104,11 +104,12 @@ class WindowsDllNopSpacePatcher final : public WindowsDllPatcherBase { while (token) { wchar_t fname[_MAX_FNAME] = {0}; if (!_wsplitpath_s(token, nullptr, 0, nullptr, 0, fname, - std::size(fname), nullptr, 0)) { + mozilla::ArrayLength(fname), nullptr, 0)) { // nvinit.dll is responsible for bootstrapping the DLL injection, so // that is the library that we check for here const wchar_t kNvInitName[] = L"nvinit"; - if (!_wcsnicmp(fname, kNvInitName, std::size(kNvInitName))) { + if (!_wcsnicmp(fname, kNvInitName, + mozilla::ArrayLength(kNvInitName))) { return false; } } diff --git a/toolkit/xre/dllservices/tests/TestDllInterceptorCrossProcess.cpp b/toolkit/xre/dllservices/tests/TestDllInterceptorCrossProcess.cpp index 95df167233f3ca..24c34c66987f97 100644 --- a/toolkit/xre/dllservices/tests/TestDllInterceptorCrossProcess.cpp +++ b/toolkit/xre/dllservices/tests/TestDllInterceptorCrossProcess.cpp @@ -61,7 +61,7 @@ int ParentMain(int argc, wchar_t* argv[]) { wchar_t* childArgv[] = {argv[0], childArgv_1}; mozilla::UniquePtr cmdLine( - mozilla::MakeCommandLine(std::size(childArgv), childArgv)); + mozilla::MakeCommandLine(mozilla::ArrayLength(childArgv), childArgv)); STARTUPINFOW si = {sizeof(si)}; PROCESS_INFORMATION pi; diff --git a/toolkit/xre/dllservices/tests/gtest/TestDLLBlocklist.cpp b/toolkit/xre/dllservices/tests/gtest/TestDLLBlocklist.cpp index 3a14c224894e59..4daa3301ba0483 100644 --- a/toolkit/xre/dllservices/tests/gtest/TestDLLBlocklist.cpp +++ b/toolkit/xre/dllservices/tests/gtest/TestDLLBlocklist.cpp @@ -329,7 +329,7 @@ TEST(TestDllBlocklist, BlocklistIntegrity) EXPECT_FALSE(pLast->mName || pLast->mMaxVersion || pLast->mFlags); - for (size_t i = 0; i < std::size(gWindowsDllBlocklist) - 1; ++i) { + for (size_t i = 0; i < mozilla::ArrayLength(gWindowsDllBlocklist) - 1; ++i) { auto pEntry = pFirst + i; // Validate name diff --git a/toolkit/xre/dllservices/tests/gtest/TestUntrustedModules.cpp b/toolkit/xre/dllservices/tests/gtest/TestUntrustedModules.cpp index a5afed61a51263..f905d4f3321b64 100644 --- a/toolkit/xre/dllservices/tests/gtest/TestUntrustedModules.cpp +++ b/toolkit/xre/dllservices/tests/gtest/TestUntrustedModules.cpp @@ -302,7 +302,7 @@ void UntrustedModulesFixture::ValidateUntrustedModules( size_t match; if (BinarySearchIf( - kKnownModules, 0, std::size(kKnownModules), + kKnownModules, 0, ArrayLength(kKnownModules), [&leafNameStr](const auto& aVal) { return _wcsicmp(leafNameStr.get(), aVal.mName); }, @@ -313,7 +313,7 @@ void UntrustedModulesFixture::ValidateUntrustedModules( } if (BinarySearchIf( - kTestModules, 0, std::size(kTestModules), + kTestModules, 0, ArrayLength(kTestModules), [&leafNameStr](const auto& aVal) { return _wcsicmp(leafNameStr.get(), aVal.get()); }, @@ -431,7 +431,7 @@ TEST_F(UntrustedModulesFixture, Serialize) { backup1.Add(std::move(data3)); } - ValidateJSValue(kPattern, std::size(kPattern) - 1, cx.GetJSContext(), + ValidateJSValue(kPattern, ArrayLength(kPattern) - 1, cx.GetJSContext(), [&backup1, &backup2]( Telemetry::UntrustedModulesDataSerializer& aSerializer) { EXPECT_NS_SUCCEEDED(aSerializer.Add(backup1)); diff --git a/toolkit/xre/nsUpdateDriver.cpp b/toolkit/xre/nsUpdateDriver.cpp index 50e36c7034893c..0446d951008c3a 100644 --- a/toolkit/xre/nsUpdateDriver.cpp +++ b/toolkit/xre/nsUpdateDriver.cpp @@ -79,13 +79,13 @@ static nsresult GetCurrentWorkingDir(nsACString& aOutPath) { #if defined(XP_WIN) wchar_t wpath[MAX_PATH]; - if (!_wgetcwd(wpath, std::size(wpath))) { + if (!_wgetcwd(wpath, ArrayLength(wpath))) { return NS_ERROR_FAILURE; } CopyUTF16toUTF8(nsDependentString(wpath), aOutPath); #else char path[MAXPATHLEN]; - if (!getcwd(path, std::size(path))) { + if (!getcwd(path, ArrayLength(path))) { return NS_ERROR_FAILURE; } aOutPath = path; diff --git a/toolkit/xre/test/gtest/TestAssembleCommandLineWin.cpp b/toolkit/xre/test/gtest/TestAssembleCommandLineWin.cpp index 0a2edbb6404a43..b140d6de9ac36d 100644 --- a/toolkit/xre/test/gtest/TestAssembleCommandLineWin.cpp +++ b/toolkit/xre/test/gtest/TestAssembleCommandLineWin.cpp @@ -143,8 +143,8 @@ TEST(WinRemoteMessage, SendReceiveV2) EXPECT_NS_SUCCEEDED(receiver.Parse(&data)); EXPECT_NS_SUCCEEDED(receiver.CommandLineRunner()->GetLength(&len)); - EXPECT_EQ(static_cast(len), std::size(kExpectedArgsW)); - for (size_t i = 0; i < std::size(kExpectedArgsW); ++i) { + EXPECT_EQ(static_cast(len), ArrayLength(kExpectedArgsW)); + for (size_t i = 0; i < ArrayLength(kExpectedArgsW); ++i) { EXPECT_TRUE( NS_SUCCEEDED(receiver.CommandLineRunner()->GetArgument(i, arg))); EXPECT_STREQ(arg.get(), kExpectedArgsW[i]); @@ -167,7 +167,7 @@ TEST(WinRemoteMessage, SendReceiveV3) wchar_t workingDirW[MAX_PATH]; EXPECT_NE(_wgetcwd(workingDirW, MAX_PATH), nullptr); - WinRemoteMessageSender v3(std::size(kCommandline), kCommandline, + WinRemoteMessageSender v3(ArrayLength(kCommandline), kCommandline, nsDependentString(workingDirW)); WinRemoteMessageReceiver receiver; @@ -177,8 +177,8 @@ TEST(WinRemoteMessage, SendReceiveV3) EXPECT_NS_SUCCEEDED(receiver.Parse(v3.CopyData())); EXPECT_NS_SUCCEEDED(receiver.CommandLineRunner()->GetLength(&len)); - EXPECT_EQ(static_cast(len), std::size(kExpectedArgsW)); - for (size_t i = 0; i < std::size(kExpectedArgsW); ++i) { + EXPECT_EQ(static_cast(len), ArrayLength(kExpectedArgsW)); + for (size_t i = 0; i < ArrayLength(kExpectedArgsW); ++i) { EXPECT_TRUE( NS_SUCCEEDED(receiver.CommandLineRunner()->GetArgument(i, arg))); EXPECT_STREQ(arg.get(), kExpectedArgsW[i]); diff --git a/toolkit/xre/test/gtest/TestGeckoArgs.cpp b/toolkit/xre/test/gtest/TestGeckoArgs.cpp index 151996e3a430fe..e135f7e2d8c414 100644 --- a/toolkit/xre/test/gtest/TestGeckoArgs.cpp +++ b/toolkit/xre/test/gtest/TestGeckoArgs.cpp @@ -40,7 +40,7 @@ TEST(GeckoArgs, const_char_ptr) { char* argv[] = {kFirefox, kCharParamStr, kCharParamValue, nullptr}; - int argc = std::size(argv); + int argc = ArrayLength(argv); EXPECT_EQ(argc, 4); Maybe charParam = kCharParam.Get(argc, argv); @@ -53,7 +53,7 @@ TEST(GeckoArgs, const_char_ptr) { char kBlahBlah[] = "-blahblah"; char* argv[] = {kFirefox, kCharParamStr, kBlahBlah, nullptr}; - int argc = std::size(argv); + int argc = ArrayLength(argv); EXPECT_EQ(argc, 4); Maybe charParam = kCharParam.Get(argc, argv); @@ -79,7 +79,7 @@ TEST(GeckoArgs, uint64) { char* argv[] = {kFirefox, kUint64ParamStr, nullptr}; - int argc = std::size(argv); + int argc = ArrayLength(argv); EXPECT_EQ(argc, 3); Maybe uint64Param = kUint64Param.Get(argc, argv); @@ -90,7 +90,7 @@ TEST(GeckoArgs, uint64) } { char* argv[] = {kFirefox, nullptr}; - int argc = std::size(argv); + int argc = ArrayLength(argv); EXPECT_EQ(argc, 2); Maybe uint64Param = kUint64Param.Get(argc, argv); @@ -102,7 +102,7 @@ TEST(GeckoArgs, uint64) { char kUint64ParamValue[] = "42"; char* argv[] = {kFirefox, kUint64ParamStr, kUint64ParamValue, nullptr}; - int argc = std::size(argv); + int argc = ArrayLength(argv); EXPECT_EQ(argc, 4); Maybe uint64Param = kUint64Param.Get(argc, argv); @@ -115,7 +115,7 @@ TEST(GeckoArgs, uint64) { char kUint64ParamValue[] = "aa"; char* argv[] = {kFirefox, kUint64ParamStr, kUint64ParamValue, nullptr}; - int argc = std::size(argv); + int argc = ArrayLength(argv); EXPECT_EQ(argc, 4); Maybe uint64Param = kUint64Param.Get(argc, argv); @@ -141,7 +141,7 @@ TEST(GeckoArgs, bool) { char* argv[] = {kFirefox, kFlagStr, nullptr}; - int argc = std::size(argv); + int argc = ArrayLength(argv); EXPECT_EQ(argc, 3); Maybe Flag = kFlag.Get(argc, argv); @@ -153,7 +153,7 @@ TEST(GeckoArgs, bool) } { char* argv[] = {kFirefox, nullptr}; - int argc = std::size(argv); + int argc = ArrayLength(argv); EXPECT_EQ(argc, 2); Maybe Flag = kFlag.Get(argc, argv); diff --git a/tools/profiler/core/ProfilerCodeAddressService.cpp b/tools/profiler/core/ProfilerCodeAddressService.cpp index 0a59d37a3ef983..5a65e0637984d9 100644 --- a/tools/profiler/core/ProfilerCodeAddressService.cpp +++ b/tools/profiler/core/ProfilerCodeAddressService.cpp @@ -30,11 +30,12 @@ static char* SearchSymbolTable(SymbolTable& aTable, uint32_t aOffset) { // First try demangling as a Rust identifier. char demangled[1024]; - if (!profiler_demangle_rust(symbol.get(), demangled, std::size(demangled))) { + if (!profiler_demangle_rust(symbol.get(), demangled, + ArrayLength(demangled))) { // Then as a C++ identifier. - DemangleSymbol(symbol.get(), demangled, std::size(demangled)); + DemangleSymbol(symbol.get(), demangled, ArrayLength(demangled)); } - demangled[std::size(demangled) - 1] = '\0'; + demangled[ArrayLength(demangled) - 1] = '\0'; // Use the mangled name if we didn't successfully demangle. return strdup(demangled[0] != '\0' ? demangled : symbol.get()); diff --git a/tools/profiler/core/platform.cpp b/tools/profiler/core/platform.cpp index d5ffc4c70c5d14..f02289e4f40131 100644 --- a/tools/profiler/core/platform.cpp +++ b/tools/profiler/core/platform.cpp @@ -5746,7 +5746,7 @@ void profiler_start_from_signal() { // start the profiler in content/child processes. profiler_start(PROFILER_DEFAULT_SIGHANDLE_ENTRIES, PROFILER_DEFAULT_INTERVAL, features, filters, - std::size(filters), 0); + MOZ_ARRAY_LENGTH(filters), 0); } else { // Directly start the profiler on this thread. We know we're not the main // thread here, so this will not start the profiler in child processes, @@ -5754,15 +5754,16 @@ void profiler_start_from_signal() { // stuck. profiler_start(PROFILER_DEFAULT_SIGHANDLE_ENTRIES, PROFILER_DEFAULT_INTERVAL, features, filters, - std::size(filters), 0); + MOZ_ARRAY_LENGTH(filters), 0); // Now also try and start the profiler from the main thread, so that the // ParentProfiler will start child threads. NS_DispatchToMainThread( NS_NewRunnableFunction("StartProfilerInChildProcesses", [=] { - Unused << NotifyProfilerStarted( - PROFILER_DEFAULT_SIGHANDLE_ENTRIES, Nothing(), - PROFILER_DEFAULT_INTERVAL, features, - const_cast(filters), std::size(filters), 0); + Unused << NotifyProfilerStarted(PROFILER_DEFAULT_SIGHANDLE_ENTRIES, + Nothing(), + PROFILER_DEFAULT_INTERVAL, features, + const_cast(filters), + MOZ_ARRAY_LENGTH(filters), 0); })); } } diff --git a/tools/profiler/lul/LulMain.cpp b/tools/profiler/lul/LulMain.cpp index 37652c4f20a9ef..7cf5508234d903 100644 --- a/tools/profiler/lul/LulMain.cpp +++ b/tools/profiler/lul/LulMain.cpp @@ -1819,7 +1819,7 @@ static __attribute__((noinline)) bool GetAndCheckStackTrace( const int MAX_TEST_FRAMES = 64; uintptr_t framePCs[MAX_TEST_FRAMES]; uintptr_t frameSPs[MAX_TEST_FRAMES]; - size_t framesAvail = std::size(framePCs); + size_t framesAvail = mozilla::ArrayLength(framePCs); size_t framesUsed = 0; size_t framePointerFramesAcquired = 0; aLUL->Unwind(&framePCs[0], &frameSPs[0], &framesUsed, diff --git a/tools/profiler/tests/gtest/GeckoProfiler.cpp b/tools/profiler/tests/gtest/GeckoProfiler.cpp index d38ac4b93416bb..6c4f1bb7324b3b 100644 --- a/tools/profiler/tests/gtest/GeckoProfiler.cpp +++ b/tools/profiler/tests/gtest/GeckoProfiler.cpp @@ -1612,7 +1612,7 @@ TEST(GeckoProfiler, FeaturesAndParams) # define PROFILER_DEFAULT_DURATION 20 /* seconds, for tests only */ profiler_start(PROFILER_DEFAULT_ENTRIES, PROFILER_DEFAULT_INTERVAL, - features, filters, std::size(filters), 100, + features, filters, MOZ_ARRAY_LENGTH(filters), 100, Some(PROFILER_DEFAULT_DURATION)); ASSERT_TRUE(profiler_is_active()); @@ -1621,7 +1621,8 @@ TEST(GeckoProfiler, FeaturesAndParams) ActiveParamsCheck(PROFILER_DEFAULT_ENTRIES.Value(), PROFILER_DEFAULT_INTERVAL, features, filters, - std::size(filters), 100, Some(PROFILER_DEFAULT_DURATION)); + MOZ_ARRAY_LENGTH(filters), 100, + Some(PROFILER_DEFAULT_DURATION)); profiler_stop(); @@ -1637,14 +1638,14 @@ TEST(GeckoProfiler, FeaturesAndParams) // Testing with some arbitrary buffer size (as could be provided by // external code), which we convert to the appropriate power of 2. profiler_start(PowerOfTwo32(999999), 3, features, filters, - std::size(filters), 123, Some(25.0)); + MOZ_ARRAY_LENGTH(filters), 123, Some(25.0)); ASSERT_TRUE(profiler_is_active()); ASSERT_TRUE(profiler_feature_active(ProfilerFeature::MainThreadIO)); ASSERT_TRUE(profiler_feature_active(ProfilerFeature::IPCMessages)); ActiveParamsCheck(int(PowerOfTwo32(999999).Value()), 3, features, filters, - std::size(filters), 123, Some(25.0)); + MOZ_ARRAY_LENGTH(filters), 123, Some(25.0)); profiler_stop(); @@ -1658,14 +1659,14 @@ TEST(GeckoProfiler, FeaturesAndParams) const char* filters[] = {"GeckoMain", "Foo", "Bar"}; profiler_start(PowerOfTwo32(999999), 3, features, filters, - std::size(filters), 0, Nothing()); + MOZ_ARRAY_LENGTH(filters), 0, Nothing()); ASSERT_TRUE(profiler_is_active()); ASSERT_TRUE(profiler_feature_active(ProfilerFeature::MainThreadIO)); ASSERT_TRUE(profiler_feature_active(ProfilerFeature::IPCMessages)); ActiveParamsCheck(int(PowerOfTwo32(999999).Value()), 3, features, filters, - std::size(filters), 0, Nothing()); + MOZ_ARRAY_LENGTH(filters), 0, Nothing()); profiler_stop(); @@ -1681,14 +1682,14 @@ TEST(GeckoProfiler, FeaturesAndParams) availableFeatures &= ~ProfilerFeature::Tracing; profiler_start(PowerOfTwo32(88888), 10, availableFeatures, filters, - std::size(filters), 0, Some(15.0)); + MOZ_ARRAY_LENGTH(filters), 0, Some(15.0)); ASSERT_TRUE(profiler_is_active()); ASSERT_TRUE(profiler_feature_active(ProfilerFeature::MainThreadIO)); ASSERT_TRUE(profiler_feature_active(ProfilerFeature::IPCMessages)); ActiveParamsCheck(PowerOfTwo32(88888).Value(), 10, availableFeatures, - filters, std::size(filters), 0, Some(15.0)); + filters, MOZ_ARRAY_LENGTH(filters), 0, Some(15.0)); // Don't call profiler_stop() here. } @@ -1700,8 +1701,8 @@ TEST(GeckoProfiler, FeaturesAndParams) // Second profiler_start() call in a row without an intervening // profiler_stop(); this will do an implicit profiler_stop() and restart. - profiler_start(PowerOfTwo32(0), 0, features, filters, std::size(filters), 0, - Some(0.0)); + profiler_start(PowerOfTwo32(0), 0, features, filters, + MOZ_ARRAY_LENGTH(filters), 0, Some(0.0)); ASSERT_TRUE(profiler_is_active()); ASSERT_TRUE(!profiler_feature_active(ProfilerFeature::MainThreadIO)); @@ -1710,7 +1711,7 @@ TEST(GeckoProfiler, FeaturesAndParams) // Entries and intervals go to defaults if 0 is specified. ActiveParamsCheck(PROFILER_DEFAULT_ENTRIES.Value(), PROFILER_DEFAULT_INTERVAL, features, filters, - std::size(filters), 0, Nothing()); + MOZ_ARRAY_LENGTH(filters), 0, Nothing()); profiler_stop(); @@ -1733,12 +1734,12 @@ TEST(GeckoProfiler, EnsureStarted) { // Inactive -> Active profiler_ensure_started(PROFILER_DEFAULT_ENTRIES, PROFILER_DEFAULT_INTERVAL, - features, filters, std::size(filters), 0, + features, filters, MOZ_ARRAY_LENGTH(filters), 0, Some(PROFILER_DEFAULT_DURATION)); - ActiveParamsCheck(PROFILER_DEFAULT_ENTRIES.Value(), - PROFILER_DEFAULT_INTERVAL, features, filters, - std::size(filters), 0, Some(PROFILER_DEFAULT_DURATION)); + ActiveParamsCheck( + PROFILER_DEFAULT_ENTRIES.Value(), PROFILER_DEFAULT_INTERVAL, features, + filters, MOZ_ARRAY_LENGTH(filters), 0, Some(PROFILER_DEFAULT_DURATION)); } { @@ -1756,12 +1757,12 @@ TEST(GeckoProfiler, EnsureStarted) // Call profiler_ensure_started with the same settings as before. // This operation must not clear our buffer! profiler_ensure_started(PROFILER_DEFAULT_ENTRIES, PROFILER_DEFAULT_INTERVAL, - features, filters, std::size(filters), 0, + features, filters, MOZ_ARRAY_LENGTH(filters), 0, Some(PROFILER_DEFAULT_DURATION)); - ActiveParamsCheck(PROFILER_DEFAULT_ENTRIES.Value(), - PROFILER_DEFAULT_INTERVAL, features, filters, - std::size(filters), 0, Some(PROFILER_DEFAULT_DURATION)); + ActiveParamsCheck( + PROFILER_DEFAULT_ENTRIES.Value(), PROFILER_DEFAULT_INTERVAL, features, + filters, MOZ_ARRAY_LENGTH(filters), 0, Some(PROFILER_DEFAULT_DURATION)); // Check that our position in the buffer stayed the same or advanced, but // not by much, and the range-start after profiler_ensure_started shouldn't @@ -1783,11 +1784,12 @@ TEST(GeckoProfiler, EnsureStarted) // profiler, thereby discarding the buffer contents. uint32_t differentFeatures = features | ProfilerFeature::CPUUtilization; profiler_ensure_started(PROFILER_DEFAULT_ENTRIES, PROFILER_DEFAULT_INTERVAL, - differentFeatures, filters, std::size(filters), 0); + differentFeatures, filters, + MOZ_ARRAY_LENGTH(filters), 0); ActiveParamsCheck(PROFILER_DEFAULT_ENTRIES.Value(), PROFILER_DEFAULT_INTERVAL, differentFeatures, filters, - std::size(filters), 0); + MOZ_ARRAY_LENGTH(filters), 0); // Check the the buffer was cleared, so its range-start should be at/after // its range-end before. @@ -1874,7 +1876,7 @@ TEST(GeckoProfiler, DifferentThreads) "GeckoProfiler_DifferentThreads_Test::TestBody", [&]() { profiler_start(PROFILER_DEFAULT_ENTRIES, PROFILER_DEFAULT_INTERVAL, features, filters, - std::size(filters), 0); + MOZ_ARRAY_LENGTH(filters), 0); })); ASSERT_TRUE(profiler_is_active()); @@ -1883,7 +1885,7 @@ TEST(GeckoProfiler, DifferentThreads) ActiveParamsCheck(PROFILER_DEFAULT_ENTRIES.Value(), PROFILER_DEFAULT_INTERVAL, features, filters, - std::size(filters), 0); + MOZ_ARRAY_LENGTH(filters), 0); NS_DispatchAndSpinEventLoopUntilComplete( "GeckoProfiler_DifferentThreads_Test::TestBody"_ns, thread, @@ -1900,7 +1902,7 @@ TEST(GeckoProfiler, DifferentThreads) const char* filters[] = {"GeckoMain", "Compositor"}; profiler_start(PROFILER_DEFAULT_ENTRIES, PROFILER_DEFAULT_INTERVAL, - features, filters, std::size(filters), 0); + features, filters, MOZ_ARRAY_LENGTH(filters), 0); NS_DispatchAndSpinEventLoopUntilComplete( "GeckoProfiler_DifferentThreads_Test::TestBody"_ns, thread, @@ -1914,7 +1916,7 @@ TEST(GeckoProfiler, DifferentThreads) ActiveParamsCheck(PROFILER_DEFAULT_ENTRIES.Value(), PROFILER_DEFAULT_INTERVAL, features, filters, - std::size(filters), 0); + MOZ_ARRAY_LENGTH(filters), 0); })); profiler_stop(); @@ -1937,7 +1939,7 @@ TEST(GeckoProfiler, GetBacktrace) const char* filters[] = {"GeckoMain"}; profiler_start(PROFILER_DEFAULT_ENTRIES, PROFILER_DEFAULT_INTERVAL, - features, filters, std::size(filters), 0); + features, filters, MOZ_ARRAY_LENGTH(filters), 0); // These will be destroyed while the profiler is active. static const int N = 100; @@ -2026,7 +2028,7 @@ TEST(GeckoProfiler, Pause) }}.join(); profiler_start(PROFILER_DEFAULT_ENTRIES, PROFILER_DEFAULT_INTERVAL, features, - filters, std::size(filters), 0); + filters, MOZ_ARRAY_LENGTH(filters), 0); ASSERT_TRUE(!profiler_is_paused()); for (ThreadProfilingFeatures features : scEachAndAnyThreadProfilingFeatures) { @@ -2289,7 +2291,7 @@ TEST(GeckoProfiler, Markers) const char* filters[] = {"GeckoMain"}; profiler_start(PROFILER_DEFAULT_ENTRIES, PROFILER_DEFAULT_INTERVAL, features, - filters, std::size(filters), 0); + filters, MOZ_ARRAY_LENGTH(filters), 0); PROFILER_MARKER("tracing event", OTHER, {}, Tracing, "A"); PROFILER_MARKER("tracing start", OTHER, MarkerTiming::IntervalStart(), @@ -3514,7 +3516,7 @@ TEST(GeckoProfiler, Markers) // Warning: this could be racy profiler_start(PROFILER_DEFAULT_ENTRIES, PROFILER_DEFAULT_INTERVAL, features, - filters, std::size(filters), 0); + filters, MOZ_ARRAY_LENGTH(filters), 0); // This last marker shouldn't get streamed. SpliceableChunkedJSONWriter w2{FailureLatchInfallibleSource::Singleton()}; @@ -3556,13 +3558,14 @@ TEST(GeckoProfiler, Counters) NumberAndCount expectedTestCounters[] = {{1u, 10}, {0u, 0}, {1u, 7}, {0u, 0}, {0u, 0}, {1u, -17}, {0u, 0}, {0u, 0}}; - constexpr size_t expectedTestCountersCount = std::size(expectedTestCounters); + constexpr size_t expectedTestCountersCount = + MOZ_ARRAY_LENGTH(expectedTestCounters); bool expectCounter2 = false; int64_t testCounters2[] = {10}; NumberAndCount expectedTestCounters2[] = {{1u, 10}, {0u, 0}}; constexpr size_t expectedTestCounters2Count = - std::size(expectedTestCounters2); + MOZ_ARRAY_LENGTH(expectedTestCounters2); auto checkCountersInJSON = [&](const Json::Value& aRoot) { size_t nextExpectedTestCounter = 0u; @@ -3623,7 +3626,7 @@ TEST(GeckoProfiler, Counters) // Inactive -> Active profiler_ensure_started(PROFILER_DEFAULT_ENTRIES, PROFILER_DEFAULT_INTERVAL, - features, filters, std::size(filters), 0); + features, filters, MOZ_ARRAY_LENGTH(filters), 0); // Output all "TestCounter"s, with increasing delays (to test different // number of counter samplings). @@ -3666,7 +3669,7 @@ TEST(GeckoProfiler, Time) // profiler_start() restarts the timer used by profiler_time(). profiler_start(PROFILER_DEFAULT_ENTRIES, PROFILER_DEFAULT_INTERVAL, features, - filters, std::size(filters), 0); + filters, MOZ_ARRAY_LENGTH(filters), 0); double t3 = profiler_time(); double t4 = profiler_time(); @@ -3687,7 +3690,7 @@ TEST(GeckoProfiler, GetProfile) ASSERT_TRUE(!profiler_get_profile()); profiler_start(PROFILER_DEFAULT_ENTRIES, PROFILER_DEFAULT_INTERVAL, features, - filters, std::size(filters), 0); + filters, MOZ_ARRAY_LENGTH(filters), 0); mozilla::Maybe activeFeatures = profiler_features_if_active(); ASSERT_TRUE(activeFeatures.isSome()); @@ -3750,7 +3753,7 @@ TEST(GeckoProfiler, StreamJSONForThisProcess) MOZ_RELEASE_ASSERT(!w.GetFailure()); profiler_start(PROFILER_DEFAULT_ENTRIES, PROFILER_DEFAULT_INTERVAL, features, - filters, std::size(filters), 0); + filters, MOZ_ARRAY_LENGTH(filters), 0); w.Start(); ASSERT_TRUE(::profiler_stream_json_for_this_process(w).isOk()); @@ -3814,7 +3817,7 @@ TEST(GeckoProfiler, StreamJSONForThisProcessThreaded) // Start the profiler on the main thread. profiler_start(PROFILER_DEFAULT_ENTRIES, PROFILER_DEFAULT_INTERVAL, features, - filters, std::size(filters), 0); + filters, MOZ_ARRAY_LENGTH(filters), 0); // Call profiler_stream_json_for_this_process on a background thread. NS_DispatchAndSpinEventLoopUntilComplete( @@ -3880,7 +3883,7 @@ TEST(GeckoProfiler, ProfilingStack) "A::C3", JS, NS_ConvertUTF8toUTF16(dynamic.get())); profiler_start(PROFILER_DEFAULT_ENTRIES, PROFILER_DEFAULT_INTERVAL, - features, filters, std::size(filters), 0); + features, filters, MOZ_ARRAY_LENGTH(filters), 0); ASSERT_TRUE(profiler_get_backtrace()); } @@ -3902,14 +3905,14 @@ TEST(GeckoProfiler, Bug1355807) const char* fewThreadsFilter[] = {"GeckoMain"}; profiler_start(PROFILER_DEFAULT_ENTRIES, PROFILER_DEFAULT_INTERVAL, features, - manyThreadsFilter, std::size(manyThreadsFilter), 0); + manyThreadsFilter, MOZ_ARRAY_LENGTH(manyThreadsFilter), 0); profiler_start(PROFILER_DEFAULT_ENTRIES, PROFILER_DEFAULT_INTERVAL, features, - fewThreadsFilter, std::size(fewThreadsFilter), 0); + fewThreadsFilter, MOZ_ARRAY_LENGTH(fewThreadsFilter), 0); // In bug 1355807 this caused an assertion failure in StopJSSampling(). profiler_start(PROFILER_DEFAULT_ENTRIES, PROFILER_DEFAULT_INTERVAL, features, - fewThreadsFilter, std::size(fewThreadsFilter), 0); + fewThreadsFilter, MOZ_ARRAY_LENGTH(fewThreadsFilter), 0); profiler_stop(); } @@ -3972,7 +3975,7 @@ TEST(GeckoProfiler, SuspendAndSample) const char* filters[] = {"GeckoMain", "Compositor"}; profiler_start(PROFILER_DEFAULT_ENTRIES, PROFILER_DEFAULT_INTERVAL, features, - filters, std::size(filters), 0); + filters, MOZ_ARRAY_LENGTH(filters), 0); ASSERT_TRUE(profiler_is_active()); @@ -3995,7 +3998,8 @@ TEST(GeckoProfiler, PostSamplingCallback) [&](SamplingState) { ASSERT_TRUE(false); })); profiler_start(PROFILER_DEFAULT_ENTRIES, PROFILER_DEFAULT_INTERVAL, - ProfilerFeature::StackWalk, filters, std::size(filters), 0); + ProfilerFeature::StackWalk, filters, MOZ_ARRAY_LENGTH(filters), + 0); { // Stack sampling -> This label should appear at least once. AUTO_PROFILER_LABEL("PostSamplingCallback completed", OTHER); @@ -4044,7 +4048,7 @@ TEST(GeckoProfiler, PostSamplingCallback) profiler_start(PROFILER_DEFAULT_ENTRIES, PROFILER_DEFAULT_INTERVAL, ProfilerFeature::StackWalk | ProfilerFeature::NoStackSampling, - filters, std::size(filters), 0); + filters, MOZ_ARRAY_LENGTH(filters), 0); { // No stack sampling -> This label should not appear. AUTO_PROFILER_LABEL("PostSamplingCallback completed (no stacks)", OTHER); @@ -4108,7 +4112,8 @@ TEST(GeckoProfiler, ProfilingStateCallback) CheckStatesIsEmpty(); profiler_start(PROFILER_DEFAULT_ENTRIES, PROFILER_DEFAULT_INTERVAL, - ProfilerFeature::StackWalk, filters, std::size(filters), 0); + ProfilerFeature::StackWalk, filters, MOZ_ARRAY_LENGTH(filters), + 0); CheckStatesOnlyContains(ProfilingState::Started, 1); @@ -4147,7 +4152,7 @@ TEST(GeckoProfiler, ProfilingStateCallback) // ProfilingState::Stopping is not notified. See `profiler_start` for details. profiler_start(PROFILER_DEFAULT_ENTRIES, PROFILER_DEFAULT_INTERVAL, ProfilerFeature::StackWalk | ProfilerFeature::NoStackSampling, - filters, std::size(filters), 0); + filters, MOZ_ARRAY_LENGTH(filters), 0); CheckStatesOnlyContains(ProfilingState::Started, 1); ASSERT_EQ(WaitForSamplingState(), SamplingState::NoStackSamplingCompleted); UniquePtr profileNoStacks = profiler_get_profile(); @@ -4178,7 +4183,7 @@ TEST(GeckoProfiler, BaseProfilerHandOff) // Start the Base Profiler. baseprofiler::profiler_start( PROFILER_DEFAULT_ENTRIES, PROFILER_DEFAULT_INTERVAL, - ProfilerFeature::StackWalk, filters, std::size(filters)); + ProfilerFeature::StackWalk, filters, MOZ_ARRAY_LENGTH(filters)); ASSERT_TRUE(baseprofiler::profiler_is_active()); ASSERT_TRUE(!profiler_is_active()); @@ -4196,7 +4201,8 @@ TEST(GeckoProfiler, BaseProfilerHandOff) // Start the Gecko Profiler, which should grab the Base Profiler profile and // stop it. profiler_start(PROFILER_DEFAULT_ENTRIES, PROFILER_DEFAULT_INTERVAL, - ProfilerFeature::StackWalk, filters, std::size(filters), 0); + ProfilerFeature::StackWalk, filters, MOZ_ARRAY_LENGTH(filters), + 0); ASSERT_TRUE(!baseprofiler::profiler_is_active()); ASSERT_TRUE(profiler_is_active()); @@ -4282,7 +4288,7 @@ TEST(GeckoProfiler, FeatureCombinations) ProfilerFeature::SamplingAllThreads, ProfilerFeature::MarkersAllThreads, ProfilerFeature::UnregisteredThreads}; - constexpr uint32_t featureCount = uint32_t(std::size(featureList)); + constexpr uint32_t featureCount = uint32_t(MOZ_ARRAY_LENGTH(featureList)); auto testFeatures = [&](uint32_t features, const std::string& featuresString) { @@ -4291,7 +4297,7 @@ TEST(GeckoProfiler, FeatureCombinations) ASSERT_TRUE(!profiler_is_active()); profiler_start(PROFILER_DEFAULT_ENTRIES, PROFILER_DEFAULT_INTERVAL, - features, filters, std::size(filters), 0); + features, filters, MOZ_ARRAY_LENGTH(filters), 0); ASSERT_TRUE(profiler_is_active()); @@ -4434,7 +4440,7 @@ TEST(GeckoProfiler, CPUUsage) PROFILER_DEFAULT_ENTRIES, PROFILER_DEFAULT_INTERVAL, ProfilerFeature::StackWalk | ProfilerFeature::CPUUtilization | (testWithNoStackSampling ? ProfilerFeature::NoStackSampling : 0), - filters, std::size(filters), 0); + filters, MOZ_ARRAY_LENGTH(filters), 0); // Grab a few samples, each with a different label on the stack. # define SAMPLE_LABEL_PREFIX "CPUUsage sample label " static constexpr const char* scSampleLabels[] = { @@ -4686,7 +4692,7 @@ TEST(GeckoProfiler, AllThreads) EXPECT_FALSE(profiler_thread_is_being_profiled_for_markers()); profiler_start(PROFILER_DEFAULT_ENTRIES, PROFILER_DEFAULT_INTERVAL, - features, filters, std::size(filters), 0); + features, filters, MOZ_ARRAY_LENGTH(filters), 0); EXPECT_TRUE(profiler_thread_is_being_profiled( ThreadProfilingFeatures::CPUUtilization)); @@ -4875,7 +4881,7 @@ TEST(GeckoProfiler, FailureHandling) uint32_t features = ProfilerFeature::StackWalk; const char* filters[] = {"GeckoMain"}; profiler_start(PROFILER_DEFAULT_ENTRIES, PROFILER_DEFAULT_INTERVAL, features, - filters, std::size(filters), 0); + filters, MOZ_ARRAY_LENGTH(filters), 0); ASSERT_EQ(WaitForSamplingState(), SamplingState::SamplingCompleted); @@ -4947,7 +4953,7 @@ TEST(GeckoProfiler, NoMarkerStacks) // Start the profiler without the NoMarkerStacks feature and make sure we // capture stacks. profiler_start(PROFILER_DEFAULT_ENTRIES, PROFILER_DEFAULT_INTERVAL, - /* features */ 0, filters, std::size(filters), 0); + /* features */ 0, filters, MOZ_ARRAY_LENGTH(filters), 0); ASSERT_TRUE(profiler_capture_backtrace()); profiler_stop(); @@ -4956,7 +4962,7 @@ TEST(GeckoProfiler, NoMarkerStacks) // Start the profiler without the NoMarkerStacks feature and make sure we // don't capture stacks. profiler_start(PROFILER_DEFAULT_ENTRIES, PROFILER_DEFAULT_INTERVAL, features, - filters, std::size(filters), 0); + filters, MOZ_ARRAY_LENGTH(filters), 0); // Make sure that the active features has the NoMarkerStacks feature. mozilla::Maybe activeFeatures = profiler_features_if_active(); diff --git a/uriloader/exthandler/nsExternalHelperAppService.cpp b/uriloader/exthandler/nsExternalHelperAppService.cpp index c4dc15918032a3..0db5201c3d6330 100644 --- a/uriloader/exthandler/nsExternalHelperAppService.cpp +++ b/uriloader/exthandler/nsExternalHelperAppService.cpp @@ -852,7 +852,7 @@ NS_IMETHODIMP nsExternalHelperAppService::ApplyDecodingForExtension( bool* aApplyDecoding) { *aApplyDecoding = true; uint32_t i; - for (i = 0; i < std::size(nonDecodableExtensions); ++i) { + for (i = 0; i < ArrayLength(nonDecodableExtensions); ++i) { if (aExtension.LowerCaseEqualsASCII( nonDecodableExtensions[i].mFileExtension) && aEncodingType.LowerCaseEqualsASCII( @@ -1483,7 +1483,7 @@ nsresult nsExternalAppHandler::SetUpTempFile(nsIChannel* aChannel) { NS_ERROR_UNEXPECTED); // Strip off the ".part" from mTempLeafName - mTempLeafName.Truncate(mTempLeafName.Length() - std::size(".part") + 1); + mTempLeafName.Truncate(mTempLeafName.Length() - ArrayLength(".part") + 1); MOZ_ASSERT(!mSaver, "Output file initialization called more than once!"); mSaver = @@ -2581,7 +2581,7 @@ nsresult nsExternalAppHandler::ContinueSave(nsIFile* aNewFileLocation) { mFinalFileDestination->GetPath(path); CheckedInt fullPathLength = CheckedInt(path.Length()) + 1 + randomChars.Length() + - std::size(".part"); + ArrayLength(".part"); if (!fullPathLength.isValid()) { leafName.Truncate(); } else if (fullPathLength.value() > MAX_PATH) { @@ -3208,7 +3208,7 @@ bool nsExternalHelperAppService::GetTypeFromExtras(const nsACString& aExtension, // Look for default entry with matching extension. nsDependentCString::const_iterator start, end, iter; - int32_t numEntries = std::size(extraMimeEntries); + int32_t numEntries = ArrayLength(extraMimeEntries); for (int32_t index = 0; index < numEntries; index++) { nsDependentCString extList(extraMimeEntries[index].mFileExtensions); extList.BeginReading(start); diff --git a/uriloader/exthandler/win/nsMIMEInfoWin.cpp b/uriloader/exthandler/win/nsMIMEInfoWin.cpp index 3797a62a8f09d8..38d460ef37ac8b 100644 --- a/uriloader/exthandler/win/nsMIMEInfoWin.cpp +++ b/uriloader/exthandler/win/nsMIMEInfoWin.cpp @@ -121,7 +121,8 @@ nsMIMEInfoWin::LaunchWithFile(nsIFile* aFile) { appArg.Append(path); const wchar_t* argv[] = {appArg.get(), path.get()}; - return ShellExecuteWithIFile(defaultApp, std::size(argv), argv); + return ShellExecuteWithIFile(defaultApp, mozilla::ArrayLength(argv), + argv); } } } @@ -206,7 +207,7 @@ nsMIMEInfoWin::LaunchWithFile(nsIFile* aFile) { nsAutoString path; aFile->GetPath(path); const wchar_t* argv[] = {path.get()}; - return ShellExecuteWithIFile(executable, std::size(argv), argv); + return ShellExecuteWithIFile(executable, mozilla::ArrayLength(argv), argv); } return NS_ERROR_INVALID_ARG; diff --git a/widget/GfxInfoBase.cpp b/widget/GfxInfoBase.cpp index 811de7efad6bef..c84cce34062513 100644 --- a/widget/GfxInfoBase.cpp +++ b/widget/GfxInfoBase.cpp @@ -1605,7 +1605,7 @@ const char* chromebookProductList[] = { bool ProductIsChromebook(nsCString product) { size_t result; return BinarySearchIf( - chromebookProductList, 0, std::size(chromebookProductList), + chromebookProductList, 0, ArrayLength(chromebookProductList), [&](const char* const aValue) -> int { return strcmp(product.get(), aValue); }, diff --git a/widget/ScrollbarDrawing.cpp b/widget/ScrollbarDrawing.cpp index ebf00cacddd4f0..33a78ddf1cc800 100644 --- a/widget/ScrollbarDrawing.cpp +++ b/widget/ScrollbarDrawing.cpp @@ -388,7 +388,7 @@ bool ScrollbarDrawing::PaintScrollbarButton( const float kPolygonSize = 17; - const int32_t arrowNumPoints = std::size(arrowPolygonX); + const int32_t arrowNumPoints = ArrayLength(arrowPolygonX); switch (aAppearance) { case StyleAppearance::ScrollbarbuttonUp: break; diff --git a/widget/ScrollbarDrawingWin11.cpp b/widget/ScrollbarDrawingWin11.cpp index d30c1380b2d2de..8517b60baa81a1 100644 --- a/widget/ScrollbarDrawingWin11.cpp +++ b/widget/ScrollbarDrawingWin11.cpp @@ -188,7 +188,7 @@ bool ScrollbarDrawingWin11::PaintScrollbarButton( const float polygonSize = style == Style::Overlay ? float(kDefaultWinOverlayScrollbarSize) : float(kDefaultWinScrollbarSize); - const int32_t arrowNumPoints = std::size(arrowPolygonX); + const int32_t arrowNumPoints = ArrayLength(arrowPolygonX); if (aElementState.HasState(ElementState::ACTIVE)) { arrowX = arrowPolygonXActive; diff --git a/widget/Theme.cpp b/widget/Theme.cpp index 85234c1bc7d85e..564c16e5870df8 100644 --- a/widget/Theme.cpp +++ b/widget/Theme.cpp @@ -838,7 +838,7 @@ void Theme::PaintMenulistArrow(nsIFrame* aFrame, DrawTarget& aDrawTarget, const auto arrowColor = sRGBColor::FromABGR( nsLayoutUtils::GetTextColor(aFrame, &nsStyleText::mWebkitTextFillColor)); ThemeDrawing::PaintArrow(aDrawTarget, aRect, xs, ys, kPolygonSize, - std::size(polygonX), arrowColor); + ArrayLength(polygonX), arrowColor); } void Theme::PaintSpinnerButton(nsIFrame* aFrame, DrawTarget& aDrawTarget, @@ -864,7 +864,7 @@ void Theme::PaintSpinnerButton(nsIFrame* aFrame, DrawTarget& aDrawTarget, } ThemeDrawing::PaintArrow(aDrawTarget, aRect, kPolygonX, polygonY, - kPolygonSize, std::size(kPolygonX), borderColor); + kPolygonSize, ArrayLength(kPolygonX), borderColor); } template diff --git a/widget/WidgetEventImpl.cpp b/widget/WidgetEventImpl.cpp index 676b70069a3cba..44b5a3d67297d8 100644 --- a/widget/WidgetEventImpl.cpp +++ b/widget/WidgetEventImpl.cpp @@ -1442,8 +1442,9 @@ void WidgetKeyboardEvent::GetDOMKeyName(KeyNameIndex aKeyNameIndex, return; } - MOZ_RELEASE_ASSERT(static_cast(aKeyNameIndex) < std::size(kKeyNames), - "Illegal key enumeration value"); + MOZ_RELEASE_ASSERT( + static_cast(aKeyNameIndex) < ArrayLength(kKeyNames), + "Illegal key enumeration value"); aKeyName = kKeyNames[aKeyNameIndex]; } @@ -1456,7 +1457,7 @@ void WidgetKeyboardEvent::GetDOMCodeName(CodeNameIndex aCodeNameIndex, } MOZ_RELEASE_ASSERT( - static_cast(aCodeNameIndex) < std::size(kCodeNames), + static_cast(aCodeNameIndex) < ArrayLength(kCodeNames), "Illegal physical code enumeration value"); // Generate some continuous runs of codes, rather than looking them up. @@ -1495,8 +1496,8 @@ void WidgetKeyboardEvent::GetDOMCodeName(CodeNameIndex aCodeNameIndex, /* static */ KeyNameIndex WidgetKeyboardEvent::GetKeyNameIndex(const nsAString& aKeyValue) { if (!sKeyNameIndexHashtable) { - sKeyNameIndexHashtable = new KeyNameIndexHashtable(std::size(kKeyNames)); - for (size_t i = 0; i < std::size(kKeyNames); i++) { + sKeyNameIndexHashtable = new KeyNameIndexHashtable(ArrayLength(kKeyNames)); + for (size_t i = 0; i < ArrayLength(kKeyNames); i++) { sKeyNameIndexHashtable->InsertOrUpdate(nsDependentString(kKeyNames[i]), static_cast(i)); } @@ -1509,8 +1510,9 @@ KeyNameIndex WidgetKeyboardEvent::GetKeyNameIndex(const nsAString& aKeyValue) { CodeNameIndex WidgetKeyboardEvent::GetCodeNameIndex( const nsAString& aCodeValue) { if (!sCodeNameIndexHashtable) { - sCodeNameIndexHashtable = new CodeNameIndexHashtable(std::size(kCodeNames)); - for (size_t i = 0; i < std::size(kCodeNames); i++) { + sCodeNameIndexHashtable = + new CodeNameIndexHashtable(ArrayLength(kCodeNames)); + for (size_t i = 0; i < ArrayLength(kCodeNames); i++) { sCodeNameIndexHashtable->InsertOrUpdate(nsDependentString(kCodeNames[i]), static_cast(i)); } @@ -1566,7 +1568,7 @@ uint32_t WidgetKeyboardEvent::GetFallbackKeyCodeOfPunctuationKey( #undef NS_DEFINE_COMMAND_WITH_PARAM #undef NS_DEFINE_COMMAND_NO_EXEC_COMMAND - MOZ_RELEASE_ASSERT(static_cast(aCommand) < std::size(kCommands), + MOZ_RELEASE_ASSERT(static_cast(aCommand) < ArrayLength(kCommands), "Illegal command enumeration value"); return kCommands[static_cast(aCommand)]; } @@ -2179,7 +2181,7 @@ void InternalEditorInputEvent::GetDOMInputTypeName(EditorInputType aInputType, } MOZ_RELEASE_ASSERT( - static_cast(aInputType) < std::size(kInputTypeNames), + static_cast(aInputType) < ArrayLength(kInputTypeNames), "Illegal input type enumeration value"); aInputTypeName.Assign(kInputTypeNames[static_cast(aInputType)]); } @@ -2192,8 +2194,8 @@ EditorInputType InternalEditorInputEvent::GetEditorInputType( } if (!sInputTypeHashtable) { - sInputTypeHashtable = new InputTypeHashtable(std::size(kInputTypeNames)); - for (size_t i = 0; i < std::size(kInputTypeNames); i++) { + sInputTypeHashtable = new InputTypeHashtable(ArrayLength(kInputTypeNames)); + for (size_t i = 0; i < ArrayLength(kInputTypeNames); i++) { sInputTypeHashtable->InsertOrUpdate(nsDependentString(kInputTypeNames[i]), static_cast(i)); } diff --git a/widget/cocoa/nsChildView.mm b/widget/cocoa/nsChildView.mm index 923056ea9d8ef5..21ba7c130fc63a 100644 --- a/widget/cocoa/nsChildView.mm +++ b/widget/cocoa/nsChildView.mm @@ -1473,7 +1473,7 @@ static void blinkRgn(RgnHandle rgn) { kCGEventOtherMouseDragged}; uint32_t eventCount = 0; - for (uint32_t i = 0; i < std::size(eventTypes); ++i) { + for (uint32_t i = 0; i < ArrayLength(eventTypes); ++i) { eventCount += CGEventSourceCounterForEventType( kCGEventSourceStateCombinedSessionState, eventTypes[i]); } diff --git a/widget/cocoa/nsCocoaUtils.mm b/widget/cocoa/nsCocoaUtils.mm index 6d5e37167be80a..a25a9738b949f3 100644 --- a/widget/cocoa/nsCocoaUtils.mm +++ b/widget/cocoa/nsCocoaUtils.mm @@ -704,7 +704,7 @@ static bool ComputeIsEntirelyBlack(const DataSourceSurface::MappedSurface& aMap, {MODIFIER_NUMLOCK, NSEventModifierFlagNumericPad}}; NSUInteger modifierFlags = 0; - for (uint32_t i = 0; i < std::size(sModifierFlagMap); ++i) { + for (uint32_t i = 0; i < ArrayLength(sModifierFlagMap); ++i) { if (aKeyEvent.mModifiers & sModifierFlagMap[i][0]) { modifierFlags |= sModifierFlagMap[i][1]; } @@ -1065,7 +1065,7 @@ - (void)insertText:(id)aString { uint32_t keyCodeNameLength = keyCodeName.Length(); const char* keyCodeNameStr = keyCodeName.get(); - for (uint16_t i = 0; i < std::size(gKeyConversions); ++i) { + for (uint16_t i = 0; i < ArrayLength(gKeyConversions); ++i) { if (keyCodeNameLength == gKeyConversions[i].strLength && nsCRT::strcmp(gKeyConversions[i].str, keyCodeNameStr) == 0) { return gKeyConversions[i].charCode; @@ -1080,7 +1080,7 @@ - (void)insertText:(id)aString { return 0; } - for (uint16_t i = 0; i < std::size(gKeyConversions); ++i) { + for (uint16_t i = 0; i < ArrayLength(gKeyConversions); ++i) { if (gKeyConversions[i].geckoKeyCode == aKeyCode) { return gKeyConversions[i].charCode; } diff --git a/widget/cocoa/nsNativeThemeCocoa.mm b/widget/cocoa/nsNativeThemeCocoa.mm index a97a7813fd348a..fd89533dee74a5 100644 --- a/widget/cocoa/nsNativeThemeCocoa.mm +++ b/widget/cocoa/nsNativeThemeCocoa.mm @@ -789,7 +789,7 @@ static void DrawCellWithSnapping(NSCell* cell, CGContextRef cgContext, // Snap to the smaller control size. controlSize = smallerControlSize; sizeIndex = smallerControlSizeIndex; - MOZ_ASSERT(sizeIndex < std::size(settings.naturalSizes)); + MOZ_ASSERT(sizeIndex < ArrayLength(settings.naturalSizes)); // Resize and center the drawRect. if (sizes[sizeIndex].width) { @@ -814,7 +814,7 @@ static void DrawCellWithSnapping(NSCell* cell, CGContextRef cgContext, [cell setControlSize:controlSize]; - MOZ_ASSERT(sizeIndex < std::size(settings.minimumSizes)); + MOZ_ASSERT(sizeIndex < ArrayLength(settings.minimumSizes)); const NSSize minimumSize = settings.minimumSizes[sizeIndex]; DrawCellWithScaling(cell, cgContext, drawRect, controlSize, sizes[sizeIndex], minimumSize, settings.margins, view, mirrorHorizontal); diff --git a/widget/cocoa/nsPrintDialogX.mm b/widget/cocoa/nsPrintDialogX.mm index d74413a5267e18..5cad69d547cfbc 100644 --- a/widget/cocoa/nsPrintDialogX.mm +++ b/widget/cocoa/nsPrintDialogX.mm @@ -390,7 +390,7 @@ - (NSPopUpButton*)headerFooterItemListWithFrame:(NSRect)aRect [list addItemsWithTitles:items]; NS_ConvertUTF16toUTF8 currentStringUTF8(aCurrentString); - for (unsigned int i = 0; i < std::size(sHeaderFooterTags); i++) { + for (unsigned int i = 0; i < ArrayLength(sHeaderFooterTags); i++) { if (!strcmp(currentStringUTF8.get(), sHeaderFooterTags[i])) { [list selectItemAtIndex:i]; break; @@ -507,7 +507,7 @@ - (void)addHeaderFooterSection { - (const char*)headerFooterStringForList:(NSPopUpButton*)aList { NSInteger index = [aList indexOfSelectedItem]; - NS_ASSERTION(index < NSInteger(std::size(sHeaderFooterTags)), + NS_ASSERTION(index < NSInteger(ArrayLength(sHeaderFooterTags)), "Index of dropdown is higher than expected!"); return sHeaderFooterTags[index]; } diff --git a/widget/gtk/DBusMenu.cpp b/widget/gtk/DBusMenu.cpp index ba5d7dbcf5ebcb..8ba7739f4ab5a6 100644 --- a/widget/gtk/DBusMenu.cpp +++ b/widget/gtk/DBusMenu.cpp @@ -49,7 +49,7 @@ static bool sLibPresent; return false; \ } \ } \ - for (uint32_t i = 0; i < std::size(k##symbol##Symbols); ++i) { \ + for (uint32_t i = 0; i < mozilla::ArrayLength(k##symbol##Symbols); ++i) { \ *k##symbol##Symbols[i].function = \ PR_FindFunctionSymbol(g##symbol, k##symbol##Symbols[i].functionName); \ if (!*k##symbol##Symbols[i].function) { \ diff --git a/widget/gtk/NativeKeyBindings.cpp b/widget/gtk/NativeKeyBindings.cpp index b50a3379676561..e050fd07c02392 100644 --- a/widget/gtk/NativeKeyBindings.cpp +++ b/widget/gtk/NativeKeyBindings.cpp @@ -95,7 +95,7 @@ static void delete_from_cursor_cb(GtkWidget* w, GtkDeleteType del_type, } gHandled = true; - if (uint32_t(del_type) >= std::size(sDeleteCommands)) { + if (uint32_t(del_type) >= ArrayLength(sDeleteCommands)) { // unsupported deletion type return; } @@ -178,7 +178,7 @@ static void move_cursor_cb(GtkWidget* w, GtkMovementStep step, gint count, gHandled = true; bool forward = count > 0; - if (uint32_t(step) >= std::size(sMoveCommands)) { + if (uint32_t(step) >= ArrayLength(sMoveCommands)) { // unsupported movement type return; } diff --git a/widget/gtk/nsClipboard.cpp b/widget/gtk/nsClipboard.cpp index 288f0a95f3b08e..630cc848ed9fc8 100644 --- a/widget/gtk/nsClipboard.cpp +++ b/widget/gtk/nsClipboard.cpp @@ -523,7 +523,7 @@ static bool TransferableSetHTML(nsITransferable* aTransferable, // Remove kHTMLMarkupPrefix again, it won't necessarily cause any // issues, but might confuse other users. - const size_t prefixLen = std::size(kHTMLMarkupPrefix) - 1; + const size_t prefixLen = ArrayLength(kHTMLMarkupPrefix) - 1; if (aData.Length() >= prefixLen && nsDependentCSubstring(aData.To(prefixLen)) .EqualsLiteral(kHTMLMarkupPrefix)) { aData = aData.From(prefixLen); @@ -1215,7 +1215,7 @@ void nsClipboard::SelectionGetEvent(GtkClipboard* aClipboard, kJPGImageMime, kGIFImageMime}; nsCOMPtr imageItem; nsCOMPtr image; - for (uint32_t i = 0; i < std::size(imageMimeTypes); i++) { + for (uint32_t i = 0; i < ArrayLength(imageMimeTypes); i++) { rv = trans->GetTransferData(imageMimeTypes[i], getter_AddRefs(imageItem)); if (NS_FAILED(rv)) { MOZ_CLIPBOARD_LOG(" %s is missing at GetTransferData()\n", diff --git a/widget/gtk/nsDragService.cpp b/widget/gtk/nsDragService.cpp index 888578585394d9..74ccf585d1e08d 100644 --- a/widget/gtk/nsDragService.cpp +++ b/widget/gtk/nsDragService.cpp @@ -2586,7 +2586,7 @@ const char* nsDragSession::GetDragServiceTaskName(DragTask aTask) { static const char* taskNames[] = {"eDragTaskNone", "eDragTaskMotion", "eDragTaskLeave", "eDragTaskDrop", "eDragTaskSourceEnd"}; - MOZ_ASSERT(size_t(aTask) < std::size(taskNames)); + MOZ_ASSERT(size_t(aTask) < ArrayLength(taskNames)); return taskNames[aTask]; } #endif diff --git a/widget/gtk/nsGtkKeyUtils.cpp b/widget/gtk/nsGtkKeyUtils.cpp index 052a94df886a73..8582120d1ee39e 100644 --- a/widget/gtk/nsGtkKeyUtils.cpp +++ b/widget/gtk/nsGtkKeyUtils.cpp @@ -531,7 +531,7 @@ void KeymapWrapper::InitBySystemSettingsX11() { // mod[0] is Modifier introduced by Mod1. MappedModifier mod[5]; int32_t foundLevel[5]; - for (uint32_t i = 0; i < std::size(mod); i++) { + for (uint32_t i = 0; i < ArrayLength(mod); i++) { mod[i] = NOT_MODIFIER; foundLevel[i] = INT32_MAX; } @@ -630,7 +630,7 @@ void KeymapWrapper::InitBySystemSettingsX11() { default: MOZ_CRASH("All indexes must be handled here"); } - for (uint32_t j = 0; j < std::size(mod); j++) { + for (uint32_t j = 0; j < ArrayLength(mod); j++) { if (modifier == mod[j]) { mModifierMasks[i] |= 1 << (j + 3); } @@ -2035,7 +2035,7 @@ bool KeymapWrapper::IsLatinGroup(guint8 aGroup) { bool KeymapWrapper::IsAutoRepeatableKey(guint aHardwareKeyCode) { #ifdef MOZ_X11 uint8_t indexOfArray = aHardwareKeyCode / 8; - MOZ_ASSERT(indexOfArray < std::size(mKeyboardState.auto_repeats), + MOZ_ASSERT(indexOfArray < ArrayLength(mKeyboardState.auto_repeats), "invalid index"); char bitMask = 1 << (aHardwareKeyCode % 8); return (mKeyboardState.auto_repeats[indexOfArray] & bitMask) != 0; diff --git a/widget/gtk/nsPrintDialogGTK.cpp b/widget/gtk/nsPrintDialogGTK.cpp index f1792be312a9ac..3885a94c24cb8e 100644 --- a/widget/gtk/nsPrintDialogGTK.cpp +++ b/widget/gtk/nsPrintDialogGTK.cpp @@ -46,7 +46,7 @@ using namespace mozilla::widget; static const char header_footer_tags[][4] = {"", "&T", "&U", "&D", "&P", "&PT"}; -#define CUSTOM_VALUE_INDEX gint(std::size(header_footer_tags)) +#define CUSTOM_VALUE_INDEX gint(ArrayLength(header_footer_tags)) static GtkWindow* get_gtk_window_for_nsiwidget(nsIWidget* widget) { return GTK_WINDOW(widget->GetNativeData(NS_NATIVE_SHELLWIDGET)); @@ -267,7 +267,7 @@ nsPrintDialogWidgetGTK::nsPrintDialogWidgetGTK(nsPIDOMWindowOuter* aParent, aSettings->GetHeaderStrCenter(header_footer_str[1]); aSettings->GetHeaderStrRight(header_footer_str[2]); - for (unsigned int i = 0; i < std::size(header_dropdown); i++) { + for (unsigned int i = 0; i < ArrayLength(header_dropdown); i++) { header_dropdown[i] = ConstructHeaderFooterDropdown(header_footer_str[i].get()); // Those 4 magic numbers in the middle provide the position in the table. @@ -278,7 +278,7 @@ nsPrintDialogWidgetGTK::nsPrintDialogWidgetGTK(nsPIDOMWindowOuter* aParent, } const char labelKeys[][7] = {"left", "center", "right"}; - for (unsigned int i = 0; i < std::size(labelKeys); i++) { + for (unsigned int i = 0; i < ArrayLength(labelKeys); i++) { gtk_table_attach(GTK_TABLE(header_footer_table), gtk_label_new(GetUTF8FromBundle(labelKeys[i]).get()), i, (i + 1), 1, 2, (GtkAttachOptions)0, (GtkAttachOptions)0, 2, @@ -289,7 +289,7 @@ nsPrintDialogWidgetGTK::nsPrintDialogWidgetGTK(nsPIDOMWindowOuter* aParent, aSettings->GetFooterStrCenter(header_footer_str[1]); aSettings->GetFooterStrRight(header_footer_str[2]); - for (unsigned int i = 0; i < std::size(footer_dropdown); i++) { + for (unsigned int i = 0; i < ArrayLength(footer_dropdown); i++) { footer_dropdown[i] = ConstructHeaderFooterDropdown(header_footer_str[i].get()); gtk_table_attach(GTK_TABLE(header_footer_table), footer_dropdown[i], i, @@ -468,7 +468,7 @@ GtkWidget* nsPrintDialogWidgetGTK::ConstructHeaderFooterDropdown( "headerFooterPage", "headerFooterPageTotal", "headerFooterCustom"}; - for (unsigned int i = 0; i < std::size(hf_options); i++) { + for (unsigned int i = 0; i < ArrayLength(hf_options); i++) { gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(dropdown), nullptr, GetUTF8FromBundle(hf_options[i]).get()); } @@ -476,7 +476,7 @@ GtkWidget* nsPrintDialogWidgetGTK::ConstructHeaderFooterDropdown( bool shouldBeCustom = true; NS_ConvertUTF16toUTF8 currentStringUTF8(currentString); - for (unsigned int i = 0; i < std::size(header_footer_tags); i++) { + for (unsigned int i = 0; i < ArrayLength(header_footer_tags); i++) { if (!strcmp(currentStringUTF8.get(), header_footer_tags[i])) { gtk_combo_box_set_active(GTK_COMBO_BOX(dropdown), i); g_object_set_data(G_OBJECT(dropdown), "previous-active", diff --git a/widget/gtk/nsWindow.cpp b/widget/gtk/nsWindow.cpp index fe1870ba059c4b..b22a1e5cc19349 100644 --- a/widget/gtk/nsWindow.cpp +++ b/widget/gtk/nsWindow.cpp @@ -3497,9 +3497,9 @@ void nsWindow::SetIcon(const nsAString& aIconSpec) { u"48.png", u"64.png", u"128.png", u"256.png", u".xpm", u"16.xpm"}; - for (uint32_t i = 0; i < std::size(extensions); i++) { + for (uint32_t i = 0; i < ArrayLength(extensions); i++) { // Don't bother looking for XPM versions if we found a PNG. - if (i == std::size(extensions) - 2 && foundIcon) break; + if (i == ArrayLength(extensions) - 2 && foundIcon) break; ResolveIconName(aIconSpec, nsDependentString(extensions[i]), getter_AddRefs(iconFile)); diff --git a/widget/nsBaseWidget.cpp b/widget/nsBaseWidget.cpp index 6428bb56cfa570..bc507c43246969 100644 --- a/widget/nsBaseWidget.cpp +++ b/widget/nsBaseWidget.cpp @@ -3353,7 +3353,7 @@ static PrefPair debug_PrefValues[] = { bool nsBaseWidget::debug_GetCachedBoolPref(const char* aPrefName) { NS_ASSERTION(nullptr != aPrefName, "cmon, pref name is null."); - for (uint32_t i = 0; i < std::size(debug_PrefValues); i++) { + for (uint32_t i = 0; i < ArrayLength(debug_PrefValues); i++) { if (strcmp(debug_PrefValues[i].name, aPrefName) == 0) { return debug_PrefValues[i].value; } @@ -3365,7 +3365,7 @@ bool nsBaseWidget::debug_GetCachedBoolPref(const char* aPrefName) { static void debug_SetCachedBoolPref(const char* aPrefName, bool aValue) { NS_ASSERTION(nullptr != aPrefName, "cmon, pref name is null."); - for (uint32_t i = 0; i < std::size(debug_PrefValues); i++) { + for (uint32_t i = 0; i < ArrayLength(debug_PrefValues); i++) { if (strcmp(debug_PrefValues[i].name, aPrefName) == 0) { debug_PrefValues[i].value = aValue; @@ -3408,7 +3408,7 @@ Debug_PrefObserver::Observe(nsISupports* subject, const char* topic, once = false; nsCOMPtr obs(new Debug_PrefObserver()); - for (uint32_t i = 0; i < std::size(debug_PrefValues); i++) { + for (uint32_t i = 0; i < ArrayLength(debug_PrefValues); i++) { // Initialize the pref values debug_PrefValues[i].value = Preferences::GetBool(debug_PrefValues[i].name, false); diff --git a/widget/nsPaper.h b/widget/nsPaper.h index 1522fc081a5fb6..b0117b73064d45 100644 --- a/widget/nsPaper.h +++ b/widget/nsPaper.h @@ -97,7 +97,8 @@ class nsPaper final : public nsIPaper { CommonPaperSize{u"na_ledger"_ns, "tabloid"_ns, {11 in, 17 in}}}; #undef mm #undef in - static constexpr size_t kNumCommonPaperSizes = std::size(kCommonPaperSizes); + static constexpr size_t kNumCommonPaperSizes = + mozilla::ArrayLength(kCommonPaperSizes); private: ~nsPaper(); diff --git a/widget/nsXPLookAndFeel.cpp b/widget/nsXPLookAndFeel.cpp index c04aef16450634..fe31dd9e561cb4 100644 --- a/widget/nsXPLookAndFeel.cpp +++ b/widget/nsXPLookAndFeel.cpp @@ -194,7 +194,7 @@ static const char sIntPrefs[][45] = { "ui.fullKeyboardAccess", }; -static_assert(std::size(sIntPrefs) == size_t(LookAndFeel::IntID::End), +static_assert(ArrayLength(sIntPrefs) == size_t(LookAndFeel::IntID::End), "Should have a pref for each int value"); // This array MUST be kept in the same order as the float id list in @@ -209,7 +209,7 @@ static const char sFloatPrefs[][37] = { }; // clang-format on -static_assert(std::size(sFloatPrefs) == size_t(LookAndFeel::FloatID::End), +static_assert(ArrayLength(sFloatPrefs) == size_t(LookAndFeel::FloatID::End), "Should have a pref for each float value"); // This array MUST be kept in the same order as the color list in @@ -322,7 +322,7 @@ static const char sColorPrefs[][41] = { "ui.themedScrollbarThumbInactive", }; -static_assert(std::size(sColorPrefs) == size_t(LookAndFeel::ColorID::End), +static_assert(ArrayLength(sColorPrefs) == size_t(LookAndFeel::ColorID::End), "Should have a pref for each color value"); // This array MUST be kept in the same order as the SystemFont enum. @@ -339,7 +339,7 @@ static const char sFontPrefs[][41] = { "ui.font.-moz-field", }; -static_assert(std::size(sFontPrefs) == size_t(LookAndFeel::FontID::End), +static_assert(ArrayLength(sFontPrefs) == size_t(LookAndFeel::FontID::End), "Should have a pref for each font value"); const char* nsXPLookAndFeel::GetColorPrefName(ColorID aId) { diff --git a/widget/windows/GfxInfo.cpp b/widget/windows/GfxInfo.cpp index c2ee366eacc78f..78304ee3a448c0 100644 --- a/widget/windows/GfxInfo.cpp +++ b/widget/windows/GfxInfo.cpp @@ -483,8 +483,8 @@ nsresult GfxInfo::Init() { } // make sure the string is nullptr terminated - if (wcsnlen(displayDevice.DeviceKey, std::size(displayDevice.DeviceKey)) == - std::size(displayDevice.DeviceKey)) { + if (wcsnlen(displayDevice.DeviceKey, ArrayLength(displayDevice.DeviceKey)) == + ArrayLength(displayDevice.DeviceKey)) { // we did not find a nullptr return rv; } @@ -501,12 +501,13 @@ nsresult GfxInfo::Init() { */ if (displayDevice.DeviceKey[0] != '\0') { if (_wcsnicmp(displayDevice.DeviceKey, DEVICE_KEY_PREFIX, - std::size(DEVICE_KEY_PREFIX) - 1) != 0) { + ArrayLength(DEVICE_KEY_PREFIX) - 1) != 0) { return rv; } // chop off DEVICE_KEY_PREFIX - mDeviceKey[0] = displayDevice.DeviceKey + std::size(DEVICE_KEY_PREFIX) - 1; + mDeviceKey[0] = + displayDevice.DeviceKey + ArrayLength(DEVICE_KEY_PREFIX) - 1; } else { mDeviceKey[0].Truncate(); } diff --git a/widget/windows/KeyboardLayout.cpp b/widget/windows/KeyboardLayout.cpp index 88445add25c932..cb6c9f5c618df7 100644 --- a/widget/windows/KeyboardLayout.cpp +++ b/widget/windows/KeyboardLayout.cpp @@ -547,7 +547,7 @@ static const nsCString GetMessageName(UINT aMessage) { } static const nsCString GetVirtualKeyCodeName(WPARAM aVK) { - if (aVK >= std::size(kVirtualKeyName)) { + if (aVK >= ArrayLength(kVirtualKeyName)) { return nsPrintfCString("Invalid (0x%08zX)", aVK); } return nsCString(kVirtualKeyName[aVK]); @@ -1107,7 +1107,7 @@ void VirtualKey::SetNormalChars(ShiftState aShiftState, const char16_t* aChars, (aChars[index] >= 0x20) ? aChars[index] : 0; } - uint32_t len = std::size(mShiftStates[aShiftState].Normal.Chars); + uint32_t len = ArrayLength(mShiftStates[aShiftState].Normal.Chars); for (uint32_t index = aNumOfChars; index < len; index++) { mShiftStates[aShiftState].Normal.Chars[index] = 0; } @@ -1181,7 +1181,7 @@ UniCharsAndModifiers VirtualKey::GetNativeUniChars( return result; } - uint32_t len = std::size(mShiftStates[kShiftStateIndex].Normal.Chars); + uint32_t len = ArrayLength(mShiftStates[kShiftStateIndex].Normal.Chars); for (uint32_t i = 0; i < len && mShiftStates[kShiftStateIndex].Normal.Chars[i]; i++) { result.Append(mShiftStates[kShiftStateIndex].Normal.Chars[i], modifiers); @@ -4437,10 +4437,10 @@ void KeyboardLayout::LoadLayout(HKL aLayout) { if (vki < 0) { continue; } - NS_ASSERTION(uint32_t(vki) < std::size(mVirtualKeys), "invalid index"); + NS_ASSERTION(uint32_t(vki) < ArrayLength(mVirtualKeys), "invalid index"); char16_t uniChars[5]; int32_t ret = ::ToUnicodeEx(virtualKey, 0, kbdState, (LPWSTR)uniChars, - std::size(uniChars), 0, mKeyboardLayout); + ArrayLength(uniChars), 0, mKeyboardLayout); // dead-key if (ret < 0) { shiftStatesWithDeadKeys |= (1 << shiftState); @@ -4448,7 +4448,7 @@ void KeyboardLayout::LoadLayout(HKL aLayout) { // representation. char16_t deadChar[2]; ret = ::ToUnicodeEx(virtualKey, 0, kbdState, (LPWSTR)deadChar, - std::size(deadChar), 0, mKeyboardLayout); + ArrayLength(deadChar), 0, mKeyboardLayout); NS_ASSERTION(ret == 2, "Expecting twice repeated dead-key character"); mVirtualKeys[vki].SetDeadChar(shiftState, deadChar[0]); @@ -4524,7 +4524,7 @@ void KeyboardLayout::LoadLayout(HKL aLayout) { MOZ_LOG(gKeyLog, LogLevel::Verbose, ("Logging virtual keycode values for scancode (0x%p)...", mKeyboardLayout)); - for (uint32_t i = 0; i < std::size(kExtendedScanCode); i++) { + for (uint32_t i = 0; i < ArrayLength(kExtendedScanCode); i++) { for (uint32_t j = 1; j <= 0xFF; j++) { UINT scanCode = kExtendedScanCode[i] + j; UINT virtualKeyCode = @@ -4631,7 +4631,7 @@ bool KeyboardLayout::EnsureDeadKeyActive(bool aIsActive, uint8_t aDeadKey, char16_t dummyChars[5]; ret = ::ToUnicodeEx(aDeadKey, 0, (PBYTE)aDeadKeyKbdState, (LPWSTR)dummyChars, - std::size(dummyChars), 0, mKeyboardLayout); + ArrayLength(dummyChars), 0, mKeyboardLayout); // returned values: // <0 - Dead key state is active. The keyboard driver will wait for next // character. @@ -4717,7 +4717,7 @@ uint32_t KeyboardLayout::GetDeadKeyCombinations( char16_t compositeChars[5]; int32_t ret = ::ToUnicodeEx(virtualKey, 0, kbdState, (LPWSTR)compositeChars, - std::size(compositeChars), 0, mKeyboardLayout); + ArrayLength(compositeChars), 0, mKeyboardLayout); switch (ret) { case 0: // This key combination does not produce any characters. The @@ -4726,7 +4726,7 @@ uint32_t KeyboardLayout::GetDeadKeyCombinations( case 1: { char16_t baseChars[5]; ret = ::ToUnicodeEx(virtualKey, 0, kbdState, (LPWSTR)baseChars, - std::size(baseChars), 0, mKeyboardLayout); + ArrayLength(baseChars), 0, mKeyboardLayout); if (entries < aDeadKeyArray.Capacity()) { switch (ret) { case 1: @@ -4753,9 +4753,9 @@ uint32_t KeyboardLayout::GetDeadKeyCombinations( break; } for (int32_t i = 0; i < 5; ++i) { - ret = ::ToUnicodeEx(virtualKey, 0, kbdState, - (LPWSTR)baseChars, std::size(baseChars), - 0, mKeyboardLayout); + ret = ::ToUnicodeEx( + virtualKey, 0, kbdState, (LPWSTR)baseChars, + ArrayLength(baseChars), 0, mKeyboardLayout); if (ret >= 0) { break; } diff --git a/widget/windows/TSFTextStore.cpp b/widget/windows/TSFTextStore.cpp index 97cf7bfe8cb847..a59362ae25c57e 100644 --- a/widget/windows/TSFTextStore.cpp +++ b/widget/windows/TSFTextStore.cpp @@ -216,7 +216,7 @@ static nsCString GetCLSIDNameStr(REFCLSID aCLSID) { static nsCString GetGUIDNameStr(REFGUID aGUID) { OLECHAR str[40]; - int len = ::StringFromGUID2(aGUID, str, std::size(str)); + int len = ::StringFromGUID2(aGUID, str, ArrayLength(str)); if (!len || !str[0]) { return ""_ns; } diff --git a/widget/windows/TaskbarWindowPreview.cpp b/widget/windows/TaskbarWindowPreview.cpp index 703aabe794a47b..4578ac4cf540af 100644 --- a/widget/windows/TaskbarWindowPreview.cpp +++ b/widget/windows/TaskbarWindowPreview.cpp @@ -176,7 +176,7 @@ TaskbarWindowPreview::SetProgressState(nsTaskbarProgressState aState, uint64_t aCurrentValue, uint64_t aMaxValue) { NS_ENSURE_ARG_RANGE(aState, nsTaskbarProgressState(0), - nsTaskbarProgressState(std::size(sNativeStates) - 1)); + nsTaskbarProgressState(ArrayLength(sNativeStates) - 1)); TBPFLAG nativeState = sNativeStates[aState]; if (nativeState == TBPF_NOPROGRESS || nativeState == TBPF_INDETERMINATE) { diff --git a/widget/windows/WinMouseScrollHandler.cpp b/widget/windows/WinMouseScrollHandler.cpp index 1e77a19db227a1..e10f7b29dcd513 100644 --- a/widget/windows/WinMouseScrollHandler.cpp +++ b/widget/windows/WinMouseScrollHandler.cpp @@ -113,7 +113,7 @@ void MouseScrollHandler::MaybeLogKeyState() { } BYTE keyboardState[256]; if (::GetKeyboardState(keyboardState)) { - for (size_t i = 0; i < std::size(keyboardState); i++) { + for (size_t i = 0; i < ArrayLength(keyboardState); i++) { if (keyboardState[i]) { MOZ_LOG(gMouseScrollLog, LogLevel::Debug, (" Current key state: keyboardState[0x%02zX]=0x%02X (%s)", i, @@ -1212,7 +1212,7 @@ bool MouseScrollHandler::Device::Elantech::IsHelperWindow(HWND aWnd) { bool result = false; wchar_t path[256] = {L'\0'}; - if (::GetProcessImageFileNameW(hProcess, path, std::size(path))) { + if (::GetProcessImageFileNameW(hProcess, path, ArrayLength(path))) { int pathLength = lstrlenW(path); if (pathLength >= filenameSuffixLength) { if (lstrcmpiW(path + pathLength - filenameSuffixLength, filenameSuffix) == diff --git a/widget/windows/WinUtils.cpp b/widget/windows/WinUtils.cpp index 29a0bef641788a..fad87bde65fd58 100644 --- a/widget/windows/WinUtils.cpp +++ b/widget/windows/WinUtils.cpp @@ -1361,14 +1361,14 @@ void WinUtils::SetupKeyModifiersSequence(nsTArray* aArray, KeyPair(VK_CONTROL, VK_LCONTROL, ScanCode::eControlLeft)); aArray->AppendElement(KeyPair(VK_MENU, VK_RMENU, ScanCode::eAltRight)); } - for (uint32_t i = std::size(sModifierKeyMap); i; --i) { + for (uint32_t i = ArrayLength(sModifierKeyMap); i; --i) { const uint32_t* map = sModifierKeyMap[i - 1]; if (aModifiers & map[0]) { aArray->AppendElement(KeyPair(map[1], map[2], map[3])); } } } else { - for (uint32_t i = 0; i < std::size(sModifierKeyMap); ++i) { + for (uint32_t i = 0; i < ArrayLength(sModifierKeyMap); ++i) { const uint32_t* map = sModifierKeyMap[i]; if (aModifiers & map[0]) { aArray->AppendElement(KeyPair(map[1], map[2], map[3])); @@ -1797,8 +1797,8 @@ bool WinUtils::MakeLongPath(nsAString& aPath) { wchar_t tempPath[MAX_PATH + 1]; DWORD longResult = GetLongPathNameW((char16ptr_t)PromiseFlatString(aPath).get(), tempPath, - std::size(tempPath)); - if (longResult > std::size(tempPath)) { + ArrayLength(tempPath)); + if (longResult > ArrayLength(tempPath)) { // Our buffer is too short, and we're guaranteeing <= MAX_PATH results. return false; } else if (longResult) { @@ -1817,7 +1817,7 @@ bool WinUtils::UnexpandEnvVars(nsAString& aPath) { // PathUnExpandEnvStringsW returns false if it doesn't make any // substitutions. Silently continue using the unaltered path. if (PathUnExpandEnvStringsW((char16ptr_t)PromiseFlatString(aPath).get(), - tempPath, std::size(tempPath))) { + tempPath, ArrayLength(tempPath))) { aPath = tempPath; MOZ_ASSERT(aPath.Length() <= MAX_PATH); } diff --git a/widget/windows/nsColorPicker.cpp b/widget/windows/nsColorPicker.cpp index 7f9e85ad1f7b26..a754fb222a5cab 100644 --- a/widget/windows/nsColorPicker.cpp +++ b/widget/windows/nsColorPicker.cpp @@ -105,8 +105,9 @@ AsyncColorChooser::Run() { ScopedRtlShimWindow shim(mParentWidget.get()); // This will overwrite custom colors if default colors were defined. - for (size_t i = 0; - i < std::min(std::size(sCustomColors), mDefaultColors.Length()); i++) { + for (size_t i = 0; i < std::min(mozilla::ArrayLength(sCustomColors), + mDefaultColors.Length()); + i++) { sCustomColors[i] = ColorStringToRGB(mDefaultColors[i]); } diff --git a/widget/windows/nsPrintSettingsWin.cpp b/widget/windows/nsPrintSettingsWin.cpp index 9cf14fd7a1bc44..788c4ab6da7698 100644 --- a/widget/windows/nsPrintSettingsWin.cpp +++ b/widget/windows/nsPrintSettingsWin.cpp @@ -166,7 +166,7 @@ nsPrintSettingsWin::nsPrintSettingsWin(const nsPrintSettingsWin& aPS) /* static */ void nsPrintSettingsWin::PaperSizeUnitFromDmPaperSize(short aPaperSize, int16_t& aPaperSizeUnit) { - if (aPaperSize > 0 && aPaperSize < int32_t(std::size(kPaperSizeUnits))) { + if (aPaperSize > 0 && aPaperSize < int32_t(ArrayLength(kPaperSizeUnits))) { aPaperSizeUnit = kPaperSizeUnits[aPaperSize]; } } diff --git a/widget/windows/nsWindow.cpp b/widget/windows/nsWindow.cpp index 49482298d60f37..00681c216c838e 100644 --- a/widget/windows/nsWindow.cpp +++ b/widget/windows/nsWindow.cpp @@ -543,7 +543,7 @@ class TIPMessageHandler { MSG* msg = reinterpret_cast(aLParam); UINT& msgCode = msg->message; - for (uint32_t i = 0; i < std::size(sInstance->mMessages); ++i) { + for (uint32_t i = 0; i < ArrayLength(sInstance->mMessages); ++i) { if (msgCode == sInstance->mMessages[i]) { A11yInstantiationBlocker block; return ::CallNextHookEx(nullptr, aCode, aWParam, aLParam); diff --git a/xpcom/base/AppShutdown.cpp b/xpcom/base/AppShutdown.cpp index 0a83fef86f8c11..53ae4e3ba9de6b 100644 --- a/xpcom/base/AppShutdown.cpp +++ b/xpcom/base/AppShutdown.cpp @@ -458,7 +458,7 @@ void AppShutdown::AdvanceShutdownPhase( } ShutdownPhase AppShutdown::GetShutdownPhaseFromTopic(const char* aTopic) { - for (size_t i = 0; i < std::size(sPhaseObserverKeys); ++i) { + for (size_t i = 0; i < ArrayLength(sPhaseObserverKeys); ++i) { if (sPhaseObserverKeys[i] && !strcmp(sPhaseObserverKeys[i], aTopic)) { return static_cast(i); } diff --git a/xpcom/base/nsISupportsImpl.h b/xpcom/base/nsISupportsImpl.h index 8a4ef05181f5d8..0485a988121c3c 100644 --- a/xpcom/base/nsISupportsImpl.h +++ b/xpcom/base/nsISupportsImpl.h @@ -1120,11 +1120,18 @@ nsresult NS_FASTCALL NS_TableDrivenQI(void* aThis, REFNSIID aIID, static_cast<_implClass*>((_class*)0x1000))) - \ reinterpret_cast((_class*)0x1000))}, -#define NS_INTERFACE_TABLE_END_WITH_PTR(_ptr) \ - { nullptr, 0 } \ - } \ - ; \ - static_assert(std::size(table) > 1, "need at least 1 interface"); \ +/* + * XXX: we want to use mozilla::ArrayLength (or equivalent, + * MOZ_ARRAY_LENGTH) in this condition, but some versions of GCC don't + * see that the static_assert condition is actually constant in those + * cases, even with constexpr support (?). + */ +#define NS_INTERFACE_TABLE_END_WITH_PTR(_ptr) \ + { nullptr, 0 } \ + } \ + ; \ + static_assert((sizeof(table) / sizeof(table[0])) > 1, \ + "need at least 1 interface"); \ rv = NS_TableDrivenQI(static_cast(_ptr), aIID, aInstancePtr, table); #define NS_INTERFACE_TABLE_END \ diff --git a/xpcom/base/nsSystemInfo.cpp b/xpcom/base/nsSystemInfo.cpp index 0f0569126342e6..bfa5106ee08b89 100644 --- a/xpcom/base/nsSystemInfo.cpp +++ b/xpcom/base/nsSystemInfo.cpp @@ -186,8 +186,9 @@ static nsresult GetFolderDiskInfo(nsIFile* file, FolderDiskInfo& info) { NS_ENSURE_SUCCESS(rv, rv); wchar_t volumeMountPoint[MAX_PATH] = {L'\\', L'\\', L'.', L'\\'}; const size_t PREFIX_LEN = 4; - if (!::GetVolumePathNameW(filePath.get(), volumeMountPoint + PREFIX_LEN, - std::size(volumeMountPoint) - PREFIX_LEN)) { + if (!::GetVolumePathNameW( + filePath.get(), volumeMountPoint + PREFIX_LEN, + mozilla::ArrayLength(volumeMountPoint) - PREFIX_LEN)) { return NS_ERROR_UNEXPECTED; } size_t volumeMountPointLen = wcslen(volumeMountPoint); @@ -498,10 +499,12 @@ static nsresult GetWindowsSecurityCenterInfo(nsAString& aAVInfo, // Each output must match the corresponding entry in providerTypes. nsAString* outputs[] = {&aAVInfo, &aAntiSpyInfo, &aFirewallInfo}; - static_assert(std::size(providerTypes) == std::size(outputs), - "Length of providerTypes and outputs arrays must match"); + static_assert( + mozilla::ArrayLength(providerTypes) == mozilla::ArrayLength(outputs), + "Length of providerTypes and outputs arrays must match"); - for (uint32_t index = 0; index < std::size(providerTypes); ++index) { + for (uint32_t index = 0; index < mozilla::ArrayLength(providerTypes); + ++index) { RefPtr prodList; HRESULT hr = ::CoCreateInstance(clsid, nullptr, CLSCTX_INPROC_SERVER, iid, getter_AddRefs(prodList)); @@ -1384,7 +1387,7 @@ nsresult nsSystemInfo::Init() { #endif if (virtualMem) SetUint64Property(u"virtualmemsize"_ns, virtualMem); - for (uint32_t i = 0; i < std::size(cpuPropItems); i++) { + for (uint32_t i = 0; i < ArrayLength(cpuPropItems); i++) { rv = SetPropertyAsBool(NS_ConvertASCIItoUTF16(cpuPropItems[i].name), cpuPropItems[i].propfun()); if (NS_WARN_IF(NS_FAILED(rv))) { diff --git a/xpcom/build/PoisonIOInterposerMac.cpp b/xpcom/build/PoisonIOInterposerMac.cpp index 7f964b99d4f3b6..46dc75122143ec 100644 --- a/xpcom/build/PoisonIOInterposerMac.cpp +++ b/xpcom/build/PoisonIOInterposerMac.cpp @@ -289,7 +289,7 @@ FuncData* Functions[] = {&aio_write_data, &writev_data, &writev_NOCANCEL_UNIX2003_data, &writev_UNIX2003_data, &writev_NOCANCEL_data}; -const int NumFunctions = std::size(Functions); +const int NumFunctions = mozilla::ArrayLength(Functions); } // namespace diff --git a/xpcom/components/ManifestParser.cpp b/xpcom/components/ManifestParser.cpp index 64974b88dd3fca..7af4865220f75a 100644 --- a/xpcom/components/ManifestParser.cpp +++ b/xpcom/components/ManifestParser.cpp @@ -520,7 +520,7 @@ void ParseManifest(NSLocationType aType, FileLocation& aFile, char* aBuf, const ManifestDirective* directive = nullptr; for (const ManifestDirective* d = kParsingTable; - d < std::end(kParsingTable); ++d) { + d < ArrayEnd(kParsingTable); ++d) { if (!strcmp(d->directive, token)) { directive = d; break; diff --git a/xpcom/components/StaticComponents.cpp.in b/xpcom/components/StaticComponents.cpp.in index 6f3db11e38a4b6..d717b9f64adffb 100644 --- a/xpcom/components/StaticComponents.cpp.in +++ b/xpcom/components/StaticComponents.cpp.in @@ -357,7 +357,7 @@ const StaticProtocolHandler* StaticProtocolHandler::Lookup(const nsACString& aSc /* static */ already_AddRefed StaticComponents::GetComponentJSMs() { #ifdef HAS_COMPONENT_JSMS - auto jsms = MakeUnique>(std::size(gComponentJSMs)); + auto jsms = MakeUnique>(MOZ_ARRAY_LENGTH(gComponentJSMs)); for (const auto& entry : gComponentJSMs) { jsms->AppendElement(GetString(entry)); @@ -374,7 +374,7 @@ StaticComponents::GetComponentJSMs() { /* static */ already_AddRefed StaticComponents::GetComponentESModules() { - auto esModules = MakeUnique>(std::size(gComponentESModules)); + auto esModules = MakeUnique>(MOZ_ARRAY_LENGTH(gComponentESModules)); for (const auto& entry : gComponentESModules) { esModules->AppendElement(GetString(entry)); @@ -387,7 +387,7 @@ StaticComponents::GetComponentESModules() { } /* static */ Span StaticComponents::GetJSServices() { - return { gJSServices, std::size(gJSServices) }; + return { gJSServices, ArrayLength(gJSServices) }; } /* static */ void StaticComponents::Shutdown() { diff --git a/xpcom/io/Base64.cpp b/xpcom/io/Base64.cpp index da4aeafb4a73f3..4bd0394ecb6246 100644 --- a/xpcom/io/Base64.cpp +++ b/xpcom/io/Base64.cpp @@ -282,13 +282,13 @@ static const uint8_t kBase64DecodeTable[] = { /* 112 */ 41, 42, 43, 44, 45, 46, 47, 48, /* 120 */ 49, 50, 51, 255, 255, 255, 255, 255, }; -static_assert(std::size(kBase64DecodeTable) == 0x80); +static_assert(mozilla::ArrayLength(kBase64DecodeTable) == 0x80); // clang-format on template [[nodiscard]] bool Base64CharToValue(T aChar, uint8_t* aValue) { size_t index = static_cast(aChar); - if (index >= std::size(kBase64DecodeTable)) { + if (index >= mozilla::ArrayLength(kBase64DecodeTable)) { *aValue = 255; return false; } @@ -298,7 +298,7 @@ template static const char kBase64URLAlphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; -static_assert(std::size(kBase64URLAlphabet) == 0x41); +static_assert(mozilla::ArrayLength(kBase64URLAlphabet) == 0x41); // Maps an encoded character to a value in the Base64 URL alphabet, per // RFC 4648, Table 2. Invalid input characters map to UINT8_MAX. @@ -323,12 +323,12 @@ static const uint8_t kBase64URLDecodeTable[] = { 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, /* a - z */ 255, 255, 255, 255, 255, }; -static_assert(std::size(kBase64URLDecodeTable) == 0x80); +static_assert(mozilla::ArrayLength(kBase64URLDecodeTable) == 0x80); // clang-format on bool Base64URLCharToValue(char aChar, uint8_t* aValue) { uint8_t index = static_cast(aChar); - if (index >= std::size(kBase64URLDecodeTable)) { + if (index >= mozilla::ArrayLength(kBase64URLDecodeTable)) { *aValue = 255; return false; } diff --git a/xpcom/io/nsEscape.cpp b/xpcom/io/nsEscape.cpp index ce87bc5467a532..f211ea28096b3f 100644 --- a/xpcom/io/nsEscape.cpp +++ b/xpcom/io/nsEscape.cpp @@ -387,7 +387,7 @@ static nsresult T_EscapeURL(const typename T::char_type* aPart, size_t aPartLen, } // Flush the temp buffer if it doesnt't have room for another encoded char. - if (tempBufferPos >= std::size(tempBuffer) - ENCODE_MAX_LEN) { + if (tempBufferPos >= mozilla::ArrayLength(tempBuffer) - ENCODE_MAX_LEN) { NS_ASSERTION(writing, "should be writing"); if (!aResult.Append(tempBuffer, tempBufferPos, mozilla::fallible)) { return NS_ERROR_OUT_OF_MEMORY; diff --git a/xpcom/io/nsLocalFileWin.cpp b/xpcom/io/nsLocalFileWin.cpp index 44ee6aac74b43a..7df87d4b430d17 100644 --- a/xpcom/io/nsLocalFileWin.cpp +++ b/xpcom/io/nsLocalFileWin.cpp @@ -139,7 +139,7 @@ nsresult nsLocalFile::RevealFile(const nsString& aResolvedPath) { } LPCITEMIDLIST selection[] = {dir}; - UINT count = std::size(selection); + UINT count = ArrayLength(selection); // Perform the open of the directory. hr = SHOpenFolderAndSelectItems(dir, count, selection, 0); @@ -169,7 +169,7 @@ nsresult nsLocalFile::RevealFile(const nsString& aResolvedPath) { } LPCITEMIDLIST selection[] = {item}; - UINT count = std::size(selection); + UINT count = ArrayLength(selection); // Perform the selection of the file. hr = SHOpenFolderAndSelectItems(dir, count, selection, 0); @@ -3018,7 +3018,7 @@ nsresult nsLocalFile::LookupExtensionIn(const char* const* aExtensionsArray, NS_IMETHODIMP nsLocalFile::IsExecutable(bool* aResult) { - return LookupExtensionIn(sExecutableExts, std::size(sExecutableExts), + return LookupExtensionIn(sExecutableExts, ArrayLength(sExecutableExts), aResult); } @@ -3415,7 +3415,7 @@ nsLocalFile::Launch() { static const char* const onlyExeExt[] = {".exe"}; bool isExecutable; nsresult rv = - LookupExtensionIn(onlyExeExt, std::size(onlyExeExt), &isExecutable); + LookupExtensionIn(onlyExeExt, ArrayLength(onlyExeExt), &isExecutable); if (NS_FAILED(rv)) { isExecutable = false; } @@ -3637,12 +3637,12 @@ void nsLocalFile::EnsureShortPath() { } WCHAR shortPath[MAX_PATH + 1]; - DWORD lengthNeeded = - ::GetShortPathNameW(mWorkingPath.get(), shortPath, std::size(shortPath)); + DWORD lengthNeeded = ::GetShortPathNameW(mWorkingPath.get(), shortPath, + ArrayLength(shortPath)); // If an error occurred then lengthNeeded is set to 0 or the length of the // needed buffer including null termination. If it succeeds the number of // wide characters not including null termination is returned. - if (lengthNeeded != 0 && lengthNeeded < std::size(shortPath)) { + if (lengthNeeded != 0 && lengthNeeded < ArrayLength(shortPath)) { mShortWorkingPath.Assign(shortPath); } else { mShortWorkingPath.Assign(mWorkingPath); diff --git a/xpcom/reflect/xptinfo/xptcodegen.py b/xpcom/reflect/xptinfo/xptcodegen.py index 583b0799121872..67860ca1f2d84a 100644 --- a/xpcom/reflect/xptinfo/xptcodegen.py +++ b/xpcom/reflect/xptinfo/xptcodegen.py @@ -584,7 +584,7 @@ def array(ty, name, els): fd.write( """ -const uint16_t sInterfacesSize = std::size(sInterfaces); +const uint16_t sInterfacesSize = mozilla::ArrayLength(sInterfaces); } // namespace detail } // namespace xpt diff --git a/xpcom/rust/gtest/bench-collections/Bench.cpp b/xpcom/rust/gtest/bench-collections/Bench.cpp index c0adb5558065a2..0035d27ed6c3d0 100644 --- a/xpcom/rust/gtest/bench-collections/Bench.cpp +++ b/xpcom/rust/gtest/bench-collections/Bench.cpp @@ -242,7 +242,7 @@ class BenchCollections : public ::testing::Test { } printf("\n"); - for (size_t i = 0; i < std::size(gParamsList); i++) { + for (size_t i = 0; i < ArrayLength(gParamsList); i++) { const Params* params = &gParamsList[i]; printf("%14s", params->mConfigName); } @@ -254,7 +254,7 @@ class BenchCollections : public ::testing::Test { StaticMutexAutoLock lock(sValsMutex); double total = 0; - for (size_t i = 0; i < std::size(gParamsList); i++) { + for (size_t i = 0; i < ArrayLength(gParamsList); i++) { const Params* params = &gParamsList[i]; TimeStamp t1 = TimeStamp::Now(); aBench(params, sVals, VALS_LEN); diff --git a/xpcom/tests/gtest/TestAtoms.cpp b/xpcom/tests/gtest/TestAtoms.cpp index b444042ff34c10..53148895d22a2e 100644 --- a/xpcom/tests/gtest/TestAtoms.cpp +++ b/xpcom/tests/gtest/TestAtoms.cpp @@ -23,7 +23,7 @@ namespace TestAtoms { TEST(Atoms, Basic) { - for (unsigned int i = 0; i < std::size(ValidStrings); ++i) { + for (unsigned int i = 0; i < ArrayLength(ValidStrings); ++i) { nsDependentString str16(ValidStrings[i].m16); nsDependentCString str8(ValidStrings[i].m8); @@ -48,7 +48,7 @@ TEST(Atoms, Basic) TEST(Atoms, 16vs8) { - for (unsigned int i = 0; i < std::size(ValidStrings); ++i) { + for (unsigned int i = 0; i < ArrayLength(ValidStrings); ++i) { RefPtr atom16 = NS_Atomize(ValidStrings[i].m16); RefPtr atom8 = NS_Atomize(ValidStrings[i].m8); EXPECT_EQ(atom16, atom8); @@ -73,7 +73,7 @@ TEST(Atoms, Null) TEST(Atoms, Invalid) { - for (unsigned int i = 0; i < std::size(Invalid16Strings); ++i) { + for (unsigned int i = 0; i < ArrayLength(Invalid16Strings); ++i) { nsrefcnt count = NS_GetNumberOfAtoms(); { @@ -85,7 +85,7 @@ TEST(Atoms, Invalid) } #ifndef DEBUG // Don't run this test in debug builds as that intentionally asserts. - for (unsigned int i = 0; i < std::size(Invalid8Strings); ++i) { + for (unsigned int i = 0; i < ArrayLength(Invalid8Strings); ++i) { nsrefcnt count = NS_GetNumberOfAtoms(); { @@ -98,7 +98,7 @@ TEST(Atoms, Invalid) EXPECT_EQ(count, NS_GetNumberOfAtoms()); } - for (unsigned int i = 0; i < std::size(Malformed8Strings); ++i) { + for (unsigned int i = 0; i < ArrayLength(Malformed8Strings); ++i) { nsrefcnt count = NS_GetNumberOfAtoms(); { diff --git a/xpcom/tests/gtest/TestDeadlockDetector.cpp b/xpcom/tests/gtest/TestDeadlockDetector.cpp index c48fbfbcf47e75..c02ba13da28050 100644 --- a/xpcom/tests/gtest/TestDeadlockDetector.cpp +++ b/xpcom/tests/gtest/TestDeadlockDetector.cpp @@ -298,10 +298,10 @@ static int ContentionNoDeadlock_Child() MOZ_NO_THREAD_SAFETY_ANALYSIS { for (uint32_t i = 0; i < kMutexCount; ++i) locks.AppendElement(new MUTEX("dd.cnd.ms")); - for (int32_t i = 0; i < (int32_t)std::size(threads); ++i) + for (int32_t i = 0; i < (int32_t)ArrayLength(threads); ++i) threads[i] = spawn(ContentionNoDeadlock_thread, states + i); - for (uint32_t i = 0; i < std::size(threads); ++i) PR_JoinThread(threads[i]); + for (uint32_t i = 0; i < ArrayLength(threads); ++i) PR_JoinThread(threads[i]); for (uint32_t i = 0; i < locks.Length(); ++i) delete locks[i]; diff --git a/xpcom/tests/gtest/TestEscape.cpp b/xpcom/tests/gtest/TestEscape.cpp index 47bf62b31d1dbd..6834d5fa13339f 100644 --- a/xpcom/tests/gtest/TestEscape.cpp +++ b/xpcom/tests/gtest/TestEscape.cpp @@ -107,11 +107,11 @@ TEST(Escape, nsAppendEscapedHTML) "foo'"&><abc", }; - ASSERT_EQ(std::size(srcs), std::size(dsts1)); - ASSERT_EQ(std::size(srcs), std::size(dsts2)); + ASSERT_EQ(ArrayLength(srcs), ArrayLength(dsts1)); + ASSERT_EQ(ArrayLength(srcs), ArrayLength(dsts2)); // Test when the destination is empty. - for (size_t i = 0; i < std::size(srcs); i++) { + for (size_t i = 0; i < ArrayLength(srcs); i++) { nsCString src(srcs[i]); nsCString dst; nsAppendEscapedHTML(src, dst); @@ -120,7 +120,7 @@ TEST(Escape, nsAppendEscapedHTML) // Test when the destination is non-empty. nsCString dst; - for (size_t i = 0; i < std::size(srcs); i++) { + for (size_t i = 0; i < ArrayLength(srcs); i++) { nsCString src(srcs[i]); nsAppendEscapedHTML(src, dst); ASSERT_TRUE(dst.Equals(dsts2[i])); @@ -227,7 +227,7 @@ TEST(Escape, EscapeURLExternalHandlerURLs) "web+foo://user:1234@example.com:8080?foo=bar"_ns, "ext+bar://id='myId'"_ns}; - for (size_t i = 0; i < std::size(input); i++) { + for (size_t i = 0; i < ArrayLength(input); i++) { nsCString src(input[i]); nsCString dst; nsresult rv = diff --git a/xpcom/tests/gtest/TestNSPRLogModulesParser.cpp b/xpcom/tests/gtest/TestNSPRLogModulesParser.cpp index 0d00d0fb34f00b..2294794ad20c1a 100644 --- a/xpcom/tests/gtest/TestNSPRLogModulesParser.cpp +++ b/xpcom/tests/gtest/TestNSPRLogModulesParser.cpp @@ -56,7 +56,7 @@ TEST(NSPRLogModulesParser, LevelSpecified) auto* currTest = expected; - for (size_t i = 0; i < std::size(expected); i++) { + for (size_t i = 0; i < MOZ_ARRAY_LENGTH(expected); i++) { bool callbackInvoked = false; mozilla::NSPRLogModulesParser( currTest->first, @@ -80,7 +80,7 @@ TEST(NSPRLogModulesParser, Multiple) {"Qux", mozilla::LogLevel::Verbose}, }; - const size_t kExpectedCount = std::size(expected); + const size_t kExpectedCount = MOZ_ARRAY_LENGTH(expected); auto* currTest = expected; @@ -106,7 +106,7 @@ TEST(NSPRLogModulesParser, Characters) {"invalid", mozilla::LogLevel::Error}, }; - const size_t kExpectedCount = std::size(expected); + const size_t kExpectedCount = MOZ_ARRAY_LENGTH(expected); auto* currTest = expected; @@ -148,7 +148,7 @@ TEST(NSPRLogModulesParser, RustModules) {"crate::mod::*", mozilla::LogLevel::Info}, }; - const size_t kExpectedCount = std::size(expected); + const size_t kExpectedCount = MOZ_ARRAY_LENGTH(expected); auto* currTest = expected; diff --git a/xpcom/tests/gtest/TestObserverArray.cpp b/xpcom/tests/gtest/TestObserverArray.cpp index 026fc533eb7d9c..8a4744d06bd1d6 100644 --- a/xpcom/tests/gtest/TestObserverArray.cpp +++ b/xpcom/tests/gtest/TestObserverArray.cpp @@ -18,7 +18,7 @@ typedef nsTObserverArray IntArray; ++testNum; \ count = 0; \ IntArray::_type iter(arr); \ - while (iter.HasMore() && count != std::size(_exp)) { \ + while (iter.HasMore() && count != ArrayLength(_exp)) { \ _code int next = iter.GetNext(); \ int expected = _exp[count++]; \ ASSERT_EQ(next, expected) \ @@ -26,7 +26,7 @@ typedef nsTObserverArray IntArray; } \ ASSERT_FALSE(iter.HasMore()) \ << "During test " << testNum << ", iterator ran over"; \ - ASSERT_EQ(count, std::size(_exp)) \ + ASSERT_EQ(count, ArrayLength(_exp)) \ << "During test " << testNum << ", iterator finished too early"; \ } while (0) diff --git a/xpcom/tests/gtest/TestTArray.cpp b/xpcom/tests/gtest/TestTArray.cpp index e165628dd4f982..54aea92dff6959 100644 --- a/xpcom/tests/gtest/TestTArray.cpp +++ b/xpcom/tests/gtest/TestTArray.cpp @@ -64,7 +64,7 @@ constexpr int dummyArrayData[] = {4, 1, 2, 8}; static const nsTArray& DummyArray() { static nsTArray sArray; if (sArray.IsEmpty()) { - sArray.AppendElements(dummyArrayData, std::size(dummyArrayData)); + sArray.AppendElements(dummyArrayData, ArrayLength(dummyArrayData)); } return sArray; } @@ -86,11 +86,11 @@ TEST(TArray, int_AppendElements_PlainArray) { nsTArray array; - int* ptr = array.AppendElements(dummyArrayData, std::size(dummyArrayData)); + int* ptr = array.AppendElements(dummyArrayData, ArrayLength(dummyArrayData)); ASSERT_EQ(&array[0], ptr); ASSERT_EQ(DummyArray(), array); - ptr = array.AppendElements(dummyArrayData, std::size(dummyArrayData)); + ptr = array.AppendElements(dummyArrayData, ArrayLength(dummyArrayData)); ASSERT_EQ(&array[DummyArray().Length()], ptr); nsTArray expected; expected.AppendElements(DummyArray()); @@ -102,13 +102,13 @@ TEST(TArray, int_AppendElements_PlainArray_Fallible) { nsTArray array; - int* ptr = - array.AppendElements(dummyArrayData, std::size(dummyArrayData), fallible); + int* ptr = array.AppendElements(dummyArrayData, ArrayLength(dummyArrayData), + fallible); ASSERT_EQ(&array[0], ptr); ASSERT_EQ(DummyArray(), array); - ptr = - array.AppendElements(dummyArrayData, std::size(dummyArrayData), fallible); + ptr = array.AppendElements(dummyArrayData, ArrayLength(dummyArrayData), + fallible); ASSERT_EQ(&array[DummyArray().Length()], ptr); nsTArray expected; expected.AppendElements(DummyArray()); diff --git a/xpcom/tests/gtest/TestTArray2.cpp b/xpcom/tests/gtest/TestTArray2.cpp index fa7b9a5ae498bf..d265e4415de7b0 100644 --- a/xpcom/tests/gtest/TestTArray2.cpp +++ b/xpcom/tests/gtest/TestTArray2.cpp @@ -197,25 +197,25 @@ static bool test_basic_array(ElementType* data, size_t dataLen, TEST(TArray, test_int_array) { int data[] = {4, 6, 8, 2, 4, 1, 5, 7, 3}; - ASSERT_TRUE(test_basic_array(data, std::size(data), int(14))); + ASSERT_TRUE(test_basic_array(data, ArrayLength(data), int(14))); } TEST(TArray, test_int64_array) { int64_t data[] = {4, 6, 8, 2, 4, 1, 5, 7, 3}; - ASSERT_TRUE(test_basic_array(data, std::size(data), int64_t(14))); + ASSERT_TRUE(test_basic_array(data, ArrayLength(data), int64_t(14))); } TEST(TArray, test_char_array) { char data[] = {4, 6, 8, 2, 4, 1, 5, 7, 3}; - ASSERT_TRUE(test_basic_array(data, std::size(data), char(14))); + ASSERT_TRUE(test_basic_array(data, ArrayLength(data), char(14))); } TEST(TArray, test_uint32_array) { uint32_t data[] = {4, 6, 8, 2, 4, 1, 5, 7, 3}; - ASSERT_TRUE(test_basic_array(data, std::size(data), uint32_t(14))); + ASSERT_TRUE(test_basic_array(data, ArrayLength(data), uint32_t(14))); } //---- @@ -251,17 +251,17 @@ TEST(TArray, test_object_array) nsTArray objArray; const char kdata[] = "hello world"; size_t i; - for (i = 0; i < std::size(kdata); ++i) { + for (i = 0; i < ArrayLength(kdata); ++i) { char x[] = {kdata[i], '\0'}; objArray.AppendElement(Object(x, i)); } - for (i = 0; i < std::size(kdata); ++i) { + for (i = 0; i < ArrayLength(kdata); ++i) { ASSERT_EQ(objArray[i].Str()[0], kdata[i]); ASSERT_EQ(objArray[i].Num(), i); } objArray.Sort(); const char ksorted[] = "\0 dehllloorw"; - for (i = 0; i < std::size(kdata) - 1; ++i) { + for (i = 0; i < ArrayLength(kdata) - 1; ++i) { ASSERT_EQ(objArray[i].Str()[0], ksorted[i]); } } @@ -663,12 +663,12 @@ TEST(TArray, test_string_array) nsTArray strArray; const char kdata[] = "hello world"; size_t i; - for (i = 0; i < std::size(kdata); ++i) { + for (i = 0; i < ArrayLength(kdata); ++i) { nsCString str; str.Assign(kdata[i]); strArray.AppendElement(str); } - for (i = 0; i < std::size(kdata); ++i) { + for (i = 0; i < ArrayLength(kdata); ++i) { ASSERT_EQ(strArray[i].CharAt(0), kdata[i]); } @@ -685,7 +685,7 @@ TEST(TArray, test_string_array) strArray.Sort(); const char ksorted[] = "\0 dehllloorw"; - for (i = std::size(kdata); i--;) { + for (i = ArrayLength(kdata); i--;) { ASSERT_EQ(strArray[i].CharAt(0), ksorted[i]); if (i > 0 && strArray[i] == strArray[i - 1]) strArray.RemoveElementAt(i); } @@ -695,12 +695,12 @@ TEST(TArray, test_string_array) auto no_index = strArray.NoIndex; // Fixes gtest compilation error ASSERT_EQ(strArray.BinaryIndexOf(""_ns), no_index); - nsCString rawArray[std::size(kdata) - 1]; - for (i = 0; i < std::size(rawArray); ++i) + nsCString rawArray[MOZ_ARRAY_LENGTH(kdata) - 1]; + for (i = 0; i < ArrayLength(rawArray); ++i) rawArray[i].Assign(kdata + i); // substrings of kdata ASSERT_TRUE( - test_basic_array(rawArray, std::size(rawArray), nsCString("foopy"))); + test_basic_array(rawArray, ArrayLength(rawArray), nsCString("foopy"))); } //---- @@ -724,7 +724,7 @@ TEST(TArray, test_comptr_array) const char* kNames[] = {"foo.txt", "bar.html", "baz.gif"}; nsTArray fileArray; size_t i; - for (i = 0; i < std::size(kNames); ++i) { + for (i = 0; i < ArrayLength(kNames); ++i) { FilePointer f; tmpDir->Clone(getter_AddRefs(f)); ASSERT_TRUE(f); @@ -917,17 +917,18 @@ TEST(TArray, test_ptrarray) TEST(TArray, test_autoarray) { uint32_t data[] = {4, 6, 8, 2, 4, 1, 5, 7, 3}; - AutoTArray array; + AutoTArray array; void* hdr = array.DebugGetHeader(); ASSERT_NE(hdr, nsTArray().DebugGetHeader()); - ASSERT_NE(hdr, (AutoTArray().DebugGetHeader())); + ASSERT_NE(hdr, + (AutoTArray().DebugGetHeader())); array.AppendElement(1u); ASSERT_EQ(hdr, array.DebugGetHeader()); array.RemoveElement(1u); - array.AppendElements(data, std::size(data)); + array.AppendElements(data, ArrayLength(data)); ASSERT_EQ(hdr, array.DebugGetHeader()); array.AppendElement(2u); @@ -936,7 +937,7 @@ TEST(TArray, test_autoarray) array.Clear(); array.Compact(); ASSERT_EQ(hdr, array.DebugGetHeader()); - array.AppendElements(data, std::size(data)); + array.AppendElements(data, ArrayLength(data)); ASSERT_EQ(hdr, array.DebugGetHeader()); nsTArray array2; @@ -945,21 +946,21 @@ TEST(TArray, test_autoarray) ASSERT_NE(emptyHdr, array.DebugGetHeader()); ASSERT_NE(hdr, array2.DebugGetHeader()); size_t i; - for (i = 0; i < std::size(data); ++i) { + for (i = 0; i < ArrayLength(data); ++i) { ASSERT_EQ(array2[i], data[i]); } ASSERT_TRUE(array.IsEmpty()); array.Compact(); - array.AppendElements(data, std::size(data)); + array.AppendElements(data, ArrayLength(data)); uint32_t data3[] = {5, 7, 11}; - AutoTArray array3; - array3.AppendElements(data3, std::size(data3)); + AutoTArray array3; + array3.AppendElements(data3, ArrayLength(data3)); array.SwapElements(array3); - for (i = 0; i < std::size(data); ++i) { + for (i = 0; i < ArrayLength(data); ++i) { ASSERT_EQ(array3[i], data[i]); } - for (i = 0; i < std::size(data3); ++i) { + for (i = 0; i < ArrayLength(data3); ++i) { ASSERT_EQ(array[i], data3[i]); } } @@ -1026,12 +1027,12 @@ static bool is_heap(const Array& ary, size_t len) { ASSERT_EQ((actual), (expected)); \ } while (0) -#define CHECK_ARRAY(arr, data) \ - do { \ - CHECK_EQ_INT((arr).Length(), (size_t)std::size(data)); \ - for (size_t _i = 0; _i < std::size(data); _i++) { \ - CHECK_EQ_INT((arr)[_i], (data)[_i]); \ - } \ +#define CHECK_ARRAY(arr, data) \ + do { \ + CHECK_EQ_INT((arr).Length(), (size_t)ArrayLength(data)); \ + for (size_t _i = 0; _i < ArrayLength(data); _i++) { \ + CHECK_EQ_INT((arr)[_i], (data)[_i]); \ + } \ } while (0) TEST(TArray, test_swap) @@ -1045,8 +1046,8 @@ TEST(TArray, test_swap) AutoTArray a; AutoTArray b; - a.AppendElements(data1, std::size(data1)); - b.AppendElements(data2, std::size(data2)); + a.AppendElements(data1, ArrayLength(data1)); + b.AppendElements(data2, ArrayLength(data2)); CHECK_IS_USING_AUTO(a); CHECK_IS_USING_AUTO(b); @@ -1064,9 +1065,9 @@ TEST(TArray, test_swap) AutoTArray a; AutoTArray b; - a.AppendElements(data1, std::size(data1)); + a.AppendElements(data1, ArrayLength(data1)); a.RemoveElementAt(3); - b.AppendElements(data2, std::size(data2)); + b.AppendElements(data2, ArrayLength(data2)); // Here and elsewhere, we assert that if we start with an auto array // capable of storing N elements, we store N+1 elements into the array, and @@ -1096,10 +1097,10 @@ TEST(TArray, test_swap) { AutoTArray a; AutoTArray b; - a.AppendElements(data1, std::size(data1)); + a.AppendElements(data1, ArrayLength(data1)); a.RemoveElementAt(3); - b.AppendElements(data2, std::size(data2)); + b.AppendElements(data2, ArrayLength(data2)); b.RemoveElementAt(2); CHECK_NOT_USING_AUTO(a); @@ -1121,8 +1122,8 @@ TEST(TArray, test_swap) AutoTArray a; AutoTArray b; - a.AppendElements(data1, std::size(data1)); - b.AppendElements(data2, std::size(data2)); + a.AppendElements(data1, ArrayLength(data1)); + b.AppendElements(data2, ArrayLength(data2)); a.SwapElements(b); @@ -1135,7 +1136,7 @@ TEST(TArray, test_swap) nsTArray a; AutoTArray b; - b.AppendElements(data2, std::size(data2)); + b.AppendElements(data2, ArrayLength(data2)); CHECK_IS_USING_AUTO(b); a.SwapElements(b); @@ -1178,7 +1179,7 @@ TEST(TArray, test_swap) { nsTArray a; nsTArray b; - b.AppendElements(data2, std::size(data2)); + b.AppendElements(data2, ArrayLength(data2)); CHECK_EQ_INT(a.Capacity(), size_t(0)); size_t bCapacity = b.Capacity(); @@ -1198,7 +1199,7 @@ TEST(TArray, test_swap) nsTArray a; AutoTArray b; - a.AppendElements(data1, std::size(data1)); + a.AppendElements(data1, ArrayLength(data1)); a.SwapElements(b); @@ -1216,7 +1217,7 @@ TEST(TArray, test_swap) AutoTArray a; AutoTArray b; - a.AppendElements(data1, std::size(data1)); + a.AppendElements(data1, ArrayLength(data1)); a.SwapElements(b); @@ -1248,7 +1249,7 @@ TEST(TArray, test_swap) AutoTArray a; AutoTArray b; - a.AppendElements(data1, std::size(data1)); + a.AppendElements(data1, ArrayLength(data1)); a.SwapElements(b); @@ -1263,7 +1264,7 @@ TEST(TArray, test_swap) nsTArray a; nsTArray b; - a.AppendElements(data1, std::size(data1)); + a.AppendElements(data1, ArrayLength(data1)); ASSERT_TRUE(a.SwapElements(b, fallible)); @@ -1276,7 +1277,7 @@ TEST(TArray, test_swap) FallibleTArray a; FallibleTArray b; - ASSERT_TRUE(a.AppendElements(data1, std::size(data1), fallible)); + ASSERT_TRUE(a.AppendElements(data1, ArrayLength(data1), fallible)); ASSERT_TRUE(a.SwapElements(b, fallible)); @@ -1289,7 +1290,7 @@ TEST(TArray, test_swap) FallibleTArray a; AutoTArray b; - ASSERT_TRUE(a.AppendElements(data1, std::size(data1), fallible)); + ASSERT_TRUE(a.AppendElements(data1, ArrayLength(data1), fallible)); ASSERT_TRUE(a.SwapElements(b, fallible)); @@ -1457,7 +1458,7 @@ bool TestCompareMethods(const Comparator& aComp) { ary.Sort(aComp); const int sorted[] = {3, 4, 5, 12, 16, 17, 57, 96}; - for (size_t i = 0; i < std::size(sorted); i++) { + for (size_t i = 0; i < MOZ_ARRAY_LENGTH(sorted); i++) { if (sorted[i] != ary[i]) { return false; } diff --git a/xpcom/tests/gtest/TestThreadUtils.cpp b/xpcom/tests/gtest/TestThreadUtils.cpp index b6666d2cbaa36b..e334d74fda4e4f 100644 --- a/xpcom/tests/gtest/TestThreadUtils.cpp +++ b/xpcom/tests/gtest/TestThreadUtils.cpp @@ -647,7 +647,7 @@ class IdleObject final { public: NS_INLINE_DECL_REFCOUNTING(IdleObject) IdleObject() { - for (uint32_t index = 0; index < std::size(mRunnableExecuted); ++index) { + for (uint32_t index = 0; index < ArrayLength(mRunnableExecuted); ++index) { mRunnableExecuted[index] = false; mSetIdleDeadlineCalled = false; } @@ -661,7 +661,7 @@ class IdleObject final { << aKey << ": Method" << index << " should've executed"; } - for (; index < std::size(mRunnableExecuted); ++index) { + for (; index < ArrayLength(mRunnableExecuted); ++index) { ASSERT_FALSE(mRunnableExecuted[index]) << aKey << ": Method" << index << " shouldn't have executed"; } diff --git a/xpcom/tests/gtest/TestUTF.cpp b/xpcom/tests/gtest/TestUTF.cpp index e30c7af9739247..1173dbd6837d96 100644 --- a/xpcom/tests/gtest/TestUTF.cpp +++ b/xpcom/tests/gtest/TestUTF.cpp @@ -23,7 +23,7 @@ namespace TestUTF { TEST(UTF, Valid) { - for (unsigned int i = 0; i < std::size(ValidStrings); ++i) { + for (unsigned int i = 0; i < ArrayLength(ValidStrings); ++i) { nsDependentCString str8(ValidStrings[i].m8); nsDependentString str16(ValidStrings[i].m16); @@ -45,7 +45,7 @@ TEST(UTF, Valid) TEST(UTF, Invalid16) { - for (unsigned int i = 0; i < std::size(Invalid16Strings); ++i) { + for (unsigned int i = 0; i < ArrayLength(Invalid16Strings); ++i) { nsDependentString str16(Invalid16Strings[i].m16); nsDependentCString str8(Invalid16Strings[i].m8); @@ -61,7 +61,7 @@ TEST(UTF, Invalid16) TEST(UTF, Invalid8) { - for (unsigned int i = 0; i < std::size(Invalid8Strings); ++i) { + for (unsigned int i = 0; i < ArrayLength(Invalid8Strings); ++i) { nsDependentString str16(Invalid8Strings[i].m16); nsDependentCString str8(Invalid8Strings[i].m8); @@ -77,7 +77,7 @@ TEST(UTF, Invalid8) TEST(UTF, Malformed8) { - for (unsigned int i = 0; i < std::size(Malformed8Strings); ++i) { + for (unsigned int i = 0; i < ArrayLength(Malformed8Strings); ++i) { nsDependentString str16(Malformed8Strings[i].m16); nsDependentCString str8(Malformed8Strings[i].m8); @@ -93,7 +93,7 @@ TEST(UTF, Malformed8) TEST(UTF, Hash16) { - for (unsigned int i = 0; i < std::size(ValidStrings); ++i) { + for (unsigned int i = 0; i < ArrayLength(ValidStrings); ++i) { nsDependentCString str8(ValidStrings[i].m8); bool err; EXPECT_EQ(HashString(ValidStrings[i].m16), @@ -101,14 +101,14 @@ TEST(UTF, Hash16) EXPECT_FALSE(err); } - for (unsigned int i = 0; i < std::size(Invalid8Strings); ++i) { + for (unsigned int i = 0; i < ArrayLength(Invalid8Strings); ++i) { nsDependentCString str8(Invalid8Strings[i].m8); bool err; EXPECT_EQ(HashUTF8AsUTF16(str8.get(), str8.Length(), &err), 0u); EXPECT_TRUE(err); } - for (unsigned int i = 0; i < std::size(Malformed8Strings); ++i) { + for (unsigned int i = 0; i < ArrayLength(Malformed8Strings); ++i) { nsDependentCString str8(Malformed8Strings[i].m8); bool err; EXPECT_EQ(HashUTF8AsUTF16(str8.get(), str8.Length(), &err), 0u); diff --git a/xpcom/tests/windows/TestPoisonIOInterposer.cpp b/xpcom/tests/windows/TestPoisonIOInterposer.cpp index 208360c508004f..9b29307f349de2 100644 --- a/xpcom/tests/windows/TestPoisonIOInterposer.cpp +++ b/xpcom/tests/windows/TestPoisonIOInterposer.cpp @@ -19,7 +19,7 @@ class TempFile final { public: TempFile() : mFullPath{0} { wchar_t tempDir[MAX_PATH + 1]; - DWORD len = ::GetTempPathW(std::size(tempDir), tempDir); + DWORD len = ::GetTempPathW(ArrayLength(tempDir), tempDir); if (!len) { return; } diff --git a/xpcom/threads/TimerThread.cpp b/xpcom/threads/TimerThread.cpp index ee98bc7a6f541f..d0ff778f201ba9 100644 --- a/xpcom/threads/TimerThread.cpp +++ b/xpcom/threads/TimerThread.cpp @@ -883,7 +883,7 @@ TimerThread::Run() { 1.0, 1.75, 2.75}; if (ChaosMode::isActive(ChaosFeature::TimerScheduling)) { microseconds *= sChaosFractions[ChaosMode::randomUint32LessThan( - std::size(sChaosFractions))]; + ArrayLength(sChaosFractions))]; forceRunNextTimer = true; } @@ -915,7 +915,7 @@ TimerThread::Run() { const double waitInMs = waitFor.ToMilliseconds(); const double chaosWaitInMs = waitInMs * sChaosFractions[ChaosMode::randomUint32LessThan( - std::size(sChaosFractions))]; + ArrayLength(sChaosFractions))]; waitFor = TimeDuration::FromMilliseconds(chaosWaitInMs); }