The Formatting String Catastrophe

This commit is contained in:
Kae 2023-06-27 20:23:44 +10:00
parent 14b9689b6d
commit 332983c97b
239 changed files with 1432 additions and 1432 deletions

View File

@ -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;

View File

@ -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, Maybe<pa
}
if (auto lobby = m_discordServerLobby)
activity.GetParty().SetId(strf("%s", lobby->first).c_str());
activity.GetParty().SetId(strf("{}", lobby->first).c_str());
if (m_joinLocation.is<JoinLocal>()) {
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<JoinRemote>()) {
String address = strf("%s", (HostAddressWithPort)m_joinLocation.get<JoinRemote>());
String joinSecret = strf("connect:address_%s", address);
Logger::info("Setting discord join secret as %s", joinSecret);
String address = strf("{}", (HostAddressWithPort)m_joinLocation.get<JoinRemote>());
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, Maybe<pa
m_discordUpdatingActivity = true;
m_state->discordCore->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<String, P2PSocketUPtr> 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<JoinLocal>() && 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<JoinLocal>()) {
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<JoinRemote>()) {
auto address = (HostAddressWithPort)location.get<JoinRemote>();
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);
}
});
}

View File

@ -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<PcP2PNetworkingService>(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

View File

@ -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<Strin
glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
if (!status) {
glGetShaderInfoLog(shader, sizeof(logBuffer), NULL, logBuffer);
throw RendererException(strf("Failed to compile %s shader: %s\n", name, logBuffer));
throw RendererException(strf("Failed to compile {} shader: {}\n", name, logBuffer));
}
return shader;
@ -158,7 +158,7 @@ void OpenGl20Renderer::setEffectConfig(Json const& effectConfig, StringMap<Strin
if (!status) {
glGetProgramInfoLog(program, sizeof(logBuffer), NULL, logBuffer);
glDeleteProgram(program);
throw RendererException(strf("Failed to link program: %s\n", logBuffer));
throw RendererException(strf("Failed to link program: {}\n", logBuffer));
}
if (m_program != 0)
@ -175,8 +175,8 @@ void OpenGl20Renderer::setEffectConfig(Json const& effectConfig, StringMap<Strin
m_textureUniforms.clear();
m_textureSizeUniforms.clear();
for (size_t i = 0; i < MultiTextureCount; ++i) {
m_textureUniforms.append(glGetUniformLocation(m_program, strf("texture%s", i).c_str()));
m_textureSizeUniforms.append(glGetUniformLocation(m_program, strf("textureSize%s", i).c_str()));
m_textureUniforms.append(glGetUniformLocation(m_program, strf("texture{}", i).c_str()));
m_textureSizeUniforms.append(glGetUniformLocation(m_program, strf("textureSize{}", i).c_str()));
}
m_screenSizeUniform = glGetUniformLocation(m_program, "screenSize");
m_vertexTransformUniform = glGetUniformLocation(m_program, "vertexTransform");
@ -193,7 +193,7 @@ void OpenGl20Renderer::setEffectConfig(Json const& effectConfig, StringMap<Strin
effectParameter.parameterUniform = glGetUniformLocation(m_program, p.second.getString("uniform").utf8Ptr());
if (effectParameter.parameterUniform == -1) {
Logger::warn("OpenGL20 effect parameter '%s' has no associated uniform, skipping", p.first);
Logger::warn("OpenGL20 effect parameter '{}' has no associated uniform, skipping", p.first);
} else {
String type = p.second.getString("type");
if (type == "bool") {
@ -209,7 +209,7 @@ void OpenGl20Renderer::setEffectConfig(Json const& effectConfig, StringMap<Strin
} else if (type == "vec4") {
effectParameter.parameterType = RenderEffectParameter::typeIndexOf<Vec4F>();
} 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, StringMap<Strin
EffectTexture effectTexture;
effectTexture.textureUniform = glGetUniformLocation(m_program, p.second.getString("textureUniform").utf8Ptr());
if (effectTexture.textureUniform == -1) {
Logger::warn("OpenGL20 effect parameter '%s' has no associated uniform, skipping", p.first);
Logger::warn("OpenGL20 effect parameter '{}' has no associated uniform, skipping", p.first);
} else {
effectTexture.textureUnit = parameterTextureUnit++;
glUniform1i(effectTexture.textureUniform, effectTexture.textureUnit);
@ -253,7 +253,7 @@ void OpenGl20Renderer::setEffectConfig(Json const& effectConfig, StringMap<Strin
if (auto tsu = p.second.optString("textureSizeUniform")) {
effectTexture.textureSizeUniform = glGetUniformLocation(m_program, tsu->utf8Ptr());
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<GlTextureGroup>(atlasNumCells);
glTextureGroup->textureAtlasSet.textureFiltering = filtering;

View File

@ -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);
}
}

View File

@ -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));
}
}

View File

@ -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<RectU> 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<DirectoryAssetSource>(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::AssetData> 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::AssetData> 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::AssetData> 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::AssetData> 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::AssetData> 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::AssetData> 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<ImageData>(loadAsset(AssetId{AssetType::Image, {path.basePath, *alias, path.directives}}));
@ -897,7 +897,7 @@ shared_ptr<Assets::AssetData> 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

View File

@ -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)));
}

View File

@ -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<AssetReader>(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);

View File

@ -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);

View File

@ -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<String> 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)

View File

@ -59,13 +59,13 @@ namespace {
uint32_t fileSize = readLEType<uint32_t>(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<uint32_t>(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<uint16_t>(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<uint32_t>(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));
}

View File

@ -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 {

View File

@ -179,7 +179,7 @@ template <typename LeftT, typename RightT, typename LeftMapT, typename RightMapT
BiMap<LeftT, RightT, LeftMapT, RightMapT>::BiMap(std::initializer_list<value_type> 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<LeftT, RightT, LeftMapT, RightMapT>::insert(Left const& left, Right c
template <typename LeftT, typename RightT, typename LeftMapT, typename RightMapT>
void BiMap<LeftT, RightT, LeftMapT, RightMapT>::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);
}

View File

@ -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() {

View File

@ -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;
}

View File

@ -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];
}

View File

@ -61,11 +61,11 @@ shared_ptr<Type1 const> as(shared_ptr<Type2 const> const& p) {
template <typename Type, typename Ptr>
auto convert(Ptr const& p) -> decltype(as<Type>(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<Type>(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 <typename Type1, typename Type2>

View File

@ -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));

View File

@ -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() {

View File

@ -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();
}

View File

@ -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) {

View File

@ -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);

View File

@ -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<pair<String, bool>> File::dirList(const String& dirName, bool skipDots) {
List<std::pair<String, bool>> 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));
}
}

View File

@ -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<std::pair<String, bool>> 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<std::pair<String, bool>> 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;

View File

@ -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;
}

View File

@ -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<pair<ElementLocation, ElementLocation>> 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<JsonElement>& 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<pair<ElementLocation, ElementLocation>> 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<pair<ElementLocation, ElementLocation>> maybeEntry = m_objectEntryLocations.maybe(key);
if (maybeEntry.isValid()) {

View File

@ -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<String, HostAddressWithPort> HostAddressWithPort::lookupWithPort(String c
auto portNum = maybeLexicalCast<uint16_t>(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())

View File

@ -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() {

View File

@ -102,7 +102,7 @@ auto IdMapWrapper<BaseMap>::nextId() -> IdType {
template <typename BaseMap>
void IdMapWrapper<BaseMap>::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 <typename BaseMap>

View File

@ -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<Vec2U, PixelFormat> 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<Vec2U, PixelFormat> 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<PixelFormat> 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);

View File

@ -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<HueShiftImageOperation>()) {
return strf("hueshift=%s", op->hueShiftAmount * 360.0f);
return strf("hueshift={}", op->hueShiftAmount * 360.0f);
} else if (auto op = operation.ptr<SaturationShiftImageOperation>()) {
return strf("saturation=%s", op->saturationShiftAmount * 100.0f);
return strf("saturation={}", op->saturationShiftAmount * 100.0f);
} else if (auto op = operation.ptr<BrightnessMultiplyImageOperation>()) {
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<FadeToColorImageOperation>()) {
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<ScanLinesImageOperation>()) {
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<SetColorImageOperation>()) {
return strf("setcolor=%s", Color::rgb(op->color).toHex());
return strf("setcolor={}", Color::rgb(op->color).toHex());
} else if (auto op = operation.ptr<ColorReplaceImageOperation>()) {
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<AlphaMaskImageOperation>()) {
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<BlendImageOperation>()) {
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<MultiplyImageOperation>()) {
return strf("multiply=%s", Color::rgba(op->color).toHex());
return strf("multiply={}", Color::rgba(op->color).toHex());
} else if (auto op = operation.ptr<BorderImageOperation>()) {
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<ScaleImageOperation>()) {
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<CropImageOperation>()) {
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<FlipImageOperation>()) {
if (op->mode == FlipImageOperation::FlipX)
return "flipx";

View File

@ -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<int64_t>();
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<bool>();
}
@ -199,7 +199,7 @@ int64_t Json::toInt() const {
} else if (type() == Type::Int) {
return m_data.get<int64_t>();
} 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<int64_t>();
} 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<StringConstPtr>();
}
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<JsonArrayConstPtr>();
}
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<JsonObjectConstPtr>();
}
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<StringConstPtr>();
}
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<JsonArrayConstPtr>();
}
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<JsonObjectConstPtr>();
}
@ -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<Json>::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<JsonArrayConstPtr>();
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<JsonObjectConstPtr>();
auto i = map->find(key);

View File

@ -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));
}
}
}

View File

@ -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();

View File

@ -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()));
}
}

View File

@ -106,7 +106,7 @@ Json jsonFromWeightedPool(WeightedPool<T> const& pool, Converter&& converter);
template <size_t Size>
Array<unsigned, Size> 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<unsigned, Size> res;
for (size_t i = 0; i < Size; i++) {
@ -119,7 +119,7 @@ Array<unsigned, Size> jsonToArrayU(Json const& v) {
template <size_t Size>
Array<size_t, Size> 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<size_t, Size> res;
for (size_t i = 0; i < Size; i++) {
@ -132,7 +132,7 @@ Array<size_t, Size> jsonToArrayS(Json const& v) {
template <size_t Size>
Array<int, Size> 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<int, Size> res;
for (size_t i = 0; i < Size; i++) {
@ -145,7 +145,7 @@ Array<int, Size> jsonToArrayI(Json const& v) {
template <size_t Size>
Array<float, Size> 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<float, Size> res;
for (size_t i = 0; i < Size; i++) {
@ -158,7 +158,7 @@ Array<float, Size> jsonToArrayF(Json const& v) {
template <size_t Size>
Array<double, Size> 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<double, Size> res;
for (size_t i = 0; i < Size; i++) {
@ -171,7 +171,7 @@ Array<double, Size> jsonToArrayD(Json const& v) {
template <size_t Size>
Array<String, Size> 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<String, Size> res;
for (size_t i = 0; i < Size; i++) {

View File

@ -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()));
}
}

View File

@ -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;

View File

@ -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<size_t> i = maybeLexicalCast<size_t>(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<size_t> i = maybeLexicalCast<size_t>(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<size_t> i = maybeLexicalCast<size_t>(*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<Jsonlike> emptyPathOp = [](Jsonlike const&) { return Json{}; };
ObjectOp<Jsonlike> 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<Jsonlike> arrayOp = [](Jsonlike const& array, Maybe<size_t> i) {

View File

@ -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));
}
}
}

View File

@ -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 <class Type>

View File

@ -668,14 +668,14 @@ size_t RandomAccessListMixin<BaseList>::lastIndexOf(const_reference e, size_t ti
template <typename BaseList>
auto RandomAccessListMixin<BaseList>::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 <typename BaseList>
auto RandomAccessListMixin<BaseList>::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);
}

View File

@ -39,7 +39,7 @@ bool LockFile::lock(int64_t timeout) {
auto doFLock = [](String const& filename, bool block) -> shared_ptr<int> {
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 {};
}

View File

@ -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>(handle);

View File

@ -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("<hours>:<minutes>:<seconds>.<millis>"), LogLevelNames.getRight(level), msg);
auto line = strf("[{}] [{}] {}\n", Time::printCurrentDateAndTime("<hours>:<minutes>:<seconds>.<millis>"), LogLevelNames.getRight(level), msg);
m_output->write(line.data(), line.size());
}

View File

@ -185,7 +185,7 @@ void Logger::error(char const* msg, Args const&... args) {
template <typename T>
void LogMap::set(String const& key, T const& t) {
setValue(key, strf("%s", t));
setValue(key, strf("{}", t));
}
}

View File

@ -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, <unknown error>", res);
error = strf("Error code {}, <unknown error>", res);
lua_pop(state, 1);

View File

@ -1717,20 +1717,20 @@ T& LuaUserData::get() const {
template <typename Function>
void LuaCallbacks::registerCallback(String name, Function&& func) {
if (!m_callbacks.insert(name, LuaDetail::wrapFunction(forward<Function>(func))).second)
throw LuaException::format("Lua callback '%s' was registered twice", name);
throw LuaException::format("Lua callback '{}' was registered twice", name);
}
template <typename Return, typename... Args, typename Function>
void LuaCallbacks::registerCallbackWithSignature(String name, Function&& func) {
if (!m_callbacks.insert(name, LuaDetail::wrapFunctionWithSignature<Return, Args...>(forward<Function>(func))).second)
throw LuaException::format("Lua callback '%s' was registered twice", name);
throw LuaException::format("Lua callback '{}' was registered twice", name);
}
template <typename T>
template <typename Function>
void LuaMethods<T>::registerMethod(String name, Function&& func) {
if (!m_methods.insert(name, LuaDetail::wrapMethod(forward<Function>(move(func)))).second)
throw LuaException::format("Lua method '%s' was registered twice", name);
throw LuaException::format("Lua method '{}' was registered twice", name);
}
template <typename T>
@ -1738,7 +1738,7 @@ template <typename Return, typename... Args, typename Function>
void LuaMethods<T>::registerMethodWithSignature(String name, Function&& func) {
if (!m_methods.insert(name, LuaDetail::wrapMethodWithSignature<Return, Args...>(forward<Function>(move(func))))
.second)
throw LuaException::format("Lua method '%s' was registered twice", name);
throw LuaException::format("Lua method '{}' was registered twice", name);
}
template <typename T>
@ -1766,7 +1766,7 @@ Ret LuaContext::invokePath(String const& key, Args const&... args) const {
auto p = getPath(key);
if (auto f = p.ptr<LuaFunction>())
return f->invoke<Ret>(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 <typename T>
@ -1867,14 +1867,14 @@ template <typename T>
T LuaEngine::luaTo(LuaValue&& v) {
if (auto res = luaMaybeTo<T>(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 <typename T>
T LuaEngine::luaTo(LuaValue const& v) {
if (auto res = luaMaybeTo<T>(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 <typename Container>
@ -2089,7 +2089,7 @@ template <typename T>
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);

View File

@ -163,7 +163,7 @@ template <typename BaseMap>
auto MapMixin<BaseMap>::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 <typename BaseMap>
@ -182,7 +182,7 @@ template <typename BaseMap>
auto MapMixin<BaseMap>::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 <typename BaseMap>
auto MapMixin<BaseMap>::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<BaseMap>::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 <typename BaseMap>
@ -267,7 +267,7 @@ template <typename BaseMap>
auto MapMixin<BaseMap>::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;
}

View File

@ -291,7 +291,7 @@ template <typename Element, size_t Rank>
Element const& MultiArray<Element, Rank>::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 <typename Element, size_t Rank>
Element& MultiArray<Element, Rank>::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 <typename Element, size_t Rank>
void MultiArray<Element, Rank>::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);

View File

@ -266,7 +266,7 @@ auto NetElementMapWrapper<BaseMap>::insert(key_type k, mapped_type v) -> pair<co
template <typename BaseMap>
void NetElementMapWrapper<BaseMap>::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 <typename BaseMap>
@ -321,7 +321,7 @@ template <typename BaseMap>
auto NetElementMapWrapper<BaseMap>::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;

View File

@ -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

View File

@ -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::Options, StringList> 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::Options, StringList> OptionParser::parseOptions(StringList co
} else {
auto const& parameter = option->get<Parameter>();
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::Options, StringList> OptionParser::parseOptions(StringList co
if (pair.second.is<Parameter>()) {
auto const& na = pair.second.get<Parameter>();
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::Options, StringList> 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<Switch>()) {
cmdLineText += strf(" [-%s]", p.first);
cmdLineText += strf(" [-{}]", p.first);
} else {
auto const& parameter = p.second.get<Parameter>();
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<Switch>()) {
auto const& sw = p.second.get<Switch>();
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<Parameter>()) {
auto const& parameter = p.second.get<Parameter>();
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);
}
}

View File

@ -228,7 +228,7 @@ template <template <typename...> class Map, typename Key, typename Value, typena
auto OrderedMapWrapper<Map, Key, Value, Allocator, MapArgs...>::get(key_type const& k) -> mapped_type& {
auto i = m_map.find(k);
if (i == m_map.end())
throw MapException(strf("Key '%s' not found in OrderedMap::get()", outputAny(k)));
throw MapException(strf("Key '{}' not found in OrderedMap::get()", outputAny(k)));
return i->second->second;
}
@ -308,7 +308,7 @@ auto OrderedMapWrapper<Map, Key, Value, Allocator, MapArgs...>::keyOf(mapped_typ
if (i->second == v)
return i->first;
}
throw MapException(strf("Value '%s' not found in OrderedMap::keyOf()", outputAny(v)));
throw MapException(strf("Value '{}' not found in OrderedMap::keyOf()", outputAny(v)));
}
template <template <typename...> class Map, typename Key, typename Value, typename Allocator, typename... MapArgs>
@ -359,7 +359,7 @@ template <template <typename...> class Map, typename Key, typename Value, typena
auto OrderedMapWrapper<Map, Key, Value, Allocator, MapArgs...>::add(key_type k, mapped_type v) -> mapped_type& {
auto pair = 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;
}
@ -405,7 +405,7 @@ auto OrderedMapWrapper<Map, Key, Value, Allocator, MapArgs...>::take(key_type co
m_order.erase(i->second);
return v;
} else {
throw MapException(strf("Key '%s' not found in OrderedMap::take()", outputAny(k)));
throw MapException(strf("Key '{}' not found in OrderedMap::take()", outputAny(k)));
}
}
@ -509,7 +509,7 @@ auto OrderedMapWrapper<Map, Key, Value, Allocator, MapArgs...>::indexOf(key_type
template <template <typename...> class Map, typename Key, typename Value, typename Allocator, typename... MapArgs>
auto OrderedMapWrapper<Map, Key, Value, Allocator, MapArgs...>::keyAt(size_t i) const -> key_type const& {
if (i >= size())
throw MapException(strf("index %s out of range in OrderedMap::at()", i));
throw MapException(strf("index {} out of range in OrderedMap::at()", i));
auto it = begin();
std::advance(it, i);
@ -524,7 +524,7 @@ auto OrderedMapWrapper<Map, Key, Value, Allocator, MapArgs...>::valueAt(size_t i
template <template <typename...> class Map, typename Key, typename Value, typename Allocator, typename... MapArgs>
auto OrderedMapWrapper<Map, Key, Value, Allocator, MapArgs...>::valueAt(size_t i) -> mapped_type& {
if (i >= size())
throw MapException(strf("index %s out of range in OrderedMap::valueAt()", i));
throw MapException(strf("index {} out of range in OrderedMap::valueAt()", i));
auto it = m_order.begin();
std::advance(it, i);
@ -612,7 +612,7 @@ template <template <typename...> class Map, typename Key, typename Value, typena
void OrderedMapWrapper<Map, Key, Value, Allocator, MapArgs...>::toBack(key_type const& k) {
auto i = m_map.find(k);
if (i == m_map.end())
throw MapException(strf("Key not found in OrderedMap::toBack('%s')", outputAny(k)));
throw MapException(strf("Key not found in OrderedMap::toBack('{}')", outputAny(k)));
toBack(i->second);
}
@ -621,7 +621,7 @@ template <template <typename...> class Map, typename Key, typename Value, typena
void OrderedMapWrapper<Map, Key, Value, Allocator, MapArgs...>::toFront(key_type const& k) {
auto i = m_map.find(k);
if (i == m_map.end())
throw MapException(strf("Key not found in OrderedMap::toFront('%s')", outputAny(k)));
throw MapException(strf("Key not found in OrderedMap::toFront('{}')", outputAny(k)));
toFront(i->second);
}

View File

@ -59,19 +59,19 @@ struct SignalHandlerImpl {
else if (modeFlag == 8)
mode = "Execute";
else
mode = strf("Mode(%s)", modeFlag);
g_sehMessage = strf("Access violation detected at %s (%s of address %s)",
mode = strf("Mode({})", modeFlag);
g_sehMessage = strf("Access violation detected at {} ({} of address {})",
ExceptionInfo->ExceptionRecord->ExceptionAddress,
mode,
(PVOID)ExceptionInfo->ExceptionRecord->ExceptionInformation[1]);
} else {
g_sehMessage = msg;
g_sehMessage = strf("%s (%p @ %s)",
g_sehMessage = strf("{} (%p @ {})",
g_sehMessage,
ExceptionInfo->ExceptionRecord->ExceptionCode,
ExceptionInfo->ExceptionRecord->ExceptionAddress);
for (DWORD i = 0; i < ExceptionInfo->ExceptionRecord->NumberParameters; i++)
g_sehMessage = strf("%s [%s]", g_sehMessage, (PVOID)ExceptionInfo->ExceptionRecord->ExceptionInformation[i]);
g_sehMessage = strf("{} [{}]", g_sehMessage, (PVOID)ExceptionInfo->ExceptionRecord->ExceptionInformation[i]);
}
// setup a hijack into our own trampoline as if the failure actually was a

View File

@ -209,7 +209,7 @@ void SmallVector<Element, MaxStackSize>::reserve(size_t newCapacity) {
newCapacity = max(oldCapacity * 2, newCapacity);
auto newMem = (Element*)Star::malloc(newCapacity * sizeof(Element));
if (!newMem)
throw MemoryException::format("Could not set new SmallVector capacity %s\n", newCapacity);
throw MemoryException::format("Could not set new SmallVector capacity {}\n", newCapacity);
size_t size = m_end - m_begin;
auto oldMem = m_begin;
@ -238,14 +238,14 @@ void SmallVector<Element, MaxStackSize>::reserve(size_t newCapacity) {
template <typename Element, size_t MaxStackSize>
auto SmallVector<Element, MaxStackSize>::at(size_t i) -> reference {
if (i >= size())
throw OutOfRangeException::format("out of range in SmallVector::at(%s)", i);
throw OutOfRangeException::format("out of range in SmallVector::at({})", i);
return m_begin[i];
}
template <typename Element, size_t MaxStackSize>
auto SmallVector<Element, MaxStackSize>::at(size_t i) const -> const_reference {
if (i >= size())
throw OutOfRangeException::format("out of range in SmallVector::at(%s)", i);
throw OutOfRangeException::format("out of range in SmallVector::at({})", i);
return m_begin[i];
}

View File

@ -49,7 +49,7 @@ Maybe<SocketPollResult> Socket::poll(SocketPollQuery const& query, unsigned time
ret = ::select(0, &readfs, &writefs, &exceptfs, &time);
if (ret < 0)
throw NetworkException::format("Error during call to select, '%s'", netErrorString());
throw NetworkException::format("Error during call to select, '{}'", netErrorString());
if (ret == 0)
return {};
@ -82,7 +82,7 @@ Maybe<SocketPollResult> Socket::poll(SocketPollQuery const& query, unsigned time
ret = ::poll(pollfds.get(), query.size(), timeout);
if (ret < 0)
throw NetworkException::format("Error during call to poll, '%s'", netErrorString());
throw NetworkException::format("Error during call to poll, '{}'", netErrorString());
if (ret == 0)
return {};
@ -127,18 +127,18 @@ void Socket::bind(HostAddressWithPort const& addressWithPort) {
m_localAddress = addressWithPort;
setNativeFromAddress(m_localAddress, &sockAddr, &sockAddrLen);
if (::bind(m_impl->socketDesc, (struct sockaddr*)&sockAddr, sockAddrLen) < 0)
throw NetworkException(strf("Cannot bind socket to %s: %s", m_localAddress, netErrorString()));
throw NetworkException(strf("Cannot bind socket to {}: {}", m_localAddress, netErrorString()));
m_socketMode = SocketMode::Bound;
Logger::debug("bind %s (%d)", addressWithPort, m_impl->socketDesc);
Logger::debug("bind {} ({})", addressWithPort, m_impl->socketDesc);
}
void Socket::listen(int backlog) {
WriteLocker locker(m_mutex);
if (::listen(m_impl->socketDesc, backlog) != 0)
throw NetworkException(strf("Could not listen on socket: '%s'", netErrorString()));
throw NetworkException(strf("Could not listen on socket: '{}'", netErrorString()));
}
void Socket::setTimeout(unsigned timeout) {
@ -168,14 +168,14 @@ void Socket::setNonBlocking(bool nonBlocking) {
#ifdef WIN32
unsigned long mode = nonBlocking ? 1 : 0;
if (ioctlsocket(m_impl->socketDesc, FIONBIO, &mode) != 0)
throw NetworkException::format("Cannot set socket non-blocking mode: %s", netErrorString());
throw NetworkException::format("Cannot set socket non-blocking mode: {}", netErrorString());
#else
int flags = fcntl(m_impl->socketDesc, F_GETFL, 0);
if (flags < 0)
throw NetworkException::format("fcntl failure getting socket flags: %s", netErrorString());
throw NetworkException::format("fcntl failure getting socket flags: {}", netErrorString());
flags = nonBlocking ? (flags | O_NONBLOCK) : (flags & ~O_NONBLOCK);
if (fcntl(m_impl->socketDesc, F_SETFL, flags) != 0)
throw NetworkException::format("fcntl failure setting non-blocking mode: %s", netErrorString());
throw NetworkException::format("fcntl failure setting non-blocking mode: {}", netErrorString());
#endif
}
@ -216,7 +216,7 @@ Socket::Socket(SocketType type, NetworkMode networkMode)
m_impl->socketDesc = ::socket(AF_INET6, type == SocketType::Tcp ? SOCK_STREAM : SOCK_DGRAM, 0);
if (invalidSocketDescriptor(m_impl->socketDesc))
throw NetworkException(strf("cannot create socket: %s", netErrorString()));
throw NetworkException(strf("cannot create socket: {}", netErrorString()));
m_socketMode = SocketMode::Shutdown;
setTimeout(60000);
@ -231,7 +231,7 @@ Socket::Socket(NetworkMode networkMode, SocketImplPtr impl, SocketMode socketMod
void Socket::checkOpen(char const* methodName) const {
if (m_socketMode == SocketMode::Closed)
throw SocketClosedException::format("Socket not open in %s", methodName);
throw SocketClosedException::format("Socket not open in {}", methodName);
}
void Socket::doShutdown() {

View File

@ -188,7 +188,7 @@ bool StaticVector<Element, MaxSize>::empty() const {
template <typename Element, size_t MaxSize>
void StaticVector<Element, MaxSize>::resize(size_t size, Element const& e) {
if (size > MaxSize)
throw StaticVectorSizeException::format("StaticVector::resize(%s) out of range %s", m_size + size, MaxSize);
throw StaticVectorSizeException::format("StaticVector::resize({}) out of range {}", m_size + size, MaxSize);
for (size_t i = m_size; i > size; --i)
pop_back();
@ -199,14 +199,14 @@ void StaticVector<Element, MaxSize>::resize(size_t size, Element const& e) {
template <typename Element, size_t MaxSize>
auto StaticVector<Element, MaxSize>::at(size_t i) -> reference {
if (i >= m_size)
throw OutOfRangeException::format("out of range in StaticVector::at(%s)", i);
throw OutOfRangeException::format("out of range in StaticVector::at({})", i);
return ptr()[i];
}
template <typename Element, size_t MaxSize>
auto StaticVector<Element, MaxSize>::at(size_t i) const -> const_reference {
if (i >= m_size)
throw OutOfRangeException::format("out of range in StaticVector::at(%s)", i);
throw OutOfRangeException::format("out of range in StaticVector::at({})", i);
return ptr()[i];
}
@ -329,7 +329,7 @@ template <typename Element, size_t MaxSize>
template <typename... Args>
void StaticVector<Element, MaxSize>::emplace_back(Args&&... args) {
if (m_size + 1 > MaxSize)
throw StaticVectorSizeException::format("StaticVector::emplace_back would extend StaticVector beyond size %s", MaxSize);
throw StaticVectorSizeException::format("StaticVector::emplace_back would extend StaticVector beyond size {}", MaxSize);
m_size += 1;
new (ptr() + m_size - 1) Element(forward<Args>(args)...);

View File

@ -187,7 +187,7 @@ bool CaseInsensitiveStringCompare::operator()(String const& lhs, String const& r
String::Char String::at(size_t i) const {
if (i > size())
throw OutOfRangeException(strf("Out of range in String::at(%s)", i));
throw OutOfRangeException(strf("Out of range in String::at({})", i));
return operator[](i);
}
@ -744,7 +744,7 @@ bool String::equalsIgnoreCase(String const& s) const {
String String::substr(size_t position, size_t n) const {
auto len = size();
if (position > len)
throw OutOfRangeException(strf("out of range in String::substr(%s, %s)", position, n));
throw OutOfRangeException(strf("out of range in String::substr({}, {})", position, n));
if (position == 0 && n >= len)
return *this;

View File

@ -388,7 +388,7 @@ String String::lookupTags(Lookup&& lookup) const {
auto substrInto = [](std::string const& ref, size_t position, size_t n, std::string& result) {
auto len = ref.size();
if (position > len)
throw OutOfRangeException(strf("out of range in substrInto: %s", position));
throw OutOfRangeException(strf("out of range in substrInto: {}", position));
auto it = ref.begin();
std::advance(it, position);

View File

@ -78,7 +78,7 @@ StringView::Char StringView::operator[](size_t index) const {
StringView::Char StringView::at(size_t i) const {
if (i > size())
throw OutOfRangeException(strf("Out of range in StringView::at(%s)", i));
throw OutOfRangeException(strf("Out of range in StringView::at({})", i));
return operator[](i);
}
@ -340,7 +340,7 @@ bool StringView::equalsIgnoreCase(StringView s) const {
StringView StringView::substr(size_t position, size_t n) const {
auto len = size();
if (position > len)
throw OutOfRangeException(strf("out of range in StringView::substr(%s, %s)", position, n));
throw OutOfRangeException(strf("out of range in StringView::substr({}, {})", position, n));
if (position == 0 && n >= len)
return *this;

View File

@ -31,7 +31,7 @@ TcpSocketPtr TcpSocket::accept() {
if (invalidSocketDescriptor(socketDesc)) {
if (netErrorInterrupt())
return {};
throw NetworkException(strf("Cannot accept connection: %s", netErrorString()));
throw NetworkException(strf("Cannot accept connection: {}", netErrorString()));
}
auto socketImpl = make_shared<SocketImpl>();
@ -47,7 +47,7 @@ TcpSocketPtr TcpSocket::accept() {
sockPtr->m_localAddress = m_localAddress;
setAddressFromNative(sockPtr->m_remoteAddress, m_localAddress.address().mode(), &sockAddr);
Logger::debug("accept from %s (%d)", sockPtr->m_remoteAddress, sockPtr->m_impl->socketDesc);
Logger::debug("accept from {} ({})", sockPtr->m_remoteAddress, sockPtr->m_impl->socketDesc);
return sockPtr;
}
@ -83,7 +83,7 @@ size_t TcpSocket::receive(char* data, size_t size) {
} else if (netErrorInterrupt()) {
r = 0;
} else {
throw NetworkException(strf("tcp recv error: %s", netErrorString()));
throw NetworkException(strf("tcp recv error: {}", netErrorString()));
}
}
@ -113,7 +113,7 @@ size_t TcpSocket::send(char const* data, size_t size) {
} else if (netErrorInterrupt()) {
w = 0;
} else {
throw NetworkException(strf("tcp send error: %s", netErrorString()));
throw NetworkException(strf("tcp send error: {}", netErrorString()));
}
}
@ -145,7 +145,7 @@ void TcpSocket::connect(HostAddressWithPort const& addressWithPort) {
socklen_t sockAddrLen;
setNativeFromAddress(addressWithPort, &sockAddr, &sockAddrLen);
if (::connect(m_impl->socketDesc, (struct sockaddr*)&sockAddr, sockAddrLen) < 0)
throw NetworkException(strf("cannot connect to %s: %s", addressWithPort, netErrorString()));
throw NetworkException(strf("cannot connect to {}: {}", addressWithPort, netErrorString()));
#if defined STAR_SYSTEM_MACOS || defined STAR_SYSTEM_FREEBSD
// Don't generate sigpipe
@ -161,7 +161,7 @@ TcpServer::TcpServer(HostAddressWithPort const& address) : m_hostAddress(address
m_hostAddress = address;
m_listenSocket = TcpSocket::listen(address);
m_listenSocket->setNonBlocking(true);
Logger::debug("TcpServer listening on: %s", address);
Logger::debug("TcpServer listening on: {}", address);
}
TcpServer::TcpServer(uint16_t port) : TcpServer(HostAddressWithPort("*", port)) {}
@ -201,7 +201,7 @@ void TcpServer::setAcceptCallback(AcceptCallback callback, unsigned timeout) {
try {
conn = accept(timeout);
} catch (NetworkException const& e) {
Logger::error("TcpServer caught exception accepting connection %s", outputException(e, false));
Logger::error("TcpServer caught exception accepting connection {}", outputException(e, false));
}
if (conn)
@ -211,7 +211,7 @@ void TcpServer::setAcceptCallback(AcceptCallback callback, unsigned timeout) {
break;
}
} catch (std::exception const& e) {
Logger::error("TcpServer will close, listener thread caught exception: %s", outputException(e, true));
Logger::error("TcpServer will close, listener thread caught exception: {}", outputException(e, true));
m_listenSocket->close();
}
});

View File

@ -31,21 +31,21 @@ struct ThreadImpl {
#ifdef STAR_SYSTEM_MACOS
// ensure the name is under the max allowed
char tname[MAX_THREAD_NAMELEN];
snprintf(tname, sizeof(tname), "%s", ptr->name.utf8Ptr());
snprintf(tname, sizeof(tname), "{}", ptr->name.utf8Ptr());
pthread_setname_np(tname);
#endif
ptr->function();
} catch (std::exception const& e) {
if (ptr->name.empty())
Logger::error("Exception caught in Thread: %s", outputException(e, true));
Logger::error("Exception caught in Thread: {}", outputException(e, true));
else
Logger::error("Exception caught in Thread %s: %s", ptr->name, outputException(e, true));
Logger::error("Exception caught in Thread {}: {}", ptr->name, outputException(e, true));
} catch (...) {
if (ptr->name.empty())
Logger::error("Unknown exception caught in Thread");
else
Logger::error("Unknown exception caught in Thread %s", ptr->name);
Logger::error("Unknown exception caught in Thread {}", ptr->name);
}
ptr->stopped = true;
return nullptr;
@ -65,12 +65,12 @@ struct ThreadImpl {
if (ret != 0) {
stopped = true;
joined = true;
throw StarException(strf("Failed to create thread, error %s", ret));
throw StarException(strf("Failed to create thread, error {}", ret));
}
// ensure the name is under the max allowed
char tname[MAX_THREAD_NAMELEN];
snprintf(tname, sizeof(tname), "%s", name.utf8Ptr());
snprintf(tname, sizeof(tname), "{}", name.utf8Ptr());
#ifdef STAR_SYSTEM_FREEBSD
pthread_set_name_np(pthread, tname);
@ -86,7 +86,7 @@ struct ThreadImpl {
return false;
int ret = pthread_join(pthread, NULL);
if (ret != 0)
throw StarException(strf("Failed to join thread, error %s", ret));
throw StarException(strf("Failed to join thread, error {}", ret));
joined = true;
return true;
}
@ -242,7 +242,7 @@ void Thread::yield() {
unsigned Thread::numberOfProcessors() {
long nprocs = sysconf(_SC_NPROCESSORS_ONLN);
if (nprocs < 1)
throw StarException(strf("Could not determine number of CPUs online: %s\n", strerror(errno)));
throw StarException(strf("Could not determine number of CPUs online: {}\n", strerror(errno)));
return nprocs;
}

View File

@ -49,14 +49,14 @@ struct ThreadImpl {
ptr->function();
} catch (std::exception const& e) {
if (ptr->name.empty())
Logger::error("Exception caught in Thread: %s", outputException(e, true));
Logger::error("Exception caught in Thread: {}", outputException(e, true));
else
Logger::error("Exception caught in Thread %s: %s", ptr->name, outputException(e, true));
Logger::error("Exception caught in Thread {}: {}", ptr->name, outputException(e, true));
} catch (...) {
if (ptr->name.empty())
Logger::error("Unknown exception caught in Thread");
else
Logger::error("Unknown exception caught in Thread %s", ptr->name);
Logger::error("Unknown exception caught in Thread {}", ptr->name);
}
ptr->stopped = true;
return 0;

View File

@ -28,19 +28,19 @@ String Time::printDuration(double time) {
if (time >= 3600) {
int numHours = (int)time / 3600;
hours = strf("%d hour%s", numHours, numHours == 1 ? "" : "s");
hours = strf("{} hour{}", numHours, numHours == 1 ? "" : "s");
}
if (time >= 60) {
int numMinutes = (int)(time / 60) % 60;
minutes = strf("%s minute%s", numMinutes, numMinutes == 1 ? "" : "s");
minutes = strf("{} minute{}", numMinutes, numMinutes == 1 ? "" : "s");
}
if (time >= 1) {
int numSeconds = (int)time % 60;
seconds = strf("%s second%s", numSeconds, numSeconds == 1 ? "" : "s");
seconds = strf("{} second{}", numSeconds, numSeconds == 1 ? "" : "s");
}
int numMilliseconds = round(time * 1000);
milliseconds = strf("%s millisecond%s", numMilliseconds, numMilliseconds == 1 ? "" : "s");
milliseconds = strf("{} millisecond{}", numMilliseconds, numMilliseconds == 1 ? "" : "s");
return String::joinWith(", ", hours, minutes, seconds, milliseconds);
}

View File

@ -18,13 +18,13 @@ String Time::printDateAndTime(int64_t epochTicks, String format) {
localtime_r(&requestedTime, &ptm);
return format.replaceTags(StringMap<String>{
{"year", strf("%04d", ptm.tm_year + 1900)},
{"month", strf("%02d", ptm.tm_mon + 1)},
{"day", strf("%02d", ptm.tm_mday)},
{"hours", strf("%02d", ptm.tm_hour)},
{"minutes", strf("%02d", ptm.tm_min)},
{"seconds", strf("%02d", ptm.tm_sec)},
{"millis", strf("%03d", (epochTicks % epochTickFrequency()) / (epochTickFrequency() / 1000))}
{"year", strf("{:04d}", ptm.tm_year + 1900)},
{"month", strf("{:02d}", ptm.tm_mon + 1)},
{"day", strf("{:02d}", ptm.tm_mday)},
{"hours", strf("{:02d}", ptm.tm_hour)},
{"minutes", strf("{:02d}", ptm.tm_min)},
{"seconds", strf("{:02d}", ptm.tm_sec)},
{"millis", strf("{:03d}", (epochTicks % epochTickFrequency()) / (epochTickFrequency() / 1000))}
});
}

View File

@ -14,13 +14,13 @@ String Time::printDateAndTime(int64_t epochTicks, String format) {
ptm = localtime(&requestedTime);
return format.replaceTags(StringMap<String>{
{"year", strf("%04d", ptm->tm_year + 1900)},
{"month", strf("%02d", ptm->tm_mon + 1)},
{"day", strf("%02d", ptm->tm_mday)},
{"hours", strf("%02d", ptm->tm_hour)},
{"minutes", strf("%02d", ptm->tm_min)},
{"seconds", strf("%02d", ptm->tm_sec)},
{"millis", strf("%03d", (epochTicks % epochTickFrequency()) / (epochTickFrequency() / 1000))},
{"year", strf("{:04d}", ptm->tm_year + 1900)},
{"month", strf("{:02d}", ptm->tm_mon + 1)},
{"day", strf("{:02d}", ptm->tm_mday)},
{"hours", strf("{:02d}", ptm->tm_hour)},
{"minutes", strf("{:02d}", ptm->tm_min)},
{"seconds", strf("{:02d}", ptm->tm_sec)},
{"millis", strf("{:03d}", (epochTicks % epochTickFrequency()) / (epochTickFrequency() / 1000))},
});
}

View File

@ -23,7 +23,7 @@ size_t UdpSocket::receive(HostAddressWithPort* address, char* data, size_t datas
else if (netErrorInterrupt())
len = 0;
else
throw NetworkException(strf("udp recv error: %s", netErrorString()));
throw NetworkException(strf("udp recv error: {}", netErrorString()));
}
if (address)
@ -47,7 +47,7 @@ size_t UdpSocket::send(HostAddressWithPort const& address, char const* data, siz
else if (netErrorInterrupt())
len = 0;
else
throw NetworkException(strf("udp send error: %s", netErrorString()));
throw NetworkException(strf("udp send error: {}", netErrorString()));
}
return len;
@ -57,7 +57,7 @@ UdpServer::UdpServer(HostAddressWithPort const& address)
: m_hostAddress(address), m_listenSocket(make_shared<UdpSocket>(m_hostAddress.address().mode())) {
m_listenSocket->setNonBlocking(true);
m_listenSocket->bind(m_hostAddress);
Logger::debug("UdpServer listening on: %s", m_hostAddress);
Logger::debug("UdpServer listening on: {}", m_hostAddress);
}
UdpServer::~UdpServer() {

View File

@ -12,7 +12,7 @@ void throwMissingUtf8End() {
}
void throwInvalidUtf32CodePoint(Utf32Type val) {
throw UnicodeException::format("Invalid UTF-32 code point %s encountered while trying to encode UTF-8", (int32_t)val);
throw UnicodeException::format("Invalid UTF-32 code point {} encountered while trying to encode UTF-8", (int32_t)val);
}
size_t utf8Length(const Utf8Type* utf8, size_t remain) {

View File

@ -9,7 +9,7 @@ Uuid::Uuid() : Uuid(Random::randBytes(UuidSize)) {}
Uuid::Uuid(ByteArray const& bytes) {
if (bytes.size() != UuidSize)
throw UuidException(strf("Size mismatch in reading Uuid from ByteArray: %s vs %s", bytes.size(), UuidSize));
throw UuidException(strf("Size mismatch in reading Uuid from ByteArray: {} vs {}", bytes.size(), UuidSize));
bytes.copyTo(m_data.ptr(), UuidSize);
}

View File

@ -125,7 +125,7 @@ WorkerPoolHandle WorkerPool::addWork(function<void()> work) {
}
WorkerPool::WorkerThread::WorkerThread(WorkerPool* parent)
: Thread(strf("WorkerThread for WorkerPool '%s'", parent->m_name)),
: Thread(strf("WorkerThread for WorkerPool '{}'", parent->m_name)),
parent(parent),
shouldStop(false),
waiting(false) {

View File

@ -31,15 +31,15 @@ ActionBar::ActionBar(MainInterfacePaneManager* paneManager, PlayerPtr player) {
GuiReader reader;
for (uint8_t i = 0; i < m_player->inventory()->customBarIndexes(); ++i) {
reader.registerCallback(strf("customBar%sL", i + 1), bind(&ActionBar::customBarClick, this, i, true));
reader.registerCallback(strf("customBar%sR", i + 1), bind(&ActionBar::customBarClick, this, i, false));
reader.registerCallback(strf("customBar{}L", i + 1), bind(&ActionBar::customBarClick, this, i, true));
reader.registerCallback(strf("customBar{}R", i + 1), bind(&ActionBar::customBarClick, this, i, false));
reader.registerCallback(strf("customBar%sL.right", i + 1), bind(&ActionBar::customBarClickRight, this, i, true));
reader.registerCallback(strf("customBar%sR.right", i + 1), bind(&ActionBar::customBarClickRight, this, i, false));
reader.registerCallback(strf("customBar{}L.right", i + 1), bind(&ActionBar::customBarClickRight, this, i, true));
reader.registerCallback(strf("customBar{}R.right", i + 1), bind(&ActionBar::customBarClickRight, this, i, false));
}
for (uint8_t i = 0; i < EssentialItemCount; ++i)
reader.registerCallback(strf("essentialBar%s", i + 1), bind(&ActionBar::essentialBarClick, this, i));
reader.registerCallback(strf("essentialBar{}", i + 1), bind(&ActionBar::essentialBarClick, this, i));
reader.registerCallback("pickupToActionBar", [=](Widget* widget) {
auto button = as<ButtonWidget>(widget);
@ -53,10 +53,10 @@ ActionBar::ActionBar(MainInterfacePaneManager* paneManager, PlayerPtr player) {
reader.construct(m_config.get("paneLayout"), this);
for (uint8_t i = 0; i < m_player->inventory()->customBarIndexes(); ++i) {
auto customBarLeft = fetchChild<ItemSlotWidget>(strf("customBar%sL", i + 1));
auto customBarRight = fetchChild<ItemSlotWidget>(strf("customBar%sR", i + 1));
auto customBarLeftOverlay = fetchChild<ImageWidget>(strf("customBar%sLOverlay", i + 1));
auto customBarRightOverlay = fetchChild<ImageWidget>(strf("customBar%sROverlay", i + 1));
auto customBarLeft = fetchChild<ItemSlotWidget>(strf("customBar{}L", i + 1));
auto customBarRight = fetchChild<ItemSlotWidget>(strf("customBar{}R", i + 1));
auto customBarLeftOverlay = fetchChild<ImageWidget>(strf("customBar{}LOverlay", i + 1));
auto customBarRightOverlay = fetchChild<ImageWidget>(strf("customBar{}ROverlay", i + 1));
TextPositioning countPosition = {jsonToVec2F(m_config.get("countMidAnchor")), HorizontalAnchor::HMidAnchor};
customBarLeft->setCountPosition(countPosition);
@ -69,7 +69,7 @@ ActionBar::ActionBar(MainInterfacePaneManager* paneManager, PlayerPtr player) {
m_customSelectedWidget = fetchChild<ImageWidget>("customSelect");
for (uint8_t i = 0; i < EssentialItemCount; ++i)
m_essentialBarWidgets.append(fetchChild<ItemSlotWidget>(strf("essentialBar%s", i + 1)));
m_essentialBarWidgets.append(fetchChild<ItemSlotWidget>(strf("essentialBar{}", i + 1)));
m_essentialSelectedWidget = fetchChild<ImageWidget>("essentialSelect");
}

View File

@ -46,7 +46,7 @@ void EditBookmarkDialog::show() {
}
auto assets = Root::singleton().assets();
fetchChild<ImageWidget>("imgIcon")->setImage(strf("/interface/bookmarks/icons/%s.png", m_bookmark.icon));
fetchChild<ImageWidget>("imgIcon")->setImage(strf("/interface/bookmarks/icons/{}.png", m_bookmark.icon));
fetchChild<LabelWidget>("lblPlanetName")->setText(m_bookmark.targetName);
fetchChild<TextBoxWidget>("name")->setText(m_bookmark.bookmarkName, false);
@ -75,7 +75,7 @@ void EditBookmarkDialog::close() {
void setupBookmarkEntry(WidgetPtr const& entry, TeleportBookmark const& bookmark) {
entry->fetchChild<LabelWidget>("name")->setText(bookmark.bookmarkName);
entry->fetchChild<LabelWidget>("planetName")->setText(bookmark.targetName);
entry->fetchChild<ImageWidget>("icon")->setImage(strf("/interface/bookmarks/icons/%s.png", bookmark.icon));
entry->fetchChild<ImageWidget>("icon")->setImage(strf("/interface/bookmarks/icons/{}.png", bookmark.icon));
}
}

View File

@ -165,7 +165,7 @@ void CharCreationPane::createPlayer() {
throw CharCreationException("The charPreview portrait has the wrong type.");
}
} catch (CharCreationException const& e) {
Logger::error("Character Preview portrait was not found in the json specification. %s", outputException(e, false));
Logger::error("Character Preview portrait was not found in the json specification. {}", outputException(e, false));
}
}
@ -269,15 +269,15 @@ void CharCreationPane::changed() {
fetchChild<LabelWidget>("labelPortrait")->setText(labels[8]);
fetchChild<LabelWidget>("labelPersonality")->setText(labels[9]);
fetchChild<ButtonWidget>(strf("species.%s", m_speciesChoice))->check();
fetchChild<ButtonWidget>(strf("gender.%s", genderIdx))->check();
auto modeButton = fetchChild<ButtonWidget>(strf("mode.%s", m_modeChoice));
fetchChild<ButtonWidget>(strf("species.{}", m_speciesChoice))->check();
fetchChild<ButtonWidget>(strf("gender.{}", genderIdx))->check();
auto modeButton = fetchChild<ButtonWidget>(strf("mode.{}", m_modeChoice));
modeButton->check();
setLabel("labelMode", modeButton->data().getString("description", "fail"));
// Update the gender images for the new species
for (size_t i = 0; i < species.genderOptions.size(); i++)
fetchChild<ButtonWidget>(strf("gender.%s", i))->setOverlayImage(species.genderOptions[i].image);
fetchChild<ButtonWidget>(strf("gender.{}", i))->setOverlayImage(species.genderOptions[i].image);
for (auto const& nameDefPair : root.speciesDatabase()->allSpecies()) {
String name;
@ -286,7 +286,7 @@ void CharCreationPane::changed() {
// NOTE: Probably not hot enough to matter, but this contains and indexOf makes this loop
// O(n^2). This is less than ideal.
if (m_speciesList.contains(name)) {
auto bw = fetchChild<ButtonWidget>(strf("species.%s", m_speciesList.indexOf(name)));
auto bw = fetchChild<ButtonWidget>(strf("species.{}", m_speciesList.indexOf(name)));
if (bw)
bw->setOverlayImage(def->options().genderOptions[genderIdx].characterImage);
}

View File

@ -183,7 +183,7 @@ void Chat::addMessages(List<ChatReceivedMessage> const& messages, bool showPane)
guiContext.setFontSize(m_fontSize);
StringList lines;
if (message.fromNick != "" && message.portrait == "")
lines = guiContext.wrapInterfaceText(strf("<%s> %s", message.fromNick, message.text), wrapWidth);
lines = guiContext.wrapInterfaceText(strf("<{}> {}", message.fromNick, message.text), wrapWidth);
else
lines = guiContext.wrapInterfaceText(message.text, wrapWidth);
@ -196,9 +196,9 @@ void Chat::addMessages(List<ChatReceivedMessage> const& messages, bool showPane)
}
if (message.fromNick != "")
Logger::info("Chat: <%s> %s", message.fromNick, message.text);
Logger::info("Chat: <{}> {}", message.fromNick, message.text);
else
Logger::info("Chat: %s", message.text);
Logger::info("Chat: {}", message.text);
}
if (showPane) {

View File

@ -189,7 +189,7 @@ void Cinematic::render() {
m_completable = true;
if (!values.alpha)
continue;
auto frame = strf("%s", ((int)values.frame) % panel->animationFrames);
auto frame = strf("{}", ((int)values.frame) % panel->animationFrames);
auto alphaColor = Color::rgbaf(1.0f, 1.0f, 1.0f, values.alpha);
for (auto const& d : panel->drawables) {
Drawable drawable = Drawable(d.set("image", d.getString("image").replaceTags(StringMap<String>{{"species", playerSpecies}, {"frame", frame}})));

View File

@ -92,11 +92,11 @@ StringList ClientCommandProcessor::handleCommand(String const& commandLine) {
}
return result;
} catch (ShellParsingException const& e) {
Logger::error("Shell parsing exception: %s", outputException(e, false));
Logger::error("Shell parsing exception: {}", outputException(e, false));
return {"Shell parsing exception"};
} catch (std::exception const& e) {
Logger::error("Exception caught handling client command %s: %s", commandLine, outputException(e, true));
return {strf("Exception caught handling client command %s", commandLine)};
Logger::error("Exception caught handling client command {}: {}", commandLine, outputException(e, true));
return {strf("Exception caught handling client command {}", commandLine)};
}
}
@ -114,7 +114,7 @@ String ClientCommandProcessor::reload() {
}
String ClientCommandProcessor::whoami() {
return strf("Client: You are %s. You are %san Admin.",
return strf("Client: You are {}. You are {}an Admin.",
m_universeClient->mainPlayer()->name(), m_universeClient->mainPlayer()->isAdmin() ? "" : "not ");
}
@ -122,7 +122,7 @@ String ClientCommandProcessor::gravity() {
if (!adminCommandAllowed())
return "You must be an admin to use this command.";
return strf("%s", m_universeClient->worldClient()->gravity(m_universeClient->mainPlayer()->position()));
return strf("{}", m_universeClient->worldClient()->gravity(m_universeClient->mainPlayer()->position()));
}
String ClientCommandProcessor::debug() {
@ -130,14 +130,14 @@ String ClientCommandProcessor::debug() {
return "You must be an admin to use this command.";
m_debugDisplayEnabled = !m_debugDisplayEnabled;
return strf("Debug display %s", m_debugDisplayEnabled ? "enabled" : "disabled");
return strf("Debug display {}", m_debugDisplayEnabled ? "enabled" : "disabled");
}
String ClientCommandProcessor::boxes() {
if (!adminCommandAllowed())
return "You must be an admin to use this command.";
return strf("Geometry debug display %s",
return strf("Geometry debug display {}",
m_universeClient->worldClient()->toggleCollisionDebug()
? "enabled" : "disabled");
}
@ -146,7 +146,7 @@ String ClientCommandProcessor::fullbright() {
if (!adminCommandAllowed())
return "You must be an admin to use this command.";
return strf("Fullbright render lighting %s",
return strf("Fullbright render lighting {}",
m_universeClient->worldClient()->toggleFullbright()
? "enabled" : "disabled");
}
@ -156,7 +156,7 @@ String ClientCommandProcessor::setGravity(StringList const& arguments) {
return "You must be an admin to use this command.";
m_universeClient->worldClient()->overrideGravity(lexicalCast<float>(arguments.at(0)));
return strf("Gravity set to %s, the change is LOCAL ONLY", arguments.at(0));
return strf("Gravity set to {}, the change is LOCAL ONLY", arguments.at(0));
}
String ClientCommandProcessor::resetGravity() {
@ -172,13 +172,13 @@ String ClientCommandProcessor::fixedCamera() {
return "You must be an admin to use this command.";
m_fixedCameraEnabled = !m_fixedCameraEnabled;
return strf("Fixed camera %s", m_fixedCameraEnabled ? "enabled" : "disabled");
return strf("Fixed camera {}", m_fixedCameraEnabled ? "enabled" : "disabled");
}
String ClientCommandProcessor::monochromeLighting() {
bool monochrome = !Root::singleton().configuration()->get("monochromeLighting").toBool();
Root::singleton().configuration()->set("monochromeLighting", monochrome);
return strf("Monochrome lighting %s", monochrome ? "enabled" : "disabled");
return strf("Monochrome lighting {}", monochrome ? "enabled" : "disabled");
}
String ClientCommandProcessor::radioMessage(StringList const& arguments) {
@ -222,7 +222,7 @@ String ClientCommandProcessor::completeQuest(StringList const& arguments) {
return "You must be an admin to use this command.";
m_universeClient->questManager()->getQuest(arguments.at(0))->complete();
return strf("Quest %s complete", arguments.at(0));
return strf("Quest {} complete", arguments.at(0));
}
String ClientCommandProcessor::failQuest(StringList const& arguments) {
@ -230,7 +230,7 @@ String ClientCommandProcessor::failQuest(StringList const& arguments) {
return "You must be an admin to use this command.";
m_universeClient->questManager()->getQuest(arguments.at(0))->fail();
return strf("Quest %s failed", arguments.at(0));
return strf("Quest {} failed", arguments.at(0));
}
String ClientCommandProcessor::previewNewQuest(StringList const& arguments) {
@ -269,12 +269,12 @@ String ClientCommandProcessor::clearScannedObjects() {
}
String ClientCommandProcessor::playTime() {
return strf("Total play time: %s", Time::printDuration(m_universeClient->mainPlayer()->log()->playTime()));
return strf("Total play time: {}", Time::printDuration(m_universeClient->mainPlayer()->log()->playTime()));
}
String ClientCommandProcessor::deathCount() {
auto deaths = m_universeClient->mainPlayer()->log()->deathCount();
return strf("Total deaths: %s%s", deaths, deaths == 0 ? ". Well done!" : "");
return strf("Total deaths: {}{}", deaths, deaths == 0 ? ". Well done!" : "");
}
String ClientCommandProcessor::cinema(StringList const& arguments) {
@ -284,7 +284,7 @@ String ClientCommandProcessor::cinema(StringList const& arguments) {
m_cinematicOverlay->load(Root::singleton().assets()->json(arguments.at(0)));
if (arguments.size() > 1)
m_cinematicOverlay->setTime(lexicalCast<float>(arguments.at(1)));
return strf("Started cinematic %s at %s", arguments.at(0), arguments.size() > 1 ? arguments.at(1) : "beginning");
return strf("Started cinematic {} at {}", arguments.at(0), arguments.size() > 1 ? arguments.at(1) : "beginning");
}
String ClientCommandProcessor::suicide() {
@ -315,7 +315,7 @@ String ClientCommandProcessor::statistic(StringList const& arguments) {
StringList values;
for (String const& statName : arguments) {
values.append(strf("%s = %s", statName, m_universeClient->statistics()->stat(statName)));
values.append(strf("{} = {}", statName, m_universeClient->statistics()->stat(statName)));
}
return values.join("\n");
}
@ -331,9 +331,9 @@ String ClientCommandProcessor::giveEssentialItem(StringList const& arguments) {
auto item = Root::singleton().itemDatabase()->item(ItemDescriptor(arguments.at(0)));
auto slot = EssentialItemNames.getLeft(arguments.at(1));
m_universeClient->mainPlayer()->inventory()->setEssentialItem(slot, item);
return strf("Put %s in player slot %s", item->name(), arguments.at(1));
return strf("Put {} in player slot {}", item->name(), arguments.at(1));
} catch (MapException const& e) {
return strf("Invalid essential item slot %s.", arguments.at(1));
return strf("Invalid essential item slot {}.", arguments.at(1));
}
}
@ -345,7 +345,7 @@ String ClientCommandProcessor::makeTechAvailable(StringList const& arguments) {
return "Not enouch arguments to /maketechavailable";
m_universeClient->mainPlayer()->techs()->makeAvailable(arguments.at(0));
return strf("Added %s to player's visible techs", arguments.at(0));
return strf("Added {} to player's visible techs", arguments.at(0));
}
String ClientCommandProcessor::enableTech(StringList const& arguments) {
@ -357,7 +357,7 @@ String ClientCommandProcessor::enableTech(StringList const& arguments) {
m_universeClient->mainPlayer()->techs()->makeAvailable(arguments.at(0));
m_universeClient->mainPlayer()->techs()->enable(arguments.at(0));
return strf("Player tech %s enabled", arguments.at(0));
return strf("Player tech {} enabled", arguments.at(0));
}
String ClientCommandProcessor::upgradeShip(StringList const& arguments) {

View File

@ -126,7 +126,7 @@ void CodexInterface::setupPageText() {
if (m_currentCodex) {
m_pageContent->setText(m_currentCodex->page(m_currentPage));
m_pageLabelWidget->show();
m_pageNumberWidget->setText(strf("%d of %d", m_currentPage + 1, m_currentCodex->pageCount()));
m_pageNumberWidget->setText(strf("{} of {}", m_currentPage + 1, m_currentCodex->pageCount()));
m_titleLabel->setText(m_currentCodex->title());
m_nextPageButton->setEnabled(m_currentPage < m_currentCodex->pageCount() - 1);
m_prevPageButton->setEnabled(m_currentPage > 0);

View File

@ -129,7 +129,7 @@ ContainerPane::ContainerPane(WorldClientPtr worldClient, PlayerPtr player, Conta
m_reader.construct(guiConfig.get("gui"), this);
if (auto countWidget = fetchChild<LabelWidget>("count"))
countWidget->setText(countWidget->text().replace("<slots>", strf("%s", container->containerSize())));
countWidget->setText(countWidget->text().replace("<slots>", strf("{}", container->containerSize())));
m_itemBag = make_shared<ItemBag>(container->containerSize());
auto items = container->containerItems();

View File

@ -294,7 +294,7 @@ void CraftingPane::update() {
updateCraftButtons();
}
setLabel("lblPlayerMoney", strf("%s", (int)m_player->currency("money")));
setLabel("lblPlayerMoney", strf("{}", (int)m_player->currency("money")));
Pane::update();
}
@ -405,7 +405,7 @@ void CraftingPane::setupWidget(WidgetPtr const& widget, ItemRecipe const& recipe
String name = item->friendlyName();
if (recipe.output.count() > 1)
name = strf("%s (x%s)", name, recipe.output.count());
name = strf("{} (x{})", name, recipe.output.count());
auto itemName = widget->fetchChild<LabelWidget>("itemName");
auto notcraftableoverlay = widget->fetchChild<ImageWidget>("notcraftableoverlay");
@ -421,7 +421,7 @@ void CraftingPane::setupWidget(WidgetPtr const& widget, ItemRecipe const& recipe
}
if (price > 0) {
widget->setLabel("priceLabel", strf("%s", price));
widget->setLabel("priceLabel", strf("{}", price));
if (auto icon = widget->fetchChild<ImageWidget>("moneyIcon"))
icon->setVisibility(true);
} else {
@ -463,7 +463,7 @@ PanePtr CraftingPane::setupTooltip(ItemRecipe const& recipe) {
auto widget = guiList->addItem();
widget->fetchChild<LabelWidget>("itemName")->setText(item->friendlyName());
auto countWidget = widget->fetchChild<LabelWidget>("count");
countWidget->setText(strf("%s/%s", availableCount, requiredCount));
countWidget->setText(strf("{}/{}", availableCount, requiredCount));
if (availableCount < requiredCount)
countWidget->setColor(Color::Red);
else
@ -616,7 +616,7 @@ void CraftingPane::countTextChanged() {
void CraftingPane::countChanged() {
if (m_textBox)
m_textBox->setText(strf("x%s", m_count), false);
m_textBox->setText(strf("x{}", m_count), false);
}
List<ItemRecipe> CraftingPane::determineRecipes() {

View File

@ -148,7 +148,7 @@ void GraphicsMenu::syncGui() {
} else {
resSlider->setVal(m_resList.size() - 1);
}
fetchChild<LabelWidget>("resValueLabel")->setText(strf("%dx%d", res[0], res[1]));
fetchChild<LabelWidget>("resValueLabel")->setText(strf("{}x{}", res[0], res[1]));
auto zoomSlider = fetchChild<SliderBarWidget>("zoomSlider");
auto zoomIt = std::lower_bound(m_zoomList.begin(), m_zoomList.end(), m_localChanges.get("zoomLevel").toFloat());
@ -159,7 +159,7 @@ void GraphicsMenu::syncGui() {
} else {
zoomSlider->setVal(m_zoomList.size() - 1);
}
fetchChild<LabelWidget>("zoomValueLabel")->setText(strf("%dx", m_localChanges.get("zoomLevel").toInt()));
fetchChild<LabelWidget>("zoomValueLabel")->setText(strf("{}x", m_localChanges.get("zoomLevel").toInt()));
fetchChild<ButtonWidget>("speechBubbleCheckbox")->setChecked(m_localChanges.get("speechBubbles").toBool());

View File

@ -87,7 +87,7 @@ InventoryPane::InventoryPane(MainInterface* parent, PlayerPtr player, ContainerI
for (auto name : bagOrder) {
auto itemGrid = itemBagConfig.get(name).getString("itemGrid");
invWindowReader.registerCallback(itemGrid, bind(leftClickCallback, name, _1));
invWindowReader.registerCallback(strf("%s.right", itemGrid), bind(bagGridCallback, name, _1));
invWindowReader.registerCallback(strf("{}.right", itemGrid), bind(bagGridCallback, name, _1));
}
invWindowReader.registerCallback("close", [=](Widget*) {
@ -195,7 +195,7 @@ PanePtr InventoryPane::createTooltip(Vec2I const& screenPosition) {
auto techDatabase = Root::singleton().techDatabase();
for (auto const& p : TechTypeNames) {
if (auto techIcon = fetchChild<ImageWidget>(strf("tech%s", p.second))) {
if (auto techIcon = fetchChild<ImageWidget>(strf("tech{}", p.second))) {
if (techIcon->screenBoundRect().contains(screenPosition)) {
if (auto techModule = m_player->techs()->equippedTechs().maybe(p.first))
return SimpleTooltipBuilder::buildTooltip(techDatabase->tech(*techModule).description);
@ -277,7 +277,7 @@ void InventoryPane::update() {
auto techDatabase = Root::singleton().techDatabase();
for (auto const& p : TechTypeNames) {
if (auto techIcon = fetchChild<ImageWidget>(strf("tech%s", p.second))) {
if (auto techIcon = fetchChild<ImageWidget>(strf("tech{}", p.second))) {
if (auto techModule = m_player->techs()->equippedTechs().maybe(p.first))
techIcon->setImage(techDatabase->tech(*techModule).icon);
else
@ -315,25 +315,25 @@ void InventoryPane::update() {
techOverlay->setVisibility(m_player->techOverridden());
auto healthLabel = fetchChild<LabelWidget>("healthtext");
healthLabel->setText(strf("%d", m_player->maxHealth()));
healthLabel->setText(strf("{}", m_player->maxHealth()));
auto energyLabel = fetchChild<LabelWidget>("energytext");
energyLabel->setText(strf("%d", m_player->maxEnergy()));
energyLabel->setText(strf("{}", m_player->maxEnergy()));
auto weaponLabel = fetchChild<LabelWidget>("weapontext");
weaponLabel->setText(strf("%d%%", ceil(m_player->powerMultiplier() * 100)));
weaponLabel->setText(strf("{}%", ceil(m_player->powerMultiplier() * 100)));
auto defenseLabel = fetchChild<LabelWidget>("defensetext");
if (m_player->protection() == 0)
defenseLabel->setText("--");
else
defenseLabel->setText(strf("%d", ceil(m_player->protection())));
defenseLabel->setText(strf("{}", ceil(m_player->protection())));
auto moneyLabel = fetchChild<LabelWidget>("lblMoney");
moneyLabel->setText(strf("%d", m_player->currency("money")));
moneyLabel->setText(strf("{}", m_player->currency("money")));
if (m_player->currency("essence") > 0) {
fetchChild<ImageWidget>("imgEssenceIcon")->show();
auto essenceLabel = fetchChild<LabelWidget>("lblEssence");
essenceLabel->show();
essenceLabel->setText(strf("%d", m_player->currency("essence")));
essenceLabel->setText(strf("{}", m_player->currency("essence")));
} else {
fetchChild<ImageWidget>("imgEssenceIcon")->hide();
fetchChild<LabelWidget>("lblEssence")->hide();
@ -357,14 +357,14 @@ void InventoryPane::update() {
auto attackLabel = fetchChild<LabelWidget>("companionAttackStat");
if (auto attack = pet->stat("attack")) {
attackLabel->setText(strf("%.0f", *attack));
attackLabel->setText(strf("{:.0f}", *attack));
} else {
attackLabel->setText("");
}
auto defenseLabel = fetchChild<LabelWidget>("companionDefenseStat");
if (auto defense = pet->stat("defense")) {
defenseLabel->setText(strf("%.0f", *defense));
defenseLabel->setText(strf("{:.0f}", *defense));
} else {
defenseLabel->setText("");
}

View File

@ -81,7 +81,7 @@ void ItemTooltipBuilder::buildItemDescriptionInner(
container->fetchChild<ItemSlotWidget>("icon")->setItem(item);
container->setLabel("nameLabel", item->name());
container->setLabel("countLabel", strf("%s", item->count()));
container->setLabel("countLabel", strf("{}", item->count()));
container->setLabel("rarityLabel", RarityNames.getRight(item->rarity()).titleCase());
@ -90,8 +90,8 @@ void ItemTooltipBuilder::buildItemDescriptionInner(
else
container->setLabel("handednessLabel", "1-Handed");
container->setLabel("countLabel", strf("%s", item->instanceValue("fuelAmount", 0).toUInt() * item->count()));
container->setLabel("priceLabel", strf("%s", (int)item->price()));
container->setLabel("countLabel", strf("{}", item->instanceValue("fuelAmount", 0).toUInt() * item->count()));
container->setLabel("priceLabel", strf("{}", (int)item->price()));
if (auto objectItem = as<ObjectItem>(item)) {
try {
@ -103,13 +103,13 @@ void ItemTooltipBuilder::buildItemDescriptionInner(
}
if (objectItem->tooltipKind() == "container")
container->setLabel("slotCountLabel", strf("Holds %s Items", objectItem->instanceValue("slotCount")));
container->setLabel("slotCountLabel", strf("Holds {} Items", objectItem->instanceValue("slotCount")));
title = object->shortDescription();
subTitle = categoryDisplayName(object->category());
description = object->description();
} catch (StarException const& e) {
Logger::error("Failed to instantiate object for object item tooltip. %s", outputException(e, false));
Logger::error("Failed to instantiate object for object item tooltip. {}", outputException(e, false));
}
} else {
if (container->containsChild("objectImage")) {
@ -137,9 +137,9 @@ void ItemTooltipBuilder::buildItemDescriptionInner(
}
if (auto fireable = as<FireableItem>(item)) {
container->setLabel("cooldownTimeLabel", strf("%.2f", fireable->cooldownTime()));
container->setLabel("windupTimeLabel", strf("%.2f", fireable->windupTime()));
container->setLabel("speedLabel", strf("%.2f", 1.0f / (fireable->cooldownTime() + fireable->windupTime())));
container->setLabel("cooldownTimeLabel", strf("{:.2f}", fireable->cooldownTime()));
container->setLabel("windupTimeLabel", strf("{:.2f}", fireable->windupTime()));
container->setLabel("speedLabel", strf("{:.2f}", 1.0f / (fireable->cooldownTime() + fireable->windupTime())));
}
if (container->containsChild("largeImage")) {
@ -198,21 +198,21 @@ void ItemTooltipBuilder::describePersistentEffect(
auto listItem = container->addItem();
listItem->fetchChild<ImageWidget>("statusImage")
->setImage(statsConfig.get(baseMultiplier->statName).getString("icon"));
listItem->setLabel("statusLabel", strf("%s%%", (baseMultiplier->baseMultiplier - 1) * 100));
listItem->setLabel("statusLabel", strf("{}%", (baseMultiplier->baseMultiplier - 1) * 100));
}
} else if (auto valueModifier = modifierEffect->ptr<StatValueModifier>()) {
if (statsConfig.contains(valueModifier->statName)) {
auto listItem = container->addItem();
listItem->fetchChild<ImageWidget>("statusImage")
->setImage(statsConfig.get(valueModifier->statName).getString("icon"));
listItem->setLabel("statusLabel", strf("%s%s", valueModifier->value < 0 ? "-" : "", valueModifier->value));
listItem->setLabel("statusLabel", strf("{}{}", valueModifier->value < 0 ? "-" : "", valueModifier->value));
}
} else if (auto effectiveMultiplier = modifierEffect->ptr<StatEffectiveMultiplier>()) {
if (statsConfig.contains(effectiveMultiplier->statName)) {
auto listItem = container->addItem();
listItem->fetchChild<ImageWidget>("statusImage")
->setImage(statsConfig.get(effectiveMultiplier->statName).getString("icon"));
listItem->setLabel("statusLabel", strf("%s%%", (effectiveMultiplier->effectiveMultiplier - 1) * 100));
listItem->setLabel("statusLabel", strf("{}%", (effectiveMultiplier->effectiveMultiplier - 1) * 100));
}
}
}

View File

@ -128,7 +128,7 @@ void KeybindingsMenu::buildListsFromConfig() {
for (auto const& bindingEntry : bindings.get(actionString).iterateArray())
inputDesc.append(inputDescriptorFromJson(bindingEntry));
} catch (StarException const& e) {
Logger::warn("Could not load keybinding for %s. %s\n", actionString, e.what());
Logger::warn("Could not load keybinding for {}. {}\n", actionString, e.what());
}
m_childToAction.insert({newListMember->fetchChild<ButtonWidget>("boundKeys").get(), action});

View File

@ -681,7 +681,7 @@ void MainInterface::update() {
}
m_messageOverflow++;
m_overflowMessage->message = m_config->overflowMessageText.replace("<count>", strf("%s", m_messageOverflow));
m_overflowMessage->message = m_config->overflowMessageText.replace("<count>", strf("{}", m_messageOverflow));
m_overflowMessage->cooldown = m_config->messageTime;
if (auto oldest = m_messages.sorted([](GuiMessagePtr a, GuiMessagePtr b) { return a->cooldown < b->cooldown; }).maybeFirst())
m_overflowMessage->cooldown = oldest.value()->cooldown;
@ -862,11 +862,11 @@ void MainInterface::queueItemPickupText(ItemPtr const& item) {
auto countMessPair = m_itemDropMessages.get(descriptor.singular());
auto newCount = item->count() + countMessPair.first;
auto message = countMessPair.second;
message->message = strf("%s - %s", item->friendlyName(), newCount);
message->message = strf("{} - {}", item->friendlyName(), newCount);
message->cooldown = m_config->messageTime;
m_itemDropMessages[descriptor.singular()] = {newCount, message};
} else {
auto message = make_shared<GuiMessage>(strf("%s - %s", item->friendlyName(), item->count()), m_config->messageTime);
auto message = make_shared<GuiMessage>(strf("{} - {}", item->friendlyName(), item->count()), m_config->messageTime);
m_messages.append(message);
m_itemDropMessages[descriptor.singular()] = {item->count(), message};
}
@ -929,7 +929,7 @@ PanePtr MainInterface::createEscapeDialog() {
});
escapeDialogReader.construct(assets->json("/interface.config:escapeDialog"), escapeDialogPtr);
escapeDialog->fetchChild<LabelWidget>("lblversion")->setText(strf("Starbound - %s (%s)", StarVersionString, StarArchitectureString));
escapeDialog->fetchChild<LabelWidget>("lblversion")->setText(strf("Starbound - {} ({})", StarVersionString, StarArchitectureString));
return escapeDialog;
}
@ -1268,7 +1268,7 @@ void MainInterface::renderDebug() {
int counter = 0;
for (auto const& pair : logMapValues) {
TextPositioning positioning = {Vec2F(m_config->debugOffset[0], windowHeight() - m_config->debugOffset[1] - m_config->fontSize * interfaceScale() * counter)};
m_debugTextRect.combine(m_guiContext->determineTextSize(strf("%s: %s", pair.first, pair.second), positioning).padded(m_config->debugBackgroundPad));
m_debugTextRect.combine(m_guiContext->determineTextSize(strf("{}: {}", pair.first, pair.second), positioning).padded(m_config->debugBackgroundPad));
++counter;
}
@ -1281,7 +1281,7 @@ void MainInterface::renderDebug() {
counter = 0;
for (auto const& pair : logMapValues) {
TextPositioning positioning = {Vec2F(m_config->debugOffset[0], windowHeight() - m_config->debugOffset[1] - m_config->fontSize * interfaceScale() * counter)};
m_guiContext->renderText(strf("%s: %s", pair.first, pair.second), positioning);
m_guiContext->renderText(strf("{}: {}", pair.first, pair.second), positioning);
++counter;
}
m_guiContext->setFontColor(Vec4B::filled(255));

View File

@ -236,13 +236,13 @@ void MerchantPane::setupWidget(WidgetPtr const& widget, Json const& itemConfig)
String name = item->friendlyName();
if (item->count() > 1)
name = strf("%s (x%s)", name, item->count());
name = strf("{} (x{})", name, item->count());
auto itemName = widget->fetchChild<LabelWidget>("itemName");
itemName->setText(name);
unsigned price = ceil(itemConfig.getInt("price", item->price()) * m_buyFactor);
widget->setLabel("priceLabel", strf("%s", price));
widget->setLabel("priceLabel", strf("{}", price));
widget->setData(price);
bool unavailable = price > m_player->currency("money");
@ -287,7 +287,7 @@ void MerchantPane::updateBuyTotal() {
else
m_buyTotal = 0;
m_buyTotalLabel->setText(strf("%s", m_buyTotal));
m_buyTotalLabel->setText(strf("{}", m_buyTotal));
if (m_selectedIndex != NPos && m_buyCount > 0)
m_buyButton->enable();
@ -332,7 +332,7 @@ void MerchantPane::updateSellTotal() {
if (item)
m_sellTotal += round(item->price() * m_sellFactor);
}
m_sellTotalLabel->setText(strf("%s", m_sellTotal));
m_sellTotalLabel->setText(strf("{}", m_sellTotal));
if (m_sellTotal > 0)
m_sellButton->enable();
else
@ -366,7 +366,7 @@ int MerchantPane::maxBuyCount() {
}
void MerchantPane::countChanged() {
m_countTextBox->setText(strf("x%s", m_buyCount));
m_countTextBox->setText(strf("x{}", m_buyCount));
updateBuyTotal();
}

View File

@ -236,7 +236,7 @@ void QuestLogInterface::fetchData() {
else if (filter.equalsIgnoreCase("completed"))
showQuests(m_manager->listCompletedQuests());
else
throw StarException(strf("Unknown quest filter '%s'", filter));
throw StarException(strf("Unknown quest filter '{}'", filter));
}
void QuestLogInterface::showQuests(List<QuestPtr> quests) {
@ -422,7 +422,7 @@ QuestCompleteInterface::QuestCompleteInterface(QuestPtr const& quest, PlayerPtr
commonSetup(config, m_quest->completionText(), "QuestComplete");
if (auto moneyLabel = fetchChild<LabelWidget>("lblMoneyAmount"))
moneyLabel->setText(strf("%s", m_quest->money()));
moneyLabel->setText(strf("{}", m_quest->money()));
disableScissoring();
}

View File

@ -51,7 +51,7 @@ void RadioMessagePopup::update() {
if (m_popupStage == PopupStage::AnimateIn) {
int frame = floor((1.0f - m_stageTimer.percent()) * m_animateInFrames);
setBG("", strf("%s:%s", m_animateInImage, frame), "");
setBG("", strf("{}:{}", m_animateInImage, frame), "");
} else if (m_popupStage == PopupStage::ScrollText) {
int frame =
int((m_stageTimer.timer / m_message.portraitSpeed) * m_message.portraitFrames) % m_message.portraitFrames;
@ -62,7 +62,7 @@ void RadioMessagePopup::update() {
// you're cool, just stay cool, cool person
} else if (m_popupStage == PopupStage::AnimateOut) {
int frame = floor((1.0f - m_stageTimer.percent()) * m_animateOutFrames);
setBG("", strf("%s:%s", m_animateOutImage, frame), "");
setBG("", strf("{}:{}", m_animateOutImage, frame), "");
}
m_slideTimer = min(m_slideTimer + WorldTimestep, m_slideTime);
@ -128,7 +128,7 @@ void RadioMessagePopup::enterStage(PopupStage newStage) {
if (m_popupStage == PopupStage::Hidden) {
m_portraitImage->hide();
m_messageLabel->hide();
setBG("", strf("%s:0", m_animateInImage), "");
setBG("", strf("{}:0", m_animateInImage), "");
} else if (m_popupStage == PopupStage::AnimateIn) {
m_stageTimer = GameTimer(m_animateInTime);
m_portraitImage->hide();

View File

@ -179,7 +179,7 @@ LuaCallbacks ScriptPane::makePaneCallbacks() {
});
callbacks.registerCallback("addWidget", [this](Json const& newWidgetConfig, Maybe<String> const& newWidgetName) {
String name = newWidgetName.value(strf("%d", Random::randu64()));
String name = newWidgetName.value(strf("{}", Random::randu64()));
WidgetPtr newWidget = m_reader.makeSingle(name, newWidgetConfig);
this->addChild(name, newWidget);
});

View File

@ -159,7 +159,7 @@ void TeamBar::buildTeamBar() {
continue;
}
String cellName = strf("%s", controlIndex);
String cellName = strf("{}", controlIndex);
WidgetPtr cell = list->fetchChild(cellName);
if (!cell) {
@ -231,7 +231,7 @@ void TeamBar::buildTeamBar() {
noInviteImage->setVisibility(!couldInvite);
while (true) {
String cellName = strf("%s", controlIndex);
String cellName = strf("{}", controlIndex);
WidgetPtr cell = list->fetchChild(cellName);
if (!cell)
break;

View File

@ -57,7 +57,7 @@ TeleportDialog::TeleportDialog(UniverseClientPtr client,
entry->fetchChild<LabelWidget>("planetName")->setText(dest.getString("planetName", ""));
if (dest.contains("icon"))
entry->fetchChild<ImageWidget>("icon")->setImage(
strf("/interface/bookmarks/icons/%s.png", dest.getString("icon")));
strf("/interface/bookmarks/icons/{}.png", dest.getString("icon")));
entry->fetchChild<ButtonWidget>("editButton")->hide();
if (dest.getBool("mission", false)) {

View File

@ -180,7 +180,7 @@ LuaCallbacks LuaBindings::makeWidgetCallbacks(Widget* parentWidget, GuiReader* r
callbacks.registerCallback("addChild", [parentWidget, reader](String const& widgetName, Json const& newChildConfig, Maybe<String> const& newChildName) {
if (auto widget = parentWidget->fetchChild<Widget>(widgetName)) {
String name = newChildName.value(strf("%d", Random::randu64()));
String name = newChildName.value(strf("{}", Random::randu64()));
WidgetPtr newChild = reader->makeSingle(name, newChildConfig);
widget->addChild(name, newChild);
}

View File

@ -1084,10 +1084,10 @@ void ActorMovementController::doSetAnchorState(Maybe<EntityAnchorState> anchorSt
if (anchorState) {
auto anchorableEntity = as<AnchorableEntity>(world()->entity(anchorState->entityId));
if (!anchorableEntity)
throw ActorMovementControllerException::format("No such anchorable entity id %s in ActorMovementController::setAnchorState", anchorState->entityId);
throw ActorMovementControllerException::format("No such anchorable entity id {} in ActorMovementController::setAnchorState", anchorState->entityId);
entityAnchor = anchorableEntity->anchor(anchorState->positionIndex);
if (!entityAnchor)
throw ActorMovementControllerException::format("Anchor position %s is disabled ActorMovementController::setAnchorState", anchorState->positionIndex);
throw ActorMovementControllerException::format("Anchor position {} is disabled ActorMovementController::setAnchorState", anchorState->positionIndex);
}
if (!entityAnchor && m_entityAnchor && m_entityAnchor->exitBottomPosition) {
@ -1327,7 +1327,7 @@ Maybe<bool> PathController::move(ActorMovementController& movementController, Ac
m_edgeIndex++;
if (m_edgeIndex < m_path->size()) {
if (!validateEdge(movementController, m_path->at(m_edgeIndex))) {
// Logger::info("Path invalidated on %s %s %s", ActionNames.getRight(nextEdge.action), nextEdge.source.position, nextEdge.target.position);
// Logger::info("Path invalidated on {} {} {}", ActionNames.getRight(nextEdge.action), nextEdge.source.position, nextEdge.target.position);
reset();
return {};
}
@ -1351,7 +1351,7 @@ Maybe<bool> PathController::move(ActorMovementController& movementController, Ac
// Vec2F velocity = debugEdge.source.velocity.orMaybe(debugEdge.target.velocity).value({ 0.0, 0.0 });
// SpatialLogger::logPoint("world", debugEdge.source.position, Color::Yellow.toRgba());
// SpatialLogger::logLine("world", debugEdge.source.position, debugEdge.target.position, Color::Yellow.toRgba());
// SpatialLogger::logText("world", strf("%s %s", ActionNames.getRight(debugEdge.action), curVelocity), debugEdge.source.position, Color::Yellow.toRgba());
// SpatialLogger::logText("world", strf("{} {}", ActionNames.getRight(debugEdge.action), curVelocity), debugEdge.source.position, Color::Yellow.toRgba());
// }
// }

View File

@ -62,7 +62,7 @@ AiSpeech AiDatabase::noMissionsSpeech() const {
}
String AiDatabase::portraitImage(String const& species, String const& frame) const {
return strf("/ai/%s:%s", m_speciesParameters.get(species).portraitFrames, frame);
return strf("/ai/{}:{}", m_speciesParameters.get(species).portraitFrames, frame);
}
Animation AiDatabase::animation(String const& species, String const& animationName) const {

View File

@ -92,7 +92,7 @@ NodeParameterValue replaceBehaviorTag(NodeParameterValue const& parameter, Strin
if (auto replace = treeParameters.maybe(treeKey)) {
return *replace;
} else {
throw StarException(strf("No parameter specified for tag '%s'", key));
throw StarException(strf("No parameter specified for tag '{}'", key));
}
}
}
@ -110,7 +110,7 @@ Maybe<String> replaceOutputBehaviorTag(Maybe<String> const& output, StringMap<No
else
return {};
} else {
throw StarException(strf("No parameter specified for tag '%s'", *out));
throw StarException(strf("No parameter specified for tag '{}'", *out));
}
}
}
@ -170,7 +170,7 @@ BehaviorDatabase::BehaviorDatabase() {
m_nodeOutput.set(node.first, output);
}
} catch (StarException const& e) {
throw StarException(strf("Could not load nodes file \'%s\'", file), e);
throw StarException(strf("Could not load nodes file \'{}\'", file), e);
}
}
@ -182,11 +182,11 @@ BehaviorDatabase::BehaviorDatabase() {
auto name = config.getString("name");
if (m_configs.contains(name))
throw StarException(strf("Duplicate behavior tree \'%s\'", name));
throw StarException(strf("Duplicate behavior tree \'{}\'", name));
m_configs[name] = config;
} catch (StarException const& e) {
throw StarException(strf("Could not load behavior file \'%s\'", file), e);
throw StarException(strf("Could not load behavior file \'{}\'", file), e);
}
}
@ -198,7 +198,7 @@ BehaviorDatabase::BehaviorDatabase() {
BehaviorTreeConstPtr BehaviorDatabase::behaviorTree(String const& name) const {
if (!m_behaviors.contains(name))
throw StarException(strf("No such behavior tree \'%s\'", name));
throw StarException(strf("No such behavior tree \'{}\'", name));
return m_behaviors.get(name);
}
@ -219,7 +219,7 @@ BehaviorTreeConstPtr BehaviorDatabase::buildTree(Json const& config, StringMap<N
Json BehaviorDatabase::behaviorConfig(String const& name) const {
if (!m_configs.contains(name))
throw StarException(strf("No such behavior tree \'%s\'", name));
throw StarException(strf("No such behavior tree \'{}\'", name));
return m_configs.get(name);
}
@ -246,7 +246,7 @@ CompositeNode BehaviorDatabase::compositeNode(Json const& config, StringMap<Node
return RandomizeNode(children);
// above statement needs to be exhaustive
throw StarException(strf("Composite node type '%s' could not be created from JSON", CompositeTypeNames.getRight(type)));
throw StarException(strf("Composite node type '{}' could not be created from JSON", CompositeTypeNames.getRight(type)));
}
BehaviorNodeConstPtr BehaviorDatabase::behaviorNode(Json const& json, StringMap<NodeParameterValue> const& treeParameters, BehaviorTree& tree) const {
@ -292,7 +292,7 @@ BehaviorNodeConstPtr BehaviorDatabase::behaviorNode(Json const& json, StringMap<
}
// above statement must be exhaustive
throw StarException(strf("Behavior node type '%s' could not be created from JSON", BehaviorNodeTypeNames.getRight(type)));
throw StarException(strf("Behavior node type '{}' could not be created from JSON", BehaviorNodeTypeNames.getRight(type)));
}
}

View File

@ -67,7 +67,7 @@ LuaTable Blackboard::parameters(StringMap<NodeParameter> const& parameters, uint
// dumb special case for allowing a vec2 of blackboard number keys
if (p.second.first == NodeParameterType::Vec2) {
if (value.type() != Json::Type::Array)
throw StarException(strf("Vec2 parameter not of array type for key %s", p.first, value));
throw StarException(strf("Vec2 parameter not of array type for key {}", p.first, value));
JsonArray vector = value.toArray();
LuaTable luaVector = m_luaContext.engine().createTable();
for (int i = 0; i < 2; i++) {
@ -210,7 +210,7 @@ NodeStatus BehaviorState::runAction(ActionNode const& node, NodeState& state) {
try {
result = thread.resume<ActionReturn>(parameters, blackboardPtr(), id, m_lastDt).value(ActionReturn(NodeStatus::Invalid, LuaNil));
} catch (LuaException const& e) {
throw StarException(strf("Lua Exception caught running action node %s in behavior %s: %s", node.name, m_tree->name, outputException(e, false)));
throw StarException(strf("Lua Exception caught running action node {} in behavior {}: {}", node.name, m_tree->name, outputException(e, false)));
}
auto status = get<0>(result);
@ -222,7 +222,7 @@ NodeStatus BehaviorState::runAction(ActionNode const& node, NodeState& state) {
try {
result = thread.resume<ActionReturn>(m_lastDt).value(ActionReturn(NodeStatus::Invalid, LuaNil));
} catch (LuaException const& e) {
throw StarException(strf("Lua Exception caught resuming action node %s in behavior %s: %s", node.name, m_tree->name, outputException(e, false)));
throw StarException(strf("Lua Exception caught resuming action node {} in behavior {}: {}", node.name, m_tree->name, outputException(e, false)));
}
auto status = get<0>(result);
@ -246,7 +246,7 @@ NodeStatus BehaviorState::runDecorator(DecoratorNode const& node, NodeState& sta
try {
status = thread.resume<NodeStatus>(parameters, blackboardPtr(), id).value(NodeStatus::Invalid);
} catch (LuaException const& e) {
throw StarException(strf("Lua Exception caught initializing decorator node %s in behavior %s: %s", node.name, m_tree->name, outputException(e, false)));
throw StarException(strf("Lua Exception caught initializing decorator node {} in behavior {}: {}", node.name, m_tree->name, outputException(e, false)));
}
if (status == NodeStatus::Success || status == NodeStatus::Failure)
return status;
@ -262,7 +262,7 @@ NodeStatus BehaviorState::runDecorator(DecoratorNode const& node, NodeState& sta
try {
status = decorator.thread.resume<NodeStatus>(childStatus).value(NodeStatus::Invalid);
} catch (LuaException const& e) {
throw StarException(strf("Lua Exception caught resuming decorator node %s in behavior %s: %s", node.name, m_tree->name, outputException(e, false)));
throw StarException(strf("Lua Exception caught resuming decorator node {} in behavior {}: {}", node.name, m_tree->name, outputException(e, false)));
}
} else {
return NodeStatus::Running;
@ -287,7 +287,7 @@ NodeStatus BehaviorState::runComposite(CompositeNode const& node, NodeState& sta
else if (node.is<RandomizeNode>())
status = runRandomize(node.get<RandomizeNode>(), state);
else
throw StarException(strf("Unable to run composite node type with variant type index %s", node.typeIndex()));
throw StarException(strf("Unable to run composite node type with variant type index {}", node.typeIndex()));
return status;
}

View File

@ -24,7 +24,7 @@ BiomeDatabase::BiomeDatabase() {
auto name = parameters.getString("name");
if (map.contains(name))
throw BiomeException(strf("Duplicate %s generator name '%s'", type, name));
throw BiomeException(strf("Duplicate {} generator name '{}'", type, name));
map[name] = {path, name, parameters};
}
};
@ -125,20 +125,20 @@ StringList BiomeDatabase::weatherNames() const {
WeatherType BiomeDatabase::weatherType(String const& name) const {
if (!m_weathers.contains(name))
throw BiomeException(strf("No such weather type '%s'", name));
throw BiomeException(strf("No such weather type '{}'", name));
auto config = m_weathers.get(name);
try {
return WeatherType(config.parameters, config.path);
} catch (MapException const& e) {
throw BiomeException(strf("Required key not found in weather config %s", config.path), e);
throw BiomeException(strf("Required key not found in weather config {}", config.path), e);
}
}
BiomePtr BiomeDatabase::createBiome(String const& biomeName, uint64_t seed, float verticalMidPoint, float threatLevel) const {
if (!m_biomes.contains(biomeName))
throw BiomeException(strf("No such biome '%s'", biomeName));
throw BiomeException(strf("No such biome '{}'", biomeName));
auto& root = Root::singleton();
auto materialDatabase = root.materialDatabase();
@ -183,7 +183,7 @@ BiomePtr BiomeDatabase::createBiome(String const& biomeName, uint64_t seed, floa
return biome;
} catch (std::exception const& cause) {
throw BiomeException(strf("Failed to parse biome: '%s'", biomeName), cause);
throw BiomeException(strf("Failed to parse biome: '{}'", biomeName), cause);
}
}

View File

@ -23,7 +23,7 @@ BiomeItem variantToBiomeItem(Json const& store) {
} else if (type == "microDungeon") {
return MicroDungeonNames(jsonToStringSet(store.get(1)));
} else {
throw BiomeException(strf("Unrecognized biome item type '%s'", type));
throw BiomeException(strf("Unrecognized biome item type '{}'", type));
}
}
@ -138,7 +138,7 @@ Maybe<BiomeItem> BiomeItemDistribution::createItem(Json const& config, RandomSou
return BiomeItem{MicroDungeonNames(jsonToStringSet(config.get("microdungeons", JsonArray())))};
} else {
throw BiomeException(strf("No such item type '%s' in item distribution", type));
throw BiomeException(strf("No such item type '{}' in item distribution", type));
}
return {};

View File

@ -31,11 +31,11 @@ CelestialCoordinate::CelestialCoordinate(Json const& variant) : CelestialCoordin
m_satelliteOrbitNumber = lexicalCast<int>(plist.at(4));
if (m_planetaryOrbitNumber <= 0)
throw CelestialException(strf("Planetary body number out of range in '%s'", id));
throw CelestialException(strf("Planetary body number out of range in '{}'", id));
if (m_satelliteOrbitNumber < 0)
throw CelestialException(strf("Satellite body number out of range in '%s'", id));
throw CelestialException(strf("Satellite body number out of range in '{}'", id));
} catch (StarException const& e) {
throw CelestialException(strf("Error parsing CelestialCoordinate from '%s'", id), e);
throw CelestialException(strf("Error parsing CelestialCoordinate from '{}'", id), e);
}
}
} else if (variant.isType(Json::Type::Object)) {
@ -44,7 +44,7 @@ CelestialCoordinate::CelestialCoordinate(Json const& variant) : CelestialCoordin
m_satelliteOrbitNumber = variant.getInt("satellite", 0);
} else if (!variant.isNull()) {
throw CelestialException(
strf("Improper variant type %s trying to convert to SystemCoordinate", variant.typeName()));
strf("Improper variant type {} trying to convert to SystemCoordinate", variant.typeName()));
}
}
@ -153,12 +153,12 @@ std::ostream& operator<<(std::ostream& os, CelestialCoordinate const& coord) {
if (coord.isNull()) {
os << "null";
} else {
format(os, "%s:%s:%s", coord.m_location[0], coord.m_location[1], coord.m_location[2]);
format(os, "{}:{}:{}", coord.m_location[0], coord.m_location[1], coord.m_location[2]);
if (coord.m_planetaryOrbitNumber) {
format(os, ":%s", coord.m_planetaryOrbitNumber);
format(os, ":{}", coord.m_planetaryOrbitNumber);
if (coord.m_satelliteOrbitNumber)
format(os, ":%s", coord.m_satelliteOrbitNumber);
format(os, ":{}", coord.m_satelliteOrbitNumber);
}
}

Some files were not shown because too many files have changed in this diff Show More