From 332983c97b7a729c4dc5f19aa9ee4a22c420f7d8 Mon Sep 17 00:00:00 2001 From: Kae <80987908+Novaenia@users.noreply.github.com> Date: Tue, 27 Jun 2023 20:23:44 +1000 Subject: [PATCH] The Formatting String Catastrophe --- .../application/StarMainApplication_sdl.cpp | 22 +-- .../StarP2PNetworkingService_pc.cpp | 98 +++++------ .../application/StarPlatformServices_pc.cpp | 18 +-- source/application/StarRenderer_opengl20.cpp | 22 +-- .../StarStatisticsService_pc_steam.cpp | 8 +- source/base/StarAnimatedPartSet.cpp | 2 +- source/base/StarAssets.cpp | 72 ++++----- source/base/StarDirectoryAssetSource.cpp | 4 +- source/base/StarPackedAssetSource.cpp | 4 +- source/base/StarVersionOptionParser.cpp | 6 +- source/client/StarClientApplication.cpp | 34 ++-- source/core/StarAudio.cpp | 12 +- source/core/StarBTreeDatabase.cpp | 14 +- source/core/StarBiMap.hpp | 6 +- source/core/StarBuffer.cpp | 4 +- source/core/StarByteArray.cpp | 4 +- source/core/StarByteArray.hpp | 2 +- source/core/StarCasting.hpp | 4 +- source/core/StarColor.cpp | 4 +- source/core/StarCompression.cpp | 16 +- source/core/StarException_unix.cpp | 10 +- source/core/StarException_windows.cpp | 6 +- source/core/StarFile.cpp | 4 +- source/core/StarFile_unix.cpp | 34 ++-- source/core/StarFile_windows.cpp | 54 +++---- source/core/StarFont.cpp | 2 +- source/core/StarFormattedJson.cpp | 34 ++-- source/core/StarHostAddress.cpp | 10 +- source/core/StarIODevice.cpp | 4 +- source/core/StarIdMap.hpp | 2 +- source/core/StarImage.cpp | 20 +-- source/core/StarImageProcessing.cpp | 40 ++--- source/core/StarJson.cpp | 32 ++-- source/core/StarJsonBuilder.cpp | 2 +- source/core/StarJsonBuilder.hpp | 8 +- source/core/StarJsonExtra.cpp | 8 +- source/core/StarJsonExtra.hpp | 12 +- source/core/StarJsonPatch.cpp | 12 +- source/core/StarJsonPath.cpp | 10 +- source/core/StarJsonPath.hpp | 26 +-- source/core/StarJsonRpc.cpp | 12 +- source/core/StarLexicalCast.hpp | 2 +- source/core/StarList.hpp | 4 +- source/core/StarLockFile_unix.cpp | 4 +- source/core/StarLockFile_windows.cpp | 2 +- source/core/StarLogging.cpp | 4 +- source/core/StarLogging.hpp | 2 +- source/core/StarLua.cpp | 8 +- source/core/StarLua.hpp | 18 +-- source/core/StarMap.hpp | 10 +- source/core/StarMultiArray.hpp | 6 +- source/core/StarNetElementContainers.hpp | 4 +- source/core/StarNetImpl.hpp | 4 +- source/core/StarOptionParser.cpp | 48 +++--- source/core/StarOrderedMap.hpp | 16 +- source/core/StarSignalHandler_windows.cpp | 8 +- source/core/StarSmallVector.hpp | 6 +- source/core/StarSocket.cpp | 20 +-- source/core/StarStaticVector.hpp | 8 +- source/core/StarString.cpp | 4 +- source/core/StarString.hpp | 2 +- source/core/StarStringView.cpp | 4 +- source/core/StarTcp.cpp | 16 +- source/core/StarThread_unix.cpp | 16 +- source/core/StarThread_windows.cpp | 6 +- source/core/StarTime.cpp | 8 +- source/core/StarTime_unix.cpp | 14 +- source/core/StarTime_windows.cpp | 14 +- source/core/StarUdp.cpp | 6 +- source/core/StarUnicode.cpp | 2 +- source/core/StarUuid.cpp | 2 +- source/core/StarWorkerPool.cpp | 2 +- source/frontend/StarActionBar.cpp | 20 +-- source/frontend/StarBookmarkInterface.cpp | 4 +- source/frontend/StarCharCreation.cpp | 12 +- source/frontend/StarChat.cpp | 6 +- source/frontend/StarCinematic.cpp | 2 +- .../frontend/StarClientCommandProcessor.cpp | 42 ++--- source/frontend/StarCodexInterface.cpp | 2 +- source/frontend/StarContainerInterface.cpp | 2 +- source/frontend/StarCraftingInterface.cpp | 10 +- source/frontend/StarGraphicsMenu.cpp | 4 +- source/frontend/StarInventory.cpp | 22 +-- source/frontend/StarItemTooltip.cpp | 22 +-- source/frontend/StarKeybindingsMenu.cpp | 2 +- source/frontend/StarMainInterface.cpp | 12 +- source/frontend/StarMerchantInterface.cpp | 10 +- source/frontend/StarQuestInterface.cpp | 4 +- source/frontend/StarRadioMessagePopup.cpp | 6 +- source/frontend/StarScriptPane.cpp | 2 +- source/frontend/StarTeamBar.cpp | 4 +- source/frontend/StarTeleportDialog.cpp | 2 +- source/frontend/StarWidgetLuaBindings.cpp | 2 +- source/game/StarActorMovementController.cpp | 8 +- source/game/StarAiDatabase.cpp | 2 +- source/game/StarBehaviorDatabase.cpp | 18 +-- source/game/StarBehaviorState.cpp | 12 +- source/game/StarBiomeDatabase.cpp | 10 +- source/game/StarBiomePlacement.cpp | 4 +- source/game/StarCelestialCoordinate.cpp | 14 +- source/game/StarCelestialDatabase.cpp | 16 +- source/game/StarCelestialGraphics.cpp | 12 +- source/game/StarCelestialParameters.cpp | 2 +- source/game/StarChatProcessor.cpp | 12 +- source/game/StarCodexDatabase.cpp | 4 +- source/game/StarCollectionDatabase.cpp | 6 +- source/game/StarCommandProcessor.cpp | 108 ++++++------- source/game/StarDamageDatabase.cpp | 8 +- source/game/StarDanceDatabase.cpp | 2 +- source/game/StarDungeonGenerator.cpp | 44 ++--- source/game/StarDungeonImagePart.cpp | 6 +- source/game/StarDungeonTMXPart.cpp | 8 +- source/game/StarEffectSourceDatabase.cpp | 4 +- source/game/StarEntityFactory.cpp | 8 +- source/game/StarEntityMap.cpp | 10 +- source/game/StarForceRegions.cpp | 2 +- source/game/StarGameTypes.cpp | 2 +- source/game/StarHumanoid.cpp | 120 +++++++------- source/game/StarInventoryTypes.cpp | 6 +- source/game/StarItem.cpp | 2 +- source/game/StarItemDatabase.cpp | 28 ++-- source/game/StarItemDescriptor.cpp | 2 +- source/game/StarLiquidsDatabase.cpp | 14 +- source/game/StarMaterialDatabase.cpp | 32 ++-- source/game/StarMaterialRenderProfile.cpp | 6 +- source/game/StarMicroDungeon.cpp | 4 +- source/game/StarMonster.cpp | 2 +- source/game/StarMonsterDatabase.cpp | 18 +-- source/game/StarNameGenerator.cpp | 8 +- source/game/StarNetPacketSocket.cpp | 14 +- source/game/StarNetPackets.cpp | 2 +- source/game/StarNetworkedAnimator.cpp | 2 +- source/game/StarNpcDatabase.cpp | 4 +- source/game/StarObject.cpp | 4 +- source/game/StarObjectDatabase.cpp | 12 +- source/game/StarParallax.cpp | 6 +- source/game/StarParticleDatabase.cpp | 4 +- source/game/StarPlant.cpp | 32 ++-- source/game/StarPlantDatabase.cpp | 14 +- source/game/StarPlatformerAStarTypes.hpp | 4 +- source/game/StarPlayer.cpp | 4 +- source/game/StarPlayerCodexes.cpp | 4 +- source/game/StarPlayerStorage.cpp | 38 ++--- source/game/StarPlayerTech.cpp | 4 +- source/game/StarProjectile.cpp | 6 +- source/game/StarProjectileDatabase.cpp | 14 +- source/game/StarQuestDescriptor.cpp | 4 +- source/game/StarQuestManager.cpp | 2 +- source/game/StarQuestTemplateDatabase.cpp | 4 +- source/game/StarQuests.cpp | 2 +- source/game/StarRadioMessageDatabase.cpp | 8 +- source/game/StarRoot.cpp | 26 +-- source/game/StarRootLoader.cpp | 10 +- source/game/StarServerClientContext.cpp | 2 +- source/game/StarSongbook.cpp | 10 +- source/game/StarSpawnTypeDatabase.cpp | 6 +- source/game/StarSpawner.cpp | 8 +- source/game/StarSpeciesDatabase.cpp | 4 +- source/game/StarStagehandDatabase.cpp | 4 +- source/game/StarStatSet.cpp | 22 +-- source/game/StarStatistics.cpp | 10 +- source/game/StarStatisticsDatabase.cpp | 8 +- source/game/StarStatusController.cpp | 2 +- source/game/StarStatusEffectDatabase.cpp | 4 +- source/game/StarStoredFunctions.cpp | 14 +- source/game/StarSystemWorld.cpp | 2 +- source/game/StarSystemWorldServer.cpp | 8 +- source/game/StarSystemWorldServerThread.cpp | 6 +- source/game/StarTechController.cpp | 2 +- source/game/StarTechDatabase.cpp | 6 +- source/game/StarTenantDatabase.cpp | 8 +- source/game/StarTerrainDatabase.cpp | 8 +- source/game/StarTilesetDatabase.cpp | 2 +- source/game/StarTreasure.cpp | 18 +-- source/game/StarUniverseClient.cpp | 10 +- source/game/StarUniverseConnection.cpp | 14 +- source/game/StarUniverseServer.cpp | 152 +++++++++--------- source/game/StarUniverseSettings.cpp | 6 +- source/game/StarVehicleDatabase.cpp | 6 +- source/game/StarVersioningDatabase.cpp | 22 +-- source/game/StarWarping.cpp | 14 +- source/game/StarWireProcessor.cpp | 2 +- source/game/StarWorldClient.cpp | 12 +- source/game/StarWorldGeneration.cpp | 16 +- source/game/StarWorldLayout.cpp | 22 +-- source/game/StarWorldParameters.cpp | 2 +- source/game/StarWorldServer.cpp | 22 +-- source/game/StarWorldServerThread.cpp | 22 +-- source/game/StarWorldStorage.cpp | 10 +- source/game/StarWorldStructure.cpp | 2 +- source/game/StarWorldTiles.cpp | 2 +- source/game/interfaces/StarBeamItem.cpp | 2 +- source/game/items/StarMaterialItem.cpp | 2 +- source/game/items/StarObjectItem.cpp | 2 +- source/game/items/StarTools.cpp | 6 +- source/game/items/StarUnlockItem.cpp | 2 +- source/game/objects/StarContainerObject.cpp | 2 +- source/game/scripting/StarLuaComponents.cpp | 8 +- source/game/scripting/StarLuaComponents.hpp | 6 +- source/game/scripting/StarLuaRoot.cpp | 6 +- .../game/scripting/StarWorldLuaBindings.cpp | 52 +++--- source/json_tool/editor_gui.cpp | 2 +- source/json_tool/json_tool.cpp | 32 ++-- source/mod_uploader/StarModUploader.cpp | 12 +- source/mod_uploader/main.cpp | 4 +- source/rendering/StarTextPainter.cpp | 2 +- source/rendering/StarTilePainter.cpp | 2 +- source/server/StarServerQueryThread.cpp | 2 +- source/server/StarServerRconClient.cpp | 12 +- source/server/StarServerRconThread.cpp | 2 +- source/server/main.cpp | 2 +- source/test/spawn_test.cpp | 2 +- source/test/string_test.cpp | 4 +- source/utility/asset_packer.cpp | 18 +-- source/utility/asset_unpacker.cpp | 10 +- source/utility/dump_versioned_json.cpp | 4 +- .../utility/dungeon_generation_benchmark.cpp | 14 +- source/utility/fix_embedded_tilesets.cpp | 6 +- source/utility/game_repl.cpp | 4 +- source/utility/generation_benchmark.cpp | 10 +- source/utility/make_versioned_json.cpp | 4 +- source/utility/map_grep.cpp | 6 +- source/utility/planet_mapgen.cpp | 6 +- source/utility/render_terrain_selector.cpp | 4 +- source/utility/tileset_updater.cpp | 18 +-- source/utility/update_tilesets.cpp | 6 +- source/utility/word_count.cpp | 8 +- source/utility/world_benchmark.cpp | 10 +- source/windowing/StarFuelWidget.cpp | 2 +- source/windowing/StarGuiReader.cpp | 6 +- source/windowing/StarGuiTypes.cpp | 2 +- source/windowing/StarItemGridWidget.cpp | 2 +- source/windowing/StarItemSlotWidget.cpp | 6 +- source/windowing/StarKeyBindings.cpp | 8 +- source/windowing/StarListWidget.cpp | 8 +- .../windowing/StarRegisteredPaneManager.hpp | 8 +- source/windowing/StarSliderBar.cpp | 18 +-- source/windowing/StarWidget.cpp | 18 +-- source/windowing/StarWidgetParsing.cpp | 54 +++---- 239 files changed, 1432 insertions(+), 1432 deletions(-) diff --git a/source/application/StarMainApplication_sdl.cpp b/source/application/StarMainApplication_sdl.cpp index 45e224d..8c05508 100644 --- a/source/application/StarMainApplication_sdl.cpp +++ b/source/application/StarMainApplication_sdl.cpp @@ -212,7 +212,7 @@ public: Logger::info("Application: Initializing SDL"); if (SDL_Init(0)) - throw ApplicationException(strf("Couldn't initialize SDL: %s", SDL_GetError())); + throw ApplicationException(strf("Couldn't initialize SDL: {}", SDL_GetError())); if (char* basePath = SDL_GetBasePath()) { File::changeDirectory(basePath); @@ -231,15 +231,15 @@ public: Logger::info("Application: Initializing SDL Video"); if (SDL_InitSubSystem(SDL_INIT_VIDEO)) - throw ApplicationException(strf("Couldn't initialize SDL Video: %s", SDL_GetError())); + throw ApplicationException(strf("Couldn't initialize SDL Video: {}", SDL_GetError())); Logger::info("Application: Initializing SDL Joystick"); if (SDL_InitSubSystem(SDL_INIT_JOYSTICK)) - throw ApplicationException(strf("Couldn't initialize SDL Joystick: %s", SDL_GetError())); + throw ApplicationException(strf("Couldn't initialize SDL Joystick: {}", SDL_GetError())); Logger::info("Application: Initializing SDL Sound"); if (SDL_InitSubSystem(SDL_INIT_AUDIO)) - throw ApplicationException(strf("Couldn't initialize SDL Sound: %s", SDL_GetError())); + throw ApplicationException(strf("Couldn't initialize SDL Sound: {}", SDL_GetError())); SDL_JoystickEventState(SDL_ENABLE); @@ -251,7 +251,7 @@ public: m_sdlWindow = SDL_CreateWindow(m_windowTitle.utf8Ptr(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, m_windowSize[0], m_windowSize[1], SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE); if (!m_sdlWindow) - throw ApplicationException::format("Application: Could not create SDL window: %s", SDL_GetError()); + throw ApplicationException::format("Application: Could not create SDL window: {}", SDL_GetError()); SDL_ShowWindow(m_sdlWindow); SDL_RaiseWindow(m_sdlWindow); @@ -263,7 +263,7 @@ public: m_sdlGlContext = SDL_GL_CreateContext(m_sdlWindow); if (!m_sdlGlContext) - throw ApplicationException::format("Application: Could not create OpenGL context: %s", SDL_GetError()); + throw ApplicationException::format("Application: Could not create OpenGL context: {}", SDL_GetError()); SDL_GL_SwapWindow(m_sdlWindow); setVSyncEnabled(m_windowVSync); @@ -288,7 +288,7 @@ public: SDL_CloseAudioDevice(m_sdlAudioDevice); Logger::error("Application: Could not open 44.1khz / 16 bit stereo audio device, no sound available!"); } else { - Logger::info("Application: Opened default audio device with 44.1khz / 16 bit stereo audio, %s sample size buffer", obtained.samples); + Logger::info("Application: Opened default audio device with 44.1khz / 16 bit stereo audio, {} sample size buffer", obtained.samples); SDL_PauseAudioDevice(m_sdlAudioDevice, 0); } @@ -375,14 +375,14 @@ public: Thread::sleepPrecise(spareMilliseconds); } } catch (std::exception const& e) { - Logger::error("Application: exception thrown, shutting down: %s", outputException(e, true)); + Logger::error("Application: exception thrown, shutting down: {}", outputException(e, true)); } try { Logger::info("Application: shutdown..."); m_application->shutdown(); } catch (std::exception const& e) { - Logger::error("Application: threw exception during shutdown: %s", outputException(e, true)); + Logger::error("Application: threw exception during shutdown: {}", outputException(e, true)); } SDL_CloseAudioDevice(m_sdlAudioDevice); @@ -432,10 +432,10 @@ private: parent->m_windowMode = WindowMode::Fullscreen; SDL_SetWindowFullscreen(parent->m_sdlWindow, SDL_WINDOW_FULLSCREEN); } else { - Logger::warn("Failed to set resolution %s, %s", (unsigned)requestedDisplayMode.w, (unsigned)requestedDisplayMode.h); + Logger::warn("Failed to set resolution {}, {}", (unsigned)requestedDisplayMode.w, (unsigned)requestedDisplayMode.h); } } else { - Logger::warn("Unable to set requested display resolution %s, %s", (int)fullScreenResolution[0], (int)fullScreenResolution[1]); + Logger::warn("Unable to set requested display resolution {}, {}", (int)fullScreenResolution[0], (int)fullScreenResolution[1]); } SDL_DisplayMode actualDisplayMode; diff --git a/source/application/StarP2PNetworkingService_pc.cpp b/source/application/StarP2PNetworkingService_pc.cpp index 2a0b876..74c48ac 100644 --- a/source/application/StarP2PNetworkingService_pc.cpp +++ b/source/application/StarP2PNetworkingService_pc.cpp @@ -32,13 +32,13 @@ PcP2PNetworkingService::PcP2PNetworkingService(PcPlatformServicesStatePtr state) m_discordOnActivityJoinToken = m_state->discordCore->ActivityManager().OnActivityJoin.Connect([this](char const* peerId) { MutexLocker serviceLocker(m_mutex); - Logger::info("Joining discord peer at '%s'", peerId); - addPendingJoin(strf("+platform:%s", peerId)); + Logger::info("Joining discord peer at '{}'", peerId); + addPendingJoin(strf("+platform:{}", peerId)); }); m_discordOnActivityRequestToken = m_state->discordCore->ActivityManager().OnActivityJoinRequest.Connect([this](discord::User const& user) { MutexLocker serviceLocker(m_mutex); String userName = String(user.GetUsername()); - Logger::info("Received join request from user '%s'", userName); + Logger::info("Received join request from user '{}'", userName); m_discordJoinRequests.emplace_back(make_pair(user.GetId(), userName)); }); m_discordOnReceiveMessage = m_state->discordCore->LobbyManager().OnNetworkMessage.Connect(bind(&PcP2PNetworkingService::discordOnReceiveMessage, this, _1, _2, _3, _4, _5)); @@ -54,9 +54,9 @@ PcP2PNetworkingService::~PcP2PNetworkingService() { if (m_state->discordAvailable) { MutexLocker discordLocker(m_state->discordMutex); if (m_discordServerLobby) { - Logger::info("Deleting discord server lobby %s", m_discordServerLobby->first); + Logger::info("Deleting discord server lobby {}", m_discordServerLobby->first); m_state->discordCore->LobbyManager().DeleteLobby(m_discordServerLobby->first, [](discord::Result res) { - Logger::error("Could not connect delete server lobby (err %s)", (int)res); + Logger::error("Could not connect delete server lobby (err {})", (int)res); }); } @@ -108,18 +108,18 @@ void Star::PcP2PNetworkingService::setActivityData(String const& title, Maybefirst).c_str()); + activity.GetParty().SetId(strf("{}", lobby->first).c_str()); if (m_joinLocation.is()) { if (auto lobby = m_discordServerLobby) { - String joinSecret = strf("connect:discord_%s_%s_%s", m_state->discordCurrentUser->GetId(), lobby->first, lobby->second); - Logger::info("Setting discord join secret as %s", joinSecret); + String joinSecret = strf("connect:discord_{}_{}_{}", m_state->discordCurrentUser->GetId(), lobby->first, lobby->second); + Logger::info("Setting discord join secret as {}", joinSecret); activity.GetSecrets().SetJoin(joinSecret.utf8Ptr()); } } else if (m_joinLocation.is()) { - String address = strf("%s", (HostAddressWithPort)m_joinLocation.get()); - String joinSecret = strf("connect:address_%s", address); - Logger::info("Setting discord join secret as %s", joinSecret); + String address = strf("{}", (HostAddressWithPort)m_joinLocation.get()); + String joinSecret = strf("connect:address_{}", address); + Logger::info("Setting discord join secret as {}", joinSecret); activity.GetSecrets().SetJoin(joinSecret.utf8Ptr()); activity.GetParty().SetId(address.utf8Ptr()); @@ -128,7 +128,7 @@ void Star::PcP2PNetworkingService::setActivityData(String const& title, MaybediscordCore->ActivityManager().UpdateActivity(activity, [this](discord::Result res) { if (res != discord::Result::Ok) - Logger::error("failed to set discord activity (err %s)", (int)res); + Logger::error("failed to set discord activity (err {})", (int)res); MutexLocker serviceLocker(m_mutex); m_discordUpdatingActivity = false; @@ -193,7 +193,7 @@ void Star::PcP2PNetworkingService::update() { m_state->discordCore->ActivityManager().SendRequestReply(p.first, reply, [](discord::Result res) { if (res != discord::Result::Ok) - Logger::error("Could not send discord activity join response (err %s)", (int)res); + Logger::error("Could not send discord activity join response (err {})", (int)res); }); } } @@ -230,17 +230,17 @@ Either PcP2PNetworkingService::connectToPeer(P2PNetworkin } #endif - return makeLeft(strf("Unsupported peer type '%s'", type)); + return makeLeft(strf("Unsupported peer type '{}'", type)); } void PcP2PNetworkingService::addPendingJoin(String connectionString) { MutexLocker serviceLocker(m_mutex); if (connectionString.extract(":") != "+platform") - throw ApplicationException::format("malformed connection string '%s'", connectionString); + throw ApplicationException::format("malformed connection string '{}'", connectionString); if (connectionString.extract(":") != "connect") - throw ApplicationException::format("malformed connection string '%s'", connectionString); + throw ApplicationException::format("malformed connection string '{}'", connectionString); String target = move(connectionString); String targetType = target.extract("_"); @@ -248,7 +248,7 @@ void PcP2PNetworkingService::addPendingJoin(String connectionString) { if (targetType == "address") m_pendingJoin = HostAddressWithPort(target); else - m_pendingJoin = P2PNetworkingPeerId(strf("%s_%s", targetType, target)); + m_pendingJoin = P2PNetworkingPeerId(strf("{}_{}", targetType, target)); } #ifdef STAR_ENABLE_STEAM_INTEGRATION @@ -312,7 +312,7 @@ auto PcP2PNetworkingService::createSteamP2PSocket(CSteamID steamId) -> unique_pt void PcP2PNetworkingService::steamOnConnectionFailure(P2PSessionConnectFail_t* callback) { MutexLocker serviceLocker(m_mutex); - Logger::warn("Connection with steam user %s failed", callback->m_steamIDRemote.ConvertToUint64()); + Logger::warn("Connection with steam user {} failed", callback->m_steamIDRemote.ConvertToUint64()); if (auto socket = m_steamOpenSockets.value(callback->m_steamIDRemote.ConvertToUint64())) { MutexLocker socketLocker(socket->mutex); steamCloseSocket(socket); @@ -320,7 +320,7 @@ void PcP2PNetworkingService::steamOnConnectionFailure(P2PSessionConnectFail_t* c } void PcP2PNetworkingService::steamOnJoinRequested(GameRichPresenceJoinRequested_t* callback) { - Logger::info("Queueing join request with steam friend id %s to address %s", callback->m_steamIDFriend.ConvertToUint64(), callback->m_rgchConnect); + Logger::info("Queueing join request with steam friend id {} to address {}", callback->m_steamIDFriend.ConvertToUint64(), callback->m_rgchConnect); addPendingJoin(callback->m_rgchConnect); } @@ -330,19 +330,19 @@ void PcP2PNetworkingService::steamOnSessionRequest(P2PSessionRequest_t* callback // non-friends can even initiate P2P sessions. if (m_acceptingP2PConnections && SteamFriends()->HasFriend(callback->m_steamIDRemote, k_EFriendFlagImmediate)) { if (SteamNetworking()->AcceptP2PSessionWithUser(callback->m_steamIDRemote)) { - Logger::info("Accepted steam p2p connection with user %s", callback->m_steamIDRemote.ConvertToUint64()); + Logger::info("Accepted steam p2p connection with user {}", callback->m_steamIDRemote.ConvertToUint64()); m_pendingIncomingConnections.append(createSteamP2PSocket(callback->m_steamIDRemote)); } else { - Logger::error("Accepting steam p2p connection from user %s failed!", callback->m_steamIDRemote.ConvertToUint64()); + Logger::error("Accepting steam p2p connection from user {} failed!", callback->m_steamIDRemote.ConvertToUint64()); } } else { - Logger::error("Ignoring steam p2p connection from user %s", callback->m_steamIDRemote.ConvertToUint64()); + Logger::error("Ignoring steam p2p connection from user {}", callback->m_steamIDRemote.ConvertToUint64()); } } void PcP2PNetworkingService::steamCloseSocket(SteamP2PSocket* socket) { if (socket->connected) { - Logger::info("Closing p2p connection with steam user %s", socket->steamId.ConvertToUint64()); + Logger::info("Closing p2p connection with steam user {}", socket->steamId.ConvertToUint64()); m_steamOpenSockets.remove(socket->steamId.ConvertToUint64()); socket->connected = false; } @@ -386,7 +386,7 @@ bool PcP2PNetworkingService::DiscordP2PSocket::sendMessage(ByteArray const& mess discord::Result res = parent->m_state->discordCore->LobbyManager().SendNetworkMessage(lobbyId, remoteUserId, DiscordMainNetworkChannel, (uint8_t*)message.ptr(), message.size()); if (res != discord::Result::Ok) - throw ApplicationException::format("discord::Network::Send returned error (err %s)", (int)res); + throw ApplicationException::format("discord::Network::Send returned error (err {})", (int)res); return true; } @@ -407,13 +407,13 @@ void PcP2PNetworkingService::discordCloseSocket(DiscordP2PSocket* socket) { if (!m_joinLocation.is() && m_discordOpenSockets.empty()) { auto res = m_state->discordCore->LobbyManager().DisconnectNetwork(socket->lobbyId); if (res != discord::Result::Ok) - Logger::error("failed to leave network for lobby %s (err %s)", socket->lobbyId, (int)res); + Logger::error("failed to leave network for lobby {} (err {})", socket->lobbyId, (int)res); m_state->discordCore->LobbyManager().DisconnectLobby(socket->lobbyId, [this, lobbyId = socket->lobbyId](discord::Result res) { if (res != discord::Result::Ok) - Logger::error("failed to leave discord lobby %s", lobbyId); + Logger::error("failed to leave discord lobby {}", lobbyId); - Logger::info("Left discord lobby %s", lobbyId); + Logger::info("Left discord lobby {}", lobbyId); MutexLocker serviceLocker(m_mutex); m_discordServerLobby = {}; m_discordForceUpdateActivity = true; @@ -438,7 +438,7 @@ P2PSocketUPtr PcP2PNetworkingService::discordConnectRemote(discord::UserId remot socket->lobbyId = lobbyId; m_discordOpenSockets[remoteUserId] = socket.get(); - Logger::info("Connect to discord lobby %s", lobbyId); + Logger::info("Connect to discord lobby {}", lobbyId); m_state->discordCore->LobbyManager().ConnectLobby(lobbyId, lobbySecret.utf8Ptr(), [this, remoteUserId, lobbyId](discord::Result res, discord::Lobby const& lobby) { MutexLocker serviceLocker(m_mutex); if (res == discord::Result::Ok) { @@ -448,25 +448,25 @@ P2PSocketUPtr PcP2PNetworkingService::discordConnectRemote(discord::UserId remot res = m_state->discordCore->LobbyManager().ConnectNetwork(lobbyId); if (res != discord::Result::Ok) { discordCloseSocket(socket); - return Logger::error("Could not connect to discord lobby network (err %s)", (int)res); + return Logger::error("Could not connect to discord lobby network (err {})", (int)res); } res = m_state->discordCore->LobbyManager().OpenNetworkChannel(lobbyId, DiscordMainNetworkChannel, true); if (res != discord::Result::Ok) { discordCloseSocket(socket); - return Logger::error("Could not open discord main network channel (err %s)", (int)res); + return Logger::error("Could not open discord main network channel (err {})", (int)res); } socket->mode = DiscordSocketMode::Connected; - Logger::info("Discord p2p connection opened to remote user %s via lobby %s", remoteUserId, lobbyId); + Logger::info("Discord p2p connection opened to remote user {} via lobby {}", remoteUserId, lobbyId); m_discordServerLobby = make_pair(lobbyId, String()); m_discordForceUpdateActivity = true; } else { - Logger::error("discord::Lobbies::Connect callback no matching remoteUserId %s found", remoteUserId); + Logger::error("discord::Lobbies::Connect callback no matching remoteUserId {} found", remoteUserId); } } else { - Logger::error("failed to connect to remote lobby (err %s)", (int)res); + Logger::error("failed to connect to remote lobby (err {})", (int)res); if (auto socket = m_discordOpenSockets.value(remoteUserId)) { MutexLocker socketLocker(socket->mutex); discordCloseSocket(socket); @@ -481,17 +481,17 @@ void PcP2PNetworkingService::discordOnReceiveMessage(discord::LobbyId lobbyId, d MutexLocker serviceLocker(m_mutex); if (lobbyId != m_discordServerLobby->first) - return Logger::error("Received message from unexpected lobby %s", lobbyId); + return Logger::error("Received message from unexpected lobby {}", lobbyId); if (auto socket = m_discordOpenSockets.value(userId)) { if (channel == DiscordMainNetworkChannel) { MutexLocker socketLocker(socket->mutex); socket->incoming.append(ByteArray((char const*)data, size)); } else { - Logger::error("Received discord message on unexpected channel %s, ignoring", channel); + Logger::error("Received discord message on unexpected channel {}, ignoring", channel); } } else { - Logger::error("Could not find associated discord socket for user id %s", userId); + Logger::error("Could not find associated discord socket for user id {}", userId); } } @@ -508,7 +508,7 @@ void PcP2PNetworkingService::discordOnLobbyMemberConnect(discord::LobbyId lobbyI m_discordOpenSockets[userId] = socket.get(); m_pendingIncomingConnections.append(move(socket)); - Logger::info("Accepted new discord connection from remote user %s", userId); + Logger::info("Accepted new discord connection from remote user {}", userId); } } } @@ -548,13 +548,13 @@ void PcP2PNetworkingService::setJoinLocation(JoinLocation location) { } else if (m_joinLocation.is()) { auto steamId = SteamUser()->GetSteamID().ConvertToUint64(); - Logger::info("Setting steam rich presence connection as steamid_%s", steamId); - SteamFriends()->SetRichPresence("connect", strf("+platform:connect:steamid_%s", steamId).c_str()); + Logger::info("Setting steam rich presence connection as steamid_{}", steamId); + SteamFriends()->SetRichPresence("connect", strf("+platform:connect:steamid_{}", steamId).c_str()); } else if (m_joinLocation.is()) { auto address = (HostAddressWithPort)location.get(); - Logger::info("Setting steam rich presence connection as address_%s", address); - SteamFriends()->SetRichPresence("connect", strf("+platform:connect:address_%s", address).c_str()); + Logger::info("Setting steam rich presence connection as address_{}", address); + SteamFriends()->SetRichPresence("connect", strf("+platform:connect:address_{}", address).c_str()); } } #endif @@ -562,9 +562,9 @@ void PcP2PNetworkingService::setJoinLocation(JoinLocation location) { #ifdef STAR_ENABLE_DISCORD_INTEGRATION if (m_state->discordAvailable && m_state->discordCurrentUser) { if (m_discordServerLobby) { - Logger::info("Deleting discord server lobby %s", m_discordServerLobby->first); + Logger::info("Deleting discord server lobby {}", m_discordServerLobby->first); m_state->discordCore->LobbyManager().DeleteLobby(m_discordServerLobby->first, [](discord::Result res) { - Logger::error("Could not connect delete server lobby (err %s)", (int)res); + Logger::error("Could not connect delete server lobby (err {})", (int)res); }); } @@ -591,21 +591,21 @@ void PcP2PNetworkingService::setJoinLocation(JoinLocation location) { // successfully joined lobby network return; } else { - Logger::error("Failed to open discord main network channel (err %s)", (int)res); + Logger::error("Failed to open discord main network channel (err {})", (int)res); } } else { - Logger::error("Failed to join discord lobby network (err %s)", (int)res); + Logger::error("Failed to join discord lobby network (err {})", (int)res); } // Created lobby but failed to join the lobby network, delete lobby - Logger::error("Failed to join discord lobby network (err %s)", (int)res); + Logger::error("Failed to join discord lobby network (err {})", (int)res); - Logger::info("Deleting discord lobby %s", lobbyId); + Logger::info("Deleting discord lobby {}", lobbyId); m_state->discordCore->LobbyManager().DeleteLobby(lobbyId, [lobbyId](discord::Result res) { - Logger::error("failed to delete lobby %s (err %s)", lobbyId, (int)res); + Logger::error("failed to delete lobby {} (err {})", lobbyId, (int)res); }); } else { - Logger::error("failed to create discord lobby (err %s)", (int)res); + Logger::error("failed to create discord lobby (err {})", (int)res); } }); } diff --git a/source/application/StarPlatformServices_pc.cpp b/source/application/StarPlatformServices_pc.cpp index 7e528f0..7023129 100644 --- a/source/application/StarPlatformServices_pc.cpp +++ b/source/application/StarPlatformServices_pc.cpp @@ -43,26 +43,26 @@ PcPlatformServicesState::PcPlatformServicesState() discord::User user; auto res = discordCore->UserManager().GetCurrentUser(&user); if (res != discord::Result::Ok) - Logger::error("Could not get current discord user. (err %s)", (int)res); + Logger::error("Could not get current discord user. (err {})", (int)res); else discordCurrentUser = user; }); } else { - Logger::error("Failed to instantiate discord core (err %s)", (int)res); + Logger::error("Failed to instantiate discord core (err {})", (int)res); } if (discordAvailable) { MutexLocker locker(discordMutex); discordCore->SetLogHook(discord::LogLevel::Info, [](discord::LogLevel level, char const* msg) { if (level == discord::LogLevel::Debug) - Logger::debug("[DISCORD]: %s", msg); + Logger::debug("[DISCORD]: {}", msg); else if (level == discord::LogLevel::Error) - Logger::debug("[DISCORD]: %s", msg); + Logger::debug("[DISCORD]: {}", msg); else if (level == discord::LogLevel::Info) - Logger::info("[DISCORD]: %s", msg); + Logger::info("[DISCORD]: {}", msg); else if (level == discord::LogLevel::Warn) - Logger::warn("[DISCORD]: %s", msg); + Logger::warn("[DISCORD]: {}", msg); }); discordEventShutdown = false; discordEventThread = Thread::invoke("PcPlatformServices::discordEventThread", [this]() { @@ -117,10 +117,10 @@ PcPlatformServicesUPtr PcPlatformServices::create(String const& path, StringList auto p2pNetworkingService = make_shared(services->m_state); for (auto& argument : platformArguments) { if (argument.beginsWith("+platform:connect:")) { - Logger::info("PC platform services joining from command line argument '%s'", argument); + Logger::info("PC platform services joining from command line argument '{}'", argument); p2pNetworkingService->addPendingJoin(move(argument)); } else { - throw ApplicationException::format("Unrecognized PC platform services command line argument '%s'", argument); + throw ApplicationException::format("Unrecognized PC platform services command line argument '{}'", argument); } } @@ -138,7 +138,7 @@ PcPlatformServicesUPtr PcPlatformServices::create(String const& path, StringList #ifdef STAR_ENABLE_DISCORD_INTEGRATION MutexLocker discordLocker(services->m_state->discordMutex); if (services->m_state->discordAvailable) { - Logger::debug("Registering starbound to discord at path: %s", path); + Logger::debug("Registering starbound to discord at path: {}", path); services->m_state->discordCore->ActivityManager().RegisterCommand(path.utf8Ptr()); } #endif diff --git a/source/application/StarRenderer_opengl20.cpp b/source/application/StarRenderer_opengl20.cpp index e80d745..82d4845 100644 --- a/source/application/StarRenderer_opengl20.cpp +++ b/source/application/StarRenderer_opengl20.cpp @@ -76,7 +76,7 @@ OpenGl20Renderer::OpenGl20Renderer() { if (!GLEW_VERSION_2_0) throw RendererException("OpenGL 2.0 not available!"); - Logger::info("OpenGL version: '%s' vendor: '%s' renderer: '%s' shader: '%s'", + Logger::info("OpenGL version: '{}' vendor: '{}' renderer: '{}' shader: '{}'", (const char*)glGetString(GL_VERSION), (const char*)glGetString(GL_VENDOR), (const char*)glGetString(GL_RENDERER), @@ -132,7 +132,7 @@ void OpenGl20Renderer::setEffectConfig(Json const& effectConfig, StringMap(); } else { - throw RendererException::format("Unrecognized effect parameter type '%s'", type); + throw RendererException::format("Unrecognized effect parameter type '{}'", type); } m_effectParameters[p.first] = effectParameter; @@ -243,7 +243,7 @@ void OpenGl20Renderer::setEffectConfig(Json const& effectConfig, StringMaputf8Ptr()); if (effectTexture.textureSizeUniform == -1) - Logger::warn("OpenGL20 effect parameter '%s' has textureSizeUniform '%s' with no associated uniform", p.first, *tsu); + Logger::warn("OpenGL20 effect parameter '{}' has textureSizeUniform '{}' with no associated uniform", p.first, *tsu); } m_effectTextures[p.first] = effectTexture; @@ -270,7 +270,7 @@ void OpenGl20Renderer::setEffectParameter(String const& parameterName, RenderEff return; if (ptr->parameterType != value.typeIndex()) - throw RendererException::format("OpenGL20Renderer::setEffectParameter '%s' parameter type mismatch", parameterName); + throw RendererException::format("OpenGL20Renderer::setEffectParameter '{}' parameter type mismatch", parameterName); flushImmediatePrimitives(); @@ -354,7 +354,7 @@ TextureGroupPtr OpenGl20Renderer::createTextureGroup(TextureGroupSize textureSiz else // TextureGroupSize::Small atlasNumCells = 64; - Logger::info("detected supported OpenGL texture size %s, using atlasNumCells %s", maxTextureSize, atlasNumCells); + Logger::info("detected supported OpenGL texture size {}, using atlasNumCells {}", maxTextureSize, atlasNumCells); auto glTextureGroup = make_shared(atlasNumCells); glTextureGroup->textureAtlasSet.textureFiltering = filtering; diff --git a/source/application/StarStatisticsService_pc_steam.cpp b/source/application/StarStatisticsService_pc_steam.cpp index 89239fd..bf74b7f 100644 --- a/source/application/StarStatisticsService_pc_steam.cpp +++ b/source/application/StarStatisticsService_pc_steam.cpp @@ -52,7 +52,7 @@ bool SteamStatisticsService::reportEvent(String const&, Json const&) { bool SteamStatisticsService::unlockAchievement(String const& name) { if (!SteamUserStats()->SetAchievement(name.utf8Ptr())) { - Logger::error("Cannot set Steam achievement %s", name); + Logger::error("Cannot set Steam achievement {}", name); return false; } return true; @@ -94,7 +94,7 @@ void SteamStatisticsService::onUserStatsReceived(UserStatsReceived_t* callback) return; if (callback->m_eResult != k_EResultOK) { - m_error = {strf("Steam RequestCurrentStats failed with code %d", (int)callback->m_eResult)}; + m_error = {strf("Steam RequestCurrentStats failed with code {}", (int)callback->m_eResult)}; return; } @@ -117,14 +117,14 @@ void SteamStatisticsService::onUserStatsStored(UserStatsStored_t* callback) { return; } - m_error = {strf("Steam StoreStats failed with code %d", (int)callback->m_eResult)}; + m_error = {strf("Steam StoreStats failed with code {}", (int)callback->m_eResult)}; } void SteamStatisticsService::onAchievementStored(UserAchievementStored_t* callback) { if (callback->m_nGameID != m_appId) return; - Logger::debug("Steam achievement %s stored successfully", callback->m_rgchAchievementName); + Logger::debug("Steam achievement {} stored successfully", callback->m_rgchAchievementName); } } diff --git a/source/base/StarAnimatedPartSet.cpp b/source/base/StarAnimatedPartSet.cpp index 62bf786..3f5d72a 100644 --- a/source/base/StarAnimatedPartSet.cpp +++ b/source/base/StarAnimatedPartSet.cpp @@ -231,7 +231,7 @@ AnimatedPartSet::AnimationMode AnimatedPartSet::stringToAnimationMode(String con } else if (string.equals("transition", String::CaseInsensitive)) { return Transition; } else { - throw AnimatedPartSetException(strf("No such AnimationMode '%s'", string)); + throw AnimatedPartSetException(strf("No such AnimationMode '{}'", string)); } } diff --git a/source/base/StarAssets.cpp b/source/base/StarAssets.cpp index a24000d..ce80136 100644 --- a/source/base/StarAssets.cpp +++ b/source/base/StarAssets.cpp @@ -22,7 +22,7 @@ namespace Star { static void validatePath(AssetPath const& components, bool canContainSubPath, bool canContainDirectives) { if (components.basePath.empty() || components.basePath[0] != '/') - throw AssetException(strf("Path '%s' must be absolute", components.basePath)); + throw AssetException(strf("Path '{}' must be absolute", components.basePath)); bool first = true; bool slashed = true; @@ -31,19 +31,19 @@ static void validatePath(AssetPath const& components, bool canContainSubPath, bo if (c == '/') { if (!first) { if (slashed) - throw AssetException(strf("Path '%s' contains consecutive //, not allowed", components.basePath)); + throw AssetException(strf("Path '{}' contains consecutive //, not allowed", components.basePath)); else if (dotted) - throw AssetException(strf("Path '%s' '.' and '..' not allowed", components.basePath)); + throw AssetException(strf("Path '{}' '.' and '..' not allowed", components.basePath)); } slashed = true; dotted = false; } else if (c == ':') { if (slashed) - throw AssetException(strf("Path '%s' has ':' after directory", components.basePath)); + throw AssetException(strf("Path '{}' has ':' after directory", components.basePath)); break; } else if (c == '?') { if (slashed) - throw AssetException(strf("Path '%s' has '?' after directory", components.basePath)); + throw AssetException(strf("Path '{}' has '?' after directory", components.basePath)); break; } else { slashed = false; @@ -52,12 +52,12 @@ static void validatePath(AssetPath const& components, bool canContainSubPath, bo first = false; } if (slashed) - throw AssetException(strf("Path '%s' cannot be a file", components.basePath)); + throw AssetException(strf("Path '{}' cannot be a file", components.basePath)); if (!canContainSubPath && components.subPath) - throw AssetException::format("Path '%s' cannot contain sub-path", components); + throw AssetException::format("Path '{}' cannot contain sub-path", components); if (!canContainDirectives && !components.directives.empty()) - throw AssetException::format("Path '%s' cannot contain directives", components); + throw AssetException::format("Path '{}' cannot contain directives", components); } Maybe FramesSpecification::getRect(String const& frame) const { @@ -76,7 +76,7 @@ Assets::Assets(Settings settings, StringList assetSources) { m_assetSources = move(assetSources); for (auto& sourcePath : m_assetSources) { - Logger::info("Loading assets from: '%s'", sourcePath); + Logger::info("Loading assets from: '{}'", sourcePath); AssetSourcePtr source; if (File::isDirectory(sourcePath)) source = make_shared(sourcePath, m_settings.pathIgnore); @@ -168,7 +168,7 @@ String Assets::assetSource(String const& path) const { MutexLocker assetsLocker(m_assetsMutex); if (auto p = m_files.ptr(path)) return m_assetSourcePaths.getLeft(p->source); - throw AssetException(strf("No such asset '%s'", path)); + throw AssetException(strf("No such asset '{}'", path)); } StringList Assets::scan(String const& suffix) const { @@ -384,7 +384,7 @@ FramesSpecification Assets::parseFramesSpecification(Json const& frameConfig, St RectU rect = RectU(jsonToRectI(pair.second)); if (rect.isEmpty()) throw AssetException( - strf("Empty rect in frame specification in image %s frame %s", framesSpecification.framesFile, frameName)); + strf("Empty rect in frame specification in image {} frame {}", framesSpecification.framesFile, frameName)); else framesSpecification.frames[frameName] = rect; } @@ -398,13 +398,13 @@ FramesSpecification Assets::parseFramesSpecification(Json const& frameConfig, St Vec2U dimensions(jsonToVec2I(grid.get("dimensions"))); if (dimensions[0] == 0 || dimensions[1] == 0) - throw AssetException(strf("Image %s \"dimensions\" in frameGrid cannot be zero", framesSpecification.framesFile)); + throw AssetException(strf("Image {} \"dimensions\" in frameGrid cannot be zero", framesSpecification.framesFile)); if (grid.contains("names")) { auto nameList = grid.get("names"); for (size_t y = 0; y < nameList.size(); ++y) { if (y >= dimensions[1]) - throw AssetException(strf("Image %s row %s is out of bounds for y-dimension %s", + throw AssetException(strf("Image {} row {} is out of bounds for y-dimension {}", framesSpecification.framesFile, y + 1, dimensions[1])); @@ -413,7 +413,7 @@ FramesSpecification Assets::parseFramesSpecification(Json const& frameConfig, St continue; for (unsigned x = 0; x < rowList.size(); ++x) { if (x >= dimensions[0]) - throw AssetException(strf("Image %s column %s is out of bounds for x-dimension %s", + throw AssetException(strf("Image {} column {} is out of bounds for x-dimension {}", framesSpecification.framesFile, x + 1, dimensions[0])); @@ -431,7 +431,7 @@ FramesSpecification Assets::parseFramesSpecification(Json const& frameConfig, St // If "names" not specified, use auto naming algorithm for (size_t y = 0; y < dimensions[1]; ++y) for (size_t x = 0; x < dimensions[0]; ++x) - framesSpecification.frames[strf("%s", y * dimensions[0] + x)] = + framesSpecification.frames[strf("{}", y * dimensions[0] + x)] = RectU::withSize(Vec2U(begin[0] + x * size[0], begin[1] + y * size[1]), size); } } @@ -449,7 +449,7 @@ FramesSpecification Assets::parseFramesSpecification(Json const& frameConfig, St auto it = aliases->find(value); if (it != aliases->end()) { if (i == aliases->size()) - throw AssetException(strf("Infinite alias loop detected for alias '%s'", key)); + throw AssetException(strf("Infinite alias loop detected for alias '{}'", key)); value = it->second.toString(); } else { @@ -458,7 +458,7 @@ FramesSpecification Assets::parseFramesSpecification(Json const& frameConfig, St } if (!framesSpecification.frames.contains(value)) - throw AssetException(strf("No such frame '%s' found for alias '%s'", value, key)); + throw AssetException(strf("No such frame '{}' found for alias '{}'", value, key)); framesSpecification.aliases[key] = move(value); } } @@ -493,7 +493,7 @@ shared_ptr Assets::tryAsset(AssetId const& id) const { freshen(i->second); return i->second; } else { - throw AssetException::format("Error loading asset %s", id.path); + throw AssetException::format("Error loading asset {}", id.path); } } else { auto j = m_queue.find(id); @@ -516,7 +516,7 @@ shared_ptr Assets::getAsset(AssetId const& id) const { freshen(asset); return asset; } else { - throw AssetException::format("Error loading asset %s", id.path); + throw AssetException::format("Error loading asset {}", id.path); } } else { // Try to load the asset in-thread, if we cannot, then the asset has been @@ -648,13 +648,13 @@ FramesSpecificationConstPtr Assets::bestFramesSpecification(String const& image) IODevicePtr Assets::open(String const& path) const { if (auto p = m_files.ptr(path)) return p->source->open(p->sourceName); - throw AssetException(strf("No such asset '%s'", path)); + throw AssetException(strf("No such asset '{}'", path)); } ByteArray Assets::read(String const& path) const { if (auto p = m_files.ptr(path)) return p->source->read(p->sourceName); - throw AssetException(strf("No such asset '%s'", path)); + throw AssetException(strf("No such asset '{}'", path)); } Json Assets::readJson(String const& path) const { @@ -673,21 +673,21 @@ Json Assets::readJson(String const& path) const { try { result = jsonPatch(result, patch.toArray()); } catch (JsonPatchTestFail const& e) { - Logger::debug("Patch test failure from file %s in source: %s. Caused by: %s", pair.first, m_assetSourcePaths.getLeft(pair.second), e.what()); + Logger::debug("Patch test failure from file {} in source: {}. Caused by: {}", pair.first, m_assetSourcePaths.getLeft(pair.second), e.what()); } } } else if (patchData.at(0).type() == Json::Type::Object) { try { result = jsonPatch(result, patchData); } catch (JsonPatchTestFail const& e) { - Logger::debug("Patch test failure from file %s in source: %s. Caused by: %s", pair.first, m_assetSourcePaths.getLeft(pair.second), e.what()); + Logger::debug("Patch test failure from file {} in source: {}. Caused by: {}", pair.first, m_assetSourcePaths.getLeft(pair.second), e.what()); } } else { - throw JsonPatchException(strf("Patch data is wrong type: %s", Json::typeName(patchData.at(0).type()))); + throw JsonPatchException(strf("Patch data is wrong type: {}", Json::typeName(patchData.at(0).type()))); } } } catch (JsonPatchException const& e) { - Logger::error("Could not apply patch from file %s in source: %s. Caused by: %s", pair.first, m_assetSourcePaths.getLeft(pair.second), e.what()); + Logger::error("Could not apply patch from file {} in source: {}. Caused by: {}", pair.first, m_assetSourcePaths.getLeft(pair.second), e.what()); } } else if (patchJson.isType(Json::Type::Object)) { //Kae: Do a good ol' json merge instead if the .patch file is a Json object @@ -697,7 +697,7 @@ Json Assets::readJson(String const& path) const { } return result; } catch (std::exception const& e) { - throw JsonParsingException(strf("Cannot parse json file: %s", path), e); + throw JsonParsingException(strf("Cannot parse json file: {}", path), e); } } @@ -707,9 +707,9 @@ bool Assets::doLoad(AssetId const& id) const { // data. return (bool)loadAsset(id); } catch (std::exception const& e) { - Logger::error("Exception caught loading asset: %s, %s", id.path, outputException(e, true)); + Logger::error("Exception caught loading asset: {}, {}", id.path, outputException(e, true)); } catch (...) { - Logger::error("Unknown exception caught loading asset: %s", id.path); + Logger::error("Unknown exception caught loading asset: {}", id.path); } // There was an exception, remove the asset from the queue and fill the cache @@ -727,9 +727,9 @@ bool Assets::doPost(AssetId const& id) const { if (id.type == AssetType::Audio) assetData = postProcessAudio(assetData); } catch (std::exception const& e) { - Logger::error("Exception caught post-processing asset: %s, %s", id.path, outputException(e, true)); + Logger::error("Exception caught post-processing asset: {}, {}", id.path, outputException(e, true)); } catch (...) { - Logger::error("Unknown exception caught post-processing asset: %s", id.path); + Logger::error("Unknown exception caught post-processing asset: {}", id.path); } m_queue.remove(id); @@ -769,10 +769,10 @@ shared_ptr Assets::loadAsset(AssetId const& id) const { } catch (StarException const& e) { if (id.type == AssetType::Image && m_settings.missingImage) { - Logger::error("Could not load image asset '%s', using placeholder default.\n%s", id.path, outputException(e, false)); + Logger::error("Could not load image asset '{}', using placeholder default.\n{}", id.path, outputException(e, false)); assetData = loadImage({*m_settings.missingImage, {}, {}}); } else if (id.type == AssetType::Audio && m_settings.missingAudio) { - Logger::error("Could not load audio asset '%s', using placeholder default.\n%s", id.path, outputException(e, false)); + Logger::error("Could not load audio asset '{}', using placeholder default.\n{}", id.path, outputException(e, false)); assetData = loadAudio({*m_settings.missingAudio, {}, {}}); } else { throw; @@ -821,7 +821,7 @@ shared_ptr Assets::loadJson(AssetPath const& path) const { newData->json = topJson->json.query(*path.subPath); return newData; } catch (StarException const& e) { - throw AssetException(strf("Could not read JSON value %s", path), e); + throw AssetException(strf("Could not read JSON value {}", path), e); } } else { return unlockDuring([&]() { @@ -830,7 +830,7 @@ shared_ptr Assets::loadJson(AssetPath const& path) const { newData->json = readJson(path.basePath); return newData; } catch (StarException const& e) { - throw AssetException(strf("Could not read JSON asset %s", path), e); + throw AssetException(strf("Could not read JSON asset {}", path), e); } }); } @@ -882,7 +882,7 @@ shared_ptr Assets::loadImage(AssetPath const& path) const { // Base image must have frames data associated with it. if (!imageData->frames) - throw AssetException::format("No associated frames file found for image '%s' while resolving image frame '%s'", path.basePath, path); + throw AssetException::format("No associated frames file found for image '{}' while resolving image frame '{}'", path.basePath, path); if (auto alias = imageData->frames->aliases.ptr(*path.subPath)) { imageData = as(loadAsset(AssetId{AssetType::Image, {path.basePath, *alias, path.directives}})); @@ -897,7 +897,7 @@ shared_ptr Assets::loadImage(AssetPath const& path) const { } else { auto frameRect = imageData->frames->frames.ptr(*path.subPath); if (!frameRect) - throw AssetException(strf("No such frame %s in frames spec %s", *path.subPath, imageData->frames->framesFile)); + throw AssetException(strf("No such frame {} in frames spec {}", *path.subPath, imageData->frames->framesFile)); return unlockDuring([&]() { // Need to flip frame coordinates because frame configs assume top diff --git a/source/base/StarDirectoryAssetSource.cpp b/source/base/StarDirectoryAssetSource.cpp index bd8c760..675c64c 100644 --- a/source/base/StarDirectoryAssetSource.cpp +++ b/source/base/StarDirectoryAssetSource.cpp @@ -17,7 +17,7 @@ DirectoryAssetSource::DirectoryAssetSource(String const& baseDirectory, StringLi m_metadata = Json::parseJson(File::readFileString(metadataFile)).toObject(); break; } catch (JsonException const& e) { - throw AssetSourceException(strf("Could not load metadata file '%s' from assets", metadataFile), e); + throw AssetSourceException(strf("Could not load metadata file '{}' from assets", metadataFile), e); } } } @@ -52,7 +52,7 @@ ByteArray DirectoryAssetSource::read(String const& path) { String DirectoryAssetSource::toFilesystem(String const& path) const { if (!path.beginsWith("/")) - throw AssetSourceException::format("Asset path '%s' must be absolute in DirectoryAssetSource::toFilesystem", path); + throw AssetSourceException::format("Asset path '{}' must be absolute in DirectoryAssetSource::toFilesystem", path); else return File::relativeTo(m_baseDirectory, File::convertDirSeparators(path.substr(1))); } diff --git a/source/base/StarPackedAssetSource.cpp b/source/base/StarPackedAssetSource.cpp index fe16a80..b335c2f 100644 --- a/source/base/StarPackedAssetSource.cpp +++ b/source/base/StarPackedAssetSource.cpp @@ -140,7 +140,7 @@ IODevicePtr PackedAssetSource::open(String const& path) { auto p = m_index.ptr(path); if (!p) - throw AssetSourceException::format("Requested file '%s' does not exist in the packed assets file", path); + throw AssetSourceException::format("Requested file '{}' does not exist in the packed assets file", path); return make_shared(m_packedFile, p->first, p->second); } @@ -148,7 +148,7 @@ IODevicePtr PackedAssetSource::open(String const& path) { ByteArray PackedAssetSource::read(String const& path) { auto p = m_index.ptr(path); if (!p) - throw AssetSourceException::format("Requested file '%s' does not exist in the packed assets file", path); + throw AssetSourceException::format("Requested file '{}' does not exist in the packed assets file", path); ByteArray data(p->second, 0); m_packedFile->readFullAbsolute(p->first, data.ptr(), p->second); diff --git a/source/base/StarVersionOptionParser.cpp b/source/base/StarVersionOptionParser.cpp index 85995ec..f972975 100644 --- a/source/base/StarVersionOptionParser.cpp +++ b/source/base/StarVersionOptionParser.cpp @@ -4,8 +4,8 @@ namespace Star { void VersionOptionParser::printVersion(std::ostream& os) { - format(os, "Starbound Version %s (%s)\n", StarVersionString, StarArchitectureString); - format(os, "Source Identifier - %s\n", StarSourceIdentifierString); + format(os, "Starbound Version {} ({})\n", StarVersionString, StarArchitectureString); + format(os, "Source Identifier - {}\n", StarSourceIdentifierString); } VersionOptionParser::VersionOptionParser() { @@ -29,7 +29,7 @@ VersionOptionParser::Options VersionOptionParser::parseOrDie(StringList const& c if (!errors.empty()) { for (auto const& err : errors) - coutf("Error: %s\n", err); + coutf("Error: {}\n", err); coutf("\n"); printHelp(std::cout); std::exit(1); diff --git a/source/client/StarClientApplication.cpp b/source/client/StarClientApplication.cpp index 907f357..a4e190f 100644 --- a/source/client/StarClientApplication.cpp +++ b/source/client/StarClientApplication.cpp @@ -127,7 +127,7 @@ void ClientApplication::startup(StringList const& cmdLineArgs) { RootLoader rootLoader({AdditionalAssetsSettings, AdditionalDefaultConfiguration, String("starbound.log"), LogLevel::Info, false, String("starbound.config")}); m_root = rootLoader.initOrDie(cmdLineArgs).first; - Logger::info("Client Version %s (%s) Source ID: %s Protocol: %s", StarVersionString, StarArchitectureString, StarSourceIdentifierString, StarProtocolVersion); + Logger::info("Client Version {} ({}) Source ID: {} Protocol: {}", StarVersionString, StarArchitectureString, StarSourceIdentifierString, StarProtocolVersion); } void ClientApplication::shutdown() { @@ -198,7 +198,7 @@ void ClientApplication::renderInit(RendererPtr renderer) { Application::renderInit(renderer); auto assets = m_root->assets(); - String rendererConfig = strf("/rendering/%s.config", renderer->rendererId()); + String rendererConfig = strf("/rendering/{}.config", renderer->rendererId()); if (assets->assetExists(rendererConfig)) { StringMap shaders; auto config = assets->json(rendererConfig); @@ -216,7 +216,7 @@ void ClientApplication::renderInit(RendererPtr renderer) { renderer->setEffectConfig(config, shaders); } else - Logger::warn("No rendering config found for renderer with id '%s'", renderer->rendererId()); + Logger::warn("No rendering config found for renderer with id '{}'", renderer->rendererId()); if (m_root->configuration()->get("limitTextureAtlasSize").optBool().value(false)) renderer->setSizeLimitEnabled(true); @@ -489,7 +489,7 @@ void ClientApplication::changeState(MainAppState newState) { try { packetSocket = TcpPacketSocket::open(TcpSocket::connectTo(*address)); } catch (StarException const& e) { - setError(strf("Join failed! Error connecting to '%s'", *address), e); + setError(strf("Join failed! Error connecting to '{}'", *address), e); return; } @@ -499,7 +499,7 @@ void ClientApplication::changeState(MainAppState newState) { if (auto p2pNetworkingService = appController()->p2pNetworkingService()) { auto result = p2pNetworkingService->connectToPeer(*p2pPeerId); if (result.isLeft()) { - setError(strf("Cannot join peer: %s", result.left())); + setError(strf("Cannot join peer: {}", result.left())); return; } else { packetSocket = P2PPacketSocket::open(move(result.right())); @@ -534,7 +534,7 @@ void ClientApplication::changeState(MainAppState newState) { } if (auto errorMessage = m_universeClient->connect(m_universeServer->addLocalClient(), "", "")) { - setError(strf("Error connecting locally: %s", *errorMessage)); + setError(strf("Error connecting locally: {}", *errorMessage)); return; } } @@ -558,8 +558,8 @@ void ClientApplication::setError(String const& error) { } void ClientApplication::setError(String const& error, std::exception const& e) { - Logger::error("%s\n%s", error, outputException(e, true)); - m_errorScreen->setMessage(strf("%s\n%s", error, outputException(e, false))); + Logger::error("{}\n{}", error, outputException(e, true)); + m_errorScreen->setMessage(strf("{}\n{}", error, outputException(e, false))); } void ClientApplication::updateMods() { @@ -570,10 +570,10 @@ void ClientApplication::updateMods() { StringList modDirectories; for (auto contentId : ugcService->subscribedContentIds()) { if (auto contentDirectory = ugcService->contentDownloadDirectory(contentId)) { - Logger::info("Loading mods from user generated content with id '%s' from directory '%s'", contentId, *contentDirectory); + Logger::info("Loading mods from user generated content with id '{}' from directory '{}'", contentId, *contentDirectory); modDirectories.append(*contentDirectory); } else { - Logger::warn("User generated content with id '%s' is not available", contentId); + Logger::warn("User generated content with id '{}' is not available", contentId); } } @@ -656,7 +656,7 @@ void ClientApplication::updateTitle() { changeState(MainAppState::MultiPlayer); } } else { - setError(strf("invalid port: %s", portString)); + setError(strf("invalid port: {}", portString)); } } else { changeState(MainAppState::MultiPlayer); @@ -760,7 +760,7 @@ void ClientApplication::updateRunning() { m_cinematicOverlay->stop(); String errMessage; if (auto disconnectReason = m_universeClient->disconnectReason()) - errMessage = strf("You were disconnected from the server for the following reason:\n%s", *disconnectReason); + errMessage = strf("You were disconnected from the server for the following reason:\n{}", *disconnectReason); else errMessage = "Client-server connection no longer valid!"; setError(errMessage); @@ -805,12 +805,12 @@ void ClientApplication::updateRunning() { Vec2F aimPosition = m_player->aimPosition(); LogMap::set("render_fps", appController()->renderFps()); LogMap::set("update_rate", appController()->updateRate()); - LogMap::set("player_pos", strf("%4.2f %4.2f", m_player->position()[0], m_player->position()[1])); - LogMap::set("player_vel", strf("%4.2f %4.2f", m_player->velocity()[0], m_player->velocity()[1])); - LogMap::set("player_aim", strf("%4.2f %4.2f", aimPosition[0], aimPosition[1])); + LogMap::set("player_pos", strf("{:4.2f} {:4.2f}", m_player->position()[0], m_player->position()[1])); + LogMap::set("player_vel", strf("{:4.2f} {:4.2f}", m_player->velocity()[0], m_player->velocity()[1])); + LogMap::set("player_aim", strf("{:4.2f} {:4.2f}", aimPosition[0], aimPosition[1])); if (m_universeClient->worldClient()) { - LogMap::set("liquid_level", strf("%d", m_universeClient->worldClient()->liquidLevel(Vec2I::floor(aimPosition)).level)); - LogMap::set("dungeonId", strf("%d", m_universeClient->worldClient()->dungeonId(Vec2I::floor(aimPosition)))); + LogMap::set("liquid_level", strf("{}", m_universeClient->worldClient()->liquidLevel(Vec2I::floor(aimPosition)).level)); + LogMap::set("dungeonId", strf("{}", m_universeClient->worldClient()->dungeonId(Vec2I::floor(aimPosition)))); } if (m_mainInterface->currentState() == MainInterface::ReturnToTitle) diff --git a/source/core/StarAudio.cpp b/source/core/StarAudio.cpp index 7e4cd31..ef5d2f4 100644 --- a/source/core/StarAudio.cpp +++ b/source/core/StarAudio.cpp @@ -59,13 +59,13 @@ namespace { uint32_t fileSize = readLEType(device); fileSize += sigLength + sizeof(fileSize); if (fileSize != device->size()) - throw AudioException(strf("Wav file is wrong size, reports %d is actually %d", fileSize, device->size())); + throw AudioException(strf("Wav file is wrong size, reports {} is actually {}", fileSize, device->size())); device->readFull(waveSig.get(), sigLength); if ((strcmp(riffSig.get(), "RIFF") != 0) || (strcmp(waveSig.get(), "WAVE") != 0)) { // bytes are not magic auto p = [](char a) { return isprint(a) ? a : '?'; }; - throw AudioException(strf("Wav file has wrong magic bytes, got `%c%c%c%c' and `%c%c%c%c' but expected `RIFF' and `WAVE'", + throw AudioException(strf("Wav file has wrong magic bytes, got `{}{}{}{}' and `{}{}{}{}' but expected `RIFF' and `WAVE'", p(riffSig[0]), p(riffSig[1]), p(riffSig[2]), p(riffSig[3]), p(waveSig[0]), p(waveSig[1]), p(waveSig[2]), p(waveSig[3]))); } @@ -74,7 +74,7 @@ namespace { device->readFull(fmtSig.get(), sigLength); if (strcmp(fmtSig.get(), "fmt ") != 0) { // friendship is magic auto p = [](char a) { return isprint(a) ? a : '?'; }; - throw AudioException(strf("Wav file fmt subchunk has wrong magic bytes, got `%c%c%c%c' but expected `fmt '", + throw AudioException(strf("Wav file fmt subchunk has wrong magic bytes, got `{}{}{}{}' but expected `fmt '", p(fmtSig[0]), p(fmtSig[1]), p(fmtSig[2]), @@ -84,7 +84,7 @@ namespace { uint32_t fmtSubchunkSize = readLEType(device); fmtSubchunkSize += sigLength; if (fmtSubchunkSize < 20) - throw AudioException(strf("fmt subchunk is sized wrong, expected 20 got %d. Is this wav file not PCM?", fmtSubchunkSize)); + throw AudioException(strf("fmt subchunk is sized wrong, expected 20 got {}. Is this wav file not PCM?", fmtSubchunkSize)); uint16_t audioFormat = readLEType(device); if (audioFormat != 1) @@ -110,14 +110,14 @@ namespace { device->readFull(dataSig.get(), sigLength); if (strcmp(dataSig.get(), "data") != 0) { // magic or more magic? auto p = [](char a) { return isprint(a) ? a : '?'; }; - throw AudioException(strf("Wav file data subchunk has wrong magic bytes, got `%c%c%c%c' but expected `data'", + throw AudioException(strf("Wav file data subchunk has wrong magic bytes, got `{}{}{}{}' but expected `data'", p(dataSig[0]), p(dataSig[1]), p(dataSig[2]), p(dataSig[3]))); } uint32_t wavDataSize = readLEType(device); size_t wavDataOffset = (size_t)device->pos(); if (wavDataSize + wavDataOffset > (size_t)device->size()) { - throw AudioException(strf("Wav file data size reported is inconsistent with file size, got %d but expected %d", + throw AudioException(strf("Wav file data size reported is inconsistent with file size, got {} but expected {}", device->size(), wavDataSize + wavDataOffset)); } diff --git a/source/core/StarBTreeDatabase.cpp b/source/core/StarBTreeDatabase.cpp index 6983df8..4ac321f 100644 --- a/source/core/StarBTreeDatabase.cpp +++ b/source/core/StarBTreeDatabase.cpp @@ -886,7 +886,7 @@ void BTreeDatabase::updateBlock(BlockIndex blockIndex, ByteArray const& block) { void BTreeDatabase::rawReadBlock(BlockIndex blockIndex, size_t blockOffset, char* block, size_t size) const { if (blockOffset > m_blockSize || size > m_blockSize - blockOffset) - throw DBException::format("Read past end of block, offset: %s size %s", blockOffset, size); + throw DBException::format("Read past end of block, offset: {} size {}", blockOffset, size); if (size <= 0) return; @@ -896,7 +896,7 @@ void BTreeDatabase::rawReadBlock(BlockIndex blockIndex, size_t blockOffset, char void BTreeDatabase::rawWriteBlock(BlockIndex blockIndex, size_t blockOffset, char const* block, size_t size) const { if (blockOffset > m_blockSize || size > m_blockSize - blockOffset) - throw DBException::format("Write past end of block, offset: %s size %s", blockOffset, size); + throw DBException::format("Write past end of block, offset: {} size {}", blockOffset, size); if (size <= 0) return; @@ -910,7 +910,7 @@ auto BTreeDatabase::readFreeIndexBlock(BlockIndex blockIndex) -> FreeIndexBlock ByteArray magic(2, 0); rawReadBlock(blockIndex, 0, magic.ptr(), 2); if (magic != ByteArray(FreeIndexMagic, 2)) - throw DBException::format("Internal exception! block %s missing free index block marker!", blockIndex); + throw DBException::format("Internal exception! block {} missing free index block marker!", blockIndex); FreeIndexBlock freeIndexBlock; DataStreamBuffer buffer(max(sizeof(BlockIndex), (size_t)4)); @@ -1124,20 +1124,20 @@ void BTreeDatabase::doCommit() { void BTreeDatabase::checkIfOpen(char const* methodName, bool shouldBeOpen) const { if (shouldBeOpen && !m_open) - throw DBException::format("BTreeDatabase method '%s' called when not open, must be open.", methodName); + throw DBException::format("BTreeDatabase method '{}' called when not open, must be open.", methodName); else if (!shouldBeOpen && m_open) - throw DBException::format("BTreeDatabase method '%s' called when open, cannot call when open.", methodName); + throw DBException::format("BTreeDatabase method '{}' called when open, cannot call when open.", methodName); } void BTreeDatabase::checkBlockIndex(size_t blockIndex) const { BlockIndex blockCount = (m_deviceSize - HeaderSize) / m_blockSize; if (blockIndex >= blockCount) - throw DBException::format("blockIndex: %s out of block range", blockIndex); + throw DBException::format("blockIndex: {} out of block range", blockIndex); } void BTreeDatabase::checkKeySize(ByteArray const& k) const { if (k.size() != m_keySize) - throw DBException::format("Wrong key size %s", k.size()); + throw DBException::format("Wrong key size {}", k.size()); } uint32_t BTreeDatabase::maxFreeIndexLength() const { diff --git a/source/core/StarBiMap.hpp b/source/core/StarBiMap.hpp index 3953fde..8e3d616 100644 --- a/source/core/StarBiMap.hpp +++ b/source/core/StarBiMap.hpp @@ -179,7 +179,7 @@ template ::BiMap(std::initializer_list list) { for (value_type const& v : list) { if (!insert(v.first, v.second)) - throw MapException::format("Repeat pair in BiMap initializer_list construction: (%s, %s)", outputAny(v.first), outputAny(v.second)); + throw MapException::format("Repeat pair in BiMap initializer_list construction: ({}, {})", outputAny(v.first), outputAny(v.second)); } } @@ -324,10 +324,10 @@ bool BiMap::insert(Left const& left, Right c template void BiMap::add(Left const& left, Right const& right) { if (m_leftMap.contains(left)) - throw MapException(strf("BiMap already contains left side value '%s'", outputAny(left))); + throw MapException(strf("BiMap already contains left side value '{}'", outputAny(left))); if (m_rightMap.contains(right)) - throw MapException(strf("BiMap already contains right side value '%s'", outputAny(right))); + throw MapException(strf("BiMap already contains right side value '{}'", outputAny(right))); insert(left, right); } diff --git a/source/core/StarBuffer.cpp b/source/core/StarBuffer.cpp index e99615c..3212e0a 100644 --- a/source/core/StarBuffer.cpp +++ b/source/core/StarBuffer.cpp @@ -90,7 +90,7 @@ void Buffer::open(IOMode mode) { } String Buffer::deviceName() const { - return strf("Buffer <%s>", (void*)this); + return strf("Buffer <{}>", (void*)this); } StreamOffset Buffer::size() { @@ -244,7 +244,7 @@ size_t ExternalBuffer::writeAbsolute(StreamOffset, char const*, size_t) { } String ExternalBuffer::deviceName() const { - return strf("ExternalBuffer <%s>", (void*)this); + return strf("ExternalBuffer <{}>", (void*)this); } StreamOffset ExternalBuffer::size() { diff --git a/source/core/StarByteArray.cpp b/source/core/StarByteArray.cpp index 944071b..6414c46 100644 --- a/source/core/StarByteArray.cpp +++ b/source/core/StarByteArray.cpp @@ -85,14 +85,14 @@ void ByteArray::reserve(size_t newCapacity) { if (!m_data) { auto newMem = (char*)Star::malloc(newCapacity); if (!newMem) - throw MemoryException::format("Could not set new ByteArray capacity %s\n", newCapacity); + throw MemoryException::format("Could not set new ByteArray capacity {}\n", newCapacity); m_data = newMem; m_capacity = newCapacity; } else { newCapacity = max({m_capacity * 2, newCapacity, (size_t)8}); auto newMem = (char*)Star::realloc(m_data, newCapacity); if (!newMem) - throw MemoryException::format("Could not set new ByteArray capacity %s\n", newCapacity); + throw MemoryException::format("Could not set new ByteArray capacity {}\n", newCapacity); m_data = newMem; m_capacity = newCapacity; } diff --git a/source/core/StarByteArray.hpp b/source/core/StarByteArray.hpp index 9f63643..cb5633b 100644 --- a/source/core/StarByteArray.hpp +++ b/source/core/StarByteArray.hpp @@ -242,7 +242,7 @@ inline char ByteArray::operator[](size_t i) const { inline char ByteArray::at(size_t i) const { if (i >= m_size) - throw OutOfRangeException(strf("Out of range in ByteArray::at(%s)", i)); + throw OutOfRangeException(strf("Out of range in ByteArray::at({})", i)); return m_data[i]; } diff --git a/source/core/StarCasting.hpp b/source/core/StarCasting.hpp index 64305af..0c2ed12 100644 --- a/source/core/StarCasting.hpp +++ b/source/core/StarCasting.hpp @@ -61,11 +61,11 @@ shared_ptr as(shared_ptr const& p) { template auto convert(Ptr const& p) -> decltype(as(p)) { if (!p) - throw PointerConvertException::format("Could not convert from nullptr to %s", typeid(Type).name()); + throw PointerConvertException::format("Could not convert from nullptr to {}", typeid(Type).name()); else if (auto a = as(p)) return a; else - throw PointerConvertException::format("Could not convert from %s to %s", typeid(*p).name(), typeid(Type).name()); + throw PointerConvertException::format("Could not convert from {} to {}", typeid(*p).name(), typeid(Type).name()); } template diff --git a/source/core/StarColor.cpp b/source/core/StarColor.cpp index 915620d..e0d6842 100644 --- a/source/core/StarColor.cpp +++ b/source/core/StarColor.cpp @@ -221,7 +221,7 @@ Color::Color(const String& name) { if (i != NamedColors.end()) *this = i->second; else - throw ColorException(strf("Named color %s not found", name), false); + throw ColorException(strf("Named color {} not found", name), false); } } @@ -622,7 +622,7 @@ Vec4B Color::hexToVec4B(StringView s) { } else if (s.utf8Size() == 8) { hexDecode(s.utf8Ptr(), 8, (char*)cbytes.data(), 4); } else { - throw ColorException(strf("Improper size for hex string '%s' in Color::hexToVec4B", s), false); + throw ColorException(strf("Improper size for hex string '{}' in Color::hexToVec4B", s), false); } return Vec4B(move(cbytes)); diff --git a/source/core/StarCompression.cpp b/source/core/StarCompression.cpp index e8d282c..2aaf17f 100644 --- a/source/core/StarCompression.cpp +++ b/source/core/StarCompression.cpp @@ -23,7 +23,7 @@ void compressData(ByteArray const& in, ByteArray& out, CompressionLevel compress strm.opaque = Z_NULL; int deflate_res = deflateInit(&strm, compression); if (deflate_res != Z_OK) - throw IOException(strf("Failed to initialise deflate (%d)", deflate_res)); + throw IOException(strf("Failed to initialise deflate ({})", deflate_res)); strm.next_in = (unsigned char*)in.ptr(); strm.avail_in = in.size(); @@ -40,7 +40,7 @@ void compressData(ByteArray const& in, ByteArray& out, CompressionLevel compress deflateEnd(&strm); if (deflate_res != Z_STREAM_END) - throw IOException(strf("Internal error in uncompressData, deflate_res is %s", deflate_res)); + throw IOException(strf("Internal error in uncompressData, deflate_res is {}", deflate_res)); out.append((char const*)temp_buffer, BUFSIZE - strm.avail_out); } @@ -66,7 +66,7 @@ void uncompressData(ByteArray const& in, ByteArray& out) { strm.opaque = Z_NULL; int inflate_res = inflateInit(&strm); if (inflate_res != Z_OK) - throw IOException(strf("Failed to initialise inflate (%d)", inflate_res)); + throw IOException(strf("Failed to initialise inflate ({})", inflate_res)); strm.next_in = (unsigned char*)in.ptr(); strm.avail_in = in.size(); @@ -86,7 +86,7 @@ void uncompressData(ByteArray const& in, ByteArray& out) { inflateEnd(&strm); if (inflate_res != Z_STREAM_END) - throw IOException(strf("Internal error in uncompressData, inflate_res is %s", inflate_res)); + throw IOException(strf("Internal error in uncompressData, inflate_res is {}", inflate_res)); out.append((char const*)temp_buffer, BUFSIZE - strm.avail_out); } @@ -134,7 +134,7 @@ void CompressedFile::seek(StreamOffset offset, IOSeek seekMode) { StreamOffset endPos = pos(); if (retCode < 0) { - throw IOException::format("Seek error: %s", gzerror((gzFile)m_file, 0)); + throw IOException::format("Seek error: {}", gzerror((gzFile)m_file, 0)); } else if ((seekMode == IOSeek::Relative && begPos + offset != endPos) || (seekMode == IOSeek::Absolute && offset != endPos)) { throw EofException("Error, unexpected end of file found"); @@ -153,7 +153,7 @@ size_t CompressedFile::read(char* data, size_t len) { if (ret == 0) throw EofException("Error, unexpected end of file found"); else if (ret == -1) - throw IOException::format("Read error: %s", gzerror((gzFile)m_file, 0)); + throw IOException::format("Read error: {}", gzerror((gzFile)m_file, 0)); else return (size_t)ret; } @@ -164,7 +164,7 @@ size_t CompressedFile::write(const char* data, size_t len) { int ret = gzwrite((gzFile)m_file, data, len); if (ret == 0) - throw IOException::format("Write error: %s", gzerror((gzFile)m_file, 0)); + throw IOException::format("Write error: {}", gzerror((gzFile)m_file, 0)); else return (size_t)ret; } @@ -210,7 +210,7 @@ void CompressedFile::open(IOMode mode) { m_file = gzopen(m_filename.utf8Ptr(), modeString.utf8Ptr()); if (!m_file) - throw IOException::format("Cannot open filename '%s'", m_filename); + throw IOException::format("Cannot open filename '{}'", m_filename); } void CompressedFile::close() { diff --git a/source/core/StarException_unix.cpp b/source/core/StarException_unix.cpp index 578c0b4..71ffd2b 100644 --- a/source/core/StarException_unix.cpp +++ b/source/core/StarException_unix.cpp @@ -112,23 +112,23 @@ OutputProxy outputException(std::exception const& e, bool fullStacktrace) { } void printStack(char const* message) { - Logger::info("Stack Trace (%s)...\n%s", message, outputStack(captureStack())); + Logger::info("Stack Trace ({})...\n{}", message, outputStack(captureStack())); } void fatalError(char const* message, bool showStackTrace) { if (showStackTrace) - Logger::error("Fatal Error: %s\n%s", message, outputStack(captureStack())); + Logger::error("Fatal Error: {}\n{}", message, outputStack(captureStack())); else - Logger::error("Fatal Error: %s", message); + Logger::error("Fatal Error: {}", message); std::abort(); } void fatalException(std::exception const& e, bool showStackTrace) { if (showStackTrace) - Logger::error("Fatal Exception caught: %s\nCaught at:\n%s", outputException(e, true), outputStack(captureStack())); + Logger::error("Fatal Exception caught: {}\nCaught at:\n{}", outputException(e, true), outputStack(captureStack())); else - Logger::error("Fatal Exception caught: %s", outputException(e, showStackTrace)); + Logger::error("Fatal Exception caught: {}", outputException(e, showStackTrace)); std::abort(); } diff --git a/source/core/StarException_windows.cpp b/source/core/StarException_windows.cpp index 7fd386c..54254d4 100644 --- a/source/core/StarException_windows.cpp +++ b/source/core/StarException_windows.cpp @@ -127,9 +127,9 @@ OutputProxy outputStack(StackCapture stack) { symbol->MaxNameLen = MAX_SYM_NAME; DWORD64 displacement = 0; - format(os, "[%i] %p", i, stack.first[i]); + format(os, "[{}] {}", i, (void*)stack.first[i]); if (SymFromAddr(process, stack.first[i], &displacement, symbol)) - format(os, " %s", symbol->Name); + format(os, " {}", symbol->Name); if (i + 1 < stack.second) os << std::endl; @@ -224,7 +224,7 @@ OutputProxy outputException(std::exception const& e, bool fullStacktrace) { } void printStack(char const* message) { - Logger::info("Stack Trace (%s)...\n%s", message, outputStack(captureStack())); + Logger::info("Stack Trace ({})...\n{}", message, outputStack(captureStack())); } void fatalError(char const* message, bool showStackTrace) { diff --git a/source/core/StarFile.cpp b/source/core/StarFile.cpp index 738a088..ec09ff7 100644 --- a/source/core/StarFile.cpp +++ b/source/core/StarFile.cpp @@ -104,8 +104,8 @@ void File::overwriteFileWithRename(String const& data, String const& filename, S void File::backupFileInSequence(String const& targetFile, unsigned maximumBackups, String const& backupExtensionPrefix) { for (unsigned i = maximumBackups; i > 0; --i) { - String curExtension = i == 1 ? "" : strf("%s%s", backupExtensionPrefix, i - 1); - String nextExtension = strf("%s%s", backupExtensionPrefix, i); + String curExtension = i == 1 ? "" : strf("{}{}", backupExtensionPrefix, i - 1); + String nextExtension = strf("{}{}", backupExtensionPrefix, i); if (File::isFile(targetFile + curExtension)) File::copy(targetFile + curExtension, targetFile + nextExtension); diff --git a/source/core/StarFile_unix.cpp b/source/core/StarFile_unix.cpp index aa22bc8..abc9fe0 100644 --- a/source/core/StarFile_unix.cpp +++ b/source/core/StarFile_unix.cpp @@ -46,19 +46,19 @@ String File::currentDirectory() { void File::changeDirectory(const String& dirName) { if (::chdir(dirName.utf8Ptr()) != 0) - throw IOException(strf("could not change directory to %s", dirName)); + throw IOException(strf("could not change directory to {}", dirName)); } void File::makeDirectory(String const& dirName) { if (::mkdir(dirName.utf8Ptr(), 0777) != 0) - throw IOException(strf("could not create directory '%s', %s", dirName, strerror(errno))); + throw IOException(strf("could not create directory '{}', {}", dirName, strerror(errno))); } List> File::dirList(const String& dirName, bool skipDots) { List> fileList; DIR* directory = ::opendir(dirName.utf8Ptr()); if (directory == NULL) - throw IOException::format("dirList failed on dir: '%s'", dirName); + throw IOException::format("dirList failed on dir: '{}'", dirName); for (dirent* entry = ::readdir(directory); entry != NULL; entry = ::readdir(directory)) { String entryString = entry->d_name; @@ -113,13 +113,13 @@ String File::fullPath(const String& fileName) { char buffer[PATH_MAX]; if (::realpath(fileName.utf8Ptr(), buffer) == NULL) - throw IOException::format("realpath failed on file: '%s' problem path was: '%s'", fileName, buffer); + throw IOException::format("realpath failed on file: '{}' problem path was: '{}'", fileName, buffer); return String(buffer); } String File::temporaryFileName() { - return relativeTo(P_tmpdir, strf("starbound.tmpfile.%s", hexEncode(Random::randBytes(16)))); + return relativeTo(P_tmpdir, strf("starbound.tmpfile.{}", hexEncode(Random::randBytes(16)))); } FilePtr File::temporaryFile() { @@ -131,16 +131,16 @@ FilePtr File::ephemeralFile() { ByteArray path = ByteArray::fromCStringWithNull(relativeTo(P_tmpdir, "starbound.tmpfile.XXXXXXXX").utf8Ptr()); auto res = mkstemp(path.ptr()); if (res < 0) - throw IOException::format("tmpfile error: %s", strerror(errno)); + throw IOException::format("tmpfile error: {}", strerror(errno)); if (::unlink(path.ptr()) < 0) - throw IOException::format("Could not remove mkstemp file when creating ephemeralFile: %s", strerror(errno)); + throw IOException::format("Could not remove mkstemp file when creating ephemeralFile: {}", strerror(errno)); file->m_file = handleFromFd(res); file->setMode(IOMode::ReadWrite); return file; } String File::temporaryDirectory() { - String dirname = relativeTo(P_tmpdir, strf("starbound.tmpdir.%s", hexEncode(Random::randBytes(16)))); + String dirname = relativeTo(P_tmpdir, strf("starbound.tmpdir.{}", hexEncode(Random::randBytes(16)))); makeDirectory(dirname); return dirname; } @@ -171,12 +171,12 @@ bool File::isDirectory(String const& path) { void File::remove(String const& filename) { if (::remove(filename.utf8Ptr()) < 0) - throw IOException::format("remove error: %s", strerror(errno)); + throw IOException::format("remove error: {}", strerror(errno)); } void File::rename(String const& source, String const& target) { if (::rename(source.utf8Ptr(), target.utf8Ptr()) < 0) - throw IOException::format("rename error: %s", strerror(errno)); + throw IOException::format("rename error: {}", strerror(errno)); } void File::overwriteFileWithRename(char const* data, size_t len, String const& filename, String const& newSuffix) { @@ -200,11 +200,11 @@ void* File::fopen(char const* filename, IOMode mode) { int fd = ::open(filename, oflag, 0666); if (fd < 0) - throw IOException::format("Error opening file '%s', error: %s", filename, strerror(errno)); + throw IOException::format("Error opening file '{}', error: {}", filename, strerror(errno)); if (mode & IOMode::Append) { if (lseek(fd, 0, SEEK_END) < 0) - throw IOException::format("Error opening file '%s', cannot seek: %s", filename, strerror(errno)); + throw IOException::format("Error opening file '{}', cannot seek: {}", filename, strerror(errno)); } return handleFromFd(fd); @@ -221,7 +221,7 @@ void File::fseek(void* f, StreamOffset offset, IOSeek seekMode) { retCode = lseek(fd, offset, SEEK_END); if (retCode < 0) - throw IOException::format("Seek error: %s", strerror(errno)); + throw IOException::format("Seek error: {}", strerror(errno)); } StreamOffset File::ftell(void* f) { @@ -237,7 +237,7 @@ size_t File::fread(void* file, char* data, size_t len) { if (ret < 0) { if (errno == EAGAIN || errno == EINTR) return 0; - throw IOException::format("Read error: %s", strerror(errno)); + throw IOException::format("Read error: {}", strerror(errno)); } else { return ret; } @@ -252,7 +252,7 @@ size_t File::fwrite(void* file, char const* data, size_t len) { if (ret < 0) { if (errno == EAGAIN || errno == EINTR) return 0; - throw IOException::format("Write error: %s", strerror(errno)); + throw IOException::format("Write error: {}", strerror(errno)); } else { return ret; } @@ -269,7 +269,7 @@ void File::fsync(void* file) { void File::fclose(void* file) { if (::close(fdFromHandle(file)) < 0) - throw IOException::format("Close error: %s", strerror(errno)); + throw IOException::format("Close error: {}", strerror(errno)); } StreamOffset File::fsize(void* file) { @@ -289,7 +289,7 @@ size_t File::pwrite(void* file, char const* data, size_t len, StreamOffset posit void File::resize(void* f, StreamOffset size) { if (::ftruncate(fdFromHandle(f), size) < 0) - throw IOException::format("resize error: %s", strerror(errno)); + throw IOException::format("resize error: {}", strerror(errno)); } } diff --git a/source/core/StarFile_windows.cpp b/source/core/StarFile_windows.cpp index bb13ffc..0b5c286 100644 --- a/source/core/StarFile_windows.cpp +++ b/source/core/StarFile_windows.cpp @@ -42,13 +42,13 @@ String File::currentDirectory() { void File::changeDirectory(const String& dirName) { if (!SetCurrentDirectoryW(stringToUtf16(dirName).get())) - throw IOException(strf("could not change directory to %s", dirName)); + throw IOException(strf("could not change directory to {}", dirName)); } void File::makeDirectory(String const& dirName) { if (CreateDirectoryW(stringToUtf16(dirName).get(), NULL) == 0) { auto error = GetLastError(); - throw IOException(strf("could not create directory '%s', %s", dirName, error)); + throw IOException(strf("could not create directory '{}', {}", dirName, error)); } } @@ -85,9 +85,9 @@ String File::fullPath(const String& path) { fullpath_size = GetFullPathNameW(stringToUtf16(path).get(), (DWORD)MAX_PATH, buffer, (WCHAR**)&lpszLastNamePart); if (0 == fullpath_size) - throw IOException::format("GetFullPathName failed on path: '%s'", path); + throw IOException::format("GetFullPathName failed on path: '{}'", path); if (fullpath_size >= MAX_PATH) - throw IOException::format("GetFullPathName failed on path: '%s'", path); + throw IOException::format("GetFullPathName failed on path: '{}'", path); return utf16ToString(buffer); } @@ -99,7 +99,7 @@ List> File::dirList(const String& dirName, bool skipDots hFind = FindFirstFileW(stringToUtf16(File::relativeTo(dirName, "*")).get(), &findFileData); if (hFind == INVALID_HANDLE_VALUE) - throw IOException(strf("Invalid file handle in dirList of '%s', error is %u", dirName, GetLastError())); + throw IOException(strf("Invalid file handle in dirList of '{}', error is %u", dirName, GetLastError())); while (true) { String entry = utf16ToString(findFileData.cFileName); @@ -113,7 +113,7 @@ List> File::dirList(const String& dirName, bool skipDots FindClose(hFind); if ((dwError != ERROR_NO_MORE_FILES) && (dwError != NO_ERROR)) - throw IOException(strf("FindNextFile error in dirList of '%s'. Error is %u", dirName, dwError)); + throw IOException(strf("FindNextFile error in dirList of '{}'. Error is %u", dirName, dwError)); return fileList; } @@ -158,10 +158,10 @@ String File::temporaryFileName() { WCHAR tempPath[MAX_PATH]; if (!GetTempPathW(MAX_PATH, tempPath)) { auto error = GetLastError(); - throw IOException(strf("Could not call GetTempPath %s", error)); + throw IOException(strf("Could not call GetTempPath {}", error)); } - return relativeTo(utf16ToString(tempPath), strf("starbound.tmpfile.%s", hexEncode(Random::randBytes(16)))); + return relativeTo(utf16ToString(tempPath), strf("starbound.tmpfile.{}", hexEncode(Random::randBytes(16)))); } FilePtr File::temporaryFile() { @@ -179,10 +179,10 @@ String File::temporaryDirectory() { WCHAR tempPath[MAX_PATH]; if (!GetTempPathW(MAX_PATH, tempPath)) { auto error = GetLastError(); - throw IOException(strf("Could not call GetTempPath %s", error)); + throw IOException(strf("Could not call GetTempPath {}", error)); } - String dirname = relativeTo(utf16ToString(tempPath), strf("starbound.tmpdir.%s", hexEncode(Random::randBytes(16)))); + String dirname = relativeTo(utf16ToString(tempPath), strf("starbound.tmpdir.{}", hexEncode(Random::randBytes(16)))); makeDirectory(dirname); return dirname; } @@ -191,11 +191,11 @@ void File::remove(String const& filename) { if (isDirectory(filename)) { if (!RemoveDirectoryW(stringToUtf16(filename).get())) { auto error = GetLastError(); - throw IOException(strf("Rename error: %s", error)); + throw IOException(strf("Rename error: {}", error)); } } else if (::_wremove(stringToUtf16(filename).get()) < 0) { auto error = errno; - throw IOException::format("remove error: %s", strerror(error)); + throw IOException::format("remove error: {}", strerror(error)); } } @@ -207,22 +207,22 @@ void File::rename(String const& source, String const& target) { if (!DeleteFileW(stringToUtf16(temp).get())) { auto error = GetLastError(); if (error != ERROR_FILE_NOT_FOUND) - throw IOException(strf("error deleting existing temp file: %s", error)); + throw IOException(strf("error deleting existing temp file: {}", error)); } if (!MoveFileExW(stringToUtf16(target).get(), stringToUtf16(temp).get(), MOVEFILE_COPY_ALLOWED | MOVEFILE_WRITE_THROUGH)) { auto error = GetLastError(); - throw IOException(strf("error temporary file '%s': %s", temp, GetLastError())); + throw IOException(strf("error temporary file '{}': {}", temp, GetLastError())); } } if (!MoveFileExW(stringToUtf16(source).get(), stringToUtf16(target).get(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED | MOVEFILE_WRITE_THROUGH)) { auto error = GetLastError(); - throw IOException(strf("Rename error: %s", error)); + throw IOException(strf("Rename error: {}", error)); } if (replace && !DeleteFileW(stringToUtf16(temp).get())) { auto error = GetLastError(); - throw IOException(strf("error deleting temp file '%s': %s", temp, GetLastError())); + throw IOException(strf("error deleting temp file '{}': {}", temp, GetLastError())); } } @@ -266,19 +266,19 @@ void* File::fopen(char const* filename, IOMode mode) { creationDisposition, 0, NULL); if (file == INVALID_HANDLE_VALUE) - throw IOException::format("could not open file '%s' %s", filename, GetLastError()); + throw IOException::format("could not open file '{}' {}", filename, GetLastError()); LARGE_INTEGER szero; szero.QuadPart = 0; if (!SetFilePointerEx(file, szero, NULL, 0)) { CloseHandle(file); - throw IOException::format("could not set file pointer in fopen '%s' %s", filename, GetLastError()); + throw IOException::format("could not set file pointer in fopen '{}' {}", filename, GetLastError()); } if (mode & IOMode::Truncate) { if (!SetEndOfFile(file)) { CloseHandle(file); - throw IOException::format("could not set end of file in fopen '%s' %s", filename, GetLastError()); + throw IOException::format("could not set end of file in fopen '{}' {}", filename, GetLastError()); } } @@ -286,11 +286,11 @@ void* File::fopen(char const* filename, IOMode mode) { LARGE_INTEGER size; if (GetFileSizeEx(file, &size) == 0) { CloseHandle(file); - throw IOException::format("could not get file size in fopen '%s' %s", filename, GetLastError()); + throw IOException::format("could not get file size in fopen '{}' {}", filename, GetLastError()); } if (!SetFilePointerEx(file, size, NULL, 0)) { CloseHandle(file); - throw IOException::format("could not set file pointer in fopen '%s' %s", filename, GetLastError()); + throw IOException::format("could not set file pointer in fopen '{}' {}", filename, GetLastError()); } } @@ -331,7 +331,7 @@ size_t File::fread(void* f, char* data, size_t len) { if (ret == 0) { auto err = GetLastError(); if (err != ERROR_IO_PENDING) - throw IOException::format("read error %s", err); + throw IOException::format("read error {}", err); } return numRead; @@ -348,7 +348,7 @@ size_t File::fwrite(void* f, char const* data, size_t len) { if (ret == 0) { auto err = GetLastError(); if (err != ERROR_IO_PENDING) - throw IOException::format("write error %s", err); + throw IOException::format("write error {}", err); } return numWritten; @@ -357,7 +357,7 @@ size_t File::fwrite(void* f, char const* data, size_t len) { void File::fsync(void* f) { HANDLE file = (HANDLE)f; if (FlushFileBuffers(file) == 0) - throw IOException::format("fsync error %s", GetLastError()); + throw IOException::format("fsync error {}", GetLastError()); } void File::fclose(void* f) { @@ -369,7 +369,7 @@ StreamOffset File::fsize(void* f) { HANDLE file = (HANDLE)f; LARGE_INTEGER size; if (GetFileSizeEx(file, &size) == 0) - throw IOException::format("could not get file size in fsize %s", GetLastError()); + throw IOException::format("could not get file size in fsize {}", GetLastError()); return size.QuadPart; } @@ -381,7 +381,7 @@ size_t File::pread(void* f, char* data, size_t len, StreamOffset position) { if (ret == 0) { auto err = GetLastError(); if (err != ERROR_IO_PENDING) - throw IOException::format("pread error %s", err); + throw IOException::format("pread error {}", err); } return numRead; @@ -395,7 +395,7 @@ size_t File::pwrite(void* f, char const* data, size_t len, StreamOffset position if (ret == 0) { auto err = GetLastError(); if (err != ERROR_IO_PENDING) - throw IOException::format("pwrite error %s", err); + throw IOException::format("pwrite error {}", err); } return numWritten; diff --git a/source/core/StarFont.cpp b/source/core/StarFont.cpp index e16a2be..6308784 100644 --- a/source/core/StarFont.cpp +++ b/source/core/StarFont.cpp @@ -66,7 +66,7 @@ void Font::setPixelSize(unsigned pixelSize) { return; if (FT_Set_Pixel_Sizes(m_fontImpl->face, pixelSize, 0)) - throw FontException(strf("Cannot set font pixel size to: %s", pixelSize)); + throw FontException(strf("Cannot set font pixel size to: {}", pixelSize)); m_pixelSize = pixelSize; } diff --git a/source/core/StarFormattedJson.cpp b/source/core/StarFormattedJson.cpp index f31f3ba..d7bd8c7 100644 --- a/source/core/StarFormattedJson.cpp +++ b/source/core/StarFormattedJson.cpp @@ -105,21 +105,21 @@ Json const& FormattedJson::toJson() const { FormattedJson FormattedJson::get(String const& key) const { if (type() != Json::Type::Object) - throw JsonException::format("Cannot call get with key on FormattedJson type %s, must be Object type", typeName()); + throw JsonException::format("Cannot call get with key on FormattedJson type {}, must be Object type", typeName()); Maybe> entry = m_objectEntryLocations.maybe(key); if (entry.isNothing()) - throw JsonException::format("No such key in FormattedJson::get(\"%s\")", key); + throw JsonException::format("No such key in FormattedJson::get(\"{}\")", key); return getFormattedJson(entry->second); } FormattedJson FormattedJson::get(size_t index) const { if (type() != Json::Type::Array) - throw JsonException::format("Cannot call get with index on FormattedJson type %s, must be Array type", typeName()); + throw JsonException::format("Cannot call get with index on FormattedJson type {}, must be Array type", typeName()); if (index >= m_arrayElementLocations.size()) - throw JsonException::format("FormattedJson::get(%s) out of range", index); + throw JsonException::format("FormattedJson::get({}) out of range", index); ElementLocation loc = m_arrayElementLocations.at(index); return getFormattedJson(loc); @@ -263,14 +263,14 @@ FormattedJson FormattedJson::prepend(String const& key, FormattedJson const& val FormattedJson FormattedJson::insertBefore(String const& key, FormattedJson const& value, String const& beforeKey) const { if (!m_objectEntryLocations.contains(beforeKey)) - throw JsonException::format("Cannot insert before key \"%s\", which does not exist", beforeKey); + throw JsonException::format("Cannot insert before key \"{}\", which does not exist", beforeKey); ElementLocation loc = m_objectEntryLocations.get(beforeKey).first; return objectInsert(key, value, loc); } FormattedJson FormattedJson::insertAfter(String const& key, FormattedJson const& value, String const& afterKey) const { if (!m_objectEntryLocations.contains(afterKey)) - throw JsonException::format("Cannot insert after key \"%s\", which does not exist", afterKey); + throw JsonException::format("Cannot insert after key \"{}\", which does not exist", afterKey); ElementLocation loc = m_objectEntryLocations.get(afterKey).second; return objectInsert(key, value, loc + 1); } @@ -303,7 +303,7 @@ void removeValueFromArray(List& elements, size_t loc) { FormattedJson FormattedJson::eraseKey(String const& key) const { if (type() != Json::Type::Object) - throw JsonException::format("Cannot call erase with key on FormattedJson type %s, must be Object type", typeName()); + throw JsonException::format("Cannot call erase with key on FormattedJson type {}, must be Object type", typeName()); Maybe> maybeEntry = m_objectEntryLocations.maybe(key); if (maybeEntry.isNothing()) @@ -319,10 +319,10 @@ FormattedJson FormattedJson::eraseKey(String const& key) const { FormattedJson FormattedJson::insert(size_t index, FormattedJson const& value) const { if (type() != Json::Type::Array) throw JsonException::format( - "Cannot call insert with index on FormattedJson type %s, must be Array type", typeName()); + "Cannot call insert with index on FormattedJson type {}, must be Array type", typeName()); if (index > m_arrayElementLocations.size()) - throw JsonException::format("FormattedJson::insert(%s) out of range", index); + throw JsonException::format("FormattedJson::insert({}) out of range", index); ElementList elements = m_elements; ElementLocation insertPosition = elements.size(); @@ -335,7 +335,7 @@ FormattedJson FormattedJson::insert(size_t index, FormattedJson const& value) co FormattedJson FormattedJson::append(FormattedJson const& value) const { if (type() != Json::Type::Array) - throw JsonException::format("Cannot call append on FormattedJson type %s, must be Array type", typeName()); + throw JsonException::format("Cannot call append on FormattedJson type {}, must be Array type", typeName()); ElementList elements = m_elements; insertWithCommaAndFormatting(elements, elements.size(), true, {ValueElement{value}}); @@ -344,10 +344,10 @@ FormattedJson FormattedJson::append(FormattedJson const& value) const { FormattedJson FormattedJson::set(size_t index, FormattedJson const& value) const { if (type() != Json::Type::Array) - throw JsonException::format("Cannot call set with index on FormattedJson type %s, must be Array type", typeName()); + throw JsonException::format("Cannot call set with index on FormattedJson type {}, must be Array type", typeName()); if (index >= m_arrayElementLocations.size()) - throw JsonException::format("FormattedJson::set(%s) out of range", index); + throw JsonException::format("FormattedJson::set({}) out of range", index); ElementLocation loc = m_arrayElementLocations.at(index); ElementList elements = m_elements; @@ -357,10 +357,10 @@ FormattedJson FormattedJson::set(size_t index, FormattedJson const& value) const FormattedJson FormattedJson::eraseIndex(size_t index) const { if (type() != Json::Type::Array) - throw JsonException::format("Cannot call set with index on FormattedJson type %s, must be Array type", typeName()); + throw JsonException::format("Cannot call set with index on FormattedJson type {}, must be Array type", typeName()); if (index >= m_arrayElementLocations.size()) - throw JsonException::format("FormattedJson::eraseIndex(%s) out of range", index); + throw JsonException::format("FormattedJson::eraseIndex({}) out of range", index); ElementLocation loc = m_arrayElementLocations.at(index); ElementList elements = m_elements; @@ -390,7 +390,7 @@ String FormattedJson::typeName() const { String FormattedJson::toFormattedDouble() const { if (!isType(Json::Type::Float)) - throw JsonException::format("Cannot call toFormattedDouble on Json type %s, must be Float", typeName()); + throw JsonException::format("Cannot call toFormattedDouble on Json type {}, must be Float", typeName()); if (m_formatting.isValid()) return *m_formatting; return toJson().repr(); @@ -398,7 +398,7 @@ String FormattedJson::toFormattedDouble() const { String FormattedJson::toFormattedInt() const { if (!isType(Json::Type::Int)) - throw JsonException::format("Cannot call toFormattedInt on Json type %s, must be Int", typeName()); + throw JsonException::format("Cannot call toFormattedInt on Json type {}, must be Int", typeName()); if (m_formatting.isValid()) return *m_formatting; return toJson().repr(); @@ -454,7 +454,7 @@ FormattedJson FormattedJson::array(ElementList const& elements) { FormattedJson FormattedJson::objectInsert(String const& key, FormattedJson const& value, ElementLocation loc) const { if (type() != Json::Type::Object) - throw JsonException::format("Cannot call set with key on FormattedJson type %s, must be Object type", typeName()); + throw JsonException::format("Cannot call set with key on FormattedJson type {}, must be Object type", typeName()); Maybe> maybeEntry = m_objectEntryLocations.maybe(key); if (maybeEntry.isValid()) { diff --git a/source/core/StarHostAddress.cpp b/source/core/StarHostAddress.cpp index f65f179..5459a7e 100644 --- a/source/core/StarHostAddress.cpp +++ b/source/core/StarHostAddress.cpp @@ -133,7 +133,7 @@ void HostAddress::set(String const& address) { hints.ai_flags = AI_ADDRCONFIG; if (::getaddrinfo(address.utf8Ptr(), NULL, &hints, &result) != 0) - throw NetworkException(strf("Failed to determine address for '%s' (%s)", address, netErrorString())); + throw NetworkException(strf("Failed to determine address for '{}' ({})", address, netErrorString())); for (ptr = result; ptr != NULL; ptr = ptr->ai_next) { NetworkMode mode; @@ -171,12 +171,12 @@ void HostAddress::set(NetworkMode mode, uint8_t const* addr) { std::ostream& operator<<(std::ostream& os, HostAddress const& address) { switch (address.mode()) { case NetworkMode::IPv4: - format(os, "%d.%d.%d.%d", address.octet(0), address.octet(1), address.octet(2), address.octet(3)); + format(os, "{}.{}.{}.{}", address.octet(0), address.octet(1), address.octet(2), address.octet(3)); break; case NetworkMode::IPv6: format(os, - "%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x", + "{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}", address.octet(0), address.octet(1), address.octet(2), @@ -196,7 +196,7 @@ std::ostream& operator<<(std::ostream& os, HostAddress const& address) { break; default: - throw NetworkException(strf("Unknown address mode (%d)", (int)address.mode())); + throw NetworkException(strf("Unknown address mode ({})", (int)address.mode())); } return os; } @@ -224,7 +224,7 @@ Either HostAddressWithPort::lookupWithPort(String c auto portNum = maybeLexicalCast(port); if (!portNum) - return makeLeft(strf("Could not parse port portion of HostAddressWithPort '%s'", port)); + return makeLeft(strf("Could not parse port portion of HostAddressWithPort '{}'", port)); auto hostAddress = HostAddress::lookup(host); if (hostAddress.isLeft()) diff --git a/source/core/StarIODevice.cpp b/source/core/StarIODevice.cpp index 1274e89..2b79bb3 100644 --- a/source/core/StarIODevice.cpp +++ b/source/core/StarIODevice.cpp @@ -42,7 +42,7 @@ void IODevice::writeFull(char const* data, size_t len) { void IODevice::open(IOMode mode) { if (mode != m_mode) - throw IOException::format("Cannot reopen device '%s", deviceName()); + throw IOException::format("Cannot reopen device '{}", deviceName()); } void IODevice::close() { @@ -52,7 +52,7 @@ void IODevice::close() { void IODevice::sync() {} String IODevice::deviceName() const { - return strf("IODevice <%s>", (void*)this); + return strf("IODevice <{}>", (void*)this); } bool IODevice::atEnd() { diff --git a/source/core/StarIdMap.hpp b/source/core/StarIdMap.hpp index 15946da..1f97c55 100644 --- a/source/core/StarIdMap.hpp +++ b/source/core/StarIdMap.hpp @@ -102,7 +102,7 @@ auto IdMapWrapper::nextId() -> IdType { template void IdMapWrapper::add(IdType id, MappedType mappedType) { if (!BaseMap::insert(make_pair(move(id), move(mappedType))).second) - throw IdMapException::format("IdMapWrapper::add(id, value) called with pre-existing id '%s'", outputAny(id)); + throw IdMapException::format("IdMapWrapper::add(id, value) called with pre-existing id '{}'", outputAny(id)); } template diff --git a/source/core/StarImage.cpp b/source/core/StarImage.cpp index bd3e838..1494503 100644 --- a/source/core/StarImage.cpp +++ b/source/core/StarImage.cpp @@ -7,7 +7,7 @@ namespace Star { Image Image::readPng(IODevicePtr device) { auto logPngError = [](png_structp png_ptr, png_const_charp c) { - Logger::debug("PNG error in file: '%s', %s", (char*)png_get_error_ptr(png_ptr), c); + Logger::debug("PNG error in file: '{}', {}", (char*)png_get_error_ptr(png_ptr), c); }; auto readPngData = [](png_structp pngPtr, png_bytep data, png_size_t length) { @@ -19,7 +19,7 @@ Image Image::readPng(IODevicePtr device) { device->readFull((char*)header, sizeof(header)); if (png_sig_cmp(header, 0, sizeof(header))) - throw ImageException(strf("File %s is not a png image!", device->deviceName())); + throw ImageException(strf("File {} is not a png image!", device->deviceName())); png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr); if (!png_ptr) @@ -94,7 +94,7 @@ Image Image::readPng(IODevicePtr device) { if (bitdepth != 8 || (channels != 3 && channels != 4)) { png_destroy_read_struct(&png_ptr, &info_ptr, &end_info); - throw ImageException(strf("Unsupported PNG pixel format in file %s", device->deviceName())); + throw ImageException(strf("Unsupported PNG pixel format in file {}", device->deviceName())); } Image image(img_width, img_height, channels == 3 ? PixelFormat::RGB24 : PixelFormat::RGBA32); @@ -112,7 +112,7 @@ Image Image::readPng(IODevicePtr device) { tuple Image::readPngMetadata(IODevicePtr device) { auto logPngError = [](png_structp png_ptr, png_const_charp c) { - Logger::debug("PNG error in file: '%s', %s", (char*)png_get_error_ptr(png_ptr), c); + Logger::debug("PNG error in file: '{}', {}", (char*)png_get_error_ptr(png_ptr), c); }; auto readPngData = [](png_structp pngPtr, png_bytep data, png_size_t length) { @@ -124,7 +124,7 @@ tuple Image::readPngMetadata(IODevicePtr device) { device->readFull((char*)header, sizeof(header)); if (png_sig_cmp(header, 0, sizeof(header))) - throw ImageException(strf("File %s is not a png image!", device->deviceName())); + throw ImageException(strf("File {} is not a png image!", device->deviceName())); png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr); if (!png_ptr) @@ -267,7 +267,7 @@ void Image::reset(unsigned width, unsigned height, Maybe pf) { newData = (uint8_t*)Star::realloc(m_data, imageSize); if (!newData) - throw MemoryException::format("Could not allocate memory for new Image size %s\n", imageSize); + throw MemoryException::format("Could not allocate memory for new Image size {}\n", imageSize); m_data = newData; memset(m_data, 0, imageSize); @@ -316,7 +316,7 @@ void Image::fillRect(Vec2U const& pos, Vec2U const& size, Vec4B const& c) { void Image::set(Vec2U const& pos, Vec4B const& c) { if (pos[0] >= m_width || pos[1] >= m_height) { - throw ImageException(strf("%s out of range in Image::set", pos)); + throw ImageException(strf("{} out of range in Image::set", pos)); } else if (bytesPerPixel() == 4) { size_t offset = pos[1] * m_width * 4 + pos[0] * 4; m_data[offset] = c[0]; @@ -333,7 +333,7 @@ void Image::set(Vec2U const& pos, Vec4B const& c) { void Image::set(Vec2U const& pos, Vec3B const& c) { if (pos[0] >= m_width || pos[1] >= m_height) { - throw ImageException(strf("%s out of range in Image::set", pos)); + throw ImageException(strf("{} out of range in Image::set", pos)); } else if (bytesPerPixel() == 4) { size_t offset = pos[1] * m_width * 4 + pos[0] * 4; m_data[offset] = c[0]; @@ -351,7 +351,7 @@ void Image::set(Vec2U const& pos, Vec3B const& c) { Vec4B Image::get(Vec2U const& pos) const { Vec4B c; if (pos[0] >= m_width || pos[1] >= m_height) { - throw ImageException(strf("%s out of range in Image::get", pos)); + throw ImageException(strf("{} out of range in Image::get", pos)); } else if (bytesPerPixel() == 4) { size_t offset = pos[1] * m_width * 4 + pos[0] * 4; c[0] = m_data[offset]; @@ -422,7 +422,7 @@ Vec4B Image::clamprgb(Vec2I const& pos) const { Image Image::subImage(Vec2U const& pos, Vec2U const& size) const { if (pos[0] + size[0] > m_width || pos[1] + size[1] > m_height) - throw ImageException(strf("call to subImage with pos %s size %s out of image bounds (%s, %s)", pos, size, m_width, m_height)); + throw ImageException(strf("call to subImage with pos {} size {} out of image bounds ({}, {})", pos, size, m_width, m_height)); Image sub(size[0], size[1], m_pixelFormat); diff --git a/source/core/StarImageProcessing.cpp b/source/core/StarImageProcessing.cpp index 2c79b58..bf4d01a 100644 --- a/source/core/StarImageProcessing.cpp +++ b/source/core/StarImageProcessing.cpp @@ -199,7 +199,7 @@ ImageOperation imageOperationFromString(StringView string) { hexDecode(hexPtr, 8, c, 4); } else if (!which || (ptr != end && ++ptr != end)) - throw ImageOperationException(strf("Improper size for hex string '%s' in imageOperationFromString", StringView(hexPtr, hexLen)), false); + throw ImageOperationException(strf("Improper size for hex string '{}' in imageOperationFromString", StringView(hexPtr, hexLen)), false); else // we're in A of A=B. In vanilla only A=B pairs are evaluated, so only throw an exception if B is also there. return move(operation); @@ -341,7 +341,7 @@ ImageOperation imageOperationFromString(StringView string) { return FlipImageOperation{FlipImageOperation::FlipXY}; } else { - throw ImageOperationException(strf("Could not recognize ImageOperation type %s", type), false); + throw ImageOperationException(strf("Could not recognize ImageOperation type {}", type), false); } } catch (OutOfRangeException const& e) { throw ImageOperationException("Error reading ImageOperation", e); @@ -352,52 +352,52 @@ ImageOperation imageOperationFromString(StringView string) { String imageOperationToString(ImageOperation const& operation) { if (auto op = operation.ptr()) { - return strf("hueshift=%s", op->hueShiftAmount * 360.0f); + return strf("hueshift={}", op->hueShiftAmount * 360.0f); } else if (auto op = operation.ptr()) { - return strf("saturation=%s", op->saturationShiftAmount * 100.0f); + return strf("saturation={}", op->saturationShiftAmount * 100.0f); } else if (auto op = operation.ptr()) { - return strf("brightness=%s", (op->brightnessMultiply - 1.0f) * 100.0f); + return strf("brightness={}", (op->brightnessMultiply - 1.0f) * 100.0f); } else if (auto op = operation.ptr()) { - return strf("fade=%s=%s", Color::rgb(op->color).toHex(), op->amount); + return strf("fade={}={}", Color::rgb(op->color).toHex(), op->amount); } else if (auto op = operation.ptr()) { - return strf("scanlines=%s=%s=%s=%s", + return strf("scanlines={}={}={}={}", Color::rgb(op->fade1.color).toHex(), op->fade1.amount, Color::rgb(op->fade2.color).toHex(), op->fade2.amount); } else if (auto op = operation.ptr()) { - return strf("setcolor=%s", Color::rgb(op->color).toHex()); + return strf("setcolor={}", Color::rgb(op->color).toHex()); } else if (auto op = operation.ptr()) { String str = "replace"; for (auto const& pair : op->colorReplaceMap) - str += strf(";%s=%s", Color::rgba(pair.first).toHex(), Color::rgba(pair.second).toHex()); + str += strf(";{}={}", Color::rgba(pair.first).toHex(), Color::rgba(pair.second).toHex()); return str; } else if (auto op = operation.ptr()) { if (op->mode == AlphaMaskImageOperation::Additive) - return strf("addmask=%s;%s;%s", op->maskImages.join("+"), op->offset[0], op->offset[1]); + return strf("addmask={};{};{}", op->maskImages.join("+"), op->offset[0], op->offset[1]); else if (op->mode == AlphaMaskImageOperation::Subtractive) - return strf("submask=%s;%s;%s", op->maskImages.join("+"), op->offset[0], op->offset[1]); + return strf("submask={};{};{}", op->maskImages.join("+"), op->offset[0], op->offset[1]); } else if (auto op = operation.ptr()) { if (op->mode == BlendImageOperation::Multiply) - return strf("blendmult=%s;%s;%s", op->blendImages.join("+"), op->offset[0], op->offset[1]); + return strf("blendmult={};{};{}", op->blendImages.join("+"), op->offset[0], op->offset[1]); else if (op->mode == BlendImageOperation::Screen) - return strf("blendscreen=%s;%s;%s", op->blendImages.join("+"), op->offset[0], op->offset[1]); + return strf("blendscreen={};{};{}", op->blendImages.join("+"), op->offset[0], op->offset[1]); } else if (auto op = operation.ptr()) { - return strf("multiply=%s", Color::rgba(op->color).toHex()); + return strf("multiply={}", Color::rgba(op->color).toHex()); } else if (auto op = operation.ptr()) { if (op->outlineOnly) - return strf("outline=%d;%s;%s", op->pixels, Color::rgba(op->startColor).toHex(), Color::rgba(op->endColor).toHex()); + return strf("outline={};{};{}", op->pixels, Color::rgba(op->startColor).toHex(), Color::rgba(op->endColor).toHex()); else - return strf("border=%d;%s;%s", op->pixels, Color::rgba(op->startColor).toHex(), Color::rgba(op->endColor).toHex()); + return strf("border={};{};{}", op->pixels, Color::rgba(op->startColor).toHex(), Color::rgba(op->endColor).toHex()); } else if (auto op = operation.ptr()) { if (op->mode == ScaleImageOperation::Nearest) - return strf("scalenearest=%s", op->scale); + return strf("scalenearest={}", op->scale); else if (op->mode == ScaleImageOperation::Bilinear) - return strf("scalebilinear=%s", op->scale); + return strf("scalebilinear={}", op->scale); else if (op->mode == ScaleImageOperation::Bicubic) - return strf("scalebicubic=%s", op->scale); + return strf("scalebicubic={}", op->scale); } else if (auto op = operation.ptr()) { - return strf("crop=%s;%s;%s;%s", op->subset.xMin(), op->subset.xMax(), op->subset.yMin(), op->subset.yMax()); + return strf("crop={};{};{};{}", op->subset.xMin(), op->subset.xMax(), op->subset.yMin(), op->subset.yMax()); } else if (auto op = operation.ptr()) { if (op->mode == FlipImageOperation::FlipX) return "flipx"; diff --git a/source/core/StarJson.cpp b/source/core/StarJson.cpp index 9639ce4..2892e1c 100644 --- a/source/core/StarJson.cpp +++ b/source/core/StarJson.cpp @@ -24,7 +24,7 @@ Json::Type Json::typeFromName(String const& t) { else if (t == "null") return Type::Null; else - throw JsonException(strf("String '%s' is not a valid json type", t)); + throw JsonException(strf("String '{}' is not a valid json type", t)); } String Json::typeName(Type t) { @@ -180,7 +180,7 @@ double Json::toDouble() const { if (type() == Type::Int) return (double)m_data.get(); - throw JsonException::format("Improper conversion to double from %s", typeName()); + throw JsonException::format("Improper conversion to double from {}", typeName()); } float Json::toFloat() const { @@ -189,7 +189,7 @@ float Json::toFloat() const { bool Json::toBool() const { if (type() != Type::Bool) - throw JsonException::format("Improper conversion to bool from %s", typeName()); + throw JsonException::format("Improper conversion to bool from {}", typeName()); return m_data.get(); } @@ -199,7 +199,7 @@ int64_t Json::toInt() const { } else if (type() == Type::Int) { return m_data.get(); } else { - throw JsonException::format("Improper conversion to int from %s", typeName()); + throw JsonException::format("Improper conversion to int from {}", typeName()); } } @@ -209,43 +209,43 @@ uint64_t Json::toUInt() const { } else if (type() == Type::Int) { return (uint64_t)m_data.get(); } else { - throw JsonException::format("Improper conversion to unsigned int from %s", typeName()); + throw JsonException::format("Improper conversion to unsigned int from {}", typeName()); } } String Json::toString() const { if (type() != Type::String) - throw JsonException(strf("Cannot convert from %s to string", typeName())); + throw JsonException(strf("Cannot convert from {} to string", typeName())); return *m_data.get(); } JsonArray Json::toArray() const { if (type() != Type::Array) - throw JsonException::format("Improper conversion to JsonArray from %s", typeName()); + throw JsonException::format("Improper conversion to JsonArray from {}", typeName()); return *m_data.get(); } JsonObject Json::toObject() const { if (type() != Type::Object) - throw JsonException::format("Improper conversion to JsonObject from %s", typeName()); + throw JsonException::format("Improper conversion to JsonObject from {}", typeName()); return *m_data.get(); } StringConstPtr Json::stringPtr() const { if (type() != Type::String) - throw JsonException(strf("Cannot convert from %s to string", typeName())); + throw JsonException(strf("Cannot convert from {} to string", typeName())); return m_data.get(); } JsonArrayConstPtr Json::arrayPtr() const { if (type() != Type::Array) - throw JsonException::format("Improper conversion to JsonArray from %s", typeName()); + throw JsonException::format("Improper conversion to JsonArray from {}", typeName()); return m_data.get(); } JsonObjectConstPtr Json::objectPtr() const { if (type() != Type::Object) - throw JsonException::format("Improper conversion to JsonObject from %s", typeName()); + throw JsonException::format("Improper conversion to JsonObject from {}", typeName()); return m_data.get(); } @@ -330,7 +330,7 @@ bool Json::contains(String const& key) const { Json Json::get(size_t index) const { if (auto p = ptr(index)) return *p; - throw JsonException(strf("Json::get(%s) out of range", index)); + throw JsonException(strf("Json::get({}) out of range", index)); } double Json::getDouble(size_t index) const { @@ -422,7 +422,7 @@ JsonObject Json::getObject(size_t index, JsonObject def) const { Json Json::get(String const& key) const { if (auto p = ptr(key)) return *p; - throw JsonException(strf("No such key in Json::get(\"%s\")", key)); + throw JsonException(strf("No such key in Json::get(\"{}\")", key)); } double Json::getDouble(String const& key) const { @@ -822,7 +822,7 @@ Json Json::convert(Type u) const { case Type::Object: return toObject(); default: - throw JsonException::format("Improper conversion to type %s", typeName(u)); + throw JsonException::format("Improper conversion to type {}", typeName(u)); } } @@ -997,7 +997,7 @@ size_t hash::operator()(Json const& v) const { Json const* Json::ptr(size_t index) const { if (type() != Type::Array) - throw JsonException::format("Cannot call get with index on Json type %s, must be Array type", typeName()); + throw JsonException::format("Cannot call get with index on Json type {}, must be Array type", typeName()); auto const& list = *m_data.get(); if (index >= list.size()) @@ -1007,7 +1007,7 @@ Json const* Json::ptr(size_t index) const { Json const* Json::ptr(String const& key) const { if (type() != Type::Object) - throw JsonException::format("Cannot call get with key on Json type %s, must be Object type", typeName()); + throw JsonException::format("Cannot call get with key on Json type {}, must be Object type", typeName()); auto const& map = m_data.get(); auto i = map->find(key); diff --git a/source/core/StarJsonBuilder.cpp b/source/core/StarJsonBuilder.cpp index 432cef9..6084c40 100644 --- a/source/core/StarJsonBuilder.cpp +++ b/source/core/StarJsonBuilder.cpp @@ -21,7 +21,7 @@ void JsonBuilderStream::endObject() { Json v = pop(); String k = pop().toString(); if (!object.insert(k, move(v)).second) - throw JsonParsingException(strf("Json object contains a duplicate entry for key '%s'", k)); + throw JsonParsingException(strf("Json object contains a duplicate entry for key '{}'", k)); } } } diff --git a/source/core/StarJsonBuilder.hpp b/source/core/StarJsonBuilder.hpp index cd2d42d..6be9e54 100644 --- a/source/core/StarJsonBuilder.hpp +++ b/source/core/StarJsonBuilder.hpp @@ -62,9 +62,9 @@ Json inputUtf8Json(InputIterator begin, InputIterator end, bool fragment) { Utf32Input pend = parser.parse(wbegin, wend, fragment); if (parser.error()) - throw JsonParsingException(strf("Error parsing json: %s at %s:%s", parser.error(), parser.line(), parser.column())); + throw JsonParsingException(strf("Error parsing json: {} at {}:{}", parser.error(), parser.line(), parser.column())); else if (pend != wend) - throw JsonParsingException(strf("Error extra data at end of input at %s:%s", parser.line(), parser.column())); + throw JsonParsingException(strf("Error extra data at end of input at {}:{}", parser.line(), parser.column())); return stream.takeTop(); } @@ -85,9 +85,9 @@ Jsonlike inputUtf32Json(InputIterator begin, InputIterator end, bool fragment) { InputIterator pend = parser.parse(begin, end, fragment); if (parser.error()) { - throw JsonParsingException(strf("Error parsing json: %s at %s:%s", parser.error(), parser.line(), parser.column())); + throw JsonParsingException(strf("Error parsing json: {} at {}:{}", parser.error(), parser.line(), parser.column())); } else if (pend != end) { - throw JsonParsingException(strf("Error extra data at end of input at %s:%s", parser.line(), parser.column())); + throw JsonParsingException(strf("Error extra data at end of input at {}:{}", parser.line(), parser.column())); } return stream.takeTop(); diff --git a/source/core/StarJsonExtra.cpp b/source/core/StarJsonExtra.cpp index d683ca1..ec6fe90 100644 --- a/source/core/StarJsonExtra.cpp +++ b/source/core/StarJsonExtra.cpp @@ -147,7 +147,7 @@ RectD jsonToRectD(Json const& v) { auto upperRight = jsonToVec2D(v.get(1)); return RectD(lowerLeft, upperRight); } catch (JsonException const& e) { - throw JsonException(strf("Inner position not well formed in jsonToRectD: %s", outputException(e, true))); + throw JsonException(strf("Inner position not well formed in jsonToRectD: {}", outputException(e, true))); } } @@ -178,7 +178,7 @@ RectI jsonToRectI(Json const& v) { auto upperRight = jsonToVec2I(v.get(1)); return RectI(lowerLeft, upperRight); } catch (JsonException const& e) { - throw JsonException(strf("Inner position not well formed in jsonToRectI: %s", outputException(e, true))); + throw JsonException(strf("Inner position not well formed in jsonToRectI: {}", outputException(e, true))); } } @@ -201,7 +201,7 @@ RectU jsonToRectU(Json const& v) { auto upperRight = jsonToVec2U(v.get(1)); return RectU(lowerLeft, upperRight); } catch (JsonException const& e) { - throw JsonException(strf("Inner position not well formed in jsonToRectU: %s", outputException(e, true))); + throw JsonException(strf("Inner position not well formed in jsonToRectU: {}", outputException(e, true))); } } @@ -226,7 +226,7 @@ Color jsonToColor(Json const& v) { } else if (v.type() == Json::Type::String) { return Color(v.toString()); } else { - throw JsonException(strf("Json of type %s cannot be converted to color", v.typeName())); + throw JsonException(strf("Json of type {} cannot be converted to color", v.typeName())); } } diff --git a/source/core/StarJsonExtra.hpp b/source/core/StarJsonExtra.hpp index cfe7efb..66d89d6 100644 --- a/source/core/StarJsonExtra.hpp +++ b/source/core/StarJsonExtra.hpp @@ -106,7 +106,7 @@ Json jsonFromWeightedPool(WeightedPool const& pool, Converter&& converter); template Array jsonToArrayU(Json const& v) { if (v.size() != Size) - throw JsonException(strf("Json array not of size %d in jsonToArrayU", Size).c_str()); + throw JsonException(strf("Json array not of size {} in jsonToArrayU", Size).c_str()); Array res; for (size_t i = 0; i < Size; i++) { @@ -119,7 +119,7 @@ Array jsonToArrayU(Json const& v) { template Array jsonToArrayS(Json const& v) { if (v.size() != Size) - throw JsonException(strf("Json array not of size %d in jsonToArrayS", Size).c_str()); + throw JsonException(strf("Json array not of size {} in jsonToArrayS", Size).c_str()); Array res; for (size_t i = 0; i < Size; i++) { @@ -132,7 +132,7 @@ Array jsonToArrayS(Json const& v) { template Array jsonToArrayI(Json const& v) { if (v.size() != Size) - throw JsonException(strf("Json array not of size %d in jsonToArrayI", Size).c_str()); + throw JsonException(strf("Json array not of size {} in jsonToArrayI", Size).c_str()); Array res; for (size_t i = 0; i < Size; i++) { @@ -145,7 +145,7 @@ Array jsonToArrayI(Json const& v) { template Array jsonToArrayF(Json const& v) { if (v.size() != Size) - throw JsonException(strf("Json array not of size %d in jsonToArrayF", Size).c_str()); + throw JsonException(strf("Json array not of size {} in jsonToArrayF", Size).c_str()); Array res; for (size_t i = 0; i < Size; i++) { @@ -158,7 +158,7 @@ Array jsonToArrayF(Json const& v) { template Array jsonToArrayD(Json const& v) { if (v.size() != Size) - throw JsonException(strf("Json array not of size %d in jsonToArrayD", Size).c_str()); + throw JsonException(strf("Json array not of size {} in jsonToArrayD", Size).c_str()); Array res; for (size_t i = 0; i < Size; i++) { @@ -171,7 +171,7 @@ Array jsonToArrayD(Json const& v) { template Array jsonToStringArray(Json const& v) { if (v.size() != Size) - throw JsonException(strf("Json array not of size %d in jsonToStringArray", Size).c_str()); + throw JsonException(strf("Json array not of size {} in jsonToStringArray", Size).c_str()); Array res; for (size_t i = 0; i < Size; i++) { diff --git a/source/core/StarJsonPatch.cpp b/source/core/StarJsonPatch.cpp index e1ab6de..34c6a82 100644 --- a/source/core/StarJsonPatch.cpp +++ b/source/core/StarJsonPatch.cpp @@ -12,7 +12,7 @@ Json jsonPatch(Json const& base, JsonArray const& patch) { } return res; } catch (JsonException const& e) { - throw JsonPatchException(strf("Could not apply patch to base. %s", e.what())); + throw JsonPatchException(strf("Could not apply patch to base. {}", e.what())); } } @@ -32,9 +32,9 @@ namespace JsonPatching { auto operation = op.getString("op"); return JsonPatching::functionMap.get(operation)(base, op); } catch (JsonException const& e) { - throw JsonPatchException(strf("Could not apply operation to base. %s", e.what())); + throw JsonPatchException(strf("Could not apply operation to base. {}", e.what())); } catch (MapException const&) { - throw JsonPatchException(strf("Invalid operation: %s", op.getString("op"))); + throw JsonPatchException(strf("Invalid operation: {}", op.getString("op"))); } } @@ -49,7 +49,7 @@ namespace JsonPatching { auto testValue = pointer.get(base); if (!value) { if (inverseTest) - throw JsonPatchTestFail(strf("Test operation failure, expected %s to be missing.", op.getString("path"))); + throw JsonPatchTestFail(strf("Test operation failure, expected {} to be missing.", op.getString("path"))); return base; } @@ -57,11 +57,11 @@ namespace JsonPatching { return base; } - throw JsonPatchTestFail(strf("Test operation failure, expected %s found %s.", value, testValue)); + throw JsonPatchTestFail(strf("Test operation failure, expected {} found {}.", value, testValue)); } catch (JsonPath::TraversalException& e) { if (inverseTest) return base; - throw JsonPatchTestFail(strf("Test operation failure: %s", e.what())); + throw JsonPatchTestFail(strf("Test operation failure: {}", e.what())); } } diff --git a/source/core/StarJsonPath.cpp b/source/core/StarJsonPath.cpp index 9eb5fae..c03e883 100644 --- a/source/core/StarJsonPath.cpp +++ b/source/core/StarJsonPath.cpp @@ -8,21 +8,21 @@ namespace JsonPath { buffer.clear(); if (*iterator != '/') - throw ParsingException::format("Missing leading '/' in Json pointer \"%s\"", path); + throw ParsingException::format("Missing leading '/' in Json pointer \"{}\"", path); iterator++; while (iterator != end && *iterator != '/') { if (*iterator == '~') { ++iterator; if (iterator == end) - throw ParsingException::format("Incomplete escape sequence in Json pointer \"%s\"", path); + throw ParsingException::format("Incomplete escape sequence in Json pointer \"{}\"", path); if (*iterator == '0') buffer.append('~'); else if (*iterator == '1') buffer.append('/'); else - throw ParsingException::format("Invalid escape sequence in Json pointer \"%s\"", path); + throw ParsingException::format("Invalid escape sequence in Json pointer \"{}\"", path); ++iterator; } else buffer.append(*iterator++); @@ -38,7 +38,7 @@ namespace JsonPath { buffer.clear(); if (*iterator == '.') { - throw ParsingException::format("Entry starts with '.' in query path \"%s\"", path); + throw ParsingException::format("Entry starts with '.' in query path \"{}\"", path); } else if (*iterator == '[') { // Parse array number and ']' @@ -49,7 +49,7 @@ namespace JsonPath { buffer.append(*iterator++); if (iterator == end || *iterator != ']') - throw ParsingException::format("Array has no trailing ']' or has invalid character in query path \"%s\"", path); + throw ParsingException::format("Array has no trailing ']' or has invalid character in query path \"{}\"", path); // Consume trailing ']' ++iterator; diff --git a/source/core/StarJsonPath.hpp b/source/core/StarJsonPath.hpp index 0f0efa9..bd60dad 100644 --- a/source/core/StarJsonPath.hpp +++ b/source/core/StarJsonPath.hpp @@ -143,24 +143,24 @@ namespace JsonPath { if (value.type() == Json::Type::Array) { if (buffer == "-") - throw TraversalException::format("Tried to get key '%s' in non-object type in pathGet(\"%s\")", buffer, path); + throw TraversalException::format("Tried to get key '{}' in non-object type in pathGet(\"{}\")", buffer, path); Maybe i = maybeLexicalCast(buffer); if (!i) - throw TraversalException::format("Cannot parse '%s' as index in pathGet(\"%s\")", buffer, path); + throw TraversalException::format("Cannot parse '{}' as index in pathGet(\"{}\")", buffer, path); if (*i < value.size()) value = value.get(*i); else - throw TraversalException::format("Index %s out of range in pathGet(\"%s\")", buffer, path); + throw TraversalException::format("Index {} out of range in pathGet(\"{}\")", buffer, path); } else if (value.type() == Json::Type::Object) { if (value.contains(buffer)) value = value.get(buffer); else - throw TraversalException::format("No such key '%s' in pathGet(\"%s\")", buffer, path); + throw TraversalException::format("No such key '{}' in pathGet(\"{}\")", buffer, path); } else { - throw TraversalException::format("Tried to get key '%s' in non-object type in pathGet(\"%s\")", buffer, path); + throw TraversalException::format("Tried to get key '{}' in non-object type in pathGet(\"{}\")", buffer, path); } } return value; @@ -218,10 +218,10 @@ namespace JsonPath { } else { Maybe i = maybeLexicalCast(buffer); if (!i) - throw TraversalException::format("Cannot parse '%s' as index in pathApply(\"%s\")", buffer, path); + throw TraversalException::format("Cannot parse '{}' as index in pathApply(\"{}\")", buffer, path); if (*i >= value.size()) - throw TraversalException::format("Index %s out of range in pathApply(\"%s\")", buffer, path); + throw TraversalException::format("Index {} out of range in pathApply(\"{}\")", buffer, path); return value.set(*i, pathApply(buffer, value.get(*i), parser, path, iterator, op)); } @@ -232,7 +232,7 @@ namespace JsonPath { } else { if (!value.contains(buffer)) - throw TraversalException::format("No such key '%s' in pathApply(\"%s\")", buffer, path); + throw TraversalException::format("No such key '{}' in pathApply(\"{}\")", buffer, path); Jsonlike newChild = pathApply(buffer, value.get(buffer), parser, path, iterator, op); iterator = current; @@ -242,7 +242,7 @@ namespace JsonPath { } } else { - throw TraversalException::format("Tried to get key '%s' in non-object type in pathApply(\"%s\")", buffer, path); + throw TraversalException::format("Tried to get key '{}' in non-object type in pathApply(\"{}\")", buffer, path); } } @@ -262,16 +262,16 @@ namespace JsonPath { return arrayOp(parent, {}); Maybe i = maybeLexicalCast(*key); if (!i) - throw TraversalException::format("Cannot parse '%s' as index in Json path \"%s\"", *key, path); + throw TraversalException::format("Cannot parse '{}' as index in Json path \"{}\"", *key, path); if (i && *i > parent.size()) - throw TraversalException::format("Index %s out of range in Json path \"%s\"", *key, path); + throw TraversalException::format("Index {} out of range in Json path \"{}\"", *key, path); if (i && *i == parent.size()) i = {}; return arrayOp(parent, i); } else if (parent.type() == Json::Type::Object) { return objectOp(parent, *key); } else { - throw TraversalException::format("Tried to set key '%s' in non-object type in pathSet(\"%s\")", *key, path); + throw TraversalException::format("Tried to set key '{}' in non-object type in pathSet(\"{}\")", *key, path); } }; } @@ -297,7 +297,7 @@ namespace JsonPath { EmptyPathOp emptyPathOp = [](Jsonlike const&) { return Json{}; }; ObjectOp objectOp = [](Jsonlike const& object, String const& key) { if (!object.contains(key)) - throw TraversalException::format("Could not find \"%s\" to remove", key); + throw TraversalException::format("Could not find \"{}\" to remove", key); return object.eraseKey(key); }; ArrayOp arrayOp = [](Jsonlike const& array, Maybe i) { diff --git a/source/core/StarJsonRpc.cpp b/source/core/StarJsonRpc.cpp index 60779b9..f6def8f 100644 --- a/source/core/StarJsonRpc.cpp +++ b/source/core/StarJsonRpc.cpp @@ -12,7 +12,7 @@ JsonRpc::JsonRpc() { void JsonRpc::registerHandler(String const& handler, JsonRpcRemoteFunction func) { if (m_handlers.contains(handler)) - throw JsonRpcException(strf("Handler by that name already exists '%s'", handler)); + throw JsonRpcException(strf("Handler by that name already exists '{}'", handler)); m_handlers.add(handler, move(func)); } @@ -23,7 +23,7 @@ void JsonRpc::registerHandlers(JsonRpcHandlers const& handlers) { void JsonRpc::removeHandler(String const& handler) { if (!m_handlers.contains(handler)) - throw JsonRpcException(strf("No such handler by the name '%s'", handler)); + throw JsonRpcException(strf("No such handler by the name '{}'", handler)); m_handlers.remove(handler); } @@ -76,14 +76,14 @@ void JsonRpc::receive(ByteArray const& inbuffer) { try { auto handlerName = request.getString("handler"); if (!m_handlers.contains(handlerName)) - throw JsonRpcException(strf("Unknown handler '%s'", handlerName)); + throw JsonRpcException(strf("Unknown handler '{}'", handlerName)); m_pending.append(JsonObject{ {"command", "response"}, {"id", request.get("id")}, {"result", m_handlers[handlerName](request.get("arguments"))} }); } catch (std::exception& e) { - Logger::error("Exception while handling variant rpc request handler call. %s", outputException(e, false)); + Logger::error("Exception while handling variant rpc request handler call. {}", outputException(e, false)); JsonObject response; response["command"] = "fail"; response["id"] = request.get("id"); @@ -98,7 +98,7 @@ void JsonRpc::receive(ByteArray const& inbuffer) { auto responseHandler = m_pendingResponse.take(request.getUInt("id")); responseHandler.fulfill(request.get("result")); } catch (std::exception& e) { - Logger::error("Exception while handling variant rpc response handler call. %s", outputException(e, true)); + Logger::error("Exception while handling variant rpc response handler call. {}", outputException(e, true)); } } else if (request.get("command") == "fail") { @@ -106,7 +106,7 @@ void JsonRpc::receive(ByteArray const& inbuffer) { auto responseHandler = m_pendingResponse.take(request.getUInt("id")); responseHandler.fulfill({}); } catch (std::exception& e) { - Logger::error("Exception while handling variant rpc failure handler call. %s", outputException(e, true)); + Logger::error("Exception while handling variant rpc failure handler call. {}", outputException(e, true)); } } } diff --git a/source/core/StarLexicalCast.hpp b/source/core/StarLexicalCast.hpp index 6359591..40e6d6d 100644 --- a/source/core/StarLexicalCast.hpp +++ b/source/core/StarLexicalCast.hpp @@ -39,7 +39,7 @@ Type lexicalCast(StringView s, std::ios_base::fmtflags flags = std::ios_base::bo if (m) return m.take(); else - throw BadLexicalCast(strf("Lexical cast failed on '%s'", s)); + throw BadLexicalCast(strf("Lexical cast failed on '{}'", s)); } template diff --git a/source/core/StarList.hpp b/source/core/StarList.hpp index e097721..49d2f84 100644 --- a/source/core/StarList.hpp +++ b/source/core/StarList.hpp @@ -668,14 +668,14 @@ size_t RandomAccessListMixin::lastIndexOf(const_reference e, size_t ti template auto RandomAccessListMixin::at(size_t n) const -> const_reference { if (n >= Base::size()) - throw OutOfRangeException(strf("out of range list::at(%s)", n)); + throw OutOfRangeException(strf("out of range list::at({})", n)); return operator[](n); } template auto RandomAccessListMixin::at(size_t n) -> reference { if (n >= Base::size()) - throw OutOfRangeException(strf("out of range list::at(%s)", n)); + throw OutOfRangeException(strf("out of range list::at({})", n)); return operator[](n); } diff --git a/source/core/StarLockFile_unix.cpp b/source/core/StarLockFile_unix.cpp index 9677f2d..298c636 100644 --- a/source/core/StarLockFile_unix.cpp +++ b/source/core/StarLockFile_unix.cpp @@ -39,7 +39,7 @@ bool LockFile::lock(int64_t timeout) { auto doFLock = [](String const& filename, bool block) -> shared_ptr { int fd = open(filename.utf8Ptr(), O_RDONLY | O_CREAT, 0644); if (fd < 0) - throw StarException(strf("Could not open lock file %s, %s\n", filename, strerror(errno))); + throw StarException(strf("Could not open lock file {}, {}\n", filename, strerror(errno))); int ret; if (block) @@ -50,7 +50,7 @@ bool LockFile::lock(int64_t timeout) { if (ret != 0) { close(fd); if (errno != EWOULDBLOCK) - throw StarException(strf("Could not lock file %s, %s\n", filename, strerror(errno))); + throw StarException(strf("Could not lock file {}, {}\n", filename, strerror(errno))); return {}; } diff --git a/source/core/StarLockFile_windows.cpp b/source/core/StarLockFile_windows.cpp index 1cf1473..33692fb 100644 --- a/source/core/StarLockFile_windows.cpp +++ b/source/core/StarLockFile_windows.cpp @@ -41,7 +41,7 @@ bool LockFile::lock(int64_t timeout) { if (handle == INVALID_HANDLE_VALUE) { if (GetLastError() == ERROR_SHARING_VIOLATION) return {}; - throw StarException(strf("Could not open lock file %s, error code %s\n", filename, GetLastError())); + throw StarException(strf("Could not open lock file {}, error code {}\n", filename, GetLastError())); } return make_shared(handle); diff --git a/source/core/StarLogging.cpp b/source/core/StarLogging.cpp index 2a7f88e..55cd27d 100644 --- a/source/core/StarLogging.cpp +++ b/source/core/StarLogging.cpp @@ -24,7 +24,7 @@ LogLevel LogSink::level() { void StdoutLogSink::log(char const* msg, LogLevel level) { MutexLocker locker(m_logMutex); - coutf("[%s] %s\n", LogLevelNames.getRight(level), msg); + coutf("[{}] {}\n", LogLevelNames.getRight(level), msg); } FileLogSink::FileLogSink(String const& filename, LogLevel level, bool truncate) { @@ -37,7 +37,7 @@ FileLogSink::FileLogSink(String const& filename, LogLevel level, bool truncate) void FileLogSink::log(char const* msg, LogLevel level) { MutexLocker locker(m_logMutex); - auto line = strf("[%s] [%s] %s\n", Time::printCurrentDateAndTime("::."), LogLevelNames.getRight(level), msg); + auto line = strf("[{}] [{}] {}\n", Time::printCurrentDateAndTime("::."), LogLevelNames.getRight(level), msg); m_output->write(line.data(), line.size()); } diff --git a/source/core/StarLogging.hpp b/source/core/StarLogging.hpp index d90e0e1..ae47e40 100644 --- a/source/core/StarLogging.hpp +++ b/source/core/StarLogging.hpp @@ -185,7 +185,7 @@ void Logger::error(char const* msg, Args const&... args) { template void LogMap::set(String const& key, T const& t) { - setValue(key, strf("%s", t)); + setValue(key, strf("{}", t)); } } diff --git a/source/core/StarLua.cpp b/source/core/StarLua.cpp index 6034c06..eb8541c 100644 --- a/source/core/StarLua.cpp +++ b/source/core/StarLua.cpp @@ -65,7 +65,7 @@ LuaCallbacks& LuaCallbacks::merge(LuaCallbacks const& callbacks) { for (auto const& pair : callbacks.m_callbacks) m_callbacks.add(pair.first, pair.second); } catch (MapException const& e) { - throw LuaException(strf("Failed to merge LuaCallbacks: %s", outputException(e, true))); + throw LuaException(strf("Failed to merge LuaCallbacks: {}", outputException(e, true))); } return *this; @@ -481,7 +481,7 @@ void LuaEngine::threadPushFunction(int threadIndex, int functionIndex) { int status = lua_status(thread); lua_Debug ar; if (status != LUA_OK || lua_getstack(thread, 0, &ar) > 0 || lua_gettop(thread) > 0) - throw LuaException(strf("Cannot push function to active or errored thread with status %s", status)); + throw LuaException(strf("Cannot push function to active or errored thread with status {}", status)); pushHandle(thread, functionIndex); } @@ -633,9 +633,9 @@ void LuaEngine::handleError(lua_State* state, int res) { String error; if (lua_isstring(state, -1)) - error = strf("Error code %s, %s", res, lua_tostring(state, -1)); + error = strf("Error code {}, {}", res, lua_tostring(state, -1)); else - error = strf("Error code %s, ", res); + error = strf("Error code {}, ", res); lua_pop(state, 1); diff --git a/source/core/StarLua.hpp b/source/core/StarLua.hpp index 95b4499..9241ec4 100644 --- a/source/core/StarLua.hpp +++ b/source/core/StarLua.hpp @@ -1717,20 +1717,20 @@ T& LuaUserData::get() const { template void LuaCallbacks::registerCallback(String name, Function&& func) { if (!m_callbacks.insert(name, LuaDetail::wrapFunction(forward(func))).second) - throw LuaException::format("Lua callback '%s' was registered twice", name); + throw LuaException::format("Lua callback '{}' was registered twice", name); } template void LuaCallbacks::registerCallbackWithSignature(String name, Function&& func) { if (!m_callbacks.insert(name, LuaDetail::wrapFunctionWithSignature(forward(func))).second) - throw LuaException::format("Lua callback '%s' was registered twice", name); + throw LuaException::format("Lua callback '{}' was registered twice", name); } template template void LuaMethods::registerMethod(String name, Function&& func) { if (!m_methods.insert(name, LuaDetail::wrapMethod(forward(move(func)))).second) - throw LuaException::format("Lua method '%s' was registered twice", name); + throw LuaException::format("Lua method '{}' was registered twice", name); } template @@ -1738,7 +1738,7 @@ template void LuaMethods::registerMethodWithSignature(String name, Function&& func) { if (!m_methods.insert(name, LuaDetail::wrapMethodWithSignature(forward(move(func)))) .second) - throw LuaException::format("Lua method '%s' was registered twice", name); + throw LuaException::format("Lua method '{}' was registered twice", name); } template @@ -1766,7 +1766,7 @@ Ret LuaContext::invokePath(String const& key, Args const&... args) const { auto p = getPath(key); if (auto f = p.ptr()) return f->invoke(args...); - throw LuaException::format("invokePath called on path '%s' which is not function type", key); + throw LuaException::format("invokePath called on path '{}' which is not function type", key); } template @@ -1867,14 +1867,14 @@ template T LuaEngine::luaTo(LuaValue&& v) { if (auto res = luaMaybeTo(move(v))) return res.take(); - throw LuaConversionException::format("Error converting LuaValue to type '%s'", typeid(T).name()); + throw LuaConversionException::format("Error converting LuaValue to type '{}'", typeid(T).name()); } template T LuaEngine::luaTo(LuaValue const& v) { if (auto res = luaMaybeTo(v)) return res.take(); - throw LuaConversionException::format("Error converting LuaValue to type '%s'", typeid(T).name()); + throw LuaConversionException::format("Error converting LuaValue to type '{}'", typeid(T).name()); } template @@ -2089,7 +2089,7 @@ template T* LuaEngine::getUserData(int handleIndex) { int typeRef = m_registeredUserDataTypes.value(typeid(T), LUA_NOREF); if (typeRef == LUA_NOREF) - throw LuaException::format("Cannot convert userdata type of %s, not registered", typeid(T).name()); + throw LuaException::format("Cannot convert userdata type of {}, not registered", typeid(T).name()); lua_checkstack(m_state, 3); @@ -2103,7 +2103,7 @@ T* LuaEngine::getUserData(int handleIndex) { lua_rawgeti(m_state, LUA_REGISTRYINDEX, typeRef); if (!lua_rawequal(m_state, -1, -2)) { lua_pop(m_state, 3); - throw LuaException::format("Improper conversion from userdata to type %s", typeid(T).name()); + throw LuaException::format("Improper conversion from userdata to type {}", typeid(T).name()); } lua_pop(m_state, 3); diff --git a/source/core/StarMap.hpp b/source/core/StarMap.hpp index e4941f3..cf9c260 100644 --- a/source/core/StarMap.hpp +++ b/source/core/StarMap.hpp @@ -163,7 +163,7 @@ template auto MapMixin::take(key_type const& k) -> mapped_type { if (auto v = maybeTake(k)) return v.take(); - throw MapException(strf("Key '%s' not found in Map::take()", outputAny(k))); + throw MapException(strf("Key '{}' not found in Map::take()", outputAny(k))); } template @@ -182,7 +182,7 @@ template auto MapMixin::get(key_type const& k) -> mapped_type& { iterator i = Base::find(k); if (i == Base::end()) - throw MapException(strf("Key '%s' not found in Map::get()", outputAny(k))); + throw MapException(strf("Key '{}' not found in Map::get()", outputAny(k))); return i->second; } @@ -190,7 +190,7 @@ template auto MapMixin::get(key_type const& k) const -> mapped_type const& { const_iterator i = Base::find(k); if (i == Base::end()) - throw MapException(strf("Key '%s' not found in Map::get()", outputAny(k))); + throw MapException(strf("Key '{}' not found in Map::get()", outputAny(k))); return i->second; } @@ -236,7 +236,7 @@ auto MapMixin::keyOf(mapped_type const& v) const -> key_type { if (i->second == v) return i->first; } - throw MapException(strf("Value '%s' not found in Map::keyOf()", outputAny(v))); + throw MapException(strf("Value '{}' not found in Map::keyOf()", outputAny(v))); } template @@ -267,7 +267,7 @@ template auto MapMixin::add(key_type k, mapped_type v) -> mapped_type& { auto pair = Base::insert(value_type(move(k), move(v))); if (!pair.second) - throw MapException(strf("Entry with key '%s' already present.", outputAny(k))); + throw MapException(strf("Entry with key '{}' already present.", outputAny(k))); else return pair.first->second; } diff --git a/source/core/StarMultiArray.hpp b/source/core/StarMultiArray.hpp index f2cf155..3668c8a 100644 --- a/source/core/StarMultiArray.hpp +++ b/source/core/StarMultiArray.hpp @@ -291,7 +291,7 @@ template Element const& MultiArray::at(IndexArray const& index) const { for (size_t i = Rank; i != 0; --i) { if (index[i - 1] >= m_shape[i - 1]) - throw MultiArrayException(strf("Out of bounds on MultiArray::at(%s)", index)); + throw MultiArrayException(strf("Out of bounds on MultiArray::at({})", index)); } return m_data[storageIndex(index)]; @@ -301,7 +301,7 @@ template Element& MultiArray::at(IndexArray const& index) { for (size_t i = Rank; i != 0; --i) { if (index[i - 1] >= m_shape[i - 1]) - throw MultiArrayException(strf("Out of bounds on MultiArray::at(%s)", index)); + throw MultiArrayException(strf("Out of bounds on MultiArray::at({})", index)); } return m_data[storageIndex(index)]; @@ -323,7 +323,7 @@ template void MultiArray::set(IndexArray const& index, Element element) { for (size_t i = Rank; i != 0; --i) { if (index[i - 1] >= m_shape[i - 1]) - throw MultiArrayException(strf("Out of bounds on MultiArray::set(%s)", index)); + throw MultiArrayException(strf("Out of bounds on MultiArray::set({})", index)); } m_data[storageIndex(index)] = move(element); diff --git a/source/core/StarNetElementContainers.hpp b/source/core/StarNetElementContainers.hpp index 5c2fd71..2127076 100644 --- a/source/core/StarNetElementContainers.hpp +++ b/source/core/StarNetElementContainers.hpp @@ -266,7 +266,7 @@ auto NetElementMapWrapper::insert(key_type k, mapped_type v) -> pair void NetElementMapWrapper::add(key_type k, mapped_type v) { if (!insert(value_type(move(k), move(v))).second) - throw MapException::format("Entry with key '%s' already present.", outputAny(k)); + throw MapException::format("Entry with key '{}' already present.", outputAny(k)); } template @@ -321,7 +321,7 @@ template auto NetElementMapWrapper::take(key_type const& k) -> mapped_type { auto i = BaseMap::find(k); if (i == BaseMap::end()) - throw MapException::format("Key '%s' not found in Map::take()", outputAny(k)); + throw MapException::format("Key '{}' not found in Map::take()", outputAny(k)); auto m = move(i->second); erase(i); return m; diff --git a/source/core/StarNetImpl.hpp b/source/core/StarNetImpl.hpp index 80d75da..076b181 100644 --- a/source/core/StarNetImpl.hpp +++ b/source/core/StarNetImpl.hpp @@ -57,7 +57,7 @@ inline String netErrorString() { return result; #else - return strf("%s - %s", errno, strerror(errno)); + return strf("{} - {}", errno, strerror(errno)); #endif } @@ -144,7 +144,7 @@ struct SocketImpl { int ret = ::setsockopt(socketDesc, level, optname, optval, len); #endif if (ret < 0) - throw NetworkException(strf("setSockOpt failed to set %d, %d: %s", level, optname, netErrorString())); + throw NetworkException(strf("setSockOpt failed to set {}, {}: {}", level, optname, netErrorString())); } #ifdef STAR_SYSTEM_FAMILY_WINDOWS diff --git a/source/core/StarOptionParser.cpp b/source/core/StarOptionParser.cpp index ecf6e28..f849f43 100644 --- a/source/core/StarOptionParser.cpp +++ b/source/core/StarOptionParser.cpp @@ -17,12 +17,12 @@ void OptionParser::setAdditionalHelp(String help) { void OptionParser::addSwitch(String const& flag, String description) { if (!m_options.insert(flag, Switch{flag, move(description)}).second) - throw OptionParserException::format("Duplicate switch '-%s' added", flag); + throw OptionParserException::format("Duplicate switch '-{}' added", flag); } void OptionParser::addParameter(String const& flag, String argument, RequirementMode requirementMode, String description) { if (!m_options.insert(flag, Parameter{flag, move(argument), requirementMode, move(description)}).second) - throw OptionParserException::format("Duplicate flag '-%s' added", flag); + throw OptionParserException::format("Duplicate flag '-{}' added", flag); } void OptionParser::addArgument(String argument, RequirementMode requirementMode, String description) { @@ -46,7 +46,7 @@ pair OptionParser::parseOptions(StringList co String flag = arg.substr(1); auto option = m_options.maybe(flag); if (!option) { - errors.append(strf("No such option '-%s'", flag)); + errors.append(strf("No such option '-{}'", flag)); continue; } @@ -55,12 +55,12 @@ pair OptionParser::parseOptions(StringList co } else { auto const& parameter = option->get(); if (!it.hasNext()) { - errors.append(strf("Option '-%s' must be followed by an argument", flag)); + errors.append(strf("Option '-{}' must be followed by an argument", flag)); continue; } String val = it.next(); if (parameter.requirementMode != Multiple && result.parameters.contains(flag)) { - errors.append(strf("Option with argument '-%s' specified multiple times", flag)); + errors.append(strf("Option with argument '-{}' specified multiple times", flag)); continue; } result.parameters[move(flag)].append(move(val)); @@ -75,7 +75,7 @@ pair OptionParser::parseOptions(StringList co if (pair.second.is()) { auto const& na = pair.second.get(); if (na.requirementMode == Required && !result.parameters.contains(pair.first)) - errors.append(strf("Missing required flag with argument '-%s'", pair.first)); + errors.append(strf("Missing required flag with argument '-{}'", pair.first)); } } @@ -91,72 +91,72 @@ pair OptionParser::parseOptions(StringList co } if (result.arguments.size() < minimumArguments) errors.append(strf( - "Too few positional arguments given, expected at least %s got %s", minimumArguments, result.arguments.size())); + "Too few positional arguments given, expected at least {} got {}", minimumArguments, result.arguments.size())); if (result.arguments.size() > maximumArguments) errors.append(strf( - "Too many positional arguments given, expected at most %s got %s", maximumArguments, result.arguments.size())); + "Too many positional arguments given, expected at most {} got {}", maximumArguments, result.arguments.size())); return {move(result), move(errors)}; } void OptionParser::printHelp(std::ostream& os) const { if (!m_commandName.empty() && !m_summary.empty()) - format(os, "%s: %s\n\n", m_commandName, m_summary); + format(os, "{}: {}\n\n", m_commandName, m_summary); else if (!m_commandName.empty()) - format(os, "%s:\n\n", m_commandName); + format(os, "{}:\n\n", m_commandName); else if (!m_summary.empty()) - format(os, "%s\n\n", m_summary); + format(os, "{}\n\n", m_summary); String cmdLineText; for (auto const& p : m_options) { if (p.second.is()) { - cmdLineText += strf(" [-%s]", p.first); + cmdLineText += strf(" [-{}]", p.first); } else { auto const& parameter = p.second.get(); if (parameter.requirementMode == Optional) - cmdLineText += strf(" [-%s <%s>]", parameter.flag, parameter.argument); + cmdLineText += strf(" [-{} <{}>]", parameter.flag, parameter.argument); else if (parameter.requirementMode == Required) - cmdLineText += strf(" -%s <%s>", parameter.flag, parameter.argument); + cmdLineText += strf(" -{} <{}>", parameter.flag, parameter.argument); else if (parameter.requirementMode == Multiple) - cmdLineText += strf(" [-%s <%s>]...", parameter.flag, parameter.argument); + cmdLineText += strf(" [-{} <{}>]...", parameter.flag, parameter.argument); } } for (auto const& p : m_arguments) { if (p.requirementMode == Optional) - cmdLineText += strf(" [<%s>]", p.argumentName); + cmdLineText += strf(" [<{}>]", p.argumentName); else if (p.requirementMode == Required) - cmdLineText += strf(" <%s>", p.argumentName); + cmdLineText += strf(" <{}>", p.argumentName); else - cmdLineText += strf(" [<%s>...]", p.argumentName); + cmdLineText += strf(" [<{}>...]", p.argumentName); } if (m_commandName.empty()) - format(os, "Command Line Usage:%s\n", cmdLineText); + format(os, "Command Line Usage:{}\n", cmdLineText); else - format(os, "Command Line Usage: %s%s\n", m_commandName, cmdLineText); + format(os, "Command Line Usage: {}{}\n", m_commandName, cmdLineText); for (auto const& p : m_options) { if (p.second.is()) { auto const& sw = p.second.get(); if (!sw.description.empty()) - format(os, " -%s\t- %s\n", sw.flag, sw.description); + format(os, " -{}\t- {}\n", sw.flag, sw.description); } if (p.second.is()) { auto const& parameter = p.second.get(); if (!parameter.description.empty()) - format(os, " -%s <%s>\t- %s\n", parameter.flag, parameter.argument, parameter.description); + format(os, " -{} <{}>\t- {}\n", parameter.flag, parameter.argument, parameter.description); } } for (auto const& p : m_arguments) { if (!p.description.empty()) - format(os, " <%s>\t- %s\n", p.argumentName, p.description); + format(os, " <{}>\t- {}\n", p.argumentName, p.description); } if (!m_additionalHelp.empty()) - format(os, "\n%s\n", m_additionalHelp); + format(os, "\n{}\n", m_additionalHelp); } } diff --git a/source/core/StarOrderedMap.hpp b/source/core/StarOrderedMap.hpp index 71fe816..4f2dc22 100644 --- a/source/core/StarOrderedMap.hpp +++ b/source/core/StarOrderedMap.hpp @@ -228,7 +228,7 @@ template