From 6d4c6fde3698ad50eba062a4d583b6088415875b Mon Sep 17 00:00:00 2001 From: Peter Van der Beken Date: Sat, 2 Mar 2024 07:50:21 +0000 Subject: [PATCH] Bug 1640839 - Make WebIDL enum helper function to convert to string return an actual string. r=mccr8,media-playback-reviewers,padenot Differential Revision: https://phabricator.services.mozilla.com/D201337 --- dom/base/ChromeUtils.cpp | 2 +- dom/base/DOMParser.cpp | 10 +-- dom/bindings/BindingDeclarations.h | 12 +-- dom/bindings/BindingUtils.h | 30 +++++-- dom/bindings/Codegen.py | 83 ++++++++++--------- dom/cache/Cache.cpp | 5 +- dom/console/ConsoleInstance.cpp | 5 +- dom/docs/webIdlBindings/index.md | 15 ++-- dom/fetch/Request.cpp | 4 +- dom/html/nsGenericHTMLElement.cpp | 21 +++-- dom/media/MediaDevices.cpp | 2 +- dom/media/MediaManager.cpp | 59 +++++-------- dom/media/MediaStreamTrack.cpp | 2 +- dom/media/eme/MediaKeySession.cpp | 14 +--- dom/media/eme/MediaKeySession.h | 2 - dom/media/eme/MediaKeySystemAccess.cpp | 2 +- dom/media/eme/MediaKeySystemAccessManager.cpp | 3 +- dom/media/eme/MediaKeys.cpp | 5 +- dom/media/eme/mediafoundation/WMFCDMProxy.cpp | 3 +- dom/media/gmp/ChromiumCDMProxy.cpp | 3 +- .../mediacapabilities/MediaCapabilities.cpp | 25 ++---- dom/media/webcodecs/VideoDecoder.cpp | 4 +- dom/media/webcodecs/VideoEncoder.cpp | 16 ++-- dom/media/webcodecs/VideoFrame.cpp | 16 ++-- dom/media/webcodecs/WebCodecsUtils.cpp | 35 +++----- dom/media/webrtc/MediaEngineFake.cpp | 6 +- .../webrtc/MediaEngineRemoteVideoSource.cpp | 3 +- dom/media/webrtc/MediaTrackConstraints.h | 4 +- dom/midi/MIDIPort.cpp | 4 +- dom/payments/PaymentRequestManager.cpp | 6 +- dom/security/ReferrerInfo.cpp | 26 ++---- dom/security/ReferrerInfo.h | 7 -- dom/serviceworkers/ServiceWorkerEvents.cpp | 3 +- dom/serviceworkers/ServiceWorkerOp.cpp | 3 +- dom/vr/XRSystem.cpp | 10 ++- dom/webgpu/Adapter.cpp | 8 +- dom/webgpu/SupportedFeatures.cpp | 3 +- ipc/glue/UtilityAudioDecoder.cpp | 4 +- .../UtilityProcessTest.cpp | 4 +- 39 files changed, 203 insertions(+), 266 deletions(-) diff --git a/dom/base/ChromeUtils.cpp b/dom/base/ChromeUtils.cpp index b47fc4c0ef07..aa6abd79b209 100644 --- a/dom/base/ChromeUtils.cpp +++ b/dom/base/ChromeUtils.cpp @@ -2077,7 +2077,7 @@ void ChromeUtils::GetAllPossibleUtilityActorNames(GlobalObject& aGlobal, aNames.Clear(); for (size_t i = 0; i < WebIDLUtilityActorNameValues::Count; ++i) { auto idlName = static_cast(i); - aNames.AppendElement(WebIDLUtilityActorNameValues::GetString(idlName)); + aNames.AppendElement(GetEnumString(idlName)); } } diff --git a/dom/base/DOMParser.cpp b/dom/base/DOMParser.cpp index 87bac2009334..b3cf6ba04bd1 100644 --- a/dom/base/DOMParser.cpp +++ b/dom/base/DOMParser.cpp @@ -181,12 +181,10 @@ already_AddRefed DOMParser::ParseFromStream(nsIInputStream* aStream, // Create a fake channel nsCOMPtr parserChannel; - NS_NewInputStreamChannel( - getter_AddRefs(parserChannel), mDocumentURI, - nullptr, // aStream - mPrincipal, nsILoadInfo::SEC_FORCE_INHERIT_PRINCIPAL, - nsIContentPolicy::TYPE_OTHER, - nsDependentCSubstring(SupportedTypeValues::GetString(aType))); + NS_NewInputStreamChannel(getter_AddRefs(parserChannel), mDocumentURI, + nullptr, // aStream + mPrincipal, nsILoadInfo::SEC_FORCE_INHERIT_PRINCIPAL, + nsIContentPolicy::TYPE_OTHER, GetEnumString(aType)); if (NS_WARN_IF(!parserChannel)) { aRv.Throw(NS_ERROR_UNEXPECTED); return nullptr; diff --git a/dom/bindings/BindingDeclarations.h b/dom/bindings/BindingDeclarations.h index 24385c9fa57d..c723af00212e 100644 --- a/dom/bindings/BindingDeclarations.h +++ b/dom/bindings/BindingDeclarations.h @@ -131,11 +131,6 @@ template constexpr bool is_dom_union_with_typedarray_members = std::is_base_of_v; -struct EnumEntry { - const char* value; - size_t length; -}; - enum class CallerType : uint32_t; class MOZ_STACK_CLASS GlobalObject { @@ -562,6 +557,13 @@ JS::Handle GetPerInterfaceObjectHandle( JSContext* aCx, size_t aSlotId, CreateInterfaceObjectsMethod aCreator, bool aDefineOnGlobal); +namespace binding_detail { + +template +struct EnumStrings; + +} // namespace binding_detail + } // namespace dom } // namespace mozilla diff --git a/dom/bindings/BindingUtils.h b/dom/bindings/BindingUtils.h index df3c509ab744..da6d2e63e4e1 100644 --- a/dom/bindings/BindingUtils.h +++ b/dom/bindings/BindingUtils.h @@ -1345,24 +1345,23 @@ inline bool EnumValueNotFound(BindingCallContext& cx, template inline int FindEnumStringIndexImpl(const CharT* chars, size_t length, - const EnumEntry* values) { - int i = 0; - for (const EnumEntry* value = values; value->value; ++value, ++i) { - if (length != value->length) { + const Span& values) { + for (size_t i = 0; i < values.Length(); ++i) { + const nsLiteralCString& value = values[i]; + if (length != value.Length()) { continue; } bool equal = true; - const char* val = value->value; for (size_t j = 0; j != length; ++j) { - if (unsigned(val[j]) != unsigned(chars[j])) { + if (unsigned(value.CharAt(j)) != unsigned(chars[j])) { equal = false; break; } } if (equal) { - return i; + return (int)i; } } @@ -1371,8 +1370,9 @@ inline int FindEnumStringIndexImpl(const CharT* chars, size_t length, template inline bool FindEnumStringIndex(BindingCallContext& cx, JS::Handle v, - const EnumEntry* values, const char* type, - const char* sourceDescription, int* index) { + const Span& values, + const char* type, const char* sourceDescription, + int* index) { // JS_StringEqualsAscii is slow as molasses, so don't use it here. JS::Rooted str(cx, JS::ToString(cx, v)); if (!str) { @@ -1405,6 +1405,18 @@ inline bool FindEnumStringIndex(BindingCallContext& cx, JS::Handle v, return EnumValueNotFound(cx, str, type, sourceDescription); } +template +inline const nsCString& GetEnumString(Enum stringId) { + if (stringId == Enum::EndGuard_) { + return EmptyCString(); + } + MOZ_RELEASE_ASSERT( + static_cast(stringId) < + mozilla::ArrayLength(binding_detail::EnumStrings::Values)); + return binding_detail::EnumStrings::Values[static_cast( + stringId)]; +} + inline nsWrapperCache* GetWrapperCache(const ParentObject& aParentObject) { return aParentObject.mWrapperCache; } diff --git a/dom/bindings/Codegen.py b/dom/bindings/Codegen.py index 2c98d31c856f..33bea4fc68d7 100644 --- a/dom/bindings/Codegen.py +++ b/dom/bindings/Codegen.py @@ -51,7 +51,6 @@ LEGACYCALLER_HOOK_NAME = "_legacycaller" RESOLVE_HOOK_NAME = "_resolve" MAY_RESOLVE_HOOK_NAME = "_mayResolve" NEW_ENUMERATE_HOOK_NAME = "_newEnumerate" -ENUM_ENTRY_VARIABLE_NAME = "strings" INSTANCE_RESERVED_SLOTS = 1 # This size is arbitrary. It is a power of 2 to make using it as a modulo @@ -7046,7 +7045,10 @@ def getJSToNativeConversionInfo( """ { int index; - if (!FindEnumStringIndex<${invalidEnumValueFatal}>(cx, $${val}, ${values}, "${enumtype}", "${sourceDescription}", &index)) { + if (!FindEnumStringIndex<${invalidEnumValueFatal}>(cx, $${val}, + binding_detail::EnumStrings<${enumtype}>::Values, + "${enumtype}", "${sourceDescription}", + &index)) { $*{exceptionCode} } $*{handleInvalidEnumValueCode} @@ -7054,7 +7056,6 @@ def getJSToNativeConversionInfo( } """, enumtype=enumName, - values=enumName + "Values::" + ENUM_ENTRY_VARIABLE_NAME, invalidEnumValueFatal=toStringBool(invalidEnumValueFatal), handleInvalidEnumValueCode=handleInvalidEnumValueCode, exceptionCode=exceptionCode, @@ -12343,7 +12344,7 @@ def getEnumValueName(value): class CGEnumToJSValue(CGAbstractMethod): def __init__(self, enum): enumType = enum.identifier.name - self.stringsArray = enumType + "Values::" + ENUM_ENTRY_VARIABLE_NAME + self.stringsArray = "binding_detail::EnumStrings<" + enumType + ">::Values" CGAbstractMethod.__init__( self, None, @@ -12361,8 +12362,8 @@ class CGEnumToJSValue(CGAbstractMethod): """ MOZ_ASSERT(uint32_t(aArgument) < ArrayLength(${strings})); JSString* resultStr = - JS_NewStringCopyN(aCx, ${strings}[uint32_t(aArgument)].value, - ${strings}[uint32_t(aArgument)].length); + JS_NewStringCopyN(aCx, ${strings}[uint32_t(aArgument)].BeginReading(), + ${strings}[uint32_t(aArgument)].Length()); if (!resultStr) { return false; } @@ -12379,48 +12380,54 @@ class CGEnum(CGThing): self.enum = enum entryDecl = fill( """ - extern const EnumEntry ${entry_array}[${entry_count}]; + static constexpr size_t Count = ${count}; - static constexpr size_t Count = ${real_entry_count}; - - // Our "${entry_array}" contains an extra entry with a null string. - static_assert(mozilla::ArrayLength(${entry_array}) - 1 == Count, + static_assert(mozilla::ArrayLength(binding_detail::EnumStrings<${name}>::Values) == Count, "Mismatch between enum strings and enum count"); static_assert(static_cast(${name}::EndGuard_) == Count, "Mismatch between enum value and enum count"); - - inline auto GetString(${name} stringId) { - MOZ_ASSERT(static_cast<${type}>(stringId) < Count); - const EnumEntry& entry = ${entry_array}[static_cast<${type}>(stringId)]; - return Span{entry.value, entry.length}; - } """, - entry_array=ENUM_ENTRY_VARIABLE_NAME, - entry_count=self.nEnumStrings(), - # -1 because nEnumStrings() includes a string for EndGuard_ - real_entry_count=self.nEnumStrings() - 1, + count=self.nEnumStrings(), name=self.enum.identifier.name, type=CGEnum.underlyingType(enum), ) - strings = CGNamespace( - self.stringsNamespace(), - CGGeneric( - declare=entryDecl, - define=fill( - """ - extern const EnumEntry ${name}[${count}] = { - $*{entries} - { nullptr, 0 } - }; - """, - name=ENUM_ENTRY_VARIABLE_NAME, - count=self.nEnumStrings(), - entries="".join( - '{"%s", %d},\n' % (val, len(val)) for val in self.enum.values() + strings = CGList( + [ + CGNamespace( + "binding_detail", + CGGeneric( + declare=fill( + """ + template <> struct EnumStrings<${name}> { + static const nsLiteralCString Values[${count}]; + }; + """, + name=self.enum.identifier.name, + count=self.nEnumStrings(), + ), + define=fill( + """ + const nsLiteralCString EnumStrings<${name}>::Values[${count}] = { + $*{entries} + }; + """, + name=self.enum.identifier.name, + count=self.nEnumStrings(), + entries="".join( + '"%s"_ns,\n' % val for val in self.enum.values() + ), + ), ), ), - ), + CGNamespace( + self.stringsNamespace(), + CGGeneric( + declare=entryDecl, + ), + ), + ], + "\n", ) toJSValue = CGEnumToJSValue(enum) self.cgThings = CGList([strings, toJSValue], "\n") @@ -12429,7 +12436,7 @@ class CGEnum(CGThing): return self.enum.identifier.name + "Values" def nEnumStrings(self): - return len(self.enum.values()) + 1 + return len(self.enum.values()) @staticmethod def underlyingType(enum): diff --git a/dom/cache/Cache.cpp b/dom/cache/Cache.cpp index d9b94f6b14bc..3f84e08e66af 100644 --- a/dom/cache/Cache.cpp +++ b/dom/cache/Cache.cpp @@ -81,13 +81,12 @@ static bool IsValidPutResponseStatus(Response& aResponse, ErrorResult& aRv) { if ((aPolicy == PutStatusPolicy::RequireOK && !aResponse.Ok()) || aResponse.Status() == 206) { - nsCString type(ResponseTypeValues::GetString(aResponse.Type())); - nsAutoString url; aResponse.GetUrl(url); aRv.ThrowTypeError( - type, IntToCString(aResponse.Status()), NS_ConvertUTF16toUTF8(url)); + GetEnumString(aResponse.Type()), IntToCString(aResponse.Status()), + NS_ConvertUTF16toUTF8(url)); return false; } diff --git a/dom/console/ConsoleInstance.cpp b/dom/console/ConsoleInstance.cpp index b2de2d6fe7b7..dead0b19c52b 100644 --- a/dom/console/ConsoleInstance.cpp +++ b/dom/console/ConsoleInstance.cpp @@ -106,8 +106,9 @@ ConsoleLogLevel PrefToValue(const nsACString& aPref, return aLevel; } - int index = FindEnumStringIndexImpl(value.get(), value.Length(), - ConsoleLogLevelValues::strings); + int index = FindEnumStringIndexImpl( + value.get(), value.Length(), + binding_detail::EnumStrings::Values); if (NS_WARN_IF(index < 0)) { nsString message; message.AssignLiteral("Invalid Console.maxLogLevelPref value: "); diff --git a/dom/docs/webIdlBindings/index.md b/dom/docs/webIdlBindings/index.md index a239179071ca..0c15cb912b77 100644 --- a/dom/docs/webIdlBindings/index.md +++ b/dom/docs/webIdlBindings/index.md @@ -894,10 +894,7 @@ which becomes the value `_empty`. For a Web IDL enum named `MyEnum`, the C++ enum is named `MyEnum` and placed in the `mozilla::dom` namespace, while the values are placed in -the `mozilla::dom::MyEnum` namespace. There is also a -`mozilla::dom::MyEnumValues::strings` which is an array of -`mozilla::dom::EnumEntry` structs that gives access to the string -representations of the values. +the `mozilla::dom::MyEnum` namespace. The type of the enum class is automatically selected to be the smallest unsigned integer type that can hold all the values. In practice, this @@ -924,12 +921,14 @@ enum class MyEnum : uint8_t { _empty, Another }; - -namespace MyEnumValues { -extern const EnumEntry strings[10]; -} // namespace MyEnumValues ``` +`mozilla::dom::GetEnumString` is a templated helper function declared in +[`BindingUtils.h`](https://searchfox.org/mozilla-central/source/dom/bindings/BindingUtils.h) +and exported to `mozilla/dom/BindingUtils.h` that can be used to convert an enum +value to its corresponding string value. It returns a `const nsCString&` +containing the string value. + #### Callback function types Callback functions are represented as an object, inheriting from diff --git a/dom/fetch/Request.cpp b/dom/fetch/Request.cpp index bad53c3527b0..5b6d7c3ba4db 100644 --- a/dom/fetch/Request.cpp +++ b/dom/fetch/Request.cpp @@ -493,8 +493,8 @@ SafeRefPtr Request::Constructor(nsIGlobalObject* aGlobal, if (cache != RequestCache::EndGuard_) { if (cache == RequestCache::Only_if_cached && request->Mode() != RequestMode::Same_origin) { - nsCString modeString(RequestModeValues::GetString(request->Mode())); - aRv.ThrowTypeError(modeString); + aRv.ThrowTypeError( + GetEnumString(request->Mode())); return nullptr; } request->SetCacheMode(cache); diff --git a/dom/html/nsGenericHTMLElement.cpp b/dom/html/nsGenericHTMLElement.cpp index b1474cde023d..1014ba2a25aa 100644 --- a/dom/html/nsGenericHTMLElement.cpp +++ b/dom/html/nsGenericHTMLElement.cpp @@ -1269,25 +1269,24 @@ bool nsGenericHTMLElement::ParseImageAttribute(nsAtom* aAttribute, bool nsGenericHTMLElement::ParseReferrerAttribute(const nsAString& aString, nsAttrValue& aResult) { using mozilla::dom::ReferrerInfo; + // This is a bit sketchy, we assume GetEnumString(…).get() points to a static + // buffer, relying on the fact that GetEnumString(…) returns a literal string. static const nsAttrValue::EnumTable kReferrerPolicyTable[] = { - {ReferrerInfo::ReferrerPolicyToString(ReferrerPolicy::No_referrer), + {GetEnumString(ReferrerPolicy::No_referrer).get(), static_cast(ReferrerPolicy::No_referrer)}, - {ReferrerInfo::ReferrerPolicyToString(ReferrerPolicy::Origin), + {GetEnumString(ReferrerPolicy::Origin).get(), static_cast(ReferrerPolicy::Origin)}, - {ReferrerInfo::ReferrerPolicyToString( - ReferrerPolicy::Origin_when_cross_origin), + {GetEnumString(ReferrerPolicy::Origin_when_cross_origin).get(), static_cast(ReferrerPolicy::Origin_when_cross_origin)}, - {ReferrerInfo::ReferrerPolicyToString( - ReferrerPolicy::No_referrer_when_downgrade), + {GetEnumString(ReferrerPolicy::No_referrer_when_downgrade).get(), static_cast(ReferrerPolicy::No_referrer_when_downgrade)}, - {ReferrerInfo::ReferrerPolicyToString(ReferrerPolicy::Unsafe_url), + {GetEnumString(ReferrerPolicy::Unsafe_url).get(), static_cast(ReferrerPolicy::Unsafe_url)}, - {ReferrerInfo::ReferrerPolicyToString(ReferrerPolicy::Strict_origin), + {GetEnumString(ReferrerPolicy::Strict_origin).get(), static_cast(ReferrerPolicy::Strict_origin)}, - {ReferrerInfo::ReferrerPolicyToString(ReferrerPolicy::Same_origin), + {GetEnumString(ReferrerPolicy::Same_origin).get(), static_cast(ReferrerPolicy::Same_origin)}, - {ReferrerInfo::ReferrerPolicyToString( - ReferrerPolicy::Strict_origin_when_cross_origin), + {GetEnumString(ReferrerPolicy::Strict_origin_when_cross_origin).get(), static_cast(ReferrerPolicy::Strict_origin_when_cross_origin)}, {nullptr, ReferrerPolicy::_empty}}; return aResult.ParseEnumValue(aString, kReferrerPolicyTable, false); diff --git a/dom/media/MediaDevices.cpp b/dom/media/MediaDevices.cpp index cfbc148337bd..2efe6d786d31 100644 --- a/dom/media/MediaDevices.cpp +++ b/dom/media/MediaDevices.cpp @@ -550,7 +550,7 @@ already_AddRefed MediaDevices::GetDisplayMedia( // for us. vc.mMediaSource.Reset(); vc.mMediaSource.Construct().AssignASCII( - dom::MediaSourceEnumValues::GetString(MediaSourceEnum::Screen)); + dom::GetEnumString(MediaSourceEnum::Screen)); RefPtr self(this); MediaManager::Get() diff --git a/dom/media/MediaManager.cpp b/dom/media/MediaManager.cpp index 2c3cd7eba4b2..a3e69f155e87 100644 --- a/dom/media/MediaManager.cpp +++ b/dom/media/MediaManager.cpp @@ -872,8 +872,7 @@ MediaDevice::MediaDevice(MediaEngine* aEngine, MediaSourceEnum aMediaSource, mCanRequestOsLevelPrompt(canRequestOsLevelPrompt == OsPromptable::Yes), mIsFake(mEngine->IsFake()), mIsPlaceholder(aIsPlaceholder == IsPlaceholder::Yes), - mType( - NS_ConvertASCIItoUTF16(dom::MediaDeviceKindValues::GetString(mKind))), + mType(NS_ConvertASCIItoUTF16(dom::GetEnumString(mKind))), mRawID(aRawID), mRawGroupID(aRawGroupID), mRawName(aRawName) { @@ -895,8 +894,7 @@ MediaDevice::MediaDevice(MediaEngine* aEngine, mCanRequestOsLevelPrompt(false), mIsFake(false), mIsPlaceholder(false), - mType( - NS_ConvertASCIItoUTF16(dom::MediaDeviceKindValues::GetString(mKind))), + mType(NS_ConvertASCIItoUTF16(dom::GetEnumString(mKind))), mRawID(aRawID), mRawGroupID(mAudioDeviceInfo->GroupID()), mRawName(mAudioDeviceInfo->Name()) {} @@ -1064,8 +1062,7 @@ LocalMediaDevice::GetMediaSource(nsAString& aMediaSource) { if (Kind() == MediaDeviceKind::Audiooutput) { aMediaSource.Truncate(); } else { - aMediaSource.AssignASCII( - dom::MediaSourceEnumValues::GetString(GetMediaSource())); + aMediaSource.AssignASCII(dom::GetEnumString(GetMediaSource())); } return NS_OK; } @@ -2747,10 +2744,11 @@ RefPtr MediaManager::GetUserMedia( auto& vc = c.mVideo.GetAsMediaTrackConstraints(); if (!vc.mMediaSource.WasPassed()) { vc.mMediaSource.Construct().AssignASCII( - dom::MediaSourceEnumValues::GetString(MediaSourceEnum::Camera)); + dom::GetEnumString(MediaSourceEnum::Camera)); } - videoType = StringToEnum(dom::MediaSourceEnumValues::strings, - vc.mMediaSource.Value(), MediaSourceEnum::Other); + videoType = StringToEnum( + dom::binding_detail::EnumStrings::Values, + vc.mMediaSource.Value(), MediaSourceEnum::Other); Telemetry::Accumulate(Telemetry::WEBRTC_GET_USER_MEDIA_TYPE, (uint32_t)videoType); switch (videoType) { @@ -2815,8 +2813,7 @@ RefPtr MediaManager::GetUserMedia( if (videoType == MediaSourceEnum::Screen || videoType == MediaSourceEnum::Browser) { videoType = MediaSourceEnum::Window; - vc.mMediaSource.Value().AssignASCII( - dom::MediaSourceEnumValues::GetString(videoType)); + vc.mMediaSource.Value().AssignASCII(dom::GetEnumString(videoType)); } // only allow privileged content to set the window id if (vc.mBrowserWindow.WasPassed()) { @@ -2840,10 +2837,11 @@ RefPtr MediaManager::GetUserMedia( auto& ac = c.mAudio.GetAsMediaTrackConstraints(); if (!ac.mMediaSource.WasPassed()) { ac.mMediaSource.Construct(NS_ConvertASCIItoUTF16( - dom::MediaSourceEnumValues::GetString(MediaSourceEnum::Microphone))); + dom::GetEnumString(MediaSourceEnum::Microphone))); } - audioType = StringToEnum(dom::MediaSourceEnumValues::strings, - ac.mMediaSource.Value(), MediaSourceEnum::Other); + audioType = StringToEnum( + dom::binding_detail::EnumStrings::Values, + ac.mMediaSource.Value(), MediaSourceEnum::Other); Telemetry::Accumulate(Telemetry::WEBRTC_GET_USER_MEDIA_TYPE, (uint32_t)audioType); @@ -4004,8 +4002,7 @@ void DeviceListener::Activate(RefPtr aDevice, MOZ_ASSERT(NS_IsMainThread(), "Only call on main thread"); LOG("DeviceListener %p activating %s device %p", this, - nsCString(dom::MediaDeviceKindValues::GetString(aDevice->Kind())).get(), - aDevice.get()); + dom::GetEnumString(aDevice->Kind()).get(), aDevice.get()); MOZ_ASSERT(!mStopped, "Cannot activate stopped device listener"); MOZ_ASSERT(!Activated(), "Already activated"); @@ -4061,18 +4058,15 @@ DeviceListener::InitializeAsync() { } if (NS_FAILED(rv)) { nsCString log; - log.AppendPrintf( - "Starting %s failed", - nsCString(dom::MediaDeviceKindValues::GetString(kind)) - .get()); + log.AppendPrintf("Starting %s failed", + dom::GetEnumString(kind).get()); aHolder.Reject( MakeRefPtr(MediaMgrError::Name::AbortError, std::move(log)), __func__); return; } - LOG("started %s device %p", - nsCString(dom::MediaDeviceKindValues::GetString(kind)).get(), + LOG("started %s device %p", dom::GetEnumString(kind).get(), device.get()); aHolder.Resolve(true, __func__); }) @@ -4180,9 +4174,7 @@ auto DeviceListener::UpdateDevice(bool aOn) -> RefPtr { } LOG("DeviceListener %p turning %s %s input device %s", this, aOn ? "on" : "off", - nsCString( - dom::MediaDeviceKindValues::GetString(GetDevice()->Kind())) - .get(), + dom::GetEnumString(GetDevice()->Kind()).get(), NS_SUCCEEDED(aResult) ? "succeeded" : "failed"); if (NS_FAILED(aResult) && aResult != NS_ERROR_ABORT) { @@ -4215,8 +4207,7 @@ void DeviceListener::SetDeviceEnabled(bool aEnable) { LOG("DeviceListener %p %s %s device", this, aEnable ? "enabling" : "disabling", - nsCString(dom::MediaDeviceKindValues::GetString(GetDevice()->Kind())) - .get()); + dom::GetEnumString(GetDevice()->Kind()).get()); state.mTrackEnabled = aEnable; @@ -4272,9 +4263,7 @@ void DeviceListener::SetDeviceEnabled(bool aEnable) { LOG("DeviceListener %p %s %s device - starting device operation", this, aEnable ? "enabling" : "disabling", - nsCString( - dom::MediaDeviceKindValues::GetString(GetDevice()->Kind())) - .get()); + dom::GetEnumString(GetDevice()->Kind()).get()); if (state.mStopped) { // Source was stopped between timer resolving and this runnable. @@ -4343,8 +4332,7 @@ void DeviceListener::SetDeviceMuted(bool aMute) { DeviceState& state = *mDeviceState; LOG("DeviceListener %p %s %s device", this, aMute ? "muting" : "unmuting", - nsCString(dom::MediaDeviceKindValues::GetString(GetDevice()->Kind())) - .get()); + dom::GetEnumString(GetDevice()->Kind()).get()); if (state.mStopped) { // Device terminally stopped. Updating device state is pointless. @@ -4358,8 +4346,7 @@ void DeviceListener::SetDeviceMuted(bool aMute) { LOG("DeviceListener %p %s %s device - starting device operation", this, aMute ? "muting" : "unmuting", - nsCString(dom::MediaDeviceKindValues::GetString(GetDevice()->Kind())) - .get()); + dom::GetEnumString(GetDevice()->Kind()).get()); state.mDeviceMuted = aMute; @@ -4465,9 +4452,7 @@ RefPtr DeviceListener::ApplyConstraints( if (mStopped || mDeviceState->mStopped) { LOG("DeviceListener %p %s device applyConstraints, but device is stopped", - this, - nsCString(dom::MediaDeviceKindValues::GetString(GetDevice()->Kind())) - .get()); + this, dom::GetEnumString(GetDevice()->Kind()).get()); return DeviceListenerPromise::CreateAndResolve(false, __func__); } diff --git a/dom/media/MediaStreamTrack.cpp b/dom/media/MediaStreamTrack.cpp index 8ddb16d8e1fc..4235d96d1355 100644 --- a/dom/media/MediaStreamTrack.cpp +++ b/dom/media/MediaStreamTrack.cpp @@ -324,7 +324,7 @@ void MediaStreamTrack::GetSettings(dom::MediaTrackSettings& aResult, } if (aResult.mFacingMode.WasPassed()) { aResult.mFacingMode.Value().AssignASCII( - VideoFacingModeEnumValues::GetString(VideoFacingModeEnum::User)); + GetEnumString(VideoFacingModeEnum::User)); } } diff --git a/dom/media/eme/MediaKeySession.cpp b/dom/media/eme/MediaKeySession.cpp index 908df5f7c814..407cf3ce3d07 100644 --- a/dom/media/eme/MediaKeySession.cpp +++ b/dom/media/eme/MediaKeySession.cpp @@ -123,9 +123,8 @@ void MediaKeySession::UpdateKeyStatusMap() { nsPrintfCString("MediaKeySession[%p,'%s'] key statuses change {", this, NS_ConvertUTF16toUTF8(mSessionId).get())); for (const CDMCaps::KeyStatus& status : keyStatuses) { - message.AppendPrintf( - " (%s,%s)", ToHexString(status.mId).get(), - nsCString(MediaKeyStatusValues::GetString(status.mStatus)).get()); + message.AppendPrintf(" (%s,%s)", ToHexString(status.mId).get(), + GetEnumString(status.mStatus).get()); } message.AppendLiteral(" }"); // Use %s so we aren't exposing random strings to printf interpolation. @@ -542,8 +541,7 @@ void MediaKeySession::DispatchKeyMessage(MediaKeyMessageType aMessageType, EME_LOG( "MediaKeySession[%p,'%s'] DispatchKeyMessage() type=%s message='%s'", this, NS_ConvertUTF16toUTF8(mSessionId).get(), - nsCString(MediaKeyMessageTypeValues::GetString(aMessageType)).get(), - ToHexString(aMessage).get()); + GetEnumString(aMessageType).get(), ToHexString(aMessage).get()); } RefPtr event( @@ -611,12 +609,8 @@ void MediaKeySession::SetOnmessage(EventHandlerNonNull* aCallback) { SetEventHandler(nsGkAtoms::onmessage, aCallback); } -nsCString ToCString(MediaKeySessionType aType) { - return nsCString(MediaKeySessionTypeValues::GetString(aType)); -} - nsString ToString(MediaKeySessionType aType) { - return NS_ConvertUTF8toUTF16(ToCString(aType)); + return NS_ConvertUTF8toUTF16(GetEnumString(aType)); } } // namespace mozilla::dom diff --git a/dom/media/eme/MediaKeySession.h b/dom/media/eme/MediaKeySession.h index e19488c311b1..c61083fa0b61 100644 --- a/dom/media/eme/MediaKeySession.h +++ b/dom/media/eme/MediaKeySession.h @@ -36,8 +36,6 @@ class ArrayBufferViewOrArrayBuffer; class MediaKeyError; class MediaKeyStatusMap; -nsCString ToCString(MediaKeySessionType aType); - nsString ToString(MediaKeySessionType aType); class MediaKeySession final : public DOMEventTargetHelper, diff --git a/dom/media/eme/MediaKeySystemAccess.cpp b/dom/media/eme/MediaKeySystemAccess.cpp index b58ff764249a..60ce880fce5b 100644 --- a/dom/media/eme/MediaKeySystemAccess.cpp +++ b/dom/media/eme/MediaKeySystemAccess.cpp @@ -1082,7 +1082,7 @@ static nsCString ToCString(const nsString& aString) { static nsCString ToCString(const MediaKeysRequirement aValue) { nsCString str("'"); - str.AppendASCII(MediaKeysRequirementValues::GetString(aValue)); + str.AppendASCII(GetEnumString(aValue)); str.AppendLiteral("'"); return str; } diff --git a/dom/media/eme/MediaKeySystemAccessManager.cpp b/dom/media/eme/MediaKeySystemAccessManager.cpp index 2bc12d57d75a..8ebe7ceee779 100644 --- a/dom/media/eme/MediaKeySystemAccessManager.cpp +++ b/dom/media/eme/MediaKeySystemAccessManager.cpp @@ -412,8 +412,7 @@ void MediaKeySystemAccessManager::RequestMediaKeySystemAccess( "MediaKeySystemAccess::GetKeySystemStatus(%s) " "result=%s msg='%s'", NS_ConvertUTF16toUTF8(aRequest->mKeySystem).get(), - nsCString(MediaKeySystemStatusValues::GetString(status)).get(), - message.get()); + GetEnumString(status).get(), message.get()); LogToBrowserConsole(NS_ConvertUTF8toUTF16(msg)); EME_LOG("%s", msg.get()); diff --git a/dom/media/eme/MediaKeys.cpp b/dom/media/eme/MediaKeys.cpp index c4340885a342..2cd7cc7f472f 100644 --- a/dom/media/eme/MediaKeys.cpp +++ b/dom/media/eme/MediaKeys.cpp @@ -792,8 +792,7 @@ void MediaKeys::GetSessionsInfo(nsString& sessionsInfo) { sessionsInfo.AppendLiteral("(kid="); sessionsInfo.Append(keyID); sessionsInfo.AppendLiteral(" status="); - sessionsInfo.AppendASCII( - MediaKeyStatusValues::GetString(keyStatusMap->GetValueAtIndex(i))); + sessionsInfo.AppendASCII(GetEnumString(keyStatusMap->GetValueAtIndex(i))); sessionsInfo.AppendLiteral(")"); } sessionsInfo.AppendLiteral(")"); @@ -824,7 +823,7 @@ already_AddRefed MediaKeys::GetStatusForPolicy( } EME_LOG("GetStatusForPolicy minHdcpVersion = %s.", - HDCPVersionValues::GetString(aPolicy.mMinHdcpVersion.Value()).data()); + GetEnumString(aPolicy.mMinHdcpVersion.Value()).get()); mProxy->GetStatusForPolicy(StorePromise(promise), aPolicy.mMinHdcpVersion.Value()); return promise.forget(); diff --git a/dom/media/eme/mediafoundation/WMFCDMProxy.cpp b/dom/media/eme/mediafoundation/WMFCDMProxy.cpp index 21207ecc220f..f7e05dfb6a84 100644 --- a/dom/media/eme/mediafoundation/WMFCDMProxy.cpp +++ b/dom/media/eme/mediafoundation/WMFCDMProxy.cpp @@ -381,8 +381,7 @@ void WMFCDMProxy::GetStatusForPolicy(PromiseId aPromiseId, RETURN_IF_SHUTDOWN(); EME_LOG("WMFCDMProxy::GetStatusForPolicy(this=%p, pid=%" PRIu32 ", minHDCP=%s)", - this, aPromiseId, - dom::HDCPVersionValues::GetString(aMinHdcpVersion).data()); + this, aPromiseId, dom::GetEnumString(aMinHdcpVersion).get()); mCDM->GetStatusForPolicy(aPromiseId, aMinHdcpVersion) ->Then( mMainThread, __func__, diff --git a/dom/media/gmp/ChromiumCDMProxy.cpp b/dom/media/gmp/ChromiumCDMProxy.cpp index e8d871a1132b..566b386b0b23 100644 --- a/dom/media/gmp/ChromiumCDMProxy.cpp +++ b/dom/media/gmp/ChromiumCDMProxy.cpp @@ -605,8 +605,7 @@ void ChromiumCDMProxy::GetStatusForPolicy( MOZ_ASSERT(NS_IsMainThread()); EME_LOG("ChromiumCDMProxy::GetStatusForPolicy(this=%p, pid=%" PRIu32 ") minHdcpVersion=%s", - this, aPromiseId, - dom::HDCPVersionValues::GetString(aMinHdcpVersion).data()); + this, aPromiseId, dom::GetEnumString(aMinHdcpVersion).get()); RefPtr cdm = GetCDMParent(); if (!cdm) { diff --git a/dom/media/mediacapabilities/MediaCapabilities.cpp b/dom/media/mediacapabilities/MediaCapabilities.cpp index abc83dae4d02..d3123f913b29 100644 --- a/dom/media/mediacapabilities/MediaCapabilities.cpp +++ b/dom/media/mediacapabilities/MediaCapabilities.cpp @@ -45,21 +45,6 @@ static nsCString VideoConfigurationToStr(const VideoConfiguration* aConfig) { return nsCString(); } - nsCString hdrMetaType( - aConfig->mHdrMetadataType.WasPassed() - ? HdrMetadataTypeValues::GetString(aConfig->mHdrMetadataType.Value()) - : "?"); - - nsCString colorGamut( - aConfig->mColorGamut.WasPassed() - ? ColorGamutValues::GetString(aConfig->mColorGamut.Value()) - : "?"); - - nsCString transferFunction(aConfig->mTransferFunction.WasPassed() - ? TransferFunctionValues::GetString( - aConfig->mTransferFunction.Value()) - : "?"); - auto str = nsPrintfCString( "[contentType:%s width:%d height:%d bitrate:%" PRIu64 " framerate:%lf hasAlphaChannel:%s hdrMetadataType:%s colorGamut:%s " @@ -69,7 +54,15 @@ static nsCString VideoConfigurationToStr(const VideoConfiguration* aConfig) { aConfig->mHasAlphaChannel.WasPassed() ? aConfig->mHasAlphaChannel.Value() ? "true" : "false" : "?", - hdrMetaType.get(), colorGamut.get(), transferFunction.get(), + aConfig->mHdrMetadataType.WasPassed() + ? GetEnumString(aConfig->mHdrMetadataType.Value()).get() + : "?", + aConfig->mColorGamut.WasPassed() + ? GetEnumString(aConfig->mColorGamut.Value()).get() + : "?", + aConfig->mTransferFunction.WasPassed() + ? GetEnumString(aConfig->mTransferFunction.Value()).get() + : "?", aConfig->mScalabilityMode.WasPassed() ? NS_ConvertUTF16toUTF8(aConfig->mScalabilityMode.Value()).get() : "?"); diff --git a/dom/media/webcodecs/VideoDecoder.cpp b/dom/media/webcodecs/VideoDecoder.cpp index 2fa03e6b2cc8..3774d539c814 100644 --- a/dom/media/webcodecs/VideoDecoder.cpp +++ b/dom/media/webcodecs/VideoDecoder.cpp @@ -170,9 +170,7 @@ nsString VideoDecoderConfigInternal::ToString() const { if (mDescription.isSome()) { rv.AppendPrintf("extradata: %zu bytes", mDescription.value()->Length()); } - rv.AppendPrintf( - "hw accel: %s", - HardwareAccelerationValues::GetString(mHardwareAcceleration).data()); + rv.AppendPrintf("hw accel: %s", GetEnumString(mHardwareAcceleration).get()); if (mOptimizeForLatency.isSome()) { rv.AppendPrintf("optimize for latency: %s", mOptimizeForLatency.value() ? "true" : "false"); diff --git a/dom/media/webcodecs/VideoEncoder.cpp b/dom/media/webcodecs/VideoEncoder.cpp index 3a2ae0a88a41..57aa03671822 100644 --- a/dom/media/webcodecs/VideoEncoder.cpp +++ b/dom/media/webcodecs/VideoEncoder.cpp @@ -135,26 +135,20 @@ nsString VideoEncoderConfigInternal::ToString() const { if (mFramerate.isSome()) { rv.AppendPrintf(", %lfHz", mFramerate.value()); } - rv.AppendPrintf( - " hw: %s", - HardwareAccelerationValues::GetString(mHardwareAcceleration).data()); - rv.AppendPrintf(", alpha: %s", AlphaOptionValues::GetString(mAlpha).data()); + rv.AppendPrintf(" hw: %s", GetEnumString(mHardwareAcceleration).get()); + rv.AppendPrintf(", alpha: %s", GetEnumString(mAlpha).get()); if (mScalabilityMode.isSome()) { rv.AppendPrintf(", scalability mode: %s", NS_ConvertUTF16toUTF8(mScalabilityMode.value()).get()); } - rv.AppendPrintf( - ", bitrate mode: %s", - VideoEncoderBitrateModeValues::GetString(mBitrateMode).data()); - rv.AppendPrintf(", latency mode: %s", - LatencyModeValues::GetString(mLatencyMode).data()); + rv.AppendPrintf(", bitrate mode: %s", GetEnumString(mBitrateMode).get()); + rv.AppendPrintf(", latency mode: %s", GetEnumString(mLatencyMode).get()); if (mContentHint.isSome()) { rv.AppendPrintf(", content hint: %s", NS_ConvertUTF16toUTF8(mContentHint.value()).get()); } if (mAvc.isSome()) { - rv.AppendPrintf(", avc-specific: %s", - AvcBitstreamFormatValues::GetString(mAvc->mFormat).data()); + rv.AppendPrintf(", avc-specific: %s", GetEnumString(mAvc->mFormat).get()); } return rv; diff --git a/dom/media/webcodecs/VideoFrame.cpp b/dom/media/webcodecs/VideoFrame.cpp index 602bc95c29ee..42ed266c6d8e 100644 --- a/dom/media/webcodecs/VideoFrame.cpp +++ b/dom/media/webcodecs/VideoFrame.cpp @@ -1789,15 +1789,13 @@ nsCString VideoFrame::ToString() const { return rv; } - rv.AppendPrintf( - "VideoFrame ts: %" PRId64 - ", %s, coded[%dx%d] visible[%dx%d], display[%dx%d] color: %s", - mTimestamp, - dom::VideoPixelFormatValues::GetString(mResource->mFormat->PixelFormat()) - .data(), - mCodedSize.width, mCodedSize.height, mVisibleRect.width, - mVisibleRect.height, mDisplaySize.width, mDisplaySize.height, - ColorSpaceInitToString(mColorSpace).get()); + rv.AppendPrintf("VideoFrame ts: %" PRId64 + ", %s, coded[%dx%d] visible[%dx%d], display[%dx%d] color: %s", + mTimestamp, + dom::GetEnumString(mResource->mFormat->PixelFormat()).get(), + mCodedSize.width, mCodedSize.height, mVisibleRect.width, + mVisibleRect.height, mDisplaySize.width, mDisplaySize.height, + ColorSpaceInitToString(mColorSpace).get()); if (mDuration) { rv.AppendPrintf(" dur: %" PRId64, mDuration.value()); diff --git a/dom/media/webcodecs/WebCodecsUtils.cpp b/dom/media/webcodecs/WebCodecsUtils.cpp index 1e03f616db18..99e7ece5bedd 100644 --- a/dom/media/webcodecs/WebCodecsUtils.cpp +++ b/dom/media/webcodecs/WebCodecsUtils.cpp @@ -364,15 +364,13 @@ struct ConfigurationChangeToString { } nsCString operator()( const HardwareAccelerationChange& aHardwareAccelerationChange) { - return nsPrintfCString("HW acceleration: %s", - dom::HardwareAccelerationValues::GetString( - aHardwareAccelerationChange.get()) - .data()); + return nsPrintfCString( + "HW acceleration: %s", + dom::GetEnumString(aHardwareAccelerationChange.get()).get()); } nsCString operator()(const AlphaChange& aAlphaChange) { - return nsPrintfCString( - "Alpha: %s", - dom::AlphaOptionValues::GetString(aAlphaChange.get()).data()); + return nsPrintfCString("Alpha: %s", + dom::GetEnumString(aAlphaChange.get()).get()); } nsCString operator()(const ScalabilityModeChange& aScalabilityModeChange) { if (aScalabilityModeChange.get().isNothing()) { @@ -383,15 +381,12 @@ struct ConfigurationChangeToString { NS_ConvertUTF16toUTF8(aScalabilityModeChange.get().value()).get()); } nsCString operator()(const BitrateModeChange& aBitrateModeChange) { - return nsPrintfCString( - "Bitrate mode: %s", - dom::VideoEncoderBitrateModeValues::GetString(aBitrateModeChange.get()) - .data()); + return nsPrintfCString("Bitrate mode: %s", + dom::GetEnumString(aBitrateModeChange.get()).get()); } nsCString operator()(const LatencyModeChange& aLatencyModeChange) { - return nsPrintfCString( - "Latency mode: %s", - dom::LatencyModeValues::GetString(aLatencyModeChange.get()).data()); + return nsPrintfCString("Latency mode: %s", + dom::GetEnumString(aLatencyModeChange.get()).get()); } nsCString operator()(const ContentHintChange& aContentHintChange) { return nsPrintfCString("Content hint: %s", @@ -489,9 +484,6 @@ WebCodecsConfigurationChangeList::ToPEMChangeList() const { return rv.forget(); } -#define ENUM_TO_STRING(enumType, enumValue) \ - enumType##Values::GetString(enumValue).data() - nsCString ColorSpaceInitToString( const dom::VideoColorSpaceInit& aColorSpaceInit) { nsCString rv("VideoColorSpace"); @@ -502,18 +494,15 @@ nsCString ColorSpaceInitToString( } if (!aColorSpaceInit.mMatrix.IsNull()) { rv.AppendPrintf(" matrix: %s", - ENUM_TO_STRING(dom::VideoMatrixCoefficients, - aColorSpaceInit.mMatrix.Value())); + GetEnumString(aColorSpaceInit.mMatrix.Value()).get()); } if (!aColorSpaceInit.mTransfer.IsNull()) { rv.AppendPrintf(" transfer: %s", - ENUM_TO_STRING(dom::VideoTransferCharacteristics, - aColorSpaceInit.mTransfer.Value())); + GetEnumString(aColorSpaceInit.mTransfer.Value()).get()); } if (!aColorSpaceInit.mPrimaries.IsNull()) { rv.AppendPrintf(" primaries: %s", - ENUM_TO_STRING(dom::VideoColorPrimaries, - aColorSpaceInit.mPrimaries.Value())); + GetEnumString(aColorSpaceInit.mPrimaries.Value()).get()); } return rv; diff --git a/dom/media/webrtc/MediaEngineFake.cpp b/dom/media/webrtc/MediaEngineFake.cpp index 8c69ec5e47b4..b14d80ffbbe4 100644 --- a/dom/media/webrtc/MediaEngineFake.cpp +++ b/dom/media/webrtc/MediaEngineFake.cpp @@ -136,10 +136,8 @@ MediaEngineFakeVideoSource::MediaEngineFakeVideoSource() mSettings->mHeight.Construct( int32_t(MediaEnginePrefs::DEFAULT_43_VIDEO_HEIGHT)); mSettings->mFrameRate.Construct(double(MediaEnginePrefs::DEFAULT_VIDEO_FPS)); - mSettings->mFacingMode.Construct( - NS_ConvertASCIItoUTF16(dom::VideoFacingModeEnumValues::strings - [uint8_t(VideoFacingModeEnum::Environment)] - .value)); + mSettings->mFacingMode.Construct(NS_ConvertASCIItoUTF16( + dom::GetEnumString(VideoFacingModeEnum::Environment))); } nsString MediaEngineFakeVideoSource::GetGroupId() { diff --git a/dom/media/webrtc/MediaEngineRemoteVideoSource.cpp b/dom/media/webrtc/MediaEngineRemoteVideoSource.cpp index a6648b68c7fd..dbb5e7ff7087 100644 --- a/dom/media/webrtc/MediaEngineRemoteVideoSource.cpp +++ b/dom/media/webrtc/MediaEngineRemoteVideoSource.cpp @@ -108,8 +108,7 @@ MediaEngineRemoteVideoSource::MediaEngineRemoteVideoSource( Maybe facingMode = GetFacingMode(mMediaDevice->mRawName); if (facingMode.isSome()) { - NS_ConvertASCIItoUTF16 facingString( - dom::VideoFacingModeEnumValues::GetString(*facingMode)); + NS_ConvertASCIItoUTF16 facingString(dom::GetEnumString(*facingMode)); mSettings->mFacingMode.Construct(facingString); mFacingMode.emplace(facingString); } diff --git a/dom/media/webrtc/MediaTrackConstraints.h b/dom/media/webrtc/MediaTrackConstraints.h index 61e0ed85ea11..03c97aa45279 100644 --- a/dom/media/webrtc/MediaTrackConstraints.h +++ b/dom/media/webrtc/MediaTrackConstraints.h @@ -23,8 +23,8 @@ class MediaDevice; template static Enum StringToEnum(const EnumValuesStrings& aStrings, const nsAString& aValue, Enum aDefaultValue) { - for (size_t i = 0; aStrings[i].value; i++) { - if (aValue.EqualsASCII(aStrings[i].value)) { + for (size_t i = 0; i < ArrayLength(aStrings); i++) { + if (aValue.EqualsASCII(aStrings[i].get())) { return Enum(i); } } diff --git a/dom/midi/MIDIPort.cpp b/dom/midi/MIDIPort.cpp index 3d75bf2d6338..94d7280c73d4 100644 --- a/dom/midi/MIDIPort.cpp +++ b/dom/midi/MIDIPort.cpp @@ -104,14 +104,14 @@ bool MIDIPort::Initialize(const MIDIPortInfo& aPortInfo, bool aSysexEnabled, mPortHolder.Init(port.forget()); LOG("MIDIPort::Initialize (%s, %s)", NS_ConvertUTF16toUTF8(Port()->Name()).get(), - MIDIPortTypeValues::strings[uint32_t(Port()->Type())].value); + GetEnumString(Port()->Type()).get()); return true; } void MIDIPort::UnsetIPCPort() { LOG("MIDIPort::UnsetIPCPort (%s, %s)", NS_ConvertUTF16toUTF8(Port()->Name()).get(), - MIDIPortTypeValues::strings[uint32_t(Port()->Type())].value); + GetEnumString(Port()->Type()).get()); mPortHolder.Clear(); } diff --git a/dom/payments/PaymentRequestManager.cpp b/dom/payments/PaymentRequestManager.cpp index 32ccac145a59..1f21ff1bab3e 100644 --- a/dom/payments/PaymentRequestManager.cpp +++ b/dom/payments/PaymentRequestManager.cpp @@ -220,8 +220,7 @@ void ConvertDetailsUpdate(JSContext* aCx, const PaymentDetailsUpdate& aDetails, void ConvertOptions(const PaymentOptions& aOptions, IPCPaymentOptions& aIPCOption) { - NS_ConvertASCIItoUTF16 shippingType( - PaymentShippingTypeValues::GetString(aOptions.mShippingType)); + NS_ConvertASCIItoUTF16 shippingType(GetEnumString(aOptions.mShippingType)); aIPCOption = IPCPaymentOptions(aOptions.mRequestPayerName, aOptions.mRequestPayerEmail, aOptions.mRequestPayerPhone, aOptions.mRequestShipping, @@ -548,8 +547,7 @@ void PaymentRequestManager::CompletePayment(PaymentRequest* aRequest, if (aTimedOut) { completeStatusString.AssignLiteral("timeout"); } else { - completeStatusString.AssignASCII( - PaymentCompleteValues::GetString(aComplete)); + completeStatusString.AssignASCII(GetEnumString(aComplete)); } nsAutoString requestId; diff --git a/dom/security/ReferrerInfo.cpp b/dom/security/ReferrerInfo.cpp index 70cdddb8aba7..b9e494b7c064 100644 --- a/dom/security/ReferrerInfo.cpp +++ b/dom/security/ReferrerInfo.cpp @@ -133,8 +133,11 @@ ReferrerPolicy ReferrerPolicyFromToken(const nsAString& aContent, // Supported tokes - ReferrerPolicyValues, are generated from // ReferrerPolicy.webidl - for (uint8_t i = 0; ReferrerPolicyValues::strings[i].value; i++) { - if (lowerContent.EqualsASCII(ReferrerPolicyValues::strings[i].value)) { + for (size_t i = 0; + i < ArrayLength(binding_detail::EnumStrings::Values); + i++) { + if (lowerContent.EqualsASCII( + binding_detail::EnumStrings::Values[i].get())) { return static_cast(i); } } @@ -187,18 +190,6 @@ ReferrerPolicy ReferrerInfo::ReferrerPolicyFromHeaderString( return referrerPolicy; } -// static -const char* ReferrerInfo::ReferrerPolicyToString(ReferrerPolicyEnum aPolicy) { - uint8_t index = static_cast(aPolicy); - uint8_t referrerPolicyCount = ArrayLength(ReferrerPolicyValues::strings); - MOZ_ASSERT(index < referrerPolicyCount); - if (index >= referrerPolicyCount) { - return ""; - } - - return ReferrerPolicyValues::strings[index].value; -} - /* static */ uint32_t ReferrerInfo::GetUserReferrerSendingPolicy() { return clamped( @@ -831,11 +822,8 @@ bool ReferrerInfo::ShouldIgnoreLessRestrictedPolicies( nsresult rv = aChannel->GetURI(getter_AddRefs(uri)); NS_ENSURE_SUCCESS(rv, true); - uint32_t idx = static_cast(aPolicy); - AutoTArray params = { - NS_ConvertUTF8toUTF16( - nsDependentCString(ReferrerPolicyValues::strings[idx].value)), + NS_ConvertUTF8toUTF16(GetEnumString(aPolicy)), NS_ConvertUTF8toUTF16(uri->GetSpecOrDefault())}; LogMessageToConsole(aChannel, "ReferrerPolicyDisallowRelaxingMessage", params); @@ -1051,7 +1039,7 @@ ReferrerInfo::GetReferrerPolicy( NS_IMETHODIMP ReferrerInfo::GetReferrerPolicyString(nsACString& aResult) { - aResult.AssignASCII(ReferrerPolicyToString(mPolicy)); + aResult.AssignASCII(GetEnumString(mPolicy)); return NS_OK; } diff --git a/dom/security/ReferrerInfo.h b/dom/security/ReferrerInfo.h index 78440a5a7017..b62afbb93486 100644 --- a/dom/security/ReferrerInfo.h +++ b/dom/security/ReferrerInfo.h @@ -258,13 +258,6 @@ class ReferrerInfo : public nsIReferrerInfo { static ReferrerPolicyEnum ReferrerPolicyFromHeaderString( const nsAString& aContent); - /* - * Helper function to convert ReferrerPolicy enum to string - * - * @param aPolicy referrer policy to convert. - */ - static const char* ReferrerPolicyToString(ReferrerPolicyEnum aPolicy); - /** * Hash function for this object */ diff --git a/dom/serviceworkers/ServiceWorkerEvents.cpp b/dom/serviceworkers/ServiceWorkerEvents.cpp index 531e29e905f6..602762502129 100644 --- a/dom/serviceworkers/ServiceWorkerEvents.cpp +++ b/dom/serviceworkers/ServiceWorkerEvents.cpp @@ -624,8 +624,7 @@ void RespondWithHandler::ResolvedCallback(JSContext* aCx, if (response->Type() == ResponseType::Opaque && mRequestMode != RequestMode::No_cors) { - NS_ConvertASCIItoUTF16 modeString( - RequestModeValues::GetString(mRequestMode)); + NS_ConvertASCIItoUTF16 modeString(GetEnumString(mRequestMode)); autoCancel.SetCancelMessage("BadOpaqueInterceptionRequestModeWithURL"_ns, mRequestURL, modeString); diff --git a/dom/serviceworkers/ServiceWorkerOp.cpp b/dom/serviceworkers/ServiceWorkerOp.cpp index 8811404a0f75..9c4fc569d194 100644 --- a/dom/serviceworkers/ServiceWorkerOp.cpp +++ b/dom/serviceworkers/ServiceWorkerOp.cpp @@ -1428,8 +1428,7 @@ void FetchEventOp::ResolvedCallback(JSContext* aCx, if (response->Type() == ResponseType::Opaque && requestMode != RequestMode::No_cors) { - NS_ConvertASCIItoUTF16 modeString( - RequestModeValues::GetString(requestMode)); + NS_ConvertASCIItoUTF16 modeString(GetEnumString(requestMode)); nsAutoString requestURL; GetRequestURL(requestURL); diff --git a/dom/vr/XRSystem.cpp b/dom/vr/XRSystem.cpp index 8d0a0e9d0e91..624eacf114c7 100644 --- a/dom/vr/XRSystem.cpp +++ b/dom/vr/XRSystem.cpp @@ -168,8 +168,9 @@ already_AddRefed XRSystem::RequestSession( if (aOptions.mRequiredFeatures.WasPassed()) { for (const nsString& val : aOptions.mRequiredFeatures.Value()) { - int index = FindEnumStringIndexImpl(val.BeginReading(), val.Length(), - XRReferenceSpaceTypeValues::strings); + int index = FindEnumStringIndexImpl( + val.BeginReading(), val.Length(), + binding_detail::EnumStrings::Values); if (index < 0) { promise->MaybeRejectWithNotSupportedError( "A required feature for the XRSession is not available."); @@ -182,8 +183,9 @@ already_AddRefed XRSystem::RequestSession( if (aOptions.mOptionalFeatures.WasPassed()) { for (const nsString& val : aOptions.mOptionalFeatures.Value()) { - int index = FindEnumStringIndexImpl(val.BeginReading(), val.Length(), - XRReferenceSpaceTypeValues::strings); + int index = FindEnumStringIndexImpl( + val.BeginReading(), val.Length(), + binding_detail::EnumStrings::Values); if (index >= 0) { optionalReferenceSpaceTypes.AppendElement( static_cast(index)); diff --git a/dom/webgpu/Adapter.cpp b/dom/webgpu/Adapter.cpp index 434ba7c6fa71..5f5101207fee 100644 --- a/dom/webgpu/Adapter.cpp +++ b/dom/webgpu/Adapter.cpp @@ -141,11 +141,11 @@ static Maybe MakeFeatureBits( for (const auto& feature : aFeatures) { const auto bit = ToWGPUFeatures(feature); if (!bit) { - const auto featureStr = dom::GPUFeatureNameValues::GetString(feature); + const auto featureStr = dom::GetEnumString(feature); (void)featureStr; NS_WARNING( nsPrintfCString("Requested feature bit for '%s' is not implemented.", - featureStr.data()) + featureStr.get()) .get()); return Nothing(); } @@ -363,12 +363,12 @@ already_AddRefed Adapter::RequestDevice( for (const auto requested : aDesc.mRequiredFeatures) { const bool supported = mFeatures->Features().count(requested); if (!supported) { - const auto fstr = dom::GPUFeatureNameValues::GetString(requested); + const auto fstr = dom::GetEnumString(requested); const auto astr = this->LabelOrId(); nsPrintfCString msg( "requestDevice: Feature '%s' requested must be supported by " "adapter %s", - fstr.data(), astr.get()); + fstr.get(), astr.get()); promise->MaybeRejectWithTypeError(msg); return; } diff --git a/dom/webgpu/SupportedFeatures.cpp b/dom/webgpu/SupportedFeatures.cpp index 294524bc8196..a32879a2b023 100644 --- a/dom/webgpu/SupportedFeatures.cpp +++ b/dom/webgpu/SupportedFeatures.cpp @@ -5,6 +5,7 @@ #include "SupportedFeatures.h" #include "Adapter.h" +#include "mozilla/dom/BindingUtils.h" #include "mozilla/dom/WebGPUBinding.h" namespace mozilla::webgpu { @@ -17,7 +18,7 @@ SupportedFeatures::SupportedFeatures(Adapter* const aParent) void SupportedFeatures::Add(const dom::GPUFeatureName aFeature, ErrorResult& aRv) { - const auto u8 = dom::GPUFeatureNameValues::GetString(aFeature); + const auto u8 = dom::GetEnumString(aFeature); const auto u16 = NS_ConvertUTF8toUTF16(u8); dom::GPUSupportedFeatures_Binding::SetlikeHelpers::Add(this, u16, aRv); diff --git a/ipc/glue/UtilityAudioDecoder.cpp b/ipc/glue/UtilityAudioDecoder.cpp index 0b28fd601e5f..0a294d95f5a0 100644 --- a/ipc/glue/UtilityAudioDecoder.cpp +++ b/ipc/glue/UtilityAudioDecoder.cpp @@ -6,6 +6,7 @@ #include "mozilla/ProcInfo.h" #include "mozilla/ipc/UtilityAudioDecoder.h" +#include "mozilla/dom/BindingUtils.h" #include "mozilla/ipc/UtilityProcessChild.h" namespace mozilla::ipc { @@ -34,8 +35,7 @@ UtilityActorName GetAudioActorName(const SandboxingKind aSandbox) { nsCString GetChildAudioActorName() { RefPtr s = ipc::UtilityProcessChild::Get(); MOZ_ASSERT(s, "Has UtilityProcessChild"); - return nsCString(dom::WebIDLUtilityActorNameValues::GetString( - GetAudioActorName(s->mSandbox))); + return dom::GetEnumString(GetAudioActorName(s->mSandbox)); } } // namespace mozilla::ipc diff --git a/ipc/glue/test/utility_process_xpcom/UtilityProcessTest.cpp b/ipc/glue/test/utility_process_xpcom/UtilityProcessTest.cpp index 6c084a3153c9..abee3e127ae5 100644 --- a/ipc/glue/test/utility_process_xpcom/UtilityProcessTest.cpp +++ b/ipc/glue/test/utility_process_xpcom/UtilityProcessTest.cpp @@ -31,9 +31,7 @@ static UtilityActorName UtilityActorNameFromString( // for iteration. for (size_t i = 0; i < WebIDLUtilityActorNameValues::Count; ++i) { auto idlName = static_cast(i); - const nsDependentCSubstring idlNameString( - WebIDLUtilityActorNameValues::GetString(idlName)); - if (idlNameString.Equals(aStringName)) { + if (GetEnumString(idlName).Equals(aStringName)) { return idlName; } }