diff --git a/CMakeLists.txt b/CMakeLists.txt index ffea36ab..2e2c5513 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -12,6 +12,7 @@ set(CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/vendor/POCO/cmake) # Several plugin options option(ENABLE_API21 "Build for 2.1 API." OFF) +option(ENABLE_DISCORD "Enable built-in Discord support" ON) option(ENABLE_OFFICIAL "Enable compatibility with official legacy plug-in" ON) #option(FORCE_32BIT_BIN "Create a 32-bit executable binary if the compiler defaults to 64-bit." OFF) # This option should only be available in certain conditions diff --git a/module/CMakeLists.txt b/module/CMakeLists.txt index f6778270..99a5e4e0 100644 --- a/module/CMakeLists.txt +++ b/module/CMakeLists.txt @@ -133,6 +133,12 @@ if(WIN32 OR MINGW) endif() # Link to base libraries target_link_libraries(SqModule Squirrel fmt::fmt SimpleINI TinyDir xxHash ConcurrentQueue SAJSON CPR PUGIXML CivetWeb maxminddb libzmq-static) +# Enable built-in Discord support +if(ENABLE_DISCORD) + target_link_libraries(SqModule DPP) + target_compile_definitions(SqModule PRIVATE VCMP_ENABLE_DISCORD=1) + target_sources(SqModule PRIVATE Library/DPP.cpp Library/DPP.hpp Library/DPPEv.cpp Library/DPPEv.hpp Library/DPPTy.cpp Library/DPPTy.hpp) +endif() # Link to POCO libraries target_link_libraries(SqModule Poco::Foundation Poco::Crypto Poco::Data Poco::Net Poco::JSON Poco::XML) # Does POCO have SQLite support? diff --git a/module/Core.cpp b/module/Core.cpp index 583f3918..87a82475 100644 --- a/module/Core.cpp +++ b/module/Core.cpp @@ -49,6 +49,9 @@ extern void TerminateRoutines(); extern void TerminateCommands(); extern void TerminateSignals(); extern void TerminateNet(); +#ifdef VCMP_ENABLE_DISCORD + extern void TerminateDPP(); +#endif extern void TerminatePocoNet(); extern void TerminatePocoData(); @@ -549,6 +552,11 @@ void Core::Terminate(bool shutdown) // Release announcers AnnounceTerminate(); cLogDbg(m_Verbosity >= 1, "Announcer terminated"); + // Release DPP +#ifdef VCMP_ENABLE_DISCORD + TerminateDPP(); + cLogDbg(m_Verbosity >= 1, "Discord terminated"); +#endif // Release network TerminateNet(); cLogDbg(m_Verbosity >= 1, "Network terminated"); diff --git a/module/Library/DPP.cpp b/module/Library/DPP.cpp new file mode 100644 index 00000000..c8d1a73d --- /dev/null +++ b/module/Library/DPP.cpp @@ -0,0 +1,800 @@ +// ------------------------------------------------------------------------------------------------ +#include "Library/DPP.hpp" +#include "Core/Signal.hpp" + +// ------------------------------------------------------------------------------------------------ +#include + +// ------------------------------------------------------------------------------------------------ +#include + +// ------------------------------------------------------------------------------------------------ +namespace SqMod { + +// ------------------------------------------------------------------------------------------------ +SQMOD_DECL_TYPENAME(SqDppCluster, _SC("SqDppCluster")) + +// ------------------------------------------------------------------------------------------------ +void TerminateDPP() +{ + // Go over all clusters and try to terminate them + for (DpCluster * inst = DpCluster::sHead; inst && inst->mNext != DpCluster::sHead; inst = inst->mNext) + { + inst->Terminate(); // Terminate() the cluster + } +} + +// ------------------------------------------------------------------------------------------------ +void ProcessDPP() +{ + // Go over all clusters and allow them to process data + for (DpCluster * inst = DpCluster::sHead; inst && inst->mNext != DpCluster::sHead; inst = inst->mNext) + { + inst->Process(); + } +} + +// ------------------------------------------------------------------------------------------------ +extern void Register_DPPTy(HSQUIRRELVM vm, Table & ns); +extern void Register_DPPEv(HSQUIRRELVM vm, Table & ns); + +// ================================================================================================ +void Register_DPP(HSQUIRRELVM vm) +{ + Table ns(vm); + // -------------------------------------------------------------------------------------------- + { + Table ens(vm); + Register_DPPEv(vm, ens); + ns.Bind(_SC("Events"), ens); + } + // Register base types + Register_DPPTy(vm, ns); + // -------------------------------------------------------------------------------------------- + ns.Bind(_SC("Cluster"), + Class< DpCluster, NoCopy< DpCluster > >(vm, SqDppCluster::Str) + // Constructors + .Ctor< StackStrF & >() + .Ctor< StackStrF &, SQInteger >() + .Ctor< StackStrF &, SQInteger, SQInteger >() + .Ctor< StackStrF &, SQInteger, SQInteger, SQInteger >() + .Ctor< StackStrF &, SQInteger, SQInteger, SQInteger, SQInteger >() + .Ctor< StackStrF &, SQInteger, SQInteger, SQInteger, SQInteger, bool >() + .Ctor< StackStrF &, SQInteger, SQInteger, SQInteger, SQInteger, bool, const DpCachePolicy & >() + // Meta-methods + .SquirrelFunc(_SC("_typename"), &SqDppCluster::Fn) + // Member Properties + .Prop(_SC("On"), &DpCluster::GetEvents) + .Prop(_SC("UpTime"), &DpCluster::UpTime) + // Member Methods + .Func(_SC("Start"), &DpCluster::Start) + .Func(_SC("Log"), &DpCluster::Log) + .Func(_SC("GetDmChannel"), &DpCluster::GetDmChannel) + .Func(_SC("SetDmChannel"), &DpCluster::SetDmChannel) + .Func(_SC("SetPresence"), &DpCluster::SetPresence) + .Func(_SC("EnableEvent"), &DpCluster::EnableEvent) + .Func(_SC("DisableEvent"), &DpCluster::DisableEvent) + ); + // -------------------------------------------------------------------------------------------- + ns.Func(_SC("HasVoice"), dpp::utility::has_voice); + + RootTable(vm).Bind(_SC("SqDiscord"), ns); +} + +// ------------------------------------------------------------------------------------------------ +SQMOD_NODISCARD LightObj EventToScriptObject(uint8_t type, uintptr_t data); +void EventInvokeCleanup(uint8_t type, uintptr_t data); + +// ------------------------------------------------------------------------------------------------ +void DpCluster::Process(bool force) +{ + // Is there a valid connection? + if (!mC && !force) + { + return; // No point in going forward + } + DpInternalEvent event; + // Retrieve each event individually and process it + for (size_t count = mQueue.size_approx(), n = 0; n <= count; ++n) + { + // Try to get an event from the queue + if (mQueue.try_dequeue(event)) + { + // Fetch the type of event + const auto type = event.GetType(); + // Fetch the event itself + const auto data = event.GetData(); + // Is this a valid event and is anyone listening to it? + if (event.mData == 0 || mEvents[type].first == nullptr || mEvents[type].first->IsEmpty()) + { + continue; // Move on + } + // Transform the event instance into a script object + LightObj obj = EventToScriptObject(type, data); + // Allow the script to take ownership of the event instance now + event.Reset(); + // Forward the call to the associated signal + (*mEvents[type].first)(obj); + // Allow the event instance to clean itself + EventInvokeCleanup(type, data); + } + } +} + +/* ================================================================================================ + * Event handlers. +*/ +void DpCluster::OnVoiceStateUpdate(const dpp::voice_state_update_t & ev) +{ + mQueue.enqueue(DpInternalEvent(DpEventID::VoiceStateUpdate, new DpVoiceStateUpdateEvent(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnLog(const dpp::log_t & ev) +{ + mQueue.enqueue(DpInternalEvent(DpEventID::Log, new DpLogEvent(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnGuildJoinRequestDelete(const dpp::guild_join_request_delete_t & ev) +{ + mQueue.enqueue(DpInternalEvent(DpEventID::GuildJoinRequestDelete, new DpGuildJoinRequestDeleteEvent(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnInteractionCreate(const dpp::interaction_create_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::InteractionCreate, new dpp::interaction_create_t(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnButtonClick(const dpp::button_click_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::ButtonClick, new dpp::button_click_t(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnSelectClick(const dpp::select_click_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::SelectClick, new dpp::select_click_t(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnGuildDelete(const dpp::guild_delete_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::GuildDelete, new dpp::guild_delete_t(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnChannelDelete(const dpp::channel_delete_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::ChannelDelete, new dpp::channel_delete_t(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnChannelUpdate(const dpp::channel_update_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::ChannelUpdate, new dpp::channel_update_t(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnReady(const dpp::ready_t & ev) +{ + mQueue.enqueue(DpInternalEvent(DpEventID::Ready, new DpReadyEvent(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnMessageDelete(const dpp::message_delete_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::MessageDelete, new dpp::message_delete_t(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnApplicationCommandDelete(const dpp::application_command_delete_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::ApplicationCommandDelete, new dpp::application_command_delete_t(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnGuildMemberRemove(const dpp::guild_member_remove_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::GuildMemberRemove, new dpp::guild_member_remove_t(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnApplicationCommandCreate(const dpp::application_command_create_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::ApplicationCommandCreate, new dpp::application_command_create_t(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnResumed(const dpp::resumed_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::Resumed, new dpp::resumed_t(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnGuildRoleCreate(const dpp::guild_role_create_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::GuildRoleCreate, new dpp::guild_role_create_t(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnTypingStart(const dpp::typing_start_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::TypingStart, new dpp::typing_start_t(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnMessageReactionAdd(const dpp::message_reaction_add_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::MessageReactionAdd, new dpp::message_reaction_add_t(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnGuildMembersChunk(const dpp::guild_members_chunk_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::GuildMembersChunk, new dpp::guild_members_chunk_t(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnMessageReactionRemove(const dpp::message_reaction_remove_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::MessageReactionRemove, new dpp::message_reaction_remove_t(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnGuildCreate(const dpp::guild_create_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::GuildCreate, new dpp::guild_create_t(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnChannelCreate(const dpp::channel_create_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::ChannelCreate, new dpp::channel_create_t(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnMessageReactionRemoveEmoji(const dpp::message_reaction_remove_emoji_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::MessageReactionRemoveEmoji, new dpp::message_reaction_remove_emoji_t(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnMessageDeleteBulk(const dpp::message_delete_bulk_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::MessageDeleteBulk, new dpp::message_delete_bulk_t(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnGuildRoleUpdate(const dpp::guild_role_update_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::GuildRoleUpdate, new dpp::guild_role_update_t(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnGuildRoleDelete(const dpp::guild_role_delete_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::GuildRoleDelete, new dpp::guild_role_delete_t(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnChannelPinsUpdate(const dpp::channel_pins_update_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::ChannelPinsUpdate, new dpp::channel_pins_update_t(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnMessageReactionRemoveAll(const dpp::message_reaction_remove_all_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::MessageReactionRemoveAll, new dpp::message_reaction_remove_all_t(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnVoiceServerUpdate(const dpp::voice_server_update_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::VoiceServerUpdate, new dpp::voice_server_update_t(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnGuildEmojisUpdate(const dpp::guild_emojis_update_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::GuildEmojisUpdate, new dpp::guild_emojis_update_t(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnGuildStickersUpdate(const dpp::guild_stickers_update_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::GuildStickersUpdate, new dpp::guild_stickers_update_t(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnPresenceUpdate(const dpp::presence_update_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::PresenceUpdate, new dpp::presence_update_t(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnWebhooksUpdate(const dpp::webhooks_update_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::WebhooksUpdate, new dpp::webhooks_update_t(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnGuildMemberAdd(const dpp::guild_member_add_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::GuildMemberAdd, new dpp::guild_member_add_t(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnInviteDelete(const dpp::invite_delete_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::InviteDelete, new dpp::invite_delete_t(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnGuildUpdate(const dpp::guild_update_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::GuildUpdate, new dpp::guild_update_t(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnGuildIntegrationsUpdate(const dpp::guild_integrations_update_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::GuildIntegrationsUpdate, new dpp::guild_integrations_update_t(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnGuildMemberUpdate(const dpp::guild_member_update_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::GuildMemberUpdate, new dpp::guild_member_update_t(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnApplicationCommandUpdate(const dpp::application_command_update_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::ApplicationCommandUpdate, new dpp::application_command_update_t(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnInviteCreate(const dpp::invite_create_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::InviteCreate, new dpp::invite_create_t(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnMessageUpdate(const dpp::message_update_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::MessageUpdate, new dpp::message_update_t(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnUserUpdate(const dpp::user_update_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::UserUpdate, new dpp::user_update_t(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnMessageCreate(const dpp::message_create_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::MessageCreate, new dpp::message_create_t(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnGuildBanAdd(const dpp::guild_ban_add_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::GuildBanAdd, new dpp::guild_ban_add_t(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnGuildBanRemove(const dpp::guild_ban_remove_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::GuildBanRemove, new dpp::guild_ban_remove_t(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnIntegrationCreate(const dpp::integration_create_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::IntegrationCreate, new dpp::integration_create_t(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnIntegrationUpdate(const dpp::integration_update_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::IntegrationUpdate, new dpp::integration_update_t(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnIntegrationDelete(const dpp::integration_delete_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::IntegrationDelete, new dpp::integration_delete_t(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnThreadCreate(const dpp::thread_create_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::ThreadCreate, new dpp::thread_create_t(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnThreadUpdate(const dpp::thread_update_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::ThreadUpdate, new dpp::thread_update_t(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnThreadDelete(const dpp::thread_delete_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::ThreadDelete, new dpp::thread_delete_t(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnThreadListSync(const dpp::thread_list_sync_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::ThreadListSync, new dpp::thread_list_sync_t(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnThreadMemberUpdate(const dpp::thread_member_update_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::ThreadMemberUpdate, new dpp::thread_member_update_t(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnThreadMembersUpdate(const dpp::thread_members_update_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::ThreadMembersUpdate, new dpp::thread_members_update_t(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnVoiceBufferSend(const dpp::voice_buffer_send_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::VoiceBufferSend, new dpp::voice_buffer_send_t(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnVoiceUserTalking(const dpp::voice_user_talking_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::VoiceUserTalking, new dpp::voice_user_talking_t(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnVoiceReady(const dpp::voice_ready_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::VoiceReady, new dpp::voice_ready_t(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnVoiceReceive(const dpp::voice_receive_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::VoiceReceive, new dpp::voice_receive_t(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnVoiceTrackMarker(const dpp::voice_track_marker_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::VoiceTrackMarker, new dpp::voice_track_marker_t(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnStageInstanceCreate(const dpp::stage_instance_create_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::StageInstanceCreate, new dpp::stage_instance_create_t(ev))); +} +// ------------------------------------------------------------------------------------------------ +void DpCluster::OnStageInstanceDelete(const dpp::stage_instance_delete_t & ev) +{ + //mQueue.enqueue(DpInternalEvent(DpEventID::StageInstanceDelete, new dpp::stage_instance_delete_t(ev))); +} + +// ------------------------------------------------------------------------------------------------ +DpCluster & DpCluster::EnableEvent(SQInteger id) +{ + switch (id) + { + case DpEventID::VoiceStateUpdate: mC->on_voice_state_update([this](auto && e) { OnVoiceStateUpdate(std::forward< decltype(e) >(e)); }); break; + case DpEventID::Log: mC->on_log([this](auto && e) { OnLog(std::forward< decltype(e) >(e)); }); break; + case DpEventID::GuildJoinRequestDelete: mC->on_guild_join_request_delete([this](auto && e) { OnGuildJoinRequestDelete(std::forward< decltype(e) >(e)); }); break; + case DpEventID::InteractionCreate: mC->on_interaction_create([this](auto && e) { OnInteractionCreate(std::forward< decltype(e) >(e)); }); break; + case DpEventID::ButtonClick: mC->on_button_click([this](auto && e) { OnButtonClick(std::forward< decltype(e) >(e)); }); break; + case DpEventID::SelectClick: mC->on_select_click([this](auto && e) { OnSelectClick(std::forward< decltype(e) >(e)); }); break; + case DpEventID::GuildDelete: mC->on_guild_delete([this](auto && e) { OnGuildDelete(std::forward< decltype(e) >(e)); }); break; + case DpEventID::ChannelDelete: mC->on_channel_delete([this](auto && e) { OnChannelDelete(std::forward< decltype(e) >(e)); }); break; + case DpEventID::ChannelUpdate: mC->on_channel_update([this](auto && e) { OnChannelUpdate(std::forward< decltype(e) >(e)); }); break; + case DpEventID::Ready: mC->on_ready([this](auto && e) { OnReady(std::forward< decltype(e) >(e)); }); break; + case DpEventID::MessageDelete: mC->on_message_delete([this](auto && e) { OnMessageDelete(std::forward< decltype(e) >(e)); }); break; + case DpEventID::ApplicationCommandDelete: mC->on_application_command_delete([this](auto && e) { OnApplicationCommandDelete(std::forward< decltype(e) >(e)); }); break; + case DpEventID::GuildMemberRemove: mC->on_guild_member_remove([this](auto && e) { OnGuildMemberRemove(std::forward< decltype(e) >(e)); }); break; + case DpEventID::ApplicationCommandCreate: mC->on_application_command_create([this](auto && e) { OnApplicationCommandCreate(std::forward< decltype(e) >(e)); }); break; + case DpEventID::Resumed: mC->on_resumed([this](auto && e) { OnResumed(std::forward< decltype(e) >(e)); }); break; + case DpEventID::GuildRoleCreate: mC->on_guild_role_create([this](auto && e) { OnGuildRoleCreate(std::forward< decltype(e) >(e)); }); break; + case DpEventID::TypingStart: mC->on_typing_start([this](auto && e) { OnTypingStart(std::forward< decltype(e) >(e)); }); break; + case DpEventID::MessageReactionAdd: mC->on_message_reaction_add([this](auto && e) { OnMessageReactionAdd(std::forward< decltype(e) >(e)); }); break; + case DpEventID::GuildMembersChunk: mC->on_guild_members_chunk([this](auto && e) { OnGuildMembersChunk(std::forward< decltype(e) >(e)); }); break; + case DpEventID::MessageReactionRemove: mC->on_message_reaction_remove([this](auto && e) { OnMessageReactionRemove(std::forward< decltype(e) >(e)); }); break; + case DpEventID::GuildCreate: mC->on_guild_create([this](auto && e) { OnGuildCreate(std::forward< decltype(e) >(e)); }); break; + case DpEventID::ChannelCreate: mC->on_channel_create([this](auto && e) { OnChannelCreate(std::forward< decltype(e) >(e)); }); break; + case DpEventID::MessageReactionRemoveEmoji: mC->on_message_reaction_remove_emoji([this](auto && e) { OnMessageReactionRemoveEmoji(std::forward< decltype(e) >(e)); }); break; + case DpEventID::MessageDeleteBulk: mC->on_message_delete_bulk([this](auto && e) { OnMessageDeleteBulk(std::forward< decltype(e) >(e)); }); break; + case DpEventID::GuildRoleUpdate: mC->on_guild_role_update([this](auto && e) { OnGuildRoleUpdate(std::forward< decltype(e) >(e)); }); break; + case DpEventID::GuildRoleDelete: mC->on_guild_role_delete([this](auto && e) { OnGuildRoleDelete(std::forward< decltype(e) >(e)); }); break; + case DpEventID::ChannelPinsUpdate: mC->on_channel_pins_update([this](auto && e) { OnChannelPinsUpdate(std::forward< decltype(e) >(e)); }); break; + case DpEventID::MessageReactionRemoveAll: mC->on_message_reaction_remove_all([this](auto && e) { OnMessageReactionRemoveAll(std::forward< decltype(e) >(e)); }); break; + case DpEventID::VoiceServerUpdate: mC->on_voice_server_update([this](auto && e) { OnVoiceServerUpdate(std::forward< decltype(e) >(e)); }); break; + case DpEventID::GuildEmojisUpdate: mC->on_guild_emojis_update([this](auto && e) { OnGuildEmojisUpdate(std::forward< decltype(e) >(e)); }); break; + case DpEventID::GuildStickersUpdate: mC->on_guild_stickers_update([this](auto && e) { OnGuildStickersUpdate(std::forward< decltype(e) >(e)); }); break; + case DpEventID::PresenceUpdate: mC->on_presence_update([this](auto && e) { OnPresenceUpdate(std::forward< decltype(e) >(e)); }); break; + case DpEventID::WebhooksUpdate: mC->on_webhooks_update([this](auto && e) { OnWebhooksUpdate(std::forward< decltype(e) >(e)); }); break; + case DpEventID::GuildMemberAdd: mC->on_guild_member_add([this](auto && e) { OnGuildMemberAdd(std::forward< decltype(e) >(e)); }); break; + case DpEventID::InviteDelete: mC->on_invite_delete([this](auto && e) { OnInviteDelete(std::forward< decltype(e) >(e)); }); break; + case DpEventID::GuildUpdate: mC->on_guild_update([this](auto && e) { OnGuildUpdate(std::forward< decltype(e) >(e)); }); break; + case DpEventID::GuildIntegrationsUpdate: mC->on_guild_integrations_update([this](auto && e) { OnGuildIntegrationsUpdate(std::forward< decltype(e) >(e)); }); break; + case DpEventID::GuildMemberUpdate: mC->on_guild_member_update([this](auto && e) { OnGuildMemberUpdate(std::forward< decltype(e) >(e)); }); break; + case DpEventID::ApplicationCommandUpdate: mC->on_application_command_update([this](auto && e) { OnApplicationCommandUpdate(std::forward< decltype(e) >(e)); }); break; + case DpEventID::InviteCreate: mC->on_invite_create([this](auto && e) { OnInviteCreate(std::forward< decltype(e) >(e)); }); break; + case DpEventID::MessageUpdate: mC->on_message_update([this](auto && e) { OnMessageUpdate(std::forward< decltype(e) >(e)); }); break; + case DpEventID::UserUpdate: mC->on_user_update([this](auto && e) { OnUserUpdate(std::forward< decltype(e) >(e)); }); break; + case DpEventID::MessageCreate: mC->on_message_create([this](auto && e) { OnMessageCreate(std::forward< decltype(e) >(e)); }); break; + case DpEventID::GuildBanAdd: mC->on_guild_ban_add([this](auto && e) { OnGuildBanAdd(std::forward< decltype(e) >(e)); }); break; + case DpEventID::GuildBanRemove: mC->on_guild_ban_remove([this](auto && e) { OnGuildBanRemove(std::forward< decltype(e) >(e)); }); break; + case DpEventID::IntegrationCreate: mC->on_integration_create([this](auto && e) { OnIntegrationCreate(std::forward< decltype(e) >(e)); }); break; + case DpEventID::IntegrationUpdate: mC->on_integration_update([this](auto && e) { OnIntegrationUpdate(std::forward< decltype(e) >(e)); }); break; + case DpEventID::IntegrationDelete: mC->on_integration_delete([this](auto && e) { OnIntegrationDelete(std::forward< decltype(e) >(e)); }); break; + case DpEventID::ThreadCreate: mC->on_thread_create([this](auto && e) { OnThreadCreate(std::forward< decltype(e) >(e)); }); break; + case DpEventID::ThreadUpdate: mC->on_thread_update([this](auto && e) { OnThreadUpdate(std::forward< decltype(e) >(e)); }); break; + case DpEventID::ThreadDelete: mC->on_thread_delete([this](auto && e) { OnThreadDelete(std::forward< decltype(e) >(e)); }); break; + case DpEventID::ThreadListSync: mC->on_thread_list_sync([this](auto && e) { OnThreadListSync(std::forward< decltype(e) >(e)); }); break; + case DpEventID::ThreadMemberUpdate: mC->on_thread_member_update([this](auto && e) { OnThreadMemberUpdate(std::forward< decltype(e) >(e)); }); break; + case DpEventID::ThreadMembersUpdate: mC->on_thread_members_update([this](auto && e) { OnThreadMembersUpdate(std::forward< decltype(e) >(e)); }); break; + case DpEventID::VoiceBufferSend: mC->on_voice_buffer_send([this](auto && e) { OnVoiceBufferSend(std::forward< decltype(e) >(e)); }); break; + case DpEventID::VoiceUserTalking: mC->on_voice_user_talking([this](auto && e) { OnVoiceUserTalking(std::forward< decltype(e) >(e)); }); break; + case DpEventID::VoiceReady: mC->on_voice_ready([this](auto && e) { OnVoiceReady(std::forward< decltype(e) >(e)); }); break; + case DpEventID::VoiceReceive: mC->on_voice_receive([this](auto && e) { OnVoiceReceive(std::forward< decltype(e) >(e)); }); break; + case DpEventID::VoiceTrackMarker: mC->on_voice_track_marker([this](auto && e) { OnVoiceTrackMarker(std::forward< decltype(e) >(e)); }); break; + case DpEventID::StageInstanceCreate: mC->on_stage_instance_create([this](auto && e) { OnStageInstanceCreate(std::forward< decltype(e) >(e)); }); break; + case DpEventID::StageInstanceDelete: mC->on_stage_instance_delete([this](auto && e) { OnStageInstanceDelete(std::forward< decltype(e) >(e)); }); break; + case DpEventID::Max: // Fall through + default: STHROWF("Invalid discord event identifier {}", id); + } + // Allow chaining + return *this; +} + +// ------------------------------------------------------------------------------------------------ +DpCluster & DpCluster::DisableEvent(SQInteger id) +{ + switch (id) + { + case DpEventID::VoiceStateUpdate: mC->on_voice_state_update(std::function{}); break; + case DpEventID::Log: mC->on_log(std::function{}); break; + case DpEventID::GuildJoinRequestDelete: mC->on_guild_join_request_delete(std::function{}); break; + case DpEventID::InteractionCreate: mC->on_interaction_create(std::function{}); break; + case DpEventID::ButtonClick: mC->on_button_click(std::function{}); break; + case DpEventID::SelectClick: mC->on_select_click(std::function{}); break; + case DpEventID::GuildDelete: mC->on_guild_delete(std::function{}); break; + case DpEventID::ChannelDelete: mC->on_channel_delete(std::function{}); break; + case DpEventID::ChannelUpdate: mC->on_channel_update(std::function{}); break; + case DpEventID::Ready: mC->on_ready(std::function{}); break; + case DpEventID::MessageDelete: mC->on_message_delete(std::function{}); break; + case DpEventID::ApplicationCommandDelete: mC->on_application_command_delete(std::function{}); break; + case DpEventID::GuildMemberRemove: mC->on_guild_member_remove(std::function{}); break; + case DpEventID::ApplicationCommandCreate: mC->on_application_command_create(std::function{}); break; + case DpEventID::Resumed: mC->on_resumed(std::function{}); break; + case DpEventID::GuildRoleCreate: mC->on_guild_role_create(std::function{}); break; + case DpEventID::TypingStart: mC->on_typing_start(std::function{}); break; + case DpEventID::MessageReactionAdd: mC->on_message_reaction_add(std::function{}); break; + case DpEventID::GuildMembersChunk: mC->on_guild_members_chunk(std::function{}); break; + case DpEventID::MessageReactionRemove: mC->on_message_reaction_remove(std::function{}); break; + case DpEventID::GuildCreate: mC->on_guild_create(std::function{}); break; + case DpEventID::ChannelCreate: mC->on_channel_create(std::function{}); break; + case DpEventID::MessageReactionRemoveEmoji: mC->on_message_reaction_remove_emoji(std::function{}); break; + case DpEventID::MessageDeleteBulk: mC->on_message_delete_bulk(std::function{}); break; + case DpEventID::GuildRoleUpdate: mC->on_guild_role_update(std::function{}); break; + case DpEventID::GuildRoleDelete: mC->on_guild_role_delete(std::function{}); break; + case DpEventID::ChannelPinsUpdate: mC->on_channel_pins_update(std::function{}); break; + case DpEventID::MessageReactionRemoveAll: mC->on_message_reaction_remove_all(std::function{}); break; + case DpEventID::VoiceServerUpdate: mC->on_voice_server_update(std::function{}); break; + case DpEventID::GuildEmojisUpdate: mC->on_guild_emojis_update(std::function{}); break; + case DpEventID::GuildStickersUpdate: mC->on_guild_stickers_update(std::function{}); break; + case DpEventID::PresenceUpdate: mC->on_presence_update(std::function{}); break; + case DpEventID::WebhooksUpdate: mC->on_webhooks_update(std::function{}); break; + case DpEventID::GuildMemberAdd: mC->on_guild_member_add(std::function{}); break; + case DpEventID::InviteDelete: mC->on_invite_delete(std::function{}); break; + case DpEventID::GuildUpdate: mC->on_guild_update(std::function{}); break; + case DpEventID::GuildIntegrationsUpdate: mC->on_guild_integrations_update(std::function{}); break; + case DpEventID::GuildMemberUpdate: mC->on_guild_member_update(std::function{}); break; + case DpEventID::ApplicationCommandUpdate: mC->on_application_command_update(std::function{}); break; + case DpEventID::InviteCreate: mC->on_invite_create(std::function{}); break; + case DpEventID::MessageUpdate: mC->on_message_update(std::function{}); break; + case DpEventID::UserUpdate: mC->on_user_update(std::function{}); break; + case DpEventID::MessageCreate: mC->on_message_create(std::function{}); break; + case DpEventID::GuildBanAdd: mC->on_guild_ban_add(std::function{}); break; + case DpEventID::GuildBanRemove: mC->on_guild_ban_remove(std::function{}); break; + case DpEventID::IntegrationCreate: mC->on_integration_create(std::function{}); break; + case DpEventID::IntegrationUpdate: mC->on_integration_update(std::function{}); break; + case DpEventID::IntegrationDelete: mC->on_integration_delete(std::function{}); break; + case DpEventID::ThreadCreate: mC->on_thread_create(std::function{}); break; + case DpEventID::ThreadUpdate: mC->on_thread_update(std::function{}); break; + case DpEventID::ThreadDelete: mC->on_thread_delete(std::function{}); break; + case DpEventID::ThreadListSync: mC->on_thread_list_sync(std::function{}); break; + case DpEventID::ThreadMemberUpdate: mC->on_thread_member_update(std::function{}); break; + case DpEventID::ThreadMembersUpdate: mC->on_thread_members_update(std::function{}); break; + case DpEventID::VoiceBufferSend: mC->on_voice_buffer_send(std::function{}); break; + case DpEventID::VoiceUserTalking: mC->on_voice_user_talking(std::function{}); break; + case DpEventID::VoiceReady: mC->on_voice_ready(std::function{}); break; + case DpEventID::VoiceReceive: mC->on_voice_receive(std::function{}); break; + case DpEventID::VoiceTrackMarker: mC->on_voice_track_marker(std::function{}); break; + case DpEventID::StageInstanceCreate: mC->on_stage_instance_create(std::function{}); break; + case DpEventID::StageInstanceDelete: mC->on_stage_instance_delete(std::function{}); break; + case DpEventID::Max: // Fall through + default: STHROWF("Invalid discord event identifier {}", id); + } + // Allow chaining + return *this; +} + +// ------------------------------------------------------------------------------------------------ +void DpInternalEvent::Release() +{ + // Make sure we actually manage something + if (mData == 0) return; + // Fetch the type of data + const auto type = GetType(); + // Fetch the data itself + const auto data = GetData(); + // Identify data type + switch (type) + { + case DpEventID::VoiceStateUpdate: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::Log: delete reinterpret_cast< DpLogEvent * >(data); break; + case DpEventID::GuildJoinRequestDelete: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::InteractionCreate: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::ButtonClick: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::SelectClick: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::GuildDelete: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::ChannelDelete: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::ChannelUpdate: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::Ready: delete reinterpret_cast< DpReadyEvent * >(data); break; + case DpEventID::MessageDelete: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::ApplicationCommandDelete: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::GuildMemberRemove: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::ApplicationCommandCreate: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::Resumed: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::GuildRoleCreate: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::TypingStart: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::MessageReactionAdd: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::GuildMembersChunk: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::MessageReactionRemove: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::GuildCreate: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::ChannelCreate: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::MessageReactionRemoveEmoji: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::MessageDeleteBulk: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::GuildRoleUpdate: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::GuildRoleDelete: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::ChannelPinsUpdate: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::MessageReactionRemoveAll: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::VoiceServerUpdate: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::GuildEmojisUpdate: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::GuildStickersUpdate: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::PresenceUpdate: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::WebhooksUpdate: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::GuildMemberAdd: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::InviteDelete: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::GuildUpdate: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::GuildIntegrationsUpdate: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::GuildMemberUpdate: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::ApplicationCommandUpdate: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::InviteCreate: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::MessageUpdate: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::UserUpdate: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::MessageCreate: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::GuildBanAdd: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::GuildBanRemove: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::IntegrationCreate: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::IntegrationUpdate: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::IntegrationDelete: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::ThreadCreate: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::ThreadUpdate: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::ThreadDelete: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::ThreadListSync: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::ThreadMemberUpdate: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::ThreadMembersUpdate: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::VoiceBufferSend: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::VoiceUserTalking: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::VoiceReady: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::VoiceReceive: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::VoiceTrackMarker: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::StageInstanceCreate: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::StageInstanceDelete: delete reinterpret_cast< uint8_t * >(data); break; + case DpEventID::Max: // Fall through + default: LogFtl("Unrecognized discord event instance type"); assert(0); break; + } + // Forget about it + Reset(); +} + +// ------------------------------------------------------------------------------------------------ +SQMOD_NODISCARD LightObj EventToScriptObject(uint8_t type, uintptr_t data) +{ + switch (type) + { + case DpEventID::VoiceStateUpdate: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::Log: return LightObj(reinterpret_cast< DpLogEvent * >(data)); + case DpEventID::GuildJoinRequestDelete: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::InteractionCreate: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::ButtonClick: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::SelectClick: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::GuildDelete: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::ChannelDelete: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::ChannelUpdate: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::Ready: return LightObj(reinterpret_cast< DpReadyEvent * >(data)); + case DpEventID::MessageDelete: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::ApplicationCommandDelete: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::GuildMemberRemove: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::ApplicationCommandCreate: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::Resumed: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::GuildRoleCreate: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::TypingStart: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::MessageReactionAdd: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::GuildMembersChunk: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::MessageReactionRemove: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::GuildCreate: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::ChannelCreate: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::MessageReactionRemoveEmoji: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::MessageDeleteBulk: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::GuildRoleUpdate: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::GuildRoleDelete: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::ChannelPinsUpdate: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::MessageReactionRemoveAll: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::VoiceServerUpdate: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::GuildEmojisUpdate: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::GuildStickersUpdate: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::PresenceUpdate: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::WebhooksUpdate: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::GuildMemberAdd: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::InviteDelete: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::GuildUpdate: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::GuildIntegrationsUpdate: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::GuildMemberUpdate: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::ApplicationCommandUpdate: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::InviteCreate: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::MessageUpdate: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::UserUpdate: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::MessageCreate: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::GuildBanAdd: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::GuildBanRemove: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::IntegrationCreate: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::IntegrationUpdate: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::IntegrationDelete: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::ThreadCreate: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::ThreadUpdate: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::ThreadDelete: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::ThreadListSync: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::ThreadMemberUpdate: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::ThreadMembersUpdate: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::VoiceBufferSend: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::VoiceUserTalking: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::VoiceReady: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::VoiceReceive: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::VoiceTrackMarker: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::StageInstanceCreate: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::StageInstanceDelete: return LightObj(reinterpret_cast< uint8_t * >(data)); + case DpEventID::Max: // Fall through + default: assert(0); return LightObj{}; + } +} + +// ------------------------------------------------------------------------------------------------ +void EventInvokeCleanup(uint8_t type, uintptr_t data) +{ + switch (type) + { + case DpEventID::VoiceStateUpdate: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::Log: reinterpret_cast< DpLogEvent * >(data)->Cleanup(); break; + case DpEventID::GuildJoinRequestDelete: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::InteractionCreate: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::ButtonClick: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::SelectClick: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::GuildDelete: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::ChannelDelete: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::ChannelUpdate: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::Ready: reinterpret_cast< DpReadyEvent * >(data)->Cleanup(); break; + case DpEventID::MessageDelete: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::ApplicationCommandDelete: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::GuildMemberRemove: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::ApplicationCommandCreate: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::Resumed: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::GuildRoleCreate: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::TypingStart: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::MessageReactionAdd: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::GuildMembersChunk: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::MessageReactionRemove: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::GuildCreate: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::ChannelCreate: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::MessageReactionRemoveEmoji: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::MessageDeleteBulk: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::GuildRoleUpdate: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::GuildRoleDelete: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::ChannelPinsUpdate: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::MessageReactionRemoveAll: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::VoiceServerUpdate: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::GuildEmojisUpdate: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::GuildStickersUpdate: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::PresenceUpdate: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::WebhooksUpdate: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::GuildMemberAdd: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::InviteDelete: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::GuildUpdate: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::GuildIntegrationsUpdate: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::GuildMemberUpdate: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::ApplicationCommandUpdate: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::InviteCreate: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::MessageUpdate: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::UserUpdate: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::MessageCreate: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::GuildBanAdd: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::GuildBanRemove: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::IntegrationCreate: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::IntegrationUpdate: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::IntegrationDelete: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::ThreadCreate: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::ThreadUpdate: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::ThreadDelete: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::ThreadListSync: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::ThreadMemberUpdate: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::ThreadMembersUpdate: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::VoiceBufferSend: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::VoiceUserTalking: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::VoiceReady: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::VoiceReceive: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::VoiceTrackMarker: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::StageInstanceCreate: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::StageInstanceDelete: reinterpret_cast< uint8_t * >(data); break; + case DpEventID::Max: // Fall through + default: assert(0); return; + } +} + +} // Namespace:: SqMod diff --git a/module/Library/DPP.hpp b/module/Library/DPP.hpp new file mode 100644 index 00000000..ec7aaa57 --- /dev/null +++ b/module/Library/DPP.hpp @@ -0,0 +1,428 @@ +#pragma once + +// ------------------------------------------------------------------------------------------------ +#include "Library/DPPEv.hpp" +#include "Library/DPPTy.hpp" +#include "Core/Signal.hpp" + +// ------------------------------------------------------------------------------------------------ +#include +#include +#include + +// ------------------------------------------------------------------------------------------------ +#include +#include + +// ------------------------------------------------------------------------------------------------ +namespace SqMod { + +/* ------------------------------------------------------------------------------------------------ + * WebSocket frame. +*/ +struct DpInternalEvent +{ + /* -------------------------------------------------------------------------------------------- + * Event data. + */ + uint64_t mData{0llu}; + + /* -------------------------------------------------------------------------------------------- + * Default constructor. + */ + DpInternalEvent() noexcept = default; + + /* -------------------------------------------------------------------------------------------- + * Explicit constructor. + */ + DpInternalEvent(uint64_t type, void * data) noexcept + : mData((type << 56u) | reinterpret_cast< uint64_t >(data)) + { + } + + /* -------------------------------------------------------------------------------------------- + * Copy constructor (disabled). + */ + DpInternalEvent(const DpInternalEvent & o) = delete; + + /* -------------------------------------------------------------------------------------------- + * Move constructor. + */ + DpInternalEvent(DpInternalEvent && o) noexcept + : mData(o.mData) + { + o.mData = 0llu; // Take ownership + } + + /* -------------------------------------------------------------------------------------------- + * Destructor. + */ + ~DpInternalEvent() + { + Release(); + } + + /* -------------------------------------------------------------------------------------------- + * Copy assignment operator (disabled). + */ + DpInternalEvent & operator = (const DpInternalEvent & o) = delete; + + /* -------------------------------------------------------------------------------------------- + * Move assignment operator. + */ + DpInternalEvent & operator = (DpInternalEvent && o) noexcept + { + if (mData != o.mData) + { + // Release current information + Release(); + // Replicate members + mData = o.mData; + // Take ownership + o.mData = 0llu; + } + return *this; + } + + /* -------------------------------------------------------------------------------------------- + * Forget about the managed event data. + */ + void Reset() noexcept + { + mData = 0llu; + } + + /* -------------------------------------------------------------------------------------------- + * Retrieve the event type. + */ + SQMOD_NODISCARD uint8_t GetType() const noexcept + { + return static_cast< uint8_t >((mData >> 56u) & 0xFFllu); + } + + /* -------------------------------------------------------------------------------------------- + * Retrieve the event data. + */ + SQMOD_NODISCARD uintptr_t GetData() const noexcept + { + return static_cast< uintptr_t >((~(0xFFllu << 56u)) & mData); + } + + /* -------------------------------------------------------------------------------------------- + * Release associated event data, if any. + */ + void Release(); +}; + +/* ------------------------------------------------------------------------------------------------ + * The cluster class represents a group of shards and a command queue for sending and receiving + * commands from discord via HTTP. +*/ +struct DpCluster : public SqChainedInstances< DpCluster > +{ + /* -------------------------------------------------------------------------------------------- + * Queue of events generated from other threads. + */ + using EventQueue = moodycamel::ConcurrentQueue< DpInternalEvent >; + + /* -------------------------------------------------------------------------------------------- + * Managed cluster instance. + */ + std::unique_ptr< dpp::cluster > mC{nullptr}; + + /* -------------------------------------------------------------------------------------------- + * Event queue. + */ + EventQueue mQueue{4096}; + + /* -------------------------------------------------------------------------------------------- + * Explicit constructor. + */ + explicit DpCluster(StackStrF & token) + : mC(std::make_unique< dpp::cluster >(token.ToStr())) + , mQueue(4096) + { + Initialize(); + } + + /* -------------------------------------------------------------------------------------------- + * Explicit constructor. + */ + DpCluster(StackStrF & token, SQInteger intents) + : mC(std::make_unique< dpp::cluster >(token.ToStr(), static_cast< uint32_t >(intents))) + , mQueue(4096) + { + Initialize(); + } + + /* -------------------------------------------------------------------------------------------- + * Explicit constructor. + */ + DpCluster(StackStrF & token, SQInteger intents, SQInteger shards) + : mC(std::make_unique< dpp::cluster >(token.ToStr(), static_cast< uint32_t >(intents), static_cast< uint32_t >(shards))) + , mQueue(4096) + { + Initialize(); + } + + /* -------------------------------------------------------------------------------------------- + * Explicit constructor. + */ + DpCluster(StackStrF & token, SQInteger intents, SQInteger shards, SQInteger cluster_id) + : mC(std::make_unique< dpp::cluster >(token.ToStr(), static_cast< uint32_t >(intents), static_cast< uint32_t >(shards), static_cast< uint32_t >(cluster_id))) + , mQueue(4096) + { + Initialize(); + } + + /* -------------------------------------------------------------------------------------------- + * Explicit constructor. + */ + DpCluster(StackStrF & token, SQInteger intents, SQInteger shards, SQInteger cluster_id, SQInteger max_clusters) + : mC(std::make_unique< dpp::cluster >(token.ToStr(), static_cast< uint32_t >(intents), static_cast< uint32_t >(shards), static_cast< uint32_t >(cluster_id), static_cast< uint32_t >(max_clusters))) + , mQueue(4096) + { + Initialize(); + } + + /* -------------------------------------------------------------------------------------------- + * Explicit constructor. + */ + DpCluster(StackStrF & token, SQInteger intents, SQInteger shards, SQInteger cluster_id, SQInteger max_clusters, bool compressed) + : mC(std::make_unique< dpp::cluster >(token.ToStr(), static_cast< uint32_t >(intents), static_cast< uint32_t >(shards), static_cast< uint32_t >(cluster_id), static_cast< uint32_t >(max_clusters), compressed)) + , mQueue(4096) + { + Initialize(); + } + + /* -------------------------------------------------------------------------------------------- + * Explicit constructor. + */ + DpCluster(StackStrF & token, SQInteger intents, SQInteger shards, SQInteger cluster_id, SQInteger max_clusters, bool compressed, const DpCachePolicy & cp) + : mC(std::make_unique< dpp::cluster >(token.ToStr(), static_cast< uint32_t >(intents), static_cast< uint32_t >(shards), static_cast< uint32_t >(cluster_id), static_cast< uint32_t >(max_clusters), compressed, cp.ToNative())) + , mQueue(4096) + { + Initialize(); + } + + /* -------------------------------------------------------------------------------------------- + * Destructor. + */ + ~DpCluster() + { + DropEvents(); + // Forget about this instance + UnchainInstance(); + } + + /* -------------------------------------------------------------------------------------------- + * Start the cluster, connecting all its shards. Returns once all shards are connected. + */ + DpCluster & Start() + { + LogInf("Before start..."); + mC->start(true); + LogInf("After start..."); + return *this; + } + + /* -------------------------------------------------------------------------------------------- + * Log a message to whatever log the user is using. + */ + DpCluster & Log(SQInteger severity, StackStrF & message) + { + mC->log(static_cast< dpp::loglevel >(severity), message.ToStr()); + return *this; + } + + /* -------------------------------------------------------------------------------------------- + * Get the dm channel for a user id. + */ + SQMOD_NODISCARD dpp::snowflake GetDmChannel(dpp::snowflake user_id) const + { + return mC->get_dm_channel(static_cast< dpp::snowflake >(user_id)); + } + + /* -------------------------------------------------------------------------------------------- + * Set the dm channel id for a user id. + */ + DpCluster & SetDmChannel(dpp::snowflake user_id, dpp::snowflake channel_id) + { + mC->set_dm_channel(user_id, channel_id); + return *this; + } + + /* -------------------------------------------------------------------------------------------- + * Returns the uptime of the cluster. + */ + SQMOD_NODISCARD dpp::utility::uptime UpTime() const + { + return mC->uptime(); + } + + /* -------------------------------------------------------------------------------------------- + * Returns the uptime of the cluster. + */ + DpCluster & SetPresence(const DpPresence & p) + { + mC->set_presence(p); + return *this; + } + + // -------------------------------------------------------------------------------------------- + LightObj mSqEvents{}; // Table containing the emitted cluster events. + + /* -------------------------------------------------------------------------------------------- + * Retrieve the events table of this cluster. + */ + SQMOD_NODISCARD LightObj & GetEvents() + { + return mSqEvents; + } + + /* -------------------------------------------------------------------------------------------- + * Cluster signals. + */ + std::array< SignalPair, static_cast< size_t >(DpEventID::Max) > mEvents{}; + + /* -------------------------------------------------------------------------------------------- + * Process the cluster. + */ + void Process(bool force = false); + + /* -------------------------------------------------------------------------------------------- + * Terminate the cluster. + */ + void Terminate() + { + // Delete the cluster instance + mC.reset(); + // Release associated script objects + mSqEvents.Release(); + // Release event signal objects + DropEvents(); + } + + /* -------------------------------------------------------------------------------------------- + * Enable a certain event for the cluster. + */ + DpCluster & EnableEvent(SQInteger id); + + /* -------------------------------------------------------------------------------------------- + * Disable a certain event for the cluster. + */ + DpCluster & DisableEvent(SQInteger id); + +private: + + /* -------------------------------------------------------------------------------------------- + * Initialize the cluster. + */ + void Initialize() + { + InitEvents(); + // Remember this instance + ChainInstance(); + } + + /* -------------------------------------------------------------------------------------------- + * Signal initialization. + */ + void InitEvents() + { + // Ignore the call if already initialized + if (!mSqEvents.IsNull()) + { + return; + } + // Create a new table on the stack + sq_newtableex(SqVM(), 64); + // Grab the table object from the stack + mSqEvents = LightObj(-1, SqVM()); + // Pop the table object from the stack + sq_pop(SqVM(), 1); + // Proceed to initializing the events + for (size_t i = 0; i < mEvents.size(); ++i) + { + InitSignalPair(mEvents[i], mSqEvents, DpEventID::NAME[i]); + } + } + + /* -------------------------------------------------------------------------------------------- + * Signal termination. + */ + void DropEvents() + { + for (auto & e : mEvents) + { + ResetSignalPair(e); + } + } + + /* -------------------------------------------------------------------------------------------- + * Event handlers. + */ + void OnVoiceStateUpdate(const dpp::voice_state_update_t & ev); + void OnLog(const dpp::log_t & ev); + void OnGuildJoinRequestDelete(const dpp::guild_join_request_delete_t & ev); + void OnInteractionCreate(const dpp::interaction_create_t & ev); + void OnButtonClick(const dpp::button_click_t & ev); + void OnSelectClick(const dpp::select_click_t & ev); + void OnGuildDelete(const dpp::guild_delete_t & ev); + void OnChannelDelete(const dpp::channel_delete_t & ev); + void OnChannelUpdate(const dpp::channel_update_t & ev); + void OnReady(const dpp::ready_t & ev); + void OnMessageDelete(const dpp::message_delete_t & ev); + void OnApplicationCommandDelete(const dpp::application_command_delete_t & ev); + void OnGuildMemberRemove(const dpp::guild_member_remove_t & ev); + void OnApplicationCommandCreate(const dpp::application_command_create_t & ev); + void OnResumed(const dpp::resumed_t & ev); + void OnGuildRoleCreate(const dpp::guild_role_create_t & ev); + void OnTypingStart(const dpp::typing_start_t & ev); + void OnMessageReactionAdd(const dpp::message_reaction_add_t & ev); + void OnGuildMembersChunk(const dpp::guild_members_chunk_t & ev); + void OnMessageReactionRemove(const dpp::message_reaction_remove_t & ev); + void OnGuildCreate(const dpp::guild_create_t & ev); + void OnChannelCreate(const dpp::channel_create_t & ev); + void OnMessageReactionRemoveEmoji(const dpp::message_reaction_remove_emoji_t & ev); + void OnMessageDeleteBulk(const dpp::message_delete_bulk_t & ev); + void OnGuildRoleUpdate(const dpp::guild_role_update_t & ev); + void OnGuildRoleDelete(const dpp::guild_role_delete_t & ev); + void OnChannelPinsUpdate(const dpp::channel_pins_update_t & ev); + void OnMessageReactionRemoveAll(const dpp::message_reaction_remove_all_t & ev); + void OnVoiceServerUpdate(const dpp::voice_server_update_t & ev); + void OnGuildEmojisUpdate(const dpp::guild_emojis_update_t & ev); + void OnGuildStickersUpdate(const dpp::guild_stickers_update_t & ev); + void OnPresenceUpdate(const dpp::presence_update_t & ev); + void OnWebhooksUpdate(const dpp::webhooks_update_t & ev); + void OnGuildMemberAdd(const dpp::guild_member_add_t & ev); + void OnInviteDelete(const dpp::invite_delete_t & ev); + void OnGuildUpdate(const dpp::guild_update_t & ev); + void OnGuildIntegrationsUpdate(const dpp::guild_integrations_update_t & ev); + void OnGuildMemberUpdate(const dpp::guild_member_update_t & ev); + void OnApplicationCommandUpdate(const dpp::application_command_update_t & ev); + void OnInviteCreate(const dpp::invite_create_t & ev); + void OnMessageUpdate(const dpp::message_update_t & ev); + void OnUserUpdate(const dpp::user_update_t & ev); + void OnMessageCreate(const dpp::message_create_t & ev); + void OnGuildBanAdd(const dpp::guild_ban_add_t & ev); + void OnGuildBanRemove(const dpp::guild_ban_remove_t & ev); + void OnIntegrationCreate(const dpp::integration_create_t & ev); + void OnIntegrationUpdate(const dpp::integration_update_t & ev); + void OnIntegrationDelete(const dpp::integration_delete_t & ev); + void OnThreadCreate(const dpp::thread_create_t & ev); + void OnThreadUpdate(const dpp::thread_update_t & ev); + void OnThreadDelete(const dpp::thread_delete_t & ev); + void OnThreadListSync(const dpp::thread_list_sync_t & ev); + void OnThreadMemberUpdate(const dpp::thread_member_update_t & ev); + void OnThreadMembersUpdate(const dpp::thread_members_update_t & ev); + void OnVoiceBufferSend(const dpp::voice_buffer_send_t & ev); + void OnVoiceUserTalking(const dpp::voice_user_talking_t & ev); + void OnVoiceReady(const dpp::voice_ready_t & ev); + void OnVoiceReceive(const dpp::voice_receive_t & ev); + void OnVoiceTrackMarker(const dpp::voice_track_marker_t & ev); + void OnStageInstanceCreate(const dpp::stage_instance_create_t & ev); + void OnStageInstanceDelete(const dpp::stage_instance_delete_t & ev); +}; + +} // Namespace:: SqMod diff --git a/module/Library/DPPEv.cpp b/module/Library/DPPEv.cpp new file mode 100644 index 00000000..26981863 --- /dev/null +++ b/module/Library/DPPEv.cpp @@ -0,0 +1,196 @@ +// ------------------------------------------------------------------------------------------------ +#include "Library/DPPEv.hpp" + +// ------------------------------------------------------------------------------------------------ +#include + +// ------------------------------------------------------------------------------------------------ +#include + +// ------------------------------------------------------------------------------------------------ +namespace SqMod { + +// ------------------------------------------------------------------------------------------------ +SQMOD_DECL_TYPENAME(SqDppVoiceStateUpdateEventEvent, _SC("SqDppVoiceStateUpdateEventEvent")) +SQMOD_DECL_TYPENAME(SqDppGuildJoinRequestDeleteEvent, _SC("SqDppGuildJoinRequestDeleteEvent")) +SQMOD_DECL_TYPENAME(SqDppLogEvent, _SC("SqDppLogEvent")) +SQMOD_DECL_TYPENAME(SqDppReadyEvent, _SC("SqDppReadyEvent")) + +// ------------------------------------------------------------------------------------------------ +const std::array< const char *, static_cast< size_t >(DpEventID::Max) > DpEventID::NAME{ + "VoiceStateUpdate", + "Log", + "GuildJoinRequestDelete", + "InteractionCreate", + "ButtonClick", + "SelectClick", + "GuildDelete", + "ChannelDelete", + "ChannelUpdate", + "Ready", + "MessageDelete", + "ApplicationCommandDelete", + "GuildMemberRemove", + "ApplicationCommandCreate", + "Resumed", + "GuildRoleCreate", + "TypingStart", + "MessageReactionAdd", + "GuildMembersChunk", + "MessageReactionRemove", + "GuildCreate", + "ChannelCreate", + "MessageReactionRemoveEmoji", + "MessageDeleteBulk", + "GuildRoleUpdate", + "GuildRoleDelete", + "ChannelPinsUpdate", + "MessageReactionRemoveAll", + "VoiceServerUpdate", + "GuildEmojisUpdate", + "GuildStickersUpdate", + "PresenceUpdate", + "WebhooksUpdate", + "GuildMemberAdd", + "InviteDelete", + "GuildUpdate", + "GuildIntegrationsUpdate", + "GuildMemberUpdate", + "ApplicationCommandUpdate", + "InviteCreate", + "MessageUpdate", + "UserUpdate", + "MessageCreate", + "GuildBanAdd", + "GuildBanRemove", + "IntegrationCreate", + "IntegrationUpdate", + "IntegrationDelete", + "ThreadCreate", + "ThreadUpdate", + "ThreadDelete", + "ThreadListSync", + "ThreadMemberUpdate", + "ThreadMembersUpdate", + "VoiceBufferSend", + "VoiceUserTalking", + "VoiceReady", + "VoiceReceive", + "VoiceTrackMarker", + "StageInstanceCreate", + "StageInstanceDelete" +}; + +// ------------------------------------------------------------------------------------------------ +void Register_DPPEv(HSQUIRRELVM vm, Table & ns) +{ + // -------------------------------------------------------------------------------------------- + ns.Bind(_SC("VoiceStateUpdate"), + Class< DpVoiceStateUpdateEvent, NoConstructor< DpVoiceStateUpdateEvent > >(vm, SqDppVoiceStateUpdateEventEvent::Str) + // Meta-methods + .SquirrelFunc(_SC("_typename"), &SqDppVoiceStateUpdateEventEvent::Fn) + .Func(_SC("_tostring"), &DpVoiceStateUpdateEvent::GetRawEvent) + // Member Properties + .Prop(_SC("State"), &DpVoiceStateUpdateEvent::GetState) + ); + // -------------------------------------------------------------------------------------------- + ns.Bind(_SC("Log"), + Class< DpLogEvent, NoConstructor< DpLogEvent > >(vm, SqDppLogEvent::Str) + // Meta-methods + .SquirrelFunc(_SC("_typename"), &SqDppLogEvent::Fn) + .Func(_SC("_tostring"), &DpLogEvent::GetRawEvent) + // Member Properties + .Prop(_SC("RawEvent"), &DpLogEvent::GetRawEvent) + .Prop(_SC("Severity"), &DpLogEvent::GetSeverity) + .Prop(_SC("Message"), &DpLogEvent::GetMessage) + ); + // -------------------------------------------------------------------------------------------- + ns.Bind(_SC("Ready"), + Class< DpReadyEvent, NoConstructor< DpReadyEvent > >(vm, SqDppReadyEvent::Str) + // Meta-methods + .SquirrelFunc(_SC("_typename"), &SqDppReadyEvent::Fn) + .Func(_SC("_tostring"), &DpReadyEvent::GetRawEvent) + // Member Properties + .Prop(_SC("RawEvent"), &DpReadyEvent::GetRawEvent) + .Prop(_SC("SessionID"), &DpReadyEvent::GetSessionID) + .Prop(_SC("ShardID"), &DpReadyEvent::GetShardID) + ); + // -------------------------------------------------------------------------------------------- + ns.Bind(_SC("GuildJoinRequestDelete"), + Class< DpGuildJoinRequestDeleteEvent, NoConstructor< DpGuildJoinRequestDeleteEvent > >(vm, SqDppGuildJoinRequestDeleteEvent::Str) + // Meta-methods + .SquirrelFunc(_SC("_typename"), &SqDppGuildJoinRequestDeleteEvent::Fn) + .Func(_SC("_tostring"), &DpGuildJoinRequestDeleteEvent::GetRawEvent) + // Member Properties + .Prop(_SC("RawEvent"), &DpGuildJoinRequestDeleteEvent::GetRawEvent) + .Prop(_SC("GuildID"), &DpGuildJoinRequestDeleteEvent::GetGuildID) + .Prop(_SC("UserID"), &DpGuildJoinRequestDeleteEvent::GetUserID) + ); + // -------------------------------------------------------------------------------------------- + ConstTable(vm).Enum(_SC("SqDiscordEvent"), Enumeration(vm) + .Const(_SC("VoiceStateUpdate"), static_cast< SQInteger >(DpEventID::VoiceStateUpdate)) + .Const(_SC("Log"), static_cast< SQInteger >(DpEventID::Log)) + .Const(_SC("GuildJoinRequestDelete"), static_cast< SQInteger >(DpEventID::GuildJoinRequestDelete)) + .Const(_SC("InteractionCreate"), static_cast< SQInteger >(DpEventID::InteractionCreate)) + .Const(_SC("ButtonClick"), static_cast< SQInteger >(DpEventID::ButtonClick)) + .Const(_SC("SelectClick"), static_cast< SQInteger >(DpEventID::SelectClick)) + .Const(_SC("GuildDelete"), static_cast< SQInteger >(DpEventID::GuildDelete)) + .Const(_SC("ChannelDelete"), static_cast< SQInteger >(DpEventID::ChannelDelete)) + .Const(_SC("ChannelUpdate"), static_cast< SQInteger >(DpEventID::ChannelUpdate)) + .Const(_SC("Ready"), static_cast< SQInteger >(DpEventID::Ready)) + .Const(_SC("MessageDelete"), static_cast< SQInteger >(DpEventID::MessageDelete)) + .Const(_SC("ApplicationCommandDelete"), static_cast< SQInteger >(DpEventID::ApplicationCommandDelete)) + .Const(_SC("GuildMemberRemove"), static_cast< SQInteger >(DpEventID::GuildMemberRemove)) + .Const(_SC("ApplicationCommandCreate"), static_cast< SQInteger >(DpEventID::ApplicationCommandCreate)) + .Const(_SC("Resumed"), static_cast< SQInteger >(DpEventID::Resumed)) + .Const(_SC("GuildRoleCreate"), static_cast< SQInteger >(DpEventID::GuildRoleCreate)) + .Const(_SC("TypingStart"), static_cast< SQInteger >(DpEventID::TypingStart)) + .Const(_SC("MessageReactionAdd"), static_cast< SQInteger >(DpEventID::MessageReactionAdd)) + .Const(_SC("GuildMembersChunk"), static_cast< SQInteger >(DpEventID::GuildMembersChunk)) + .Const(_SC("MessageReactionRemove"), static_cast< SQInteger >(DpEventID::MessageReactionRemove)) + .Const(_SC("GuildCreate"), static_cast< SQInteger >(DpEventID::GuildCreate)) + .Const(_SC("ChannelCreate"), static_cast< SQInteger >(DpEventID::ChannelCreate)) + .Const(_SC("MessageReactionRemoveEmoji"), static_cast< SQInteger >(DpEventID::MessageReactionRemoveEmoji)) + .Const(_SC("MessageDeleteBulk"), static_cast< SQInteger >(DpEventID::MessageDeleteBulk)) + .Const(_SC("GuildRoleUpdate"), static_cast< SQInteger >(DpEventID::GuildRoleUpdate)) + .Const(_SC("GuildRoleDelete"), static_cast< SQInteger >(DpEventID::GuildRoleDelete)) + .Const(_SC("ChannelPinsUpdate"), static_cast< SQInteger >(DpEventID::ChannelPinsUpdate)) + .Const(_SC("MessageReactionRemoveAll"), static_cast< SQInteger >(DpEventID::MessageReactionRemoveAll)) + .Const(_SC("VoiceServerUpdate"), static_cast< SQInteger >(DpEventID::VoiceServerUpdate)) + .Const(_SC("GuildEmojisUpdate"), static_cast< SQInteger >(DpEventID::GuildEmojisUpdate)) + .Const(_SC("GuildStickersUpdate"), static_cast< SQInteger >(DpEventID::GuildStickersUpdate)) + .Const(_SC("PresenceUpdate"), static_cast< SQInteger >(DpEventID::PresenceUpdate)) + .Const(_SC("WebhooksUpdate"), static_cast< SQInteger >(DpEventID::WebhooksUpdate)) + .Const(_SC("GuildMemberAdd"), static_cast< SQInteger >(DpEventID::GuildMemberAdd)) + .Const(_SC("InviteDelete"), static_cast< SQInteger >(DpEventID::InviteDelete)) + .Const(_SC("GuildUpdate"), static_cast< SQInteger >(DpEventID::GuildUpdate)) + .Const(_SC("GuildIntegrationsUpdate"), static_cast< SQInteger >(DpEventID::GuildIntegrationsUpdate)) + .Const(_SC("GuildMemberUpdate"), static_cast< SQInteger >(DpEventID::GuildMemberUpdate)) + .Const(_SC("ApplicationCommandUpdate"), static_cast< SQInteger >(DpEventID::ApplicationCommandUpdate)) + .Const(_SC("InviteCreate"), static_cast< SQInteger >(DpEventID::InviteCreate)) + .Const(_SC("MessageUpdate"), static_cast< SQInteger >(DpEventID::MessageUpdate)) + .Const(_SC("UserUpdate"), static_cast< SQInteger >(DpEventID::UserUpdate)) + .Const(_SC("MessageCreate"), static_cast< SQInteger >(DpEventID::MessageCreate)) + .Const(_SC("GuildBanAdd"), static_cast< SQInteger >(DpEventID::GuildBanAdd)) + .Const(_SC("GuildBanRemove"), static_cast< SQInteger >(DpEventID::GuildBanRemove)) + .Const(_SC("IntegrationCreate"), static_cast< SQInteger >(DpEventID::IntegrationCreate)) + .Const(_SC("IntegrationUpdate"), static_cast< SQInteger >(DpEventID::IntegrationUpdate)) + .Const(_SC("IntegrationDelete"), static_cast< SQInteger >(DpEventID::IntegrationDelete)) + .Const(_SC("ThreadCreate"), static_cast< SQInteger >(DpEventID::ThreadCreate)) + .Const(_SC("ThreadUpdate"), static_cast< SQInteger >(DpEventID::ThreadUpdate)) + .Const(_SC("ThreadDelete"), static_cast< SQInteger >(DpEventID::ThreadDelete)) + .Const(_SC("ThreadListSync"), static_cast< SQInteger >(DpEventID::ThreadListSync)) + .Const(_SC("ThreadMemberUpdate"), static_cast< SQInteger >(DpEventID::ThreadMemberUpdate)) + .Const(_SC("ThreadMembersUpdate"), static_cast< SQInteger >(DpEventID::ThreadMembersUpdate)) + .Const(_SC("VoiceBufferSend"), static_cast< SQInteger >(DpEventID::VoiceBufferSend)) + .Const(_SC("VoiceUserTalking"), static_cast< SQInteger >(DpEventID::VoiceUserTalking)) + .Const(_SC("VoiceReady"), static_cast< SQInteger >(DpEventID::VoiceReady)) + .Const(_SC("VoiceReceive"), static_cast< SQInteger >(DpEventID::VoiceReceive)) + .Const(_SC("VoiceTrackMarker"), static_cast< SQInteger >(DpEventID::VoiceTrackMarker)) + .Const(_SC("StageInstanceCreate"), static_cast< SQInteger >(DpEventID::StageInstanceCreate)) + .Const(_SC("StageInstanceDelete"), static_cast< SQInteger >(DpEventID::StageInstanceDelete)) + .Const(_SC("Max"), static_cast< SQInteger >(DpEventID::Max)) + ); +} + +} // Namespace:: SqMod diff --git a/module/Library/DPPEv.hpp b/module/Library/DPPEv.hpp new file mode 100644 index 00000000..2ec213bd --- /dev/null +++ b/module/Library/DPPEv.hpp @@ -0,0 +1,383 @@ +#pragma once + +// ------------------------------------------------------------------------------------------------ +#include "Library/DPPTy.hpp" + +// ------------------------------------------------------------------------------------------------ +#include +#include + +// ------------------------------------------------------------------------------------------------ +#include + +// ------------------------------------------------------------------------------------------------ +namespace SqMod { + +/* ------------------------------------------------------------------------------------------------ + * Unique ID for each event. +*/ +struct DpEventID +{ + /* -------------------------------------------------------------------------------------------- + * ID enumeration. + */ + enum Type + { + VoiceStateUpdate=0, + Log, + GuildJoinRequestDelete, + InteractionCreate, + ButtonClick, + SelectClick, + GuildDelete, + ChannelDelete, + ChannelUpdate, + Ready, + MessageDelete, + ApplicationCommandDelete, + GuildMemberRemove, + ApplicationCommandCreate, + Resumed, + GuildRoleCreate, + TypingStart, + MessageReactionAdd, + GuildMembersChunk, + MessageReactionRemove, + GuildCreate, + ChannelCreate, + MessageReactionRemoveEmoji, + MessageDeleteBulk, + GuildRoleUpdate, + GuildRoleDelete, + ChannelPinsUpdate, + MessageReactionRemoveAll, + VoiceServerUpdate, + GuildEmojisUpdate, + GuildStickersUpdate, + PresenceUpdate, + WebhooksUpdate, + GuildMemberAdd, + InviteDelete, + GuildUpdate, + GuildIntegrationsUpdate, + GuildMemberUpdate, + ApplicationCommandUpdate, + InviteCreate, + MessageUpdate, + UserUpdate, + MessageCreate, + GuildBanAdd, + GuildBanRemove, + IntegrationCreate, + IntegrationUpdate, + IntegrationDelete, + ThreadCreate, + ThreadUpdate, + ThreadDelete, + ThreadListSync, + ThreadMemberUpdate, + ThreadMembersUpdate, + VoiceBufferSend, + VoiceUserTalking, + VoiceReady, + VoiceReceive, + VoiceTrackMarker, + StageInstanceCreate, + StageInstanceDelete, + Max + }; + /* -------------------------------------------------------------------------------------------- + * String identification. + */ + static const std::array< const char *, static_cast< size_t >(Max) > NAME; +}; + +/* ------------------------------------------------------------------------------------------------ + * Base class of an event handler. +*/ +struct DpEventBase +{ + /* -------------------------------------------------------------------------------------------- + * Raw event text. + */ + std::string mRaw{}; + + /* -------------------------------------------------------------------------------------------- + * Shard the event came from. + */ + dpp::discord_client * mFrom{nullptr}; + + /* -------------------------------------------------------------------------------------------- + * Default constructor. + */ + DpEventBase() noexcept = default; + + /* -------------------------------------------------------------------------------------------- + * Explicit constructor. + */ + explicit DpEventBase(const dpp::event_dispatch_t & d) noexcept + : mRaw(d.raw_event), mFrom(d.from) + { + } + + /* -------------------------------------------------------------------------------------------- + * Copy constructor (disabled). + */ + DpEventBase(const DpEventBase &) noexcept = delete; + + /* -------------------------------------------------------------------------------------------- + * Move constructor (disabled). + */ + DpEventBase(DpEventBase &&) noexcept = delete; + + /* -------------------------------------------------------------------------------------------- + * Destructor. + */ + virtual ~DpEventBase() noexcept = default; + + /* -------------------------------------------------------------------------------------------- + * Copy assignment operator (disabled). + */ + DpEventBase & operator = (const DpEventBase &) noexcept = delete; + + /* -------------------------------------------------------------------------------------------- + * Move assignment operator (disabled). + */ + DpEventBase & operator = (DpEventBase &&) noexcept = delete; + + /* -------------------------------------------------------------------------------------------- + * Cleanup after the event was processed. + */ + virtual void Cleanup() + { + mFrom = nullptr; + } +}; + +/* ------------------------------------------------------------------------------------------------ + * Voice state update event. +*/ +struct DpVoiceStateUpdateEvent : public DpEventBase +{ + // -------------------------------------------------------------------------------------------- + dpp::voicestate mState{}; + + // -------------------------------------------------------------------------------------------- + LightObj mSqState{}; + + /* -------------------------------------------------------------------------------------------- + * Explicit constructor. + */ + explicit DpVoiceStateUpdateEvent(const dpp::voice_state_update_t & d) noexcept + : DpEventBase(d), mState(d.state), mSqState() + { + } + + /* -------------------------------------------------------------------------------------------- + * Validate the managed handle. + */ + void Validate() const { if (!mFrom) STHROWF("Invalid discord [Ready] event handle"); } + + /* -------------------------------------------------------------------------------------------- + * Validate the managed handle and retrieve a reference to it. + */ + SQMOD_NODISCARD DpVoiceStateUpdateEvent & Valid() { Validate(); return *this; } + + /* -------------------------------------------------------------------------------------------- + * Validate the managed handle and retrieve a const reference to it. + */ + SQMOD_NODISCARD const DpVoiceStateUpdateEvent & Valid() const { Validate(); return *this; } + + /* -------------------------------------------------------------------------------------------- + * Cleanup after the event was processed. + */ + void Cleanup() override + { + if (!mSqState.IsNull()) + { + [[maybe_unused]] auto p = mSqState.CastI< DpVoiceState >()->mPtr.release(); + // Release script resources + mSqState.Release(); + } + // Allow the base to cleanup as well + DpEventBase::Cleanup(); + } + + /* -------------------------------------------------------------------------------------------- + * Retrieve the raw event. + */ + SQMOD_NODISCARD const std::string & GetRawEvent() const { return mRaw; } + + /* -------------------------------------------------------------------------------------------- + * Retrieve the voice state. + */ + SQMOD_NODISCARD LightObj & GetState() + { + if (Valid().mSqState.IsNull()) + { + mSqState = LightObj{SqTypeIdentity< DpVoiceState >{}, SqVM(), &mState, false}; + } + // Return the associated script object + return mSqState; + } +}; + +/* ------------------------------------------------------------------------------------------------ + * Guild join request delete (user declined membership screening) event. +*/ +struct DpGuildJoinRequestDeleteEvent : public DpEventBase +{ + // -------------------------------------------------------------------------------------------- + dpp::snowflake mGuildID{}; + dpp::snowflake mUserID{}; + + /* -------------------------------------------------------------------------------------------- + * Explicit constructor. + */ + explicit DpGuildJoinRequestDeleteEvent(const dpp::guild_join_request_delete_t & d) noexcept + : DpEventBase(d), mGuildID(d.guild_id), mUserID(d.user_id) + { + } + + /* -------------------------------------------------------------------------------------------- + * Validate the managed handle. + */ + void Validate() const { if (!mFrom) STHROWF("Invalid discord [GuildJoinRequestDelete] event handle"); } + + /* -------------------------------------------------------------------------------------------- + * Validate the managed handle and retrieve a reference to it. + */ + SQMOD_NODISCARD DpGuildJoinRequestDeleteEvent & Valid() { Validate(); return *this; } + + /* -------------------------------------------------------------------------------------------- + * Validate the managed handle and retrieve a const reference to it. + */ + SQMOD_NODISCARD const DpGuildJoinRequestDeleteEvent & Valid() const { Validate(); return *this; } + + /* -------------------------------------------------------------------------------------------- + * Cleanup after the event was processed. + */ + void Cleanup() override + { + // Allow the base to cleanup as well + DpEventBase::Cleanup(); + } + + /* -------------------------------------------------------------------------------------------- + * Retrieve the raw event. + */ + SQMOD_NODISCARD const std::string & GetRawEvent() const { return Valid().mRaw; } + + /* -------------------------------------------------------------------------------------------- + * Retrieve the guild id. + */ + SQMOD_NODISCARD dpp::snowflake GetGuildID() const { return Valid().mGuildID; } + + /* -------------------------------------------------------------------------------------------- + * Retrieve the user id. + */ + SQMOD_NODISCARD dpp::snowflake GetUserID() const { return Valid().mUserID; } +}; + +/* ------------------------------------------------------------------------------------------------ + * Log message event. +*/ +struct DpLogEvent : public DpEventBase +{ + // -------------------------------------------------------------------------------------------- + SQInteger mSeverity{0}; + std::string mMessage{}; + + /* -------------------------------------------------------------------------------------------- + * Explicit constructor. + */ + explicit DpLogEvent(const dpp::log_t & d) noexcept + : DpEventBase(d), mSeverity(d.severity), mMessage(d.message) + { + } + + /* -------------------------------------------------------------------------------------------- + * Cleanup after the event was processed. + */ + void Cleanup() override + { + // Allow the base to cleanup as well + DpEventBase::Cleanup(); + } + + /* -------------------------------------------------------------------------------------------- + * Retrieve the raw event. + */ + SQMOD_NODISCARD const std::string & GetRawEvent() const { return mRaw; } + + /* -------------------------------------------------------------------------------------------- + * Retrieve log severity. + */ + SQMOD_NODISCARD SQInteger GetSeverity() const { return mSeverity; } + + /* -------------------------------------------------------------------------------------------- + * Retrieve log message. + */ + SQMOD_NODISCARD const std::string & GetMessage() const { return mMessage; } +}; + +/* ------------------------------------------------------------------------------------------------ + * Session ready event. +*/ +struct DpReadyEvent : public DpEventBase +{ + // -------------------------------------------------------------------------------------------- + std::string mSessionID{}; + uint32_t mShardID{}; + + /* -------------------------------------------------------------------------------------------- + * Explicit constructor. + */ + explicit DpReadyEvent(const dpp::ready_t & d) noexcept + : DpEventBase(d) + , mSessionID(d.session_id) + , mShardID(d.shard_id) + { + } + + /* -------------------------------------------------------------------------------------------- + * Validate the managed handle. + */ + void Validate() const { if (!mFrom) STHROWF("Invalid discord [Ready] event handle"); } + + /* -------------------------------------------------------------------------------------------- + * Validate the managed handle and retrieve a reference to it. + */ + SQMOD_NODISCARD DpReadyEvent & Valid() { Validate(); return *this; } + + /* -------------------------------------------------------------------------------------------- + * Validate the managed handle and retrieve a const reference to it. + */ + SQMOD_NODISCARD const DpReadyEvent & Valid() const { Validate(); return *this; } + + /* -------------------------------------------------------------------------------------------- + * Cleanup after the event was processed. + */ + void Cleanup() override + { + // Allow the base to cleanup as well + DpEventBase::Cleanup(); + } + + /* -------------------------------------------------------------------------------------------- + * Retrieve the raw event. + */ + SQMOD_NODISCARD const std::string & GetRawEvent() const { return Valid().mRaw; } + + /* -------------------------------------------------------------------------------------------- + * Retrieve the session id. + */ + SQMOD_NODISCARD const std::string & GetSessionID() const { return Valid().mSessionID; } + + /* -------------------------------------------------------------------------------------------- + * Retrieve the shard id. + */ + SQMOD_NODISCARD SQInteger GetShardID() const { return static_cast< SQInteger >(Valid().mShardID); } +}; + +} // Namespace:: SqMod diff --git a/module/Library/DPPTy.cpp b/module/Library/DPPTy.cpp new file mode 100644 index 00000000..30b8fea8 --- /dev/null +++ b/module/Library/DPPTy.cpp @@ -0,0 +1,257 @@ +// ------------------------------------------------------------------------------------------------ +#include "Library/DPPTy.hpp" + +// ------------------------------------------------------------------------------------------------ +#include + +// ------------------------------------------------------------------------------------------------ +#include + +// ------------------------------------------------------------------------------------------------ +namespace SqMod { + +// ------------------------------------------------------------------------------------------------ +SQMOD_DECL_TYPENAME(SqDppCachePolicy, _SC("SqDppCachePolicy")) +SQMOD_DECL_TYPENAME(SqDppUptime, _SC("SqDppUptime")) +SQMOD_DECL_TYPENAME(SqDppIconHash, _SC("SqDppIconHash")) +SQMOD_DECL_TYPENAME(SqDppActivity, _SC("SqDppActivity")) +SQMOD_DECL_TYPENAME(SqDppPresence, _SC("SqDppPresence")) +SQMOD_DECL_TYPENAME(SqDppVoiceState, _SC("SqDppVoiceState")) +SQMOD_DECL_TYPENAME(SqDppGuild, _SC("SqDppGuild")) + +// ------------------------------------------------------------------------------------------------ +void Register_DPPConst(HSQUIRRELVM vm, Table & ns); + +// ------------------------------------------------------------------------------------------------ +void Register_DPPTy(HSQUIRRELVM vm, Table & ns) +{ + Register_DPPConst(vm, ns); + // -------------------------------------------------------------------------------------------- + ns.Bind(_SC("Uptime"), + Class< dpp::utility::uptime >(vm, SqDppUptime::Str) + // Constructors + .Ctor() + // Meta-methods + .SquirrelFunc(_SC("_typename"), &SqDppUptime::Fn) + .Func(_SC("_tostring"), &dpp::utility::uptime::to_string) + // Member Variables + .Var(_SC("Days"), &dpp::utility::uptime::days) + .Var(_SC("Hours"), &dpp::utility::uptime::hours) + .Var(_SC("Minutes"), &dpp::utility::uptime::mins) + .Var(_SC("Seconds"), &dpp::utility::uptime::secs) + // Member Methods + .Func(_SC("ToSeconds"), &dpp::utility::uptime::to_secs) + .Func(_SC("ToMilliseconds"), &dpp::utility::uptime::to_msecs) + ); + // -------------------------------------------------------------------------------------------- + ns.Bind(_SC("IconHash"), + Class< dpp::utility::iconhash >(vm, SqDppIconHash::Str) + // Constructors + .Ctor() + .Ctor< const std::string & >() + // Meta-methods + .SquirrelFunc(_SC("_typename"), &SqDppIconHash::Fn) + .Func(_SC("_tostring"), &dpp::utility::iconhash::to_string) + // Member Variables + .Var(_SC("High"), &dpp::utility::iconhash::first) + .Var(_SC("Low"), &dpp::utility::iconhash::second) + // Member Methods + .Func(_SC("Set"), &dpp::utility::iconhash::set) + ); + // -------------------------------------------------------------------------------------------- + ns.Bind(_SC("CachePolicy"), + Class< DpCachePolicy >(vm, SqDppCachePolicy::Str) + // Constructors + .Ctor() + .Ctor< SQInteger >() + .Ctor< SQInteger, SQInteger >() + .Ctor< SQInteger, SQInteger, SQInteger >() + // Meta-methods + .SquirrelFunc(_SC("_typename"), &SqDppCachePolicy::Fn) + // Member Variables + .Var(_SC("UserPolicy"), &DpCachePolicy::mUserPolicy) + .Var(_SC("EmojiPolicy"), &DpCachePolicy::mEmojiPolicy) + .Var(_SC("RolePolicy"), &DpCachePolicy::mRolePolicy) + ); + // -------------------------------------------------------------------------------------------- + ns.Bind(_SC("Activity"), + Class< DpActivity >(vm, SqDppActivity::Str) + // Constructors + .Ctor() + .Ctor< SQInteger, StackStrF &, StackStrF &, StackStrF & >() + // Meta-methods + .SquirrelFunc(_SC("_typename"), &SqDppActivity::Fn) + // Member Properties + .Prop(_SC("Name"), &DpActivity::GetName, &DpActivity::SetName) + .Prop(_SC("State"), &DpActivity::GetState, &DpActivity::SetState) + .Prop(_SC("URL"), &DpActivity::GetURL, &DpActivity::SetURL) + .Prop(_SC("Type"), &DpActivity::GetType, &DpActivity::SetType) + .Prop(_SC("CreatedAt"), &DpActivity::GetCreatedAt, &DpActivity::SetCreatedAt) + .Prop(_SC("Start"), &DpActivity::GetStart, &DpActivity::SetStart) + .Prop(_SC("End"), &DpActivity::GetEnd, &DpActivity::SetEnd) + // Member Methods + .Func(_SC("SetName"), &DpActivity::ApplyName) + .Func(_SC("SetState"), &DpActivity::ApplyState) + .Func(_SC("SetURL"), &DpActivity::ApplyURL) + .Func(_SC("SetType"), &DpActivity::ApplyType) + .Func(_SC("SetCreatedAt"), &DpActivity::ApplyCreatedAt) + .Func(_SC("SetStart"), &DpActivity::ApplyStart) + .Func(_SC("SetEnd"), &DpActivity::ApplyEnd) + ); + // -------------------------------------------------------------------------------------------- + ns.Bind(_SC("Presence"), + Class< DpPresence >(vm, SqDppPresence::Str) + // Constructors + .Ctor() + // Meta-methods + .SquirrelFunc(_SC("_typename"), &SqDppPresence::Fn) + // Member Properties + .Prop(_SC("UserID"), &DpPresence::GetUserID, &DpPresence::SetUserID) + .Prop(_SC("GuildID"), &DpPresence::GetGuildID, &DpPresence::SetGuildID) + .Prop(_SC("Flags"), &DpPresence::GetFlags, &DpPresence::SetFlags) + .Prop(_SC("ActivityCount"), &DpPresence::ActivityCount) + .Prop(_SC("DesktopStatus"), &DpPresence::GetDesktopStatus) + .Prop(_SC("WebStatus"), &DpPresence::GetWebStatus) + .Prop(_SC("MobileStatus"), &DpPresence::GetMobileStatus) + .Prop(_SC("Status"), &DpPresence::GetStatus) + // Member Methods + .Func(_SC("SetUserID"), &DpPresence::ApplyUserID) + .Func(_SC("SetGuildID"), &DpPresence::ApplyGuildID) + .Func(_SC("SetFlags"), &DpPresence::ApplyFlags) + .Func(_SC("AddActivity"), &DpPresence::AddActivity) + .Func(_SC("EachActivity"), &DpPresence::EachActivity) + .Func(_SC("ClearActivities"), &DpPresence::ClearActivities) + .Func(_SC("FilterActivities"), &DpPresence::FilterActivities) + .Func(_SC("BuildJSON"), &DpPresence::BuildJSON) + ); + // -------------------------------------------------------------------------------------------- + ns.Bind(_SC("VoiceState"), + Class< DpVoiceState, NoConstructor< DpVoiceState > >(vm, SqDppVoiceState::Str) + // Meta-methods + .SquirrelFunc(_SC("_typename"), &SqDppVoiceState::Fn) + .Func(_SC("_tojson"), &DpVoiceState::BuildJSON) + // Member Properties + .Prop(_SC("Valid"), &DpVoiceState::IsValid) + .Prop(_SC("GuildID"), &DpVoiceState::GetGuildID) + .Prop(_SC("ChannelID"), &DpVoiceState::GetChannelID) + .Prop(_SC("UserID"), &DpVoiceState::GetUserID) + .Prop(_SC("SessionID"), &DpVoiceState::GetSessionID) + .Prop(_SC("Flags"), &DpVoiceState::GetFlags, &DpVoiceState::SetFlags) + .Prop(_SC("JSON"), &DpVoiceState::BuildJSON) + .Prop(_SC("Deaf"), &DpVoiceState::IsDeaf) + .Prop(_SC("Mute"), &DpVoiceState::IsMute) + .Prop(_SC("SelfMute"), &DpVoiceState::IsSelfMute) + .Prop(_SC("SelfDeaf"), &DpVoiceState::IsSelfDeaf) + .Prop(_SC("SelfStream"), &DpVoiceState::SelfStream) + .Prop(_SC("SelfVideo"), &DpVoiceState::SelfVideo) + .Prop(_SC("Supressed"), &DpVoiceState::IsSupressed) + ); + // -------------------------------------------------------------------------------------------- + ns.Bind(_SC("Guild"), + Class< DpGuild, NoConstructor< DpGuild > >(vm, SqDppGuild::Str) + // Meta-methods + .SquirrelFunc(_SC("_typename"), &SqDppGuild::Fn) + // Member Properties + .Prop(_SC("Valid"), &DpGuild::IsValid) + ); +} + +// ------------------------------------------------------------------------------------------------ +void Register_DPPConst(HSQUIRRELVM vm, Table & ns) +{ + // -------------------------------------------------------------------------------------------- + ConstTable(vm).Enum(_SC("SqDiscordLogLevel"), Enumeration(vm) + .Const(_SC("Trace"), static_cast< SQInteger >(dpp::ll_trace)) + .Const(_SC("Debug"), static_cast< SQInteger >(dpp::ll_debug)) + .Const(_SC("Info"), static_cast< SQInteger >(dpp::ll_info)) + .Const(_SC("Warning"), static_cast< SQInteger >(dpp::ll_warning)) + .Const(_SC("Error"), static_cast< SQInteger >(dpp::ll_error)) + .Const(_SC("Critical"), static_cast< SQInteger >(dpp::ll_critical)) + ); + // -------------------------------------------------------------------------------------------- + ConstTable(vm).Enum(_SC("SqDiscordImageType"), Enumeration(vm) + .Const(_SC("PNG"), static_cast< SQInteger >(dpp::i_png)) + .Const(_SC("JPG"), static_cast< SQInteger >(dpp::i_jpg)) + .Const(_SC("GIF"), static_cast< SQInteger >(dpp::i_gif)) + ); + // -------------------------------------------------------------------------------------------- + ConstTable(vm).Enum(_SC("SqDiscordCachePolicy"), Enumeration(vm) + .Const(_SC("Aggressive"), static_cast< SQInteger >(dpp::cp_aggressive)) + .Const(_SC("Lazy"), static_cast< SQInteger >(dpp::cp_lazy)) + .Const(_SC("None"), static_cast< SQInteger >(dpp::cp_none)) + ); + // -------------------------------------------------------------------------------------------- + ConstTable(vm).Enum(_SC("SqDiscordClusterIntents"), Enumeration(vm) + .Const(_SC("Guilds"), static_cast< SQInteger >(dpp::i_guilds)) + .Const(_SC("GuildMembers"), static_cast< SQInteger >(dpp::i_guild_members)) + .Const(_SC("GuildBans"), static_cast< SQInteger >(dpp::i_guild_bans)) + .Const(_SC("GuildEmojis"), static_cast< SQInteger >(dpp::i_guild_emojis)) + .Const(_SC("GuildIntegrations"), static_cast< SQInteger >(dpp::i_guild_integrations)) + .Const(_SC("GuildWebhooks"), static_cast< SQInteger >(dpp::i_guild_webhooks)) + .Const(_SC("GuildInvites"), static_cast< SQInteger >(dpp::i_guild_invites)) + .Const(_SC("GuildVoiceStates"), static_cast< SQInteger >(dpp::i_guild_voice_states)) + .Const(_SC("GuildPresences"), static_cast< SQInteger >(dpp::i_guild_presences)) + .Const(_SC("GuildMessages"), static_cast< SQInteger >(dpp::i_guild_messages)) + .Const(_SC("GuildMessageReactions"), static_cast< SQInteger >(dpp::i_guild_message_reactions)) + .Const(_SC("GuildMessageTyping"), static_cast< SQInteger >(dpp::i_guild_message_typing)) + .Const(_SC("DirectMessages"), static_cast< SQInteger >(dpp::i_direct_messages)) + .Const(_SC("DirectMessageReactions"), static_cast< SQInteger >(dpp::i_direct_message_reactions)) + .Const(_SC("DirectMessageTyping"), static_cast< SQInteger >(dpp::i_direct_message_typing)) + .Const(_SC("Default"), static_cast< SQInteger >(dpp::i_default_intents)) + .Const(_SC("Privileged"), static_cast< SQInteger >(dpp::i_privileged_intents)) + .Const(_SC("All"), static_cast< SQInteger >(dpp::i_all_intents)) + ); + // -------------------------------------------------------------------------------------------- + ConstTable(vm).Enum(_SC("SqDiscordPresenceFlags"), Enumeration(vm) + .Const(_SC("DesktopOnline"), static_cast< SQInteger >(dpp::p_desktop_online)) + .Const(_SC("DesktopDND"), static_cast< SQInteger >(dpp::p_desktop_dnd)) + .Const(_SC("DesktopIdle"), static_cast< SQInteger >(dpp::p_desktop_idle)) + .Const(_SC("WebWnline"), static_cast< SQInteger >(dpp::p_web_online)) + .Const(_SC("WebDND"), static_cast< SQInteger >(dpp::p_web_dnd)) + .Const(_SC("WebIdle"), static_cast< SQInteger >(dpp::p_web_idle)) + .Const(_SC("MobileOnline"), static_cast< SQInteger >(dpp::p_mobile_online)) + .Const(_SC("MobileDND"), static_cast< SQInteger >(dpp::p_mobile_dnd)) + .Const(_SC("MobileIdle"), static_cast< SQInteger >(dpp::p_mobile_idle)) + .Const(_SC("StatusOnline"), static_cast< SQInteger >(dpp::p_status_online)) + .Const(_SC("StatusDND"), static_cast< SQInteger >(dpp::p_status_dnd)) + .Const(_SC("StatusIdle"), static_cast< SQInteger >(dpp::p_status_idle)) + ); + // -------------------------------------------------------------------------------------------- + ConstTable(vm).Enum(_SC("SqDiscordPresenceStatus"), Enumeration(vm) + .Const(_SC("Offline"), static_cast< SQInteger >(dpp::ps_offline)) + .Const(_SC("Online"), static_cast< SQInteger >(dpp::ps_online)) + .Const(_SC("DND"), static_cast< SQInteger >(dpp::ps_dnd)) + .Const(_SC("Idle"), static_cast< SQInteger >(dpp::ps_idle)) + ); + // -------------------------------------------------------------------------------------------- + ConstTable(vm).Enum(_SC("SqDiscordDesktopStatusBits"), Enumeration(vm) + .Const(_SC("ShiftDesktop"), static_cast< SQInteger >(PF_SHIFT_DESKTOP)) + .Const(_SC("ShiftWeb"), static_cast< SQInteger >(PF_SHIFT_WEB)) + .Const(_SC("ShiftMobile"), static_cast< SQInteger >(PF_SHIFT_MOBILE)) + .Const(_SC("ShiftMain"), static_cast< SQInteger >(PF_SHIFT_MAIN)) + .Const(_SC("StatusMask"), static_cast< SQInteger >(PF_STATUS_MASK)) + .Const(_SC("ClearDesktop"), static_cast< SQInteger >(PF_CLEAR_DESKTOP)) + .Const(_SC("ClearWeb"), static_cast< SQInteger >(PF_CLEAR_WEB)) + .Const(_SC("ClearMobile"), static_cast< SQInteger >(PF_CLEAR_MOBILE)) + .Const(_SC("ClearStatus"), static_cast< SQInteger >(PF_CLEAR_STATUS)) + ); + // -------------------------------------------------------------------------------------------- + ConstTable(vm).Enum(_SC("SqDiscordActivityType"), Enumeration(vm) + .Const(_SC("Game"), static_cast< SQInteger >(dpp::at_game)) + .Const(_SC("Streaming"), static_cast< SQInteger >(dpp::at_streaming)) + .Const(_SC("Listening"), static_cast< SQInteger >(dpp::at_listening)) + .Const(_SC("Custom"), static_cast< SQInteger >(dpp::at_custom)) + .Const(_SC("Competing"), static_cast< SQInteger >(dpp::at_competing)) + ); + // -------------------------------------------------------------------------------------------- + ConstTable(vm).Enum(_SC("SqDiscordActivityFlags"), Enumeration(vm) + .Const(_SC("Instance"), static_cast< SQInteger >(dpp::af_instance)) + .Const(_SC("Join"), static_cast< SQInteger >(dpp::af_join)) + .Const(_SC("Spectate"), static_cast< SQInteger >(dpp::af_spectate)) + .Const(_SC("JoinRequest"), static_cast< SQInteger >(dpp::af_join_request)) + .Const(_SC("Sync"), static_cast< SQInteger >(dpp::af_sync)) + .Const(_SC("Play"), static_cast< SQInteger >(dpp::af_play)) + ); +} + +} // Namespace:: SqMod diff --git a/module/Library/DPPTy.hpp b/module/Library/DPPTy.hpp new file mode 100644 index 00000000..daee1ac1 --- /dev/null +++ b/module/Library/DPPTy.hpp @@ -0,0 +1,702 @@ +#pragma once + +// ------------------------------------------------------------------------------------------------ +#include "Core/Utility.hpp" + +// ------------------------------------------------------------------------------------------------ +#include + +// ------------------------------------------------------------------------------------------------ +namespace SqMod { + +/* ------------------------------------------------------------------------------------------------ + * Represents the caching policy of the cluster. +*/ +struct DpCachePolicy +{ + SQInteger mUserPolicy{dpp::cp_aggressive}; + SQInteger mEmojiPolicy{dpp::cp_aggressive}; + SQInteger mRolePolicy{dpp::cp_aggressive}; + + /* -------------------------------------------------------------------------------------------- + * Default constructor. + */ + DpCachePolicy() noexcept = default; + + /* -------------------------------------------------------------------------------------------- + * Explicit constructor. + */ + explicit DpCachePolicy(SQInteger user) noexcept + : mUserPolicy(user), mEmojiPolicy(dpp::cp_aggressive), mRolePolicy(dpp::cp_aggressive) + { + } + + /* -------------------------------------------------------------------------------------------- + * Explicit constructor. + */ + DpCachePolicy(SQInteger user, SQInteger emoji) noexcept + : mUserPolicy(user), mEmojiPolicy(emoji), mRolePolicy(dpp::cp_aggressive) + { + } + + /* -------------------------------------------------------------------------------------------- + * Explicit constructor. + */ + DpCachePolicy(SQInteger user, SQInteger emoji, SQInteger role) noexcept + : mUserPolicy(user), mEmojiPolicy(emoji), mRolePolicy(role) + { + } + + /* -------------------------------------------------------------------------------------------- + * Copy constructor. + */ + DpCachePolicy(const DpCachePolicy &) noexcept = default; + + /* -------------------------------------------------------------------------------------------- + * Convert to native cache policy type. + */ + SQMOD_NODISCARD dpp::cache_policy_t ToNative() const noexcept + { + return dpp::cache_policy_t{ + static_cast< dpp::cache_policy_setting_t >(mUserPolicy), + static_cast< dpp::cache_policy_setting_t >(mEmojiPolicy), + static_cast< dpp::cache_policy_setting_t >(mRolePolicy) + }; + } +}; + +/* ------------------------------------------------------------------------------------------------ + * An activity is a representation of what a user is doing. It might be a game, or a website, or a movie. Whatever. +*/ +struct DpActivity : public dpp::activity +{ + /* -------------------------------------------------------------------------------------------- + * Default constructor. + */ + DpActivity() + : dpp::activity() + { + } + + /* -------------------------------------------------------------------------------------------- + * Explicit constructor. + */ + DpActivity(SQInteger type, StackStrF & name, StackStrF & state, StackStrF & url) + : dpp::activity(static_cast< dpp::activity_type >(type), name.ToStr(), state.ToStr(), url.ToStr()) + { + } + + /* -------------------------------------------------------------------------------------------- + * Copy constructor. + */ + explicit DpActivity(const dpp::activity & o) + : dpp::activity(o) + { + } + + /* -------------------------------------------------------------------------------------------- + * Retrieve the name of the activity. + */ + SQMOD_NODISCARD const std::string & GetName() const noexcept + { + return dpp::activity::name; + } + + /* -------------------------------------------------------------------------------------------- + * Modify the name of the activity. + */ + void SetName(StackStrF & name) + { + dpp::activity::name = name.ToStr(); + } + + /* -------------------------------------------------------------------------------------------- + * Modify the name of the activity. + */ + DpActivity & ApplyName(StackStrF & name) + { + SetName(name); + return *this; + } + + /* -------------------------------------------------------------------------------------------- + * Retrieve the state of the activity. + */ + SQMOD_NODISCARD const std::string & GetState() const noexcept + { + return dpp::activity::state; + } + + /* -------------------------------------------------------------------------------------------- + * Modify the state of the activity. + */ + void SetState(StackStrF & state) + { + dpp::activity::state = state.ToStr(); + } + + /* -------------------------------------------------------------------------------------------- + * Modify the state of the activity. + */ + DpActivity & ApplyState(StackStrF & state) + { + SetState(state); + return *this; + } + + /* -------------------------------------------------------------------------------------------- + * Retrieve the url of the activity. + */ + SQMOD_NODISCARD const std::string & GetURL() const noexcept + { + return dpp::activity::url; + } + + /* -------------------------------------------------------------------------------------------- + * Modify the url of the activity. + */ + void SetURL(StackStrF & url) + { + dpp::activity::url = url.ToStr(); + } + + /* -------------------------------------------------------------------------------------------- + * Modify the url of the activity. + */ + DpActivity & ApplyURL(StackStrF & url) + { + SetURL(url); + return *this; + } + + /* -------------------------------------------------------------------------------------------- + * Retrieve the type of the activity. + */ + SQMOD_NODISCARD SQInteger GetType() const noexcept + { + return static_cast< SQInteger >(dpp::activity::type); + } + + /* -------------------------------------------------------------------------------------------- + * Modify the type of the activity. + */ + void SetType(SQInteger s) + { + dpp::activity::type = static_cast< dpp::activity_type >(s); + } + + /* -------------------------------------------------------------------------------------------- + * Modify the type of the activity. + */ + DpActivity & ApplyType(SQInteger s) + { + SetType(s); + return *this; + } + + /* -------------------------------------------------------------------------------------------- + * Retrieve when the activity was created. + */ + SQMOD_NODISCARD SQInteger GetCreatedAt() const noexcept + { + return static_cast< SQInteger >(std::chrono::duration_cast< std::chrono::seconds >(std::chrono::system_clock::from_time_t(dpp::activity::created_at).time_since_epoch()).count()); + } + + /* -------------------------------------------------------------------------------------------- + * Modify when the activity was created. + */ + void SetCreatedAt(SQInteger s) + { + dpp::activity::created_at = std::chrono::system_clock::to_time_t(std::chrono::time_point< std::chrono::system_clock >{std::chrono::seconds{s}}); + } + + /* -------------------------------------------------------------------------------------------- + * Modify when the activity was created. + */ + DpActivity & ApplyCreatedAt(SQInteger s) + { + SetCreatedAt(s); + return *this; + } + + /* -------------------------------------------------------------------------------------------- + * Retrieve when the activity was started. + */ + SQMOD_NODISCARD SQInteger GetStart() const noexcept + { + return static_cast< SQInteger >(std::chrono::duration_cast< std::chrono::seconds >(std::chrono::system_clock::from_time_t(dpp::activity::start).time_since_epoch()).count()); + } + + /* -------------------------------------------------------------------------------------------- + * Modify when the activity was started. + */ + void SetStart(SQInteger s) + { + dpp::activity::start = std::chrono::system_clock::to_time_t(std::chrono::time_point< std::chrono::system_clock >{std::chrono::seconds{s}}); + } + + /* -------------------------------------------------------------------------------------------- + * Modify when the activity was started. + */ + DpActivity & ApplyStart(SQInteger s) + { + SetStart(s); + return *this; + } + + /* -------------------------------------------------------------------------------------------- + * Retrieve when the activity was stopped. + */ + SQMOD_NODISCARD SQInteger GetEnd() const noexcept + { + return static_cast< SQInteger >(std::chrono::duration_cast< std::chrono::seconds >(std::chrono::system_clock::from_time_t(dpp::activity::end).time_since_epoch()).count()); + } + + /* -------------------------------------------------------------------------------------------- + * Modify when the activity was stopped. + */ + void SetEnd(SQInteger s) + { + dpp::activity::end = std::chrono::system_clock::to_time_t(std::chrono::time_point< std::chrono::system_clock >{std::chrono::seconds{s}}); + } + + /* -------------------------------------------------------------------------------------------- + * Modify when the activity was stopped. + */ + DpActivity & ApplyEnd(SQInteger s) + { + SetEnd(s); + return *this; + } +}; + +/* ------------------------------------------------------------------------------------------------ + * Represents user presence, e.g. what game they are playing and if they are online. +*/ +struct DpPresence : public dpp::presence +{ + /* -------------------------------------------------------------------------------------------- + * Default constructor. + */ + DpPresence() + : dpp::presence() + { + } + + /* -------------------------------------------------------------------------------------------- + * Retrieve the user that the presence applies to. + */ + SQMOD_NODISCARD dpp::snowflake GetUserID() const noexcept + { + return dpp::presence::user_id; + } + + /* -------------------------------------------------------------------------------------------- + * Modify the user that the presence applies to. + */ + void SetUserID(dpp::snowflake id) + { + dpp::presence::user_id = id; + } + + /* -------------------------------------------------------------------------------------------- + * Modify the user that the presence applies to. + */ + DpPresence & ApplyUserID(dpp::snowflake id) + { + SetUserID(id); + return *this; + } + + /* -------------------------------------------------------------------------------------------- + * Retrieve the guild that the presence applies to. + */ + SQMOD_NODISCARD dpp::snowflake GetGuildID() const noexcept + { + return dpp::presence::guild_id; + } + + /* -------------------------------------------------------------------------------------------- + * Modify the guild that the presence applies to. + */ + void SetGuildID(dpp::snowflake id) + { + dpp::presence::guild_id = id; + } + + /* -------------------------------------------------------------------------------------------- + * Modify the guild that the presence applies to. + */ + DpPresence & ApplyGuildID(dpp::snowflake id) + { + SetGuildID(id); + return *this; + } + + /* -------------------------------------------------------------------------------------------- + * Retrieve the presence bit-mask. + */ + SQMOD_NODISCARD SQInteger GetFlags() const noexcept + { + return static_cast< SQInteger >(dpp::presence::flags); + } + + /* -------------------------------------------------------------------------------------------- + * Modify the presence bit-mask. + */ + void SetFlags(SQInteger f) + { + dpp::presence::flags = static_cast< uint8_t >(f); + } + + /* -------------------------------------------------------------------------------------------- + * Modify the presence bit-mask. + */ + DpPresence & ApplyFlags(SQInteger f) + { + SetFlags(f); + return *this; + } + + /* -------------------------------------------------------------------------------------------- + * Retrieve the number of activities. + */ + SQMOD_NODISCARD SQInteger ActivityCount() const + { + return static_cast< SQInteger >(dpp::presence::activities.size()); + } + + /* -------------------------------------------------------------------------------------------- + * Add a new activity. + */ + DpPresence & AddActivity(const DpActivity & a) + { + dpp::presence::activities.push_back(a); + return *this; + } + + /* -------------------------------------------------------------------------------------------- + * Iterate all activities. + */ + DpPresence & EachActivity(Function & fn) + { + for (const auto & a : dpp::presence::activities) + { + fn.Execute(a); + } + return *this; + } + + /* -------------------------------------------------------------------------------------------- + * Retrieve the number of activities. + */ + DpPresence & ClearActivities(const DpActivity & a) + { + dpp::presence::activities.clear(); + return *this; + } + + /* -------------------------------------------------------------------------------------------- + * Filter activities. + */ + DpPresence & FilterActivities(Function & fn) + { + std::vector< dpp::activity > list; + list.reserve(dpp::presence::activities.size()); + for (const auto & a : dpp::presence::activities) + { + auto ret = fn.Eval(a); + // (null || true) == keep & false == skip + if (!ret.IsNull() || !ret.template Cast< bool >()) + { + list.push_back(a); + } + } + dpp::presence::activities.swap(list); + return *this; + } + + /* -------------------------------------------------------------------------------------------- + * Build JSON string from this object. + */ + SQMOD_NODISCARD std::string BuildJSON() const + { + return dpp::presence::build_json(); + } + + /* -------------------------------------------------------------------------------------------- + * Retrieve the users status on desktop. + */ + SQMOD_NODISCARD SQInteger GetDesktopStatus() const noexcept + { + return static_cast< SQInteger >(dpp::presence::desktop_status()); + } + + /* -------------------------------------------------------------------------------------------- + * Retrieve the user's status on web. + */ + SQMOD_NODISCARD SQInteger GetWebStatus() const noexcept + { + return static_cast< SQInteger >(dpp::presence::web_status()); + } + + /* -------------------------------------------------------------------------------------------- + * Retrieve the user's status on mobile. + */ + SQMOD_NODISCARD SQInteger GetMobileStatus() const noexcept + { + return static_cast< SQInteger >(dpp::presence::mobile_status()); + } + + /* -------------------------------------------------------------------------------------------- + * Retrieve the user's status as shown to other users. + */ + SQMOD_NODISCARD SQInteger GetStatus() const noexcept + { + return static_cast< SQInteger >(dpp::presence::status()); + } +}; + +/* ------------------------------------------------------------------------------------------------ + * Represents the voice state of a user on a guild. + * These are stored in the DpGuild object, and accessible there, or via DpChannel::GetVoiceMembers. +*/ +struct DpVoiceState +{ + using Ptr = std::unique_ptr< dpp::voicestate >; + /* -------------------------------------------------------------------------------------------- + * Referenced voice state instance. + */ + Ptr mPtr{nullptr}; + + /* -------------------------------------------------------------------------------------------- + * Whether the referenced pointer is owned. + */ + bool mOwned{false}; + + /* -------------------------------------------------------------------------------------------- + * Default constructor. + */ + DpVoiceState() noexcept = default; + + /* -------------------------------------------------------------------------------------------- + * Explicit constructor. + */ + explicit DpVoiceState(Ptr::pointer ptr, bool owned = false) noexcept + : mPtr(ptr), mOwned(owned) + { + } + + /* -------------------------------------------------------------------------------------------- + * Copy constructor (disabled). + */ + DpVoiceState(const DpVoiceState & o) = delete; + + /* -------------------------------------------------------------------------------------------- + * Move constructor. + */ + DpVoiceState(DpVoiceState && o) noexcept = default; + + /* -------------------------------------------------------------------------------------------- + * Destructor. + */ + ~DpVoiceState() noexcept + { + // Do we own this to try delete it? + if (!mOwned && mPtr) [[maybe_unused]] auto p = mPtr.release(); + } + + /* -------------------------------------------------------------------------------------------- + * Copy assignment operator (disabled). + */ + DpVoiceState & operator = (const DpVoiceState & o) = delete; + + /* -------------------------------------------------------------------------------------------- + * Move assignment operator. + */ + DpVoiceState & operator = (DpVoiceState && o) noexcept + { + if (this != &o) + { + // Do we own this to try delete it? + if (!mOwned && mPtr) [[maybe_unused]] auto p = mPtr.release(); + // Transfer members values + mPtr = std::move(o.mPtr); + mOwned = o.mOwned; + } + return *this; + } + + /* -------------------------------------------------------------------------------------------- + * Validate the managed handle. + */ + void Validate() const { if (!mPtr) STHROWF("Invalid discord voice state handle"); } + + /* -------------------------------------------------------------------------------------------- + * Validate the managed handle and retrieve a const reference to it. + */ + SQMOD_NODISCARD Ptr::element_type & Valid() const { Validate(); return *mPtr; } + + /* -------------------------------------------------------------------------------------------- + * Check whether a valid instance is managed. + */ + SQMOD_NODISCARD bool IsValid() const { return static_cast< bool >(mPtr); } + + /* -------------------------------------------------------------------------------------------- + * Retrieve the guild id this voice state is for (optional). + */ + SQMOD_NODISCARD dpp::snowflake GetGuildID() const { return Valid().guild_id; } + + /* -------------------------------------------------------------------------------------------- + * Retrieve the guild id this voice state is for (optional). + */ + SQMOD_NODISCARD dpp::snowflake GetChannelID() const { return Valid().channel_id; } + + /* -------------------------------------------------------------------------------------------- + * Retrieve the guild id this voice state is for (optional). + */ + SQMOD_NODISCARD dpp::snowflake GetUserID() const { return Valid().user_id; } + + /* -------------------------------------------------------------------------------------------- + * Retrieve the guild id this voice state is for (optional). + */ + SQMOD_NODISCARD const std::string & GetSessionID() const { return Valid().session_id; } + + /* -------------------------------------------------------------------------------------------- + * Retrieve the guild id this voice state is for (optional). + */ + SQMOD_NODISCARD SQInteger GetFlags() const { return Valid().flags; } + + /* -------------------------------------------------------------------------------------------- + * Retrieve the guild id this voice state is for (optional). + */ + void SetFlags(SQInteger flags) const { Valid().flags = flags; } + + /* -------------------------------------------------------------------------------------------- + * Retrieve the guild id this voice state is for (optional). + */ + SQMOD_NODISCARD std::string BuildJSON() const { return Valid().build_json(); } + + /* -------------------------------------------------------------------------------------------- + * Check if user is deafened. + */ + SQMOD_NODISCARD bool IsDeaf() const { return Valid().is_deaf(); } + + /* -------------------------------------------------------------------------------------------- + * Check if user is muted. + */ + SQMOD_NODISCARD bool IsMute() const { return Valid().is_mute(); } + + /* -------------------------------------------------------------------------------------------- + * Check if user muted themselves. + */ + SQMOD_NODISCARD bool IsSelfMute() const { return Valid().is_self_mute(); } + + /* -------------------------------------------------------------------------------------------- + * Check if user deafened themselves. + */ + SQMOD_NODISCARD bool IsSelfDeaf() const { return Valid().is_self_deaf(); } + + /* -------------------------------------------------------------------------------------------- + * Check if user is streamig. + */ + SQMOD_NODISCARD bool SelfStream() const { return Valid().self_stream(); } + + /* -------------------------------------------------------------------------------------------- + * Check if user is in video. + */ + SQMOD_NODISCARD bool SelfVideo() const { return Valid().self_video(); } + + /* -------------------------------------------------------------------------------------------- + * Check if user is surpressed. + */ + SQMOD_NODISCARD bool IsSupressed() const { return Valid().is_supressed(); } +}; + +/* ------------------------------------------------------------------------------------------------ + * Represents a guild on Discord (AKA a server) +*/ +struct DpGuild +{ + using Ptr = std::unique_ptr< dpp::guild >; + /* -------------------------------------------------------------------------------------------- + * Referenced voice state instance. + */ + Ptr mPtr{nullptr}; + + /* -------------------------------------------------------------------------------------------- + * Whether the referenced pointer is owned. + */ + bool mOwned{false}; + + /* -------------------------------------------------------------------------------------------- + * Default constructor. + */ + DpGuild() noexcept = default; + + /* -------------------------------------------------------------------------------------------- + * Explicit constructor. + */ + explicit DpGuild(Ptr::pointer ptr, bool owned = false) noexcept + : mPtr(ptr), mOwned(owned) + { + } + + /* -------------------------------------------------------------------------------------------- + * Copy constructor (disabled). + */ + DpGuild(const DpGuild & o) = delete; + + /* -------------------------------------------------------------------------------------------- + * Move constructor. + */ + DpGuild(DpGuild && o) noexcept = default; + + /* -------------------------------------------------------------------------------------------- + * Destructor. + */ + ~DpGuild() noexcept + { + // Do we own this to try delete it? + if (!mOwned && mPtr) [[maybe_unused]] auto p = mPtr.release(); + } + + /* -------------------------------------------------------------------------------------------- + * Copy assignment operator (disabled). + */ + DpGuild & operator = (const DpGuild & o) = delete; + + /* -------------------------------------------------------------------------------------------- + * Move assignment operator. + */ + DpGuild & operator = (DpGuild && o) noexcept + { + if (this != &o) + { + // Do we own this to try delete it? + if (!mOwned && mPtr) [[maybe_unused]] auto p = mPtr.release(); + // Transfer members values + mPtr = std::move(o.mPtr); + mOwned = o.mOwned; + } + return *this; + } + + /* -------------------------------------------------------------------------------------------- + * Validate the managed handle. + */ + void Validate() const { if (!mPtr) STHROWF("Invalid discord guild handle"); } + + /* -------------------------------------------------------------------------------------------- + * Validate the managed handle and retrieve a const reference to it. + */ + SQMOD_NODISCARD Ptr::element_type & Valid() const { Validate(); return *mPtr; } + + /* -------------------------------------------------------------------------------------------- + * Check whether a valid instance is managed. + */ + SQMOD_NODISCARD bool IsValid() const { return static_cast< bool >(mPtr); } + +}; + +} // Namespace:: SqMod diff --git a/module/Main.cpp b/module/Main.cpp index acdcb2f2..65b686f2 100644 --- a/module/Main.cpp +++ b/module/Main.cpp @@ -24,6 +24,9 @@ extern void ProcessRoutines(); extern void ProcessTasks(); extern void ProcessThreads(); extern void ProcessNet(); +#ifdef VCMP_ENABLE_DISCORD + extern void ProcessDPP(); +#endif /* ------------------------------------------------------------------------------------------------ * Will the scripts be reloaded at the end of the current event? @@ -172,6 +175,10 @@ static void OnServerFrame(float elapsed_time) ProcessThreads(); // Process network ProcessNet(); + // Process DPP +#ifdef VCMP_ENABLE_DISCORD + ProcessDPP(); +#endif // Process log messages from other threads Logger::Get().ProcessQueue(); // See if a reload was requested diff --git a/module/Register.cpp b/module/Register.cpp index 417bd160..24f472b8 100644 --- a/module/Register.cpp +++ b/module/Register.cpp @@ -44,6 +44,9 @@ extern void Register_System(HSQUIRRELVM vm); extern void Register_Utils(HSQUIRRELVM vm); extern void Register_XML(HSQUIRRELVM vm); extern void Register_ZMQ(HSQUIRRELVM vm); +#ifdef VCMP_ENABLE_DISCORD + extern void Register_DPP(HSQUIRRELVM vm); +#endif #ifdef SQMOD_POCO_HAS_SQLITE extern void Register_SQLite(HSQUIRRELVM vm); #endif @@ -110,6 +113,9 @@ bool RegisterAPI(HSQUIRRELVM vm) Register_Utils(vm); Register_XML(vm); Register_ZMQ(vm); +#ifdef VCMP_ENABLE_DISCORD + Register_DPP(vm); +#endif #ifdef SQMOD_POCO_HAS_SQLITE Register_SQLite(vm); #endif diff --git a/vendor/CMakeLists.txt b/vendor/CMakeLists.txt index e88ca59b..a71df960 100644 --- a/vendor/CMakeLists.txt +++ b/vendor/CMakeLists.txt @@ -52,3 +52,7 @@ if (WIN32 OR MINGW) set(ZMQ_HAVE_IPC OFF CACHE INTERNAL "" FORCE) endif() add_subdirectory(ZMQ) +# Should we include DPP? +if (ENABLE_DISCORD) + add_subdirectory(DPP) +endif() diff --git a/vendor/DPP/CMakeLists.txt b/vendor/DPP/CMakeLists.txt new file mode 100644 index 00000000..0069bd56 --- /dev/null +++ b/vendor/DPP/CMakeLists.txt @@ -0,0 +1,171 @@ +# Create the DPP library +add_library(DPP STATIC + include/dpp/nlohmann/json.hpp + include/dpp/nlohmann/json_fwd.hpp + include/dpp/auditlog.h + include/dpp/ban.h + include/dpp/cache.h + include/dpp/channel.h + include/dpp/cluster.h + include/dpp/commandhandler.h + include/dpp/discord.h + include/dpp/discordclient.h + include/dpp/discordevents.h + include/dpp/discordvoiceclient.h + include/dpp/dispatcher.h + include/dpp/dpp.h + include/dpp/dtemplate.h + include/dpp/emoji.h + include/dpp/event.h + include/dpp/export.h + include/dpp/guild.h + include/dpp/httplib.h + include/dpp/integration.h + include/dpp/intents.h + include/dpp/invite.h + include/dpp/json_fwd.hpp + include/dpp/message.h + include/dpp/presence.h + include/dpp/prune.h + include/dpp/queues.h + include/dpp/role.h + include/dpp/slashcommand.h + include/dpp/sslclient.h + include/dpp/stringops.h + include/dpp/user.h + include/dpp/version.h + include/dpp/voiceregion.h + include/dpp/voicestate.h + include/dpp/webhook.h + include/dpp/wsclient.h + src/dpp/ban.cpp + src/dpp/cache.cpp + src/dpp/channel.cpp + src/dpp/cluster.cpp + src/dpp/commandhandler.cpp + src/dpp/discordclient.cpp + src/dpp/discordevents.cpp + src/dpp/discordvoiceclient.cpp + src/dpp/dispatcher.cpp + src/dpp/dtemplate.cpp + src/dpp/emoji.cpp + src/dpp/guild.cpp + src/dpp/httplib.cpp + src/dpp/integration.cpp + src/dpp/invite.cpp + src/dpp/managed.cpp + src/dpp/message.cpp + src/dpp/presence.cpp + src/dpp/prune.cpp + src/dpp/queues.cpp + src/dpp/role.cpp + src/dpp/slashcommand.cpp + src/dpp/sslclient.cpp + src/dpp/user.cpp + src/dpp/utility.cpp + src/dpp/voiceregion.cpp + src/dpp/voicestate.cpp + src/dpp/webhook.cpp + src/dpp/wsclient.cpp + src/dpp/auditlog.cpp + src/dpp/events/application_command_update.cpp + src/dpp/events/channel_create.cpp + src/dpp/events/channel_delete.cpp + src/dpp/events/channel_pins_update.cpp + src/dpp/events/channel_update.cpp + src/dpp/events/guild_ban_add.cpp + src/dpp/events/guild_ban_remove.cpp + src/dpp/events/guild_create.cpp + src/dpp/events/guild_delete.cpp + src/dpp/events/guild_emojis_update.cpp + src/dpp/events/guild_integrations_update.cpp + src/dpp/events/guild_join_request_delete.cpp + src/dpp/events/guild_member_add.cpp + src/dpp/events/guild_member_remove.cpp + src/dpp/events/guild_member_update.cpp + src/dpp/events/guild_members_chunk.cpp + src/dpp/events/guild_role_create.cpp + src/dpp/events/guild_role_delete.cpp + src/dpp/events/guild_role_update.cpp + src/dpp/events/guild_stickers_update.cpp + src/dpp/events/guild_update.cpp + src/dpp/events/integration_create.cpp + src/dpp/events/integration_delete.cpp + src/dpp/events/integration_update.cpp + src/dpp/events/interaction_create.cpp + src/dpp/events/invite_create.cpp + src/dpp/events/invite_delete.cpp + src/dpp/events/logger.cpp + src/dpp/events/message_create.cpp + src/dpp/events/message_delete.cpp + src/dpp/events/message_delete_bulk.cpp + src/dpp/events/message_reaction_add.cpp + src/dpp/events/message_reaction_remove.cpp + src/dpp/events/message_reaction_remove_all.cpp + src/dpp/events/message_reaction_remove_emoji.cpp + src/dpp/events/message_update.cpp + src/dpp/events/presence_update.cpp + src/dpp/events/ready.cpp + src/dpp/events/resumed.cpp + src/dpp/events/stage_instance_create.cpp + src/dpp/events/stage_instance_delete.cpp + src/dpp/events/thread_create.cpp + src/dpp/events/thread_delete.cpp + src/dpp/events/thread_list_sync.cpp + src/dpp/events/thread_member_update.cpp + src/dpp/events/thread_members_update.cpp + src/dpp/events/thread_update.cpp + src/dpp/events/typing_start.cpp + src/dpp/events/user_update.cpp + src/dpp/events/voice_server_update.cpp + src/dpp/events/voice_state_update.cpp + src/dpp/events/webhooks_update.cpp + src/dpp/events/application_command_create.cpp + src/dpp/events/application_command_delete.cpp +) +# Configure include folders +target_include_directories(DPP PRIVATE ${CMAKE_CURRENT_LIST_DIR}/src) +target_include_directories(DPP PRIVATE ${CMAKE_CURRENT_LIST_DIR}/src/dpp) +target_include_directories(DPP PUBLIC ${CMAKE_CURRENT_LIST_DIR}/include) +# Link to built-in third-party libraries +target_link_libraries(DPP PUBLIC fmt::fmt) +# Project defines +target_compile_definitions(DPP PUBLIC DPP_BUILD=1) +# Platform defines +if(WIN32) + target_compile_definitions(DPP PRIVATE _WIN32_WINNT=0x0601 OPENSSL_SYS_WIN32=1 _WINSOCK_DEPRECATED_NO_WARNINGS=1 WIN32_LEAN_AND_MEAN=1 _CRT_SECURE_NO_WARNINGS=1 _CRT_NONSTDC_NO_DEPRECATE=1) + if (MINGW) + target_compile_definitions(DPP PUBLIC WIN32=1) + endif() + target_link_libraries(DPP PRIVATE Crypt32) +endif() +# Third-party library preferences +set(THREADS_PREFER_PTHREAD_FLAG ON) +# Find required third-party libraries +find_package(Threads REQUIRED) +find_package(ZLIB REQUIRED) +find_package(OpenSSL REQUIRED) +# Link to required third-party libraries +target_link_libraries(DPP PUBLIC Threads::Threads ZLIB::ZLIB OpenSSL::Crypto OpenSSL::SSL) +# Include the custom module folder +set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_CURRENT_LIST_DIR}/cmake/") +# Look for sodium and opus libraries +include("cmake/FindSodium.cmake") +include("cmake/FindOpus.cmake") +# Was the opus library found? +if(DEFINED OPUS_FOUND) + message(STATUS "Opus library was found") + # Link to opus library + target_include_directories(DPP PUBLIC ${OPUS_INCLUDE_DIRS}) + target_link_libraries(DPP PUBLIC ${OPUS_LIBRARIES}) + # Was the sodium library found? + if(DEFINED sodium_VERSION_STRING) + message(STATUS "Sodium library was found") + message(STATUS "DPP voice support enabled") + # Let the code know about this + target_compile_definitions(DPP PRIVATE HAVE_VOICE=1) + # Link to sodium library + target_include_directories(DPP PUBLIC ${sodium_INCLUDE_DIR}) + target_link_libraries(DPP PUBLIC ${sodium_LIBRARY_RELEASE}) + endif() +endif() diff --git a/vendor/DPP/LICENSE b/vendor/DPP/LICENSE new file mode 100644 index 00000000..261eeb9e --- /dev/null +++ b/vendor/DPP/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/DPP/cmake/FindOpus.cmake b/vendor/DPP/cmake/FindOpus.cmake new file mode 100644 index 00000000..ba231669 --- /dev/null +++ b/vendor/DPP/cmake/FindOpus.cmake @@ -0,0 +1,36 @@ +# OPUS_FOUND - system has opus +# OPUS_INCLUDE_DIRS - the opus include directory +# OPUS_LIBRARIES - The libraries needed to use opus + +find_path(OPUS_INCLUDE_DIRS + NAMES opus/opus.h + PATH_SUFFIXES include +) +if(OPUS_INCLUDE_DIRS) + set(HAVE_OPUS_OPUS_H 1) +endif() + +if(OPUS_USE_STATIC_LIBS) + find_library(OPUS_LIBRARIES NAMES "libopus.a") +else() + find_library(OPUS_LIBRARIES NAMES opus) +endif() + +if(OPUS_LIBRARIES) + if(OPUS_USE_STATIC_LIBS) + find_library(LIBM NAMES "libm.a" "libm.tbd") + else() + find_library(LIBM NAMES m) + endif() + if(LIBM) + list(APPEND OPUS_LIBRARIES ${LIBM}) + endif() +endif() + +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(Opus + DEFAULT_MSG + OPUS_INCLUDE_DIRS OPUS_LIBRARIES HAVE_OPUS_OPUS_H +) + +mark_as_advanced(OPUS_INCLUDE_DIRS OPUS_LIBRARIES HAVE_OPUS_OPUS_H) diff --git a/vendor/DPP/cmake/FindSodium.cmake b/vendor/DPP/cmake/FindSodium.cmake new file mode 100644 index 00000000..23c53171 --- /dev/null +++ b/vendor/DPP/cmake/FindSodium.cmake @@ -0,0 +1,293 @@ +# Written in 2016 by Henrik Steffen Gaßmann +# +# To the extent possible under law, the author(s) have dedicated all copyright +# and related and neighboring rights to this software to the public domain +# worldwide. This software is distributed without any warranty. +# +# You should have received a copy of the CC0 Public Domain Dedication along with +# this software. If not, see +# +# http://creativecommons.org/publicdomain/zero/1.0/ +# +# ############################################################################## +# Tries to find the local libsodium installation. +# +# On Windows the sodium_DIR environment variable is used as a default hint which +# can be overridden by setting the corresponding cmake variable. +# +# Once done the following variables will be defined: +# +# sodium_FOUND sodium_INCLUDE_DIR sodium_LIBRARY_DEBUG sodium_LIBRARY_RELEASE +# sodium_VERSION_STRING +# +# Furthermore an imported "sodium" target is created. +# + +if(CMAKE_C_COMPILER_ID STREQUAL "GNU" OR CMAKE_C_COMPILER_ID STREQUAL "Clang") + set(_GCC_COMPATIBLE 1) +endif() + +# static library option +if(NOT DEFINED sodium_USE_STATIC_LIBS) + option(sodium_USE_STATIC_LIBS "enable to statically link against sodium" OFF) +endif() +if(NOT (sodium_USE_STATIC_LIBS EQUAL sodium_USE_STATIC_LIBS_LAST)) + unset(sodium_LIBRARY CACHE) + unset(sodium_LIBRARY_DEBUG CACHE) + unset(sodium_LIBRARY_RELEASE CACHE) + unset(sodium_DLL_DEBUG CACHE) + unset(sodium_DLL_RELEASE CACHE) + set(sodium_USE_STATIC_LIBS_LAST + ${sodium_USE_STATIC_LIBS} + CACHE INTERNAL "internal change tracking variable") +endif() + +# ############################################################################## +# UNIX +if(UNIX) + # import pkg-config + find_package(PkgConfig QUIET) + if(PKG_CONFIG_FOUND) + pkg_check_modules(sodium_PKG QUIET libsodium) + endif() + + if(sodium_USE_STATIC_LIBS) + if(sodium_PKG_STATIC_LIBRARIES) + foreach(_libname ${sodium_PKG_STATIC_LIBRARIES}) + if(NOT _libname MATCHES "^lib.*\\.a$") # ignore strings already ending + # with .a + list(INSERT sodium_PKG_STATIC_LIBRARIES 0 "lib${_libname}.a") + endif() + endforeach() + list(REMOVE_DUPLICATES sodium_PKG_STATIC_LIBRARIES) + else() + # if pkgconfig for libsodium doesn't provide static lib info, then + # override PKG_STATIC here.. + set(sodium_PKG_STATIC_LIBRARIES libsodium.a) + endif() + + set(XPREFIX sodium_PKG_STATIC) + else() + if(sodium_PKG_LIBRARIES STREQUAL "") + set(sodium_PKG_LIBRARIES sodium) + endif() + + set(XPREFIX sodium_PKG) + endif() + + find_path(sodium_INCLUDE_DIR sodium.h HINTS ${${XPREFIX}_INCLUDE_DIRS}) + find_library(sodium_LIBRARY_DEBUG + NAMES ${${XPREFIX}_LIBRARIES} + HINTS ${${XPREFIX}_LIBRARY_DIRS}) + find_library(sodium_LIBRARY_RELEASE + NAMES ${${XPREFIX}_LIBRARIES} + HINTS ${${XPREFIX}_LIBRARY_DIRS}) + + # ############################################################################ + # Windows +elseif(WIN32) + set(sodium_DIR "$ENV{sodium_DIR}" CACHE FILEPATH "sodium install directory") + mark_as_advanced(sodium_DIR) + + find_path(sodium_INCLUDE_DIR sodium.h + HINTS ${sodium_DIR} + PATH_SUFFIXES include) + + if(MSVC) + # detect target architecture + file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/arch.cpp" [=[ + #if defined _M_IX86 + #error ARCH_VALUE x86_32 + #elif defined _M_X64 + #error ARCH_VALUE x86_64 + #endif + #error ARCH_VALUE unknown + ]=]) + try_compile(_UNUSED_VAR "${CMAKE_CURRENT_BINARY_DIR}" + "${CMAKE_CURRENT_BINARY_DIR}/arch.cpp" + OUTPUT_VARIABLE _COMPILATION_LOG) + string(REGEX + REPLACE ".*ARCH_VALUE ([a-zA-Z0-9_]+).*" + "\\1" + _TARGET_ARCH + "${_COMPILATION_LOG}") + + # construct library path + if(_TARGET_ARCH STREQUAL "x86_32") + string(APPEND _PLATFORM_PATH "Win32") + elseif(_TARGET_ARCH STREQUAL "x86_64") + string(APPEND _PLATFORM_PATH "x64") + else() + message( + FATAL_ERROR + "the ${_TARGET_ARCH} architecture is not supported by Findsodium.cmake." + ) + endif() + string(APPEND _PLATFORM_PATH "/$$CONFIG$$") + + if(MSVC_VERSION LESS 1900) + math(EXPR _VS_VERSION "${MSVC_VERSION} / 10 - 60") + else() + math(EXPR _VS_VERSION "${MSVC_VERSION} / 10 - 50") + endif() + string(APPEND _PLATFORM_PATH "/v${_VS_VERSION}") + + if(sodium_USE_STATIC_LIBS) + string(APPEND _PLATFORM_PATH "/static") + else() + string(APPEND _PLATFORM_PATH "/dynamic") + endif() + + string(REPLACE "$$CONFIG$$" + "Debug" + _DEBUG_PATH_SUFFIX + "${_PLATFORM_PATH}") + string(REPLACE "$$CONFIG$$" + "Release" + _RELEASE_PATH_SUFFIX + "${_PLATFORM_PATH}") + + find_library(sodium_LIBRARY_DEBUG libsodium.lib + HINTS ${sodium_DIR} + PATH_SUFFIXES ${_DEBUG_PATH_SUFFIX}) + find_library(sodium_LIBRARY_RELEASE libsodium.lib + HINTS ${sodium_DIR} + PATH_SUFFIXES ${_RELEASE_PATH_SUFFIX}) + if(NOT sodium_USE_STATIC_LIBS) + set(CMAKE_FIND_LIBRARY_SUFFIXES_BCK ${CMAKE_FIND_LIBRARY_SUFFIXES}) + set(CMAKE_FIND_LIBRARY_SUFFIXES ".dll") + find_library(sodium_DLL_DEBUG libsodium + HINTS ${sodium_DIR} + PATH_SUFFIXES ${_DEBUG_PATH_SUFFIX}) + find_library(sodium_DLL_RELEASE libsodium + HINTS ${sodium_DIR} + PATH_SUFFIXES ${_RELEASE_PATH_SUFFIX}) + set(CMAKE_FIND_LIBRARY_SUFFIXES ${CMAKE_FIND_LIBRARY_SUFFIXES_BCK}) + endif() + + elseif(_GCC_COMPATIBLE) + if(sodium_USE_STATIC_LIBS) + find_library(sodium_LIBRARY_DEBUG libsodium.a + HINTS ${sodium_DIR} + PATH_SUFFIXES lib) + find_library(sodium_LIBRARY_RELEASE libsodium.a + HINTS ${sodium_DIR} + PATH_SUFFIXES lib) + else() + find_library(sodium_LIBRARY_DEBUG libsodium.dll.a + HINTS ${sodium_DIR} + PATH_SUFFIXES lib) + find_library(sodium_LIBRARY_RELEASE libsodium.dll.a + HINTS ${sodium_DIR} + PATH_SUFFIXES lib) + + file(GLOB _DLL + LIST_DIRECTORIES false + RELATIVE "${sodium_DIR}/bin" + "${sodium_DIR}/bin/libsodium*.dll") + find_library(sodium_DLL_DEBUG ${_DLL} libsodium + HINTS ${sodium_DIR} + PATH_SUFFIXES bin) + find_library(sodium_DLL_RELEASE ${_DLL} libsodium + HINTS ${sodium_DIR} + PATH_SUFFIXES bin) + endif() + else() + message(FATAL_ERROR "this platform is not supported by FindSodium.cmake") + endif() + + # ############################################################################ + # unsupported +else() + message(FATAL_ERROR "this platform is not supported by FindSodium.cmake") +endif() + +# ############################################################################## +# common stuff + +# extract sodium version +if(sodium_INCLUDE_DIR) + set(_VERSION_HEADER "${sodium_INCLUDE_DIR}/sodium/version.h") + if(EXISTS "${_VERSION_HEADER}") + file(READ "${_VERSION_HEADER}" _VERSION_HEADER_CONTENT) + string( + REGEX + REPLACE + ".*#define[ \t]*SODIUM_VERSION_STRING[ \t]*\"([^\n]*)\".*" + "\\1" + sodium_VERSION_STRING + "${_VERSION_HEADER_CONTENT}") + set(sodium_VERSION_STRING "${sodium_VERSION_STRING}") + endif() +endif() + +# communicate results +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(sodium + REQUIRED_VARS + sodium_LIBRARY_RELEASE + sodium_LIBRARY_DEBUG + sodium_INCLUDE_DIR + VERSION_VAR + sodium_VERSION_STRING) + +# mark file paths as advanced +mark_as_advanced(sodium_INCLUDE_DIR) +mark_as_advanced(sodium_LIBRARY_DEBUG) +mark_as_advanced(sodium_LIBRARY_RELEASE) +if(WIN32) + mark_as_advanced(sodium_DLL_DEBUG) + mark_as_advanced(sodium_DLL_RELEASE) +endif() + +# create imported target +if(sodium_USE_STATIC_LIBS) + set(_LIB_TYPE STATIC) +else() + set(_LIB_TYPE SHARED) +endif() +add_library(sodium ${_LIB_TYPE} IMPORTED) + +set_target_properties(sodium + PROPERTIES INTERFACE_INCLUDE_DIRECTORIES + "${sodium_INCLUDE_DIR}" + IMPORTED_LINK_INTERFACE_LANGUAGES + "C") + +if(sodium_USE_STATIC_LIBS) + set_target_properties(sodium + PROPERTIES INTERFACE_COMPILE_DEFINITIONS + "SODIUM_STATIC" + IMPORTED_LOCATION + "${sodium_LIBRARY_RELEASE}" + IMPORTED_LOCATION_DEBUG + "${sodium_LIBRARY_DEBUG}") +else() + if(UNIX) + set_target_properties(sodium + PROPERTIES IMPORTED_LOCATION + "${sodium_LIBRARY_RELEASE}" + IMPORTED_LOCATION_DEBUG + "${sodium_LIBRARY_DEBUG}") + elseif(WIN32) + set_target_properties(sodium + PROPERTIES IMPORTED_IMPLIB + "${sodium_LIBRARY_RELEASE}" + IMPORTED_IMPLIB_DEBUG + "${sodium_LIBRARY_DEBUG}") + if(NOT (sodium_DLL_DEBUG MATCHES ".*-NOTFOUND")) + set_target_properties(sodium + PROPERTIES IMPORTED_LOCATION_DEBUG + "${sodium_DLL_DEBUG}") + endif() + if(NOT (sodium_DLL_RELEASE MATCHES ".*-NOTFOUND")) + set_target_properties(sodium + PROPERTIES IMPORTED_LOCATION_RELWITHDEBINFO + "${sodium_DLL_RELEASE}" + IMPORTED_LOCATION_MINSIZEREL + "${sodium_DLL_RELEASE}" + IMPORTED_LOCATION_RELEASE + "${sodium_DLL_RELEASE}") + endif() + endif() +endif() diff --git a/vendor/DPP/include/dpp/auditlog.h b/vendor/DPP/include/dpp/auditlog.h new file mode 100644 index 00000000..50411d77 --- /dev/null +++ b/vendor/DPP/include/dpp/auditlog.h @@ -0,0 +1,165 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ + +#pragma once +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief Defines types of audit log entry + */ +enum audit_type { + /// Guild update + ae_guild_update = 1, + /// Channel create + ae_channel_create = 10, + /// Channel update + ae_channel_update = 11, + /// Channel delete + ae_channel_delete = 12, + /// Channel overwrite create + ae_channel_overwrite_create = 13, + /// Channel overwrite update + ae_channel_overwrite_update = 14, + /// Channel overwrite delete + ae_channel_overwrite_delete = 15, + /// Channel member kick + ae_member_kick = 20, + /// Channel member prune + ae_member_prune = 21, + /// Channel member ban add + ae_member_ban_add = 22, + /// Channel member ban remove + ae_member_ban_remove = 23, + /// Guild member update + ae_member_update = 24, + /// Guild member role update + ae_member_role_update = 25, + /// Guild member move + ae_member_move = 26, + /// Guild member voice disconnect + ae_member_disconnect = 27, + /// Guild bot add + ae_bot_add = 28, + /// Guild role create + ae_role_create = 30, + /// Guild role update + ae_role_update = 31, + /// Guild role delete + ae_role_delete = 32, + /// Guild invite create + ae_invite_create = 40, + /// Guild invite update + ae_invite_update = 41, + /// Guild invite delete + ae_invite_delete = 42, + /// Guild webhook create + ae_webhook_create = 50, + /// Guild webhook update + ae_webhook_update = 51, + /// Guild webhook delete + ae_webhook_delete = 52, + /// Guild emoji create + ae_emoji_create = 60, + /// Guild emoji update + ae_emoji_update = 61, + /// Guild emoji delete + ae_emoji_delete = 62, + /// Guild message delete + ae_message_delete = 72, + /// Guild message bulk delete + ae_message_bulk_delete = 73, + /// Guild message pin + ae_message_pin = 74, + /// Guild message unpin + ae_message_unpin = 75, + /// Guild integration create + ae_integration_create = 80, + /// Guild integration update + ae_integration_update = 81, + /// Guild integration delete + ae_integration_delete = 82 +}; + +/** + * @brief Defines audit log changes + */ +struct CoreExport audit_change { + /// Optional: Serialised new value of the key + std::string new_value; + /// Optional: Serialised old value of the key + std::string old_value; + /// name of audit log change key + std::string key; +}; + +/** + * @brief Extra information for an audit log entry + */ +struct CoreExport audit_extra { + std::string delete_member_days; //!< number of days after which inactive members were kicked + std::string members_removed; //!< number of members removed by the prune + snowflake channel_id; //!< channel in which the entities were targeted + snowflake message_id; //!< id of the message that was targeted + std::string count; //!< number of entities that were targeted + snowflake id; //!< id of the overwritten entity + std::string type; //!< type of overwritten entity - "0" for "role" or "1" for "member" + std::string role_name; //!< name of the role if type is "0" (not present if type is "1") +}; + +/** + * @brief An individual audit log entry + */ +struct CoreExport audit_entry { + snowflake id; //!< id of the entry + snowflake target_id; //!< id of the affected entity (webhook, user, role, etc.) (may be empty) + std::vector changes; //!< Optional: changes made to the target_id + snowflake user_id; //!< the user who made the changes (may be empty) + audit_type event; //!< type of action that occurred + std::optional options; //!< Optional: additional info for certain action types + std::string reason; //!< Optional: the reason for the change (0-512 characters) +}; + +/** + * @brief The auditlog class represents the audit log entry of a guild. + */ +class CoreExport auditlog { +public: + std::vector entries; //!< Audit log entries + + /** Constructor */ + auditlog(); + + /** Destructor */ + ~auditlog(); + + /** Read class values from json object + * @param j A json object to read from + * @return A reference to self + */ + auditlog& fill_from_json(nlohmann::json* j); +}; + +}; diff --git a/vendor/DPP/include/dpp/ban.h b/vendor/DPP/include/dpp/ban.h new file mode 100644 index 00000000..5d0311a3 --- /dev/null +++ b/vendor/DPP/include/dpp/ban.h @@ -0,0 +1,64 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ + +#pragma once +#include +#include +#include + +namespace dpp { + +/** + * @brief The ban class represents a ban on a guild. + * + */ +class CoreExport ban { +public: + /** The ban reason */ + std::string reason; + /** User ID the ban applies to */ + snowflake user_id; + + /** Constructor */ + ban(); + + /** Destructor */ + ~ban(); + + /** Read class values from json object + * @param j A json object to read from + * @return A reference to self + */ + ban& fill_from_json(nlohmann::json* j); + + /** + * @brief Build json representation of a ban + * + * @return std::string stringified json + */ + std::string build_json() const; +}; + +/** A group of bans + */ +typedef std::unordered_map ban_map; + +}; diff --git a/vendor/DPP/include/dpp/cache.h b/vendor/DPP/include/dpp/cache.h new file mode 100644 index 00000000..60a341f9 --- /dev/null +++ b/vendor/DPP/include/dpp/cache.h @@ -0,0 +1,127 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ + +#pragma once +#include +#include +#include +#include + +namespace dpp { + + /** + * @brief A set of cached managed objects + */ + typedef std::unordered_map cache_container; + + /** + * @brief A cache object maintains a cache of dpp::managed objects. + * This is for example users, channels or guilds. + */ + class CoreExport cache { + private: + + /** Mutex to protect the cache */ + std::mutex cache_mutex; + + /** Cached items */ + cache_container* cache_map; + + public: + + /** + * @brief Construct a new cache object + */ + cache(); + + /** + * @brief Destroy the cache object + */ + ~cache(); + + /** Store an object in the cache. + * @param object object to store + */ + void store(managed* object); + + /** Remove an object from the cache. + * @param object object to remove + */ + void remove(managed* object); + + /** Find an object in the cache by id. + * @param id Object id to find + */ + managed* find(snowflake id); + + /** Return a count of the number of items in the cache. + */ + uint64_t count(); + + /** + * @brief Return the cache's locking mutex. Use this whenever + * you manipulate or iterate raw elements in the cache! + * + * @return The mutex used to protect the container + */ + std::mutex& get_mutex(); + + /** + * @brief Get the container map + * @warning Be sure to use cache::get_mutex() correctly if you + * manipulate or iterate the map returned by this method! If you do + * not, this is not thread safe and will casue crashes! + * @see cache::get_mutex + * + * @return cache_container& A reference to the cache's container map + */ + cache_container& get_container(); + + /** + * @brief "Rehash" a cache by cleaning out used RAM + * @warning May be time consuming! + */ + void rehash(); + + /** + * @brief Get "real" size in RAM of the cache + * + * @return size_t + */ + size_t bytes(); + + }; + + /** Run garbage collection across all caches removing deleted items + * that have been deleted over 60 seconds ago. + */ + void CoreExport garbage_collection(); + + #define cache_decl(type, setter, getter, counter) CoreExport type * setter (snowflake id); CoreExport cache * getter (); CoreExport uint64_t counter (); + + /* Declare major caches */ + cache_decl(user, find_user, get_user_cache, get_user_count); + cache_decl(guild, find_guild, get_guild_cache, get_guild_count); + cache_decl(role, find_role, get_role_cache, get_role_count); + cache_decl(channel, find_channel, get_channel_cache, get_channel_count); + cache_decl(emoji, find_emoji, get_emoji_cache, get_emoji_count); +}; + diff --git a/vendor/DPP/include/dpp/channel.h b/vendor/DPP/include/dpp/channel.h new file mode 100644 index 00000000..7d4646b2 --- /dev/null +++ b/vendor/DPP/include/dpp/channel.h @@ -0,0 +1,302 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ + +#pragma once +#include +#include + +namespace dpp { + +/** @brief Flag integers as received from and sent to discord */ +enum channel_type { +GUILD_TEXT = 0, //!< a text channel within a server +DM = 1, //!< a direct message between users +GUILD_VOICE = 2, //!< a voice channel within a server +GROUP_DM = 3, //!< a direct message between multiple users +GUILD_CATEGORY = 4, //!< an organizational category that contains up to 50 channels +GUILD_NEWS = 5, //!< a channel that users can follow and crosspost into their own server +GUILD_STORE = 6, //!< a channel in which game developers can sell their game on Discord +GUILD_NEWS_THREAD = 10, //!< a temporary sub-channel within a GUILD_NEWS channel +GUILD_PUBLIC_THREAD = 11, //!< a temporary sub-channel within a GUILD_TEXT channel +GUILD_PRIVATE_THREAD = 12, //!< a temporary sub-channel within a GUILD_TEXT channel that is only viewable by those invited and those with the MANAGE_THREADS permission +GUILD_STAGE = 13 //!< a "stage" channel, like a voice channel with one authorised speaker +}; +/** @brief Our flags as stored in the object */ +enum channel_flags { + /// NSFW Gated Channel + c_nsfw = 0b00000001, + /// Text channel + c_text = 0b00000010, + /// Direct Message + c_dm = 0b00000100, + /// Voice channel + c_voice = 0b00001000, + /// Group + c_group = 0b00010000, + /// Category + c_category = 0b00100000, + /// News channel + c_news = 0b01000000, + /// Store page + c_store = 0b10000000, + /// Stage channel + c_stage = 0b11000000, + /// News thread + c_news_thread = 0b11100000, + /// Public thread + c_public_thread = 0b11110000, + /// Private thread + c_private_thread = 0b11111000 +}; + +/** + * @brief channel permission overwrite types + */ +enum overwrite_type : uint8_t { + /// Role + ot_role = 0, + /// Member + ot_member = 1 +}; + +/** + * @brief channel permission overwrites + */ +struct CoreExport permission_overwrite { + /// Overwrite id + snowflake id; + /// Overwrite type + uint8_t type; + /// Allow mask + uint64_t allow; + /// Deny mask + uint64_t deny; +}; + + +/** + * @brief metadata for threads + */ +struct CoreExport thread_metadata { + /// Whether a thread is archived + bool archived; + /// When the thread was archived + time_t archive_timestamp; + /// The duration after a thread will archive + uint16_t auto_archive_duration; + /// Whether a thread is locked + bool locked; +}; + +/** + * @brief represents membership of a user with a thread + */ +struct CoreExport thread_member +{ + /// ID of the thread member is part of + snowflake thread_id; + /// ID of the member + snowflake user_id; + /// When the user joined the thread + time_t joined; + /// Flags bitmap + uint32_t flags; + + /** + * @brief Read struct values from a json object + * @param j json to read values from + * @return A reference to self + */ + thread_member& fill_from_json(nlohmann::json* j); +}; + +/** @brief A group of thread member objects*/ +typedef std::unordered_map thread_member_map; + +/** @brief A definition of a discord channel */ +class CoreExport channel : public managed { +public: + /** Flags bitmap */ + uint8_t flags; + + /** Guild id of the guild that owns the channel */ + snowflake guild_id; + + /** Sorting position, lower number means higher up the list */ + uint16_t position; + + /** Channel name */ + std::string name; + + /** Channel topic */ + std::string topic; + + /** ID of last message to be sent to the channel */ + snowflake last_message_id; + + /** Maximum user limit for voice channels (0-99) */ + uint8_t user_limit; + + /** Rate limit in kilobits per second for voice channels */ + uint16_t rate_limit_per_user; + + /** User ID of owner for group DMs */ + snowflake owner_id; + + /** Parent ID (category) */ + snowflake parent_id; + + /** Timestamp of last pinned message */ + time_t last_pin_timestamp; + + /** DM recipients */ + std::vector recipients; + + /** Permission overwrites to apply to base permissions */ + std::vector permission_overwrites; + + /** Approximate count of messages in a thread (threads) */ + uint8_t message_count; + + /** Approximate count of members in a thread (threads) */ + uint8_t member_count; + + /** Thread metadata (threads) */ + thread_metadata metadata; + + /** Constructor */ + channel(); + + /** Destructor */ + virtual ~channel(); + + /** Read class values from json object + * @param j A json object to read from + * @return A reference to self + */ + channel& fill_from_json(nlohmann::json* j); + + /** + * @brief Build json for this channel object + * + * @param with_id include the ID in the json + * @return std::string JSON string + */ + std::string build_json(bool with_id = false) const; + + /** + * @brief Get the user permissions for a user on this channel + * + * @param member The user to return permissions for + * @return uint64_t Permissions bitmask made of bits in role_permissions. + * Note that if the user is not on the channel or the guild is + * not in the cache, the function will always return 0. + */ + uint64_t get_user_permissions(const class user* member) const; + + /** + * @brief Return a map of members on the channel, built from the guild's + * member list based on which members have the VIEW_CHANNEL permission. + * Does not return reliable information for voice channels, use + * dpp::channel::get_voice_members() instead for this. + * @return A map of guild members keyed by user id. + */ + std::map get_members(); + + /** + * @brief Get a map of members in this channel, if it is a voice channel. + * The map is keyed by snowflake id of the user. + * + * @return std::map The voice members of the channel + */ + std::map get_voice_members(); + + /** + * @brief Returns true if the channel is NSFW gated + * + * @return true if NSFW + */ + bool is_nsfw() const; + + /** + * @brief Returns true if the channel is a text channel + * + * @return true if text channel + */ + bool is_text_channel() const; + + /** + * @brief Returns true if the channel is a DM + * + * @return true if is a DM + */ + bool is_dm() const; + + /** + * @brief Returns true if the channel is a voice channel + * + * @return true if voice channel + */ + bool is_voice_channel() const; + + /** + * @brief Returns true if the channel is a group DM channel + * + * @return true if group DM + */ + bool is_group_dm() const; + + /** + * @brief Returns true if the channel is a category + * + * @return true if a category + */ + bool is_category() const; + + /** + * @brief Returns true if the channel is a news channel + * + * @return true if news channel + */ + bool is_news_channel() const; + + /** + * @brief Returns true if the channel is a store channel + * + * @return true if store channel + */ + bool is_store_channel() const; + + /** + * @brief Returns true if the channel is a stage channel + * + * @return true if stage channel + */ + bool is_stage_channel() const; +}; + +/** + * @brief A group of channels + */ +typedef std::unordered_map channel_map; + +}; + diff --git a/vendor/DPP/include/dpp/cluster.h b/vendor/DPP/include/dpp/cluster.h new file mode 100644 index 00000000..87938927 --- /dev/null +++ b/vendor/DPP/include/dpp/cluster.h @@ -0,0 +1,2138 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { + +/** + * @brief A list of shards + */ +typedef std::map shard_list; + +/** + * @brief Represents the various information from the 'get gateway bot' api call + */ +struct CoreExport gateway { + /// Gateway websocket url + std::string url; + /// Number of suggested shards to start + uint32_t shards; + /// Total number of sessions that can be started + uint32_t session_start_total; + /// How many sessions are left + uint32_t session_start_remaining; + /// How many seconds until the session start quota resets + uint32_t session_start_reset_after; + /// How many sessions can be started at the same time + uint32_t session_start_max_concurrency; + /** + * @brief Construct a new gateway object + * + * @param j JSON data to construct from + */ + gateway(nlohmann::json* j); +}; + +/** + * @brief Confirmation object represents any true or false simple REST request + * + */ +struct CoreExport confirmation { + bool success; +}; + +/** + * @brief A container for types that can be returned for a REST API call + * + */ +typedef std::variant< + confirmation, + message, + message_map, + user, + user_map, + guild_member, + guild_member_map, + channel, + channel_map, + thread_member_map, + guild, + guild_map, + role, + role_map, + invite, + invite_map, + dtemplate, + dtemplate_map, + emoji, + emoji_map, + ban, + ban_map, + voiceregion, + voiceregion_map, + integration, + integration_map, + webhook, + webhook_map, + prune, + guild_widget, + gateway, + interaction, + interaction_response, + auditlog, + slashcommand, + slashcommand_map, + sticker, + sticker_map, + sticker_pack, + sticker_pack_map + > confirmable_t; + +/** + * @brief The details of a field in an error response + */ +struct CoreExport error_detail { + /** + * @brief Object name which is in error + */ + std::string object; + /** + * @brief Field name which is in error + */ + std::string field; + /** + * @brief Error code + */ + std::string code; + /** + * @brief Error reason (full message) + */ + std::string reason; +}; + +/** + * @brief The full details of an error from a REST response + */ +struct CoreExport error_info { + /** + * @brief Error code + */ + uint32_t code = 0; + /** + * @brief Error message + * + */ + std::string message; + /** + * @brief Field specific error descriptions + */ + std::vector errors; +}; + +/** + * @brief The results of a REST call wrapped in a convenient struct + */ +struct CoreExport confirmation_callback_t { + /** Returned data type in confirmable_t, used to double check to avoid an exception if you wish */ + std::string type; + /** Information about the HTTP call used to make the request */ + http_request_completion_t http_info; + /** Value returned, wrapped in variant */ + confirmable_t value; + + /** + * @brief Construct a new confirmation callback t object + */ + confirmation_callback_t() = default; + + /** + * @brief Construct a new confirmation callback object + * + * @param _type The type of callback that is encapsulated in the confirmable_t + * @param _value The value to encapsulate in the confirmable_t + * @param _http The HTTP metadata from the REST call + */ + confirmation_callback_t(const std::string &_type, const confirmable_t& _value, const http_request_completion_t& _http); + + /** + * @brief Returns true if the call resulted in an error rather than a legitimate value in the + * confirmation_callback_t::value member. + * + * @return true There was an error who's details can be obtained by get_error() + * @return false There was no error + */ + bool is_error() const; + + /** + * @brief Get the error_info object. + * The error_info object contains the details of any REST error, if there is an error + * (to find out if there is an error check confirmation_callback_t::is_error()) + * + * @return error_info The details of the error message + */ + error_info get_error() const; +}; + +/** + * @brief A callback upon command completion + */ +typedef std::function command_completion_event_t; + +/** + * @brief Automatically JSON encoded HTTP result + */ +typedef std::function json_encode_t; + +/** @brief The cluster class represents a group of shards and a command queue for sending and + * receiving commands from discord via HTTP. You should usually instantiate a cluster object + * at the very least to make use of the library. + */ +class CoreExport cluster { + + /** queue system for commands sent to Discord, and any replies */ + request_queue* rest; + + /** True if to use compression on shards */ + bool compressed; + + /** + * @brief Lock to prevent concurrent access to dm_channels + */ + std::mutex dm_list_lock; + + /** + * @brief Start time of cluster + */ + time_t start_time; + + /** + * @brief Active DM channels for the bot + */ + std::unordered_map dm_channels; + + /** + * @brief Active shards on this cluster. Shard IDs may have gaps between if there + * are multiple clusters. + */ + shard_list shards; + + /** + * @brief Accepts result from /gateway/bot REST API call and populates numshards with it + * + * @param shardinfo Received HTTP data from API call + */ + void auto_shard(const confirmation_callback_t &shardinfo); +public: + /** Current bot token for all shards on this cluster and all commands sent via HTTP */ + std::string token; + + /* Last time the bot sent an IDENTIFY */ + time_t last_identify; + + /** Current bitmask of gateway intents */ + uint32_t intents; + + /** Total number of shards across all clusters */ + uint32_t numshards; + + /** ID of this cluster, between 0 and MAXCLUSTERS-1 inclusive */ + uint32_t cluster_id; + + /** Total number of clusters that are active */ + uint32_t maxclusters; + + /** Routes events from Discord back to user program code via std::functions */ + dpp::dispatcher dispatch; + + /** + * @brief The details of the bot user. This is assumed to be identical across all shards + * in the cluster. Each connecting shard updates this information. + */ + dpp::user me; + + cache_policy_t cache_policy; + + /** + * @brief Constructor for creating a cluster. All but the token are optional. + * @param token The bot token to use for all HTTP commands and websocket connections + * @param intents A bitmask of dpd::intents values for all shards on this cluster. This is required to be sent for all bots with over 100 servers. + * @param shards The total number of shards on this bot. If there are multiple clusters, then (shards / clusters) actual shards will run on this cluster. + * If you omit this value, the library will attempt to query the Discord API for the correct number of shards to start. + * @param cluster_id The ID of this cluster, should be between 0 and MAXCLUSTERS-1 + * @param maxclusters The total number of clusters that are active, which may be on seperate processes or even separate machines. + * @param compressed Wether or not to use compression for shards on this cluster. Saves a ton of bandwidth at the cost of some CPU + * @param policy Set the user caching policy for the cluster, either lazy (only cache users/members when they message the bot) or aggressive (request whole member lists on seeing new guilds too) + */ + cluster(const std::string &token, uint32_t intents = i_default_intents, uint32_t shards = 0, uint32_t cluster_id = 0, uint32_t maxclusters = 1, bool compressed = true, cache_policy_t policy = {cp_aggressive, cp_aggressive, cp_aggressive}); + + /** + * @brief dpp::cluster is non-copyable + */ + cluster(const cluster&) = delete; + + /** + * @brief dpp::cluster is non-moveable + */ + cluster(const cluster&&) = delete; + + /** Destructor */ + ~cluster(); + + /** + * @brief Log a message to whatever log the user is using. + * The logged message is passed up the chain to the on_log event in user code which can then do whatever + * it wants to do with it. + * @param severity The log level from dpp::loglevel + * @param msg The log message to output + */ + void log(dpp::loglevel severity, const std::string &msg) const; + + /** + * @brief Get the dm channel for a user id + * + * @param user_id the user id to get the dm channel for + * @return Returns 0 on failure + */ + snowflake get_dm_channel(snowflake user_id); + + /** + * @brief Set the dm channel id for a user id + * + * @param user_id user id to set the dm channel for + * @param channel_id dm channel to set + */ + void set_dm_channel(snowflake user_id, snowflake channel_id); + + /** + * @brief Returns the uptime of the cluster + * + * @return dpp::utility::uptime The uptime of the cluster + */ + dpp::utility::uptime uptime(); + + /** + * @brief Start the cluster, connecting all its shards. + * Returns once all shards are connected. + * + * @param return_after If true the bot will return to your program after starting shards, if false this function will never return. + */ + void start(bool return_after = true); + + /** + * @brief Set the presence for all shards on the cluster + * + * @param p The presence to set. Only the online status and the first activity are sent. + */ + void set_presence(const class dpp::presence &p); + + /** + * @brief Get a shard by id, returning the discord_client + * + * @param id Shard ID + * @return discord_client* shard, or null + */ + discord_client* get_shard(uint32_t id); + + /** + * @brief Get the list of shards + * + * @return shard_list& Reference to map of shards for this cluster + */ + const shard_list& get_shards(); + + /* Functions for attaching to event handlers */ + + /** + * @brief on voice state update event + * + * @param _voice_state_update User function to attach to event + */ + void on_voice_state_update (std::function _voice_state_update); + + /** + * @brief Called when a log message is to be written to the log. + * You can attach any logging system here you wish, e.g. spdlog, or even just a simple + * use of std::cout or printf. If nothing attaches this log event, then the + * library will be silent. + * + * @param _log User function to attach to event + */ + void on_log (std::function _log); + + /** + * @brief on guild join request delete. + * Triggered when a user declines the membership screening questionnaire for a guild. + * + * @param _guild_join_request_delete User function to attach to event + */ + void on_guild_join_request_delete(std::function _guild_join_request_delete); + + /** + * @brief Called when a new interaction is created. + * Interactions are created by discord when commands you have registered are issued + * by a user. For an example of this in action please see \ref slashcommands + * + * @param _interaction_create User function to attach to event + */ + void on_interaction_create (std::function _interaction_create); + + /** + * @brief Called when a button is clicked attached to a message. + * Button clicks are triggered by discord when buttons are clicked which you have + * associated with a message using dpp::component. + * + * @param _button_click User function to attach to event + */ + void on_button_click (std::function _button_click); + + /** + * @brief Called when a select menu is clicked attached to a message. + * Select menu clicks are triggered by discord when select menus are clicked which you have + * associated with a message using dpp::component. + * + * @param _select_click User function to attach to event + */ + void on_select_click (std::function _select_click); + + /** + * @brief Called when a guild is deleted. + * A guild can be deleted via the bot being kicked, the bot leaving the guild + * explicitly with dpp::guild_delete, or via the guild being unavaialble due to + * an outage. + * + * @param _guild_delete User function to attach to event + */ + void on_guild_delete (std::function _guild_delete); + + /** + * @brief Called when a channel is deleted from a guild. + * The channel will still be temporarily avaialble in the cache. Pointers to the + * channel should not be retained long-term as they will be deleted by the garbage + * collector. + * + * @param _channel_delete User function to attach to event + */ + void on_channel_delete (std::function _channel_delete); + + /** + * @brief Called when a channel is edited on a guild. + * The new channel details have already been applied to the guild when you + * receive this event. + * + * @param _channel_update User function to attach to event + */ + void on_channel_update (std::function _channel_update); + + /** + * @brief Called when a shard is connected and ready. + * A set of on_guild_create events will follow this event. + * + * @param _ready User function to attach to event + */ + void on_ready (std::function _ready); + + /** + * @brief Called when a message is deleted. + * The message has already been deleted from Discord when you + * receive this event. + * + * @param _message_delete User function to attach to event + */ + void on_message_delete (std::function _message_delete); + + /** + * @brief Called when an application command (slash command) is deleted. + * + * @param _application_command_delete User function to attach to event + */ + void on_application_command_delete (std::function _application_command_delete); + + /** + * @brief Called when a user leaves a guild (either through being kicked, or choosing to leave) + * + * @param _guild_member_remove User function to attach to event + */ + void on_guild_member_remove (std::function _guild_member_remove); + + /** + * @brief Called when a new application command (slash command) is registered. + * + * @param _application_command_create User function to attach to event + */ + void on_application_command_create (std::function _application_command_create); + + /** + * @brief Called when a connection to a shard successfully resumes. + * A resumed session does not need to re-synchronise guilds, members, etc. + * This is generally non-fatal and informational only. + * + * @param _resumed User function to attach to event + */ + void on_resumed (std::function _resumed); + + /** + * @brief Called when a new role is created on a guild. + * + * @param _guild_role_create User function to attach to event + */ + void on_guild_role_create (std::function _guild_role_create); + + /** + * @brief Called when a user is typing on a channel. + * + * @param _typing_start User function to attach to event + */ + void on_typing_start (std::function _typing_start); + + /** + * @brief Called when a new reaction is added to a message. + * + * @param _message_reaction_add User function to attach to event + */ + void on_message_reaction_add (std::function _message_reaction_add); + + /** + * @brief Called when a set of members is received for a guild. + * D++ will request these for all new guilds if needed, after the on_guild_create + * events. + * + * @param _guild_members_chunk User function to attach to event + */ + void on_guild_members_chunk (std::function _guild_members_chunk); + + /** + * @brief Called when a single reaction is removed from a message. + * + * @param _message_reaction_remove User function to attach to event + */ + void on_message_reaction_remove (std::function _message_reaction_remove); + + /** + * @brief Called when a new guild is created. + * D++ will request members for the guild for its cache using guild_members_chunk. + * + * @param _guild_create User function to attach to event + */ + void on_guild_create (std::function _guild_create); + + /** + * @brief Called when a new channel is created on a guild. + * + * @param _channel_create User function to attach to event + */ + void on_channel_create (std::function _channel_create); + + /** + * @brief Called when all reactions for a particular emoji are removed from a message. + * + * @param _message_reaction_remove_emoji User function to attach to event + */ + void on_message_reaction_remove_emoji (std::function _message_reaction_remove_emoji); + + /** + * @brief Called when multiple messages are deleted from a channel or DM. + * + * @param _message_delete_bulk User function to attach to event + */ + void on_message_delete_bulk (std::function _message_delete_bulk); + + /** + * @brief Called when an existing role is updated on a guild. + * + * @param _guild_role_update User function to attach to event + */ + void on_guild_role_update (std::function _guild_role_update); + + /** + * @brief Called when a role is deleted in a guild. + * + * @param _guild_role_delete User function to attach to event + */ + void on_guild_role_delete (std::function _guild_role_delete); + + /** + * @brief Called when a message is pinned. + * Note that the pinned message is not returned to this event, just the timestamp + * of the last pinned message. + * + * @param _channel_pins_update User function to attach to event + */ + void on_channel_pins_update (std::function _channel_pins_update); + + /** + * @brief Called when all reactions are removed from a message. + * + * @param _message_reaction_remove_all User function to attach to event + */ + void on_message_reaction_remove_all (std::function _message_reaction_remove_all); + + /** + * @brief Called when we are told which voice server we can use. + * This will be sent either when we establish a new voice channel connection, + * or as discord rearrange their infrastructure. + * + * @param _voice_server_update User function to attach to event + */ + void on_voice_server_update (std::function _voice_server_update); + + /** + * @brief Called when new emojis are added to a guild. + * The complete set of emojis is sent every time. + * + * @param _guild_emojis_update User function to attach to event + */ + void on_guild_emojis_update (std::function _guild_emojis_update); + + /** + * @brief Called when new stickers are added to a guild. + * The complete set of stickers is sent every time. + * + * @param _guild_stickers_update User function to attach to event + */ + void on_guild_stickers_update (std::function _guild_stickers_update); + + /** + * @brief Called when a user's presence is updated. + * To receive these you will need the GUILD_PRESENCES privileged intent. + * You will receive many of these, very often, and receiving them will significaintly + * increase your bot's CPU usage. If you don't need them it is recommended to not ask + * for them. + * + * @param _presence_update User function to attach to event + */ + void on_presence_update (std::function _presence_update); + + /** + * @brief Called when the webhooks for a guild are updated. + * + * @param _webhooks_update User function to attach to event + */ + void on_webhooks_update (std::function _webhooks_update); + + /** + * @brief Called when a new member joins a guild. + * + * @param _guild_member_add User function to attach to event + */ + void on_guild_member_add (std::function _guild_member_add); + + /** + * @brief Called when an invite is deleted from a guild. + * + * @param _invite_delete User function to attach to event + */ + void on_invite_delete (std::function _invite_delete); + + /** + * @brief Called when details of a guild are updated. + * + * @param _guild_update User function to attach to event + */ + void on_guild_update (std::function _guild_update); + + /** + * @brief Called when an integration is updated for a guild. + * This returns the complete list. + * An integration is a connection to a guild of a user's associated accounts, + * e.g. youtube or twitch, for automatic assignment of roles etc. + * + * @param _guild_integrations_update User function to attach to event + */ + void on_guild_integrations_update (std::function _guild_integrations_update); + + /** + * @brief Called when details of a guild member (e.g. their roles or nickname) are updated. + * + * @param _guild_member_update User function to attach to event + */ + void on_guild_member_update (std::function _guild_member_update); + + /** + * @brief Called when an application command (slash command) is updated. + * You will only receive this event for application commands that belong to your bot/application. + * + * @param _application_command_update User function to attach to event + */ + void on_application_command_update (std::function _application_command_update); + + /** + * @brief Called when a new invite is created for a guild. + * + * @param _invite_create User function to attach to event + */ + void on_invite_create (std::function _invite_create); + + /** + * @brief Called when a message is updated (edited). + * + * @param _message_update User function to attach to event + */ + void on_message_update (std::function _message_update); + + /** + * @brief Called when a user is updated. + * This is separate to guild_member_update and includes things such as an avatar change, + * username change, discriminator change or change in subscription status for nitro. + * + * @param _user_update User function to attach to event + */ + void on_user_update (std::function _user_update); + + /** + * @brief Called when a new message arrives from discord. + * Note that D++ does not cache messages. If you want to cache these objects you + * should create something yourself within your bot. Caching of messages is not on + * the roadmap to be supported as it consumes excessive amounts of RAM. + * + * @param _message_create User function to attach to event + */ + void on_message_create (std::function _message_create); + + /** + * @brief Called when a ban is added to a guild. + * + * @param _guild_ban_add User function to attach to event + */ + void on_guild_ban_add (std::function _guild_ban_add); + + /** + * @brief Called when a ban is removed from a guild. + * + * @param _guild_ban_remove User function to attach to event + */ + void on_guild_ban_remove (std::function _guild_ban_remove); + + /** + * @brief Called when a new intgration is attached to a guild by a user. + * An integration is a connection to a guild of a user's associated accounts, + * e.g. youtube or twitch, for automatic assignment of roles etc. + * + * @param _integration_create User function to attach to event + */ + void on_integration_create (std::function _integration_create); + + /** + * @brief Called when an integration is updated by a user. + * This returns details of just the single integration that has changed. + * An integration is a connection to a guild of a user's associated accounts, + * e.g. youtube or twitch, for automatic assignment of roles etc. + * + * @param _integration_update User function to attach to event + */ + void on_integration_update (std::function _integration_update); + + /** + * @brief Called when an integration is removed by a user. + * An integration is a connection to a guild of a user's associated accounts, + * e.g. youtube or twitch, for automatic assignment of roles etc. + * + * @param _integration_delete User function to attach to event + */ + void on_integration_delete (std::function _integration_delete); + + /** + * @brief Called when a thread is created + * Note: Threads are not cached by D++, but a list of thread IDs is accessible in a guild object + * + * @param _thread_create User function to attach to event + */ + void on_thread_create (std::function _thread_create); + + /** + * @brief Called when a thread is updated + * + * @param _thread_update User function to attach to event + */ + void on_thread_update (std::function _thread_update); + + /** + * @brief Called when a thread is deleted + * + * @param _thread_delete User function to attach to event + */ + void on_thread_delete (std::function _thread_delete); + + /** + * @brief Called when thread list is synced (upon gaining access to a channel) + * Note: Threads are not cached by D++, but a list of thread IDs is accessible in a guild object + * + * @param _thread_list_sync User function to attach to event + */ + void on_thread_list_sync (std::function _thread_list_sync); + + /** + * @brief Called when current user's thread member object is updated + * + * @param _thread_member_update User function to attach to event + */ + void on_thread_member_update (std::function _thread_member_update); + + /** + * @brief Called when a thread's member list is updated (without GUILD_MEMBERS intent, is only called for current user) + * + * @param _thread_members_update User function to attach to event + */ + void on_thread_members_update (std::function _thread_members_update); + + /** + * @brief Called when packets are sent from the voice buffer. + * The voice buffer contains packets that are already encoded with Opus and encrypted + * with Sodium, and merged into packets by the repacketizer, which is done in the + * dpp::discord_voice_client::send_audio method. You should use the buffer size properties + * of dpp::voice_buffer_send_t to determine if you should fill the buffer with more + * content. + * + * @param _voice_buffer_send User function to attach to event + */ + void on_voice_buffer_send (std::function _voice_buffer_send); + + /** + * @brief Called when a user is talking on a voice channel. + * + * @param _voice_user_talking User function to attach to event + */ + void on_voice_user_talking (std::function _voice_user_talking); + + /** + * @brief Called when a voice channel is connected and ready to send audio. + * Note that this is not directly attached to the READY event of the websocket, + * as there is further connection that needs to be done before audio is ready to send. + * + * @param _voice_ready User function to attach to event + */ + void on_voice_ready (std::function _voice_ready); + + /** + * @brief Called when new audio data is received. + * @note Receiveing audio for bots is not supported or documented, so this + * endpoint will be triggered at the correct times but the audio buffer will + * always be null and size zero. + * + * @param _voice_receive User function to attach to event + */ + void on_voice_receive (std::function _voice_receive); + + /** + * @brief Called when sending of audio passes over a track marker. + * Track markers are arbitrarily placed "bookmarks" in the audio buffer, placed + * by the bot developer. Each track marker can have a string value associated with it + * which is specified in dpp::discord_voice_client::insert_marker and returned to this + * event. + * + * @param _voice_receive User function to attach to event + */ + void on_voice_track_marker (std::function _voice_track_marker); + + /** + * @brief Called when a new stage instance is created on a stage channel. + * + * @param _stage_instance_create User function to attach to event + */ + void on_stage_instance_create (std::function _stage_instance_create); + + /** + * @brief Called when an existing stage instance is deleted from a stage channel. + * + * @param _stage_instance_delete User function to attach to event + */ + void on_stage_instance_delete (std::function _stage_instance_delete); + + /** + * @brief Post a REST request. Where possible use a helper method instead like message_create + * + * @param endpoint Endpoint to post to, e.g. /api/guilds + * @param major_parameters Major parameters for the endpoint e.g. a guild id + * @param parameters Minor parameters for the API request + * @param method Method, e.g. GET, POST + * @param postdata Post data (usually JSON encoded) + * @param callback Function to call when the HTTP call completes. The callback parameter will contain amongst other things, the decoded json. + * @param filename Filename to post for POST requests (for uploading files) + * @param filecontent File content to post for POST requests (for uploading files) + */ + void post_rest(const std::string &endpoint, const std::string &major_parameters, const std::string ¶meters, http_method method, const std::string &postdata, json_encode_t callback, const std::string &filename = "", const std::string &filecontent = ""); + + /** + * @brief Respond to a slash command + * + * @param interaction_id Interaction id to respond to + * @param r Response to send + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void interaction_response_create(snowflake interaction_id, const std::string &token, const interaction_response &r, command_completion_event_t callback = {}); + + /** + * @brief Respond to a slash command + * + * @param m Message to send + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void interaction_response_edit(const std::string &token, const message &r, command_completion_event_t callback = {}); + + /** + * @brief Create a global slash command (a bot can have a maximum of 100 of these) + * + * @param s Slash command to create, s.id will be filled if the creation succeeds + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::slashcommmand object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void global_command_create(slashcommand &s, command_completion_event_t callback = {}); + + /** + * @brief Get the audit log for a guild + * + * @param guild_id Guild to get the audit log of + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::auditlog object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_auditlog_get(snowflake guild_id, command_completion_event_t callback); + + /** + * @brief Create a slash command local to a guild + * + * @param s Slash command to create, s.id will be filled if the creation succeeds + * @param guild_id Guild ID to create the slash command in + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::slashcommmand object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_command_create(slashcommand &s, snowflake guild_id, command_completion_event_t callback = {}); + + + /** + * @brief Create/overwrite guild slash commands + * + * @param s Vector of slash commands to create/update. + * New guild commands will be available in the guild immediately. If the command did not already exist, it will count toward daily application command create limits. + * @param guild_id Guild ID to create/update the slash commands in + * @param callback Function to call when the API call completes. + * On success the callback will contain a list of dpp::slashcommmand object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_bulk_command_create(const std::vector &commands, snowflake guild_id, command_completion_event_t callback = {}); + + /** + * @brief Create/overwrite global slash commands + * + * @param s Vector of slash commands to create/update. + * overwriting existing commands that are registered globally for this application. Updates will be available in all guilds after 1 hour. + * Commands that do not already exist will count toward daily application command create limits. + * @param callback Function to call when the API call completes. + * On success the callback will contain a list of dpp::slashcommmand object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void global_bulk_command_create(const std::vector &commands, command_completion_event_t callback = {}); + + /** + * @brief Edit a global slash command (a bot can have a maximum of 100 of these) + * + * @param s Slash command to change + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void global_command_edit(const slashcommand &s, command_completion_event_t callback = {}); + + /** + * @brief Edit a slash command local to a guild + * + * @param s Slash command to edit + * @param guild_id Guild ID to edit the slash command in + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_command_edit(const slashcommand &s, snowflake guild_id, command_completion_event_t callback = {}); + + /** + * @brief Edit slash command permissions local to a guild, + * permissions are read from s.permissions + * + * @param s Slash command to edit + * @param guild_id Guild ID to edit the slash command in + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_command_edit_permissions(const slashcommand &s, snowflake guild_id, command_completion_event_t callback = {}); + + + + /** + * @brief Delete a global slash command (a bot can have a maximum of 100 of these) + * + * @param id Slash command to delete + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void global_command_delete(snowflake id, command_completion_event_t callback = {}); + + /** + * @brief Delete a slash command local to a guild + * + * @param id Slash command to delete + * @param guild_id Guild ID to delete the slash command in + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_command_delete(snowflake id, snowflake guild_id, command_completion_event_t callback = {}); + + /** + * @brief Get the application's slash commands for a guild + * + * @param guild_id Guild ID to get the slash commands for + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::slashcommand_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_commands_get(snowflake guild_id, command_completion_event_t callback); + + /** + * @brief Get the application's global slash commands + * + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::slashcommand_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void global_commands_get(command_completion_event_t callback); + + /** + * @brief Create a direct message, also create the channel for the direct message if needed + * + * @param user_id User ID of user to send message to + * @param m Message object + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::message object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void direct_message_create(snowflake user_id, const message &m, command_completion_event_t callback = {}); + + /** + * @brief Get a message + * + * @param message_id Message ID + * @param channel_id Channel ID + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::message object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void message_get(snowflake message_id, snowflake channel_id, command_completion_event_t callback); + + /** + * @brief Get multiple messages + * + * @param channel_id Channel ID to retrieve messages for + * @param around Messages should be retrieved around this ID if this is set to non-zero + * @param before Messages before this ID should be retrieved if this is set to non-zero + * @param after Messages before this ID should be retrieved if this is set to non-zero + * @param limit This number of messages maximum should be returned + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::message_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void messages_get(snowflake channel_id, snowflake around, snowflake before, snowflake after, snowflake limit, command_completion_event_t callback); + + /** + * @brief Send a message to a channel. The callback function is called when the message has been sent + * + * @param m Message to send + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::message object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void message_create(const struct message &m, command_completion_event_t callback = {}); + + /** + * @brief Crosspost a message. The callback function is called when the message has been sent + * + * @param message_id Message to crosspost + * @param channel_id Channel ID to crosspost from + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::message object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void message_crosspost(snowflake message_id, snowflake channel_id, command_completion_event_t callback = {}); + + /** + * @brief Edit a message on a channel. The callback function is called when the message has been edited + * + * @param m Message to edit + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::message object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void message_edit(const struct message &m, command_completion_event_t callback = {}); + + /** + * @brief Add a reaction to a message. The reaction string must be either an `emojiname:id` or a unicode character. + * + * @param m Message to add a reaction to + * @param reaction Reaction to add. Emojis should be in the form emojiname:id + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void message_add_reaction(const struct message &m, const std::string &reaction, command_completion_event_t callback = {}); + + /** + * @brief Delete own reaction from a message. The reaction string must be either an `emojiname:id` or a unicode character. + * + * @param m Message to delete own reaction from + * @param reaction Reaction to delete. The reaction should be in the form emojiname:id + * @param callback Function to call when the API call completes. + */ + void message_delete_own_reaction(const struct message &m, const std::string &reaction, command_completion_event_t callback = {}); + + /** + * @brief Delete a user's reaction from a message. The reaction string must be either an `emojiname:id` or a unicode character + * + * @param m Message to delete a user's reaction from + * @param user_id User ID who's reaction you want to remove + * @param reaction Reaction to remove. Reactions should be in the form emojiname:id + * @param callback Function to call when the API call completes. + */ + void message_delete_reaction(const struct message &m, snowflake user_id, const std::string &reaction, command_completion_event_t callback = {}); + + /** + * @brief Get reactions on a message for a particular emoji. The reaction string must be either an `emojiname:id` or a unicode character + * + * @param m Message to get reactions for + * @param reaction Reaction should be in the form emojiname:id or a unicode character + * @param before Reactions before this ID should be retrieved if this is set to non-zero + * @param after Reactions before this ID should be retrieved if this is set to non-zero + * @param limit This number of reactions maximum should be returned + * @param callback Function to call when the API call completes. + */ + void message_get_reactions(const struct message &m, const std::string &reaction, snowflake before, snowflake after, snowflake limit, command_completion_event_t callback); + + /** + * @brief Delete all reactions on a message + * + * @param m Message to delete reactions from + * @param callback Function to call when the API call completes. + */ + void message_delete_all_reactions(const struct message &m, command_completion_event_t callback = {}); + + /** + * @brief Delete all reactions on a message using a particular emoji. The reaction string must be either an `emojiname:id` or a unicode character + * + * @param m Message to delete reactions from + * @param reaction Reaction to delete, in the form emojiname:id or a unicode character + * @param callback Function to call when the API call completes. + */ + void message_delete_reaction_emoji(const struct message &m, const std::string &reaction, command_completion_event_t callback = {}); + + /** + * @brief Add a reaction to a message by id. The reaction string must be either an `emojiname:id` or a unicode character. + * + * @param message_id Message to add reactions to + * @param channel_id Channel to add reactions to + * @param reaction Reaction to add. Emojis should be in the form emojiname:id + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void message_add_reaction(snowflake message_id, snowflake channel_id, const std::string &reaction, command_completion_event_t callback = {}); + + /** + * @brief Delete own reaction from a message by id. The reaction string must be either an `emojiname:id` or a unicode character. + * + * @param message_id Message to delete reactions from + * @param channel_id Channel to delete reactions from + * @param reaction Reaction to delete. The reaction should be in the form emojiname:id + * @param callback Function to call when the API call completes. + */ + void message_delete_own_reaction(snowflake message_id, snowflake channel_id, const std::string &reaction, command_completion_event_t callback = {}); + + /** + * @brief Delete a user's reaction from a message by id. The reaction string must be either an `emojiname:id` or a unicode character + * + * @param message_id Message to delete reactions from + * @param channel_id Channel to delete reactions from + * @param user_id User ID who's reaction you want to remove + * @param reaction Reaction to remove. Reactions should be in the form emojiname:id + * @param callback Function to call when the API call completes. + */ + void message_delete_reaction(snowflake message_id, snowflake channel_id, snowflake user_id, const std::string &reaction, command_completion_event_t callback = {}); + + /** + * @brief Get reactions on a message for a particular emoji by id. The reaction string must be either an `emojiname:id` or a unicode character + * + * @param message_id Message to get reactions for + * @param channel_id Channel to get reactions for + * @param reaction Reaction should be in the form emojiname:id or a unicode character + * @param before Reactions before this ID should be retrieved if this is set to non-zero + * @param after Reactions before this ID should be retrieved if this is set to non-zero + * @param limit This number of reactions maximum should be returned + * @param callback Function to call when the API call completes. + */ + void message_get_reactions(snowflake message_id, snowflake channel_id, const std::string &reaction, snowflake before, snowflake after, snowflake limit, command_completion_event_t callback); + + /** + * @brief Delete all reactions on a message by id + * + * @param message_id Message to delete reactions from + * @param channel_id Channel to delete reactions from + * @param callback Function to call when the API call completes. + */ + void message_delete_all_reactions(snowflake message_id, snowflake channel_id, command_completion_event_t callback = {}); + + /** + * @brief Delete all reactions on a message using a particular emoji by id. The reaction string must be either an `emojiname:id` or a unicode character + * + * @param message_id Message to delete reactions from + * @param channel_id Channel to delete reactions from + * @param reaction Reaction to delete, in the form emojiname:id or a unicode character + * @param callback Function to call when the API call completes. + */ + void message_delete_reaction_emoji(snowflake message_id, snowflake channel_id, const std::string &reaction, command_completion_event_t callback = {}); + + /** + * @brief Delete a message from a channel. The callback function is called when the message has been edited + * + * @param message_id Message ID to delete + * @param channel_id Channel to delete from + * @param callback Function to call when the API call completes. + */ + void message_delete(snowflake message_id, snowflake channel_id, command_completion_event_t callback = {}); + + /** + * @brief Bulk delete messages from a channel. The callback function is called when the message has been edited + * + * @param message_ids List of message IDs to delete (maximum of 100 message IDs) + * @param channel_id Channel to delete from + * @param callback Function to call when the API call completes. + */ + void message_delete_bulk(const std::vector &message_ids, snowflake channel_id, command_completion_event_t callback = {}); + + /** + * @brief Get a channel + * + * @param c Channel ID to retrieve + * @param callback Function to call when the API call completes. + */ + void channel_get(snowflake c, command_completion_event_t callback); + + /** + * @brief Get all channels for a guild + * + * @param guild_id Guild ID to retrieve channels for + * @param callback Function to call when the API call completes. + */ + void channels_get(snowflake guild_id, command_completion_event_t callback); + + /** + * @brief Create a channel + * + * @param c Channel to create + * @param callback Function to call when the API call completes. + */ + void channel_create(const class channel &c, command_completion_event_t callback = {}); + + /** + * @brief Edit a channel + * + * @param c Channel to edit/update + * @param callback Function to call when the API call completes. + */ + void channel_edit(const class channel &c, command_completion_event_t callback = {}); + + /** + * @brief Edit a channel's position + * + * @param c Channel to change the position for + * @param callback Function to call when the API call completes. + */ + void channel_edit_position(const class channel &c, command_completion_event_t callback = {}); + + /** + * @brief Edit a channel's permissions + * + * @param c Channel to set permissions for + * @param overwrite_id Overwrite to change (a user or channel ID) + * @param allow allow permissions + * @param deny deny permissions + * @param member true if the overwrite_id is a user id, false if it is a channel id + * @param callback Function to call when the API call completes. + */ + void channel_edit_permissions(const class channel &c, snowflake overwrite_id, uint32_t allow, uint32_t deny, bool member, command_completion_event_t callback = {}); + + /** + * @brief Delete a channel + * + * @param channel_id Channel id to delete + * @param callback Function to call when the API call completes. + */ + void channel_delete(snowflake channel_id, command_completion_event_t callback = {}); + + /** + * @brief Get details about an invite + * + * @param invite Invite code to get information on + * @param callback Function to call when the API call completes. + */ + void invite_get(const std::string &invite, command_completion_event_t callback); + + /** + * @brief Delete an invite + * + * @param invite Invite code to delete + * @param callback Function to call when the API call completes. + */ + void invite_delete(const std::string &invite, command_completion_event_t callback = {}); + + /** + * @brief Get invites for a channel + * + * @param c Channel to get invites for + * @param callback Function to call when the API call completes. + */ + void channel_invites_get(const class channel &c, command_completion_event_t callback); + + /** + * @brief Create invite for a channel + * + * @param c Channel to create an invite on + * @param i Invite to create + * @param callback Function to call when the API call completes. + */ + void channel_invite_create(const class channel &c, const class invite &i, command_completion_event_t callback = {}); + + /** + * @brief Get a channel's pins + * + * @param channel_id Channel ID to get pins for + * @param callback Function to call when the API call completes. + */ + void pins_get(snowflake channel_id, command_completion_event_t callback); + + /** + * @brief Adds a recipient to a Group DM using their access token + * + * @param channel_id Channel id to add group DM recipients to + * @param user_id User ID to add + * @param access_token Access token from OAuth2 + * @param nick Nickname of user to apply to the chat + * @param callback Function to call when the API call completes. + */ + void gdm_add(snowflake channel_id, snowflake user_id, const std::string &access_token, const std::string &nick, command_completion_event_t callback = {}); + + /** + * @brief Removes a recipient from a Group DM + * + * @param channel_id Channel ID of group DM + * @param user_id User ID to remove from group DM + * @param callback Function to call when the API call completes. + */ + void gdm_remove(snowflake channel_id, snowflake user_id, command_completion_event_t callback = {}); + + /** + * @brief Remove a permission from a channel + * + * @param c Channel to remove permission from + * @param overwrite_id Overwrite to remove, user or channel ID + * @param callback Function to call when the API call completes. + */ + void channel_delete_permission(const class channel &c, snowflake overwrite_id, command_completion_event_t callback = {}); + + /** + * @brief Follow a news channel + * + * @param c Channel id to follow + * @param target_channel_id Channel to subscribe the channel to + * @param callback Function to call when the API call completes. + */ + void channel_follow_news(const class channel &c, snowflake target_channel_id, command_completion_event_t callback = {}); + + /** + * @brief Trigger channel typing indicator + * + * @param c Channel to set as typing on + * @param callback Function to call when the API call completes. + */ + void channel_typing(const class channel &c, command_completion_event_t callback = {}); + + /** + * @brief Pin a message + * + * @param channel_id Channel id to pin message on + * @param message_id Message id to pin message on + * @param callback Function to call when the API call completes. + */ + void message_pin(snowflake channel_id, snowflake message_id, command_completion_event_t callback = {}); + + /** + * @brief Unpin a message + * + * @param channel_id Channel id to unpin message on + * @param message_id Message id to unpin message on + * @param callback Function to call when the API call completes. + */ + void message_unpin(snowflake channel_id, snowflake message_id, command_completion_event_t callback = {}); + + /** + * @brief Get a guild + * + * @param g Guild ID to retrieve + * @param callback Function to call when the API call completes. + */ + void guild_get(snowflake g, command_completion_event_t callback); + + /** + * @brief Get a guild preview. Returns a guild object but only a subset of the fields will be populated. + * + * @param g Guild ID to retrieve + * @param callback Function to call when the API call completes. + */ + void guild_get_preview(snowflake g, command_completion_event_t callback); + + /** + * @brief Get a guild member + * + * @param guild_id Guild ID to get member for + * @param user_id User ID of member to get + * @param callback Function to call when the API call completes. + */ + void guild_get_member(snowflake guild_id, snowflake user_id, command_completion_event_t callback); + + /** + * @brief Get all guild members + * + * @param guild_id Guild ID to get all members for + * @param callback Function to call when the API call completes. + */ + void guild_get_members(snowflake guild_id, command_completion_event_t callback); + + /** + * @brief Add guild member. Needs a specific oauth2 scope, from which you get the access_token. + * + * @param gm Guild member to add + * @param access_token Access token from Oauth2 scope + * @param callback Function to call when the API call completes. + */ + void guild_add_member(const guild_member& gm, const std::string &access_token, command_completion_event_t callback = {}); + + /** + * @brief Edit the properties of an existing guild member + * + * @param gm Guild member to edit + * @param callback Function to call when the API call completes. + */ + void guild_edit_member(const guild_member& gm, command_completion_event_t callback = {}); + + /** + * @brief Moves the guild member to a other voice channel, if member is connected to one + * @param channel_id Id of the channel to which the user is used + * @param guild_id Guild id to which the user is connected + * @param user_id User id, who should be moved + * @param callback Function to call when the API call completes. + */ + void guild_member_move(const snowflake channel_id, const snowflake guild_id, const snowflake user_id, command_completion_event_t callback = {}); + + /** + * @brief Change current user nickname + * + * @param guild_id Guild ID to change nickanem on + * @param nickname New nickname, or empty string to clear nickname + * @param callback Function to call when the API call completes. + */ + void guild_set_nickname(snowflake guild_id, const std::string &nickname, command_completion_event_t callback = {}); + + /** + * @brief Add role to guild member + * + * @param guild_id Guild ID to add a role to + * @param user_id User ID to add role to + * @param role_id Role ID to add to the user + * @param callback Function to call when the API call completes. + */ + void guild_member_add_role(snowflake guild_id, snowflake user_id, snowflake role_id, command_completion_event_t callback = {}); + + /** + * @brief Remove role from guild member + * + * @param guild_id Guild ID to remove role from user on + * @param user_id User ID to remove role from + * @param role_id Role to remove + * @param callback Function to call when the API call completes. + */ + void guild_member_delete_role(snowflake guild_id, snowflake user_id, snowflake role_id, command_completion_event_t callback = {}); + + /** + * @brief Remove (kick) a guild member + * + * @param guild_id Guild ID to kick member from + * @param user_id User ID to kick + * @param callback Function to call when the API call completes. + */ + void guild_member_delete(snowflake guild_id, snowflake user_id, command_completion_event_t callback = {}); + + /** + * @brief Add guild ban + * + * @param guild_id Guild ID to add ban to + * @param user_id User ID to ban + * @param delete_message_days How many days of ther user's messages to also delete + * @param reason Reason for ban + * @param callback Function to call when the API call completes. + */ + void guild_ban_add(snowflake guild_id, snowflake user_id, uint32_t delete_message_days, const std::string &reason, command_completion_event_t callback = {}); + + /** + * @brief Delete guild ban + * + * @param guild_id Guild to delete ban from + * @param user_id User ID to delete ban for + * @param callback Function to call when the API call completes. + */ + void guild_ban_delete(snowflake guild_id, snowflake user_id, command_completion_event_t callback = {}); + + /** + * @brief Get guild ban list + * + * @param guild_id Guild ID to get bans for + * @param callback Function to call when the API call completes. + */ + void guild_get_bans(snowflake guild_id, command_completion_event_t callback); + + /** + * @brief Get single guild ban + * + * @param guild_id Guild ID to get ban for + * @param user_id User ID of ban to retrieve + * @param callback Function to call when the API call completes. + */ + void guild_get_ban(snowflake guild_id, snowflake user_id, command_completion_event_t callback); + + /** + * @brief Get a template + * + * @param code Template code + * @param callback Function to call when the API call completes. + */ + void template_get(const std::string &code, command_completion_event_t callback); + + /** + * @brief Create a new guild based on a template. + * + * @param code Template code to create guild from + * @param name Guild name to create + * @param callback Function to call when the API call completes. + */ + void guild_create_from_template(const std::string &code, const std::string &name, command_completion_event_t callback = {}); + + /** + * @brief Get guild templates + * + * @param guild_id Guild ID to get templates for + * @param callback Function to call when the API call completes. + */ + void guild_templates_get(snowflake guild_id, command_completion_event_t callback); + + /** + * @brief Creates a template for the guild + * + * @param guild_id Guild to create template from + * @param name Template name to create + * @param description Description of template to create + * @param callback Function to call when the API call completes. + */ + void guild_template_create(snowflake guild_id, const std::string &name, const std::string &description, command_completion_event_t callback); + + /** + * @brief Syncs the template to the guild's current state. + * + * @param guild_id Guild to synchronise template for + * @param code Code of template to synchronise + * @param callback Function to call when the API call completes. + */ + void guild_template_sync(snowflake guild_id, const std::string &code, command_completion_event_t callback = {}); + + /** + * @brief Modifies the template's metadata. + * + * @param guild_id Guild ID of template to modify + * @param code Template code to modify + * @param name New name of template + * @param description New description of template + * @param callback Function to call when the API call completes. + */ + void guild_template_modify(snowflake guild_id, const std::string &code, const std::string &name, const std::string &description, command_completion_event_t callback = {}); + + /** + * @brief Deletes the template + * + * @param guild_id Guild ID of template to delete + * @param code Template code to delete + * @param callback Function to call when the API call completes. + */ + void guild_template_delete(snowflake guild_id, const std::string &code, command_completion_event_t callback = {}); + + /** + * @brief Create a guild + * + * @param g Guild to create + * @param callback Function to call when the API call completes. + */ + void guild_create(const class guild &g, command_completion_event_t callback = {}); + + /** + * @brief Edit a guild + * + * @param g Guild to edit + * @param callback Function to call when the API call completes. + */ + void guild_edit(const class guild &g, command_completion_event_t callback = {}); + + /** + * @brief Delete a guild + * + * @param guild_id Guild ID to delete + * @param callback Function to call when the API call completes. + */ + void guild_delete(snowflake guild_id, command_completion_event_t callback = {}); + + /** + * @brief Get all emojis for a guild + * + * @param guild_id Guild ID to get emojis for + * @param callback Function to call when the API call completes. + */ + void guild_emojis_get(snowflake guild_id, command_completion_event_t callback); + + /** + * @brief Get a single emoji + * + * @param guild_id Guild ID to get emoji for + * @param emoji_id Emoji ID to get + * @param callback Function to call when the API call completes. + */ + void guild_emoji_get(snowflake guild_id, snowflake emoji_id, command_completion_event_t callback); + + /** + * @brief Create single emoji. + * You must ensure that the emoji passed contained image data using the emoji::load_image() method. + * + * @param guild_id Guild ID to create emoji om + * @param newemoji Emoji to create + * @param callback Function to call when the API call completes. + */ + void guild_emoji_create(snowflake guild_id, const class emoji& newemoji, command_completion_event_t callback = {}); + + /** + * @brief Edit a single emoji. + * You must ensure that the emoji passed contained image data using the emoji::load_image() method. + * + * @param guild_id Guild ID to edit emoji on + * @param newemoji Emoji to edit + * @param callback Function to call when the API call completes. + */ + void guild_emoji_edit(snowflake guild_id, const class emoji& newemoji, command_completion_event_t callback = {}); + + /** + * @brief Delete a guild emoji + * + * @param guild_id Guild ID to delete emoji on + * @param emoji_id Emoji ID to delete + * @param callback Function to call when the API call completes. + */ + void guild_emoji_delete(snowflake guild_id, snowflake emoji_id, command_completion_event_t callback = {}); + + /** + * @brief Get prune counts + * + * @param guild_id Guild ID to count for pruning + * @param pruneinfo Pruning info + * @param callback Function to call when the API call completes. + */ + void guild_get_prune_counts(snowflake guild_id, const struct prune& pruneinfo, command_completion_event_t callback); + + /** + * @brief Begin guild prune + * + * @param guild_id Guild ID to prune + * @param pruneinfo Pruning info + * @param callback Function to call when the API call completes. + */ + void guild_begin_prune(snowflake guild_id, const struct prune& pruneinfo, command_completion_event_t callback = {}); + + /** + * @brief Get guild voice regions. + * Voice regions per guild are somewhat deprecated in preference of per-channel voice regions. + * + * @param guild_id Guild ID to get voice regions for + * @param callback Function to call when the API call completes. + */ + void guild_get_voice_regions(snowflake guild_id, command_completion_event_t callback); + + /** + * @brief Get guild invites + * + * @param guild_id Guild ID to get invites for + * @param callback Function to call when the API call completes. + */ + void get_guild_invites(snowflake guild_id, command_completion_event_t callback); + + /** + * @brief Get guild itegrations + * + * @param guild_id Guild ID to get integrations for + * @param callback Function to call when the API call completes. + */ + void guild_get_integrations(snowflake guild_id, command_completion_event_t callback); + + /** + * @brief Modify guild integration + * + * @param guild_id Guild ID to modify integration for + * @param i Integration to modify + * @param callback Function to call when the API call completes. + */ + void guild_modify_integration(snowflake guild_id, const class integration &i, command_completion_event_t callback = {}); + + /** + * @brief Delete guild integration + * + * @param guild_id Guild ID to delete integration for + * @param integration_id Integration ID to delete + * @param callback Function to call when the API call completes. + */ + void guild_delete_integration(snowflake guild_id, snowflake integration_id, command_completion_event_t callback = {}); + + /** + * @brief Sync guild integration + * + * @param guild_id Guild ID to sync integration on + * @param integration_id Integration ID to synchronise + * @param callback Function to call when the API call completes. + */ + void guild_sync_integration(snowflake guild_id, snowflake integration_id, command_completion_event_t callback = {}); + + /** + * @brief Get guild widget + * + * @param guild_id Guild ID to get widget for + * @param callback Function to call when the API call completes. + */ + void guild_get_widget(snowflake guild_id, command_completion_event_t callback); + + /** + * @brief Edit guild widget + * + * @param guild_id Guild ID to edit widget for + * @param gw New guild widget information + * @param callback Function to call when the API call completes. + */ + void guild_edit_widget(snowflake guild_id, const class guild_widget &gw, command_completion_event_t callback = {}); + + /** + * @brief Get guild vanity url, if enabled + * + * @param guild_id Guild to get vanity URL for + * @param callback Function to call when the API call completes. + */ + void guild_get_vanity(snowflake guild_id, command_completion_event_t callback); + + /** + * @brief Create a webhook + * + * @param w Webhook to create + * @param callback Function to call when the API call completes. + */ + void create_webhook(const class webhook &w, command_completion_event_t callback = {}); + + /** + * @brief Get guild webhooks + * + * @param guild_id Guild ID to get webhooks for + * @param callback Function to call when the API call completes. + */ + void get_guild_webhooks(snowflake guild_id, command_completion_event_t callback); + + /** + * @brief Get channel webhooks + * + * @param channel_id Channel ID to get webhooks for + * @param callback Function to call when the API call completes. + */ + void get_channel_webhooks(snowflake channel_id, command_completion_event_t callback); + + /** + * @brief Get webhook + * + * @param webhook_id Webhook ID to get + * @param callback Function to call when the API call completes. + */ + void get_webhook(snowflake webhook_id, command_completion_event_t callback); + + /** + * @brief Get webhook using token + * + * @param webhook_id Webhook ID to retrieve + * @param token Token of webhook + * @param callback Function to call when the API call completes. + */ + void get_webhook_with_token(snowflake webhook_id, const std::string &token, command_completion_event_t callback); + + /** + * @brief Edit webhook + * + * @param wh Webhook to edit + * @param callback Function to call when the API call completes. + */ + void edit_webhook(const class webhook& wh, command_completion_event_t callback = {}); + + /** + * @brief Edit webhook with token (token is encapsulated in the webhook object) + * + * @param wh Wehook to edit (should include token) + * @param callback Function to call when the API call completes. + */ + void edit_webhook_with_token(const class webhook& wh, command_completion_event_t callback = {}); + + /** + * @brief Delete a webhook + * + * @param webhook_id Webhook ID to delete + * @param callback Function to call when the API call completes. + */ + void delete_webhook(snowflake webhook_id, command_completion_event_t callback = {}); + + /** + * @brief Delete webhook with token + * + * @param webhook_id Webhook ID to delete + * @param token Token of webhook to delete + * @param callback Function to call when the API call completes. + */ + void delete_webhook_with_token(snowflake webhook_id, const std::string &token, command_completion_event_t callback = {}); + + /** + * @brief Execute webhook + * + * @param wh Webhook to execute + * @param m Message to send + * @param wait waits for server confirmation of message send before response, and returns the created message body + * @param thread_id Send a message to the specified thread within a webhook's channel. The thread will automatically be unarchived + * @param callback Function to call when the API call completes. + */ + void execute_webhook(const class webhook &wh, const struct message &m, bool wait = false, snowflake thread_id = 0, command_completion_event_t callback = {}); + + /** + * @brief Get webhook message + * + * @param Webhook to get the original message for + * @param callback Function to call when the API call completes. + */ + void get_webhook_message(const class webhook &wh, command_completion_event_t callback = {}); + + /** + * @brief Edit webhook message + * + * @param wh Webhook to edit message for + * @param m New message + * @param callback Function to call when the API call completes. + */ + void edit_webhook_message(const class webhook &wh, const struct message &m, command_completion_event_t callback = {}); + + /** + * @brief Delete webhook message + * + * @param wh Webhook to delete message for + * @param message_id Message ID to delete + * @param callback Function to call when the API call completes. + */ + void delete_webhook_message(const class webhook &wh, snowflake message_id, command_completion_event_t callback = {}); + + /** + * @brief Get a role for a guild + * + * @param guild_id Guild ID to get role for + * @param callback Function to call when the API call completes. + */ + void roles_get(snowflake guild_id, command_completion_event_t callback); + + /** + * @brief Create a role on a guild + * + * @param r Role to create (guild ID is encapsulated in the role object) + * @param callback Function to call when the API call completes. + */ + void role_create(const class role &r, command_completion_event_t callback = {}); + + /** + * @brief Edit a role on a guild + * + * @param r Role to edit + * @param callback Function to call when the API call completes. + */ + void role_edit(const class role &r, command_completion_event_t callback = {}); + + /** + * @brief Edit a role's position in a guild + * + * @param r Role to change position of + * @param callback Function to call when the API call completes. + */ + void role_edit_position(const class role &r, command_completion_event_t callback = {}); + + /** + * @brief Delete a role + * + * @param guild_id Guild ID to delete the role on + * @param role_id Role ID to delete + * @param callback Function to call when the API call completes. + */ + void role_delete(snowflake guild_id, snowflake role_id, command_completion_event_t callback = {}); + + /** + * @brief Get a user by id + * + * @param user_id User ID to retrieve + * @param callback Function to call when the API call completes. + */ + void user_get(snowflake user_id, command_completion_event_t callback); + + /** + * @brief Get current (bot) user + * + * @param callback Function to call when the API call completes. + */ + void current_user_get(command_completion_event_t callback); + + /** + * @brief Get current (bot) user guilds + * + * @param callback Function to call when the API call completes. + */ + void current_user_get_guilds(command_completion_event_t callback); + + /** + * @brief Edit current (bot) user + * + * @param nickname Nickname to set + * @param image_blob Avatar data to upload (NOTE: Very heavily rate limited!) + * @param type Type of image for avatar + * @param callback Function to call when the API call completes. + */ + void current_user_edit(const std::string &nickname, const std::string& image_blob, image_type type, command_completion_event_t callback = {}); + + /** + * @brief Get current user DM channels + * + * @param callback Function to call when the API call completes. + */ + void current_user_get_dms(command_completion_event_t callback); + + /** + * @brief Create a dm channel + * + * @param user_id User ID to create DM channel with + * @param callback Function to call when the API call completes. + */ + void create_dm_channel(snowflake user_id, command_completion_event_t callback = {}); + + /** + * @brief Leave a guild + * + * @param guild_id Guild ID to leave + * @param callback Function to call when the API call completes. + */ + void current_user_leave_guild(snowflake guild_id, command_completion_event_t callback = {}); + + /** + * @brief Create a thread + * + * @param thread_name Name of the thread + * @param channel_id Channel in which thread to create + * @param auto_archive_duration Duration after which thread auto-archives. Can be set to - 60, 1440 (for boosted guilds can also be: 4320, 10080) + * @param thread_type Type of thread - GUILD_PUBLIC_THREAD, GUILD_NEWS_THREAD, GUILD_PRIVATE_THREAD + * @param callback Function to call when the API call completes. + */ + void thread_create(const std::string& thread_name, snowflake channel_id, uint16_t auto_archive_duration, channel_type thread_type, command_completion_event_t callback = {}); + + /** + * @brief Create a thread with a message (Discord: ID of a thread is same as mesage ID) + * + * @param thread_name Name of the thread + * @param channel_id Channel in which thread to create + * @param message_id message to start thread with + * @param auto_archive_duration Duration after which thread auto-archives. Can be set to - 60, 1440 (for boosted guilds can also be: 4320, 10080) + * @param callback Function to call when the API call completes. + */ + void thread_create_with_message(const std::string& thread_name, snowflake channel_id, snowflake message_id, uint16_t auto_archive_duration, command_completion_event_t callback = {}); + + /** + * @brief Join a thread + * + * @param thread_id Thread ID to join + * @param callback Function to call when the API call completes. + */ + void current_user_join_thread(snowflake thread_id, command_completion_event_t callback = {}); + + /** + * @brief Leave a thread + * + * @param thread_id Thread ID to leave + * @param callback Function to call when the API call completes. + */ + void current_user_leave_thread(snowflake thread_id, command_completion_event_t callback = {}); + + /** + * @brief Add a member to a thread + * + * @param thread_id Thread ID to add to + * @param user_id Member ID to add + * @param callback Function to call when the API call completes. + */ + void thread_member_add(snowflake thread_id, snowflake user_id, command_completion_event_t callback = {}); + + /** + * @brief Remove a member from a thread + * + * @param thread_id Thread ID to remove from + * @param user_id Member ID to remove + * @param callback Function to call when the API call completes. + */ + void thread_member_remove(snowflake thread_id, snowflake user_id, command_completion_event_t callback = {}); + + /** + * @brief Get members of a thread + * + * @param thread_id Thread to get members for + */ + void get_thread_members(snowflake thread_id, command_completion_event_t callback = {}); + + /** + * @brief Get active threads in a channel (Sorted by ID in descending order) + * + * @param channel_id Channel to get active threads for + */ + void get_active_threads(snowflake channel_id, command_completion_event_t callback = {}); + + /** + * @brief Get public archived threads in a channel (Sorted by archive_timestamp in descending order) + * + * @param channel_id Channel to get public archived threads for + * @param before_timestamp Get threads before this timestamp + * @param limit Number of threads to get + */ + void get_public_archived_threads(snowflake channel_id, time_t before_timestamp = 0, uint16_t limit = 0, command_completion_event_t callback = {}); + + /** + * @brief Get private archived threads in a channel (Sorted by archive_timestamp in descending order) + * + * @param channel_id Channel to get public archived threads for + * @param before_timestamp Get threads before this timestamp + * @param limit Number of threads to get + */ + void get_private_archived_threads(snowflake channel_id, time_t before_timestamp = 0, uint16_t limit = 0, command_completion_event_t callback = {}); + + /** + * @brief Get private archived threads in a channel which current user has joined (Sorted by ID in descending order) + + * + * @param channel_id Channel to get public archived threads for + * @param before_id Get threads before this id + * @param limit Number of threads to get + */ + void get_joined_private_archived_threads(snowflake channel_id, snowflake before_id = 0, uint16_t limit = 0, command_completion_event_t callback = {}); + + /** + * @brief Create a sticker in a guild + * + * @param s Sticker to create. Must have its guild ID set. + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::sticker object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_sticker_create(sticker &s, command_completion_event_t callback = {}); + + /** + * @brief Modify a sticker in a guild + * + * @param s Sticker to modify. Must have its guild ID and sticker ID set. + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::sticker object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_sticker_modify(sticker &s, command_completion_event_t callback = {}); + + /** + * @brief Delete a sticker from a guild + * + * @param sticker_id sticker ID to delete + * @param guild_id guild ID to delete from + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::sticker object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_sticker_delete(snowflake sticker_id, snowflake guild_id, command_completion_event_t callback = {}); + + /** + * @brief Get a nitro sticker + * + * @param id Id of sticker to get. + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::sticker object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void nitro_sticker_get(snowflake id, command_completion_event_t callback); + + /** + * @brief Get a guild sticker + * + * @param id Id of sticker to get. + * @param guild_id Guild ID of the guild where the sticker is + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::sticker object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_sticker_get(snowflake id, snowflake guild_id, command_completion_event_t callback); + + /** + * @brief Get all guild stickers + * + * @param guild_id Guild ID of the guild where the sticker is + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::sticker object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_stickers_get(snowflake guild_id, command_completion_event_t callback); + + /** + * @brief Get sticker packs + * + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::sticker object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void sticker_packs_get(command_completion_event_t callback); + + /** + * @brief Get all voice regions + * + * @param callback Function to call when the API call completes. + */ + void get_voice_regions(command_completion_event_t callback); + + /** + * @brief Get the gateway information for the bot using the token + * + * @param callback Function to call when the API call completes. + */ + void get_gateway_bot(command_completion_event_t callback); + + +}; + +}; diff --git a/vendor/DPP/include/dpp/commandhandler.h b/vendor/DPP/include/dpp/commandhandler.h new file mode 100644 index 00000000..b7aea158 --- /dev/null +++ b/vendor/DPP/include/dpp/commandhandler.h @@ -0,0 +1,285 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ + +#pragma once +#include +#include +#include +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief Represents a received parameter. + * We use variant so that multiple non-related types can be contained within. + */ +typedef std::variant command_parameter; + +/** + * @brief Parameter types when registering a command. + * We don't pass these in when triggering the command in the handler, because it is + * expected the developer added the command so they know what types to expect for each named + * parameter. + */ +enum parameter_type { + pt_string, //!< String value + pt_role, //!< Role object + pt_channel, //!< Channel object + pt_user, //!< User object + pt_integer, //!< 32 bit signed integer + pt_boolean //!< boolean +}; + +/** + * @brief Details of a command parameter used in registration. + * Note that for non-slash commands optional parameters can only be at the end of + * the list of parameters. + */ +struct CoreExport param_info { + + /** + * @brief Type of parameter + */ + parameter_type type; + + /** + * @brief True if the parameter is optional. + * For non-slash commands optional parameters may only be on the end of the list. + */ + bool optional; + + /** + * @brief Description of command. Displayed only for slash commands + */ + std::string description; + + /** + * @brief Allowed multiple choice options. + * The key name is the string passed to the command handler + * and the key value is its description displayed to the user. + */ + std::map choices; + + /** + * @brief Construct a new param_info object + * + * @param t Type of parameter + * @param o True if parameter is optional + * @param description The parameter description + * @param opts The options for a multiple choice parameter + */ + param_info(parameter_type t, bool o, const std::string &description, const std::map &opts = {}); +}; + +/** + * @brief Parameter list used during registration. + * Note that use of vector/pair is important here to preserve parameter order, + * as opposed to unordered_map (which doesnt guarantee any order at all) and + * std::map, which reorders keys alphabetically. + */ +typedef std::vector> parameter_registration_t; + +/** + * @brief Parameter list for a called command. + * See dpp::parameter_registration_t for an explaination as to why vector is used. + */ +typedef std::vector> parameter_list_t; + +/** + * @brief Represents the sending source of a command. + * This is passed to any command handler and should be passed back to + * commandhandler::reply(), allowing the reply method to route any replies back + * to the origin, which may be a slash command or a message. Both require different + * response facilities but we want this to be transparent if you use the command + * handler class. + */ +struct CoreExport command_source { + /** + * @brief Sending guild id + */ + snowflake guild_id = 0; + /** + * @brief Source channel id + */ + snowflake channel_id = 0; + /** + * @brief Command ID of a slash command + */ + snowflake command_id = 0; + /** + * @brief Token for sending a slash command reply + */ + std::string command_token; + /** + * @brief The user who issued the command + */ + user* issuer; +}; + +/** + * @brief The function definition for a command handler. Expects a command name string, + * and a list of command parameters. + */ +typedef std::function command_handler; + +/** + * @brief Represents the details of a command added to the command handler class. + */ +struct CoreExport command_info_t { + /** + * @brief Function reference for the handler. This is std::function so it can represent + * a class member, a lambda or a raw C function pointer. + */ + command_handler func; + /** + * @brief Parameters requested for the command, with their types + */ + parameter_registration_t parameters; + /** + * @brief Guild ID the command exists on, or 0 to be present on all guilds + */ + snowflake guild_id; +}; + + +/** + * @brief The commandhandler class represents a group of commands, prefixed or slash commands with handling functions. + * + */ +class CoreExport commandhandler { + /** + * @brief Commands in the handler + */ + std::unordered_map commands; + + /** + * @brief Valid prefixes + */ + std::vector prefixes; + + /** + * @brief Set to true automatically if one of the prefixes added is "/" + */ + bool slash_commands_enabled; + + /** + * @brief Cluster we are attached to for issuing REST calls + */ + class cluster* owner; + + /** + * @brief Application ID + */ + snowflake app_id; + + /** + * @brief Returns true if the string has a known prefix on the start. + * Modifies string to remove prefix if it returns true. + * + * @param str String to check and modify + * @return true string contained a prefix, prefix removed from string + * @return false string did not contain a prefix + */ + bool string_has_prefix(std::string &str); + +public: + + /** + * @brief Construct a new commandhandler object + * + * @param o Owning cluster to attach to + * @param auto_hook_events Set to true to automatically hook the on_interaction_create + * and on_message events. Only do this if you have no other use for these events than + * commands that are handled by the command handler (this is usually the case). + * @param application_id The application id of the bot. If not specified, the class will + * look within the cluster object and use cluster::me::id instead. + */ + commandhandler(class cluster* o, bool auto_hook_events = true, snowflake application_id = 0); + + /** + * @brief Destroy the commandhandler object + */ + ~commandhandler(); + + /** + * @brief Set the application id after construction + * + * @param o Owning cluster to attach to + */ + commandhandler& set_owner(class cluster* o); + + /** + * @brief Add a prefix to the command handler + * + * @param prefix Prefix to be handled by the command handler + * @return commandhandler& reference to self + */ + commandhandler& add_prefix(const std::string &prefix); + + /** + * @brief Add a command to the command handler + * + * @param command Command to be handled. + * Note that if any one of your prefixes is "/" this will attempt to register + * a global command using the API and you will receive notification of this command + * via an interaction event. + * + * @param handler Handler function + * @param parameters Parameters to use for the command + * @return commandhandler& reference to self + */ + commandhandler& add_command(const std::string &command, const parameter_registration_t ¶meters, command_handler handler, const std::string &description = "", snowflake guild_id = 0); + + /** + * @brief Route a command from the on_message_create function. + * Call this method from within your on_message_create with the received + * dpp::message object. + * + * @param msg message to parse + */ + void route(const class dpp::message& msg); + + /** + * @brief Route a command from the on_interaction_create function. + * Call this method from your on_interaction_create with the received + * dpp::interaction_create_t object. + * + * @param event command interaction event to parse + */ + void route(const class interaction_create_t & event); + + /** + * @brief Reply to a command. + * You should use this method rather than cluster::message_create as + * the way you reply varies between slash commands and message commands. + * Note you should ALWAYS reply. Slash commands will emit an ugly error + * to the user if you do not emit some form of reply within 3 seconds. + * + * @param m message to reply with. + * @param interaction true if the reply is generated by an interaction + */ + void reply(const dpp::message &m, command_source source); +}; + +}; \ No newline at end of file diff --git a/vendor/DPP/include/dpp/discord.h b/vendor/DPP/include/dpp/discord.h new file mode 100644 index 00000000..d5571404 --- /dev/null +++ b/vendor/DPP/include/dpp/discord.h @@ -0,0 +1,283 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include +#include +#include + +/** + * @brief The main namespace for D++ functions. classes and types + */ +namespace dpp { + /** @brief A 64 bit unsigned value representing many things on discord. + * Discord calls the value a 'snowflake' value. + */ + typedef uint64_t snowflake; + + /** @brief The managed class is the base class for various types that can + * be stored in a cache that are identified by a dpp::snowflake id + */ + class CoreExport managed { + public: + /** Unique ID of object */ + snowflake id; + /** Constructor, initialises id to 0 */ + managed(const snowflake = 0); + /** Default destructor */ + virtual ~managed() = default; + }; + + /** @brief Supported image types for profile pictures */ + enum image_type { + /// image/png + i_png, + /// image/jpeg + i_jpg, + /// image/gif + i_gif + }; + + /** @brief Log levels */ + enum loglevel { + /// Trace + ll_trace = 0, + /// Debug + ll_debug, + /// Information + ll_info, + /// Warning + ll_warning, + /// Error + ll_error, + /// Critical + ll_critical + }; + + /** @brief Utility helper functions, generally for logging */ + namespace utility { + + typedef std::function cmd_result_t; + + /** + * @brief Run a commandline program asyncronously. The command line program + * is spawned in a separate std::thread, and when complete, its output from + * stdout is passed to the callback function in its string prameter. For eample + * ``` + * dpp::utility::exec("ls", [](const std::string& output) { + * std::cout << "Output of 'ls': " << output << "\n"; + * }); + * ``` + * + * @param cmd The command to run. + * @param parameters Command line parameters. Each will be escaped using std::quoted. + * @param callback The callback to call on completion. + */ + void CoreExport exec(const std::string& cmd, std::vector parameters = {}, cmd_result_t callback = {}); + + /** + * @brief Returns urrent date and time + * + * @return std::string Current date and time + */ + std::string CoreExport current_date_time(); + /** + * @brief Convert a dpp::loglevel enum value to a string + * + * @param in log level to convert + * @return std::string string form of log level + */ + std::string CoreExport loglevel(dpp::loglevel in); + + /** + * @brief Store a 128 bit icon hash (profile picture, server icon etc) + * as a 128 bit binary value made of two uint64_t. + * Has a constructor to build one from a string, and a method to fetch + * the value back in string form. + */ + struct CoreExport iconhash { + + uint64_t first; //!< High 64 bits + uint64_t second; //!< Low 64 bits + + /** + * @brief Construct a new iconcash object + */ + iconhash(); + + /** + * @brief Construct a new iconhash object + * + * @param hash String hash to construct from. + * Must contain a 32 character hex string. + * + * @throws std::length_error if the provided + * string is not exactly 32 characters long. + */ + iconhash(const std::string &hash); + + /** + * @brief Assign from std::string + * + * @param assignment string to assign from. + * + * @throws std::length_error if the provided + * string is not exactly 32 characters long. + */ + iconhash& operator=(const std::string &assignment); + + /** + * @brief Change value of iconhash object + * + * @param hash String hash to change to. + * Must contain a 32 character hex string. + * + * @throws std::length_error if the provided + * string is not exactly 32 characters long. + */ + void set(const std::string &hash); + + /** + * @brief Convert iconhash back to 32 character + * string value. + * + * @return std::string Hash value + */ + std::string to_string() const; + }; + + /** + * @brief Return the current time with fractions of seconds. + * This is a unix epoch time with the fractional seconds part + * after the decimal place. + * + * @return double time with fractional seconds + */ + double CoreExport time_f(); + + /** + * @brief Returns true if D++ was built with voice support + * + * @return bool True if voice support is compiled in (libsodium/libopus) + */ + bool CoreExport has_voice(); + + /** + * @brief Convert a byte count to display value + * + * @param c number of bytes + * @return std::string display value suffixed with M, G, T where neccessary + */ + std::string CoreExport bytes(uint64_t c); + + /** + * @brief A class used to represent an uptime in hours, minutes, + * seconds and days, with helper functions to convert from time_t + * and display as a string. + */ + struct CoreExport uptime { + uint16_t days; //!< Number of days + uint8_t hours; //!< Number of hours + uint8_t mins; //!< Number of minutes + uint8_t secs; //!< Number of seconds + + /** + * @brief Construct a new uptime object + */ + uptime(); + + /** + * @brief Construct a new uptime object + * + * @param diff A time_t to initialise the object from + */ + uptime(time_t diff); + + /** + * @brief Get uptime as string + * + * @return std::string Uptime as string + */ + std::string to_string(); + + /** + * @brief Get uptime as seconds + * + * @return uint64_t Uptime as seconds + */ + uint64_t to_secs(); + + /** + * @brief Get uptime as milliseconds + * + * @return uint64_t Uptime as milliseconds + */ + uint64_t to_msecs(); + }; + + /** + * @brief Output hex values of a section of memory for debugging + * + * @param data The start of the data to display + * @param length The length of data to display + */ + void CoreExport debug_dump(uint8_t* data, size_t length); + + /** + * @brief Returns the length of a UTF-8 string in codepoints + * + * @param str string to count length of + * @return size_t length of string (0 for invalid utf8) + */ + size_t CoreExport utf8len(const std::string &str); + + /** + * @brief Return substring of a UTF-8 encoded string in codepoints + * + * @param str string to return substring from + * @param start start codepoint offset + * @param length length in codepoints + * @return std::string Substring in UTF-8 or emtpy string if invalid UTF-8 passed in + */ + std::string CoreExport utf8substr(const std::string& str, std::string::size_type start, std::string::size_type length); + }; + +}; + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include diff --git a/vendor/DPP/include/dpp/discordclient.h b/vendor/DPP/include/dpp/discordclient.h new file mode 100644 index 00000000..c2488c94 --- /dev/null +++ b/vendor/DPP/include/dpp/discordclient.h @@ -0,0 +1,358 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ + +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +#define DISCORD_API_VERSION "9" +#define DEFAULT_GATEWAY "gateway.discord.gg" +#define API_PATH "/api/v" DISCORD_API_VERSION +namespace dpp { + +// Forward declarations +class cluster; + +/** This is an opaque class containing zlib library specific structures. + * We define it this way so that the public facing D++ library doesnt require + * the zlib headers be available to build against it. + */ +class zlibcontext; + +/** + * @brief Represents a connection to a voice channel. + * A client can only connect to one voice channel per guild at a time, so these are stored in a map + * in the dpp::discord_client keyed by guild_id. + */ +class CoreExport voiceconn { + /** + * @brief Owning dpp::discord_client instance + */ + class discord_client* creator; +public: + /** + * @brief Voice Channel ID + */ + snowflake channel_id; + + /** + * @brief Websocket hostname for status + */ + std::string websocket_hostname; + + /** + * @brief Voice Voice session ID + */ + std::string session_id; + + /** + * @brief Voice websocket token + */ + std::string token; + + /** + * @brief voice websocket client + */ + class discord_voice_client* voiceclient; + + /** + * @brief Construct a new voiceconn object + */ + voiceconn() = default; + + /** + * @brief Construct a new voiceconn object + * + * @param o owner + * @param _channel_id voice channel id + */ + voiceconn(class discord_client* o, snowflake _channel_id); + + /** + * @brief Destroy the voiceconn object + */ + ~voiceconn(); + + /** + * @brief return true if the connection is ready to connect + * (has hostname, token and session id) + * + * @return true if ready to connect + */ + bool is_ready(); + + /** + * @brief return true if the connection is active (websocket exists) + * + * @return true if has an active websocket + */ + bool is_active(); + + /** + * @brief Create websocket object and connect it. + * Needs hosname, token and session_id to be set or does nothing. + * + * @param guild_id Guild to connect to the voice channel on + */ + void connect(snowflake guild_id); + + /** + * @brief Disconnect from the currently connected voice channel + */ + void disconnect(); +}; + +/** @brief Implements a discord client. Each discord_client connects to one shard and derives from a websocket client. */ +class CoreExport discord_client : public websocket_client +{ + /** Mutex for message queue */ + std::mutex queue_mutex; + + /** Queue of outbound messages */ + std::deque message_queue; + + /** Thread this shard is executing on */ + std::thread* runner; + + /** Run shard loop under a thread */ + void ThreadRun(); + + /** If true, stream compression is enabled */ + bool compressed; + + /** ZLib decompression buffer */ + unsigned char* decomp_buffer; + + /** Decompressed string */ + std::string decompressed; + + /** Frame decompression stream */ + zlibcontext* zlib; + + /** Total decompressed received bytes */ + uint64_t decompressed_total; + + /** Last connect time of cluster */ + time_t connect_time; + + /** Time last ping sent to websocket */ + double ping_start; + + /** + * @brief Initialise ZLib + */ + void SetupZLib(); + + /** + * @brief Shut down ZLib + */ + void EndZLib(); + +public: + /** Owning cluster */ + class dpp::cluster* creator; + + /** Heartbeat interval for sending heartbeat keepalive */ + uint32_t heartbeat_interval; + + /** Last heartbeat */ + time_t last_heartbeat; + + /** Shard ID of this client */ + uint32_t shard_id; + + /** Total number of shards */ + uint32_t max_shards; + + /** Thread ID */ + std::thread::native_handle_type thread_id; + + /** Last sequence number received, for resumes and pings */ + uint64_t last_seq; + + /** Discord bot token */ + std::string token; + + /** Privileged gateway intents */ + uint32_t intents; + + /** Discord session id */ + std::string sessionid; + + /** Mutex for voice connections map */ + std::mutex voice_mutex; + + /** Resume count */ + uint32_t resumes; + + /** Reconnection count */ + uint32_t reconnects; + + /** Websocket latency in fractional seconds */ + double websocket_ping; + + /** True if READY or RESUMED has been received */ + bool ready; + + /** Last heartbeat ACK (opcode 11) */ + time_t last_heartbeat_ack; + + /** List of voice channels we are connecting to keyed by guild id */ + std::unordered_map connecting_voice_channels; + + /** Log a message to whatever log the user is using. + * The logged message is passed up the chain to the on_log event in user code which can then do whatever + * it wants to do with it. + * @param severity The log level from dpp::loglevel + * @param msg The log message to output + */ + virtual void log(dpp::loglevel severity, const std::string &msg) const; + + /** Handle an event (opcode 0) + * @param event Event name, e.g. MESSAGE_CREATE + * @param j JSON object for the event content + * @param raw Raw JSON event string + */ + virtual void HandleEvent(const std::string &event, json &j, const std::string &raw); + + /** + * @brief Get the Guild Count for this shard + * + * @return uint64_t guild count + */ + uint64_t get_guild_count(); + + /** + * @brief Get the Member Count for this shard + * + * @return uint64_t member count + */ + uint64_t get_member_count(); + + /** + * @brief Get the Channel Count for this shard + * + * @return uint64_t channel count + */ + uint64_t get_channel_count(); + + /** Fires every second from the underlying socket I/O loop, used for sending heartbeats */ + virtual void one_second_timer(); + + /** + * @brief Queue a message to be sent via the websocket + * + * @param j The JSON data of the message to be sent + * @param to_front If set to true, will place the message at the front of the queue not the back + * (this is for urgent messages such as heartbeat, presence, so they can take precedence over + * chunk requests etc) + */ + void QueueMessage(const std::string &j, bool to_front = false); + + /** + * @brief Clear the outbound message queue + * + */ + void ClearQueue(); + + /** + * @brief Get the size of the outbound message queue + * + * @return The size of the queue + */ + size_t GetQueueSize(); + + /** + * @brief Returns true if the shard is connected + * + * @return True if connected + */ + bool is_connected(); + + /** + * @brief Returns the connection time of the shard + * + * @return dpp::utility::uptime Detail of how long the shard has been connected for + */ + dpp::utility::uptime get_uptime(); + + /** Constructor takes shard id, max shards and token. + * @param _cluster The owning cluster for this shard + * @param _shard_id The ID of the shard to start + * @param _max_shards The total number of shards across all clusters + * @param _token The bot token to use for identifying to the websocket + * @param intents Privileged intents to use, a bitmask of values from dpp::intents + * @param compressed True if the received data will be gzip compressed + */ + discord_client(dpp::cluster* _cluster, uint32_t _shard_id, uint32_t _max_shards, const std::string &_token, uint32_t intents = 0, bool compressed = true); + + /** Destructor */ + virtual ~discord_client(); + + /** Get decompressed total bytes received */ + uint64_t get_decompressed_bytes_in(); + + /** Handle JSON from the websocket. + * @param buffer The entire buffer content from the websocket client + * @returns True if a frame has been handled + */ + virtual bool HandleFrame(const std::string &buffer); + + /** Handle a websocket error. + * @param errorcode The error returned from the websocket + */ + virtual void Error(uint32_t errorcode); + + /** Start and monitor I/O loop */ + void Run(); + + /** + * @brief Connect to a voice channel + * + * @param guild_id Guild where the voice channel is + * @param channel_id Channel ID of the voice channel + */ + void connect_voice(snowflake guild_id, snowflake channel_id); + + /** + * @brief Disconnect from the connected voice channel on a guild + * + * @param guild_id The guild who's voice channel you wish to disconnect from + */ + void disconnect_voice(snowflake guild_id); + + voiceconn* get_voice(snowflake guild_id); +}; + +}; diff --git a/vendor/DPP/include/dpp/discordevents.h b/vendor/DPP/include/dpp/discordevents.h new file mode 100644 index 00000000..74838d5b --- /dev/null +++ b/vendor/DPP/include/dpp/discordevents.h @@ -0,0 +1,148 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once + +#include + +namespace dpp { + +/** @brief Returns a snowflake id from a json field value, if defined, else returns 0 + * @param j nlohmann::json instance to retrieve value from + * @param keyname key name to check for a value + * @return found value + */ +uint64_t SnowflakeNotNull(const nlohmann::json* j, const char *keyname); + +/** @brief Sets a snowflake id from a json field value, if defined, else does nothing + * @param j nlohmann::json instance to retrieve value from + * @param keyname key name to check for a value + * @param v Value to change + */ +void SetSnowflakeNotNull(const nlohmann::json* j, const char *keyname, uint64_t &v); + +/** @brief Returns a string from a json field value, if defined, else returns an empty string. + * @param j nlohmann::json instance to retrieve value from + * @param keyname key name to check for a value + * @return found value + */ +std::string StringNotNull(const nlohmann::json* j, const char *keyname); + +/** @brief Sets a string from a json field value, if defined, else does nothing + * @param j nlohmann::json instance to retrieve value from + * @param keyname key name to check for a value + * @param v Value to change + */ +void SetStringNotNull(const nlohmann::json* j, const char *keyname, std::string &v); + +/** @brief Returns a 64 bit unsigned integer from a json field value, if defined, else returns 0. + * DO NOT use this for snowflakes, as usually snowflakes are wrapped in a string! + * @param j nlohmann::json instance to retrieve value from + * @param keyname key name to check for a value + * @return found value + */ +uint64_t Int64NotNull(const nlohmann::json* j, const char *keyname); + +/** @brief Sets an unsigned 64 bit integer from a json field value, if defined, else does nothing + * @param j nlohmann::json instance to retrieve value from + * @param keyname key name to check for a value + * @param v Value to change + */ +void SetInt64NotNull(const nlohmann::json* j, const char *keyname, uint64_t &v); + +/** @brief Returns a 32 bit unsigned integer from a json field value, if defined, else returns 0 + * @param j nlohmann::json instance to retrieve value from + * @param keyname key name to check for a value + * @return found value + */ +uint32_t Int32NotNull(const nlohmann::json* j, const char *keyname); + +/** @brief Sets an unsigned 32 bit integer from a json field value, if defined, else does nothing + * @param j nlohmann::json instance to retrieve value from + * @param keyname key name to check for a value + * @param v Value to change + */ +void SetInt32NotNull(const nlohmann::json* j, const char *keyname, uint32_t &v); + +/** @brief Returns a 16 bit unsigned integer from a json field value, if defined, else returns 0 + * @param j nlohmann::json instance to retrieve value from + * @param keyname key name to check for a value + * @return found value + */ +uint16_t Int16NotNull(const nlohmann::json* j, const char *keyname); + +/** @brief Sets an unsigned 16 bit integer from a json field value, if defined, else does nothing + * @param j nlohmann::json instance to retrieve value from + * @param keyname key name to check for a value + * @param v Value to change + */ +void SetInt16NotNull(const nlohmann::json* j, const char *keyname, uint16_t &v); + +/** @brief Returns an 8 bit unsigned integer from a json field value, if defined, else returns 0 + * @param j nlohmann::json instance to retrieve value from + * @param keyname key name to check for a value + * @return found value + */ +uint8_t Int8NotNull(const nlohmann::json* j, const char *keyname); + +/** @brief Sets an unsigned 8 bit integer from a json field value, if defined, else does nothing + * @param j nlohmann::json instance to retrieve value from + * @param keyname key name to check for a value + * @param v Value to change + */ +void SetInt8NotNull(const nlohmann::json* j, const char *keyname, uint8_t &v); + +/** @brief Returns a boolean value from a json field value, if defined, else returns false + * @param j nlohmann::json instance to retrieve value from + * @param keyname key name to check for a value + * @return found value + */ +bool BoolNotNull(const nlohmann::json* j, const char *keyname); + +/** @brief Sets a boolean from a json field value, if defined, else does nothing + * @param j nlohmann::json instance to retrieve value from + * @param keyname key name to check for a value + * @param v Value to change + */ +void SetBoolNotNull(const nlohmann::json* j, const char *keyname, bool &v); + +/** @brief Returns a time_t from an ISO8601 timestamp field in a json value, if defined, else returns + * epoch value of 0. + * @param j nlohmann::json instance to retrieve value from + * @param keyname key name to check for a value + * @return found value + */ +time_t TimestampNotNull(const nlohmann::json* j, const char *keyname); + +/** @brief Sets an timestamp from a json field value containing an ISO8601 string, if defined, else does nothing + * @param j nlohmann::json instance to retrieve value from + * @param keyname key name to check for a value + * @param v Value to change + */ +void SetTimestampNotNull(const nlohmann::json* j, const char *keyname, time_t &v); + +/** @brief Base64 encode data into a string. + * @param buf Raw binary buffer + * @param buffer_length Buffer length to encode + * @return The base64 encoded string + */ +std::string base64_encode(unsigned char const* buf, unsigned int buffer_length); + +}; diff --git a/vendor/DPP/include/dpp/discordvoiceclient.h b/vendor/DPP/include/dpp/discordvoiceclient.h new file mode 100644 index 00000000..5ab56a47 --- /dev/null +++ b/vendor/DPP/include/dpp/discordvoiceclient.h @@ -0,0 +1,513 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once + +#include + +#include + +#ifdef _WIN32 +#include +#include +#include +#else +#include +#include +#include +#include +#include +#include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef HAVE_VOICE +#include +#include +#endif + + +using json = nlohmann::json; + +namespace dpp { + +// Forward declaration +class cluster; + +#define AUDIO_TRACK_MARKER (uint16_t)0xFFFF + +/** @brief Implements a discord voice connection. + * Each discord_voice_client connects to one voice channel and derives from a websocket client. + */ +class CoreExport discord_voice_client : public websocket_client +{ + /** Mutex for outbound packet stream */ + std::mutex stream_mutex; + + /** Mutex for message queue */ + std::mutex queue_mutex; + + /** Queue of outbound messages */ + std::deque message_queue; + + /** Thread this connection is executing on */ + std::thread* runner; + + /** Run shard loop under a thread */ + void ThreadRun(); + + /** Last connect time of voice session */ + time_t connect_time; + + /** + * @brief IP of UDP/RTP endpoint + */ + std::string ip; + + /** + * @brief Port number of UDP/RTP endpoint + */ + uint16_t port; + + /** + * @brief SSRC value + */ + uint64_t ssrc; + + /** + * @brief List of supported audio encoding modes + */ + std::vector modes; + + /** Output buffer. Each string is a UDP packet. + * Generally these will be RTP. + */ + std::vector outbuf; + + /** Input buffer. Each string is a received UDP + * packet. These will usually be RTP. + */ + std::vector inbuf; + + /** If true, audio packet sending is paused + */ + bool paused; + +#ifdef HAVE_VOICE + /** libopus encoder + */ + OpusEncoder* encoder; + + /** libopus decoder + */ + OpusDecoder* decoder; + + /** libopus repacketizer + * (merges frames into one packet) + */ + OpusRepacketizer* repacketizer; +#endif + + /** File descriptor for UDP connection + */ + SOCKET fd; + + /** Socket address of voice server + */ + struct sockaddr_in servaddr; + + /** Secret key for encrypting voice. + * If it has been sent, this is non-null and points to a + * sequence of exactly 32 bytes. + */ + uint8_t* secret_key; + + /** Sequence number of outbound audio. This is incremented + * once per frame sent. + */ + uint16_t sequence; + + /** Timestamp value used in outbound audio. Each packet + * has the timestamp value which is incremented to match + * how many frames are sent. + */ + uint32_t timestamp; + + /** This is set to true if we have started sending audio. + * When this moves from false to true, this causes the + * client to send the 'talking' notification to the websocket. + */ + bool sending; + + /** Number of track markers in the buffer. For example if there + * are two track markers in the buffer there are 3 tracks. + * Special case: + * If the buffer is empty, there are zero tracks in the + * buffer. + */ + uint32_t tracks; + + /** Meta data associated with each track. + * Arbitrary string that the user can set via + * dpp::discord_voice_client::AddMarker + */ + std::vector track_meta; + + /** Encoding buffer for opus repacketizer and encode + */ + uint8_t encode_buffer[65536]; + + /** + * @brief Send data to UDP socket immediately. + * + * @param data data to send + * @param length length of data to send + * @return int bytes sent. Will return -1 if we cannot send + */ + int UDPSend(const char* data, size_t length); + + /** + * @brief Receieve data from UDP socket immediately. + * + * @param data data to receive + * @param max_length size of data receiving buffer + * @return int bytes received. -1 if there is an error + * (e.g. EAGAIN) + */ + int UDPRecv(char* data, size_t max_length); + + /** + * @brief This hooks the ssl_client, returning the file + * descriptor if we want to send buffered data, or + * -1 if there is nothing to send + * + * @return int file descriptor or -1 + */ + int WantWrite(); + + /** + * @brief This hooks the ssl_client, returning the file + * descriptor if we want to receive buffered data, or + * -1 if we are not wanting to receive + * + * @return int file descriptor or -1 + */ + int WantRead(); + + /** + * @brief Called by ssl_client when the socket is ready + * for writing, at this point we pick the head item off + * the buffer and send it. So long as it doesnt error + * completely, we pop it off the head of the queue. + */ + void WriteReady(); + + /** + * @brief Called by ssl_client when there is data to be + * read. At this point we insert that data into the + * input queue. + */ + void ReadReady(); + + /** + * @brief Send data to the UDP socket, using the buffer. + * + * @param packet packet data + * @param len length of packet + */ + void Send(const char* packet, size_t len); + + /** + * @brief Queue a message to be sent via the websocket + * + * @param j The JSON data of the message to be sent + * @param to_front If set to true, will place the message at the front of the queue not the back + * (this is for urgent messages such as heartbeat, presence, so they can take precedence over + * chunk requests etc) + */ + void QueueMessage(const std::string &j, bool to_front = false); + + /** + * @brief Clear the outbound message queue + * + */ + void ClearQueue(); + + /** + * @brief Get the size of the outbound message queue + * + * @return The size of the queue + */ + size_t GetQueueSize(); + + /** + * @brief Encode a byte buffer using opus codec. + * Multiple opus frames (2880 bytes each) will be encoded into one packet for sending. + * + * @param input Input data as raw bytes of PCM data + * @param inDataSize Input data length + * @param output Output data as an opus encoded packet + * @param outDataSize Output data length, should be at least equal to the input size. + * Will be adjusted on return to the actual compressed data size. + * @return size_t The compressed data size that was encoded. + */ + size_t encode(uint8_t *input, size_t inDataSize, uint8_t *output, size_t &outDataSize); + +public: + + /** Owning cluster */ + class dpp::cluster* creator; + + /* This needs to be static, we only initialise libsodium once per program start, + * so initialising it on first use in a voice connection is best. + */ + static bool sodium_initialised; + + /** True when the thread is shutting down */ + bool terminating; + + /** Heartbeat interval for sending heartbeat keepalive */ + uint32_t heartbeat_interval; + + /** Last heartbeat */ + time_t last_heartbeat; + + /** Thread ID */ + std::thread::native_handle_type thread_id; + + /** Discord voice session token */ + std::string token; + + /** Discord voice session id */ + std::string sessionid; + + /** Server ID */ + snowflake server_id; + + /** Channel ID */ + snowflake channel_id; + + /** Log a message to whatever log the user is using. + * The logged message is passed up the chain to the on_log event in user code which can then do whatever + * it wants to do with it. + * @param severity The log level from dpp::loglevel + * @param msg The log message to output + */ + virtual void log(dpp::loglevel severity, const std::string &msg); + + /** Fires every second from the underlying socket I/O loop, used for sending heartbeats */ + virtual void one_second_timer(); + + /** + * @brief voice client is ready to stream audio. + * The voice client is considered ready if it has a secret key. + * + * @return true if ready to stream audio + */ + bool is_ready(); + + /** + * @brief Returns true if the voice client is connected to the websocket + * + * @return True if connected + */ + bool is_connected(); + + /** + * @brief Returns the connection time of the voice client + * + * @return dpp::utility::uptime Detail of how long the voice client has been connected for + */ + dpp::utility::uptime get_uptime(); + + /** Constructor takes shard id, max shards and token. + * @param _cluster The owning cluster for this shard + * @param _server_id The server id to identify voice connection as + * @param _token The voice session token to use for identifying to the websocket + * @param _session_id The voice session id to identify with + * @param _host The voice server hostname to connect to (hostname:port format) + */ + discord_voice_client(dpp::cluster* _cluster, snowflake _channel_id, snowflake _server_id, const std::string &_token, const std::string &_session_id, const std::string &_host); + + /** Destructor */ + virtual ~discord_voice_client(); + + /** Handle JSON from the websocket. + * @param buffer The entire buffer content from the websocket client + * @returns True if a frame has been handled + */ + virtual bool HandleFrame(const std::string &buffer); + + /** Handle a websocket error. + * @param errorcode The error returned from the websocket + */ + virtual void Error(uint32_t errorcode); + + /** Start and monitor I/O loop */ + void Run(); + + /** + * @brief Send audio to the voice channel. + * + * You should send an audio packet of n11520 bytes. + * Note that this function can be costly as it has to opus encode + * the PCM audio on the fly, and also encrypt it with libsodium. + * + * @note Because this function encrypts and encodes packets before + * pushing them onto the output queue, if you have a complete stream + * ready to send and know its length it is advisable to call this + * method multiple times to enqueue the entire stream audio so that + * it is all encoded at once. Constantly calling this from the + * dpp::on_voice_buffer_send callback can and will eat a TON of cpu! + * + * @param audio_data Raw PCM audio data. Channels are interleaved, + * with each channel's amplitude being a 16 bit value. + * @param length The length of the audio data. The length should + * be a multiple of 4 (2x 16 bit stero channels) with a maximum + * length of 11520, which is a complete opus frame at highest + * quality. + * @param use_opus Some containers such as .ogg may contain OPUS + * encoded data already. In this case, we don't need to encode the + * frames using opus here. We can set use_opus to false and bypass the + * codec, only applying libsodium to the stream. + */ + void send_audio(uint16_t* audio_data, const size_t length, bool use_opus = true); + + /** + * @brief Pause sending of audio + * + * @param pause True to pause, false to resume + */ + void pause_audio(bool pause); + + /** + * @brief Immediately stop all audio. + * Clears the packet queue. + */ + void stop_audio(); + + /** + * @brief Returns true if we are playing audio + * + * @return true if audio is playing + */ + bool is_playing(); + + /** + * @brief Get the number of seconds remaining + * of the audio output buffer + * + * @return float number of seconds remaining + */ + float get_secs_remaining(); + + /** + * @brief Get the number of tracks remaining + * in the output buffer. + * This is calculated by the number of track + * markers plus one. + * @return uint32_t Number of tracks in the + * buffer + */ + uint32_t get_tracks_remaining(); + + /** + * @brief Get the time remaining to send the + * audio output buffer in hours:minutes:seconds + * + * @return dpp::utility::uptime length of buffer + */ + dpp::utility::uptime get_remaining(); + + /** + * @brief Insert a track marker into the audio + * output buffer. + * A track marker is an arbitrary flag in the + * buffer contents that indictes the end of some + * block of audio of significance to the sender. + * This may be a song from a streaming site, or + * some voice audio/speech, a sound effect, or + * whatever you choose. You can later skip + * to the next marker using the + * dpp::discord_voice_client::skip_to_next_marker + * function. + * @param metadata Arbitrary information related to this + * track + */ + void insert_marker(const std::string& metadata = ""); + + /** + * @brief Skip tp the next track marker, + * previously inserted by using the + * dpp::discord_voice_client::insert_marker + * function. If there are no markers in the + * output buffer, then this skips to the end + * of the buffer and is equivalent to the + * dpp::discord_voice_client::stop_audio + * function. + * @note It is possible to use this function + * while the output stream is paused. + */ + void skip_to_next_marker(); + + /** + * @brief Get the metdata string associated with each inserted marker. + * + * @return const std::vector& list of metadata strings + */ + const std::vector get_marker_metadata(); + + /** + * @brief Returns true if the audio is paused. + * You can unpause with + * dpp::discord_voice_client::pause_audio. + * + * @return true if paused + */ + bool is_paused(); + + /** + * @brief Discord external IP detection. + * @return std::string Your external IP address + * @note This is a blocking operation that waits + * for a single packet from Discord's voice servers. + */ + std::string discover_ip(); +}; + +}; + diff --git a/vendor/DPP/include/dpp/dispatcher.h b/vendor/DPP/include/dpp/dispatcher.h new file mode 100644 index 00000000..ed95da6a --- /dev/null +++ b/vendor/DPP/include/dpp/dispatcher.h @@ -0,0 +1,1189 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include +#include +#include +#include + +namespace dpp { + +struct CoreExport confirmation_callback_t; + +typedef std::function command_completion_event_t; + +/** @brief Base event parameter struct */ +struct CoreExport event_dispatch_t { + + /** Raw event text */ + std::string raw_event; + + /** Shard the event came from */ + class discord_client* from; + + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + event_dispatch_t(class discord_client* client, const std::string& raw); +}; + +/** @brief Log messages */ +struct CoreExport log_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on. CAN BE NULL + * for log events originating from the cluster object + * @param raw Raw event text as JSON + */ + log_t(class discord_client* client, const std::string& raw); + /** Severity */ + loglevel severity; + /** Log Message */ + std::string message; +}; + +/** @brief Create stage instance */ +struct CoreExport stage_instance_create_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on. CAN BE NULL + * for log events originating from the cluster object + * @param raw Raw event text as JSON + */ + stage_instance_create_t(class discord_client* client, const std::string& raw); + /** + * @brief stage instance id + */ + snowflake id; + /** + * @brief Channel ID + */ + snowflake channel_id; + /** + * @brief Guild ID + */ + snowflake guild_id; + /** + * @brief Privacy level + */ + uint8_t privacy_level; + /** + * @brief Stage Topic + */ + std::string topic; +}; + +/** @brief Delete stage instance */ +struct CoreExport stage_instance_delete_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on. CAN BE NULL + * for log events originating from the cluster object + * @param raw Raw event text as JSON + */ + stage_instance_delete_t(class discord_client* client, const std::string& raw); + /** + * @brief stage instance id + */ + snowflake id; + /** + * @brief Channel ID + */ + snowflake channel_id; + /** + * @brief Guild ID + */ + snowflake guild_id; + /** + * @brief Privacy level + */ + uint8_t privacy_level; + /** + * @brief Stage Topic + */ + std::string topic; +}; + +/** @brief Voice state update */ +struct CoreExport voice_state_update_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + voice_state_update_t(class discord_client* client, const std::string& raw); + /** Voice state */ + voicestate state; +}; + +/** + * @brief Create interaction + */ +struct CoreExport interaction_create_t : public event_dispatch_t { + + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + interaction_create_t(class discord_client* client, const std::string& raw); + + /** + * @brief Send a reply for this interaction + * + * @param t Type of reply to send + * @param m Message object to send. Not all fields are supported by Discord. + */ + void reply(interaction_response_type t, const message & m) const; + + /** + * @brief Send a reply for this interaction + * + * @param t Type of reply to send + * @param mt The string value to send, for simple text only messages + */ + void reply(interaction_response_type t, const std::string & mt) const; + + /** + * @brief Get original response message for this interaction + * + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::message object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void get_original_response(command_completion_event_t callback = {}) const; + + /** + * @brief Edit the response for this interaction + * + * @param m Message object to send. Not all fields are supported by Discord. + */ + void edit_response(const message & m) const; + + /** + * @brief Edit the response for this interaction + * + * @param mt The string value to send, for simple text only messages + */ + void edit_response(const std::string & mt) const; + + /** + * @brief Get a command line parameter + * + * @param name The command line parameter to retrieve + * @return const command_value& If the command line parameter does not + * exist, an empty variant is returned. + */ + const virtual command_value& get_parameter(const std::string& name) const; + + interaction command; +}; + +/** + * @brief Click on button + */ +struct CoreExport button_click_t : public interaction_create_t { + + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + button_click_t(class discord_client* client, const std::string& raw); + + /** + * @brief Get a command line parameter + * + * @param name The command line parameter to retrieve + * @return Always returns an empty parameter as buttons dont have parameters! + */ + const virtual command_value& get_parameter(const std::string& name) const; + + std::string custom_id; + uint8_t component_type; +}; + +/** + * @brief Click on select + */ +struct CoreExport select_click_t : public interaction_create_t { + + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + select_click_t(class discord_client* client, const std::string& raw); + + /** + * @brief Get a command line parameter + * + * @param name The command line parameter to retrieve + * @return Always returns an empty parameter as buttons dont have parameters! + */ + const virtual command_value& get_parameter(const std::string& name) const; + + std::string custom_id; + std::vector values; + uint8_t component_type; +}; + + +/** @brief Delete guild */ +struct CoreExport guild_delete_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + guild_delete_t(class discord_client* client, const std::string& raw); + /** Deleted guild */ + guild* deleted; +}; + +/** @brief Update guild stickers */ +struct CoreExport guild_stickers_update_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + guild_stickers_update_t(class discord_client* client, const std::string& raw); + /** Deleted guild */ + guild* updating_guild; + std::vector stickers; +}; + +/** @brief Guild join request delete (user declined membership screening) */ +struct CoreExport guild_join_request_delete_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + guild_join_request_delete_t(class discord_client* client, const std::string& raw); + /** Deleted guild */ + snowflake guild_id; + snowflake user_id; +}; + +/** @brief Delete channel */ +struct CoreExport channel_delete_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + channel_delete_t(class discord_client* client, const std::string& raw); + guild* deleting_guild; + channel* deleted; +}; + +/** @brief Update channel */ +struct CoreExport channel_update_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + channel_update_t(class discord_client* client, const std::string& raw); + guild* updating_guild; + channel* updated; +}; + +/** @brief Session ready */ +struct CoreExport ready_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + ready_t(class discord_client* client, const std::string& raw); + std::string session_id; + uint32_t shard_id; +}; + +/** @brief Message Deleted */ +struct CoreExport message_delete_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + message_delete_t(class discord_client* client, const std::string& raw); + message* deleted; +}; + +struct CoreExport application_command_delete_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + application_command_delete_t(class discord_client* client, const std::string& raw); +}; + +/** @brief Guild member remove */ +struct CoreExport guild_member_remove_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + guild_member_remove_t(class discord_client* client, const std::string& raw); + guild* removing_guild; + user* removed; +}; + +/** + * @brief Create application slash command + * + */ +struct CoreExport application_command_create_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + application_command_create_t(class discord_client* client, const std::string& raw); +}; + +/** @brief Session resumed */ +struct CoreExport resumed_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + resumed_t(class discord_client* client, const std::string& raw); + std::string session_id; + uint32_t shard_id; +}; + +/** @brief Guild role create */ +struct CoreExport guild_role_create_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + guild_role_create_t(class discord_client* client, const std::string& raw); + guild* creating_guild; + role* created; +}; + +/** @brief Typing start */ +struct CoreExport typing_start_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + typing_start_t(class discord_client* client, const std::string& raw); + guild* typing_guild; + channel* typing_channel; + user* typing_user; + time_t timestamp; +}; + +/** @brief Voice state update */ +struct CoreExport voice_track_marker_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on. + * Will always be null. + * @param raw Raw event text as JSON. + * Will always be empty. + */ + voice_track_marker_t(class discord_client* client, const std::string& raw); + /** Voice client */ + class discord_voice_client* voice_client; + /** Track metadata */ + std::string track_meta; +}; + + +/** @brief Message reaction add */ +struct CoreExport message_reaction_add_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + message_reaction_add_t(class discord_client* client, const std::string& raw); + guild* reacting_guild; + user* reacting_user; + channel* reacting_channel; + emoji* reacting_emoji; + snowflake message_id; +}; + +/** @brief Guild members chunk */ +struct CoreExport guild_members_chunk_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + guild_members_chunk_t(class discord_client* client, const std::string& raw); + guild* adding; + guild_member_map* members; +}; + +/** @brief Message reaction remove */ +struct CoreExport message_reaction_remove_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + message_reaction_remove_t(class discord_client* client, const std::string& raw); + guild* reacting_guild; + user* reacting_user; + channel* reacting_channel; + emoji* reacting_emoji; + snowflake message_id; +}; + +/** @brief Create guild */ +struct CoreExport guild_create_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + guild_create_t(class discord_client* client, const std::string& raw); + guild* created; +}; + +/** @brief Create channel */ +struct CoreExport channel_create_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + channel_create_t(class discord_client* client, const std::string& raw); + guild* creating_guild; + channel* created; +}; + +/** @brief Message remove emoji */ +struct CoreExport message_reaction_remove_emoji_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + message_reaction_remove_emoji_t(class discord_client* client, const std::string& raw); + guild* reacting_guild; + channel* reacting_channel; + emoji* reacting_emoji; + snowflake message_id; +}; + +/** @brief Message delete bulk */ +struct CoreExport message_delete_bulk_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + message_delete_bulk_t(class discord_client* client, const std::string& raw); + guild* deleting_guild; + user* deleting_user; + channel* deleting_channel; + std::vector deleted; +}; + +/** @brief Guild role update */ +struct CoreExport guild_role_update_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + guild_role_update_t(class discord_client* client, const std::string& raw); + guild* updating_guild; + role* updated; +}; + +/** @brief Guild role delete */ +struct CoreExport guild_role_delete_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + guild_role_delete_t(class discord_client* client, const std::string& raw); + guild* deleting_guild; + role* deleted; +}; + +/** @brief Channel pins update */ +struct CoreExport channel_pins_update_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + channel_pins_update_t(class discord_client* client, const std::string& raw); + guild* pin_guild; + channel* pin_channel; + time_t timestamp; +}; + +/** @brief Message remove all reactions */ +struct CoreExport message_reaction_remove_all_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + message_reaction_remove_all_t(class discord_client* client, const std::string& raw); + guild* reacting_guild; + channel* reacting_channel; + snowflake message_id; +}; + +/** @brief Voice server update */ +struct CoreExport voice_server_update_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + voice_server_update_t(class discord_client* client, const std::string& raw); + snowflake guild_id; + std::string token; + std::string endpoint; +}; + +/** @brief Guild emojis update */ +struct CoreExport guild_emojis_update_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + guild_emojis_update_t(class discord_client* client, const std::string& raw); + std::vector emojis; + guild* updating_guild; +}; + +/** + * @brief Presence update + * + */ +struct CoreExport presence_update_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + presence_update_t(class discord_client* client, const std::string& raw); + presence rich_presence; +}; + +/** @brief Webhooks update */ +struct CoreExport webhooks_update_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + webhooks_update_t(class discord_client* client, const std::string& raw); + guild* webhook_guild; + channel* webhook_channel; +}; + +/** @brief Guild member add */ +struct CoreExport guild_member_add_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + guild_member_add_t(class discord_client* client, const std::string& raw); + guild* adding_guild; + guild_member added; +}; + +/** @brief Invite delete */ +struct CoreExport invite_delete_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + invite_delete_t(class discord_client* client, const std::string& raw); + invite deleted_invite; +}; + +/** @brief Guild update */ +struct CoreExport guild_update_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + guild_update_t(class discord_client* client, const std::string& raw); + guild* updated; +}; + +/** @brief Guild integrations update */ +struct CoreExport guild_integrations_update_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + guild_integrations_update_t(class discord_client* client, const std::string& raw); + guild* updating_guild; +}; + +/** @brief Guild member update */ +struct CoreExport guild_member_update_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + guild_member_update_t(class discord_client* client, const std::string& raw); + guild* updating_guild; + guild_member updated; +}; + +/** + * @brief Update application slash command + * + */ +struct CoreExport application_command_update_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + application_command_update_t(class discord_client* client, const std::string& raw); +}; + +/** @brief Invite create */ +struct CoreExport invite_create_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + invite_create_t(class discord_client* client, const std::string& raw); + invite created_invite; +}; + +/** @brief Message update */ +struct CoreExport message_update_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + message_update_t(class discord_client* client, const std::string& raw); + message* updated; +}; + +/* @brief User update */ +struct CoreExport user_update_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + user_update_t(class discord_client* client, const std::string& raw); + user updated; +}; + +/** @brief Create message */ +struct CoreExport message_create_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + message_create_t(class discord_client* client, const std::string& raw); + message* msg; +}; + +/** @brief Guild ban add */ +struct CoreExport guild_ban_add_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + guild_ban_add_t(class discord_client* client, const std::string& raw); + guild* banning_guild; + user banned; +}; + +/** @brief Guild ban remove */ +struct CoreExport guild_ban_remove_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + guild_ban_remove_t(class discord_client* client, const std::string& raw); + guild* unbanning_guild; + user unbanned; +}; + +/** @brief Integration create */ +struct CoreExport integration_create_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + integration_create_t(class discord_client* client, const std::string& raw); + integration created_integration; +}; + +/** @brief Integration update */ +struct CoreExport integration_update_t : public event_dispatch_t { + /** + * @brief Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + integration_update_t(class discord_client* client, const std::string& raw); + integration updated_integration; +}; + +/** @brief Integration delete */ +struct CoreExport integration_delete_t : public event_dispatch_t { + /** + * @brief Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + integration_delete_t(class discord_client* client, const std::string& raw); + integration deleted_integration; +}; + +/** @brief Thread Create*/ +struct CoreExport thread_create_t : public event_dispatch_t { + /** + * @brief Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + thread_create_t(class discord_client* client, const std::string& raw); + guild* creating_guild; + channel created; +}; + +/** @brief Thread Update*/ +struct CoreExport thread_update_t : public event_dispatch_t { + /** + * @brief Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + thread_update_t(class discord_client* client, const std::string& raw); + guild* updating_guild; + channel updated; +}; + +/** @bried Thread Delete*/ +struct CoreExport thread_delete_t : public event_dispatch_t { + /** + * @brief Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + thread_delete_t(class discord_client* client, const std::string& raw); + guild* deleting_guild; + channel deleted; +}; + +/** @brief Thread List Sync*/ +struct CoreExport thread_list_sync_t : public event_dispatch_t { + /** + * @brief Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + thread_list_sync_t(class discord_client* client, const std::string& raw); + guild* updating_guild; + std::vector threads; + std::vector members; +}; + +/** @brief Thread Member Update*/ +struct CoreExport thread_member_update_t : public event_dispatch_t { + /** + * @brief Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + thread_member_update_t(class discord_client* client, const std::string& raw); + thread_member updated; +}; + +/** @brief Thread Members Update*/ +struct CoreExport thread_members_update_t : public event_dispatch_t { + /** + * @brief Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + thread_members_update_t(class discord_client* client, const std::string& raw); + snowflake thread_id; + guild* updating_guild; + uint8_t member_count; + std::vector added; + std::vector removed_ids; +}; + +/** @brief voice buffer send */ +struct CoreExport voice_buffer_send_t : public event_dispatch_t { + /** + * @brief Constructor + * @param client The shard the event originated on + * WILL ALWAYS be NULL. + * @param raw Raw event text as JSON + */ + voice_buffer_send_t(class discord_client* client, const std::string &raw); + class discord_voice_client* voice_client; + int buffer_size; +}; + +/** @brief voice user talking */ +struct CoreExport voice_user_talking_t : public event_dispatch_t { + /** + * @brief Constructor + * @param client The shard the event originated on + * WILL ALWAYS be NULL. + * @param raw Raw event text as JSON + */ + voice_user_talking_t(class discord_client* client, const std::string &raw); + class discord_voice_client* voice_client; + snowflake user_id; + uint8_t talking_flags; +}; + +/** @brief voice user talking */ +struct CoreExport voice_ready_t : public event_dispatch_t { + /** + * @brief Constructor + * @param client The shard the event originated on + * WILL ALWAYS be NULL. + * @param raw Raw event text as JSON + */ + voice_ready_t(class discord_client* client, const std::string &raw); + class discord_voice_client* voice_client; + snowflake voice_channel_id; +}; + +/** @brief voice receive packet */ +struct CoreExport voice_receive_t : public event_dispatch_t { + /** + * @brief Constructor + * @param client The shard the event originated on. + * WILL ALWAYS be NULL. + * @param raw Raw event text as JSON + */ + voice_receive_t(class discord_client* client, const std::string &raw); + class discord_voice_client* voice_client; + uint8_t* audio; + size_t audio_size; +}; + +/** @brief The dispatcher class contains a set of std::functions representing hooked events + * that the user code is interested in. These are modified via the on_eventname style + * methods in the cluster class. + */ +class CoreExport dispatcher { +public: + /** @brief Event handler function pointer for log event + * @param event Event parameters + */ + std::function log; + /** @brief Event handler function pointer for voice state update event + * @param event Event parameters + */ + std::function voice_state_update; + /** @brief Event handler function pointer for interaction create event + * @param event Event parameters + */ + std::function interaction_create; + /** @brief Event handler function pointer for button click event + * @param event Event parameters + */ + std::function button_click; + /** @brief Event handler function pointer for button click event + * @param event Event parameters + */ + std::function select_click; + /** @brief Event handler function pointer for guild delete event + * @param event Event parameters + */ + std::function guild_delete; + /** @brief Event handler function pointer for channel delete event + * @param event Event parameters + */ + std::function channel_delete; + /** @brief Event handler function pointer for channel update event + * @param event Event parameters + */ + std::function channel_update; + /** @brief Event handler function pointer for ready event + * @param event Event parameters + */ + std::function ready; + /** @brief Event handler function pointer for message delete event + * @param event Event parameters + */ + std::function message_delete; + /** @brief Event handler function pointer for application command delete event + * @param event Event parameters + */ + std::function application_command_delete; + /** @brief Event handler function pointer for guild member remove event + * @param event Event parameters + */ + std::function guild_member_remove; + /** @brief Event handler function pointer for guild member remove event + * @param event Event parameters + */ + std::function application_command_create; + /** @brief Event handler function pointer for resumed event + * @param event Event parameters + */ + std::function resumed; + /** @brief Event handler function pointer for guild role create event + * @param event Event parameters + */ + std::function guild_role_create; + /** @brief Event handler function pointer for typing start event + * @param event Event parameters + */ + std::function typing_start; + /** @brief Event handler function pointer for message reaction add event + * @param event Event parameters + */ + std::function message_reaction_add; + /** @brief Event handler function pointer for guild members chunk event + * @param event Event parameters + */ + std::function guild_members_chunk; + /** @brief Event handler function pointer for message reaction remove event + * @param event Event parameters + */ + std::function message_reaction_remove; + /** @brief Event handler function pointer for guild create event + * @param event Event parameters + */ + std::function guild_create; + /** @brief Event handler function pointer for guild channel create event + * @param event Event parameters + */ + std::function channel_create; + /** @brief Event handler function pointer for message reaction remove emoji event + * @param event Event parameters + */ + std::function message_reaction_remove_emoji; + /** @brief Event handler function pointer for message delete bulk event + * @param event Event parameters + */ + std::function message_delete_bulk; + /** @brief Event handler function pointer for guild role update event + * @param event Event parameters + */ + std::function guild_role_update; + /** @brief Event handler function pointer for guild role delete event + * @param event Event parameters + */ + std::function guild_role_delete; + /** @brief Event handler function pointer for channel pins update event + * @param event Event parameters + */ + std::function channel_pins_update; + /** @brief Event handler function pointer for message reaction remove all event + * @param event Event parameters + */ + std::function message_reaction_remove_all; + /** @brief Event handler function pointer for voice server update event + * @param event Event parameters + */ + std::function voice_server_update; + /** @brief Event handler function pointer for guild emojis update event + * @param event Event parameters + */ + std::function guild_emojis_update; + /** @brief Event handler function pointer for presence update event + * @param event Event parameters + */ + std::function presence_update; + /** @brief Event handler function pointer for webhooks update event + * @param event Event parameters + */ + std::function webhooks_update; + /** @brief Event handler function pointer for guild member add event + * @param event Event parameters + */ + std::function guild_member_add; + /** @brief Event handler function pointer for invite delete event + * @param event Event parameters + */ + std::function invite_delete; + /** @brief Event handler function pointer for guild update event + * @param event Event parameters + */ + std::function guild_update; + /** @brief Event handler function pointer for guild integrations update event + * @param event Event parameters + */ + std::function guild_integrations_update; + /** @brief Event handler function pointer for guild member update event + * @param event Event parameters + */ + std::function guild_member_update; + /** @brief Event handler function pointer for application command update event + * @param event Event parameters + */ + std::function application_command_update; + /** @brief Event handler function pointer for invite create event + * @param event Event parameters + */ + std::function invite_create; + /** @brief Event handler function pointer for message update event + * @param event Event parameters + */ + std::function message_update; + /** @brief Event handler function pointer for user update event + * @param event Event parameters + */ + std::function user_update; + /** @brief Event handler function pointer for message create event + * @param event Event parameters + */ + std::function message_create; + /** @brief Event handler function pointer for guild ban add event + * @param event Event parameters + */ + std::function guild_ban_add; + /** @brief Event handler function pointer for guild ban remove event + * @param event Event parameters + */ + std::function guild_ban_remove; + /** @brief Event handler function pointer for integration create event + * @param event Event parameters + */ + std::function integration_create; + /** @brief Event handler function pointer for integration update event + * @param event Event parameters + */ + std::function integration_update; + /** @brief Event handler function pointer for integration delete event + * @param event Event parameters + */ + std::function integration_delete; + /** @brief Event handler function pointer for thread create event + * @param event Event parameters + */ + std::function thread_create; + /** @brief Event handler function pointer for thread update event + * @param event Event parameters + */ + std::function thread_update; + /** @brief Event handler function pointer for thread delete event + * @param event Event parameters + */ + std::function thread_delete; + /** @brief Event handler function pointer for thread list sync event + * @param event Event parameters + */ + std::function thread_list_sync; + /** @brief Event handler function pointer for thread member update event + * @param event Event parameters + */ + std::function thread_member_update; + /** @brief Event handler function pointer for thread members update event + * @param event Event parameters + */ + std::function thread_members_update; + /** @brief Event handler function pointer for voice buffer send event + * @param event Event parameters + */ + std::function voice_buffer_send; + /** @brief Event handler function pointer for voice user talking event + * @param event Event parameters + */ + std::function voice_user_talking; + /** @brief Event handler function pointer for voice ready event + * @param event Event parameters + */ + std::function voice_ready; + /** @brief Event handler function pointer for voice receieve event + * @param event Event parameters + */ + std::function voice_receive; + /** @brief Event handler function pointer for voice track marker event + * @param event Event parameters + */ + std::function voice_track_marker; + /** @brief Event handler function pointer for guild join request delete event + * @param event Event parameters + */ + std::function guild_join_request_delete; + /** @brief Event handler function pointer for stage instance create event + * @param event Event parameters + */ + std::function stage_instance_create; + /** @brief Event handler function pointer for stage instance delete event + * @param event Event parameters + */ + std::function stage_instance_delete; + /** @brief Event handler function pointer for guild sticker update event + * @param event Event parameters + */ + std::function stickers_update; +}; + +/** + * @brief The dpp::exception class derives from std::exception and supports some other + * ways of passing in error details such as via std::string. + */ +class exception : public std::exception +{ + /** + * @brief Exception message + */ + std::string msg; + +public: + + using std::exception::exception; + + /** + * @brief Construct a new exception object + */ + exception() = default; + + explicit exception(const char* what) : msg(what) { } + exception(const char* what, size_t len) : msg(what, len) { } + + explicit exception(const std::string& what) : msg(what) { } + explicit exception(std::string&& what) : msg(std::move(what)) { } + + /** + * @brief Construct a new exception object (copy constructor) + */ + exception(const exception&) = default; + + /** + * @brief Construct a new exception object (move constructor) + */ + exception(exception&&) = default; + + /** + * @brief Destroy the exception object + */ + ~exception() override = default; + + /** + * @brief Copy assignment operator + * + * @return exception& reference to self + */ + exception & operator = (const exception &) = default; + + /** + * @brief Move assignment operator + * + * @return exception& reference to self + */ + exception & operator = (exception&&) = default; + + /** + * @brief Get exception message + * + * @return const char* error message + */ + [[nodiscard]] const char* what() const noexcept override { return msg.c_str(); }; + +}; + +}; + diff --git a/vendor/DPP/include/dpp/dpp.h b/vendor/DPP/include/dpp/dpp.h new file mode 100644 index 00000000..8f740fe1 --- /dev/null +++ b/vendor/DPP/include/dpp/dpp.h @@ -0,0 +1,36 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include \ No newline at end of file diff --git a/vendor/DPP/include/dpp/dtemplate.h b/vendor/DPP/include/dpp/dtemplate.h new file mode 100644 index 00000000..16202287 --- /dev/null +++ b/vendor/DPP/include/dpp/dtemplate.h @@ -0,0 +1,94 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include + +namespace dpp { + +/** + * @brief Represents a guild template + */ +class CoreExport dtemplate { +public: + /** + * @brief Template code + */ + std::string code; + /** + * @brief Template name + */ + std::string name; + /** + * @brief Template description + */ + std::string description; + /** + * @brief Usage counter + */ + uint32_t usage_count; + /** + * @brief User ID of creator + */ + snowflake creator_id; + /** + * @brief Creation date/time + * + */ + time_t created_at; + /** + * @brief Last update date/time + */ + time_t updated_at; + /** + * @brief Guild id the template is created from + */ + snowflake source_guild_id; + /** + * @brief True if needs synchronising + */ + bool is_dirty; + + /** + * @brief Construct a new dtemplate object + */ + dtemplate(); + + /** + * @brief Destroy the dtemplate object + */ + ~dtemplate(); + + /** Read class values from json object + * @param j A json object to read from + * @return A reference to self + */ + dtemplate& fill_from_json(nlohmann::json* j); + std::string build_json() const; + +}; + +/** A container of invites */ +typedef std::unordered_map dtemplate_map; + + +}; diff --git a/vendor/DPP/include/dpp/emoji.h b/vendor/DPP/include/dpp/emoji.h new file mode 100644 index 00000000..737e671f --- /dev/null +++ b/vendor/DPP/include/dpp/emoji.h @@ -0,0 +1,155 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include + +namespace dpp { + +#define MAX_EMOJI_SIZE 256 * 1024 + +/** + * @brief Flags for dpp::emoji + */ +enum emoji_flags { + /// Emoji requires colons + e_require_colons = 0b00000001, + /// Managed (introduced by application) + e_managed = 0b00000010, + /// Animated + e_animated = 0b00000100, + /// Available (false if the guild doesn't meet boosting criteria, etc) + e_available = 0b00001000, +}; + +/** + * @brief Represents an emoji for a dpp::guild + */ +class CoreExport emoji : public managed { +public: + /** + * @brief Emoji name + */ + std::string name; + /** + * @brief User id who uploaded the emoji + */ + snowflake user_id; + /** + * @brief Flags for the emoji from dpp::emoji_flags + */ + uint8_t flags; + /** + * @brief Image data for the emoji if uploading + */ + std::string* image_data; + + /** + * @brief Construct a new emoji object + */ + emoji(); + + /** + * @brief Construct a new emoji object with name, ID and flags + * + * @param name The emoji's name + * @param id ID, if it has one (unicode does not) + * @param flags Emoji flags (emoji_flags) + */ + emoji(const std::string, const snowflake = 0, const uint8_t = 0); + + /** + * @brief Destroy the emoji object + */ + virtual ~emoji(); + + /** + * @brief Read class values from json object + * + * @param j A json object to read from + * @return A reference to self + */ + emoji& fill_from_json(nlohmann::json* j); + + /** + * @brief Build the json for this object + * + * @param with_id include the id in the JSON + * @return std::string json data + */ + std::string build_json(bool with_id = false) const; + + /** + * @brief Emoji requires colons + * + * @return true Requires colons + * @return false Does not require colons + */ + bool requires_colons() const; + + /** + * @brief Emoji is managed + * + * @return true Is managed + * @return false Is not managed + */ + bool is_managed() const; + + /** + * @brief Emoji is animated + * + * @return true Is animated + * @return false Is noy animated + */ + bool is_animated() const; + + /** + * @brief Is available + * + * @return true Is available + * @return false Is unavailable + */ + bool is_available() const; + + /** + * @brief Load an image into the object as base64 + * + * @param image_blob Image binary data + * @param type Type of image + * @return emoji& Reference to self + */ + emoji& load_image(const std::string &image_blob, image_type type); + + /** + * @brief Format to name if unicode, name:id if has id or a:name:id if animated + * + * @return Formatted name for reactions + */ + std::string format() const; +}; + +/** + * @brief Group of emojis + */ +typedef std::unordered_map emoji_map; + +}; diff --git a/vendor/DPP/include/dpp/event.h b/vendor/DPP/include/dpp/event.h new file mode 100644 index 00000000..e1899764 --- /dev/null +++ b/vendor/DPP/include/dpp/event.h @@ -0,0 +1,139 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include + +#define event_decl(x) class x : public event { public: virtual void handle(dpp::discord_client* client, nlohmann::json &j, const std::string &raw); }; + +namespace dpp { + +class discord_client; + +/** + * @brief The events namespace holds the internal event handlers for each websocket event. + * These are handled internally and also dispatched to the user code if the event is hooked. + */ +namespace events { + +/** + * @brief An event object represents an event handled internally, passed from the websocket e.g. MESSAGE_CREATE. + */ +class CoreExport event { +public: + /** Pure virtual method for event handler code + * @param client The creating shard + * @param j The json data of the event + * @param raw The raw event json + */ + virtual void handle(class discord_client* client, nlohmann::json &j, const std::string &raw) = 0; +}; + +/* Internal logger */ +event_decl(logger); + +/* Guilds */ +event_decl(guild_create); +event_decl(guild_update); +event_decl(guild_delete); +event_decl(guild_ban_add); +event_decl(guild_ban_remove); +event_decl(guild_emojis_update); +event_decl(guild_integrations_update); +event_decl(guild_join_request_delete); +event_decl(guild_stickers_update); + +/* Stage channels */ +event_decl(stage_instance_create); +event_decl(stage_instance_delete); + +/* Guild members */ +event_decl(guild_member_add); +event_decl(guild_member_remove); +event_decl(guild_members_chunk); +event_decl(guild_member_update); + +/* Guild roles */ +event_decl(guild_role_create); +event_decl(guild_role_update); +event_decl(guild_role_delete); + +/* Session state */ +event_decl(resumed); +event_decl(ready); + +/* Channels */ +event_decl(channel_create); +event_decl(channel_update); +event_decl(channel_delete); +event_decl(channel_pins_update); + +/* Threads */ +event_decl(thread_create); +event_decl(thread_update); +event_decl(thread_delete); +event_decl(thread_list_sync); +event_decl(thread_member_update); +event_decl(thread_members_update); + +/* Messages */ +event_decl(message_create); +event_decl(message_update); +event_decl(message_delete); +event_decl(message_delete_bulk); + +/* Presence/typing */ +event_decl(presence_update); +event_decl(typing_start); + +/* Users (outside of guild) */ +event_decl(user_update); + +/* Message reactions */ +event_decl(message_reaction_add); +event_decl(message_reaction_remove); +event_decl(message_reaction_remove_all); +event_decl(message_reaction_remove_emoji); + +/* Invites */ +event_decl(invite_create); +event_decl(invite_delete); + +/* Voice */ +event_decl(voice_state_update); +event_decl(voice_server_update); + +/* Webhooks */ +event_decl(webhooks_update); + +/* Slash commands */ +event_decl(application_command_create); +event_decl(application_command_update); +event_decl(application_command_delete); +event_decl(interaction_create); + +/* Integrations */ +event_decl(integration_create); +event_decl(integration_update); +event_decl(integration_delete); + +}}; diff --git a/vendor/DPP/include/dpp/export.h b/vendor/DPP/include/dpp/export.h new file mode 100644 index 00000000..0f1a7425 --- /dev/null +++ b/vendor/DPP/include/dpp/export.h @@ -0,0 +1,43 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once + +#ifdef DPP_BUILD + #ifdef _WIN32 + #define CoreExport __declspec(dllexport) + #else + #define CoreExport + #endif +#else + #ifdef _WIN32 + #define CoreExport __declspec(dllimport) + /* This is required otherwise fmt::format requires additional file linkage to your project */ + #define FMT_HEADER_ONLY + #else + #define CoreExport + #endif +#endif + +#ifndef _WIN32 + #define SOCKET int +#else + #include +#endif \ No newline at end of file diff --git a/vendor/DPP/include/dpp/guild.h b/vendor/DPP/include/dpp/guild.h new file mode 100644 index 00000000..6e34f187 --- /dev/null +++ b/vendor/DPP/include/dpp/guild.h @@ -0,0 +1,432 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief Represents voice regions for guilds and channels. + * @note Largely deprecated in favour of per-channel regions. + */ +enum region : uint8_t { + r_brazil, //!< Brazil + r_central_europe, //!< Central Europe + r_hong_kong, //!< Hong Kong + r_india, //!< India + r_japan, //!< Japan + r_russia, //!< Russia + r_singapore, //!< Singapore + r_south_africa, //!< South Africa + r_sydney, //!< Sydney + r_us_central, //!< US Central + r_us_east, //!< US East Coast + r_us_south, //!< US South + r_us_west, //!< US West Coast + r_western_europe //!< Western Europe +}; + +/** + * @brief The various flags that represent the status of a dpp::guild object + */ +enum guild_flags { + /** Large guild */ + g_large = 0b000000000000000000001, + /** Unavailable guild (inaccessible due to an outage) */ + g_unavailable = 0b000000000000000000010, + /** Guild has widget enabled */ + g_widget_enabled = 0b000000000000000000100, + /** Guild can have an invite splash image */ + g_invite_splash = 0b000000000000000001000, + /** Guild can have VIP regions */ + g_vip_regions = 0b000000000000000010000, + /** Guild can have a vanity url */ + g_vanity_url = 0b000000000000000100000, + /** Guild is verified */ + g_verified = 0b000000000000001000000, + /** Guild is partnered */ + g_partnered = 0b000000000000010000000, + /** Community features enabled */ + g_community = 0b000000000000100000000, + /** Guild has commerce features enabled */ + g_commerce = 0b000000000001000000000, + /** Guild has news features enabled */ + g_news = 0b000000000010000000000, + /** Guild is discoverable in discovery */ + g_discoverable = 0b000000000100000000000, + /** Guild is featureable */ + g_featureable = 0b000000001000000000000, + /** Guild can have an animated icon (doesn't mean it actually has one though) */ + g_animated_icon = 0b000000010000000000000, + /** Guild can have a banner image */ + g_banner = 0b000000100000000000000, + /** Guild has a welcome screen */ + g_welcome_screen_enabled = 0b000001000000000000000, + /** Guild has a member verification gate */ + g_member_verification_gate = 0b000010000000000000000, + /** Guild has a preview */ + g_preview_enabled = 0b000100000000000000000, + /** Guild join notifications are off */ + g_no_join_notifications = 0b001000000000000000000, + /** Guild boost notifications are off */ + g_no_boost_notifications = 0b010000000000000000000, + /** Guild has an actual animated icon (set by the icon hash starting with 'a_') */ + g_has_animated_icon = 0b100000000000000000000 +}; + +/** + * @brief Various flags that can be used to indicate the status of a guild member + */ +enum guild_member_flags { + /** Member deafened */ + gm_deaf = 0b00001, + /** Member muted */ + gm_mute = 0b00010, + /** Member pending verification by membership screening */ + gm_pending = 0b00100 +}; + +/** + * @brief Represents dpp::user membership upon a dpp::guild + */ +class CoreExport guild_member { +public: + /** Nickname, or nullptr if they don't have a nickname on this guild */ + std::string nickname; + /** Guild id */ + snowflake guild_id; + /** User id */ + snowflake user_id; + /** List of roles this user has on this guild */ + std::vector roles; + /** Date and time the user joined the guild */ + time_t joined_at; + /** Boosting since */ + time_t premium_since; + /** A set of flags built from the bitmask defined by dpp::guild_member_flags */ + uint8_t flags; + + /** Default constructor */ + guild_member(); + + /** Fill this object from a json object. + * @param j The json object to get data from + * @param g_id The guild id to associate the member with + * @param u_id The user id to associate the member with + */ + guild_member& fill_from_json(nlohmann::json* j, snowflake g_id, snowflake u_id); + + /** Build json string for the member object */ + std::string build_json() const; + + /** Returns true if the user is deafened */ + bool is_deaf() const; + + /** Returns true if the user is muted */ + bool is_muted() const; + + /** Returns true if pending verification by membership screening */ + bool is_pending() const; + +}; + +/** @brief Guild members container + */ +typedef std::unordered_map members_container; + +/** + * @brief Represents a guild on Discord (AKA a server) + */ +class CoreExport guild : public managed { +public: + /** Shard ID of the guild */ + uint16_t shard_id; + + /** Flags bitmask as defined by values within dpp::guild_flags */ + uint32_t flags; + + /** Guild name */ + std::string name; + + /** Server description for communities */ + std::string description; + + /** Vanity url code for verified or partnered servers and boost level 3 */ + std::string vanity_url_code; + + /** Guild icon hash */ + utility::iconhash icon; + + /** Guild splash hash */ + utility::iconhash splash; + + /** Guild discovery splash hash */ + utility::iconhash discovery_splash; + + /** Snowflake id of guild owner */ + snowflake owner_id; + + /** Guild voice region */ + region voice_region; + + /** Snowflake ID of AFK voice channel or 0 */ + snowflake afk_channel_id; + + /** Voice AFK timeout before moving users to AFK channel */ + uint8_t afk_timeout; + + /** Snowflake ID of widget channel, or 0 */ + snowflake widget_channel_id; + + /** Verification level of server */ + uint8_t verification_level; + + /** Setting for how notifications are to be delivered to users */ + uint8_t default_message_notifications; + + /** Wether or not explicit content filtering is enable and what setting it is */ + uint8_t explicit_content_filter; + + /** If multi factor authentication is required for moderators or not */ + uint8_t mfa_level; + + /** ID of creating application, if any, or 0 */ + snowflake application_id; + + /** ID of system channel where discord update messages are sent */ + snowflake system_channel_id; + + /** ID of rules channel for communities */ + snowflake rules_channel_id; + + /** Approximate member count. May be sent as zero */ + uint32_t member_count; + + /** Server banner hash */ + utility::iconhash banner; + + /** Boost level */ + uint8_t premium_tier; + + /** Number of boosters */ + uint16_t premium_subscription_count; + + /** Public updates channel id or 0 */ + snowflake public_updates_channel_id; + + /** Maximum users in a video channel, or 0 */ + uint16_t max_video_channel_users; + + /** Roles defined on this server */ + std::vector roles; + + /** List of channels on this server */ + std::vector channels; + + /** List of threads on this server */ + std::vector threads; + + /** List of guild members. Note that when you first receive the + * guild create event, this may be empty or near empty. + * This depends upon your dpp::intents and the size of your bot. + * It will be filled by guild member chunk requests. + */ + members_container members; + + /** List of members in voice channels in the guild. + */ + std::map voice_members; + + /** List of emojis + */ + std::vector emojis; + + /** Default constructor, zeroes all values */ + guild(); + + /** + * @brief Destroy the guild object + */ + virtual ~guild() = default; + + /** Read class values from json object + * @param shard originating shard + * @param j A json object to read from + * @return A reference to self + */ + guild& fill_from_json(class discord_client* shard, nlohmann::json* j); + + /** Build a JSON string from this object. + * @param with_id True if an ID is to be included in the JSON + */ + std::string build_json(bool with_id = false) const; + + /** + * @brief Get the base permissions for a member on this guild, + * before permission overwrites are applied. + * + * @param member member to get permissions for + * @return uint64_t permissions bitmask + */ + uint64_t base_permissions(const class user* member) const; + + /** + * @brief Get the permission overwrites for a member + * merged into a bitmask. + * + * @param base_permissions base permissions before overwrites, + * from channel::base_permissions + * @param member Member to fetch permissions for + * @param channel Channel to fetch permissions against + * @return uint64_t Merged permissions bitmask of overwrites. + */ + uint64_t permission_overwrites(const uint64_t base_permissions, const user* member, const channel* channel) const; + + /** + * @brief Rehash members map + */ + void rehash_members(); + + /** + * @brief Connect to a voice channel another guild member is in + * + * @param user_id User id to join + * @return True if the user specified is in a vc, false if they aren't + */ + bool connect_member_voice(snowflake user_id); + + /** Is a large server (>250 users) */ + bool is_large() const; + + /** Is unavailable due to outage (most other fields will be blank or outdated */ + bool is_unavailable() const; + + /** Widget is enabled for this server */ + bool widget_enabled() const; + + /** Guild has an invite splash */ + bool has_invite_splash() const; + + /** Guild has VIP regions */ + bool has_vip_regions() const; + + /** Guild can have a vanity url */ + bool has_vanity_url() const; + + /** Guild is a verified server */ + bool is_verified() const; + + /** Guild is a discord partner server */ + bool is_partnered() const; + + /** Guild has enabled community */ + bool is_community() const; + + /** Guild has enabled commerce channels */ + bool has_commerce() const; + + /** Guild has news channels */ + bool has_news() const; + + /** Guild is discoverable */ + bool is_discoverable() const; + + /** Guild is featureable */ + bool is_featureable() const; + + /** Guild is allowed an animated icon */ + bool has_animated_icon() const; + + /** Guild has a banner image */ + bool has_banner() const; + + /** Guild has enabled welcome screen */ + bool is_welcome_screen_enabled() const; + + /** Guild has enabled membership screening */ + bool has_member_verification_gate() const; + + /** Guild has preview enabled */ + bool is_preview_enabled() const; + + /** Server icon is actually an animated gif */ + bool has_animated_icon_hash() const; + +}; + +/** A container of guilds */ +typedef std::unordered_map guild_map; + +/** + * @brief Represents a guild widget, simple web widget of member list + */ +class CoreExport guild_widget { +public: + /** + * @brief True if enabled + */ + bool enabled; + /** + * @brief Channel widget points to + */ + snowflake channel_id; + + /** + * @brief Construct a new guild widget object + */ + guild_widget(); + + /** + * @brief Build a guild widget from json + * + * @param j json to build from + * @return guild_widget& reference to self + */ + guild_widget& fill_from_json(nlohmann::json* j); + + /** + * @brief Build json for a guild widget + * + * @return std::string guild widget stringified json + */ + std::string build_json() const; +}; + +/** + * @brief helper function to deserialize a guild_member from json + * + * @see https://github.com/nlohmann/json#arbitrary-types-conversions + * + * @param j output json object + * @param gm guild_member to be deserialized + */ +void from_json(const nlohmann::json& j, guild_member& gm); + +/** A container of guild members */ +typedef std::unordered_map guild_member_map; + + +}; diff --git a/vendor/DPP/include/dpp/httplib.h b/vendor/DPP/include/dpp/httplib.h new file mode 100644 index 00000000..066a3d2b --- /dev/null +++ b/vendor/DPP/include/dpp/httplib.h @@ -0,0 +1,1452 @@ +// +// httplib.h +// +// Copyright (c) 2020 Yuji Hirose. All rights reserved. +// MIT License +// + +#ifndef CPPHTTPLIB_HTTPLIB_H +#define CPPHTTPLIB_HTTPLIB_H + +/* + * Configuration + */ + +#ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND +#define CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND 5 +#endif + +#ifndef CPPHTTPLIB_KEEPALIVE_MAX_COUNT +#define CPPHTTPLIB_KEEPALIVE_MAX_COUNT 5 +#endif + +#ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND +#define CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND 300 +#endif + +#ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND +#define CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND 0 +#endif + +#ifndef CPPHTTPLIB_READ_TIMEOUT_SECOND +#define CPPHTTPLIB_READ_TIMEOUT_SECOND 5 +#endif + +#ifndef CPPHTTPLIB_READ_TIMEOUT_USECOND +#define CPPHTTPLIB_READ_TIMEOUT_USECOND 0 +#endif + +#ifndef CPPHTTPLIB_WRITE_TIMEOUT_SECOND +#define CPPHTTPLIB_WRITE_TIMEOUT_SECOND 5 +#endif + +#ifndef CPPHTTPLIB_WRITE_TIMEOUT_USECOND +#define CPPHTTPLIB_WRITE_TIMEOUT_USECOND 0 +#endif + +#ifndef CPPHTTPLIB_IDLE_INTERVAL_SECOND +#define CPPHTTPLIB_IDLE_INTERVAL_SECOND 0 +#endif + +#ifndef CPPHTTPLIB_IDLE_INTERVAL_USECOND +#ifdef _WIN32 +#define CPPHTTPLIB_IDLE_INTERVAL_USECOND 10000 +#else +#define CPPHTTPLIB_IDLE_INTERVAL_USECOND 0 +#endif +#endif + +#ifndef CPPHTTPLIB_REQUEST_URI_MAX_LENGTH +#define CPPHTTPLIB_REQUEST_URI_MAX_LENGTH 8192 +#endif + +#ifndef CPPHTTPLIB_REDIRECT_MAX_COUNT +#define CPPHTTPLIB_REDIRECT_MAX_COUNT 20 +#endif + +#ifndef CPPHTTPLIB_PAYLOAD_MAX_LENGTH +#define CPPHTTPLIB_PAYLOAD_MAX_LENGTH ((std::numeric_limits::max)()) +#endif + +#ifndef CPPHTTPLIB_TCP_NODELAY +#define CPPHTTPLIB_TCP_NODELAY false +#endif + +#ifndef CPPHTTPLIB_RECV_BUFSIZ +#define CPPHTTPLIB_RECV_BUFSIZ size_t(4096u) +#endif + +#ifndef CPPHTTPLIB_COMPRESSION_BUFSIZ +#define CPPHTTPLIB_COMPRESSION_BUFSIZ size_t(16384u) +#endif + +#ifndef CPPHTTPLIB_THREAD_POOL_COUNT +#define CPPHTTPLIB_THREAD_POOL_COUNT \ + ((std::max)(8u, std::thread::hardware_concurrency() > 0 \ + ? std::thread::hardware_concurrency() - 1 \ + : 0)) +#endif + +#ifndef CPPHTTPLIB_RECV_FLAGS +#define CPPHTTPLIB_RECV_FLAGS 0 +#endif + +#ifndef CPPHTTPLIB_SEND_FLAGS +#define CPPHTTPLIB_SEND_FLAGS 0 +#endif + +/* + * Headers + */ + +#ifdef _WIN32 +#ifndef _CRT_SECURE_NO_WARNINGS +#define _CRT_SECURE_NO_WARNINGS +#endif //_CRT_SECURE_NO_WARNINGS + +#ifndef _CRT_NONSTDC_NO_DEPRECATE +#define _CRT_NONSTDC_NO_DEPRECATE +#endif //_CRT_NONSTDC_NO_DEPRECATE + +#if defined(_MSC_VER) +#ifdef _WIN64 +using ssize_t = __int64; +#else +using ssize_t = int; +#endif + +#if _MSC_VER < 1900 +#define snprintf _snprintf_s +#endif +#endif // _MSC_VER + +#ifndef S_ISREG +#define S_ISREG(m) (((m)&S_IFREG) == S_IFREG) +#endif // S_ISREG + +#ifndef S_ISDIR +#define S_ISDIR(m) (((m)&S_IFDIR) == S_IFDIR) +#endif // S_ISDIR + +#ifndef NOMINMAX +#define NOMINMAX +#endif // NOMINMAX + +#include +#include + +#include +#include + +#ifndef WSA_FLAG_NO_HANDLE_INHERIT +#define WSA_FLAG_NO_HANDLE_INHERIT 0x80 +#endif + +#ifdef _MSC_VER +#pragma comment(lib, "ws2_32.lib") +#pragma comment(lib, "crypt32.lib") +#pragma comment(lib, "cryptui.lib") +#endif + +#ifndef strcasecmp +#define strcasecmp _stricmp +#endif // strcasecmp + +using socket_t = SOCKET; +#ifdef CPPHTTPLIB_USE_POLL +#define poll(fds, nfds, timeout) WSAPoll(fds, nfds, timeout) +#endif + +#else // not _WIN32 + +#include +#include +#include +#include +#include +#ifdef __linux__ +#include +#endif +#include +#ifdef CPPHTTPLIB_USE_POLL +#include +#endif +#include +#include +#include +#include +#include + +using socket_t = int; +#define INVALID_SOCKET (-1) +#endif //_WIN32 + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef OPENSSL_SYS_WIN32 +#undef X509_NAME +#undef X509_EXTENSIONS +#undef X509_CERT_PAIR +#undef PKCS7_ISSUER_AND_SERIAL +#undef OCSP_REQUEST +#undef OCSP_RESPONSE +#endif + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT +#include +#include +#include +#include + +#if defined(_WIN32) && defined(OPENSSL_USE_APPLINK) +#include +#endif + +#include +#include + +#if OPENSSL_VERSION_NUMBER < 0x1010100fL +#error Sorry, OpenSSL versions prior to 1.1.1 are not supported +#endif + +#if OPENSSL_VERSION_NUMBER < 0x10100000L +#include +inline const unsigned char *ASN1_STRING_get0_data(const ASN1_STRING *asn1) { + return M_ASN1_STRING_data(asn1); +} +#endif +#endif + +#ifdef CPPHTTPLIB_ZLIB_SUPPORT +#include +#endif + +#ifdef CPPHTTPLIB_BROTLI_SUPPORT +#include +#include +#endif + +/* + * Declaration + */ +namespace httplib { + +namespace detail { + +/* + * Backport std::make_unique from C++14. + * + * NOTE: This code came up with the following stackoverflow post: + * https://stackoverflow.com/questions/10149840/c-arrays-and-make-unique + * + */ + +template +typename std::enable_if::value, std::unique_ptr>::type +make_unique(Args &&...args) { + return std::unique_ptr(new T(std::forward(args)...)); +} + +template +typename std::enable_if::value, std::unique_ptr>::type +make_unique(std::size_t n) { + typedef typename std::remove_extent::type RT; + return std::unique_ptr(new RT[n]); +} + +struct ci { + bool operator()(const std::string &s1, const std::string &s2) const { + return std::lexicographical_compare(s1.begin(), s1.end(), s2.begin(), + s2.end(), + [](unsigned char c1, unsigned char c2) { + return ::tolower(c1) < ::tolower(c2); + }); + } +}; + +} // namespace detail + +using Headers = std::multimap; + +using Params = std::multimap; +using Match = std::smatch; + +using Progress = std::function; + +struct Response; +using ResponseHandler = std::function; + +struct MultipartFormData { + std::string name; + std::string content; + std::string filename; + std::string content_type; +}; +using MultipartFormDataItems = std::vector; +using MultipartFormDataMap = std::multimap; + +class DataSink { +public: + DataSink() : os(&sb_), sb_(*this) {} + + DataSink(const DataSink &) = delete; + DataSink &operator=(const DataSink &) = delete; + DataSink(DataSink &&) = delete; + DataSink &operator=(DataSink &&) = delete; + + std::function write; + std::function done; + std::function is_writable; + std::ostream os; + +private: + class data_sink_streambuf : public std::streambuf { + public: + explicit data_sink_streambuf(DataSink &sink) : sink_(sink) {} + + protected: + std::streamsize xsputn(const char *s, std::streamsize n) { + sink_.write(s, static_cast(n)); + return n; + } + + private: + DataSink &sink_; + }; + + data_sink_streambuf sb_; +}; + +using ContentProvider = + std::function; + +using ContentProviderWithoutLength = + std::function; + +using ContentReceiverWithProgress = + std::function; + +using ContentReceiver = + std::function; + +using MultipartContentHeader = + std::function; + +class ContentReader { +public: + using Reader = std::function; + using MultipartReader = std::function; + + ContentReader(Reader reader, MultipartReader multipart_reader) + : reader_(std::move(reader)), + multipart_reader_(std::move(multipart_reader)) {} + + bool operator()(MultipartContentHeader header, + ContentReceiver receiver) const { + return multipart_reader_(std::move(header), std::move(receiver)); + } + + bool operator()(ContentReceiver receiver) const { + return reader_(std::move(receiver)); + } + + Reader reader_; + MultipartReader multipart_reader_; +}; + +using Range = std::pair; +using Ranges = std::vector; + +struct Request { + std::string method; + std::string path; + Headers headers; + std::string body; + + std::string remote_addr; + int remote_port = -1; + + // for server + std::string version; + std::string target; + Params params; + MultipartFormDataMap files; + Ranges ranges; + Match matches; + + // for client + ResponseHandler response_handler; + ContentReceiverWithProgress content_receiver; + Progress progress; +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + const SSL *ssl = nullptr; +#endif + + bool has_header(const char *key) const; + std::string get_header_value(const char *key, size_t id = 0) const; + template + T get_header_value(const char *key, size_t id = 0) const; + size_t get_header_value_count(const char *key) const; + void set_header(const char *key, const char *val); + void set_header(const char *key, const std::string &val); + + bool has_param(const char *key) const; + std::string get_param_value(const char *key, size_t id = 0) const; + size_t get_param_value_count(const char *key) const; + + bool is_multipart_form_data() const; + + bool has_file(const char *key) const; + MultipartFormData get_file_value(const char *key) const; + + // private members... + size_t redirect_count_ = CPPHTTPLIB_REDIRECT_MAX_COUNT; + size_t content_length_ = 0; + ContentProvider content_provider_; + bool is_chunked_content_provider_ = false; + size_t authorization_count_ = 0; +}; + +struct Response { + std::string version; + int status = -1; + std::string reason; + Headers headers; + std::string body; + std::string location; // Redirect location + + bool has_header(const char *key) const; + std::string get_header_value(const char *key, size_t id = 0) const; + template + T get_header_value(const char *key, size_t id = 0) const; + size_t get_header_value_count(const char *key) const; + void set_header(const char *key, const char *val); + void set_header(const char *key, const std::string &val); + + void set_redirect(const char *url, int status = 302); + void set_redirect(const std::string &url, int status = 302); + void set_content(const char *s, size_t n, const char *content_type); + void set_content(const std::string &s, const char *content_type); + + void set_content_provider( + size_t length, const char *content_type, ContentProvider provider, + const std::function &resource_releaser = nullptr); + + void set_content_provider( + const char *content_type, ContentProviderWithoutLength provider, + const std::function &resource_releaser = nullptr); + + void set_chunked_content_provider( + const char *content_type, ContentProviderWithoutLength provider, + const std::function &resource_releaser = nullptr); + + Response() = default; + Response(const Response &) = default; + Response &operator=(const Response &) = default; + Response(Response &&) = default; + Response &operator=(Response &&) = default; + ~Response() { + if (content_provider_resource_releaser_) { + content_provider_resource_releaser_(); + } + } + + // private members... + size_t content_length_ = 0; + ContentProvider content_provider_; + std::function content_provider_resource_releaser_; + bool is_chunked_content_provider_ = false; +}; + +class Stream { +public: + virtual ~Stream() = default; + + virtual bool is_readable() const = 0; + virtual bool is_writable() const = 0; + + virtual ssize_t read(char *ptr, size_t size) = 0; + virtual ssize_t write(const char *ptr, size_t size) = 0; + virtual void get_remote_ip_and_port(std::string &ip, int &port) const = 0; + virtual socket_t socket() const = 0; + + template + ssize_t write_format(const char *fmt, const Args &...args); + ssize_t write(const char *ptr); + ssize_t write(const std::string &s); +}; + +class TaskQueue { +public: + TaskQueue() = default; + virtual ~TaskQueue() = default; + + virtual void enqueue(std::function fn) = 0; + virtual void shutdown() = 0; + + virtual void on_idle(){}; +}; + +class ThreadPool : public TaskQueue { +public: + explicit ThreadPool(size_t n) : shutdown_(false) { + while (n) { + threads_.emplace_back(worker(*this)); + n--; + } + } + + ThreadPool(const ThreadPool &) = delete; + ~ThreadPool() override = default; + + void enqueue(std::function fn) override { + std::unique_lock lock(mutex_); + jobs_.push_back(std::move(fn)); + cond_.notify_one(); + } + + void shutdown() override { + // Stop all worker threads... + { + std::unique_lock lock(mutex_); + shutdown_ = true; + } + + cond_.notify_all(); + + // Join... + for (auto &t : threads_) { + t.join(); + } + } + +private: + struct worker { + explicit worker(ThreadPool &pool) : pool_(pool) {} + + void operator()() { + for (;;) { + std::function fn; + { + std::unique_lock lock(pool_.mutex_); + + pool_.cond_.wait( + lock, [&] { return !pool_.jobs_.empty() || pool_.shutdown_; }); + + if (pool_.shutdown_ && pool_.jobs_.empty()) { break; } + + fn = pool_.jobs_.front(); + pool_.jobs_.pop_front(); + } + + assert(true == static_cast(fn)); + fn(); + } + } + + ThreadPool &pool_; + }; + friend struct worker; + + std::vector threads_; + std::list> jobs_; + + bool shutdown_; + + std::condition_variable cond_; + std::mutex mutex_; +}; + +using Logger = std::function; + +using SocketOptions = std::function; + +inline void default_socket_options(socket_t sock) { + int yes = 1; +#ifdef _WIN32 + setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast(&yes), + sizeof(yes)); + setsockopt(sock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, + reinterpret_cast(&yes), sizeof(yes)); +#else +#ifdef SO_REUSEPORT + setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, reinterpret_cast(&yes), + sizeof(yes)); +#else + setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast(&yes), + sizeof(yes)); +#endif +#endif +} + +class Server { +public: + using Handler = std::function; + + using ExceptionHandler = + std::function; + + enum class HandlerResponse { + Handled, + Unhandled, + }; + using HandlerWithResponse = + std::function; + + using HandlerWithContentReader = std::function; + + using Expect100ContinueHandler = + std::function; + + Server(); + + virtual ~Server(); + + virtual bool is_valid() const; + + Server &Get(const char *pattern, Handler handler); + Server &Get(const char *pattern, size_t pattern_len, Handler handler); + Server &Post(const char *pattern, Handler handler); + Server &Post(const char *pattern, size_t pattern_len, Handler handler); + Server &Post(const char *pattern, HandlerWithContentReader handler); + Server &Post(const char *pattern, size_t pattern_len, + HandlerWithContentReader handler); + Server &Put(const char *pattern, Handler handler); + Server &Put(const char *pattern, size_t pattern_len, Handler handler); + Server &Put(const char *pattern, HandlerWithContentReader handler); + Server &Put(const char *pattern, size_t pattern_len, + HandlerWithContentReader handler); + Server &Patch(const char *pattern, Handler handler); + Server &Patch(const char *pattern, size_t pattern_len, Handler handler); + Server &Patch(const char *pattern, HandlerWithContentReader handler); + Server &Patch(const char *pattern, size_t pattern_len, + HandlerWithContentReader handler); + Server &Delete(const char *pattern, Handler handler); + Server &Delete(const char *pattern, size_t pattern_len, Handler handler); + Server &Delete(const char *pattern, HandlerWithContentReader handler); + Server &Delete(const char *pattern, size_t pattern_len, + HandlerWithContentReader handler); + Server &Options(const char *pattern, Handler handler); + Server &Options(const char *pattern, size_t pattern_len, Handler handler); + + bool set_base_dir(const char *dir, const char *mount_point = nullptr); + bool set_mount_point(const char *mount_point, const char *dir, + Headers headers = Headers()); + bool remove_mount_point(const char *mount_point); + Server &set_file_extension_and_mimetype_mapping(const char *ext, + const char *mime); + Server &set_file_request_handler(Handler handler); + + Server &set_error_handler(HandlerWithResponse handler); + Server &set_error_handler(Handler handler); + Server &set_exception_handler(ExceptionHandler handler); + Server &set_pre_routing_handler(HandlerWithResponse handler); + Server &set_post_routing_handler(Handler handler); + + Server &set_expect_100_continue_handler(Expect100ContinueHandler handler); + Server &set_logger(Logger logger); + + Server &set_address_family(int family); + Server &set_tcp_nodelay(bool on); + Server &set_socket_options(SocketOptions socket_options); + + Server &set_keep_alive_max_count(size_t count); + Server &set_keep_alive_timeout(time_t sec); + + Server &set_read_timeout(time_t sec, time_t usec = 0); + template + Server &set_read_timeout(const std::chrono::duration &duration); + + Server &set_write_timeout(time_t sec, time_t usec = 0); + template + Server &set_write_timeout(const std::chrono::duration &duration); + + Server &set_idle_interval(time_t sec, time_t usec = 0); + template + Server &set_idle_interval(const std::chrono::duration &duration); + + Server &set_payload_max_length(size_t length); + + bool bind_to_port(const char *host, int port, int socket_flags = 0); + int bind_to_any_port(const char *host, int socket_flags = 0); + bool listen_after_bind(); + + bool listen(const char *host, int port, int socket_flags = 0); + + bool is_running() const; + void stop(); + + std::function new_task_queue; + +protected: + bool process_request(Stream &strm, bool close_connection, + bool &connection_closed, + const std::function &setup_request); + + std::atomic svr_sock_; + size_t keep_alive_max_count_ = CPPHTTPLIB_KEEPALIVE_MAX_COUNT; + time_t keep_alive_timeout_sec_ = CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND; + time_t read_timeout_sec_ = CPPHTTPLIB_READ_TIMEOUT_SECOND; + time_t read_timeout_usec_ = CPPHTTPLIB_READ_TIMEOUT_USECOND; + time_t write_timeout_sec_ = CPPHTTPLIB_WRITE_TIMEOUT_SECOND; + time_t write_timeout_usec_ = CPPHTTPLIB_WRITE_TIMEOUT_USECOND; + time_t idle_interval_sec_ = CPPHTTPLIB_IDLE_INTERVAL_SECOND; + time_t idle_interval_usec_ = CPPHTTPLIB_IDLE_INTERVAL_USECOND; + size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH; + +private: + using Handlers = std::vector>; + using HandlersForContentReader = + std::vector>; + + socket_t create_server_socket(const char *host, int port, int socket_flags, + SocketOptions socket_options) const; + int bind_internal(const char *host, int port, int socket_flags); + bool listen_internal(); + + bool routing(Request &req, Response &res, Stream &strm); + bool handle_file_request(const Request &req, Response &res, + bool head = false); + bool dispatch_request(Request &req, Response &res, const Handlers &handlers); + bool + dispatch_request_for_content_reader(Request &req, Response &res, + ContentReader content_reader, + const HandlersForContentReader &handlers); + + bool parse_request_line(const char *s, Request &req); + void apply_ranges(const Request &req, Response &res, + std::string &content_type, std::string &boundary); + bool write_response(Stream &strm, bool close_connection, const Request &req, + Response &res); + bool write_response_with_content(Stream &strm, bool close_connection, + const Request &req, Response &res); + bool write_response_core(Stream &strm, bool close_connection, + const Request &req, Response &res, + bool need_apply_ranges); + bool write_content_with_provider(Stream &strm, const Request &req, + Response &res, const std::string &boundary, + const std::string &content_type); + bool read_content(Stream &strm, Request &req, Response &res); + bool + read_content_with_content_receiver(Stream &strm, Request &req, Response &res, + ContentReceiver receiver, + MultipartContentHeader multipart_header, + ContentReceiver multipart_receiver); + bool read_content_core(Stream &strm, Request &req, Response &res, + ContentReceiver receiver, + MultipartContentHeader mulitpart_header, + ContentReceiver multipart_receiver); + + virtual bool process_and_close_socket(socket_t sock); + + struct MountPointEntry { + std::string mount_point; + std::string base_dir; + Headers headers; + }; + std::vector base_dirs_; + + std::atomic is_running_; + std::map file_extension_and_mimetype_map_; + Handler file_request_handler_; + Handlers get_handlers_; + Handlers post_handlers_; + HandlersForContentReader post_handlers_for_content_reader_; + Handlers put_handlers_; + HandlersForContentReader put_handlers_for_content_reader_; + Handlers patch_handlers_; + HandlersForContentReader patch_handlers_for_content_reader_; + Handlers delete_handlers_; + HandlersForContentReader delete_handlers_for_content_reader_; + Handlers options_handlers_; + HandlerWithResponse error_handler_; + ExceptionHandler exception_handler_; + HandlerWithResponse pre_routing_handler_; + Handler post_routing_handler_; + Logger logger_; + Expect100ContinueHandler expect_100_continue_handler_; + + int address_family_ = AF_UNSPEC; + bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY; + SocketOptions socket_options_ = default_socket_options; +}; + +enum class Error { + Success = 0, + Unknown, + Connection, + BindIPAddress, + Read, + Write, + ExceedRedirectCount, + Canceled, + SSLConnection, + SSLLoadingCerts, + SSLServerVerification, + UnsupportedMultipartBoundaryChars, + Compression, +}; + +inline std::ostream& operator << (std::ostream& os, const Error& obj) +{ + os << static_cast::type>(obj); + return os; +} + +class Result { +public: + Result(std::unique_ptr &&res, Error err, + Headers &&request_headers = Headers{}) + : res_(std::move(res)), err_(err), + request_headers_(std::move(request_headers)) {} + // Response + operator bool() const { return res_ != nullptr; } + bool operator==(std::nullptr_t) const { return res_ == nullptr; } + bool operator!=(std::nullptr_t) const { return res_ != nullptr; } + const Response &value() const { return *res_; } + Response &value() { return *res_; } + const Response &operator*() const { return *res_; } + Response &operator*() { return *res_; } + const Response *operator->() const { return res_.get(); } + Response *operator->() { return res_.get(); } + + // Error + Error error() const { return err_; } + + // Request Headers + bool has_request_header(const char *key) const; + std::string get_request_header_value(const char *key, size_t id = 0) const; + template + T get_request_header_value(const char *key, size_t id = 0) const; + size_t get_request_header_value_count(const char *key) const; + +private: + std::unique_ptr res_; + Error err_; + Headers request_headers_; +}; + +class ClientImpl { +public: + explicit ClientImpl(const std::string &host); + + explicit ClientImpl(const std::string &host, int port); + + explicit ClientImpl(const std::string &host, int port, + const std::string &client_cert_path, + const std::string &client_key_path); + + virtual ~ClientImpl(); + + virtual bool is_valid() const; + + Result Get(const char *path); + Result Get(const char *path, const Headers &headers); + Result Get(const char *path, Progress progress); + Result Get(const char *path, const Headers &headers, Progress progress); + Result Get(const char *path, ContentReceiver content_receiver); + Result Get(const char *path, const Headers &headers, + ContentReceiver content_receiver); + Result Get(const char *path, ContentReceiver content_receiver, + Progress progress); + Result Get(const char *path, const Headers &headers, + ContentReceiver content_receiver, Progress progress); + Result Get(const char *path, ResponseHandler response_handler, + ContentReceiver content_receiver); + Result Get(const char *path, const Headers &headers, + ResponseHandler response_handler, + ContentReceiver content_receiver); + Result Get(const char *path, ResponseHandler response_handler, + ContentReceiver content_receiver, Progress progress); + Result Get(const char *path, const Headers &headers, + ResponseHandler response_handler, ContentReceiver content_receiver, + Progress progress); + + Result Get(const char *path, const Params ¶ms, const Headers &headers, + Progress progress = nullptr); + Result Get(const char *path, const Params ¶ms, const Headers &headers, + ContentReceiver content_receiver, Progress progress = nullptr); + Result Get(const char *path, const Params ¶ms, const Headers &headers, + ResponseHandler response_handler, ContentReceiver content_receiver, + Progress progress = nullptr); + + Result Head(const char *path); + Result Head(const char *path, const Headers &headers); + + Result Post(const char *path); + Result Post(const char *path, const char *body, size_t content_length, + const char *content_type); + Result Post(const char *path, const Headers &headers, const char *body, + size_t content_length, const char *content_type); + Result Post(const char *path, const std::string &body, + const char *content_type); + Result Post(const char *path, const Headers &headers, const std::string &body, + const char *content_type); + Result Post(const char *path, size_t content_length, + ContentProvider content_provider, const char *content_type); + Result Post(const char *path, ContentProviderWithoutLength content_provider, + const char *content_type); + Result Post(const char *path, const Headers &headers, size_t content_length, + ContentProvider content_provider, const char *content_type); + Result Post(const char *path, const Headers &headers, + ContentProviderWithoutLength content_provider, + const char *content_type); + Result Post(const char *path, const Params ¶ms); + Result Post(const char *path, const Headers &headers, const Params ¶ms); + Result Post(const char *path, const MultipartFormDataItems &items); + Result Post(const char *path, const Headers &headers, + const MultipartFormDataItems &items); + Result Post(const char *path, const Headers &headers, + const MultipartFormDataItems &items, const std::string &boundary); + + Result Put(const char *path); + Result Put(const char *path, const char *body, size_t content_length, + const char *content_type); + Result Put(const char *path, const Headers &headers, const char *body, + size_t content_length, const char *content_type); + Result Put(const char *path, const std::string &body, + const char *content_type); + Result Put(const char *path, const Headers &headers, const std::string &body, + const char *content_type); + Result Put(const char *path, size_t content_length, + ContentProvider content_provider, const char *content_type); + Result Put(const char *path, ContentProviderWithoutLength content_provider, + const char *content_type); + Result Put(const char *path, const Headers &headers, size_t content_length, + ContentProvider content_provider, const char *content_type); + Result Put(const char *path, const Headers &headers, + ContentProviderWithoutLength content_provider, + const char *content_type); + Result Put(const char *path, const Params ¶ms); + Result Put(const char *path, const Headers &headers, const Params ¶ms); + + Result Patch(const char *path); + Result Patch(const char *path, const char *body, size_t content_length, + const char *content_type); + Result Patch(const char *path, const Headers &headers, const char *body, + size_t content_length, const char *content_type); + Result Patch(const char *path, const std::string &body, + const char *content_type); + Result Patch(const char *path, const Headers &headers, + const std::string &body, const char *content_type); + Result Patch(const char *path, size_t content_length, + ContentProvider content_provider, const char *content_type); + Result Patch(const char *path, ContentProviderWithoutLength content_provider, + const char *content_type); + Result Patch(const char *path, const Headers &headers, size_t content_length, + ContentProvider content_provider, const char *content_type); + Result Patch(const char *path, const Headers &headers, + ContentProviderWithoutLength content_provider, + const char *content_type); + + Result Delete(const char *path); + Result Delete(const char *path, const Headers &headers); + Result Delete(const char *path, const char *body, size_t content_length, + const char *content_type); + Result Delete(const char *path, const Headers &headers, const char *body, + size_t content_length, const char *content_type); + Result Delete(const char *path, const std::string &body, + const char *content_type); + Result Delete(const char *path, const Headers &headers, + const std::string &body, const char *content_type); + + Result Options(const char *path); + Result Options(const char *path, const Headers &headers); + + bool send(Request &req, Response &res, Error &error); + Result send(const Request &req); + + size_t is_socket_open() const; + + void stop(); + + void set_default_headers(Headers headers); + + void set_address_family(int family); + void set_tcp_nodelay(bool on); + void set_socket_options(SocketOptions socket_options); + + void set_connection_timeout(time_t sec, time_t usec = 0); + template + void + set_connection_timeout(const std::chrono::duration &duration); + + void set_read_timeout(time_t sec, time_t usec = 0); + template + void set_read_timeout(const std::chrono::duration &duration); + + void set_write_timeout(time_t sec, time_t usec = 0); + template + void set_write_timeout(const std::chrono::duration &duration); + + void set_basic_auth(const char *username, const char *password); + void set_bearer_token_auth(const char *token); +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + void set_digest_auth(const char *username, const char *password); +#endif + + void set_keep_alive(bool on); + void set_follow_location(bool on); + + void set_compress(bool on); + + void set_decompress(bool on); + + void set_interface(const char *intf); + + void set_proxy(const char *host, int port); + void set_proxy_basic_auth(const char *username, const char *password); + void set_proxy_bearer_token_auth(const char *token); +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + void set_proxy_digest_auth(const char *username, const char *password); +#endif + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + void enable_server_certificate_verification(bool enabled); +#endif + + void set_logger(Logger logger); + +protected: + struct Socket { + socket_t sock = INVALID_SOCKET; +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + SSL *ssl = nullptr; +#endif + + bool is_open() const { return sock != INVALID_SOCKET; } + }; + + Result send_(Request &&req); + + virtual bool create_and_connect_socket(Socket &socket, Error &error); + + // All of: + // shutdown_ssl + // shutdown_socket + // close_socket + // should ONLY be called when socket_mutex_ is locked. + // Also, shutdown_ssl and close_socket should also NOT be called concurrently + // with a DIFFERENT thread sending requests using that socket. + virtual void shutdown_ssl(Socket &socket, bool shutdown_gracefully); + void shutdown_socket(Socket &socket); + void close_socket(Socket &socket); + + // Similar to shutdown_ssl and close_socket, this should NOT be called + // concurrently with a DIFFERENT thread sending requests from the socket + void lock_socket_and_shutdown_and_close(); + + bool process_request(Stream &strm, Request &req, Response &res, + bool close_connection, Error &error); + + bool write_content_with_provider(Stream &strm, const Request &req, + Error &error); + + void copy_settings(const ClientImpl &rhs); + + // Socket endoint information + const std::string host_; + const int port_; + const std::string host_and_port_; + + // Current open socket + Socket socket_; + mutable std::mutex socket_mutex_; + std::recursive_mutex request_mutex_; + + // These are all protected under socket_mutex + size_t socket_requests_in_flight_ = 0; + std::thread::id socket_requests_are_from_thread_ = std::thread::id(); + bool socket_should_be_closed_when_request_is_done_ = false; + + // Default headers + Headers default_headers_; + + // Settings + std::string client_cert_path_; + std::string client_key_path_; + + time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND; + time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND; + time_t read_timeout_sec_ = CPPHTTPLIB_READ_TIMEOUT_SECOND; + time_t read_timeout_usec_ = CPPHTTPLIB_READ_TIMEOUT_USECOND; + time_t write_timeout_sec_ = CPPHTTPLIB_WRITE_TIMEOUT_SECOND; + time_t write_timeout_usec_ = CPPHTTPLIB_WRITE_TIMEOUT_USECOND; + + std::string basic_auth_username_; + std::string basic_auth_password_; + std::string bearer_token_auth_token_; +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + std::string digest_auth_username_; + std::string digest_auth_password_; +#endif + + bool keep_alive_ = false; + bool follow_location_ = false; + + int address_family_ = AF_UNSPEC; + bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY; + SocketOptions socket_options_ = nullptr; + + bool compress_ = false; + bool decompress_ = true; + + std::string interface_; + + std::string proxy_host_; + int proxy_port_ = -1; + + std::string proxy_basic_auth_username_; + std::string proxy_basic_auth_password_; + std::string proxy_bearer_token_auth_token_; +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + std::string proxy_digest_auth_username_; + std::string proxy_digest_auth_password_; +#endif + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + bool server_certificate_verification_ = true; +#endif + + Logger logger_; + +private: + socket_t create_client_socket(Error &error) const; + bool read_response_line(Stream &strm, const Request &req, Response &res); + bool write_request(Stream &strm, Request &req, bool close_connection, + Error &error); + bool redirect(Request &req, Response &res, Error &error); + bool handle_request(Stream &strm, Request &req, Response &res, + bool close_connection, Error &error); + std::unique_ptr send_with_content_provider( + Request &req, + // const char *method, const char *path, const Headers &headers, + const char *body, size_t content_length, ContentProvider content_provider, + ContentProviderWithoutLength content_provider_without_length, + const char *content_type, Error &error); + Result send_with_content_provider( + const char *method, const char *path, const Headers &headers, + const char *body, size_t content_length, ContentProvider content_provider, + ContentProviderWithoutLength content_provider_without_length, + const char *content_type); + + virtual bool process_socket(const Socket &socket, + std::function callback); + virtual bool is_ssl() const; +}; + +class Client { +public: + // Universal interface + explicit Client(const char *scheme_host_port); + + explicit Client(const char *scheme_host_port, + const std::string &client_cert_path, + const std::string &client_key_path); + + // HTTP only interface + explicit Client(const std::string &host, int port); + + explicit Client(const std::string &host, int port, + const std::string &client_cert_path, + const std::string &client_key_path); + + ~Client(); + + bool is_valid() const; + + Result Get(const char *path); + Result Get(const char *path, const Headers &headers); + Result Get(const char *path, Progress progress); + Result Get(const char *path, const Headers &headers, Progress progress); + Result Get(const char *path, ContentReceiver content_receiver); + Result Get(const char *path, const Headers &headers, + ContentReceiver content_receiver); + Result Get(const char *path, ContentReceiver content_receiver, + Progress progress); + Result Get(const char *path, const Headers &headers, + ContentReceiver content_receiver, Progress progress); + Result Get(const char *path, ResponseHandler response_handler, + ContentReceiver content_receiver); + Result Get(const char *path, const Headers &headers, + ResponseHandler response_handler, + ContentReceiver content_receiver); + Result Get(const char *path, const Headers &headers, + ResponseHandler response_handler, ContentReceiver content_receiver, + Progress progress); + Result Get(const char *path, ResponseHandler response_handler, + ContentReceiver content_receiver, Progress progress); + + Result Get(const char *path, const Params ¶ms, const Headers &headers, + Progress progress = nullptr); + Result Get(const char *path, const Params ¶ms, const Headers &headers, + ContentReceiver content_receiver, Progress progress = nullptr); + Result Get(const char *path, const Params ¶ms, const Headers &headers, + ResponseHandler response_handler, ContentReceiver content_receiver, + Progress progress = nullptr); + + Result Head(const char *path); + Result Head(const char *path, const Headers &headers); + + Result Post(const char *path); + Result Post(const char *path, const char *body, size_t content_length, + const char *content_type); + Result Post(const char *path, const Headers &headers, const char *body, + size_t content_length, const char *content_type); + Result Post(const char *path, const std::string &body, + const char *content_type); + Result Post(const char *path, const Headers &headers, const std::string &body, + const char *content_type); + Result Post(const char *path, size_t content_length, + ContentProvider content_provider, const char *content_type); + Result Post(const char *path, ContentProviderWithoutLength content_provider, + const char *content_type); + Result Post(const char *path, const Headers &headers, size_t content_length, + ContentProvider content_provider, const char *content_type); + Result Post(const char *path, const Headers &headers, + ContentProviderWithoutLength content_provider, + const char *content_type); + Result Post(const char *path, const Params ¶ms); + Result Post(const char *path, const Headers &headers, const Params ¶ms); + Result Post(const char *path, const MultipartFormDataItems &items); + Result Post(const char *path, const Headers &headers, + const MultipartFormDataItems &items); + Result Post(const char *path, const Headers &headers, + const MultipartFormDataItems &items, const std::string &boundary); + Result Put(const char *path); + Result Put(const char *path, const char *body, size_t content_length, + const char *content_type); + Result Put(const char *path, const Headers &headers, const char *body, + size_t content_length, const char *content_type); + Result Put(const char *path, const std::string &body, + const char *content_type); + Result Put(const char *path, const Headers &headers, const std::string &body, + const char *content_type); + Result Put(const char *path, size_t content_length, + ContentProvider content_provider, const char *content_type); + Result Put(const char *path, ContentProviderWithoutLength content_provider, + const char *content_type); + Result Put(const char *path, const Headers &headers, size_t content_length, + ContentProvider content_provider, const char *content_type); + Result Put(const char *path, const Headers &headers, + ContentProviderWithoutLength content_provider, + const char *content_type); + Result Put(const char *path, const Params ¶ms); + Result Put(const char *path, const Headers &headers, const Params ¶ms); + Result Patch(const char *path); + Result Patch(const char *path, const char *body, size_t content_length, + const char *content_type); + Result Patch(const char *path, const Headers &headers, const char *body, + size_t content_length, const char *content_type); + Result Patch(const char *path, const std::string &body, + const char *content_type); + Result Patch(const char *path, const Headers &headers, + const std::string &body, const char *content_type); + Result Patch(const char *path, size_t content_length, + ContentProvider content_provider, const char *content_type); + Result Patch(const char *path, ContentProviderWithoutLength content_provider, + const char *content_type); + Result Patch(const char *path, const Headers &headers, size_t content_length, + ContentProvider content_provider, const char *content_type); + Result Patch(const char *path, const Headers &headers, + ContentProviderWithoutLength content_provider, + const char *content_type); + + Result Delete(const char *path); + Result Delete(const char *path, const Headers &headers); + Result Delete(const char *path, const char *body, size_t content_length, + const char *content_type); + Result Delete(const char *path, const Headers &headers, const char *body, + size_t content_length, const char *content_type); + Result Delete(const char *path, const std::string &body, + const char *content_type); + Result Delete(const char *path, const Headers &headers, + const std::string &body, const char *content_type); + + Result Options(const char *path); + Result Options(const char *path, const Headers &headers); + + bool send(Request &req, Response &res, Error &error); + Result send(const Request &req); + + size_t is_socket_open() const; + + void stop(); + + void set_default_headers(Headers headers); + + void set_address_family(int family); + void set_tcp_nodelay(bool on); + void set_socket_options(SocketOptions socket_options); + + void set_connection_timeout(time_t sec, time_t usec = 0); + template + void + set_connection_timeout(const std::chrono::duration &duration); + + void set_read_timeout(time_t sec, time_t usec = 0); + template + void set_read_timeout(const std::chrono::duration &duration); + + void set_write_timeout(time_t sec, time_t usec = 0); + template + void set_write_timeout(const std::chrono::duration &duration); + + void set_basic_auth(const char *username, const char *password); + void set_bearer_token_auth(const char *token); +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + void set_digest_auth(const char *username, const char *password); +#endif + + void set_keep_alive(bool on); + void set_follow_location(bool on); + + void set_compress(bool on); + + void set_decompress(bool on); + + void set_interface(const char *intf); + + void set_proxy(const char *host, int port); + void set_proxy_basic_auth(const char *username, const char *password); + void set_proxy_bearer_token_auth(const char *token); +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + void set_proxy_digest_auth(const char *username, const char *password); +#endif + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + void enable_server_certificate_verification(bool enabled); +#endif + + void set_logger(Logger logger); + + // SSL +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + void set_ca_cert_path(const char *ca_cert_file_path, + const char *ca_cert_dir_path = nullptr); + + void set_ca_cert_store(X509_STORE *ca_cert_store); + + long get_openssl_verify_result() const; + + SSL_CTX *ssl_context() const; +#endif + +private: + std::unique_ptr cli_; + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + bool is_ssl_ = false; +#endif +}; + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT +class SSLServer : public Server { +public: + SSLServer(const char *cert_path, const char *private_key_path, + const char *client_ca_cert_file_path = nullptr, + const char *client_ca_cert_dir_path = nullptr); + + SSLServer(X509 *cert, EVP_PKEY *private_key, + X509_STORE *client_ca_cert_store = nullptr); + + ~SSLServer() override; + + bool is_valid() const override; + +private: + bool process_and_close_socket(socket_t sock) override; + + SSL_CTX *ctx_; + std::mutex ctx_mutex_; +}; + +class SSLClient : public ClientImpl { +public: + explicit SSLClient(const std::string &host); + + explicit SSLClient(const std::string &host, int port); + + explicit SSLClient(const std::string &host, int port, + const std::string &client_cert_path, + const std::string &client_key_path); + + explicit SSLClient(const std::string &host, int port, X509 *client_cert, + EVP_PKEY *client_key); + + ~SSLClient() override; + + bool is_valid() const override; + + void set_ca_cert_path(const char *ca_cert_file_path, + const char *ca_cert_dir_path = nullptr); + + void set_ca_cert_store(X509_STORE *ca_cert_store); + + long get_openssl_verify_result() const; + + SSL_CTX *ssl_context() const; + +private: + bool create_and_connect_socket(Socket &socket, Error &error) override; + void shutdown_ssl(Socket &socket, bool shutdown_gracefully) override; + + bool process_socket(const Socket &socket, + std::function callback) override; + bool is_ssl() const override; + + bool connect_with_proxy(Socket &sock, Response &res, bool &success, + Error &error); + bool initialize_ssl(Socket &socket, Error &error); + + bool load_certs(); + + bool verify_host(X509 *server_cert) const; + bool verify_host_with_subject_alt_name(X509 *server_cert) const; + bool verify_host_with_common_name(X509 *server_cert) const; + bool check_host_name(const char *pattern, size_t pattern_len) const; + + SSL_CTX *ctx_; + std::mutex ctx_mutex_; + std::once_flag initialize_cert_; + + std::vector host_components_; + + std::string ca_cert_file_path_; + std::string ca_cert_dir_path_; + long verify_result_ = 0; + + friend class ClientImpl; +}; +#endif + + +} // namespace httplib + +#endif // CPPHTTPLIB_HTTPLIB_H diff --git a/vendor/DPP/include/dpp/integration.h b/vendor/DPP/include/dpp/integration.h new file mode 100644 index 00000000..2e236752 --- /dev/null +++ b/vendor/DPP/include/dpp/integration.h @@ -0,0 +1,132 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include + +namespace dpp { + +/** + * @brief Integration types + */ +enum integration_type { + /// Twitch integration + i_twitch, + /// YouTube integration + i_youtube, + /// Discord integration + i_discord +}; + +/** + * @brief Integration flags + */ +enum integration_flags { + /// Integration enabled + if_enabled = 0b00000001, + /// Integration synching + if_syncing = 0b00000010, + /// Emoji integration + if_emoticons = 0b00000100, + /// Integration revoked + if_revoked = 0b00001000, + /// Kick users when their subscription expires + if_expire_kick = 0b00010000, +}; + +/** + * @brief An application that has been integrated + */ +struct CoreExport integration_app { + /// Inegration id + snowflake id; + /// Name + std::string name; + /// Icon + std::string icon; + /// Description + std::string description; + /// Integration summary + std::string summary; + /// Pointer to bot user + user* bot; +}; + +/** Represents an integration within a dpp::guild */ +class CoreExport integration : public managed { +public: + /** Integration name */ + std::string name; + /** Integration type */ + integration_type type; + /** Integration flags from dpp::integration_flags */ + uint8_t flags; + /** Role id */ + snowflake role_id; + /** User id */ + snowflake user_id; + /** Expiry grace period */ + uint32_t expire_grace_period; + /** Sync time */ + time_t synced_at; + /** Subscriber count */ + uint32_t subscriber_count; + /* Account id */ + std::string account_id; + /* Account name */ + std::string account_name; + /* Integration application */ + integration_app app; + + /** Default constructor */ + integration(); + + /** Default destructor */ + ~integration(); + + /** Read class values from json object + * @param j A json object to read from + * @return A reference to self + */ + integration& fill_from_json(nlohmann::json* j); + + /** Build a json string from this object. + * @return JSON string of the object + */ + std::string build_json() const; + + /** True if emoticons are enabled */ + bool emoticons_enabled() const; + /** True if integration is enabled */ + bool is_enabled() const; + /** True if is syncing */ + bool is_syncing() const; + /** True if has been revoked */ + bool is_revoked() const; + /** True if expiring kicks the user */ + bool expiry_kicks_user() const; +}; + +/** A group of integrations */ +typedef std::unordered_map integration_map; + +}; + diff --git a/vendor/DPP/include/dpp/intents.h b/vendor/DPP/include/dpp/intents.h new file mode 100644 index 00000000..0993bef4 --- /dev/null +++ b/vendor/DPP/include/dpp/intents.h @@ -0,0 +1,71 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once + +namespace dpp { + +/** + * @brief intents are a bitmask of allowed events on your websocket. + * + * Some of these are known as Privileged intents (GUILD_MEMBERS and GUILD_PRESENCES) + * and require verification of a bot over 100 servers by discord via submission of + * your real life ID. + */ +enum intents { + /// Intent for receipt of guild information + i_guilds = (1 << 0), + /// Intent for receipt of guild members + i_guild_members = (1 << 1), + /// Intent for receipt of guild bans + i_guild_bans = (1 << 2), + /// Intent for receipt of guild emojis + i_guild_emojis = (1 << 3), + /// Intent for receipt of guild integrations + i_guild_integrations = (1 << 4), + /// Intent for receipt of guild webhooks + i_guild_webhooks = (1 << 5), + /// Intent for receipt of guild invites + i_guild_invites = (1 << 6), + /// Intent for receipt of guild voice states + i_guild_voice_states = (1 << 7), + /// Intent for receipt of guild presences + i_guild_presences = (1 << 8), + /// Intent for receipt of guild messages + i_guild_messages = (1 << 9), + /// Intent for receipt of guild message reactions + i_guild_message_reactions = (1 << 10), + /// Intent for receipt of guild message typing notifications + i_guild_message_typing = (1 << 11), + /// Intent for receipt of direct messages (DMs) + i_direct_messages = (1 << 12), + /// Intent for receipt of direct message reactions + i_direct_message_reactions = (1 << 13), + /// Intent for receipt of direct message typing notifications + i_direct_message_typing = (1 << 14), + /// Default D++ intents (all non-privileged intents) + i_default_intents = dpp::i_guilds | dpp::i_guild_bans | dpp::i_guild_emojis | dpp::i_guild_integrations | dpp::i_guild_webhooks | dpp::i_guild_invites | dpp::i_guild_voice_states | dpp::i_guild_messages | dpp::i_guild_message_reactions | dpp::i_guild_message_typing | dpp::i_direct_messages | dpp::i_direct_message_typing | dpp::i_direct_message_reactions, + // Privileged intents requiring ID + i_privileged_intents = dpp::i_guild_members | dpp::i_guild_presences, + // Every single intent + i_all_intents = dpp::i_default_intents | dpp::i_privileged_intents +}; + +}; diff --git a/vendor/DPP/include/dpp/invite.h b/vendor/DPP/include/dpp/invite.h new file mode 100644 index 00000000..d2725746 --- /dev/null +++ b/vendor/DPP/include/dpp/invite.h @@ -0,0 +1,94 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include + +namespace dpp { + +/** + * @brief Represents an invite to a discord guild or channel + */ +class CoreExport invite { +public: + /** Invite code + */ + std::string code; + /** Guild for the invite + */ + snowflake guild_id; + /** Channel id for invite + */ + snowflake channel_id; + /** User ID of invite creator + */ + snowflake inviter_id; + /** Target user ID of invite, for invites sent via DM + */ + snowflake target_user_id; + /** Target user type (generally this is always 1, "stream") + */ + uint8_t target_user_type; + /** Approximate number of online users + */ + uint32_t approximate_presence_count; + /** Approximate total users online and offline + */ + uint32_t approximate_member_count; + /** Maximum age of invite + */ + uint32_t max_age; + /** Maximum number of uses + */ + uint32_t max_uses; + /** True if a temporary invite which grants access for a limited time + */ + bool temporary; + /** True if this invite should not replace or "attach to" similar invites + */ + bool unique; + + /** Constructor + */ + invite(); + + /** Destructor + */ + ~invite(); + + /** Read class values from json object + * @param j A json object to read from + * @return A reference to self + */ + invite& fill_from_json(nlohmann::json* j); + + /** Build JSON from this object. + * @return The JSON text of the invite + */ + std::string build_json() const; + +}; + +/** A container of invites */ +typedef std::unordered_map invite_map; + +}; diff --git a/vendor/DPP/include/dpp/json_fwd.hpp b/vendor/DPP/include/dpp/json_fwd.hpp new file mode 100644 index 00000000..332227c1 --- /dev/null +++ b/vendor/DPP/include/dpp/json_fwd.hpp @@ -0,0 +1,78 @@ +#ifndef INCLUDE_NLOHMANN_JSON_FWD_HPP_ +#define INCLUDE_NLOHMANN_JSON_FWD_HPP_ + +#include // int64_t, uint64_t +#include // map +#include // allocator +#include // string +#include // vector + +/*! +@brief namespace for Niels Lohmann +@see https://github.com/nlohmann +@since version 1.0.0 +*/ +namespace nlohmann +{ +/*! +@brief default JSONSerializer template argument + +This serializer ignores the template arguments and uses ADL +([argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl)) +for serialization. +*/ +template +struct adl_serializer; + +template class ObjectType = + std::map, + template class ArrayType = std::vector, + class StringType = std::string, class BooleanType = bool, + class NumberIntegerType = std::int64_t, + class NumberUnsignedType = std::uint64_t, + class NumberFloatType = double, + template class AllocatorType = std::allocator, + template class JSONSerializer = + adl_serializer, + class BinaryType = std::vector> +class basic_json; + +/*! +@brief JSON Pointer + +A JSON pointer defines a string syntax for identifying a specific value +within a JSON document. It can be used with functions `at` and +`operator[]`. Furthermore, JSON pointers are the base for JSON patches. + +@sa [RFC 6901](https://tools.ietf.org/html/rfc6901) + +@since version 2.0.0 +*/ +template +class json_pointer; + +/*! +@brief default JSON class + +This type is the default specialization of the @ref basic_json class which +uses the standard template types. + +@since version 1.0.0 +*/ +using json = basic_json<>; + +template +struct ordered_map; + +/*! +@brief ordered JSON class + +This type preserves the insertion order of object keys. + +@since version 3.9.0 +*/ +using ordered_json = basic_json; + +} // namespace nlohmann + +#endif // INCLUDE_NLOHMANN_JSON_FWD_HPP_ diff --git a/vendor/DPP/include/dpp/message.h b/vendor/DPP/include/dpp/message.h new file mode 100644 index 00000000..7621cac2 --- /dev/null +++ b/vendor/DPP/include/dpp/message.h @@ -0,0 +1,1111 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief Represents the type of a component + */ +enum component_type : uint8_t { + /// Action row, a container for other components + cot_action_row = 1, + /// Clickable button + cot_button = 2, + /// Select menu + cot_selectmenu = 3 +}; + +/** + * @brief Represents the style of a button + */ +enum component_style : uint8_t { + /// Blurple + cos_primary = 1, + /// Grey + cos_secondary, + /// Green + cos_success, + /// Red + cos_danger, + /// An external hyperlink to a website + cos_link +}; + +struct CoreExport select_option { + std::string label; + std::string value; + std::string description; + bool is_default; + /** Emoji definition. To set an emoji on your button + * you must set one of either the name or id fields. + * The easiest way is to use the component::set_emoji + * method. + */ + struct inner_select_emoji { + /** Set the name field to the name of the emoji. + * For built in unicode emojis, set this to the + * actual unicode value of the emoji e.g. "😄" + * and not for example ":smile:" + */ + std::string name; + /** The emoji ID value for emojis that are custom + * ones belonging to a guild. The same rules apply + * as with other emojis, that the bot must be on + * the guild where the emoji resides and it must + * be available for use (e.g. not disabled due to + * lack of boosts etc) + */ + dpp::snowflake id = 0; + /** True if the emoji is animated. Only applies to + * custom emojis. + */ + bool animated = false; + } emoji; + + select_option(); + + select_option(const std::string &label, const std::string &value, const std::string &description = ""); + + select_option& set_label(const std::string &l); + + select_option& set_value(const std::string &v); + + select_option& set_description(const std::string &d); + + select_option& set_emoji(const std::string &n, dpp::snowflake id = 0, bool animated = false); + + select_option& set_default(bool def); + + select_option& set_animated(bool anim); +}; + +/** + * @brief Represents the component object. + * A component is a clickable button or drop down list + * within a discord message, where the buttons emit + * on_button_click events when the user interacts with + * them. + * + * You should generally define one component object and + * then insert one or more additional components into it + * using component::add_component(), so that the parent + * object is an action row and the child objects are buttons. + * + * @note At present this only works for whitelisted + * guilds. The beta is **closed**. When this feature is + * released, then the functionality will work correctly. + */ +class CoreExport component { +public: + /** Component type, either a button or action row + */ + component_type type; + + /** Sub commponents, buttons on an action row + */ + std::vector components; + + /** Component label (for buttons). + * Maximum of 80 characters. + */ + std::string label; + + /** Component style (for buttons) + */ + component_style style; + + /** Component id (for buttons). + * Maximum of 100 characters. + */ + std::string custom_id; + + /** URL for link types (dpp::cos_link). + * Maximum of 512 characters. + */ + std::string url; + + /** Placeholder text for select menus + */ + std::string placeholder; + + /** Minimum number of selectable values for a select menu. + * -1 to not set this + */ + int32_t min_values; + + /** Maximum number of selectable values for a select menu. + * -1 to not set this. + */ + int32_t max_values; + + /** Select options for select menus + */ + std::vector options; + + /** Disabled flag (for buttons) + */ + bool disabled; + + /** Emoji definition. To set an emoji on your button + * you must set one of either the name or id fields. + * The easiest way is to use the component::set_emoji + * method. + */ + struct inner_emoji { + /** Set the name field to the name of the emoji. + * For built in unicode emojis, set this to the + * actual unicode value of the emoji e.g. "😄" + * and not for example ":smile:" + */ + std::string name; + /** The emoji ID value for emojis that are custom + * ones belonging to a guild. The same rules apply + * as with other emojis, that the bot must be on + * the guild where the emoji resides and it must + * be available for use (e.g. not disabled due to + * lack of boosts etc) + */ + dpp::snowflake id; + /** True if the emoji is animated. Only applies to + * custom emojis. + */ + bool animated; + } emoji; + + /** Constructor + */ + component(); + + /** Destructor + */ + ~component() = default; + + /** + * @brief Set the type of the component. Button components + * (type dpp::cot_button) should always be contained within + * an action row (type dpp::cot_action_row). As described + * below, many of the other methods automatically set this + * to the correct type so usually you should not need to + * manually call component::set_type(). + * + * @param ct The component type + * @return component& reference to self + */ + component& set_type(component_type ct); + + /** + * @brief Set the label of the component, e.g. button text. + * For action rows, this field is ignored. Setting the + * label will auto-set the type to dpp::cot_button. + * + * @param label Label text to set + * @return component& Reference to self + */ + component& set_label(const std::string &label); + + /** + * @brief Set the url for dpp::cos_link types. + * Calling this function sets the style to dpp::cos_link + * and the type to dpp::cot_button. + * + * @param url URL to set, maximum length of 512 characters + * @return component& reference to self. + */ + component& set_url(const std::string &url); + + /** + * @brief Set the style of the component, e.g. button colour. + * For action rows, this field is ignored. Setting the + * style will auto-set the type to dpp::cot_button. + * + * @param cs Component style to set + * @return component& reference to self + */ + component& set_style(component_style cs); + + /** + * @brief Set the id of the component. + * For action rows, this field is ignored. Setting the + * id will auto-set the type to dpp::cot_button. + * + * @param id Custom ID string to set. This ID will be sent + * for any on_button_click events related to the button. + * @return component& Reference to self + */ + component& set_id(const std::string &id); + + /** + * @brief Set the component to disabled. + * Defaults to false on all created components. + * + * @param disable True to disable, false to disable. + * @return component& + */ + component& set_disabled(bool disable); + + + component& set_placeholder(const std::string &placeholder); + + component& set_min_values(uint32_t min_values); + + component& set_max_values(uint32_t max_values); + + component& add_select_option(const select_option &option); + + /** + * @brief Add a sub-component, only valid for action rows. + * Adding subcomponents to a component will automatically + * set this component's type to dpp::cot_action_row. + * + * @param c The sub-component to add + * @return component& reference to self + */ + component& add_component(const component& c); + + /** + * @brief Set the emoji of the current sub-component. + * Only valid for buttons. Adding an emoji to a component + * will automatically set this components type to + * dpp::cot_button. One or both of name and id must be set. + * For a built in unicode emoji, you only need set name, + * and should set it to a unicode character e.g. "😄". + * For custom emojis, set the name to the name of the emoji + * on the guild, and the id to the emoji's ID. + * Setting the animated boolean is only valid for custom + * emojis. + * + * @param name Emoji name, or unicode character to use + * @param id Emoji id, for custom emojis only. + * @param animated True if the custom emoji is animated. + * @return component& Reference to self + */ + component& set_emoji(const std::string& name, dpp::snowflake id = 0, bool animated = false); + + /** Read class values from json object + * @param j A json object to read from + * @return A reference to self + */ + component& fill_from_json(nlohmann::json* j); + + /** Build JSON from this object. + * @return The JSON text of the invite + */ + std::string build_json() const; + +}; + +/** + * @brief A footer in a dpp::embed + */ +struct CoreExport embed_footer { + /** Footer text */ + std::string text; + /** Footer icon url */ + std::string icon_url; + /** Proxied icon url */ + std::string proxy_url; + + /** Set footer's text. Returns footer itself so these methods may be "chained" + * @param t string to set as footer text + * @return A reference to self + */ + embed_footer& set_text(const std::string& t); + + /** Set footer's icon url. Returns footer itself so these methods may be "chained" + * @param i url to set as footer icon url + * @return A reference to self + */ + embed_footer& set_icon(const std::string& i); + + /** Set footer's proxied icon url. Returns footer itself so these methods may be "chained" + * @param p url to set as footer proxied icon url + * @return A reference to self + */ + embed_footer& set_proxy(const std::string& p); +}; + +/** + * @brief An video, image or thumbnail in a dpp::embed + */ +struct CoreExport embed_image { + /** URL to image or video */ + std::string url; + /** Proxied image url */ + std::string proxy_url; + /** Height (calculated by discord) */ + std::string height; + /** Width (calculated by discord) */ + std::string width; +}; + +/** + * @brief Embed provider in a dpp::embed. Received from discord but cannot be sent + */ +struct CoreExport embed_provider { + /** Provider name */ + std::string name; + /** Provider URL */ + std::string url; +}; + +/** + * @brief Author within a dpp::embed object + */ +struct CoreExport embed_author { + /** Author name */ + std::string name; + /** Author url */ + std::string url; + /** Author icon url */ + std::string icon_url; + /** Proxied icon url */ + std::string proxy_icon_url; +}; + +/** + * @brief A dpp::embed may contain zero or more fields + */ +struct CoreExport embed_field { + /** Name of field */ + std::string name; + /** Value of field (max length 1000) */ + std::string value; + /** True if the field is to be displayed inline */ + bool is_inline; +}; + +/** + * @brief A rich embed for display within a dpp::message + */ +struct CoreExport embed { + /** Optional: title of embed */ + std::string title; + /** Optional: type of embed (always "rich" for webhook embeds) */ + std::string type; + /** Optional: description of embed */ + std::string description; + /** Optional: url of embed */ + std::string url; + /** Optional: timestamp of embed content */ + time_t timestamp; + /** Optional: color code of the embed */ + uint32_t color; + /** Optional: footer information */ + std::optional footer; + /** Optional: image information */ + std::optional image; + /** Optional: thumbnail information */ + std::optional thumbnail; + /** Optional: video information (can't send these) */ + std::optional video; + /** Optional: provider information (can't send these) */ + std::optional provider; + /** Optional: author information */ + std::optional author; + /** Optional: fields information */ + std::vector fields; + + /** Constructor */ + embed(); + + /** Constructor to build embed from json object + * @param j JSON to read content from + */ + embed(nlohmann::json* j); + + /** Destructor */ + ~embed(); + + /** Set embed title. Returns the embed itself so these method calls may be "chained" + * @param text The text of the title + * @return A reference to self + */ + embed& set_title(const std::string &text); + + /** Set embed description. Returns the embed itself so these method calls may be "chained" + * @param text The text of the title + * @return A reference to self + */ + embed& set_description(const std::string &text); + + /** + * @brief Set the footer of the embed + * + * @param f the footer to set + * @return embed& a reference to self + */ + embed& set_footer(const embed_footer& f); + + /** Set embed colour. Returns the embed itself so these method calls may be "chained" + * @param col The colour of the embed + * @return A reference to self + */ + embed& set_color(uint32_t col); + + /** Set embed url. Returns the embed itself so these method calls may be "chained" + * @param url the url of the embed + * @return A reference to self + */ + embed& set_url(const std::string &url); + + /** Add an embed field. Returns the embed itself so these method calls may be "chained" + * @param name The name of the field + * @param value The value of the field (max length 1000) + * @param is_inline Wether or not to display the field 'inline' or on its own line + * @return A reference to self + */ + embed& add_field(const std::string& name, const std::string &value, bool is_inline = false); + + /** Set embed author. Returns the embed itself so these method calls may be "chained" + * @param a The author to set + * @return A reference to self + */ + embed& set_author(const dpp::embed_author& a); + + /** Set embed author. Returns the embed itself so these method calls may be "chained" + * @param name The name of the author + * @param url The url of the author + * @param icon_url The icon URL of the author + * @return A reference to self + */ + embed& set_author(const std::string& name, const std::string& url, const std::string& icon_url); + + /** Set embed provider. Returns the embed itself so these method calls may be "chained" + * @param name The provider name + * @param url The provider url + * @return A reference to self + */ + embed& set_provider(const std::string& name, const std::string& url); + + /** Set embed image. Returns the embed itself so these method calls may be "chained" + * @param url The embed image URL + * @return A reference to self + */ + embed& set_image(const std::string& url); + + /** Set embed video. Returns the embed itself so these method calls may be "chained" + * @param url The embed video url + * @return A reference to self + */ + embed& set_video(const std::string& url); + + /** Set embed thumbnail. Returns the embed itself so these method calls may be "chained" + * @param url The embed thumbnail url + * @return A reference to self + */ + embed& set_thumbnail(const std::string& url); +}; + +/** + * @brief Represets a reaction to a dpp::message + */ +struct CoreExport reaction { + /** Number of times this reaction has been added */ + uint32_t count; + /** Reaction was from the bot's id */ + bool me; + /** ID of emoji for reaction */ + snowflake emoji_id; + /** Name of emoji, if applicable */ + std::string emoji_name; + + /** + * @brief Constructs a new reaction object. + */ + reaction(); + + /** + * @brief Constructs a new reaction object from a JSON object. + * @param j The JSON to read data from + */ + reaction(nlohmann::json* j); + + /** + * @brief Destructs the reaction object. + */ + ~reaction() = default; +}; + +/** + * @brief Represents an attachment in a dpp::message + */ +struct CoreExport attachment { + /** ID of attachment */ + snowflake id; + /** Size of the attachment in bytes */ + uint32_t size; + /** File name of the attachment */ + std::string filename; + /** URL which points to the attachment */ + std::string url; + /** Proxied URL which points to the attachment */ + std::string proxy_url; + /** Width of the attachment, if applicable */ + uint32_t width; + /** Height of the attachment, if applicable */ + uint32_t height; + /** MIME type of the attachment, if applicable */ + std::string content_type; + + /** + * @brief Constructs a new attachment object. + */ + attachment(); + + /** + * @brief Constructs a new attachment object from a JSON object. + * @param j JSON to read information from + */ + attachment(nlohmann::json* j); + + /** + * @brief Destructs the attachment object. + */ + ~attachment() = default; +}; + +enum sticker_type : uint8_t { + /// Nitro pack sticker + st_standard = 1, + /// Guild sticker + st_guild = 2 +}; + +/** + * @brief The file format (png, apng, lottie) of a sticker + */ +enum sticker_format : uint8_t { + sf_png = 1, + sf_apng = 2, + sf_lottie = 3 +}; + +/** + * @brief Represents stickers received in messages + */ +struct CoreExport sticker { + /** @brief The ID of the sticker + */ + snowflake id; + /** Optional: for standard stickers, id of the pack the sticker is from + */ + snowflake pack_id; + /** The name of the sticker */ + std::string name; + /// description of the sticker (may be empty) + std::string description; + /** for guild stickers, the Discord name of a unicode emoji representing the sticker's expression. + * for standard stickers, a comma-separated list of related expressions. + */ + std::string tags; + /** + * @brief Asset ID + * @deprecated now an empty string but still sent by discord. + * While discord still send this empty string value we will still have a field + * here in the library. + */ + std::string asset; + /** The type of sticker */ + sticker_type type; + /// type of sticker format + sticker_format format_type; + /// Optional: whether this guild sticker can be used, may be false due to loss of Server Boosts + bool available; + /// Optional: id of the guild that owns this sticker + snowflake guild_id; + /// Optional: the user that uploaded the guild sticker + user sticker_user; + /// Optional: the standard sticker's sort order within its pack + uint8_t sort_value; + /** Name of file to upload (when adding or editing a sticker) */ + std::string filename; + /** File content to upload (raw binary) */ + std::string filecontent; + + /** + * @brief Construct a new sticker object + */ + sticker(); + + /** Read class values from json object + * @param j A json object to read from + * @return A reference to self + */ + sticker& fill_from_json(nlohmann::json* j); + + /** Build JSON from this object. + * @param with_id True if the ID is to be set in the JSON structure + * @return The JSON text of the invite + */ + std::string build_json(bool with_id = true) const; + + /** + * @brief Set the filename + * + * @param fn filename + * @return message& reference to self + */ + sticker& set_filename(const std::string &fn); + + /** + * @brief Set the file content + * + * @param fc raw file content contained in std::string + * @return message& reference to self + */ + sticker& set_file_content(const std::string &fc); + +}; + +struct CoreExport sticker_pack { + /// id of the sticker pack + snowflake id; + /// the stickers in the pack + std::map stickers; + /// name of the sticker pack + std::string name; + /// id of the pack's SKU + snowflake sku_id; + /// Optional: id of a sticker in the pack which is shown as the pack's icon + snowflake cover_sticker_id; + /// description of the sticker pack + std::string description; + /// id of the sticker pack's banner image + snowflake banner_asset_id; + + /** + * @brief Construct a new sticker pack object + */ + sticker_pack(); + + /** Read class values from json object + * @param j A json object to read from + * @return A reference to self + */ + sticker_pack& fill_from_json(nlohmann::json* j); + + /** Build JSON from this object. + * @param with_id True if the ID is to be set in the JSON structure + * @return The JSON text of the invite + */ + std::string build_json(bool with_id = true) const; + +}; + +/** + * @brief Bitmask flags for a dpp::message + */ +enum message_flags { + /// this message has been published to subscribed channels (via Channel Following) + m_crossposted = 1 << 0, + /// this message originated from a message in another channel (via Channel Following) + m_is_crosspost = 1 << 1, + /// do not include any embeds when serializing this message + m_supress_embeds = 1 << 2, + /// the source message for this crosspost has been deleted (via Channel Following) + m_source_message_deleted = 1 << 3, + /// this message came from the urgent message system + m_urgent = 1 << 4, + /// this message is only visible to the user who invoked the Interaction + m_ephemeral = 1 << 6, + /// this message is an Interaction Response and the bot is "thinking" + m_loading = 1 << 7 +}; + +/** + * @brief Mesage types for dpp::message::type + */ +enum message_type { + /// Default + mt_default = 0, + /// Add recipient + mt_recipient_add = 1, + /// Remove recipient + mt_recipient_remove = 2, + /// Call + mt_call = 3, + /// Channel name change + mt_channel_name_change = 4, + /// Channel icon change + mt_channel_icon_change = 5, + /// Message pinned + mt_channel_pinned_message = 6, + /// Member joined + mt_guild_member_join = 7, + /// Boost + mt_user_premium_guild_subscription = 8, + /// Boost level 1 + mt_user_premium_guild_subscription_tier_1 = 9, + /// Boost level 2 + mt_user_premium_guild_subscription_tier_2 = 10, + /// Boost level 3 + mt_user_premium_guild_subscription_tier_3 = 11, + /// Follow channel + mt_channel_follow_add = 12, + /// Disqualified from discovery + mt_guild_discovery_disqualified = 14, + /// Re-qualified for discovery + mt_guild_discovery_requalified = 15, + /// Discovery grace period warning 1 + mt_guild_discovery_grace_period_initial_warning = 16, + /// Discovery grace period warning 2 + mt_guild_discovery_grace_period_final_warning = 17, + /// Thread Created + mt_thread_created = 18, + /// Reply + mt_reply = 19, + /// Application command + mt_application_command = 20, + /// Thread starter message + mt_thread_starter_message = 21, + /// Invite reminder + mt_guild_invite_reminder = 22 +}; + +enum cache_policy_setting_t { + /** + * @brief request aggressively on seeing new guilds, and also store missing data from messages. + * This is the default behaviour. + */ + cp_aggressive = 0, + /** + * @brief only cache when there is relavent activity, e.g. a message to the bot. + */ + cp_lazy = 1, + /** + * @brief Don't cache anything. Fill details when we see them. + * (NOT IMPLEMENTED YET) + */ + cp_none = 2 +}; + +/** + * @brief Represents the caching policy of the cluster. + * + * Channels and guilds are always cached as these caches are used + * interally by the library. The memory usage of these is minimal. + * + * All default to 'aggressive' which means to actively attempt to cache, + * going out of the way to fill the caches completely. On large bots this + * can take a LOT of RAM. + */ +struct CoreExport cache_policy_t { + /** + * @brief Caching policy for users and guild members + */ + cache_policy_setting_t user_policy = cp_aggressive; + + /** + * @brief Caching policy for emojis + */ + cache_policy_setting_t emoji_policy = cp_aggressive; + + /** + * @brief Caching policy for roles + */ + cache_policy_setting_t role_policy = cp_aggressive; +}; + +/** + * @brief Represents messages sent and received on Discord + */ +struct CoreExport message { + /** id of the message */ + snowflake id; + /** id of the channel the message was sent in */ + snowflake channel_id; + /** Optional: id of the guild the message was sent in */ + snowflake guild_id; + /** the author of this message (not guaranteed to be a valid user) */ + user* author; + /** Optional: member properties for this message's author */ + guild_member member; + /** contents of the message */ + std::string content; + /** message components */ + std::vector components; + /** when this message was sent */ + time_t sent; + /** when this message was edited (may be 0 if never edited) */ + time_t edited; + /** whether this was a TTS message */ + bool tts; + /** whether this message mentions everyone */ + bool mention_everyone; + /** users specifically mentioned in the message */ + std::vector mentions; + /** roles specifically mentioned in this message */ + std::vector mention_roles; + /** Optional: channels specifically mentioned in this message */ + std::vector mention_channels; + /** any attached files */ + std::vector attachments; + /** zero or more dpp::embed objects */ + std::vector embeds; + /** Optional: reactions to the message */ + std::vector reactions; + /** Optional: used for validating a message was sent */ + std::string nonce; + /** whether this message is pinned */ + bool pinned; + /** Optional: if the message is generated by a webhook, its id will be here otherwise the field will be 0 */ + snowflake webhook_id; + /** Flags */ + uint8_t flags; + /** Stickers */ + std::vector stickers; + + /** Name of file to upload (for use server-side in discord's url) */ + std::string filename; + + /** File content to upload (raw binary) */ + std::string filecontent; + + /** Message type */ + uint8_t type; + + /** Self allocated user for caching being off */ + user self_author; + + struct message_ref { + /// id of the originating message + snowflake message_id; + /// id of the originating message's channel + snowflake channel_id; + /// id of the originating message's guild + snowflake guild_id; + /// when sending, whether to error if the referenced message doesn't exist instead of sending as a normal (non-reply) message, default true + bool fail_if_not_exists; + } message_reference; + + struct message_interaction_struct{ + // id of the interaction + snowflake id; + // type of interaction + uint8_t type; + // name of the application command + std::string name; + // the user who invoked the interaction + user usr; + } interaction; + + struct allowed_ref { + bool parse_users; + bool parse_everyone; + bool parse_roles; + bool replied_user; + std::vector users; + std::vector roles; + } allowed_mentions; + + /** + * @brief Construct a new message object + */ + message(); + + /** + * @brief Destroy the message object + */ + ~message(); + + /** + * @brief Construct a new message object with a channel and content + * + * @param channel_id The channel to send the message to + * @param content The content of the message + * @param type The message type to create + */ + message(snowflake channel_id, const std::string &content, message_type type = mt_default); + + /** + * @brief Construct a new message object with a channel and content + * + * @param channel_id The channel to send the message to + * @param _embed An embed to send + */ + message(snowflake channel_id, const embed & _embed); + + /** + * @brief Construct a new message object with content + * + * @param content The content of the message + * @param type The message type to create + */ + message(const std::string &content, message_type type = mt_default); + + /** + * @brief Set the original message reference for replies/crossposts + * + * @param _message_id message id to reply to + * @param _guild_id guild id to reply to (optional) + * @param _channel_id channel id to reply to (optional) + * @param fail_if_not_exists true if the message send should fail if these values are invalid (optional) + * @return message& reference to self + */ + message& set_reference(snowflake _message_id, snowflake _guild_id = 0, snowflake _channel_id = 0, bool fail_if_not_exists = false); + + /** + * @brief Set the allowed mentions object for pings on the message + * + * @param _parse_users wether or not to parse users in the message content or embeds + * @param _parse_roles wether or not to parse roles in the message content or embeds + * @param _parse_everyone wether or not to parse everyone/here in the message content or embeds + * @param _replied_user if set to true and this is a reply, then ping the user we reply to + * @param users list of user ids to allow pings for + * @param roles list of role ids to allow pings for + * @return message& reference to self + */ + message& set_allowed_mentions(bool _parse_users, bool _parse_roles, bool _parse_everyone, bool _replied_user, const std::vector &users, const std::vector &roles); + + /** Fill this object from json. + * @param j JSON object to fill from + * @param cp Cache policy for user records, wether or not we cache users when a message is received + * @return A reference to self + */ + message& fill_from_json(nlohmann::json* j, cache_policy_t cp = {cp_aggressive, cp_aggressive, cp_aggressive}); + + /** Build JSON from this object. + * @param with_id True if the ID is to be included in the built JSON + * @return The JSON text of the message + */ + std::string build_json(bool with_id = false, bool is_interaction_response = false) const; + + /** + * @brief Returns true if the message was crossposted to other servers + * + * @return true if crossposted + */ + bool is_crossposted() const; + + /** + * @brief Returns true if posted from other servers news channel via webhook + * + * @return true if posted from other server + */ + bool is_crosspost() const; + + /** + * @brief True if embeds have been removed + * + * @return true if embeds removed + */ + bool supress_embeds() const; + + /** + * @brief True if source message was deleted + * + * @return true if source message deleted + */ + bool is_source_message_deleted() const; + + /** + * @brief True if urgent + * + * @return true if urgent + */ + bool is_urgent() const; + + /** + * @brief True if ephemeral (visible only to issuer of a slash command) + * + * @return true if ephemeral + */ + bool is_ephemeral() const; + + /** + * @brief True if loading + * + * @return true if loading + */ + bool is_loading() const; + + /** + * @brief Add a component (button) to message + * + * @param c component to add + * @return message& reference to self + */ + message& add_component(const component& c); + + /** + * @brief Add an embed to message + * + * @param e embed to add + * @return message& reference to self + */ + message& add_embed(const embed& e); + + /** + * @brief Set the flags + * + * @param f flags to set + * @return message& reference to self + */ + message& set_flags(uint8_t f); + + /** + * @brief Set the message type + * + * @param t type to set + * @return message& reference to self + */ + message& set_type(message_type t); + + /** + * @brief Set the filename + * + * @param fn filename + * @return message& reference to self + */ + message& set_filename(const std::string &fn); + + /** + * @brief Set the file content + * + * @param fc raw file content contained in std::string + * @return message& reference to self + */ + message& set_file_content(const std::string &fc); + + /** + * @brief Set the message content + * + * @param c message content + * @return message& reference to self + */ + message& set_content(const std::string &c); +}; + +/** A group of messages */ +typedef std::unordered_map message_map; + +/** A group of stickers */ +typedef std::unordered_map sticker_map; + +/** A group of sticker packs */ +typedef std::unordered_map sticker_pack_map; + +}; diff --git a/vendor/DPP/include/dpp/nlohmann/json.hpp b/vendor/DPP/include/dpp/nlohmann/json.hpp new file mode 100644 index 00000000..dfb18190 --- /dev/null +++ b/vendor/DPP/include/dpp/nlohmann/json.hpp @@ -0,0 +1,26137 @@ +/* + __ _____ _____ _____ + __| | __| | | | JSON for Modern C++ +| | |__ | | | | | | version 3.9.1 +|_____|_____|_____|_|___| https://github.com/nlohmann/json + +Licensed under the MIT License . +SPDX-License-Identifier: MIT +Copyright (c) 2013-2019 Niels Lohmann . + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + +#ifndef INCLUDE_NLOHMANN_JSON_HPP_ +#define INCLUDE_NLOHMANN_JSON_HPP_ + +#define NLOHMANN_JSON_VERSION_MAJOR 3 +#define NLOHMANN_JSON_VERSION_MINOR 9 +#define NLOHMANN_JSON_VERSION_PATCH 1 + +#include // all_of, find, for_each +#include // nullptr_t, ptrdiff_t, size_t +#include // hash, less +#include // initializer_list +#include // istream, ostream +#include // random_access_iterator_tag +#include // unique_ptr +#include // accumulate +#include // string, stoi, to_string +#include // declval, forward, move, pair, swap +#include // vector + +// #include + + +#include +#include + +// #include + + +#include // transform +#include // array +#include // forward_list +#include // inserter, front_inserter, end +#include // map +#include // string +#include // tuple, make_tuple +#include // is_arithmetic, is_same, is_enum, underlying_type, is_convertible +#include // unordered_map +#include // pair, declval +#include // valarray + +// #include + + +#include // exception +#include // runtime_error +#include // to_string +#include // vector + +// #include + + +#include // array +#include // size_t +#include // uint8_t +#include // string + +namespace nlohmann +{ +namespace detail +{ +/////////////////////////// +// JSON type enumeration // +/////////////////////////// + +/*! +@brief the JSON type enumeration + +This enumeration collects the different JSON types. It is internally used to +distinguish the stored values, and the functions @ref basic_json::is_null(), +@ref basic_json::is_object(), @ref basic_json::is_array(), +@ref basic_json::is_string(), @ref basic_json::is_boolean(), +@ref basic_json::is_number() (with @ref basic_json::is_number_integer(), +@ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()), +@ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and +@ref basic_json::is_structured() rely on it. + +@note There are three enumeration entries (number_integer, number_unsigned, and +number_float), because the library distinguishes these three types for numbers: +@ref basic_json::number_unsigned_t is used for unsigned integers, +@ref basic_json::number_integer_t is used for signed integers, and +@ref basic_json::number_float_t is used for floating-point numbers or to +approximate integers which do not fit in the limits of their respective type. + +@sa see @ref basic_json::basic_json(const value_t value_type) -- create a JSON +value with the default value for a given type + +@since version 1.0.0 +*/ +enum class value_t : std::uint8_t +{ + null, ///< null value + object, ///< object (unordered set of name/value pairs) + array, ///< array (ordered collection of values) + string, ///< string value + boolean, ///< boolean value + number_integer, ///< number value (signed integer) + number_unsigned, ///< number value (unsigned integer) + number_float, ///< number value (floating-point) + binary, ///< binary array (ordered collection of bytes) + discarded ///< discarded by the parser callback function +}; + +/*! +@brief comparison operator for JSON types + +Returns an ordering that is similar to Python: +- order: null < boolean < number < object < array < string < binary +- furthermore, each type is not smaller than itself +- discarded values are not comparable +- binary is represented as a b"" string in python and directly comparable to a + string; however, making a binary array directly comparable with a string would + be surprising behavior in a JSON file. + +@since version 1.0.0 +*/ +inline bool operator<(const value_t lhs, const value_t rhs) noexcept +{ + static constexpr std::array order = {{ + 0 /* null */, 3 /* object */, 4 /* array */, 5 /* string */, + 1 /* boolean */, 2 /* integer */, 2 /* unsigned */, 2 /* float */, + 6 /* binary */ + } + }; + + const auto l_index = static_cast(lhs); + const auto r_index = static_cast(rhs); + return l_index < order.size() && r_index < order.size() && order[l_index] < order[r_index]; +} +} // namespace detail +} // namespace nlohmann + +// #include + + +#include +// #include + + +#include // pair +// #include + + +/* Hedley - https://nemequ.github.io/hedley + * Created by Evan Nemerson + * + * To the extent possible under law, the author(s) have dedicated all + * copyright and related and neighboring rights to this software to + * the public domain worldwide. This software is distributed without + * any warranty. + * + * For details, see . + * SPDX-License-Identifier: CC0-1.0 + */ + +#if !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < 15) +#if defined(JSON_HEDLEY_VERSION) + #undef JSON_HEDLEY_VERSION +#endif +#define JSON_HEDLEY_VERSION 15 + +#if defined(JSON_HEDLEY_STRINGIFY_EX) + #undef JSON_HEDLEY_STRINGIFY_EX +#endif +#define JSON_HEDLEY_STRINGIFY_EX(x) #x + +#if defined(JSON_HEDLEY_STRINGIFY) + #undef JSON_HEDLEY_STRINGIFY +#endif +#define JSON_HEDLEY_STRINGIFY(x) JSON_HEDLEY_STRINGIFY_EX(x) + +#if defined(JSON_HEDLEY_CONCAT_EX) + #undef JSON_HEDLEY_CONCAT_EX +#endif +#define JSON_HEDLEY_CONCAT_EX(a,b) a##b + +#if defined(JSON_HEDLEY_CONCAT) + #undef JSON_HEDLEY_CONCAT +#endif +#define JSON_HEDLEY_CONCAT(a,b) JSON_HEDLEY_CONCAT_EX(a,b) + +#if defined(JSON_HEDLEY_CONCAT3_EX) + #undef JSON_HEDLEY_CONCAT3_EX +#endif +#define JSON_HEDLEY_CONCAT3_EX(a,b,c) a##b##c + +#if defined(JSON_HEDLEY_CONCAT3) + #undef JSON_HEDLEY_CONCAT3 +#endif +#define JSON_HEDLEY_CONCAT3(a,b,c) JSON_HEDLEY_CONCAT3_EX(a,b,c) + +#if defined(JSON_HEDLEY_VERSION_ENCODE) + #undef JSON_HEDLEY_VERSION_ENCODE +#endif +#define JSON_HEDLEY_VERSION_ENCODE(major,minor,revision) (((major) * 1000000) + ((minor) * 1000) + (revision)) + +#if defined(JSON_HEDLEY_VERSION_DECODE_MAJOR) + #undef JSON_HEDLEY_VERSION_DECODE_MAJOR +#endif +#define JSON_HEDLEY_VERSION_DECODE_MAJOR(version) ((version) / 1000000) + +#if defined(JSON_HEDLEY_VERSION_DECODE_MINOR) + #undef JSON_HEDLEY_VERSION_DECODE_MINOR +#endif +#define JSON_HEDLEY_VERSION_DECODE_MINOR(version) (((version) % 1000000) / 1000) + +#if defined(JSON_HEDLEY_VERSION_DECODE_REVISION) + #undef JSON_HEDLEY_VERSION_DECODE_REVISION +#endif +#define JSON_HEDLEY_VERSION_DECODE_REVISION(version) ((version) % 1000) + +#if defined(JSON_HEDLEY_GNUC_VERSION) + #undef JSON_HEDLEY_GNUC_VERSION +#endif +#if defined(__GNUC__) && defined(__GNUC_PATCHLEVEL__) + #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__) +#elif defined(__GNUC__) + #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, 0) +#endif + +#if defined(JSON_HEDLEY_GNUC_VERSION_CHECK) + #undef JSON_HEDLEY_GNUC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_GNUC_VERSION) + #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GNUC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_MSVC_VERSION) + #undef JSON_HEDLEY_MSVC_VERSION +#endif +#if defined(_MSC_FULL_VER) && (_MSC_FULL_VER >= 140000000) && !defined(__ICL) + #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 10000000, (_MSC_FULL_VER % 10000000) / 100000, (_MSC_FULL_VER % 100000) / 100) +#elif defined(_MSC_FULL_VER) && !defined(__ICL) + #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 1000000, (_MSC_FULL_VER % 1000000) / 10000, (_MSC_FULL_VER % 10000) / 10) +#elif defined(_MSC_VER) && !defined(__ICL) + #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_VER / 100, _MSC_VER % 100, 0) +#endif + +#if defined(JSON_HEDLEY_MSVC_VERSION_CHECK) + #undef JSON_HEDLEY_MSVC_VERSION_CHECK +#endif +#if !defined(JSON_HEDLEY_MSVC_VERSION) + #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (0) +#elif defined(_MSC_VER) && (_MSC_VER >= 1400) + #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 10000000) + (minor * 100000) + (patch))) +#elif defined(_MSC_VER) && (_MSC_VER >= 1200) + #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 1000000) + (minor * 10000) + (patch))) +#else + #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_VER >= ((major * 100) + (minor))) +#endif + +#if defined(JSON_HEDLEY_INTEL_VERSION) + #undef JSON_HEDLEY_INTEL_VERSION +#endif +#if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE) && !defined(__ICL) + #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, __INTEL_COMPILER_UPDATE) +#elif defined(__INTEL_COMPILER) && !defined(__ICL) + #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, 0) +#endif + +#if defined(JSON_HEDLEY_INTEL_VERSION_CHECK) + #undef JSON_HEDLEY_INTEL_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_INTEL_VERSION) + #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_INTEL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_INTEL_CL_VERSION) + #undef JSON_HEDLEY_INTEL_CL_VERSION +#endif +#if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE) && defined(__ICL) + #define JSON_HEDLEY_INTEL_CL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER, __INTEL_COMPILER_UPDATE, 0) +#endif + +#if defined(JSON_HEDLEY_INTEL_CL_VERSION_CHECK) + #undef JSON_HEDLEY_INTEL_CL_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_INTEL_CL_VERSION) + #define JSON_HEDLEY_INTEL_CL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_INTEL_CL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_INTEL_CL_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_PGI_VERSION) + #undef JSON_HEDLEY_PGI_VERSION +#endif +#if defined(__PGI) && defined(__PGIC__) && defined(__PGIC_MINOR__) && defined(__PGIC_PATCHLEVEL__) + #define JSON_HEDLEY_PGI_VERSION JSON_HEDLEY_VERSION_ENCODE(__PGIC__, __PGIC_MINOR__, __PGIC_PATCHLEVEL__) +#endif + +#if defined(JSON_HEDLEY_PGI_VERSION_CHECK) + #undef JSON_HEDLEY_PGI_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_PGI_VERSION) + #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PGI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_SUNPRO_VERSION) + #undef JSON_HEDLEY_SUNPRO_VERSION +#endif +#if defined(__SUNPRO_C) && (__SUNPRO_C > 0x1000) + #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((((__SUNPRO_C >> 16) & 0xf) * 10) + ((__SUNPRO_C >> 12) & 0xf), (((__SUNPRO_C >> 8) & 0xf) * 10) + ((__SUNPRO_C >> 4) & 0xf), (__SUNPRO_C & 0xf) * 10) +#elif defined(__SUNPRO_C) + #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_C >> 8) & 0xf, (__SUNPRO_C >> 4) & 0xf, (__SUNPRO_C) & 0xf) +#elif defined(__SUNPRO_CC) && (__SUNPRO_CC > 0x1000) + #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((((__SUNPRO_CC >> 16) & 0xf) * 10) + ((__SUNPRO_CC >> 12) & 0xf), (((__SUNPRO_CC >> 8) & 0xf) * 10) + ((__SUNPRO_CC >> 4) & 0xf), (__SUNPRO_CC & 0xf) * 10) +#elif defined(__SUNPRO_CC) + #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_CC >> 8) & 0xf, (__SUNPRO_CC >> 4) & 0xf, (__SUNPRO_CC) & 0xf) +#endif + +#if defined(JSON_HEDLEY_SUNPRO_VERSION_CHECK) + #undef JSON_HEDLEY_SUNPRO_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_SUNPRO_VERSION) + #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_SUNPRO_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION) + #undef JSON_HEDLEY_EMSCRIPTEN_VERSION +#endif +#if defined(__EMSCRIPTEN__) + #define JSON_HEDLEY_EMSCRIPTEN_VERSION JSON_HEDLEY_VERSION_ENCODE(__EMSCRIPTEN_major__, __EMSCRIPTEN_minor__, __EMSCRIPTEN_tiny__) +#endif + +#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK) + #undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION) + #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_EMSCRIPTEN_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_ARM_VERSION) + #undef JSON_HEDLEY_ARM_VERSION +#endif +#if defined(__CC_ARM) && defined(__ARMCOMPILER_VERSION) + #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCOMPILER_VERSION / 1000000, (__ARMCOMPILER_VERSION % 1000000) / 10000, (__ARMCOMPILER_VERSION % 10000) / 100) +#elif defined(__CC_ARM) && defined(__ARMCC_VERSION) + #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCC_VERSION / 1000000, (__ARMCC_VERSION % 1000000) / 10000, (__ARMCC_VERSION % 10000) / 100) +#endif + +#if defined(JSON_HEDLEY_ARM_VERSION_CHECK) + #undef JSON_HEDLEY_ARM_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_ARM_VERSION) + #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_ARM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_IBM_VERSION) + #undef JSON_HEDLEY_IBM_VERSION +#endif +#if defined(__ibmxl__) + #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ibmxl_version__, __ibmxl_release__, __ibmxl_modification__) +#elif defined(__xlC__) && defined(__xlC_ver__) + #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, (__xlC_ver__ >> 8) & 0xff) +#elif defined(__xlC__) + #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, 0) +#endif + +#if defined(JSON_HEDLEY_IBM_VERSION_CHECK) + #undef JSON_HEDLEY_IBM_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_IBM_VERSION) + #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IBM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_VERSION) + #undef JSON_HEDLEY_TI_VERSION +#endif +#if \ + defined(__TI_COMPILER_VERSION__) && \ + ( \ + defined(__TMS470__) || defined(__TI_ARM__) || \ + defined(__MSP430__) || \ + defined(__TMS320C2000__) \ + ) +#if (__TI_COMPILER_VERSION__ >= 16000000) + #define JSON_HEDLEY_TI_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif +#endif + +#if defined(JSON_HEDLEY_TI_VERSION_CHECK) + #undef JSON_HEDLEY_TI_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_VERSION) + #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CL2000_VERSION) + #undef JSON_HEDLEY_TI_CL2000_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C2000__) + #define JSON_HEDLEY_TI_CL2000_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CL2000_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CL2000_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CL2000_VERSION) + #define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL2000_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CL430_VERSION) + #undef JSON_HEDLEY_TI_CL430_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__MSP430__) + #define JSON_HEDLEY_TI_CL430_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CL430_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CL430_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CL430_VERSION) + #define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL430_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_ARMCL_VERSION) + #undef JSON_HEDLEY_TI_ARMCL_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && (defined(__TMS470__) || defined(__TI_ARM__)) + #define JSON_HEDLEY_TI_ARMCL_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_ARMCL_VERSION_CHECK) + #undef JSON_HEDLEY_TI_ARMCL_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_ARMCL_VERSION) + #define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_ARMCL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CL6X_VERSION) + #undef JSON_HEDLEY_TI_CL6X_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C6X__) + #define JSON_HEDLEY_TI_CL6X_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CL6X_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CL6X_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CL6X_VERSION) + #define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL6X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CL7X_VERSION) + #undef JSON_HEDLEY_TI_CL7X_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__C7000__) + #define JSON_HEDLEY_TI_CL7X_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CL7X_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CL7X_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CL7X_VERSION) + #define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL7X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CLPRU_VERSION) + #undef JSON_HEDLEY_TI_CLPRU_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__PRU__) + #define JSON_HEDLEY_TI_CLPRU_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CLPRU_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CLPRU_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CLPRU_VERSION) + #define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CLPRU_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_CRAY_VERSION) + #undef JSON_HEDLEY_CRAY_VERSION +#endif +#if defined(_CRAYC) + #if defined(_RELEASE_PATCHLEVEL) + #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, _RELEASE_PATCHLEVEL) + #else + #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, 0) + #endif +#endif + +#if defined(JSON_HEDLEY_CRAY_VERSION_CHECK) + #undef JSON_HEDLEY_CRAY_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_CRAY_VERSION) + #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_CRAY_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_IAR_VERSION) + #undef JSON_HEDLEY_IAR_VERSION +#endif +#if defined(__IAR_SYSTEMS_ICC__) + #if __VER__ > 1000 + #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE((__VER__ / 1000000), ((__VER__ / 1000) % 1000), (__VER__ % 1000)) + #else + #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE(__VER__ / 100, __VER__ % 100, 0) + #endif +#endif + +#if defined(JSON_HEDLEY_IAR_VERSION_CHECK) + #undef JSON_HEDLEY_IAR_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_IAR_VERSION) + #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IAR_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TINYC_VERSION) + #undef JSON_HEDLEY_TINYC_VERSION +#endif +#if defined(__TINYC__) + #define JSON_HEDLEY_TINYC_VERSION JSON_HEDLEY_VERSION_ENCODE(__TINYC__ / 1000, (__TINYC__ / 100) % 10, __TINYC__ % 100) +#endif + +#if defined(JSON_HEDLEY_TINYC_VERSION_CHECK) + #undef JSON_HEDLEY_TINYC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TINYC_VERSION) + #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TINYC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_DMC_VERSION) + #undef JSON_HEDLEY_DMC_VERSION +#endif +#if defined(__DMC__) + #define JSON_HEDLEY_DMC_VERSION JSON_HEDLEY_VERSION_ENCODE(__DMC__ >> 8, (__DMC__ >> 4) & 0xf, __DMC__ & 0xf) +#endif + +#if defined(JSON_HEDLEY_DMC_VERSION_CHECK) + #undef JSON_HEDLEY_DMC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_DMC_VERSION) + #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_DMC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_COMPCERT_VERSION) + #undef JSON_HEDLEY_COMPCERT_VERSION +#endif +#if defined(__COMPCERT_VERSION__) + #define JSON_HEDLEY_COMPCERT_VERSION JSON_HEDLEY_VERSION_ENCODE(__COMPCERT_VERSION__ / 10000, (__COMPCERT_VERSION__ / 100) % 100, __COMPCERT_VERSION__ % 100) +#endif + +#if defined(JSON_HEDLEY_COMPCERT_VERSION_CHECK) + #undef JSON_HEDLEY_COMPCERT_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_COMPCERT_VERSION) + #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_COMPCERT_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_PELLES_VERSION) + #undef JSON_HEDLEY_PELLES_VERSION +#endif +#if defined(__POCC__) + #define JSON_HEDLEY_PELLES_VERSION JSON_HEDLEY_VERSION_ENCODE(__POCC__ / 100, __POCC__ % 100, 0) +#endif + +#if defined(JSON_HEDLEY_PELLES_VERSION_CHECK) + #undef JSON_HEDLEY_PELLES_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_PELLES_VERSION) + #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PELLES_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_MCST_LCC_VERSION) + #undef JSON_HEDLEY_MCST_LCC_VERSION +#endif +#if defined(__LCC__) && defined(__LCC_MINOR__) + #define JSON_HEDLEY_MCST_LCC_VERSION JSON_HEDLEY_VERSION_ENCODE(__LCC__ / 100, __LCC__ % 100, __LCC_MINOR__) +#endif + +#if defined(JSON_HEDLEY_MCST_LCC_VERSION_CHECK) + #undef JSON_HEDLEY_MCST_LCC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_MCST_LCC_VERSION) + #define JSON_HEDLEY_MCST_LCC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_MCST_LCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_MCST_LCC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_GCC_VERSION) + #undef JSON_HEDLEY_GCC_VERSION +#endif +#if \ + defined(JSON_HEDLEY_GNUC_VERSION) && \ + !defined(__clang__) && \ + !defined(JSON_HEDLEY_INTEL_VERSION) && \ + !defined(JSON_HEDLEY_PGI_VERSION) && \ + !defined(JSON_HEDLEY_ARM_VERSION) && \ + !defined(JSON_HEDLEY_CRAY_VERSION) && \ + !defined(JSON_HEDLEY_TI_VERSION) && \ + !defined(JSON_HEDLEY_TI_ARMCL_VERSION) && \ + !defined(JSON_HEDLEY_TI_CL430_VERSION) && \ + !defined(JSON_HEDLEY_TI_CL2000_VERSION) && \ + !defined(JSON_HEDLEY_TI_CL6X_VERSION) && \ + !defined(JSON_HEDLEY_TI_CL7X_VERSION) && \ + !defined(JSON_HEDLEY_TI_CLPRU_VERSION) && \ + !defined(__COMPCERT__) && \ + !defined(JSON_HEDLEY_MCST_LCC_VERSION) + #define JSON_HEDLEY_GCC_VERSION JSON_HEDLEY_GNUC_VERSION +#endif + +#if defined(JSON_HEDLEY_GCC_VERSION_CHECK) + #undef JSON_HEDLEY_GCC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_GCC_VERSION) + #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_HAS_ATTRIBUTE) + #undef JSON_HEDLEY_HAS_ATTRIBUTE +#endif +#if \ + defined(__has_attribute) && \ + ( \ + (!defined(JSON_HEDLEY_IAR_VERSION) || JSON_HEDLEY_IAR_VERSION_CHECK(8,5,9)) \ + ) +# define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) __has_attribute(attribute) +#else +# define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_ATTRIBUTE) + #undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE +#endif +#if defined(__has_attribute) + #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_HAS_ATTRIBUTE(attribute) +#else + #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_ATTRIBUTE) + #undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE +#endif +#if defined(__has_attribute) + #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_HAS_ATTRIBUTE(attribute) +#else + #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE) + #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE +#endif +#if \ + defined(__has_cpp_attribute) && \ + defined(__cplusplus) && \ + (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0)) + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) __has_cpp_attribute(attribute) +#else + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) (0) +#endif + +#if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS) + #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS +#endif +#if !defined(__cplusplus) || !defined(__has_cpp_attribute) + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0) +#elif \ + !defined(JSON_HEDLEY_PGI_VERSION) && \ + !defined(JSON_HEDLEY_IAR_VERSION) && \ + (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0)) && \ + (!defined(JSON_HEDLEY_MSVC_VERSION) || JSON_HEDLEY_MSVC_VERSION_CHECK(19,20,0)) + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(ns::attribute) +#else + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE) + #undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE +#endif +#if defined(__has_cpp_attribute) && defined(__cplusplus) + #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute) +#else + #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE) + #undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE +#endif +#if defined(__has_cpp_attribute) && defined(__cplusplus) + #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute) +#else + #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_BUILTIN) + #undef JSON_HEDLEY_HAS_BUILTIN +#endif +#if defined(__has_builtin) + #define JSON_HEDLEY_HAS_BUILTIN(builtin) __has_builtin(builtin) +#else + #define JSON_HEDLEY_HAS_BUILTIN(builtin) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_BUILTIN) + #undef JSON_HEDLEY_GNUC_HAS_BUILTIN +#endif +#if defined(__has_builtin) + #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin) +#else + #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_BUILTIN) + #undef JSON_HEDLEY_GCC_HAS_BUILTIN +#endif +#if defined(__has_builtin) + #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin) +#else + #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_FEATURE) + #undef JSON_HEDLEY_HAS_FEATURE +#endif +#if defined(__has_feature) + #define JSON_HEDLEY_HAS_FEATURE(feature) __has_feature(feature) +#else + #define JSON_HEDLEY_HAS_FEATURE(feature) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_FEATURE) + #undef JSON_HEDLEY_GNUC_HAS_FEATURE +#endif +#if defined(__has_feature) + #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature) +#else + #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_FEATURE) + #undef JSON_HEDLEY_GCC_HAS_FEATURE +#endif +#if defined(__has_feature) + #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature) +#else + #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_EXTENSION) + #undef JSON_HEDLEY_HAS_EXTENSION +#endif +#if defined(__has_extension) + #define JSON_HEDLEY_HAS_EXTENSION(extension) __has_extension(extension) +#else + #define JSON_HEDLEY_HAS_EXTENSION(extension) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_EXTENSION) + #undef JSON_HEDLEY_GNUC_HAS_EXTENSION +#endif +#if defined(__has_extension) + #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension) +#else + #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_EXTENSION) + #undef JSON_HEDLEY_GCC_HAS_EXTENSION +#endif +#if defined(__has_extension) + #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension) +#else + #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE) + #undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE +#endif +#if defined(__has_declspec_attribute) + #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) __has_declspec_attribute(attribute) +#else + #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE) + #undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE +#endif +#if defined(__has_declspec_attribute) + #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute) +#else + #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE) + #undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE +#endif +#if defined(__has_declspec_attribute) + #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute) +#else + #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_WARNING) + #undef JSON_HEDLEY_HAS_WARNING +#endif +#if defined(__has_warning) + #define JSON_HEDLEY_HAS_WARNING(warning) __has_warning(warning) +#else + #define JSON_HEDLEY_HAS_WARNING(warning) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_WARNING) + #undef JSON_HEDLEY_GNUC_HAS_WARNING +#endif +#if defined(__has_warning) + #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning) +#else + #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_WARNING) + #undef JSON_HEDLEY_GCC_HAS_WARNING +#endif +#if defined(__has_warning) + #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning) +#else + #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if \ + (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \ + defined(__clang__) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,7,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(2,0,1) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,0,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0) || \ + JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,17) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(8,0,0) || \ + (JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) && defined(__C99_PRAGMA_OPERATOR)) + #define JSON_HEDLEY_PRAGMA(value) _Pragma(#value) +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) + #define JSON_HEDLEY_PRAGMA(value) __pragma(value) +#else + #define JSON_HEDLEY_PRAGMA(value) +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_PUSH) + #undef JSON_HEDLEY_DIAGNOSTIC_PUSH +#endif +#if defined(JSON_HEDLEY_DIAGNOSTIC_POP) + #undef JSON_HEDLEY_DIAGNOSTIC_POP +#endif +#if defined(__clang__) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("clang diagnostic push") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("clang diagnostic pop") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("GCC diagnostic push") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("GCC diagnostic pop") +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH __pragma(warning(push)) + #define JSON_HEDLEY_DIAGNOSTIC_POP __pragma(warning(pop)) +#elif JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("push") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("pop") +#elif \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,4,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("diag_push") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("diag_pop") +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)") +#else + #define JSON_HEDLEY_DIAGNOSTIC_PUSH + #define JSON_HEDLEY_DIAGNOSTIC_POP +#endif + +/* JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ is for + HEDLEY INTERNAL USE ONLY. API subject to change without notice. */ +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ +#endif +#if defined(__cplusplus) +# if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat") +# if JSON_HEDLEY_HAS_WARNING("-Wc++17-extensions") +# if JSON_HEDLEY_HAS_WARNING("-Wc++1z-extensions") +# define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \ + _Pragma("clang diagnostic ignored \"-Wc++17-extensions\"") \ + _Pragma("clang diagnostic ignored \"-Wc++1z-extensions\"") \ + xpr \ + JSON_HEDLEY_DIAGNOSTIC_POP +# else +# define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \ + _Pragma("clang diagnostic ignored \"-Wc++17-extensions\"") \ + xpr \ + JSON_HEDLEY_DIAGNOSTIC_POP +# endif +# else +# define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \ + xpr \ + JSON_HEDLEY_DIAGNOSTIC_POP +# endif +# endif +#endif +#if !defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(x) x +#endif + +#if defined(JSON_HEDLEY_CONST_CAST) + #undef JSON_HEDLEY_CONST_CAST +#endif +#if defined(__cplusplus) +# define JSON_HEDLEY_CONST_CAST(T, expr) (const_cast(expr)) +#elif \ + JSON_HEDLEY_HAS_WARNING("-Wcast-qual") || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) +# define JSON_HEDLEY_CONST_CAST(T, expr) (__extension__ ({ \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL \ + ((T) (expr)); \ + JSON_HEDLEY_DIAGNOSTIC_POP \ + })) +#else +# define JSON_HEDLEY_CONST_CAST(T, expr) ((T) (expr)) +#endif + +#if defined(JSON_HEDLEY_REINTERPRET_CAST) + #undef JSON_HEDLEY_REINTERPRET_CAST +#endif +#if defined(__cplusplus) + #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) (reinterpret_cast(expr)) +#else + #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) ((T) (expr)) +#endif + +#if defined(JSON_HEDLEY_STATIC_CAST) + #undef JSON_HEDLEY_STATIC_CAST +#endif +#if defined(__cplusplus) + #define JSON_HEDLEY_STATIC_CAST(T, expr) (static_cast(expr)) +#else + #define JSON_HEDLEY_STATIC_CAST(T, expr) ((T) (expr)) +#endif + +#if defined(JSON_HEDLEY_CPP_CAST) + #undef JSON_HEDLEY_CPP_CAST +#endif +#if defined(__cplusplus) +# if JSON_HEDLEY_HAS_WARNING("-Wold-style-cast") +# define JSON_HEDLEY_CPP_CAST(T, expr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wold-style-cast\"") \ + ((T) (expr)) \ + JSON_HEDLEY_DIAGNOSTIC_POP +# elif JSON_HEDLEY_IAR_VERSION_CHECK(8,3,0) +# define JSON_HEDLEY_CPP_CAST(T, expr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("diag_suppress=Pe137") \ + JSON_HEDLEY_DIAGNOSTIC_POP +# else +# define JSON_HEDLEY_CPP_CAST(T, expr) ((T) (expr)) +# endif +#else +# define JSON_HEDLEY_CPP_CAST(T, expr) (expr) +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wdeprecated-declarations") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warning(disable:1478 1786)") +#elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED __pragma(warning(disable:1478 1786)) +#elif JSON_HEDLEY_PGI_VERSION_CHECK(20,7,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1216,1444,1445") +#elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1444") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED __pragma(warning(disable:4996)) +#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1444") +#elif \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1291,1718") +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && !defined(__cplusplus) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,E_DEPRECATED_ATT,E_DEPRECATED_ATT_MESS)") +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && defined(__cplusplus) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,symdeprecated,symdeprecated2)") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress=Pe1444,Pe1215") +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warn(disable:2241)") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("clang diagnostic ignored \"-Wunknown-pragmas\"") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("warning(disable:161)") +#elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS __pragma(warning(disable:161)) +#elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 1675") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("GCC diagnostic ignored \"-Wunknown-pragmas\"") +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS __pragma(warning(disable:4068)) +#elif \ + JSON_HEDLEY_TI_VERSION_CHECK(16,9,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,3,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163") +#elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress=Pe161") +#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 161") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunknown-attributes") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("clang diagnostic ignored \"-Wunknown-attributes\"") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("warning(disable:1292)") +#elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES __pragma(warning(disable:1292)) +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES __pragma(warning(disable:5030)) +#elif JSON_HEDLEY_PGI_VERSION_CHECK(20,7,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097,1098") +#elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097") +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("error_messages(off,attrskipunsup)") +#elif \ + JSON_HEDLEY_TI_VERSION_CHECK(18,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,3,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1173") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress=Pe1097") +#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wcast-qual") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("clang diagnostic ignored \"-Wcast-qual\"") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("warning(disable:2203 2331)") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("GCC diagnostic ignored \"-Wcast-qual\"") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunused-function") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("clang diagnostic ignored \"-Wunused-function\"") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("GCC diagnostic ignored \"-Wunused-function\"") +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(1,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION __pragma(warning(disable:4505)) +#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("diag_suppress 3142") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION +#endif + +#if defined(JSON_HEDLEY_DEPRECATED) + #undef JSON_HEDLEY_DEPRECATED +#endif +#if defined(JSON_HEDLEY_DEPRECATED_FOR) + #undef JSON_HEDLEY_DEPRECATED_FOR +#endif +#if \ + JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated("Since " # since)) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated("Since " #since "; use " #replacement)) +#elif \ + (JSON_HEDLEY_HAS_EXTENSION(attribute_deprecated_with_message) && !defined(JSON_HEDLEY_IAR_VERSION)) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(18,1,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(18,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,3,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,3,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__("Since " #since))) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__("Since " #since "; use " #replacement))) +#elif defined(__cplusplus) && (__cplusplus >= 201402L) + #define JSON_HEDLEY_DEPRECATED(since) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since)]]) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since "; use " #replacement)]]) +#elif \ + JSON_HEDLEY_HAS_ATTRIBUTE(deprecated) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) + #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__)) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__)) +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ + JSON_HEDLEY_PELLES_VERSION_CHECK(6,50,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated) +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DEPRECATED(since) _Pragma("deprecated") + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) _Pragma("deprecated") +#else + #define JSON_HEDLEY_DEPRECATED(since) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) +#endif + +#if defined(JSON_HEDLEY_UNAVAILABLE) + #undef JSON_HEDLEY_UNAVAILABLE +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(warning) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_UNAVAILABLE(available_since) __attribute__((__warning__("Not available until " #available_since))) +#else + #define JSON_HEDLEY_UNAVAILABLE(available_since) +#endif + +#if defined(JSON_HEDLEY_WARN_UNUSED_RESULT) + #undef JSON_HEDLEY_WARN_UNUSED_RESULT +#endif +#if defined(JSON_HEDLEY_WARN_UNUSED_RESULT_MSG) + #undef JSON_HEDLEY_WARN_UNUSED_RESULT_MSG +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(warn_unused_result) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_WARN_UNUSED_RESULT __attribute__((__warn_unused_result__)) + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) __attribute__((__warn_unused_result__)) +#elif (JSON_HEDLEY_HAS_CPP_ATTRIBUTE(nodiscard) >= 201907L) + #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard(msg)]]) +#elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(nodiscard) + #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) +#elif defined(_Check_return_) /* SAL */ + #define JSON_HEDLEY_WARN_UNUSED_RESULT _Check_return_ + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) _Check_return_ +#else + #define JSON_HEDLEY_WARN_UNUSED_RESULT + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) +#endif + +#if defined(JSON_HEDLEY_SENTINEL) + #undef JSON_HEDLEY_SENTINEL +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(sentinel) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_SENTINEL(position) __attribute__((__sentinel__(position))) +#else + #define JSON_HEDLEY_SENTINEL(position) +#endif + +#if defined(JSON_HEDLEY_NO_RETURN) + #undef JSON_HEDLEY_NO_RETURN +#endif +#if JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_NO_RETURN __noreturn +#elif \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__)) +#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L + #define JSON_HEDLEY_NO_RETURN _Noreturn +#elif defined(__cplusplus) && (__cplusplus >= 201103L) + #define JSON_HEDLEY_NO_RETURN JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[noreturn]]) +#elif \ + JSON_HEDLEY_HAS_ATTRIBUTE(noreturn) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,2,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) + #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__)) +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) + #define JSON_HEDLEY_NO_RETURN _Pragma("does_not_return") +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_NO_RETURN __declspec(noreturn) +#elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,0,0) && defined(__cplusplus) + #define JSON_HEDLEY_NO_RETURN _Pragma("FUNC_NEVER_RETURNS;") +#elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0) + #define JSON_HEDLEY_NO_RETURN __attribute((noreturn)) +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0) + #define JSON_HEDLEY_NO_RETURN __declspec(noreturn) +#else + #define JSON_HEDLEY_NO_RETURN +#endif + +#if defined(JSON_HEDLEY_NO_ESCAPE) + #undef JSON_HEDLEY_NO_ESCAPE +#endif +#if JSON_HEDLEY_HAS_ATTRIBUTE(noescape) + #define JSON_HEDLEY_NO_ESCAPE __attribute__((__noescape__)) +#else + #define JSON_HEDLEY_NO_ESCAPE +#endif + +#if defined(JSON_HEDLEY_UNREACHABLE) + #undef JSON_HEDLEY_UNREACHABLE +#endif +#if defined(JSON_HEDLEY_UNREACHABLE_RETURN) + #undef JSON_HEDLEY_UNREACHABLE_RETURN +#endif +#if defined(JSON_HEDLEY_ASSUME) + #undef JSON_HEDLEY_ASSUME +#endif +#if \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_ASSUME(expr) __assume(expr) +#elif JSON_HEDLEY_HAS_BUILTIN(__builtin_assume) + #define JSON_HEDLEY_ASSUME(expr) __builtin_assume(expr) +#elif \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) + #if defined(__cplusplus) + #define JSON_HEDLEY_ASSUME(expr) std::_nassert(expr) + #else + #define JSON_HEDLEY_ASSUME(expr) _nassert(expr) + #endif +#endif +#if \ + (JSON_HEDLEY_HAS_BUILTIN(__builtin_unreachable) && (!defined(JSON_HEDLEY_ARM_VERSION))) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(18,10,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(13,1,5) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(10,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_UNREACHABLE() __builtin_unreachable() +#elif defined(JSON_HEDLEY_ASSUME) + #define JSON_HEDLEY_UNREACHABLE() JSON_HEDLEY_ASSUME(0) +#endif +#if !defined(JSON_HEDLEY_ASSUME) + #if defined(JSON_HEDLEY_UNREACHABLE) + #define JSON_HEDLEY_ASSUME(expr) JSON_HEDLEY_STATIC_CAST(void, ((expr) ? 1 : (JSON_HEDLEY_UNREACHABLE(), 1))) + #else + #define JSON_HEDLEY_ASSUME(expr) JSON_HEDLEY_STATIC_CAST(void, expr) + #endif +#endif +#if defined(JSON_HEDLEY_UNREACHABLE) + #if \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) + #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return (JSON_HEDLEY_STATIC_CAST(void, JSON_HEDLEY_ASSUME(0)), (value)) + #else + #define JSON_HEDLEY_UNREACHABLE_RETURN(value) JSON_HEDLEY_UNREACHABLE() + #endif +#else + #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return (value) +#endif +#if !defined(JSON_HEDLEY_UNREACHABLE) + #define JSON_HEDLEY_UNREACHABLE() JSON_HEDLEY_ASSUME(0) +#endif + +JSON_HEDLEY_DIAGNOSTIC_PUSH +#if JSON_HEDLEY_HAS_WARNING("-Wpedantic") + #pragma clang diagnostic ignored "-Wpedantic" +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat-pedantic") && defined(__cplusplus) + #pragma clang diagnostic ignored "-Wc++98-compat-pedantic" +#endif +#if JSON_HEDLEY_GCC_HAS_WARNING("-Wvariadic-macros",4,0,0) + #if defined(__clang__) + #pragma clang diagnostic ignored "-Wvariadic-macros" + #elif defined(JSON_HEDLEY_GCC_VERSION) + #pragma GCC diagnostic ignored "-Wvariadic-macros" + #endif +#endif +#if defined(JSON_HEDLEY_NON_NULL) + #undef JSON_HEDLEY_NON_NULL +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(nonnull) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) + #define JSON_HEDLEY_NON_NULL(...) __attribute__((__nonnull__(__VA_ARGS__))) +#else + #define JSON_HEDLEY_NON_NULL(...) +#endif +JSON_HEDLEY_DIAGNOSTIC_POP + +#if defined(JSON_HEDLEY_PRINTF_FORMAT) + #undef JSON_HEDLEY_PRINTF_FORMAT +#endif +#if defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && !defined(__USE_MINGW_ANSI_STDIO) + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(ms_printf, string_idx, first_to_check))) +#elif defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && defined(__USE_MINGW_ANSI_STDIO) + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(gnu_printf, string_idx, first_to_check))) +#elif \ + JSON_HEDLEY_HAS_ATTRIBUTE(format) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(__printf__, string_idx, first_to_check))) +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(6,0,0) + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __declspec(vaformat(printf,string_idx,first_to_check)) +#else + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) +#endif + +#if defined(JSON_HEDLEY_CONSTEXPR) + #undef JSON_HEDLEY_CONSTEXPR +#endif +#if defined(__cplusplus) + #if __cplusplus >= 201103L + #define JSON_HEDLEY_CONSTEXPR JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(constexpr) + #endif +#endif +#if !defined(JSON_HEDLEY_CONSTEXPR) + #define JSON_HEDLEY_CONSTEXPR +#endif + +#if defined(JSON_HEDLEY_PREDICT) + #undef JSON_HEDLEY_PREDICT +#endif +#if defined(JSON_HEDLEY_LIKELY) + #undef JSON_HEDLEY_LIKELY +#endif +#if defined(JSON_HEDLEY_UNLIKELY) + #undef JSON_HEDLEY_UNLIKELY +#endif +#if defined(JSON_HEDLEY_UNPREDICTABLE) + #undef JSON_HEDLEY_UNPREDICTABLE +#endif +#if JSON_HEDLEY_HAS_BUILTIN(__builtin_unpredictable) + #define JSON_HEDLEY_UNPREDICTABLE(expr) __builtin_unpredictable((expr)) +#endif +#if \ + (JSON_HEDLEY_HAS_BUILTIN(__builtin_expect_with_probability) && !defined(JSON_HEDLEY_PGI_VERSION)) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(9,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) +# define JSON_HEDLEY_PREDICT(expr, value, probability) __builtin_expect_with_probability( (expr), (value), (probability)) +# define JSON_HEDLEY_PREDICT_TRUE(expr, probability) __builtin_expect_with_probability(!!(expr), 1 , (probability)) +# define JSON_HEDLEY_PREDICT_FALSE(expr, probability) __builtin_expect_with_probability(!!(expr), 0 , (probability)) +# define JSON_HEDLEY_LIKELY(expr) __builtin_expect (!!(expr), 1 ) +# define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect (!!(expr), 0 ) +#elif \ + (JSON_HEDLEY_HAS_BUILTIN(__builtin_expect) && !defined(JSON_HEDLEY_INTEL_CL_VERSION)) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,7,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,27) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) +# define JSON_HEDLEY_PREDICT(expr, expected, probability) \ + (((probability) >= 0.9) ? __builtin_expect((expr), (expected)) : (JSON_HEDLEY_STATIC_CAST(void, expected), (expr))) +# define JSON_HEDLEY_PREDICT_TRUE(expr, probability) \ + (__extension__ ({ \ + double hedley_probability_ = (probability); \ + ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 1) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 0) : !!(expr))); \ + })) +# define JSON_HEDLEY_PREDICT_FALSE(expr, probability) \ + (__extension__ ({ \ + double hedley_probability_ = (probability); \ + ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 0) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 1) : !!(expr))); \ + })) +# define JSON_HEDLEY_LIKELY(expr) __builtin_expect(!!(expr), 1) +# define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect(!!(expr), 0) +#else +# define JSON_HEDLEY_PREDICT(expr, expected, probability) (JSON_HEDLEY_STATIC_CAST(void, expected), (expr)) +# define JSON_HEDLEY_PREDICT_TRUE(expr, probability) (!!(expr)) +# define JSON_HEDLEY_PREDICT_FALSE(expr, probability) (!!(expr)) +# define JSON_HEDLEY_LIKELY(expr) (!!(expr)) +# define JSON_HEDLEY_UNLIKELY(expr) (!!(expr)) +#endif +#if !defined(JSON_HEDLEY_UNPREDICTABLE) + #define JSON_HEDLEY_UNPREDICTABLE(expr) JSON_HEDLEY_PREDICT(expr, 1, 0.5) +#endif + +#if defined(JSON_HEDLEY_MALLOC) + #undef JSON_HEDLEY_MALLOC +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(malloc) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_MALLOC __attribute__((__malloc__)) +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) + #define JSON_HEDLEY_MALLOC _Pragma("returns_new_memory") +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_MALLOC __declspec(restrict) +#else + #define JSON_HEDLEY_MALLOC +#endif + +#if defined(JSON_HEDLEY_PURE) + #undef JSON_HEDLEY_PURE +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(pure) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(2,96,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) +# define JSON_HEDLEY_PURE __attribute__((__pure__)) +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) +# define JSON_HEDLEY_PURE _Pragma("does_not_write_global_data") +#elif defined(__cplusplus) && \ + ( \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(2,0,1) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) \ + ) +# define JSON_HEDLEY_PURE _Pragma("FUNC_IS_PURE;") +#else +# define JSON_HEDLEY_PURE +#endif + +#if defined(JSON_HEDLEY_CONST) + #undef JSON_HEDLEY_CONST +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(const) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(2,5,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_CONST __attribute__((__const__)) +#elif \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) + #define JSON_HEDLEY_CONST _Pragma("no_side_effect") +#else + #define JSON_HEDLEY_CONST JSON_HEDLEY_PURE +#endif + +#if defined(JSON_HEDLEY_RESTRICT) + #undef JSON_HEDLEY_RESTRICT +#endif +#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && !defined(__cplusplus) + #define JSON_HEDLEY_RESTRICT restrict +#elif \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,4) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus)) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \ + defined(__clang__) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_RESTRICT __restrict +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,3,0) && !defined(__cplusplus) + #define JSON_HEDLEY_RESTRICT _Restrict +#else + #define JSON_HEDLEY_RESTRICT +#endif + +#if defined(JSON_HEDLEY_INLINE) + #undef JSON_HEDLEY_INLINE +#endif +#if \ + (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \ + (defined(__cplusplus) && (__cplusplus >= 199711L)) + #define JSON_HEDLEY_INLINE inline +#elif \ + defined(JSON_HEDLEY_GCC_VERSION) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(6,2,0) + #define JSON_HEDLEY_INLINE __inline__ +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,1,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_INLINE __inline +#else + #define JSON_HEDLEY_INLINE +#endif + +#if defined(JSON_HEDLEY_ALWAYS_INLINE) + #undef JSON_HEDLEY_ALWAYS_INLINE +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(always_inline) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) +# define JSON_HEDLEY_ALWAYS_INLINE __attribute__((__always_inline__)) JSON_HEDLEY_INLINE +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) +# define JSON_HEDLEY_ALWAYS_INLINE __forceinline +#elif defined(__cplusplus) && \ + ( \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) \ + ) +# define JSON_HEDLEY_ALWAYS_INLINE _Pragma("FUNC_ALWAYS_INLINE;") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) +# define JSON_HEDLEY_ALWAYS_INLINE _Pragma("inline=forced") +#else +# define JSON_HEDLEY_ALWAYS_INLINE JSON_HEDLEY_INLINE +#endif + +#if defined(JSON_HEDLEY_NEVER_INLINE) + #undef JSON_HEDLEY_NEVER_INLINE +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(noinline) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) + #define JSON_HEDLEY_NEVER_INLINE __attribute__((__noinline__)) +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline) +#elif JSON_HEDLEY_PGI_VERSION_CHECK(10,2,0) + #define JSON_HEDLEY_NEVER_INLINE _Pragma("noinline") +#elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,0,0) && defined(__cplusplus) + #define JSON_HEDLEY_NEVER_INLINE _Pragma("FUNC_CANNOT_INLINE;") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_NEVER_INLINE _Pragma("inline=never") +#elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0) + #define JSON_HEDLEY_NEVER_INLINE __attribute((noinline)) +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0) + #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline) +#else + #define JSON_HEDLEY_NEVER_INLINE +#endif + +#if defined(JSON_HEDLEY_PRIVATE) + #undef JSON_HEDLEY_PRIVATE +#endif +#if defined(JSON_HEDLEY_PUBLIC) + #undef JSON_HEDLEY_PUBLIC +#endif +#if defined(JSON_HEDLEY_IMPORT) + #undef JSON_HEDLEY_IMPORT +#endif +#if defined(_WIN32) || defined(__CYGWIN__) +# define JSON_HEDLEY_PRIVATE +# define JSON_HEDLEY_PUBLIC __declspec(dllexport) +# define JSON_HEDLEY_IMPORT __declspec(dllimport) +#else +# if \ + JSON_HEDLEY_HAS_ATTRIBUTE(visibility) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ + ( \ + defined(__TI_EABI__) && \ + ( \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) \ + ) \ + ) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) +# define JSON_HEDLEY_PRIVATE __attribute__((__visibility__("hidden"))) +# define JSON_HEDLEY_PUBLIC __attribute__((__visibility__("default"))) +# else +# define JSON_HEDLEY_PRIVATE +# define JSON_HEDLEY_PUBLIC +# endif +# define JSON_HEDLEY_IMPORT extern +#endif + +#if defined(JSON_HEDLEY_NO_THROW) + #undef JSON_HEDLEY_NO_THROW +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(nothrow) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_NO_THROW __attribute__((__nothrow__)) +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,1,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) + #define JSON_HEDLEY_NO_THROW __declspec(nothrow) +#else + #define JSON_HEDLEY_NO_THROW +#endif + +#if defined(JSON_HEDLEY_FALL_THROUGH) + #undef JSON_HEDLEY_FALL_THROUGH +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(fallthrough) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(7,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_FALL_THROUGH __attribute__((__fallthrough__)) +#elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(clang,fallthrough) + #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[clang::fallthrough]]) +#elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(fallthrough) + #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[fallthrough]]) +#elif defined(__fallthrough) /* SAL */ + #define JSON_HEDLEY_FALL_THROUGH __fallthrough +#else + #define JSON_HEDLEY_FALL_THROUGH +#endif + +#if defined(JSON_HEDLEY_RETURNS_NON_NULL) + #undef JSON_HEDLEY_RETURNS_NON_NULL +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(returns_nonnull) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_RETURNS_NON_NULL __attribute__((__returns_nonnull__)) +#elif defined(_Ret_notnull_) /* SAL */ + #define JSON_HEDLEY_RETURNS_NON_NULL _Ret_notnull_ +#else + #define JSON_HEDLEY_RETURNS_NON_NULL +#endif + +#if defined(JSON_HEDLEY_ARRAY_PARAM) + #undef JSON_HEDLEY_ARRAY_PARAM +#endif +#if \ + defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ + !defined(__STDC_NO_VLA__) && \ + !defined(__cplusplus) && \ + !defined(JSON_HEDLEY_PGI_VERSION) && \ + !defined(JSON_HEDLEY_TINYC_VERSION) + #define JSON_HEDLEY_ARRAY_PARAM(name) (name) +#else + #define JSON_HEDLEY_ARRAY_PARAM(name) +#endif + +#if defined(JSON_HEDLEY_IS_CONSTANT) + #undef JSON_HEDLEY_IS_CONSTANT +#endif +#if defined(JSON_HEDLEY_REQUIRE_CONSTEXPR) + #undef JSON_HEDLEY_REQUIRE_CONSTEXPR +#endif +/* JSON_HEDLEY_IS_CONSTEXPR_ is for + HEDLEY INTERNAL USE ONLY. API subject to change without notice. */ +#if defined(JSON_HEDLEY_IS_CONSTEXPR_) + #undef JSON_HEDLEY_IS_CONSTEXPR_ +#endif +#if \ + JSON_HEDLEY_HAS_BUILTIN(__builtin_constant_p) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,19) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ + (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) && !defined(__cplusplus)) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_IS_CONSTANT(expr) __builtin_constant_p(expr) +#endif +#if !defined(__cplusplus) +# if \ + JSON_HEDLEY_HAS_BUILTIN(__builtin_types_compatible_p) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0) || \ + JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,24) +#if defined(__INTPTR_TYPE__) + #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0)), int*) +#else + #include + #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((intptr_t) ((expr) * 0)) : (int*) 0)), int*) +#endif +# elif \ + ( \ + defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) && \ + !defined(JSON_HEDLEY_SUNPRO_VERSION) && \ + !defined(JSON_HEDLEY_PGI_VERSION) && \ + !defined(JSON_HEDLEY_IAR_VERSION)) || \ + (JSON_HEDLEY_HAS_EXTENSION(c_generic_selections) && !defined(JSON_HEDLEY_IAR_VERSION)) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,3,0) +#if defined(__INTPTR_TYPE__) + #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0), int*: 1, void*: 0) +#else + #include + #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((intptr_t) * 0) : (int*) 0), int*: 1, void*: 0) +#endif +# elif \ + defined(JSON_HEDLEY_GCC_VERSION) || \ + defined(JSON_HEDLEY_INTEL_VERSION) || \ + defined(JSON_HEDLEY_TINYC_VERSION) || \ + defined(JSON_HEDLEY_TI_ARMCL_VERSION) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(18,12,0) || \ + defined(JSON_HEDLEY_TI_CL2000_VERSION) || \ + defined(JSON_HEDLEY_TI_CL6X_VERSION) || \ + defined(JSON_HEDLEY_TI_CL7X_VERSION) || \ + defined(JSON_HEDLEY_TI_CLPRU_VERSION) || \ + defined(__clang__) +# define JSON_HEDLEY_IS_CONSTEXPR_(expr) ( \ + sizeof(void) != \ + sizeof(*( \ + 1 ? \ + ((void*) ((expr) * 0L) ) : \ +((struct { char v[sizeof(void) * 2]; } *) 1) \ + ) \ + ) \ + ) +# endif +#endif +#if defined(JSON_HEDLEY_IS_CONSTEXPR_) + #if !defined(JSON_HEDLEY_IS_CONSTANT) + #define JSON_HEDLEY_IS_CONSTANT(expr) JSON_HEDLEY_IS_CONSTEXPR_(expr) + #endif + #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (JSON_HEDLEY_IS_CONSTEXPR_(expr) ? (expr) : (-1)) +#else + #if !defined(JSON_HEDLEY_IS_CONSTANT) + #define JSON_HEDLEY_IS_CONSTANT(expr) (0) + #endif + #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (expr) +#endif + +#if defined(JSON_HEDLEY_BEGIN_C_DECLS) + #undef JSON_HEDLEY_BEGIN_C_DECLS +#endif +#if defined(JSON_HEDLEY_END_C_DECLS) + #undef JSON_HEDLEY_END_C_DECLS +#endif +#if defined(JSON_HEDLEY_C_DECL) + #undef JSON_HEDLEY_C_DECL +#endif +#if defined(__cplusplus) + #define JSON_HEDLEY_BEGIN_C_DECLS extern "C" { + #define JSON_HEDLEY_END_C_DECLS } + #define JSON_HEDLEY_C_DECL extern "C" +#else + #define JSON_HEDLEY_BEGIN_C_DECLS + #define JSON_HEDLEY_END_C_DECLS + #define JSON_HEDLEY_C_DECL +#endif + +#if defined(JSON_HEDLEY_STATIC_ASSERT) + #undef JSON_HEDLEY_STATIC_ASSERT +#endif +#if \ + !defined(__cplusplus) && ( \ + (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)) || \ + (JSON_HEDLEY_HAS_FEATURE(c_static_assert) && !defined(JSON_HEDLEY_INTEL_CL_VERSION)) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(6,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + defined(_Static_assert) \ + ) +# define JSON_HEDLEY_STATIC_ASSERT(expr, message) _Static_assert(expr, message) +#elif \ + (defined(__cplusplus) && (__cplusplus >= 201103L)) || \ + JSON_HEDLEY_MSVC_VERSION_CHECK(16,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) +# define JSON_HEDLEY_STATIC_ASSERT(expr, message) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(static_assert(expr, message)) +#else +# define JSON_HEDLEY_STATIC_ASSERT(expr, message) +#endif + +#if defined(JSON_HEDLEY_NULL) + #undef JSON_HEDLEY_NULL +#endif +#if defined(__cplusplus) + #if __cplusplus >= 201103L + #define JSON_HEDLEY_NULL JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(nullptr) + #elif defined(NULL) + #define JSON_HEDLEY_NULL NULL + #else + #define JSON_HEDLEY_NULL JSON_HEDLEY_STATIC_CAST(void*, 0) + #endif +#elif defined(NULL) + #define JSON_HEDLEY_NULL NULL +#else + #define JSON_HEDLEY_NULL ((void*) 0) +#endif + +#if defined(JSON_HEDLEY_MESSAGE) + #undef JSON_HEDLEY_MESSAGE +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") +# define JSON_HEDLEY_MESSAGE(msg) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \ + JSON_HEDLEY_PRAGMA(message msg) \ + JSON_HEDLEY_DIAGNOSTIC_POP +#elif \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) +# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message msg) +#elif JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0) +# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(_CRI message msg) +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) +# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg)) +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,0,0) +# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg)) +#else +# define JSON_HEDLEY_MESSAGE(msg) +#endif + +#if defined(JSON_HEDLEY_WARNING) + #undef JSON_HEDLEY_WARNING +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") +# define JSON_HEDLEY_WARNING(msg) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \ + JSON_HEDLEY_PRAGMA(clang warning msg) \ + JSON_HEDLEY_DIAGNOSTIC_POP +#elif \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,8,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) +# define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(GCC warning msg) +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) +# define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(message(msg)) +#else +# define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_MESSAGE(msg) +#endif + +#if defined(JSON_HEDLEY_REQUIRE) + #undef JSON_HEDLEY_REQUIRE +#endif +#if defined(JSON_HEDLEY_REQUIRE_MSG) + #undef JSON_HEDLEY_REQUIRE_MSG +#endif +#if JSON_HEDLEY_HAS_ATTRIBUTE(diagnose_if) +# if JSON_HEDLEY_HAS_WARNING("-Wgcc-compat") +# define JSON_HEDLEY_REQUIRE(expr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \ + __attribute__((diagnose_if(!(expr), #expr, "error"))) \ + JSON_HEDLEY_DIAGNOSTIC_POP +# define JSON_HEDLEY_REQUIRE_MSG(expr,msg) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \ + __attribute__((diagnose_if(!(expr), msg, "error"))) \ + JSON_HEDLEY_DIAGNOSTIC_POP +# else +# define JSON_HEDLEY_REQUIRE(expr) __attribute__((diagnose_if(!(expr), #expr, "error"))) +# define JSON_HEDLEY_REQUIRE_MSG(expr,msg) __attribute__((diagnose_if(!(expr), msg, "error"))) +# endif +#else +# define JSON_HEDLEY_REQUIRE(expr) +# define JSON_HEDLEY_REQUIRE_MSG(expr,msg) +#endif + +#if defined(JSON_HEDLEY_FLAGS) + #undef JSON_HEDLEY_FLAGS +#endif +#if JSON_HEDLEY_HAS_ATTRIBUTE(flag_enum) && (!defined(__cplusplus) || JSON_HEDLEY_HAS_WARNING("-Wbitfield-enum-conversion")) + #define JSON_HEDLEY_FLAGS __attribute__((__flag_enum__)) +#else + #define JSON_HEDLEY_FLAGS +#endif + +#if defined(JSON_HEDLEY_FLAGS_CAST) + #undef JSON_HEDLEY_FLAGS_CAST +#endif +#if JSON_HEDLEY_INTEL_VERSION_CHECK(19,0,0) +# define JSON_HEDLEY_FLAGS_CAST(T, expr) (__extension__ ({ \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("warning(disable:188)") \ + ((T) (expr)); \ + JSON_HEDLEY_DIAGNOSTIC_POP \ + })) +#else +# define JSON_HEDLEY_FLAGS_CAST(T, expr) JSON_HEDLEY_STATIC_CAST(T, expr) +#endif + +#if defined(JSON_HEDLEY_EMPTY_BASES) + #undef JSON_HEDLEY_EMPTY_BASES +#endif +#if \ + (JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,23918) && !JSON_HEDLEY_MSVC_VERSION_CHECK(20,0,0)) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_EMPTY_BASES __declspec(empty_bases) +#else + #define JSON_HEDLEY_EMPTY_BASES +#endif + +/* Remaining macros are deprecated. */ + +#if defined(JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK) + #undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK +#endif +#if defined(__clang__) + #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) (0) +#else + #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_CLANG_HAS_ATTRIBUTE) + #undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE +#endif +#define JSON_HEDLEY_CLANG_HAS_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_ATTRIBUTE(attribute) + +#if defined(JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE) + #undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE +#endif +#define JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) + +#if defined(JSON_HEDLEY_CLANG_HAS_BUILTIN) + #undef JSON_HEDLEY_CLANG_HAS_BUILTIN +#endif +#define JSON_HEDLEY_CLANG_HAS_BUILTIN(builtin) JSON_HEDLEY_HAS_BUILTIN(builtin) + +#if defined(JSON_HEDLEY_CLANG_HAS_FEATURE) + #undef JSON_HEDLEY_CLANG_HAS_FEATURE +#endif +#define JSON_HEDLEY_CLANG_HAS_FEATURE(feature) JSON_HEDLEY_HAS_FEATURE(feature) + +#if defined(JSON_HEDLEY_CLANG_HAS_EXTENSION) + #undef JSON_HEDLEY_CLANG_HAS_EXTENSION +#endif +#define JSON_HEDLEY_CLANG_HAS_EXTENSION(extension) JSON_HEDLEY_HAS_EXTENSION(extension) + +#if defined(JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE) + #undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE +#endif +#define JSON_HEDLEY_CLANG_HAS_DECLSPEC_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) + +#if defined(JSON_HEDLEY_CLANG_HAS_WARNING) + #undef JSON_HEDLEY_CLANG_HAS_WARNING +#endif +#define JSON_HEDLEY_CLANG_HAS_WARNING(warning) JSON_HEDLEY_HAS_WARNING(warning) + +#endif /* !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < X) */ + + +// This file contains all internal macro definitions +// You MUST include macro_unscope.hpp at the end of json.hpp to undef all of them + +// exclude unsupported compilers +#if !defined(JSON_SKIP_UNSUPPORTED_COMPILER_CHECK) + #if defined(__clang__) + #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400 + #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers" + #endif + #elif defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER)) + #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40800 + #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers" + #endif + #endif +#endif + +// C++ language standard detection +// if the user manually specified the used c++ version this is skipped +#if !defined(JSON_HAS_CPP_20) && !defined(JSON_HAS_CPP_17) && !defined(JSON_HAS_CPP_14) && !defined(JSON_HAS_CPP_11) + #if (defined(__cplusplus) && __cplusplus >= 202002L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 202002L) + #define JSON_HAS_CPP_20 + #define JSON_HAS_CPP_17 + #define JSON_HAS_CPP_14 + #elif (defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464 + #define JSON_HAS_CPP_17 + #define JSON_HAS_CPP_14 + #elif (defined(__cplusplus) && __cplusplus >= 201402L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1) + #define JSON_HAS_CPP_14 + #endif + // the cpp 11 flag is always specified because it is the minimal required version + #define JSON_HAS_CPP_11 +#endif + +// disable documentation warnings on clang +#if defined(__clang__) + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wdocumentation" +#endif + +// allow to disable exceptions +#if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(JSON_NOEXCEPTION) + #define JSON_THROW(exception) throw exception + #define JSON_TRY try + #define JSON_CATCH(exception) catch(exception) + #define JSON_INTERNAL_CATCH(exception) catch(exception) +#else + #include + #define JSON_THROW(exception) std::abort() + #define JSON_TRY if(true) + #define JSON_CATCH(exception) if(false) + #define JSON_INTERNAL_CATCH(exception) if(false) +#endif + +// override exception macros +#if defined(JSON_THROW_USER) + #undef JSON_THROW + #define JSON_THROW JSON_THROW_USER +#endif +#if defined(JSON_TRY_USER) + #undef JSON_TRY + #define JSON_TRY JSON_TRY_USER +#endif +#if defined(JSON_CATCH_USER) + #undef JSON_CATCH + #define JSON_CATCH JSON_CATCH_USER + #undef JSON_INTERNAL_CATCH + #define JSON_INTERNAL_CATCH JSON_CATCH_USER +#endif +#if defined(JSON_INTERNAL_CATCH_USER) + #undef JSON_INTERNAL_CATCH + #define JSON_INTERNAL_CATCH JSON_INTERNAL_CATCH_USER +#endif + +// allow to override assert +#if !defined(JSON_ASSERT) + #include // assert + #define JSON_ASSERT(x) assert(x) +#endif + +// allow to access some private functions (needed by the test suite) +#if defined(JSON_TESTS_PRIVATE) + #define JSON_PRIVATE_UNLESS_TESTED public +#else + #define JSON_PRIVATE_UNLESS_TESTED private +#endif + +/*! +@brief macro to briefly define a mapping between an enum and JSON +@def NLOHMANN_JSON_SERIALIZE_ENUM +@since version 3.4.0 +*/ +#define NLOHMANN_JSON_SERIALIZE_ENUM(ENUM_TYPE, ...) \ + template \ + inline void to_json(BasicJsonType& j, const ENUM_TYPE& e) \ + { \ + static_assert(std::is_enum::value, #ENUM_TYPE " must be an enum!"); \ + static const std::pair m[] = __VA_ARGS__; \ + auto it = std::find_if(std::begin(m), std::end(m), \ + [e](const std::pair& ej_pair) -> bool \ + { \ + return ej_pair.first == e; \ + }); \ + j = ((it != std::end(m)) ? it : std::begin(m))->second; \ + } \ + template \ + inline void from_json(const BasicJsonType& j, ENUM_TYPE& e) \ + { \ + static_assert(std::is_enum::value, #ENUM_TYPE " must be an enum!"); \ + static const std::pair m[] = __VA_ARGS__; \ + auto it = std::find_if(std::begin(m), std::end(m), \ + [&j](const std::pair& ej_pair) -> bool \ + { \ + return ej_pair.second == j; \ + }); \ + e = ((it != std::end(m)) ? it : std::begin(m))->first; \ + } + +// Ugly macros to avoid uglier copy-paste when specializing basic_json. They +// may be removed in the future once the class is split. + +#define NLOHMANN_BASIC_JSON_TPL_DECLARATION \ + template class ObjectType, \ + template class ArrayType, \ + class StringType, class BooleanType, class NumberIntegerType, \ + class NumberUnsignedType, class NumberFloatType, \ + template class AllocatorType, \ + template class JSONSerializer, \ + class BinaryType> + +#define NLOHMANN_BASIC_JSON_TPL \ + basic_json + +// Macros to simplify conversion from/to types + +#define NLOHMANN_JSON_EXPAND( x ) x +#define NLOHMANN_JSON_GET_MACRO(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54, _55, _56, _57, _58, _59, _60, _61, _62, _63, _64, NAME,...) NAME +#define NLOHMANN_JSON_PASTE(...) NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_GET_MACRO(__VA_ARGS__, \ + NLOHMANN_JSON_PASTE64, \ + NLOHMANN_JSON_PASTE63, \ + NLOHMANN_JSON_PASTE62, \ + NLOHMANN_JSON_PASTE61, \ + NLOHMANN_JSON_PASTE60, \ + NLOHMANN_JSON_PASTE59, \ + NLOHMANN_JSON_PASTE58, \ + NLOHMANN_JSON_PASTE57, \ + NLOHMANN_JSON_PASTE56, \ + NLOHMANN_JSON_PASTE55, \ + NLOHMANN_JSON_PASTE54, \ + NLOHMANN_JSON_PASTE53, \ + NLOHMANN_JSON_PASTE52, \ + NLOHMANN_JSON_PASTE51, \ + NLOHMANN_JSON_PASTE50, \ + NLOHMANN_JSON_PASTE49, \ + NLOHMANN_JSON_PASTE48, \ + NLOHMANN_JSON_PASTE47, \ + NLOHMANN_JSON_PASTE46, \ + NLOHMANN_JSON_PASTE45, \ + NLOHMANN_JSON_PASTE44, \ + NLOHMANN_JSON_PASTE43, \ + NLOHMANN_JSON_PASTE42, \ + NLOHMANN_JSON_PASTE41, \ + NLOHMANN_JSON_PASTE40, \ + NLOHMANN_JSON_PASTE39, \ + NLOHMANN_JSON_PASTE38, \ + NLOHMANN_JSON_PASTE37, \ + NLOHMANN_JSON_PASTE36, \ + NLOHMANN_JSON_PASTE35, \ + NLOHMANN_JSON_PASTE34, \ + NLOHMANN_JSON_PASTE33, \ + NLOHMANN_JSON_PASTE32, \ + NLOHMANN_JSON_PASTE31, \ + NLOHMANN_JSON_PASTE30, \ + NLOHMANN_JSON_PASTE29, \ + NLOHMANN_JSON_PASTE28, \ + NLOHMANN_JSON_PASTE27, \ + NLOHMANN_JSON_PASTE26, \ + NLOHMANN_JSON_PASTE25, \ + NLOHMANN_JSON_PASTE24, \ + NLOHMANN_JSON_PASTE23, \ + NLOHMANN_JSON_PASTE22, \ + NLOHMANN_JSON_PASTE21, \ + NLOHMANN_JSON_PASTE20, \ + NLOHMANN_JSON_PASTE19, \ + NLOHMANN_JSON_PASTE18, \ + NLOHMANN_JSON_PASTE17, \ + NLOHMANN_JSON_PASTE16, \ + NLOHMANN_JSON_PASTE15, \ + NLOHMANN_JSON_PASTE14, \ + NLOHMANN_JSON_PASTE13, \ + NLOHMANN_JSON_PASTE12, \ + NLOHMANN_JSON_PASTE11, \ + NLOHMANN_JSON_PASTE10, \ + NLOHMANN_JSON_PASTE9, \ + NLOHMANN_JSON_PASTE8, \ + NLOHMANN_JSON_PASTE7, \ + NLOHMANN_JSON_PASTE6, \ + NLOHMANN_JSON_PASTE5, \ + NLOHMANN_JSON_PASTE4, \ + NLOHMANN_JSON_PASTE3, \ + NLOHMANN_JSON_PASTE2, \ + NLOHMANN_JSON_PASTE1)(__VA_ARGS__)) +#define NLOHMANN_JSON_PASTE2(func, v1) func(v1) +#define NLOHMANN_JSON_PASTE3(func, v1, v2) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE2(func, v2) +#define NLOHMANN_JSON_PASTE4(func, v1, v2, v3) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE3(func, v2, v3) +#define NLOHMANN_JSON_PASTE5(func, v1, v2, v3, v4) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE4(func, v2, v3, v4) +#define NLOHMANN_JSON_PASTE6(func, v1, v2, v3, v4, v5) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE5(func, v2, v3, v4, v5) +#define NLOHMANN_JSON_PASTE7(func, v1, v2, v3, v4, v5, v6) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE6(func, v2, v3, v4, v5, v6) +#define NLOHMANN_JSON_PASTE8(func, v1, v2, v3, v4, v5, v6, v7) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE7(func, v2, v3, v4, v5, v6, v7) +#define NLOHMANN_JSON_PASTE9(func, v1, v2, v3, v4, v5, v6, v7, v8) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE8(func, v2, v3, v4, v5, v6, v7, v8) +#define NLOHMANN_JSON_PASTE10(func, v1, v2, v3, v4, v5, v6, v7, v8, v9) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE9(func, v2, v3, v4, v5, v6, v7, v8, v9) +#define NLOHMANN_JSON_PASTE11(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE10(func, v2, v3, v4, v5, v6, v7, v8, v9, v10) +#define NLOHMANN_JSON_PASTE12(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE11(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11) +#define NLOHMANN_JSON_PASTE13(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE12(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12) +#define NLOHMANN_JSON_PASTE14(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE13(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13) +#define NLOHMANN_JSON_PASTE15(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE14(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14) +#define NLOHMANN_JSON_PASTE16(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE15(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) +#define NLOHMANN_JSON_PASTE17(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE16(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) +#define NLOHMANN_JSON_PASTE18(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE17(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17) +#define NLOHMANN_JSON_PASTE19(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE18(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18) +#define NLOHMANN_JSON_PASTE20(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE19(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19) +#define NLOHMANN_JSON_PASTE21(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE20(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20) +#define NLOHMANN_JSON_PASTE22(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE21(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21) +#define NLOHMANN_JSON_PASTE23(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE22(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22) +#define NLOHMANN_JSON_PASTE24(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE23(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23) +#define NLOHMANN_JSON_PASTE25(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE24(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24) +#define NLOHMANN_JSON_PASTE26(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE25(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25) +#define NLOHMANN_JSON_PASTE27(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE26(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26) +#define NLOHMANN_JSON_PASTE28(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE27(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27) +#define NLOHMANN_JSON_PASTE29(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE28(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28) +#define NLOHMANN_JSON_PASTE30(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE29(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29) +#define NLOHMANN_JSON_PASTE31(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE30(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30) +#define NLOHMANN_JSON_PASTE32(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE31(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31) +#define NLOHMANN_JSON_PASTE33(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE32(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32) +#define NLOHMANN_JSON_PASTE34(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE33(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33) +#define NLOHMANN_JSON_PASTE35(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE34(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34) +#define NLOHMANN_JSON_PASTE36(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE35(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35) +#define NLOHMANN_JSON_PASTE37(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE36(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36) +#define NLOHMANN_JSON_PASTE38(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE37(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37) +#define NLOHMANN_JSON_PASTE39(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE38(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38) +#define NLOHMANN_JSON_PASTE40(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE39(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39) +#define NLOHMANN_JSON_PASTE41(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE40(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40) +#define NLOHMANN_JSON_PASTE42(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE41(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41) +#define NLOHMANN_JSON_PASTE43(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE42(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42) +#define NLOHMANN_JSON_PASTE44(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE43(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43) +#define NLOHMANN_JSON_PASTE45(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE44(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44) +#define NLOHMANN_JSON_PASTE46(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE45(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45) +#define NLOHMANN_JSON_PASTE47(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE46(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46) +#define NLOHMANN_JSON_PASTE48(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE47(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47) +#define NLOHMANN_JSON_PASTE49(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE48(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48) +#define NLOHMANN_JSON_PASTE50(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE49(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49) +#define NLOHMANN_JSON_PASTE51(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE50(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50) +#define NLOHMANN_JSON_PASTE52(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE51(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51) +#define NLOHMANN_JSON_PASTE53(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE52(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52) +#define NLOHMANN_JSON_PASTE54(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE53(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53) +#define NLOHMANN_JSON_PASTE55(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE54(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54) +#define NLOHMANN_JSON_PASTE56(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE55(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55) +#define NLOHMANN_JSON_PASTE57(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE56(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56) +#define NLOHMANN_JSON_PASTE58(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE57(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57) +#define NLOHMANN_JSON_PASTE59(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE58(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58) +#define NLOHMANN_JSON_PASTE60(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE59(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59) +#define NLOHMANN_JSON_PASTE61(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE60(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60) +#define NLOHMANN_JSON_PASTE62(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE61(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61) +#define NLOHMANN_JSON_PASTE63(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE62(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62) +#define NLOHMANN_JSON_PASTE64(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62, v63) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE63(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62, v63) + +#define NLOHMANN_JSON_TO(v1) nlohmann_json_j[#v1] = nlohmann_json_t.v1; +#define NLOHMANN_JSON_FROM(v1) nlohmann_json_j.at(#v1).get_to(nlohmann_json_t.v1); + +/*! +@brief macro +@def NLOHMANN_DEFINE_TYPE_INTRUSIVE +@since version 3.9.0 +*/ +#define NLOHMANN_DEFINE_TYPE_INTRUSIVE(Type, ...) \ + friend void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + friend void from_json(const nlohmann::json& nlohmann_json_j, Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) } + +/*! +@brief macro +@def NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE +@since version 3.9.0 +*/ +#define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(Type, ...) \ + inline void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + inline void from_json(const nlohmann::json& nlohmann_json_j, Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) } + +#ifndef JSON_USE_IMPLICIT_CONVERSIONS + #define JSON_USE_IMPLICIT_CONVERSIONS 1 +#endif + +#if JSON_USE_IMPLICIT_CONVERSIONS + #define JSON_EXPLICIT +#else + #define JSON_EXPLICIT explicit +#endif + + +namespace nlohmann +{ +namespace detail +{ + +/*! +@brief replace all occurrences of a substring by another string + +@param[in,out] s the string to manipulate; changed so that all + occurrences of @a f are replaced with @a t +@param[in] f the substring to replace with @a t +@param[in] t the string to replace @a f + +@pre The search string @a f must not be empty. **This precondition is +enforced with an assertion.** + +@since version 2.0.0 +*/ +inline void replace_substring(std::string& s, const std::string& f, + const std::string& t) +{ + JSON_ASSERT(!f.empty()); + for (auto pos = s.find(f); // find first occurrence of f + pos != std::string::npos; // make sure f was found + s.replace(pos, f.size(), t), // replace with t, and + pos = s.find(f, pos + t.size())) // find next occurrence of f + {} +} + +/*! + * @brief string escaping as described in RFC 6901 (Sect. 4) + * @param[in] s string to escape + * @return escaped string + * + * Note the order of escaping "~" to "~0" and "/" to "~1" is important. + */ +inline std::string escape(std::string s) +{ + replace_substring(s, "~", "~0"); + replace_substring(s, "/", "~1"); + return s; +} + +/*! + * @brief string unescaping as described in RFC 6901 (Sect. 4) + * @param[in] s string to unescape + * @return unescaped string + * + * Note the order of escaping "~1" to "/" and "~0" to "~" is important. + */ +static void unescape(std::string& s) +{ + replace_substring(s, "~1", "/"); + replace_substring(s, "~0", "~"); +} + +} // namespace detail +} // namespace nlohmann + +// #include + + +#include // size_t + +namespace nlohmann +{ +namespace detail +{ +/// struct to capture the start position of the current token +struct position_t +{ + /// the total number of characters read + std::size_t chars_read_total = 0; + /// the number of characters read in the current line + std::size_t chars_read_current_line = 0; + /// the number of lines read + std::size_t lines_read = 0; + + /// conversion to size_t to preserve SAX interface + constexpr operator size_t() const + { + return chars_read_total; + } +}; + +} // namespace detail +} // namespace nlohmann + +// #include + + +namespace nlohmann +{ +namespace detail +{ +//////////////// +// exceptions // +//////////////// + +/*! +@brief general exception of the @ref basic_json class + +This class is an extension of `std::exception` objects with a member @a id for +exception ids. It is used as the base class for all exceptions thrown by the +@ref basic_json class. This class can hence be used as "wildcard" to catch +exceptions. + +Subclasses: +- @ref parse_error for exceptions indicating a parse error +- @ref invalid_iterator for exceptions indicating errors with iterators +- @ref type_error for exceptions indicating executing a member function with + a wrong type +- @ref out_of_range for exceptions indicating access out of the defined range +- @ref other_error for exceptions indicating other library errors + +@internal +@note To have nothrow-copy-constructible exceptions, we internally use + `std::runtime_error` which can cope with arbitrary-length error messages. + Intermediate strings are built with static functions and then passed to + the actual constructor. +@endinternal + +@liveexample{The following code shows how arbitrary library exceptions can be +caught.,exception} + +@since version 3.0.0 +*/ +class exception : public std::exception +{ + public: + /// returns the explanatory string + const char* what() const noexcept override + { + return m.what(); + } + + /// the id of the exception + const int id; // NOLINT(cppcoreguidelines-non-private-member-variables-in-classes) + + protected: + JSON_HEDLEY_NON_NULL(3) + exception(int id_, const char* what_arg) : id(id_), m(what_arg) {} + + static std::string name(const std::string& ename, int id_) + { + return "[json.exception." + ename + "." + std::to_string(id_) + "] "; + } + + template + static std::string diagnostics(const BasicJsonType& leaf_element) + { +#if JSON_DIAGNOSTICS + std::vector tokens; + for (const auto* current = &leaf_element; current->m_parent != nullptr; current = current->m_parent) + { + switch (current->m_parent->type()) + { + case value_t::array: + { + for (std::size_t i = 0; i < current->m_parent->m_value.array->size(); ++i) + { + if (¤t->m_parent->m_value.array->operator[](i) == current) + { + tokens.emplace_back(std::to_string(i)); + break; + } + } + break; + } + + case value_t::object: + { + for (const auto& element : *current->m_parent->m_value.object) + { + if (&element.second == current) + { + tokens.emplace_back(element.first.c_str()); + break; + } + } + break; + } + + default: // LCOV_EXCL_LINE + break; // LCOV_EXCL_LINE + } + } + + if (tokens.empty()) + { + return ""; + } + + return "(" + std::accumulate(tokens.rbegin(), tokens.rend(), std::string{}, + [](const std::string & a, const std::string & b) + { + return a + "/" + detail::escape(b); + }) + ") "; +#else + static_cast(leaf_element); + return ""; +#endif + } + + private: + /// an exception object as storage for error messages + std::runtime_error m; +}; + +/*! +@brief exception indicating a parse error + +This exception is thrown by the library when a parse error occurs. Parse errors +can occur during the deserialization of JSON text, CBOR, MessagePack, as well +as when using JSON Patch. + +Member @a byte holds the byte index of the last read character in the input +file. + +Exceptions have ids 1xx. + +name / id | example message | description +------------------------------ | --------------- | ------------------------- +json.exception.parse_error.101 | parse error at 2: unexpected end of input; expected string literal | This error indicates a syntax error while deserializing a JSON text. The error message describes that an unexpected token (character) was encountered, and the member @a byte indicates the error position. +json.exception.parse_error.102 | parse error at 14: missing or wrong low surrogate | JSON uses the `\uxxxx` format to describe Unicode characters. Code points above above 0xFFFF are split into two `\uxxxx` entries ("surrogate pairs"). This error indicates that the surrogate pair is incomplete or contains an invalid code point. +json.exception.parse_error.103 | parse error: code points above 0x10FFFF are invalid | Unicode supports code points up to 0x10FFFF. Code points above 0x10FFFF are invalid. +json.exception.parse_error.104 | parse error: JSON patch must be an array of objects | [RFC 6902](https://tools.ietf.org/html/rfc6902) requires a JSON Patch document to be a JSON document that represents an array of objects. +json.exception.parse_error.105 | parse error: operation must have string member 'op' | An operation of a JSON Patch document must contain exactly one "op" member, whose value indicates the operation to perform. Its value must be one of "add", "remove", "replace", "move", "copy", or "test"; other values are errors. +json.exception.parse_error.106 | parse error: array index '01' must not begin with '0' | An array index in a JSON Pointer ([RFC 6901](https://tools.ietf.org/html/rfc6901)) may be `0` or any number without a leading `0`. +json.exception.parse_error.107 | parse error: JSON pointer must be empty or begin with '/' - was: 'foo' | A JSON Pointer must be a Unicode string containing a sequence of zero or more reference tokens, each prefixed by a `/` character. +json.exception.parse_error.108 | parse error: escape character '~' must be followed with '0' or '1' | In a JSON Pointer, only `~0` and `~1` are valid escape sequences. +json.exception.parse_error.109 | parse error: array index 'one' is not a number | A JSON Pointer array index must be a number. +json.exception.parse_error.110 | parse error at 1: cannot read 2 bytes from vector | When parsing CBOR or MessagePack, the byte vector ends before the complete value has been read. +json.exception.parse_error.112 | parse error at 1: error reading CBOR; last byte: 0xF8 | Not all types of CBOR or MessagePack are supported. This exception occurs if an unsupported byte was read. +json.exception.parse_error.113 | parse error at 2: expected a CBOR string; last byte: 0x98 | While parsing a map key, a value that is not a string has been read. +json.exception.parse_error.114 | parse error: Unsupported BSON record type 0x0F | The parsing of the corresponding BSON record type is not implemented (yet). +json.exception.parse_error.115 | parse error at byte 5: syntax error while parsing UBJSON high-precision number: invalid number text: 1A | A UBJSON high-precision number could not be parsed. + +@note For an input with n bytes, 1 is the index of the first character and n+1 + is the index of the terminating null byte or the end of file. This also + holds true when reading a byte vector (CBOR or MessagePack). + +@liveexample{The following code shows how a `parse_error` exception can be +caught.,parse_error} + +@sa - @ref exception for the base class of the library exceptions +@sa - @ref invalid_iterator for exceptions indicating errors with iterators +@sa - @ref type_error for exceptions indicating executing a member function with + a wrong type +@sa - @ref out_of_range for exceptions indicating access out of the defined range +@sa - @ref other_error for exceptions indicating other library errors + +@since version 3.0.0 +*/ +class parse_error : public exception +{ + public: + /*! + @brief create a parse error exception + @param[in] id_ the id of the exception + @param[in] pos the position where the error occurred (or with + chars_read_total=0 if the position cannot be + determined) + @param[in] what_arg the explanatory string + @return parse_error object + */ + template + static parse_error create(int id_, const position_t& pos, const std::string& what_arg, const BasicJsonType& context) + { + std::string w = exception::name("parse_error", id_) + "parse error" + + position_string(pos) + ": " + exception::diagnostics(context) + what_arg; + return parse_error(id_, pos.chars_read_total, w.c_str()); + } + + template + static parse_error create(int id_, std::size_t byte_, const std::string& what_arg, const BasicJsonType& context) + { + std::string w = exception::name("parse_error", id_) + "parse error" + + (byte_ != 0 ? (" at byte " + std::to_string(byte_)) : "") + + ": " + exception::diagnostics(context) + what_arg; + return parse_error(id_, byte_, w.c_str()); + } + + /*! + @brief byte index of the parse error + + The byte index of the last read character in the input file. + + @note For an input with n bytes, 1 is the index of the first character and + n+1 is the index of the terminating null byte or the end of file. + This also holds true when reading a byte vector (CBOR or MessagePack). + */ + const std::size_t byte; + + private: + parse_error(int id_, std::size_t byte_, const char* what_arg) + : exception(id_, what_arg), byte(byte_) {} + + static std::string position_string(const position_t& pos) + { + return " at line " + std::to_string(pos.lines_read + 1) + + ", column " + std::to_string(pos.chars_read_current_line); + } +}; + +/*! +@brief exception indicating errors with iterators + +This exception is thrown if iterators passed to a library function do not match +the expected semantics. + +Exceptions have ids 2xx. + +name / id | example message | description +----------------------------------- | --------------- | ------------------------- +json.exception.invalid_iterator.201 | iterators are not compatible | The iterators passed to constructor @ref basic_json(InputIT first, InputIT last) are not compatible, meaning they do not belong to the same container. Therefore, the range (@a first, @a last) is invalid. +json.exception.invalid_iterator.202 | iterator does not fit current value | In an erase or insert function, the passed iterator @a pos does not belong to the JSON value for which the function was called. It hence does not define a valid position for the deletion/insertion. +json.exception.invalid_iterator.203 | iterators do not fit current value | Either iterator passed to function @ref erase(IteratorType first, IteratorType last) does not belong to the JSON value from which values shall be erased. It hence does not define a valid range to delete values from. +json.exception.invalid_iterator.204 | iterators out of range | When an iterator range for a primitive type (number, boolean, or string) is passed to a constructor or an erase function, this range has to be exactly (@ref begin(), @ref end()), because this is the only way the single stored value is expressed. All other ranges are invalid. +json.exception.invalid_iterator.205 | iterator out of range | When an iterator for a primitive type (number, boolean, or string) is passed to an erase function, the iterator has to be the @ref begin() iterator, because it is the only way to address the stored value. All other iterators are invalid. +json.exception.invalid_iterator.206 | cannot construct with iterators from null | The iterators passed to constructor @ref basic_json(InputIT first, InputIT last) belong to a JSON null value and hence to not define a valid range. +json.exception.invalid_iterator.207 | cannot use key() for non-object iterators | The key() member function can only be used on iterators belonging to a JSON object, because other types do not have a concept of a key. +json.exception.invalid_iterator.208 | cannot use operator[] for object iterators | The operator[] to specify a concrete offset cannot be used on iterators belonging to a JSON object, because JSON objects are unordered. +json.exception.invalid_iterator.209 | cannot use offsets with object iterators | The offset operators (+, -, +=, -=) cannot be used on iterators belonging to a JSON object, because JSON objects are unordered. +json.exception.invalid_iterator.210 | iterators do not fit | The iterator range passed to the insert function are not compatible, meaning they do not belong to the same container. Therefore, the range (@a first, @a last) is invalid. +json.exception.invalid_iterator.211 | passed iterators may not belong to container | The iterator range passed to the insert function must not be a subrange of the container to insert to. +json.exception.invalid_iterator.212 | cannot compare iterators of different containers | When two iterators are compared, they must belong to the same container. +json.exception.invalid_iterator.213 | cannot compare order of object iterators | The order of object iterators cannot be compared, because JSON objects are unordered. +json.exception.invalid_iterator.214 | cannot get value | Cannot get value for iterator: Either the iterator belongs to a null value or it is an iterator to a primitive type (number, boolean, or string), but the iterator is different to @ref begin(). + +@liveexample{The following code shows how an `invalid_iterator` exception can be +caught.,invalid_iterator} + +@sa - @ref exception for the base class of the library exceptions +@sa - @ref parse_error for exceptions indicating a parse error +@sa - @ref type_error for exceptions indicating executing a member function with + a wrong type +@sa - @ref out_of_range for exceptions indicating access out of the defined range +@sa - @ref other_error for exceptions indicating other library errors + +@since version 3.0.0 +*/ +class invalid_iterator : public exception +{ + public: + template + static invalid_iterator create(int id_, const std::string& what_arg, const BasicJsonType& context) + { + std::string w = exception::name("invalid_iterator", id_) + exception::diagnostics(context) + what_arg; + return invalid_iterator(id_, w.c_str()); + } + + private: + JSON_HEDLEY_NON_NULL(3) + invalid_iterator(int id_, const char* what_arg) + : exception(id_, what_arg) {} +}; + +/*! +@brief exception indicating executing a member function with a wrong type + +This exception is thrown in case of a type error; that is, a library function is +executed on a JSON value whose type does not match the expected semantics. + +Exceptions have ids 3xx. + +name / id | example message | description +----------------------------- | --------------- | ------------------------- +json.exception.type_error.301 | cannot create object from initializer list | To create an object from an initializer list, the initializer list must consist only of a list of pairs whose first element is a string. When this constraint is violated, an array is created instead. +json.exception.type_error.302 | type must be object, but is array | During implicit or explicit value conversion, the JSON type must be compatible to the target type. For instance, a JSON string can only be converted into string types, but not into numbers or boolean types. +json.exception.type_error.303 | incompatible ReferenceType for get_ref, actual type is object | To retrieve a reference to a value stored in a @ref basic_json object with @ref get_ref, the type of the reference must match the value type. For instance, for a JSON array, the @a ReferenceType must be @ref array_t &. +json.exception.type_error.304 | cannot use at() with string | The @ref at() member functions can only be executed for certain JSON types. +json.exception.type_error.305 | cannot use operator[] with string | The @ref operator[] member functions can only be executed for certain JSON types. +json.exception.type_error.306 | cannot use value() with string | The @ref value() member functions can only be executed for certain JSON types. +json.exception.type_error.307 | cannot use erase() with string | The @ref erase() member functions can only be executed for certain JSON types. +json.exception.type_error.308 | cannot use push_back() with string | The @ref push_back() and @ref operator+= member functions can only be executed for certain JSON types. +json.exception.type_error.309 | cannot use insert() with | The @ref insert() member functions can only be executed for certain JSON types. +json.exception.type_error.310 | cannot use swap() with number | The @ref swap() member functions can only be executed for certain JSON types. +json.exception.type_error.311 | cannot use emplace_back() with string | The @ref emplace_back() member function can only be executed for certain JSON types. +json.exception.type_error.312 | cannot use update() with string | The @ref update() member functions can only be executed for certain JSON types. +json.exception.type_error.313 | invalid value to unflatten | The @ref unflatten function converts an object whose keys are JSON Pointers back into an arbitrary nested JSON value. The JSON Pointers must not overlap, because then the resulting value would not be well defined. +json.exception.type_error.314 | only objects can be unflattened | The @ref unflatten function only works for an object whose keys are JSON Pointers. +json.exception.type_error.315 | values in object must be primitive | The @ref unflatten function only works for an object whose keys are JSON Pointers and whose values are primitive. +json.exception.type_error.316 | invalid UTF-8 byte at index 10: 0x7E | The @ref dump function only works with UTF-8 encoded strings; that is, if you assign a `std::string` to a JSON value, make sure it is UTF-8 encoded. | +json.exception.type_error.317 | JSON value cannot be serialized to requested format | The dynamic type of the object cannot be represented in the requested serialization format (e.g. a raw `true` or `null` JSON object cannot be serialized to BSON) | + +@liveexample{The following code shows how a `type_error` exception can be +caught.,type_error} + +@sa - @ref exception for the base class of the library exceptions +@sa - @ref parse_error for exceptions indicating a parse error +@sa - @ref invalid_iterator for exceptions indicating errors with iterators +@sa - @ref out_of_range for exceptions indicating access out of the defined range +@sa - @ref other_error for exceptions indicating other library errors + +@since version 3.0.0 +*/ +class type_error : public exception +{ + public: + template + static type_error create(int id_, const std::string& what_arg, const BasicJsonType& context) + { + std::string w = exception::name("type_error", id_) + exception::diagnostics(context) + what_arg; + return type_error(id_, w.c_str()); + } + + private: + JSON_HEDLEY_NON_NULL(3) + type_error(int id_, const char* what_arg) : exception(id_, what_arg) {} +}; + +/*! +@brief exception indicating access out of the defined range + +This exception is thrown in case a library function is called on an input +parameter that exceeds the expected range, for instance in case of array +indices or nonexisting object keys. + +Exceptions have ids 4xx. + +name / id | example message | description +------------------------------- | --------------- | ------------------------- +json.exception.out_of_range.401 | array index 3 is out of range | The provided array index @a i is larger than @a size-1. +json.exception.out_of_range.402 | array index '-' (3) is out of range | The special array index `-` in a JSON Pointer never describes a valid element of the array, but the index past the end. That is, it can only be used to add elements at this position, but not to read it. +json.exception.out_of_range.403 | key 'foo' not found | The provided key was not found in the JSON object. +json.exception.out_of_range.404 | unresolved reference token 'foo' | A reference token in a JSON Pointer could not be resolved. +json.exception.out_of_range.405 | JSON pointer has no parent | The JSON Patch operations 'remove' and 'add' can not be applied to the root element of the JSON value. +json.exception.out_of_range.406 | number overflow parsing '10E1000' | A parsed number could not be stored as without changing it to NaN or INF. +json.exception.out_of_range.407 | number overflow serializing '9223372036854775808' | UBJSON and BSON only support integer numbers up to 9223372036854775807. (until version 3.8.0) | +json.exception.out_of_range.408 | excessive array size: 8658170730974374167 | The size (following `#`) of an UBJSON array or object exceeds the maximal capacity. | +json.exception.out_of_range.409 | BSON key cannot contain code point U+0000 (at byte 2) | Key identifiers to be serialized to BSON cannot contain code point U+0000, since the key is stored as zero-terminated c-string | + +@liveexample{The following code shows how an `out_of_range` exception can be +caught.,out_of_range} + +@sa - @ref exception for the base class of the library exceptions +@sa - @ref parse_error for exceptions indicating a parse error +@sa - @ref invalid_iterator for exceptions indicating errors with iterators +@sa - @ref type_error for exceptions indicating executing a member function with + a wrong type +@sa - @ref other_error for exceptions indicating other library errors + +@since version 3.0.0 +*/ +class out_of_range : public exception +{ + public: + template + static out_of_range create(int id_, const std::string& what_arg, const BasicJsonType& context) + { + std::string w = exception::name("out_of_range", id_) + exception::diagnostics(context) + what_arg; + return out_of_range(id_, w.c_str()); + } + + private: + JSON_HEDLEY_NON_NULL(3) + out_of_range(int id_, const char* what_arg) : exception(id_, what_arg) {} +}; + +/*! +@brief exception indicating other library errors + +This exception is thrown in case of errors that cannot be classified with the +other exception types. + +Exceptions have ids 5xx. + +name / id | example message | description +------------------------------ | --------------- | ------------------------- +json.exception.other_error.501 | unsuccessful: {"op":"test","path":"/baz", "value":"bar"} | A JSON Patch operation 'test' failed. The unsuccessful operation is also printed. + +@sa - @ref exception for the base class of the library exceptions +@sa - @ref parse_error for exceptions indicating a parse error +@sa - @ref invalid_iterator for exceptions indicating errors with iterators +@sa - @ref type_error for exceptions indicating executing a member function with + a wrong type +@sa - @ref out_of_range for exceptions indicating access out of the defined range + +@liveexample{The following code shows how an `other_error` exception can be +caught.,other_error} + +@since version 3.0.0 +*/ +class other_error : public exception +{ + public: + template + static other_error create(int id_, const std::string& what_arg, const BasicJsonType& context) + { + std::string w = exception::name("other_error", id_) + exception::diagnostics(context) + what_arg; + return other_error(id_, w.c_str()); + } + + private: + JSON_HEDLEY_NON_NULL(3) + other_error(int id_, const char* what_arg) : exception(id_, what_arg) {} +}; +} // namespace detail +} // namespace nlohmann + +// #include + +// #include + + +#include // size_t +#include // conditional, enable_if, false_type, integral_constant, is_constructible, is_integral, is_same, remove_cv, remove_reference, true_type +#include // index_sequence, make_index_sequence, index_sequence_for + +// #include + + +namespace nlohmann +{ +namespace detail +{ + +template +using uncvref_t = typename std::remove_cv::type>::type; + +#ifdef JSON_HAS_CPP_14 + +// the following utilities are natively available in C++14 +using std::enable_if_t; +using std::index_sequence; +using std::make_index_sequence; +using std::index_sequence_for; + +#else + +// alias templates to reduce boilerplate +template +using enable_if_t = typename std::enable_if::type; + +// The following code is taken from https://github.com/abseil/abseil-cpp/blob/10cb35e459f5ecca5b2ff107635da0bfa41011b4/absl/utility/utility.h +// which is part of Google Abseil (https://github.com/abseil/abseil-cpp), licensed under the Apache License 2.0. + +//// START OF CODE FROM GOOGLE ABSEIL + +// integer_sequence +// +// Class template representing a compile-time integer sequence. An instantiation +// of `integer_sequence` has a sequence of integers encoded in its +// type through its template arguments (which is a common need when +// working with C++11 variadic templates). `absl::integer_sequence` is designed +// to be a drop-in replacement for C++14's `std::integer_sequence`. +// +// Example: +// +// template< class T, T... Ints > +// void user_function(integer_sequence); +// +// int main() +// { +// // user_function's `T` will be deduced to `int` and `Ints...` +// // will be deduced to `0, 1, 2, 3, 4`. +// user_function(make_integer_sequence()); +// } +template +struct integer_sequence +{ + using value_type = T; + static constexpr std::size_t size() noexcept + { + return sizeof...(Ints); + } +}; + +// index_sequence +// +// A helper template for an `integer_sequence` of `size_t`, +// `absl::index_sequence` is designed to be a drop-in replacement for C++14's +// `std::index_sequence`. +template +using index_sequence = integer_sequence; + +namespace utility_internal +{ + +template +struct Extend; + +// Note that SeqSize == sizeof...(Ints). It's passed explicitly for efficiency. +template +struct Extend, SeqSize, 0> +{ + using type = integer_sequence < T, Ints..., (Ints + SeqSize)... >; +}; + +template +struct Extend, SeqSize, 1> +{ + using type = integer_sequence < T, Ints..., (Ints + SeqSize)..., 2 * SeqSize >; +}; + +// Recursion helper for 'make_integer_sequence'. +// 'Gen::type' is an alias for 'integer_sequence'. +template +struct Gen +{ + using type = + typename Extend < typename Gen < T, N / 2 >::type, N / 2, N % 2 >::type; +}; + +template +struct Gen +{ + using type = integer_sequence; +}; + +} // namespace utility_internal + +// Compile-time sequences of integers + +// make_integer_sequence +// +// This template alias is equivalent to +// `integer_sequence`, and is designed to be a drop-in +// replacement for C++14's `std::make_integer_sequence`. +template +using make_integer_sequence = typename utility_internal::Gen::type; + +// make_index_sequence +// +// This template alias is equivalent to `index_sequence<0, 1, ..., N-1>`, +// and is designed to be a drop-in replacement for C++14's +// `std::make_index_sequence`. +template +using make_index_sequence = make_integer_sequence; + +// index_sequence_for +// +// Converts a typename pack into an index sequence of the same length, and +// is designed to be a drop-in replacement for C++14's +// `std::index_sequence_for()` +template +using index_sequence_for = make_index_sequence; + +//// END OF CODE FROM GOOGLE ABSEIL + +#endif + +// dispatch utility (taken from ranges-v3) +template struct priority_tag : priority_tag < N - 1 > {}; +template<> struct priority_tag<0> {}; + +// taken from ranges-v3 +template +struct static_const +{ + static constexpr T value{}; +}; + +template +constexpr T static_const::value; + +} // namespace detail +} // namespace nlohmann + +// #include + + +namespace nlohmann +{ +namespace detail +{ +// dispatching helper struct +template struct identity_tag {}; +} // namespace detail +} // namespace nlohmann + +// #include + + +#include // numeric_limits +#include // false_type, is_constructible, is_integral, is_same, true_type +#include // declval +#include // tuple + +// #include + + +#include // random_access_iterator_tag + +// #include + + +namespace nlohmann +{ +namespace detail +{ +template struct make_void +{ + using type = void; +}; +template using void_t = typename make_void::type; +} // namespace detail +} // namespace nlohmann + +// #include + + +namespace nlohmann +{ +namespace detail +{ +template +struct iterator_types {}; + +template +struct iterator_types < + It, + void_t> +{ + using difference_type = typename It::difference_type; + using value_type = typename It::value_type; + using pointer = typename It::pointer; + using reference = typename It::reference; + using iterator_category = typename It::iterator_category; +}; + +// This is required as some compilers implement std::iterator_traits in a way that +// doesn't work with SFINAE. See https://github.com/nlohmann/json/issues/1341. +template +struct iterator_traits +{ +}; + +template +struct iterator_traits < T, enable_if_t < !std::is_pointer::value >> + : iterator_types +{ +}; + +template +struct iterator_traits::value>> +{ + using iterator_category = std::random_access_iterator_tag; + using value_type = T; + using difference_type = ptrdiff_t; + using pointer = T*; + using reference = T&; +}; +} // namespace detail +} // namespace nlohmann + +// #include + +// #include + +// #include + + +#include + +// #include + + +// https://en.cppreference.com/w/cpp/experimental/is_detected +namespace nlohmann +{ +namespace detail +{ +struct nonesuch +{ + nonesuch() = delete; + ~nonesuch() = delete; + nonesuch(nonesuch const&) = delete; + nonesuch(nonesuch const&&) = delete; + void operator=(nonesuch const&) = delete; + void operator=(nonesuch&&) = delete; +}; + +template class Op, + class... Args> +struct detector +{ + using value_t = std::false_type; + using type = Default; +}; + +template class Op, class... Args> +struct detector>, Op, Args...> +{ + using value_t = std::true_type; + using type = Op; +}; + +template class Op, class... Args> +using is_detected = typename detector::value_t; + +template class Op, class... Args> +using detected_t = typename detector::type; + +template class Op, class... Args> +using detected_or = detector; + +template class Op, class... Args> +using detected_or_t = typename detected_or::type; + +template class Op, class... Args> +using is_detected_exact = std::is_same>; + +template class Op, class... Args> +using is_detected_convertible = + std::is_convertible, To>; +} // namespace detail +} // namespace nlohmann + +// #include +#ifndef INCLUDE_NLOHMANN_JSON_FWD_HPP_ +#define INCLUDE_NLOHMANN_JSON_FWD_HPP_ + +#include // int64_t, uint64_t +#include // map +#include // allocator +#include // string +#include // vector + +/*! +@brief namespace for Niels Lohmann +@see https://github.com/nlohmann +@since version 1.0.0 +*/ +namespace nlohmann +{ +/*! +@brief default JSONSerializer template argument + +This serializer ignores the template arguments and uses ADL +([argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl)) +for serialization. +*/ +template +struct adl_serializer; + +template class ObjectType = + std::map, + template class ArrayType = std::vector, + class StringType = std::string, class BooleanType = bool, + class NumberIntegerType = std::int64_t, + class NumberUnsignedType = std::uint64_t, + class NumberFloatType = double, + template class AllocatorType = std::allocator, + template class JSONSerializer = + adl_serializer, + class BinaryType = std::vector> +class basic_json; + +/*! +@brief JSON Pointer + +A JSON pointer defines a string syntax for identifying a specific value +within a JSON document. It can be used with functions `at` and +`operator[]`. Furthermore, JSON pointers are the base for JSON patches. + +@sa [RFC 6901](https://tools.ietf.org/html/rfc6901) + +@since version 2.0.0 +*/ +template +class json_pointer; + +/*! +@brief default JSON class + +This type is the default specialization of the @ref basic_json class which +uses the standard template types. + +@since version 1.0.0 +*/ +using json = basic_json<>; + +template +struct ordered_map; + +/*! +@brief ordered JSON class + +This type preserves the insertion order of object keys. + +@since version 3.9.0 +*/ +using ordered_json = basic_json; + +} // namespace nlohmann + +#endif // INCLUDE_NLOHMANN_JSON_FWD_HPP_ + + +namespace nlohmann +{ +/*! +@brief detail namespace with internal helper functions + +This namespace collects functions that should not be exposed, +implementations of some @ref basic_json methods, and meta-programming helpers. + +@since version 2.1.0 +*/ +namespace detail +{ +///////////// +// helpers // +///////////// + +// Note to maintainers: +// +// Every trait in this file expects a non CV-qualified type. +// The only exceptions are in the 'aliases for detected' section +// (i.e. those of the form: decltype(T::member_function(std::declval()))) +// +// In this case, T has to be properly CV-qualified to constraint the function arguments +// (e.g. to_json(BasicJsonType&, const T&)) + +template struct is_basic_json : std::false_type {}; + +NLOHMANN_BASIC_JSON_TPL_DECLARATION +struct is_basic_json : std::true_type {}; + +////////////////////// +// json_ref helpers // +////////////////////// + +template +class json_ref; + +template +struct is_json_ref : std::false_type {}; + +template +struct is_json_ref> : std::true_type {}; + +////////////////////////// +// aliases for detected // +////////////////////////// + +template +using mapped_type_t = typename T::mapped_type; + +template +using key_type_t = typename T::key_type; + +template +using value_type_t = typename T::value_type; + +template +using difference_type_t = typename T::difference_type; + +template +using pointer_t = typename T::pointer; + +template +using reference_t = typename T::reference; + +template +using iterator_category_t = typename T::iterator_category; + +template +using iterator_t = typename T::iterator; + +template +using to_json_function = decltype(T::to_json(std::declval()...)); + +template +using from_json_function = decltype(T::from_json(std::declval()...)); + +template +using get_template_function = decltype(std::declval().template get()); + +// trait checking if JSONSerializer::from_json(json const&, udt&) exists +template +struct has_from_json : std::false_type {}; + +// trait checking if j.get is valid +// use this trait instead of std::is_constructible or std::is_convertible, +// both rely on, or make use of implicit conversions, and thus fail when T +// has several constructors/operator= (see https://github.com/nlohmann/json/issues/958) +template +struct is_getable +{ + static constexpr bool value = is_detected::value; +}; + +template +struct has_from_json < BasicJsonType, T, enable_if_t < !is_basic_json::value >> +{ + using serializer = typename BasicJsonType::template json_serializer; + + static constexpr bool value = + is_detected_exact::value; +}; + +// This trait checks if JSONSerializer::from_json(json const&) exists +// this overload is used for non-default-constructible user-defined-types +template +struct has_non_default_from_json : std::false_type {}; + +template +struct has_non_default_from_json < BasicJsonType, T, enable_if_t < !is_basic_json::value >> +{ + using serializer = typename BasicJsonType::template json_serializer; + + static constexpr bool value = + is_detected_exact::value; +}; + +// This trait checks if BasicJsonType::json_serializer::to_json exists +// Do not evaluate the trait when T is a basic_json type, to avoid template instantiation infinite recursion. +template +struct has_to_json : std::false_type {}; + +template +struct has_to_json < BasicJsonType, T, enable_if_t < !is_basic_json::value >> +{ + using serializer = typename BasicJsonType::template json_serializer; + + static constexpr bool value = + is_detected_exact::value; +}; + + +/////////////////// +// is_ functions // +/////////////////// + +// https://en.cppreference.com/w/cpp/types/conjunction +template struct conjunction : std::true_type { }; +template struct conjunction : B1 { }; +template +struct conjunction +: std::conditional, B1>::type {}; + +// Reimplementation of is_constructible and is_default_constructible, due to them being broken for +// std::pair and std::tuple until LWG 2367 fix (see https://cplusplus.github.io/LWG/lwg-defects.html#2367). +// This causes compile errors in e.g. clang 3.5 or gcc 4.9. +template +struct is_default_constructible : std::is_default_constructible {}; + +template +struct is_default_constructible> + : conjunction, is_default_constructible> {}; + +template +struct is_default_constructible> + : conjunction, is_default_constructible> {}; + +template +struct is_default_constructible> + : conjunction...> {}; + +template +struct is_default_constructible> + : conjunction...> {}; + + +template +struct is_constructible : std::is_constructible {}; + +template +struct is_constructible> : is_default_constructible> {}; + +template +struct is_constructible> : is_default_constructible> {}; + +template +struct is_constructible> : is_default_constructible> {}; + +template +struct is_constructible> : is_default_constructible> {}; + + +template +struct is_iterator_traits : std::false_type {}; + +template +struct is_iterator_traits> +{ + private: + using traits = iterator_traits; + + public: + static constexpr auto value = + is_detected::value && + is_detected::value && + is_detected::value && + is_detected::value && + is_detected::value; +}; + +// The following implementation of is_complete_type is taken from +// https://blogs.msdn.microsoft.com/vcblog/2015/12/02/partial-support-for-expression-sfinae-in-vs-2015-update-1/ +// and is written by Xiang Fan who agreed to using it in this library. + +template +struct is_complete_type : std::false_type {}; + +template +struct is_complete_type : std::true_type {}; + +template +struct is_compatible_object_type_impl : std::false_type {}; + +template +struct is_compatible_object_type_impl < + BasicJsonType, CompatibleObjectType, + enable_if_t < is_detected::value&& + is_detected::value >> +{ + using object_t = typename BasicJsonType::object_t; + + // macOS's is_constructible does not play well with nonesuch... + static constexpr bool value = + is_constructible::value && + is_constructible::value; +}; + +template +struct is_compatible_object_type + : is_compatible_object_type_impl {}; + +template +struct is_constructible_object_type_impl : std::false_type {}; + +template +struct is_constructible_object_type_impl < + BasicJsonType, ConstructibleObjectType, + enable_if_t < is_detected::value&& + is_detected::value >> +{ + using object_t = typename BasicJsonType::object_t; + + static constexpr bool value = + (is_default_constructible::value && + (std::is_move_assignable::value || + std::is_copy_assignable::value) && + (is_constructible::value && + std::is_same < + typename object_t::mapped_type, + typename ConstructibleObjectType::mapped_type >::value)) || + (has_from_json::value || + has_non_default_from_json < + BasicJsonType, + typename ConstructibleObjectType::mapped_type >::value); +}; + +template +struct is_constructible_object_type + : is_constructible_object_type_impl {}; + +template +struct is_compatible_string_type_impl : std::false_type {}; + +template +struct is_compatible_string_type_impl < + BasicJsonType, CompatibleStringType, + enable_if_t::value >> +{ + static constexpr auto value = + is_constructible::value; +}; + +template +struct is_compatible_string_type + : is_compatible_string_type_impl {}; + +template +struct is_constructible_string_type_impl : std::false_type {}; + +template +struct is_constructible_string_type_impl < + BasicJsonType, ConstructibleStringType, + enable_if_t::value >> +{ + static constexpr auto value = + is_constructible::value; +}; + +template +struct is_constructible_string_type + : is_constructible_string_type_impl {}; + +template +struct is_compatible_array_type_impl : std::false_type {}; + +template +struct is_compatible_array_type_impl < + BasicJsonType, CompatibleArrayType, + enable_if_t < is_detected::value&& + is_detected::value&& +// This is needed because json_reverse_iterator has a ::iterator type... +// Therefore it is detected as a CompatibleArrayType. +// The real fix would be to have an Iterable concept. + !is_iterator_traits < + iterator_traits>::value >> +{ + static constexpr bool value = + is_constructible::value; +}; + +template +struct is_compatible_array_type + : is_compatible_array_type_impl {}; + +template +struct is_constructible_array_type_impl : std::false_type {}; + +template +struct is_constructible_array_type_impl < + BasicJsonType, ConstructibleArrayType, + enable_if_t::value >> + : std::true_type {}; + +template +struct is_constructible_array_type_impl < + BasicJsonType, ConstructibleArrayType, + enable_if_t < !std::is_same::value&& + is_default_constructible::value&& +(std::is_move_assignable::value || + std::is_copy_assignable::value)&& +is_detected::value&& +is_detected::value&& +is_complete_type < +detected_t>::value >> +{ + static constexpr bool value = + // This is needed because json_reverse_iterator has a ::iterator type, + // furthermore, std::back_insert_iterator (and other iterators) have a + // base class `iterator`... Therefore it is detected as a + // ConstructibleArrayType. The real fix would be to have an Iterable + // concept. + !is_iterator_traits>::value && + + (std::is_same::value || + has_from_json::value || + has_non_default_from_json < + BasicJsonType, typename ConstructibleArrayType::value_type >::value); +}; + +template +struct is_constructible_array_type + : is_constructible_array_type_impl {}; + +template +struct is_compatible_integer_type_impl : std::false_type {}; + +template +struct is_compatible_integer_type_impl < + RealIntegerType, CompatibleNumberIntegerType, + enable_if_t < std::is_integral::value&& + std::is_integral::value&& + !std::is_same::value >> +{ + // is there an assert somewhere on overflows? + using RealLimits = std::numeric_limits; + using CompatibleLimits = std::numeric_limits; + + static constexpr auto value = + is_constructible::value && + CompatibleLimits::is_integer && + RealLimits::is_signed == CompatibleLimits::is_signed; +}; + +template +struct is_compatible_integer_type + : is_compatible_integer_type_impl {}; + +template +struct is_compatible_type_impl: std::false_type {}; + +template +struct is_compatible_type_impl < + BasicJsonType, CompatibleType, + enable_if_t::value >> +{ + static constexpr bool value = + has_to_json::value; +}; + +template +struct is_compatible_type + : is_compatible_type_impl {}; + +template +struct is_constructible_tuple : std::false_type {}; + +template +struct is_constructible_tuple> : conjunction...> {}; +} // namespace detail +} // namespace nlohmann + +// #include + + +namespace nlohmann +{ +namespace detail +{ +template +void from_json(const BasicJsonType& j, typename std::nullptr_t& n) +{ + if (JSON_HEDLEY_UNLIKELY(!j.is_null())) + { + JSON_THROW(type_error::create(302, "type must be null, but is " + std::string(j.type_name()), j)); + } + n = nullptr; +} + +// overloads for basic_json template parameters +template < typename BasicJsonType, typename ArithmeticType, + enable_if_t < std::is_arithmetic::value&& + !std::is_same::value, + int > = 0 > +void get_arithmetic_value(const BasicJsonType& j, ArithmeticType& val) +{ + switch (static_cast(j)) + { + case value_t::number_unsigned: + { + val = static_cast(*j.template get_ptr()); + break; + } + case value_t::number_integer: + { + val = static_cast(*j.template get_ptr()); + break; + } + case value_t::number_float: + { + val = static_cast(*j.template get_ptr()); + break; + } + + default: + JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name()), j)); + } +} + +template +void from_json(const BasicJsonType& j, typename BasicJsonType::boolean_t& b) +{ + if (JSON_HEDLEY_UNLIKELY(!j.is_boolean())) + { + JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(j.type_name()), j)); + } + b = *j.template get_ptr(); +} + +template +void from_json(const BasicJsonType& j, typename BasicJsonType::string_t& s) +{ + if (JSON_HEDLEY_UNLIKELY(!j.is_string())) + { + JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name()), j)); + } + s = *j.template get_ptr(); +} + +template < + typename BasicJsonType, typename ConstructibleStringType, + enable_if_t < + is_constructible_string_type::value&& + !std::is_same::value, + int > = 0 > +void from_json(const BasicJsonType& j, ConstructibleStringType& s) +{ + if (JSON_HEDLEY_UNLIKELY(!j.is_string())) + { + JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name()), j)); + } + + s = *j.template get_ptr(); +} + +template +void from_json(const BasicJsonType& j, typename BasicJsonType::number_float_t& val) +{ + get_arithmetic_value(j, val); +} + +template +void from_json(const BasicJsonType& j, typename BasicJsonType::number_unsigned_t& val) +{ + get_arithmetic_value(j, val); +} + +template +void from_json(const BasicJsonType& j, typename BasicJsonType::number_integer_t& val) +{ + get_arithmetic_value(j, val); +} + +template::value, int> = 0> +void from_json(const BasicJsonType& j, EnumType& e) +{ + typename std::underlying_type::type val; + get_arithmetic_value(j, val); + e = static_cast(val); +} + +// forward_list doesn't have an insert method +template::value, int> = 0> +void from_json(const BasicJsonType& j, std::forward_list& l) +{ + if (JSON_HEDLEY_UNLIKELY(!j.is_array())) + { + JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j)); + } + l.clear(); + std::transform(j.rbegin(), j.rend(), + std::front_inserter(l), [](const BasicJsonType & i) + { + return i.template get(); + }); +} + +// valarray doesn't have an insert method +template::value, int> = 0> +void from_json(const BasicJsonType& j, std::valarray& l) +{ + if (JSON_HEDLEY_UNLIKELY(!j.is_array())) + { + JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j)); + } + l.resize(j.size()); + std::transform(j.begin(), j.end(), std::begin(l), + [](const BasicJsonType & elem) + { + return elem.template get(); + }); +} + +template +auto from_json(const BasicJsonType& j, T (&arr)[N]) // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) +-> decltype(j.template get(), void()) +{ + for (std::size_t i = 0; i < N; ++i) + { + arr[i] = j.at(i).template get(); + } +} + +template +void from_json_array_impl(const BasicJsonType& j, typename BasicJsonType::array_t& arr, priority_tag<3> /*unused*/) +{ + arr = *j.template get_ptr(); +} + +template +auto from_json_array_impl(const BasicJsonType& j, std::array& arr, + priority_tag<2> /*unused*/) +-> decltype(j.template get(), void()) +{ + for (std::size_t i = 0; i < N; ++i) + { + arr[i] = j.at(i).template get(); + } +} + +template::value, + int> = 0> +auto from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr, priority_tag<1> /*unused*/) +-> decltype( + arr.reserve(std::declval()), + j.template get(), + void()) +{ + using std::end; + + ConstructibleArrayType ret; + ret.reserve(j.size()); + std::transform(j.begin(), j.end(), + std::inserter(ret, end(ret)), [](const BasicJsonType & i) + { + // get() returns *this, this won't call a from_json + // method when value_type is BasicJsonType + return i.template get(); + }); + arr = std::move(ret); +} + +template::value, + int> = 0> +void from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr, + priority_tag<0> /*unused*/) +{ + using std::end; + + ConstructibleArrayType ret; + std::transform( + j.begin(), j.end(), std::inserter(ret, end(ret)), + [](const BasicJsonType & i) + { + // get() returns *this, this won't call a from_json + // method when value_type is BasicJsonType + return i.template get(); + }); + arr = std::move(ret); +} + +template < typename BasicJsonType, typename ConstructibleArrayType, + enable_if_t < + is_constructible_array_type::value&& + !is_constructible_object_type::value&& + !is_constructible_string_type::value&& + !std::is_same::value&& + !is_basic_json::value, + int > = 0 > +auto from_json(const BasicJsonType& j, ConstructibleArrayType& arr) +-> decltype(from_json_array_impl(j, arr, priority_tag<3> {}), +j.template get(), +void()) +{ + if (JSON_HEDLEY_UNLIKELY(!j.is_array())) + { + JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j)); + } + + from_json_array_impl(j, arr, priority_tag<3> {}); +} + +template < typename BasicJsonType, typename T, std::size_t... Idx > +std::array from_json_inplace_array_impl(BasicJsonType&& j, + identity_tag> /*unused*/, index_sequence /*unused*/) +{ + return { { std::forward(j).at(Idx).template get()... } }; +} + +template < typename BasicJsonType, typename T, std::size_t N > +auto from_json(BasicJsonType&& j, identity_tag> tag) +-> decltype(from_json_inplace_array_impl(std::forward(j), tag, make_index_sequence {})) +{ + if (JSON_HEDLEY_UNLIKELY(!j.is_array())) + { + JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j)); + } + + return from_json_inplace_array_impl(std::forward(j), tag, make_index_sequence {}); +} + +template +void from_json(const BasicJsonType& j, typename BasicJsonType::binary_t& bin) +{ + if (JSON_HEDLEY_UNLIKELY(!j.is_binary())) + { + JSON_THROW(type_error::create(302, "type must be binary, but is " + std::string(j.type_name()), j)); + } + + bin = *j.template get_ptr(); +} + +template::value, int> = 0> +void from_json(const BasicJsonType& j, ConstructibleObjectType& obj) +{ + if (JSON_HEDLEY_UNLIKELY(!j.is_object())) + { + JSON_THROW(type_error::create(302, "type must be object, but is " + std::string(j.type_name()), j)); + } + + ConstructibleObjectType ret; + const auto* inner_object = j.template get_ptr(); + using value_type = typename ConstructibleObjectType::value_type; + std::transform( + inner_object->begin(), inner_object->end(), + std::inserter(ret, ret.begin()), + [](typename BasicJsonType::object_t::value_type const & p) + { + return value_type(p.first, p.second.template get()); + }); + obj = std::move(ret); +} + +// overload for arithmetic types, not chosen for basic_json template arguments +// (BooleanType, etc..); note: Is it really necessary to provide explicit +// overloads for boolean_t etc. in case of a custom BooleanType which is not +// an arithmetic type? +template < typename BasicJsonType, typename ArithmeticType, + enable_if_t < + std::is_arithmetic::value&& + !std::is_same::value&& + !std::is_same::value&& + !std::is_same::value&& + !std::is_same::value, + int > = 0 > +void from_json(const BasicJsonType& j, ArithmeticType& val) +{ + switch (static_cast(j)) + { + case value_t::number_unsigned: + { + val = static_cast(*j.template get_ptr()); + break; + } + case value_t::number_integer: + { + val = static_cast(*j.template get_ptr()); + break; + } + case value_t::number_float: + { + val = static_cast(*j.template get_ptr()); + break; + } + case value_t::boolean: + { + val = static_cast(*j.template get_ptr()); + break; + } + + default: + JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name()), j)); + } +} + +template +std::tuple from_json_tuple_impl_base(BasicJsonType&& j, index_sequence /*unused*/) +{ + return std::make_tuple(std::forward(j).at(Idx).template get()...); +} + +template < typename BasicJsonType, class A1, class A2 > +std::pair from_json_tuple_impl(BasicJsonType&& j, identity_tag> /*unused*/, priority_tag<0> /*unused*/) +{ + return {std::forward(j).at(0).template get(), + std::forward(j).at(1).template get()}; +} + +template +void from_json_tuple_impl(BasicJsonType&& j, std::pair& p, priority_tag<1> /*unused*/) +{ + p = from_json_tuple_impl(std::forward(j), identity_tag> {}, priority_tag<0> {}); +} + +template +std::tuple from_json_tuple_impl(BasicJsonType&& j, identity_tag> /*unused*/, priority_tag<2> /*unused*/) +{ + return from_json_tuple_impl_base(std::forward(j), index_sequence_for {}); +} + +template +void from_json_tuple_impl(BasicJsonType&& j, std::tuple& t, priority_tag<3> /*unused*/) +{ + t = from_json_tuple_impl_base(std::forward(j), index_sequence_for {}); +} + +template +auto from_json(BasicJsonType&& j, TupleRelated&& t) +-> decltype(from_json_tuple_impl(std::forward(j), std::forward(t), priority_tag<3> {})) +{ + if (JSON_HEDLEY_UNLIKELY(!j.is_array())) + { + JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j)); + } + + return from_json_tuple_impl(std::forward(j), std::forward(t), priority_tag<3> {}); +} + +template < typename BasicJsonType, typename Key, typename Value, typename Compare, typename Allocator, + typename = enable_if_t < !std::is_constructible < + typename BasicJsonType::string_t, Key >::value >> +void from_json(const BasicJsonType& j, std::map& m) +{ + if (JSON_HEDLEY_UNLIKELY(!j.is_array())) + { + JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j)); + } + m.clear(); + for (const auto& p : j) + { + if (JSON_HEDLEY_UNLIKELY(!p.is_array())) + { + JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name()), j)); + } + m.emplace(p.at(0).template get(), p.at(1).template get()); + } +} + +template < typename BasicJsonType, typename Key, typename Value, typename Hash, typename KeyEqual, typename Allocator, + typename = enable_if_t < !std::is_constructible < + typename BasicJsonType::string_t, Key >::value >> +void from_json(const BasicJsonType& j, std::unordered_map& m) +{ + if (JSON_HEDLEY_UNLIKELY(!j.is_array())) + { + JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j)); + } + m.clear(); + for (const auto& p : j) + { + if (JSON_HEDLEY_UNLIKELY(!p.is_array())) + { + JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name()), j)); + } + m.emplace(p.at(0).template get(), p.at(1).template get()); + } +} + +struct from_json_fn +{ + template + auto operator()(const BasicJsonType& j, T&& val) const + noexcept(noexcept(from_json(j, std::forward(val)))) + -> decltype(from_json(j, std::forward(val))) + { + return from_json(j, std::forward(val)); + } +}; +} // namespace detail + +/// namespace to hold default `from_json` function +/// to see why this is required: +/// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html +namespace // NOLINT(cert-dcl59-cpp,fuchsia-header-anon-namespaces,google-build-namespaces) +{ +constexpr const auto& from_json = detail::static_const::value; // NOLINT(misc-definitions-in-headers) +} // namespace +} // namespace nlohmann + +// #include + + +#include // copy +#include // begin, end +#include // string +#include // tuple, get +#include // is_same, is_constructible, is_floating_point, is_enum, underlying_type +#include // move, forward, declval, pair +#include // valarray +#include // vector + +// #include + + +#include // size_t +#include // input_iterator_tag +#include // string, to_string +#include // tuple_size, get, tuple_element +#include // move + +// #include + +// #include + + +namespace nlohmann +{ +namespace detail +{ +template +void int_to_string( string_type& target, std::size_t value ) +{ + // For ADL + using std::to_string; + target = to_string(value); +} +template class iteration_proxy_value +{ + public: + using difference_type = std::ptrdiff_t; + using value_type = iteration_proxy_value; + using pointer = value_type * ; + using reference = value_type & ; + using iterator_category = std::input_iterator_tag; + using string_type = typename std::remove_cv< typename std::remove_reference().key() ) >::type >::type; + + private: + /// the iterator + IteratorType anchor; + /// an index for arrays (used to create key names) + std::size_t array_index = 0; + /// last stringified array index + mutable std::size_t array_index_last = 0; + /// a string representation of the array index + mutable string_type array_index_str = "0"; + /// an empty string (to return a reference for primitive values) + const string_type empty_str{}; + + public: + explicit iteration_proxy_value(IteratorType it) noexcept + : anchor(std::move(it)) + {} + + /// dereference operator (needed for range-based for) + iteration_proxy_value& operator*() + { + return *this; + } + + /// increment operator (needed for range-based for) + iteration_proxy_value& operator++() + { + ++anchor; + ++array_index; + + return *this; + } + + /// equality operator (needed for InputIterator) + bool operator==(const iteration_proxy_value& o) const + { + return anchor == o.anchor; + } + + /// inequality operator (needed for range-based for) + bool operator!=(const iteration_proxy_value& o) const + { + return anchor != o.anchor; + } + + /// return key of the iterator + const string_type& key() const + { + JSON_ASSERT(anchor.m_object != nullptr); + + switch (anchor.m_object->type()) + { + // use integer array index as key + case value_t::array: + { + if (array_index != array_index_last) + { + int_to_string( array_index_str, array_index ); + array_index_last = array_index; + } + return array_index_str; + } + + // use key from the object + case value_t::object: + return anchor.key(); + + // use an empty key for all primitive types + default: + return empty_str; + } + } + + /// return value of the iterator + typename IteratorType::reference value() const + { + return anchor.value(); + } +}; + +/// proxy class for the items() function +template class iteration_proxy +{ + private: + /// the container to iterate + typename IteratorType::reference container; + + public: + /// construct iteration proxy from a container + explicit iteration_proxy(typename IteratorType::reference cont) noexcept + : container(cont) {} + + /// return iterator begin (needed for range-based for) + iteration_proxy_value begin() noexcept + { + return iteration_proxy_value(container.begin()); + } + + /// return iterator end (needed for range-based for) + iteration_proxy_value end() noexcept + { + return iteration_proxy_value(container.end()); + } +}; +// Structured Bindings Support +// For further reference see https://blog.tartanllama.xyz/structured-bindings/ +// And see https://github.com/nlohmann/json/pull/1391 +template = 0> +auto get(const nlohmann::detail::iteration_proxy_value& i) -> decltype(i.key()) +{ + return i.key(); +} +// Structured Bindings Support +// For further reference see https://blog.tartanllama.xyz/structured-bindings/ +// And see https://github.com/nlohmann/json/pull/1391 +template = 0> +auto get(const nlohmann::detail::iteration_proxy_value& i) -> decltype(i.value()) +{ + return i.value(); +} +} // namespace detail +} // namespace nlohmann + +// The Addition to the STD Namespace is required to add +// Structured Bindings Support to the iteration_proxy_value class +// For further reference see https://blog.tartanllama.xyz/structured-bindings/ +// And see https://github.com/nlohmann/json/pull/1391 +namespace std +{ +#if defined(__clang__) + // Fix: https://github.com/nlohmann/json/issues/1401 + #pragma clang diagnostic push + #pragma clang diagnostic ignored "-Wmismatched-tags" +#endif +template +class tuple_size<::nlohmann::detail::iteration_proxy_value> + : public std::integral_constant {}; + +template +class tuple_element> +{ + public: + using type = decltype( + get(std::declval < + ::nlohmann::detail::iteration_proxy_value> ())); +}; +#if defined(__clang__) + #pragma clang diagnostic pop +#endif +} // namespace std + +// #include + +// #include + +// #include + + +namespace nlohmann +{ +namespace detail +{ +////////////////// +// constructors // +////////////////// + +template struct external_constructor; + +template<> +struct external_constructor +{ + template + static void construct(BasicJsonType& j, typename BasicJsonType::boolean_t b) noexcept + { + j.m_type = value_t::boolean; + j.m_value = b; + j.assert_invariant(); + } +}; + +template<> +struct external_constructor +{ + template + static void construct(BasicJsonType& j, const typename BasicJsonType::string_t& s) + { + j.m_type = value_t::string; + j.m_value = s; + j.assert_invariant(); + } + + template + static void construct(BasicJsonType& j, typename BasicJsonType::string_t&& s) + { + j.m_type = value_t::string; + j.m_value = std::move(s); + j.assert_invariant(); + } + + template < typename BasicJsonType, typename CompatibleStringType, + enable_if_t < !std::is_same::value, + int > = 0 > + static void construct(BasicJsonType& j, const CompatibleStringType& str) + { + j.m_type = value_t::string; + j.m_value.string = j.template create(str); + j.assert_invariant(); + } +}; + +template<> +struct external_constructor +{ + template + static void construct(BasicJsonType& j, const typename BasicJsonType::binary_t& b) + { + j.m_type = value_t::binary; + j.m_value = typename BasicJsonType::binary_t(b); + j.assert_invariant(); + } + + template + static void construct(BasicJsonType& j, typename BasicJsonType::binary_t&& b) + { + j.m_type = value_t::binary; + j.m_value = typename BasicJsonType::binary_t(std::move(b));; + j.assert_invariant(); + } +}; + +template<> +struct external_constructor +{ + template + static void construct(BasicJsonType& j, typename BasicJsonType::number_float_t val) noexcept + { + j.m_type = value_t::number_float; + j.m_value = val; + j.assert_invariant(); + } +}; + +template<> +struct external_constructor +{ + template + static void construct(BasicJsonType& j, typename BasicJsonType::number_unsigned_t val) noexcept + { + j.m_type = value_t::number_unsigned; + j.m_value = val; + j.assert_invariant(); + } +}; + +template<> +struct external_constructor +{ + template + static void construct(BasicJsonType& j, typename BasicJsonType::number_integer_t val) noexcept + { + j.m_type = value_t::number_integer; + j.m_value = val; + j.assert_invariant(); + } +}; + +template<> +struct external_constructor +{ + template + static void construct(BasicJsonType& j, const typename BasicJsonType::array_t& arr) + { + j.m_type = value_t::array; + j.m_value = arr; + j.set_parents(); + j.assert_invariant(); + } + + template + static void construct(BasicJsonType& j, typename BasicJsonType::array_t&& arr) + { + j.m_type = value_t::array; + j.m_value = std::move(arr); + j.set_parents(); + j.assert_invariant(); + } + + template < typename BasicJsonType, typename CompatibleArrayType, + enable_if_t < !std::is_same::value, + int > = 0 > + static void construct(BasicJsonType& j, const CompatibleArrayType& arr) + { + using std::begin; + using std::end; + j.m_type = value_t::array; + j.m_value.array = j.template create(begin(arr), end(arr)); + j.set_parents(); + j.assert_invariant(); + } + + template + static void construct(BasicJsonType& j, const std::vector& arr) + { + j.m_type = value_t::array; + j.m_value = value_t::array; + j.m_value.array->reserve(arr.size()); + for (const bool x : arr) + { + j.m_value.array->push_back(x); + j.set_parent(j.m_value.array->back()); + } + j.assert_invariant(); + } + + template::value, int> = 0> + static void construct(BasicJsonType& j, const std::valarray& arr) + { + j.m_type = value_t::array; + j.m_value = value_t::array; + j.m_value.array->resize(arr.size()); + if (arr.size() > 0) + { + std::copy(std::begin(arr), std::end(arr), j.m_value.array->begin()); + } + j.set_parents(); + j.assert_invariant(); + } +}; + +template<> +struct external_constructor +{ + template + static void construct(BasicJsonType& j, const typename BasicJsonType::object_t& obj) + { + j.m_type = value_t::object; + j.m_value = obj; + j.set_parents(); + j.assert_invariant(); + } + + template + static void construct(BasicJsonType& j, typename BasicJsonType::object_t&& obj) + { + j.m_type = value_t::object; + j.m_value = std::move(obj); + j.set_parents(); + j.assert_invariant(); + } + + template < typename BasicJsonType, typename CompatibleObjectType, + enable_if_t < !std::is_same::value, int > = 0 > + static void construct(BasicJsonType& j, const CompatibleObjectType& obj) + { + using std::begin; + using std::end; + + j.m_type = value_t::object; + j.m_value.object = j.template create(begin(obj), end(obj)); + j.set_parents(); + j.assert_invariant(); + } +}; + +///////////// +// to_json // +///////////// + +template::value, int> = 0> +void to_json(BasicJsonType& j, T b) noexcept +{ + external_constructor::construct(j, b); +} + +template::value, int> = 0> +void to_json(BasicJsonType& j, const CompatibleString& s) +{ + external_constructor::construct(j, s); +} + +template +void to_json(BasicJsonType& j, typename BasicJsonType::string_t&& s) +{ + external_constructor::construct(j, std::move(s)); +} + +template::value, int> = 0> +void to_json(BasicJsonType& j, FloatType val) noexcept +{ + external_constructor::construct(j, static_cast(val)); +} + +template::value, int> = 0> +void to_json(BasicJsonType& j, CompatibleNumberUnsignedType val) noexcept +{ + external_constructor::construct(j, static_cast(val)); +} + +template::value, int> = 0> +void to_json(BasicJsonType& j, CompatibleNumberIntegerType val) noexcept +{ + external_constructor::construct(j, static_cast(val)); +} + +template::value, int> = 0> +void to_json(BasicJsonType& j, EnumType e) noexcept +{ + using underlying_type = typename std::underlying_type::type; + external_constructor::construct(j, static_cast(e)); +} + +template +void to_json(BasicJsonType& j, const std::vector& e) +{ + external_constructor::construct(j, e); +} + +template < typename BasicJsonType, typename CompatibleArrayType, + enable_if_t < is_compatible_array_type::value&& + !is_compatible_object_type::value&& + !is_compatible_string_type::value&& + !std::is_same::value&& + !is_basic_json::value, + int > = 0 > +void to_json(BasicJsonType& j, const CompatibleArrayType& arr) +{ + external_constructor::construct(j, arr); +} + +template +void to_json(BasicJsonType& j, const typename BasicJsonType::binary_t& bin) +{ + external_constructor::construct(j, bin); +} + +template::value, int> = 0> +void to_json(BasicJsonType& j, const std::valarray& arr) +{ + external_constructor::construct(j, std::move(arr)); +} + +template +void to_json(BasicJsonType& j, typename BasicJsonType::array_t&& arr) +{ + external_constructor::construct(j, std::move(arr)); +} + +template < typename BasicJsonType, typename CompatibleObjectType, + enable_if_t < is_compatible_object_type::value&& !is_basic_json::value, int > = 0 > +void to_json(BasicJsonType& j, const CompatibleObjectType& obj) +{ + external_constructor::construct(j, obj); +} + +template +void to_json(BasicJsonType& j, typename BasicJsonType::object_t&& obj) +{ + external_constructor::construct(j, std::move(obj)); +} + +template < + typename BasicJsonType, typename T, std::size_t N, + enable_if_t < !std::is_constructible::value, // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) + int > = 0 > +void to_json(BasicJsonType& j, const T(&arr)[N]) // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) +{ + external_constructor::construct(j, arr); +} + +template < typename BasicJsonType, typename T1, typename T2, enable_if_t < std::is_constructible::value&& std::is_constructible::value, int > = 0 > +void to_json(BasicJsonType& j, const std::pair& p) +{ + j = { p.first, p.second }; +} + +// for https://github.com/nlohmann/json/pull/1134 +template>::value, int> = 0> +void to_json(BasicJsonType& j, const T& b) +{ + j = { {b.key(), b.value()} }; +} + +template +void to_json_tuple_impl(BasicJsonType& j, const Tuple& t, index_sequence /*unused*/) +{ + j = { std::get(t)... }; +} + +template::value, int > = 0> +void to_json(BasicJsonType& j, const T& t) +{ + to_json_tuple_impl(j, t, make_index_sequence::value> {}); +} + +struct to_json_fn +{ + template + auto operator()(BasicJsonType& j, T&& val) const noexcept(noexcept(to_json(j, std::forward(val)))) + -> decltype(to_json(j, std::forward(val)), void()) + { + return to_json(j, std::forward(val)); + } +}; +} // namespace detail + +/// namespace to hold default `to_json` function +/// to see why this is required: +/// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html +namespace // NOLINT(cert-dcl59-cpp,fuchsia-header-anon-namespaces,google-build-namespaces) +{ +constexpr const auto& to_json = detail::static_const::value; // NOLINT(misc-definitions-in-headers) +} // namespace +} // namespace nlohmann + +// #include + +// #include + + +namespace nlohmann +{ + +template +struct adl_serializer +{ + /*! + @brief convert a JSON value to any value type + + This function is usually called by the `get()` function of the + @ref basic_json class (either explicit or via conversion operators). + + @note This function is chosen for default-constructible value types. + + @param[in] j JSON value to read from + @param[in,out] val value to write to + */ + template + static auto from_json(BasicJsonType && j, TargetType& val) noexcept( + noexcept(::nlohmann::from_json(std::forward(j), val))) + -> decltype(::nlohmann::from_json(std::forward(j), val), void()) + { + ::nlohmann::from_json(std::forward(j), val); + } + + /*! + @brief convert a JSON value to any value type + + This function is usually called by the `get()` function of the + @ref basic_json class (either explicit or via conversion operators). + + @note This function is chosen for value types which are not default-constructible. + + @param[in] j JSON value to read from + + @return copy of the JSON value, converted to @a ValueType + */ + template + static auto from_json(BasicJsonType && j) noexcept( + noexcept(::nlohmann::from_json(std::forward(j), detail::identity_tag {}))) + -> decltype(::nlohmann::from_json(std::forward(j), detail::identity_tag {})) + { + return ::nlohmann::from_json(std::forward(j), detail::identity_tag {}); + } + + /*! + @brief convert any value type to a JSON value + + This function is usually called by the constructors of the @ref basic_json + class. + + @param[in,out] j JSON value to write to + @param[in] val value to read from + */ + template + static auto to_json(BasicJsonType& j, TargetType && val) noexcept( + noexcept(::nlohmann::to_json(j, std::forward(val)))) + -> decltype(::nlohmann::to_json(j, std::forward(val)), void()) + { + ::nlohmann::to_json(j, std::forward(val)); + } +}; +} // namespace nlohmann + +// #include + + +#include // uint8_t +#include // tie +#include // move + +namespace nlohmann +{ + +/*! +@brief an internal type for a backed binary type + +This type extends the template parameter @a BinaryType provided to `basic_json` +with a subtype used by BSON and MessagePack. This type exists so that the user +does not have to specify a type themselves with a specific naming scheme in +order to override the binary type. + +@tparam BinaryType container to store bytes (`std::vector` by + default) + +@since version 3.8.0 +*/ +template +class byte_container_with_subtype : public BinaryType +{ + public: + /// the type of the underlying container + using container_type = BinaryType; + + byte_container_with_subtype() noexcept(noexcept(container_type())) + : container_type() + {} + + byte_container_with_subtype(const container_type& b) noexcept(noexcept(container_type(b))) + : container_type(b) + {} + + byte_container_with_subtype(container_type&& b) noexcept(noexcept(container_type(std::move(b)))) + : container_type(std::move(b)) + {} + + byte_container_with_subtype(const container_type& b, std::uint8_t subtype_) noexcept(noexcept(container_type(b))) + : container_type(b) + , m_subtype(subtype_) + , m_has_subtype(true) + {} + + byte_container_with_subtype(container_type&& b, std::uint8_t subtype_) noexcept(noexcept(container_type(std::move(b)))) + : container_type(std::move(b)) + , m_subtype(subtype_) + , m_has_subtype(true) + {} + + bool operator==(const byte_container_with_subtype& rhs) const + { + return std::tie(static_cast(*this), m_subtype, m_has_subtype) == + std::tie(static_cast(rhs), rhs.m_subtype, rhs.m_has_subtype); + } + + bool operator!=(const byte_container_with_subtype& rhs) const + { + return !(rhs == *this); + } + + /*! + @brief sets the binary subtype + + Sets the binary subtype of the value, also flags a binary JSON value as + having a subtype, which has implications for serialization. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @sa see @ref subtype() -- return the binary subtype + @sa see @ref clear_subtype() -- clears the binary subtype + @sa see @ref has_subtype() -- returns whether or not the binary value has a + subtype + + @since version 3.8.0 + */ + void set_subtype(std::uint8_t subtype_) noexcept + { + m_subtype = subtype_; + m_has_subtype = true; + } + + /*! + @brief return the binary subtype + + Returns the numerical subtype of the value if it has a subtype. If it does + not have a subtype, this function will return size_t(-1) as a sentinel + value. + + @return the numerical subtype of the binary value + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @sa see @ref set_subtype() -- sets the binary subtype + @sa see @ref clear_subtype() -- clears the binary subtype + @sa see @ref has_subtype() -- returns whether or not the binary value has a + subtype + + @since version 3.8.0 + */ + constexpr std::uint8_t subtype() const noexcept + { + return m_subtype; + } + + /*! + @brief return whether the value has a subtype + + @return whether the value has a subtype + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @sa see @ref subtype() -- return the binary subtype + @sa see @ref set_subtype() -- sets the binary subtype + @sa see @ref clear_subtype() -- clears the binary subtype + + @since version 3.8.0 + */ + constexpr bool has_subtype() const noexcept + { + return m_has_subtype; + } + + /*! + @brief clears the binary subtype + + Clears the binary subtype and flags the value as not having a subtype, which + has implications for serialization; for instance MessagePack will prefer the + bin family over the ext family. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @sa see @ref subtype() -- return the binary subtype + @sa see @ref set_subtype() -- sets the binary subtype + @sa see @ref has_subtype() -- returns whether or not the binary value has a + subtype + + @since version 3.8.0 + */ + void clear_subtype() noexcept + { + m_subtype = 0; + m_has_subtype = false; + } + + private: + std::uint8_t m_subtype = 0; + bool m_has_subtype = false; +}; + +} // namespace nlohmann + +// #include + +// #include + +// #include + +// #include + + +#include // uint8_t +#include // size_t +#include // hash + +// #include + + +namespace nlohmann +{ +namespace detail +{ + +// boost::hash_combine +inline std::size_t combine(std::size_t seed, std::size_t h) noexcept +{ + seed ^= h + 0x9e3779b9 + (seed << 6U) + (seed >> 2U); + return seed; +} + +/*! +@brief hash a JSON value + +The hash function tries to rely on std::hash where possible. Furthermore, the +type of the JSON value is taken into account to have different hash values for +null, 0, 0U, and false, etc. + +@tparam BasicJsonType basic_json specialization +@param j JSON value to hash +@return hash value of j +*/ +template +std::size_t hash(const BasicJsonType& j) +{ + using string_t = typename BasicJsonType::string_t; + using number_integer_t = typename BasicJsonType::number_integer_t; + using number_unsigned_t = typename BasicJsonType::number_unsigned_t; + using number_float_t = typename BasicJsonType::number_float_t; + + const auto type = static_cast(j.type()); + switch (j.type()) + { + case BasicJsonType::value_t::null: + case BasicJsonType::value_t::discarded: + { + return combine(type, 0); + } + + case BasicJsonType::value_t::object: + { + auto seed = combine(type, j.size()); + for (const auto& element : j.items()) + { + const auto h = std::hash {}(element.key()); + seed = combine(seed, h); + seed = combine(seed, hash(element.value())); + } + return seed; + } + + case BasicJsonType::value_t::array: + { + auto seed = combine(type, j.size()); + for (const auto& element : j) + { + seed = combine(seed, hash(element)); + } + return seed; + } + + case BasicJsonType::value_t::string: + { + const auto h = std::hash {}(j.template get_ref()); + return combine(type, h); + } + + case BasicJsonType::value_t::boolean: + { + const auto h = std::hash {}(j.template get()); + return combine(type, h); + } + + case BasicJsonType::value_t::number_integer: + { + const auto h = std::hash {}(j.template get()); + return combine(type, h); + } + + case BasicJsonType::value_t::number_unsigned: + { + const auto h = std::hash {}(j.template get()); + return combine(type, h); + } + + case BasicJsonType::value_t::number_float: + { + const auto h = std::hash {}(j.template get()); + return combine(type, h); + } + + case BasicJsonType::value_t::binary: + { + auto seed = combine(type, j.get_binary().size()); + const auto h = std::hash {}(j.get_binary().has_subtype()); + seed = combine(seed, h); + seed = combine(seed, j.get_binary().subtype()); + for (const auto byte : j.get_binary()) + { + seed = combine(seed, std::hash {}(byte)); + } + return seed; + } + + default: // LCOV_EXCL_LINE + JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE + return 0; // LCOV_EXCL_LINE + } +} + +} // namespace detail +} // namespace nlohmann + +// #include + + +#include // generate_n +#include // array +#include // ldexp +#include // size_t +#include // uint8_t, uint16_t, uint32_t, uint64_t +#include // snprintf +#include // memcpy +#include // back_inserter +#include // numeric_limits +#include // char_traits, string +#include // make_pair, move +#include // vector + +// #include + +// #include + + +#include // array +#include // size_t +#include //FILE * +#include // strlen +#include // istream +#include // begin, end, iterator_traits, random_access_iterator_tag, distance, next +#include // shared_ptr, make_shared, addressof +#include // accumulate +#include // string, char_traits +#include // enable_if, is_base_of, is_pointer, is_integral, remove_pointer +#include // pair, declval + +// #include + +// #include + + +namespace nlohmann +{ +namespace detail +{ +/// the supported input formats +enum class input_format_t { json, cbor, msgpack, ubjson, bson }; + +//////////////////// +// input adapters // +//////////////////// + +/*! +Input adapter for stdio file access. This adapter read only 1 byte and do not use any + buffer. This adapter is a very low level adapter. +*/ +class file_input_adapter +{ + public: + using char_type = char; + + JSON_HEDLEY_NON_NULL(2) + explicit file_input_adapter(std::FILE* f) noexcept + : m_file(f) + {} + + // make class move-only + file_input_adapter(const file_input_adapter&) = delete; + file_input_adapter(file_input_adapter&&) noexcept = default; + file_input_adapter& operator=(const file_input_adapter&) = delete; + file_input_adapter& operator=(file_input_adapter&&) = delete; + ~file_input_adapter() = default; + + std::char_traits::int_type get_character() noexcept + { + return std::fgetc(m_file); + } + + private: + /// the file pointer to read from + std::FILE* m_file; +}; + + +/*! +Input adapter for a (caching) istream. Ignores a UFT Byte Order Mark at +beginning of input. Does not support changing the underlying std::streambuf +in mid-input. Maintains underlying std::istream and std::streambuf to support +subsequent use of standard std::istream operations to process any input +characters following those used in parsing the JSON input. Clears the +std::istream flags; any input errors (e.g., EOF) will be detected by the first +subsequent call for input from the std::istream. +*/ +class input_stream_adapter +{ + public: + using char_type = char; + + ~input_stream_adapter() + { + // clear stream flags; we use underlying streambuf I/O, do not + // maintain ifstream flags, except eof + if (is != nullptr) + { + is->clear(is->rdstate() & std::ios::eofbit); + } + } + + explicit input_stream_adapter(std::istream& i) + : is(&i), sb(i.rdbuf()) + {} + + // delete because of pointer members + input_stream_adapter(const input_stream_adapter&) = delete; + input_stream_adapter& operator=(input_stream_adapter&) = delete; + input_stream_adapter& operator=(input_stream_adapter&&) = delete; + + input_stream_adapter(input_stream_adapter&& rhs) noexcept + : is(rhs.is), sb(rhs.sb) + { + rhs.is = nullptr; + rhs.sb = nullptr; + } + + // std::istream/std::streambuf use std::char_traits::to_int_type, to + // ensure that std::char_traits::eof() and the character 0xFF do not + // end up as the same value, eg. 0xFFFFFFFF. + std::char_traits::int_type get_character() + { + auto res = sb->sbumpc(); + // set eof manually, as we don't use the istream interface. + if (JSON_HEDLEY_UNLIKELY(res == std::char_traits::eof())) + { + is->clear(is->rdstate() | std::ios::eofbit); + } + return res; + } + + private: + /// the associated input stream + std::istream* is = nullptr; + std::streambuf* sb = nullptr; +}; + +// General-purpose iterator-based adapter. It might not be as fast as +// theoretically possible for some containers, but it is extremely versatile. +template +class iterator_input_adapter +{ + public: + using char_type = typename std::iterator_traits::value_type; + + iterator_input_adapter(IteratorType first, IteratorType last) + : current(std::move(first)), end(std::move(last)) + {} + + typename std::char_traits::int_type get_character() + { + if (JSON_HEDLEY_LIKELY(current != end)) + { + auto result = std::char_traits::to_int_type(*current); + std::advance(current, 1); + return result; + } + + return std::char_traits::eof(); + } + + private: + IteratorType current; + IteratorType end; + + template + friend struct wide_string_input_helper; + + bool empty() const + { + return current == end; + } +}; + + +template +struct wide_string_input_helper; + +template +struct wide_string_input_helper +{ + // UTF-32 + static void fill_buffer(BaseInputAdapter& input, + std::array::int_type, 4>& utf8_bytes, + size_t& utf8_bytes_index, + size_t& utf8_bytes_filled) + { + utf8_bytes_index = 0; + + if (JSON_HEDLEY_UNLIKELY(input.empty())) + { + utf8_bytes[0] = std::char_traits::eof(); + utf8_bytes_filled = 1; + } + else + { + // get the current character + const auto wc = input.get_character(); + + // UTF-32 to UTF-8 encoding + if (wc < 0x80) + { + utf8_bytes[0] = static_cast::int_type>(wc); + utf8_bytes_filled = 1; + } + else if (wc <= 0x7FF) + { + utf8_bytes[0] = static_cast::int_type>(0xC0u | ((static_cast(wc) >> 6u) & 0x1Fu)); + utf8_bytes[1] = static_cast::int_type>(0x80u | (static_cast(wc) & 0x3Fu)); + utf8_bytes_filled = 2; + } + else if (wc <= 0xFFFF) + { + utf8_bytes[0] = static_cast::int_type>(0xE0u | ((static_cast(wc) >> 12u) & 0x0Fu)); + utf8_bytes[1] = static_cast::int_type>(0x80u | ((static_cast(wc) >> 6u) & 0x3Fu)); + utf8_bytes[2] = static_cast::int_type>(0x80u | (static_cast(wc) & 0x3Fu)); + utf8_bytes_filled = 3; + } + else if (wc <= 0x10FFFF) + { + utf8_bytes[0] = static_cast::int_type>(0xF0u | ((static_cast(wc) >> 18u) & 0x07u)); + utf8_bytes[1] = static_cast::int_type>(0x80u | ((static_cast(wc) >> 12u) & 0x3Fu)); + utf8_bytes[2] = static_cast::int_type>(0x80u | ((static_cast(wc) >> 6u) & 0x3Fu)); + utf8_bytes[3] = static_cast::int_type>(0x80u | (static_cast(wc) & 0x3Fu)); + utf8_bytes_filled = 4; + } + else + { + // unknown character + utf8_bytes[0] = static_cast::int_type>(wc); + utf8_bytes_filled = 1; + } + } + } +}; + +template +struct wide_string_input_helper +{ + // UTF-16 + static void fill_buffer(BaseInputAdapter& input, + std::array::int_type, 4>& utf8_bytes, + size_t& utf8_bytes_index, + size_t& utf8_bytes_filled) + { + utf8_bytes_index = 0; + + if (JSON_HEDLEY_UNLIKELY(input.empty())) + { + utf8_bytes[0] = std::char_traits::eof(); + utf8_bytes_filled = 1; + } + else + { + // get the current character + const auto wc = input.get_character(); + + // UTF-16 to UTF-8 encoding + if (wc < 0x80) + { + utf8_bytes[0] = static_cast::int_type>(wc); + utf8_bytes_filled = 1; + } + else if (wc <= 0x7FF) + { + utf8_bytes[0] = static_cast::int_type>(0xC0u | ((static_cast(wc) >> 6u))); + utf8_bytes[1] = static_cast::int_type>(0x80u | (static_cast(wc) & 0x3Fu)); + utf8_bytes_filled = 2; + } + else if (0xD800 > wc || wc >= 0xE000) + { + utf8_bytes[0] = static_cast::int_type>(0xE0u | ((static_cast(wc) >> 12u))); + utf8_bytes[1] = static_cast::int_type>(0x80u | ((static_cast(wc) >> 6u) & 0x3Fu)); + utf8_bytes[2] = static_cast::int_type>(0x80u | (static_cast(wc) & 0x3Fu)); + utf8_bytes_filled = 3; + } + else + { + if (JSON_HEDLEY_UNLIKELY(!input.empty())) + { + const auto wc2 = static_cast(input.get_character()); + const auto charcode = 0x10000u + (((static_cast(wc) & 0x3FFu) << 10u) | (wc2 & 0x3FFu)); + utf8_bytes[0] = static_cast::int_type>(0xF0u | (charcode >> 18u)); + utf8_bytes[1] = static_cast::int_type>(0x80u | ((charcode >> 12u) & 0x3Fu)); + utf8_bytes[2] = static_cast::int_type>(0x80u | ((charcode >> 6u) & 0x3Fu)); + utf8_bytes[3] = static_cast::int_type>(0x80u | (charcode & 0x3Fu)); + utf8_bytes_filled = 4; + } + else + { + utf8_bytes[0] = static_cast::int_type>(wc); + utf8_bytes_filled = 1; + } + } + } + } +}; + +// Wraps another input apdater to convert wide character types into individual bytes. +template +class wide_string_input_adapter +{ + public: + using char_type = char; + + wide_string_input_adapter(BaseInputAdapter base) + : base_adapter(base) {} + + typename std::char_traits::int_type get_character() noexcept + { + // check if buffer needs to be filled + if (utf8_bytes_index == utf8_bytes_filled) + { + fill_buffer(); + + JSON_ASSERT(utf8_bytes_filled > 0); + JSON_ASSERT(utf8_bytes_index == 0); + } + + // use buffer + JSON_ASSERT(utf8_bytes_filled > 0); + JSON_ASSERT(utf8_bytes_index < utf8_bytes_filled); + return utf8_bytes[utf8_bytes_index++]; + } + + private: + BaseInputAdapter base_adapter; + + template + void fill_buffer() + { + wide_string_input_helper::fill_buffer(base_adapter, utf8_bytes, utf8_bytes_index, utf8_bytes_filled); + } + + /// a buffer for UTF-8 bytes + std::array::int_type, 4> utf8_bytes = {{0, 0, 0, 0}}; + + /// index to the utf8_codes array for the next valid byte + std::size_t utf8_bytes_index = 0; + /// number of valid bytes in the utf8_codes array + std::size_t utf8_bytes_filled = 0; +}; + + +template +struct iterator_input_adapter_factory +{ + using iterator_type = IteratorType; + using char_type = typename std::iterator_traits::value_type; + using adapter_type = iterator_input_adapter; + + static adapter_type create(IteratorType first, IteratorType last) + { + return adapter_type(std::move(first), std::move(last)); + } +}; + +template +struct is_iterator_of_multibyte +{ + using value_type = typename std::iterator_traits::value_type; + enum + { + value = sizeof(value_type) > 1 + }; +}; + +template +struct iterator_input_adapter_factory::value>> +{ + using iterator_type = IteratorType; + using char_type = typename std::iterator_traits::value_type; + using base_adapter_type = iterator_input_adapter; + using adapter_type = wide_string_input_adapter; + + static adapter_type create(IteratorType first, IteratorType last) + { + return adapter_type(base_adapter_type(std::move(first), std::move(last))); + } +}; + +// General purpose iterator-based input +template +typename iterator_input_adapter_factory::adapter_type input_adapter(IteratorType first, IteratorType last) +{ + using factory_type = iterator_input_adapter_factory; + return factory_type::create(first, last); +} + +// Convenience shorthand from container to iterator +// Enables ADL on begin(container) and end(container) +// Encloses the using declarations in namespace for not to leak them to outside scope + +namespace container_input_adapter_factory_impl +{ + +using std::begin; +using std::end; + +template +struct container_input_adapter_factory {}; + +template +struct container_input_adapter_factory< ContainerType, + void_t()), end(std::declval()))>> + { + using adapter_type = decltype(input_adapter(begin(std::declval()), end(std::declval()))); + + static adapter_type create(const ContainerType& container) +{ + return input_adapter(begin(container), end(container)); +} + }; + +} // namespace container_input_adapter_factory_impl + +template +typename container_input_adapter_factory_impl::container_input_adapter_factory::adapter_type input_adapter(const ContainerType& container) +{ + return container_input_adapter_factory_impl::container_input_adapter_factory::create(container); +} + +// Special cases with fast paths +inline file_input_adapter input_adapter(std::FILE* file) +{ + return file_input_adapter(file); +} + +inline input_stream_adapter input_adapter(std::istream& stream) +{ + return input_stream_adapter(stream); +} + +inline input_stream_adapter input_adapter(std::istream&& stream) +{ + return input_stream_adapter(stream); +} + +using contiguous_bytes_input_adapter = decltype(input_adapter(std::declval(), std::declval())); + +// Null-delimited strings, and the like. +template < typename CharT, + typename std::enable_if < + std::is_pointer::value&& + !std::is_array::value&& + std::is_integral::type>::value&& + sizeof(typename std::remove_pointer::type) == 1, + int >::type = 0 > +contiguous_bytes_input_adapter input_adapter(CharT b) +{ + auto length = std::strlen(reinterpret_cast(b)); + const auto* ptr = reinterpret_cast(b); + return input_adapter(ptr, ptr + length); +} + +template +auto input_adapter(T (&array)[N]) -> decltype(input_adapter(array, array + N)) // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) +{ + return input_adapter(array, array + N); +} + +// This class only handles inputs of input_buffer_adapter type. +// It's required so that expressions like {ptr, len} can be implicitely casted +// to the correct adapter. +class span_input_adapter +{ + public: + template < typename CharT, + typename std::enable_if < + std::is_pointer::value&& + std::is_integral::type>::value&& + sizeof(typename std::remove_pointer::type) == 1, + int >::type = 0 > + span_input_adapter(CharT b, std::size_t l) + : ia(reinterpret_cast(b), reinterpret_cast(b) + l) {} + + template::iterator_category, std::random_access_iterator_tag>::value, + int>::type = 0> + span_input_adapter(IteratorType first, IteratorType last) + : ia(input_adapter(first, last)) {} + + contiguous_bytes_input_adapter&& get() + { + return std::move(ia); // NOLINT(hicpp-move-const-arg,performance-move-const-arg) + } + + private: + contiguous_bytes_input_adapter ia; +}; +} // namespace detail +} // namespace nlohmann + +// #include + + +#include +#include // string +#include // move +#include // vector + +// #include + +// #include + + +namespace nlohmann +{ + +/*! +@brief SAX interface + +This class describes the SAX interface used by @ref nlohmann::json::sax_parse. +Each function is called in different situations while the input is parsed. The +boolean return value informs the parser whether to continue processing the +input. +*/ +template +struct json_sax +{ + using number_integer_t = typename BasicJsonType::number_integer_t; + using number_unsigned_t = typename BasicJsonType::number_unsigned_t; + using number_float_t = typename BasicJsonType::number_float_t; + using string_t = typename BasicJsonType::string_t; + using binary_t = typename BasicJsonType::binary_t; + + /*! + @brief a null value was read + @return whether parsing should proceed + */ + virtual bool null() = 0; + + /*! + @brief a boolean value was read + @param[in] val boolean value + @return whether parsing should proceed + */ + virtual bool boolean(bool val) = 0; + + /*! + @brief an integer number was read + @param[in] val integer value + @return whether parsing should proceed + */ + virtual bool number_integer(number_integer_t val) = 0; + + /*! + @brief an unsigned integer number was read + @param[in] val unsigned integer value + @return whether parsing should proceed + */ + virtual bool number_unsigned(number_unsigned_t val) = 0; + + /*! + @brief an floating-point number was read + @param[in] val floating-point value + @param[in] s raw token value + @return whether parsing should proceed + */ + virtual bool number_float(number_float_t val, const string_t& s) = 0; + + /*! + @brief a string was read + @param[in] val string value + @return whether parsing should proceed + @note It is safe to move the passed string. + */ + virtual bool string(string_t& val) = 0; + + /*! + @brief a binary string was read + @param[in] val binary value + @return whether parsing should proceed + @note It is safe to move the passed binary. + */ + virtual bool binary(binary_t& val) = 0; + + /*! + @brief the beginning of an object was read + @param[in] elements number of object elements or -1 if unknown + @return whether parsing should proceed + @note binary formats may report the number of elements + */ + virtual bool start_object(std::size_t elements) = 0; + + /*! + @brief an object key was read + @param[in] val object key + @return whether parsing should proceed + @note It is safe to move the passed string. + */ + virtual bool key(string_t& val) = 0; + + /*! + @brief the end of an object was read + @return whether parsing should proceed + */ + virtual bool end_object() = 0; + + /*! + @brief the beginning of an array was read + @param[in] elements number of array elements or -1 if unknown + @return whether parsing should proceed + @note binary formats may report the number of elements + */ + virtual bool start_array(std::size_t elements) = 0; + + /*! + @brief the end of an array was read + @return whether parsing should proceed + */ + virtual bool end_array() = 0; + + /*! + @brief a parse error occurred + @param[in] position the position in the input where the error occurs + @param[in] last_token the last read token + @param[in] ex an exception object describing the error + @return whether parsing should proceed (must return false) + */ + virtual bool parse_error(std::size_t position, + const std::string& last_token, + const detail::exception& ex) = 0; + + json_sax() = default; + json_sax(const json_sax&) = default; + json_sax(json_sax&&) noexcept = default; + json_sax& operator=(const json_sax&) = default; + json_sax& operator=(json_sax&&) noexcept = default; + virtual ~json_sax() = default; +}; + + +namespace detail +{ +/*! +@brief SAX implementation to create a JSON value from SAX events + +This class implements the @ref json_sax interface and processes the SAX events +to create a JSON value which makes it basically a DOM parser. The structure or +hierarchy of the JSON value is managed by the stack `ref_stack` which contains +a pointer to the respective array or object for each recursion depth. + +After successful parsing, the value that is passed by reference to the +constructor contains the parsed value. + +@tparam BasicJsonType the JSON type +*/ +template +class json_sax_dom_parser +{ + public: + using number_integer_t = typename BasicJsonType::number_integer_t; + using number_unsigned_t = typename BasicJsonType::number_unsigned_t; + using number_float_t = typename BasicJsonType::number_float_t; + using string_t = typename BasicJsonType::string_t; + using binary_t = typename BasicJsonType::binary_t; + + /*! + @param[in,out] r reference to a JSON value that is manipulated while + parsing + @param[in] allow_exceptions_ whether parse errors yield exceptions + */ + explicit json_sax_dom_parser(BasicJsonType& r, const bool allow_exceptions_ = true) + : root(r), allow_exceptions(allow_exceptions_) + {} + + // make class move-only + json_sax_dom_parser(const json_sax_dom_parser&) = delete; + json_sax_dom_parser(json_sax_dom_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) + json_sax_dom_parser& operator=(const json_sax_dom_parser&) = delete; + json_sax_dom_parser& operator=(json_sax_dom_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) + ~json_sax_dom_parser() = default; + + bool null() + { + handle_value(nullptr); + return true; + } + + bool boolean(bool val) + { + handle_value(val); + return true; + } + + bool number_integer(number_integer_t val) + { + handle_value(val); + return true; + } + + bool number_unsigned(number_unsigned_t val) + { + handle_value(val); + return true; + } + + bool number_float(number_float_t val, const string_t& /*unused*/) + { + handle_value(val); + return true; + } + + bool string(string_t& val) + { + handle_value(val); + return true; + } + + bool binary(binary_t& val) + { + handle_value(std::move(val)); + return true; + } + + bool start_object(std::size_t len) + { + ref_stack.push_back(handle_value(BasicJsonType::value_t::object)); + + if (JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) && len > ref_stack.back()->max_size())) + { + JSON_THROW(out_of_range::create(408, "excessive object size: " + std::to_string(len), *ref_stack.back())); + } + + return true; + } + + bool key(string_t& val) + { + // add null at given key and store the reference for later + object_element = &(ref_stack.back()->m_value.object->operator[](val)); + return true; + } + + bool end_object() + { + ref_stack.back()->set_parents(); + ref_stack.pop_back(); + return true; + } + + bool start_array(std::size_t len) + { + ref_stack.push_back(handle_value(BasicJsonType::value_t::array)); + + if (JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) && len > ref_stack.back()->max_size())) + { + JSON_THROW(out_of_range::create(408, "excessive array size: " + std::to_string(len), *ref_stack.back())); + } + + return true; + } + + bool end_array() + { + ref_stack.back()->set_parents(); + ref_stack.pop_back(); + return true; + } + + template + bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/, + const Exception& ex) + { + errored = true; + static_cast(ex); + if (allow_exceptions) + { + JSON_THROW(ex); + } + return false; + } + + constexpr bool is_errored() const + { + return errored; + } + + private: + /*! + @invariant If the ref stack is empty, then the passed value will be the new + root. + @invariant If the ref stack contains a value, then it is an array or an + object to which we can add elements + */ + template + JSON_HEDLEY_RETURNS_NON_NULL + BasicJsonType* handle_value(Value&& v) + { + if (ref_stack.empty()) + { + root = BasicJsonType(std::forward(v)); + return &root; + } + + JSON_ASSERT(ref_stack.back()->is_array() || ref_stack.back()->is_object()); + + if (ref_stack.back()->is_array()) + { + ref_stack.back()->m_value.array->emplace_back(std::forward(v)); + return &(ref_stack.back()->m_value.array->back()); + } + + JSON_ASSERT(ref_stack.back()->is_object()); + JSON_ASSERT(object_element); + *object_element = BasicJsonType(std::forward(v)); + return object_element; + } + + /// the parsed JSON value + BasicJsonType& root; + /// stack to model hierarchy of values + std::vector ref_stack {}; + /// helper to hold the reference for the next object element + BasicJsonType* object_element = nullptr; + /// whether a syntax error occurred + bool errored = false; + /// whether to throw exceptions in case of errors + const bool allow_exceptions = true; +}; + +template +class json_sax_dom_callback_parser +{ + public: + using number_integer_t = typename BasicJsonType::number_integer_t; + using number_unsigned_t = typename BasicJsonType::number_unsigned_t; + using number_float_t = typename BasicJsonType::number_float_t; + using string_t = typename BasicJsonType::string_t; + using binary_t = typename BasicJsonType::binary_t; + using parser_callback_t = typename BasicJsonType::parser_callback_t; + using parse_event_t = typename BasicJsonType::parse_event_t; + + json_sax_dom_callback_parser(BasicJsonType& r, + const parser_callback_t cb, + const bool allow_exceptions_ = true) + : root(r), callback(cb), allow_exceptions(allow_exceptions_) + { + keep_stack.push_back(true); + } + + // make class move-only + json_sax_dom_callback_parser(const json_sax_dom_callback_parser&) = delete; + json_sax_dom_callback_parser(json_sax_dom_callback_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) + json_sax_dom_callback_parser& operator=(const json_sax_dom_callback_parser&) = delete; + json_sax_dom_callback_parser& operator=(json_sax_dom_callback_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) + ~json_sax_dom_callback_parser() = default; + + bool null() + { + handle_value(nullptr); + return true; + } + + bool boolean(bool val) + { + handle_value(val); + return true; + } + + bool number_integer(number_integer_t val) + { + handle_value(val); + return true; + } + + bool number_unsigned(number_unsigned_t val) + { + handle_value(val); + return true; + } + + bool number_float(number_float_t val, const string_t& /*unused*/) + { + handle_value(val); + return true; + } + + bool string(string_t& val) + { + handle_value(val); + return true; + } + + bool binary(binary_t& val) + { + handle_value(std::move(val)); + return true; + } + + bool start_object(std::size_t len) + { + // check callback for object start + const bool keep = callback(static_cast(ref_stack.size()), parse_event_t::object_start, discarded); + keep_stack.push_back(keep); + + auto val = handle_value(BasicJsonType::value_t::object, true); + ref_stack.push_back(val.second); + + // check object limit + if (ref_stack.back() && JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) && len > ref_stack.back()->max_size())) + { + JSON_THROW(out_of_range::create(408, "excessive object size: " + std::to_string(len), *ref_stack.back())); + } + + return true; + } + + bool key(string_t& val) + { + BasicJsonType k = BasicJsonType(val); + + // check callback for key + const bool keep = callback(static_cast(ref_stack.size()), parse_event_t::key, k); + key_keep_stack.push_back(keep); + + // add discarded value at given key and store the reference for later + if (keep && ref_stack.back()) + { + object_element = &(ref_stack.back()->m_value.object->operator[](val) = discarded); + } + + return true; + } + + bool end_object() + { + if (ref_stack.back()) + { + if (!callback(static_cast(ref_stack.size()) - 1, parse_event_t::object_end, *ref_stack.back())) + { + // discard object + *ref_stack.back() = discarded; + } + else + { + ref_stack.back()->set_parents(); + } + } + + JSON_ASSERT(!ref_stack.empty()); + JSON_ASSERT(!keep_stack.empty()); + ref_stack.pop_back(); + keep_stack.pop_back(); + + if (!ref_stack.empty() && ref_stack.back() && ref_stack.back()->is_structured()) + { + // remove discarded value + for (auto it = ref_stack.back()->begin(); it != ref_stack.back()->end(); ++it) + { + if (it->is_discarded()) + { + ref_stack.back()->erase(it); + break; + } + } + } + + return true; + } + + bool start_array(std::size_t len) + { + const bool keep = callback(static_cast(ref_stack.size()), parse_event_t::array_start, discarded); + keep_stack.push_back(keep); + + auto val = handle_value(BasicJsonType::value_t::array, true); + ref_stack.push_back(val.second); + + // check array limit + if (ref_stack.back() && JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) && len > ref_stack.back()->max_size())) + { + JSON_THROW(out_of_range::create(408, "excessive array size: " + std::to_string(len), *ref_stack.back())); + } + + return true; + } + + bool end_array() + { + bool keep = true; + + if (ref_stack.back()) + { + keep = callback(static_cast(ref_stack.size()) - 1, parse_event_t::array_end, *ref_stack.back()); + if (keep) + { + ref_stack.back()->set_parents(); + } + else + { + // discard array + *ref_stack.back() = discarded; + } + } + + JSON_ASSERT(!ref_stack.empty()); + JSON_ASSERT(!keep_stack.empty()); + ref_stack.pop_back(); + keep_stack.pop_back(); + + // remove discarded value + if (!keep && !ref_stack.empty() && ref_stack.back()->is_array()) + { + ref_stack.back()->m_value.array->pop_back(); + } + + return true; + } + + template + bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/, + const Exception& ex) + { + errored = true; + static_cast(ex); + if (allow_exceptions) + { + JSON_THROW(ex); + } + return false; + } + + constexpr bool is_errored() const + { + return errored; + } + + private: + /*! + @param[in] v value to add to the JSON value we build during parsing + @param[in] skip_callback whether we should skip calling the callback + function; this is required after start_array() and + start_object() SAX events, because otherwise we would call the + callback function with an empty array or object, respectively. + + @invariant If the ref stack is empty, then the passed value will be the new + root. + @invariant If the ref stack contains a value, then it is an array or an + object to which we can add elements + + @return pair of boolean (whether value should be kept) and pointer (to the + passed value in the ref_stack hierarchy; nullptr if not kept) + */ + template + std::pair handle_value(Value&& v, const bool skip_callback = false) + { + JSON_ASSERT(!keep_stack.empty()); + + // do not handle this value if we know it would be added to a discarded + // container + if (!keep_stack.back()) + { + return {false, nullptr}; + } + + // create value + auto value = BasicJsonType(std::forward(v)); + + // check callback + const bool keep = skip_callback || callback(static_cast(ref_stack.size()), parse_event_t::value, value); + + // do not handle this value if we just learnt it shall be discarded + if (!keep) + { + return {false, nullptr}; + } + + if (ref_stack.empty()) + { + root = std::move(value); + return {true, &root}; + } + + // skip this value if we already decided to skip the parent + // (https://github.com/nlohmann/json/issues/971#issuecomment-413678360) + if (!ref_stack.back()) + { + return {false, nullptr}; + } + + // we now only expect arrays and objects + JSON_ASSERT(ref_stack.back()->is_array() || ref_stack.back()->is_object()); + + // array + if (ref_stack.back()->is_array()) + { + ref_stack.back()->m_value.array->emplace_back(std::move(value)); + return {true, &(ref_stack.back()->m_value.array->back())}; + } + + // object + JSON_ASSERT(ref_stack.back()->is_object()); + // check if we should store an element for the current key + JSON_ASSERT(!key_keep_stack.empty()); + const bool store_element = key_keep_stack.back(); + key_keep_stack.pop_back(); + + if (!store_element) + { + return {false, nullptr}; + } + + JSON_ASSERT(object_element); + *object_element = std::move(value); + return {true, object_element}; + } + + /// the parsed JSON value + BasicJsonType& root; + /// stack to model hierarchy of values + std::vector ref_stack {}; + /// stack to manage which values to keep + std::vector keep_stack {}; + /// stack to manage which object keys to keep + std::vector key_keep_stack {}; + /// helper to hold the reference for the next object element + BasicJsonType* object_element = nullptr; + /// whether a syntax error occurred + bool errored = false; + /// callback function + const parser_callback_t callback = nullptr; + /// whether to throw exceptions in case of errors + const bool allow_exceptions = true; + /// a discarded value for the callback + BasicJsonType discarded = BasicJsonType::value_t::discarded; +}; + +template +class json_sax_acceptor +{ + public: + using number_integer_t = typename BasicJsonType::number_integer_t; + using number_unsigned_t = typename BasicJsonType::number_unsigned_t; + using number_float_t = typename BasicJsonType::number_float_t; + using string_t = typename BasicJsonType::string_t; + using binary_t = typename BasicJsonType::binary_t; + + bool null() + { + return true; + } + + bool boolean(bool /*unused*/) + { + return true; + } + + bool number_integer(number_integer_t /*unused*/) + { + return true; + } + + bool number_unsigned(number_unsigned_t /*unused*/) + { + return true; + } + + bool number_float(number_float_t /*unused*/, const string_t& /*unused*/) + { + return true; + } + + bool string(string_t& /*unused*/) + { + return true; + } + + bool binary(binary_t& /*unused*/) + { + return true; + } + + bool start_object(std::size_t /*unused*/ = std::size_t(-1)) + { + return true; + } + + bool key(string_t& /*unused*/) + { + return true; + } + + bool end_object() + { + return true; + } + + bool start_array(std::size_t /*unused*/ = std::size_t(-1)) + { + return true; + } + + bool end_array() + { + return true; + } + + bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/, const detail::exception& /*unused*/) + { + return false; + } +}; +} // namespace detail + +} // namespace nlohmann + +// #include + + +#include // array +#include // localeconv +#include // size_t +#include // snprintf +#include // strtof, strtod, strtold, strtoll, strtoull +#include // initializer_list +#include // char_traits, string +#include // move +#include // vector + +// #include + +// #include + +// #include + + +namespace nlohmann +{ +namespace detail +{ +/////////// +// lexer // +/////////// + +template +class lexer_base +{ + public: + /// token types for the parser + enum class token_type + { + uninitialized, ///< indicating the scanner is uninitialized + literal_true, ///< the `true` literal + literal_false, ///< the `false` literal + literal_null, ///< the `null` literal + value_string, ///< a string -- use get_string() for actual value + value_unsigned, ///< an unsigned integer -- use get_number_unsigned() for actual value + value_integer, ///< a signed integer -- use get_number_integer() for actual value + value_float, ///< an floating point number -- use get_number_float() for actual value + begin_array, ///< the character for array begin `[` + begin_object, ///< the character for object begin `{` + end_array, ///< the character for array end `]` + end_object, ///< the character for object end `}` + name_separator, ///< the name separator `:` + value_separator, ///< the value separator `,` + parse_error, ///< indicating a parse error + end_of_input, ///< indicating the end of the input buffer + literal_or_value ///< a literal or the begin of a value (only for diagnostics) + }; + + /// return name of values of type token_type (only used for errors) + JSON_HEDLEY_RETURNS_NON_NULL + JSON_HEDLEY_CONST + static const char* token_type_name(const token_type t) noexcept + { + switch (t) + { + case token_type::uninitialized: + return ""; + case token_type::literal_true: + return "true literal"; + case token_type::literal_false: + return "false literal"; + case token_type::literal_null: + return "null literal"; + case token_type::value_string: + return "string literal"; + case token_type::value_unsigned: + case token_type::value_integer: + case token_type::value_float: + return "number literal"; + case token_type::begin_array: + return "'['"; + case token_type::begin_object: + return "'{'"; + case token_type::end_array: + return "']'"; + case token_type::end_object: + return "'}'"; + case token_type::name_separator: + return "':'"; + case token_type::value_separator: + return "','"; + case token_type::parse_error: + return ""; + case token_type::end_of_input: + return "end of input"; + case token_type::literal_or_value: + return "'[', '{', or a literal"; + // LCOV_EXCL_START + default: // catch non-enum values + return "unknown token"; + // LCOV_EXCL_STOP + } + } +}; +/*! +@brief lexical analysis + +This class organizes the lexical analysis during JSON deserialization. +*/ +template +class lexer : public lexer_base +{ + using number_integer_t = typename BasicJsonType::number_integer_t; + using number_unsigned_t = typename BasicJsonType::number_unsigned_t; + using number_float_t = typename BasicJsonType::number_float_t; + using string_t = typename BasicJsonType::string_t; + using char_type = typename InputAdapterType::char_type; + using char_int_type = typename std::char_traits::int_type; + + public: + using token_type = typename lexer_base::token_type; + + explicit lexer(InputAdapterType&& adapter, bool ignore_comments_ = false) noexcept + : ia(std::move(adapter)) + , ignore_comments(ignore_comments_) + , decimal_point_char(static_cast(get_decimal_point())) + {} + + // delete because of pointer members + lexer(const lexer&) = delete; + lexer(lexer&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) + lexer& operator=(lexer&) = delete; + lexer& operator=(lexer&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) + ~lexer() = default; + + private: + ///////////////////// + // locales + ///////////////////// + + /// return the locale-dependent decimal point + JSON_HEDLEY_PURE + static char get_decimal_point() noexcept + { + const auto* loc = localeconv(); + JSON_ASSERT(loc != nullptr); + return (loc->decimal_point == nullptr) ? '.' : *(loc->decimal_point); + } + + ///////////////////// + // scan functions + ///////////////////// + + /*! + @brief get codepoint from 4 hex characters following `\u` + + For input "\u c1 c2 c3 c4" the codepoint is: + (c1 * 0x1000) + (c2 * 0x0100) + (c3 * 0x0010) + c4 + = (c1 << 12) + (c2 << 8) + (c3 << 4) + (c4 << 0) + + Furthermore, the possible characters '0'..'9', 'A'..'F', and 'a'..'f' + must be converted to the integers 0x0..0x9, 0xA..0xF, 0xA..0xF, resp. The + conversion is done by subtracting the offset (0x30, 0x37, and 0x57) + between the ASCII value of the character and the desired integer value. + + @return codepoint (0x0000..0xFFFF) or -1 in case of an error (e.g. EOF or + non-hex character) + */ + int get_codepoint() + { + // this function only makes sense after reading `\u` + JSON_ASSERT(current == 'u'); + int codepoint = 0; + + const auto factors = { 12u, 8u, 4u, 0u }; + for (const auto factor : factors) + { + get(); + + if (current >= '0' && current <= '9') + { + codepoint += static_cast((static_cast(current) - 0x30u) << factor); + } + else if (current >= 'A' && current <= 'F') + { + codepoint += static_cast((static_cast(current) - 0x37u) << factor); + } + else if (current >= 'a' && current <= 'f') + { + codepoint += static_cast((static_cast(current) - 0x57u) << factor); + } + else + { + return -1; + } + } + + JSON_ASSERT(0x0000 <= codepoint && codepoint <= 0xFFFF); + return codepoint; + } + + /*! + @brief check if the next byte(s) are inside a given range + + Adds the current byte and, for each passed range, reads a new byte and + checks if it is inside the range. If a violation was detected, set up an + error message and return false. Otherwise, return true. + + @param[in] ranges list of integers; interpreted as list of pairs of + inclusive lower and upper bound, respectively + + @pre The passed list @a ranges must have 2, 4, or 6 elements; that is, + 1, 2, or 3 pairs. This precondition is enforced by an assertion. + + @return true if and only if no range violation was detected + */ + bool next_byte_in_range(std::initializer_list ranges) + { + JSON_ASSERT(ranges.size() == 2 || ranges.size() == 4 || ranges.size() == 6); + add(current); + + for (auto range = ranges.begin(); range != ranges.end(); ++range) + { + get(); + if (JSON_HEDLEY_LIKELY(*range <= current && current <= *(++range))) + { + add(current); + } + else + { + error_message = "invalid string: ill-formed UTF-8 byte"; + return false; + } + } + + return true; + } + + /*! + @brief scan a string literal + + This function scans a string according to Sect. 7 of RFC 8259. While + scanning, bytes are escaped and copied into buffer token_buffer. Then the + function returns successfully, token_buffer is *not* null-terminated (as it + may contain \0 bytes), and token_buffer.size() is the number of bytes in the + string. + + @return token_type::value_string if string could be successfully scanned, + token_type::parse_error otherwise + + @note In case of errors, variable error_message contains a textual + description. + */ + token_type scan_string() + { + // reset token_buffer (ignore opening quote) + reset(); + + // we entered the function by reading an open quote + JSON_ASSERT(current == '\"'); + + while (true) + { + // get next character + switch (get()) + { + // end of file while parsing string + case std::char_traits::eof(): + { + error_message = "invalid string: missing closing quote"; + return token_type::parse_error; + } + + // closing quote + case '\"': + { + return token_type::value_string; + } + + // escapes + case '\\': + { + switch (get()) + { + // quotation mark + case '\"': + add('\"'); + break; + // reverse solidus + case '\\': + add('\\'); + break; + // solidus + case '/': + add('/'); + break; + // backspace + case 'b': + add('\b'); + break; + // form feed + case 'f': + add('\f'); + break; + // line feed + case 'n': + add('\n'); + break; + // carriage return + case 'r': + add('\r'); + break; + // tab + case 't': + add('\t'); + break; + + // unicode escapes + case 'u': + { + const int codepoint1 = get_codepoint(); + int codepoint = codepoint1; // start with codepoint1 + + if (JSON_HEDLEY_UNLIKELY(codepoint1 == -1)) + { + error_message = "invalid string: '\\u' must be followed by 4 hex digits"; + return token_type::parse_error; + } + + // check if code point is a high surrogate + if (0xD800 <= codepoint1 && codepoint1 <= 0xDBFF) + { + // expect next \uxxxx entry + if (JSON_HEDLEY_LIKELY(get() == '\\' && get() == 'u')) + { + const int codepoint2 = get_codepoint(); + + if (JSON_HEDLEY_UNLIKELY(codepoint2 == -1)) + { + error_message = "invalid string: '\\u' must be followed by 4 hex digits"; + return token_type::parse_error; + } + + // check if codepoint2 is a low surrogate + if (JSON_HEDLEY_LIKELY(0xDC00 <= codepoint2 && codepoint2 <= 0xDFFF)) + { + // overwrite codepoint + codepoint = static_cast( + // high surrogate occupies the most significant 22 bits + (static_cast(codepoint1) << 10u) + // low surrogate occupies the least significant 15 bits + + static_cast(codepoint2) + // there is still the 0xD800, 0xDC00 and 0x10000 noise + // in the result so we have to subtract with: + // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00 + - 0x35FDC00u); + } + else + { + error_message = "invalid string: surrogate U+D800..U+DBFF must be followed by U+DC00..U+DFFF"; + return token_type::parse_error; + } + } + else + { + error_message = "invalid string: surrogate U+D800..U+DBFF must be followed by U+DC00..U+DFFF"; + return token_type::parse_error; + } + } + else + { + if (JSON_HEDLEY_UNLIKELY(0xDC00 <= codepoint1 && codepoint1 <= 0xDFFF)) + { + error_message = "invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF"; + return token_type::parse_error; + } + } + + // result of the above calculation yields a proper codepoint + JSON_ASSERT(0x00 <= codepoint && codepoint <= 0x10FFFF); + + // translate codepoint into bytes + if (codepoint < 0x80) + { + // 1-byte characters: 0xxxxxxx (ASCII) + add(static_cast(codepoint)); + } + else if (codepoint <= 0x7FF) + { + // 2-byte characters: 110xxxxx 10xxxxxx + add(static_cast(0xC0u | (static_cast(codepoint) >> 6u))); + add(static_cast(0x80u | (static_cast(codepoint) & 0x3Fu))); + } + else if (codepoint <= 0xFFFF) + { + // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx + add(static_cast(0xE0u | (static_cast(codepoint) >> 12u))); + add(static_cast(0x80u | ((static_cast(codepoint) >> 6u) & 0x3Fu))); + add(static_cast(0x80u | (static_cast(codepoint) & 0x3Fu))); + } + else + { + // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx + add(static_cast(0xF0u | (static_cast(codepoint) >> 18u))); + add(static_cast(0x80u | ((static_cast(codepoint) >> 12u) & 0x3Fu))); + add(static_cast(0x80u | ((static_cast(codepoint) >> 6u) & 0x3Fu))); + add(static_cast(0x80u | (static_cast(codepoint) & 0x3Fu))); + } + + break; + } + + // other characters after escape + default: + error_message = "invalid string: forbidden character after backslash"; + return token_type::parse_error; + } + + break; + } + + // invalid control characters + case 0x00: + { + error_message = "invalid string: control character U+0000 (NUL) must be escaped to \\u0000"; + return token_type::parse_error; + } + + case 0x01: + { + error_message = "invalid string: control character U+0001 (SOH) must be escaped to \\u0001"; + return token_type::parse_error; + } + + case 0x02: + { + error_message = "invalid string: control character U+0002 (STX) must be escaped to \\u0002"; + return token_type::parse_error; + } + + case 0x03: + { + error_message = "invalid string: control character U+0003 (ETX) must be escaped to \\u0003"; + return token_type::parse_error; + } + + case 0x04: + { + error_message = "invalid string: control character U+0004 (EOT) must be escaped to \\u0004"; + return token_type::parse_error; + } + + case 0x05: + { + error_message = "invalid string: control character U+0005 (ENQ) must be escaped to \\u0005"; + return token_type::parse_error; + } + + case 0x06: + { + error_message = "invalid string: control character U+0006 (ACK) must be escaped to \\u0006"; + return token_type::parse_error; + } + + case 0x07: + { + error_message = "invalid string: control character U+0007 (BEL) must be escaped to \\u0007"; + return token_type::parse_error; + } + + case 0x08: + { + error_message = "invalid string: control character U+0008 (BS) must be escaped to \\u0008 or \\b"; + return token_type::parse_error; + } + + case 0x09: + { + error_message = "invalid string: control character U+0009 (HT) must be escaped to \\u0009 or \\t"; + return token_type::parse_error; + } + + case 0x0A: + { + error_message = "invalid string: control character U+000A (LF) must be escaped to \\u000A or \\n"; + return token_type::parse_error; + } + + case 0x0B: + { + error_message = "invalid string: control character U+000B (VT) must be escaped to \\u000B"; + return token_type::parse_error; + } + + case 0x0C: + { + error_message = "invalid string: control character U+000C (FF) must be escaped to \\u000C or \\f"; + return token_type::parse_error; + } + + case 0x0D: + { + error_message = "invalid string: control character U+000D (CR) must be escaped to \\u000D or \\r"; + return token_type::parse_error; + } + + case 0x0E: + { + error_message = "invalid string: control character U+000E (SO) must be escaped to \\u000E"; + return token_type::parse_error; + } + + case 0x0F: + { + error_message = "invalid string: control character U+000F (SI) must be escaped to \\u000F"; + return token_type::parse_error; + } + + case 0x10: + { + error_message = "invalid string: control character U+0010 (DLE) must be escaped to \\u0010"; + return token_type::parse_error; + } + + case 0x11: + { + error_message = "invalid string: control character U+0011 (DC1) must be escaped to \\u0011"; + return token_type::parse_error; + } + + case 0x12: + { + error_message = "invalid string: control character U+0012 (DC2) must be escaped to \\u0012"; + return token_type::parse_error; + } + + case 0x13: + { + error_message = "invalid string: control character U+0013 (DC3) must be escaped to \\u0013"; + return token_type::parse_error; + } + + case 0x14: + { + error_message = "invalid string: control character U+0014 (DC4) must be escaped to \\u0014"; + return token_type::parse_error; + } + + case 0x15: + { + error_message = "invalid string: control character U+0015 (NAK) must be escaped to \\u0015"; + return token_type::parse_error; + } + + case 0x16: + { + error_message = "invalid string: control character U+0016 (SYN) must be escaped to \\u0016"; + return token_type::parse_error; + } + + case 0x17: + { + error_message = "invalid string: control character U+0017 (ETB) must be escaped to \\u0017"; + return token_type::parse_error; + } + + case 0x18: + { + error_message = "invalid string: control character U+0018 (CAN) must be escaped to \\u0018"; + return token_type::parse_error; + } + + case 0x19: + { + error_message = "invalid string: control character U+0019 (EM) must be escaped to \\u0019"; + return token_type::parse_error; + } + + case 0x1A: + { + error_message = "invalid string: control character U+001A (SUB) must be escaped to \\u001A"; + return token_type::parse_error; + } + + case 0x1B: + { + error_message = "invalid string: control character U+001B (ESC) must be escaped to \\u001B"; + return token_type::parse_error; + } + + case 0x1C: + { + error_message = "invalid string: control character U+001C (FS) must be escaped to \\u001C"; + return token_type::parse_error; + } + + case 0x1D: + { + error_message = "invalid string: control character U+001D (GS) must be escaped to \\u001D"; + return token_type::parse_error; + } + + case 0x1E: + { + error_message = "invalid string: control character U+001E (RS) must be escaped to \\u001E"; + return token_type::parse_error; + } + + case 0x1F: + { + error_message = "invalid string: control character U+001F (US) must be escaped to \\u001F"; + return token_type::parse_error; + } + + // U+0020..U+007F (except U+0022 (quote) and U+005C (backspace)) + case 0x20: + case 0x21: + case 0x23: + case 0x24: + case 0x25: + case 0x26: + case 0x27: + case 0x28: + case 0x29: + case 0x2A: + case 0x2B: + case 0x2C: + case 0x2D: + case 0x2E: + case 0x2F: + case 0x30: + case 0x31: + case 0x32: + case 0x33: + case 0x34: + case 0x35: + case 0x36: + case 0x37: + case 0x38: + case 0x39: + case 0x3A: + case 0x3B: + case 0x3C: + case 0x3D: + case 0x3E: + case 0x3F: + case 0x40: + case 0x41: + case 0x42: + case 0x43: + case 0x44: + case 0x45: + case 0x46: + case 0x47: + case 0x48: + case 0x49: + case 0x4A: + case 0x4B: + case 0x4C: + case 0x4D: + case 0x4E: + case 0x4F: + case 0x50: + case 0x51: + case 0x52: + case 0x53: + case 0x54: + case 0x55: + case 0x56: + case 0x57: + case 0x58: + case 0x59: + case 0x5A: + case 0x5B: + case 0x5D: + case 0x5E: + case 0x5F: + case 0x60: + case 0x61: + case 0x62: + case 0x63: + case 0x64: + case 0x65: + case 0x66: + case 0x67: + case 0x68: + case 0x69: + case 0x6A: + case 0x6B: + case 0x6C: + case 0x6D: + case 0x6E: + case 0x6F: + case 0x70: + case 0x71: + case 0x72: + case 0x73: + case 0x74: + case 0x75: + case 0x76: + case 0x77: + case 0x78: + case 0x79: + case 0x7A: + case 0x7B: + case 0x7C: + case 0x7D: + case 0x7E: + case 0x7F: + { + add(current); + break; + } + + // U+0080..U+07FF: bytes C2..DF 80..BF + case 0xC2: + case 0xC3: + case 0xC4: + case 0xC5: + case 0xC6: + case 0xC7: + case 0xC8: + case 0xC9: + case 0xCA: + case 0xCB: + case 0xCC: + case 0xCD: + case 0xCE: + case 0xCF: + case 0xD0: + case 0xD1: + case 0xD2: + case 0xD3: + case 0xD4: + case 0xD5: + case 0xD6: + case 0xD7: + case 0xD8: + case 0xD9: + case 0xDA: + case 0xDB: + case 0xDC: + case 0xDD: + case 0xDE: + case 0xDF: + { + if (JSON_HEDLEY_UNLIKELY(!next_byte_in_range({0x80, 0xBF}))) + { + return token_type::parse_error; + } + break; + } + + // U+0800..U+0FFF: bytes E0 A0..BF 80..BF + case 0xE0: + { + if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0xA0, 0xBF, 0x80, 0xBF})))) + { + return token_type::parse_error; + } + break; + } + + // U+1000..U+CFFF: bytes E1..EC 80..BF 80..BF + // U+E000..U+FFFF: bytes EE..EF 80..BF 80..BF + case 0xE1: + case 0xE2: + case 0xE3: + case 0xE4: + case 0xE5: + case 0xE6: + case 0xE7: + case 0xE8: + case 0xE9: + case 0xEA: + case 0xEB: + case 0xEC: + case 0xEE: + case 0xEF: + { + if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0xBF, 0x80, 0xBF})))) + { + return token_type::parse_error; + } + break; + } + + // U+D000..U+D7FF: bytes ED 80..9F 80..BF + case 0xED: + { + if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0x9F, 0x80, 0xBF})))) + { + return token_type::parse_error; + } + break; + } + + // U+10000..U+3FFFF F0 90..BF 80..BF 80..BF + case 0xF0: + { + if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x90, 0xBF, 0x80, 0xBF, 0x80, 0xBF})))) + { + return token_type::parse_error; + } + break; + } + + // U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF + case 0xF1: + case 0xF2: + case 0xF3: + { + if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF})))) + { + return token_type::parse_error; + } + break; + } + + // U+100000..U+10FFFF F4 80..8F 80..BF 80..BF + case 0xF4: + { + if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0x8F, 0x80, 0xBF, 0x80, 0xBF})))) + { + return token_type::parse_error; + } + break; + } + + // remaining bytes (80..C1 and F5..FF) are ill-formed + default: + { + error_message = "invalid string: ill-formed UTF-8 byte"; + return token_type::parse_error; + } + } + } + } + + /*! + * @brief scan a comment + * @return whether comment could be scanned successfully + */ + bool scan_comment() + { + switch (get()) + { + // single-line comments skip input until a newline or EOF is read + case '/': + { + while (true) + { + switch (get()) + { + case '\n': + case '\r': + case std::char_traits::eof(): + case '\0': + return true; + + default: + break; + } + } + } + + // multi-line comments skip input until */ is read + case '*': + { + while (true) + { + switch (get()) + { + case std::char_traits::eof(): + case '\0': + { + error_message = "invalid comment; missing closing '*/'"; + return false; + } + + case '*': + { + switch (get()) + { + case '/': + return true; + + default: + { + unget(); + continue; + } + } + } + + default: + continue; + } + } + } + + // unexpected character after reading '/' + default: + { + error_message = "invalid comment; expecting '/' or '*' after '/'"; + return false; + } + } + } + + JSON_HEDLEY_NON_NULL(2) + static void strtof(float& f, const char* str, char** endptr) noexcept + { + f = std::strtof(str, endptr); + } + + JSON_HEDLEY_NON_NULL(2) + static void strtof(double& f, const char* str, char** endptr) noexcept + { + f = std::strtod(str, endptr); + } + + JSON_HEDLEY_NON_NULL(2) + static void strtof(long double& f, const char* str, char** endptr) noexcept + { + f = std::strtold(str, endptr); + } + + /*! + @brief scan a number literal + + This function scans a string according to Sect. 6 of RFC 8259. + + The function is realized with a deterministic finite state machine derived + from the grammar described in RFC 8259. Starting in state "init", the + input is read and used to determined the next state. Only state "done" + accepts the number. State "error" is a trap state to model errors. In the + table below, "anything" means any character but the ones listed before. + + state | 0 | 1-9 | e E | + | - | . | anything + ---------|----------|----------|----------|---------|---------|----------|----------- + init | zero | any1 | [error] | [error] | minus | [error] | [error] + minus | zero | any1 | [error] | [error] | [error] | [error] | [error] + zero | done | done | exponent | done | done | decimal1 | done + any1 | any1 | any1 | exponent | done | done | decimal1 | done + decimal1 | decimal2 | decimal2 | [error] | [error] | [error] | [error] | [error] + decimal2 | decimal2 | decimal2 | exponent | done | done | done | done + exponent | any2 | any2 | [error] | sign | sign | [error] | [error] + sign | any2 | any2 | [error] | [error] | [error] | [error] | [error] + any2 | any2 | any2 | done | done | done | done | done + + The state machine is realized with one label per state (prefixed with + "scan_number_") and `goto` statements between them. The state machine + contains cycles, but any cycle can be left when EOF is read. Therefore, + the function is guaranteed to terminate. + + During scanning, the read bytes are stored in token_buffer. This string is + then converted to a signed integer, an unsigned integer, or a + floating-point number. + + @return token_type::value_unsigned, token_type::value_integer, or + token_type::value_float if number could be successfully scanned, + token_type::parse_error otherwise + + @note The scanner is independent of the current locale. Internally, the + locale's decimal point is used instead of `.` to work with the + locale-dependent converters. + */ + token_type scan_number() // lgtm [cpp/use-of-goto] + { + // reset token_buffer to store the number's bytes + reset(); + + // the type of the parsed number; initially set to unsigned; will be + // changed if minus sign, decimal point or exponent is read + token_type number_type = token_type::value_unsigned; + + // state (init): we just found out we need to scan a number + switch (current) + { + case '-': + { + add(current); + goto scan_number_minus; + } + + case '0': + { + add(current); + goto scan_number_zero; + } + + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + { + add(current); + goto scan_number_any1; + } + + // all other characters are rejected outside scan_number() + default: // LCOV_EXCL_LINE + JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE + } + +scan_number_minus: + // state: we just parsed a leading minus sign + number_type = token_type::value_integer; + switch (get()) + { + case '0': + { + add(current); + goto scan_number_zero; + } + + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + { + add(current); + goto scan_number_any1; + } + + default: + { + error_message = "invalid number; expected digit after '-'"; + return token_type::parse_error; + } + } + +scan_number_zero: + // state: we just parse a zero (maybe with a leading minus sign) + switch (get()) + { + case '.': + { + add(decimal_point_char); + goto scan_number_decimal1; + } + + case 'e': + case 'E': + { + add(current); + goto scan_number_exponent; + } + + default: + goto scan_number_done; + } + +scan_number_any1: + // state: we just parsed a number 0-9 (maybe with a leading minus sign) + switch (get()) + { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + { + add(current); + goto scan_number_any1; + } + + case '.': + { + add(decimal_point_char); + goto scan_number_decimal1; + } + + case 'e': + case 'E': + { + add(current); + goto scan_number_exponent; + } + + default: + goto scan_number_done; + } + +scan_number_decimal1: + // state: we just parsed a decimal point + number_type = token_type::value_float; + switch (get()) + { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + { + add(current); + goto scan_number_decimal2; + } + + default: + { + error_message = "invalid number; expected digit after '.'"; + return token_type::parse_error; + } + } + +scan_number_decimal2: + // we just parsed at least one number after a decimal point + switch (get()) + { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + { + add(current); + goto scan_number_decimal2; + } + + case 'e': + case 'E': + { + add(current); + goto scan_number_exponent; + } + + default: + goto scan_number_done; + } + +scan_number_exponent: + // we just parsed an exponent + number_type = token_type::value_float; + switch (get()) + { + case '+': + case '-': + { + add(current); + goto scan_number_sign; + } + + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + { + add(current); + goto scan_number_any2; + } + + default: + { + error_message = + "invalid number; expected '+', '-', or digit after exponent"; + return token_type::parse_error; + } + } + +scan_number_sign: + // we just parsed an exponent sign + switch (get()) + { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + { + add(current); + goto scan_number_any2; + } + + default: + { + error_message = "invalid number; expected digit after exponent sign"; + return token_type::parse_error; + } + } + +scan_number_any2: + // we just parsed a number after the exponent or exponent sign + switch (get()) + { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + { + add(current); + goto scan_number_any2; + } + + default: + goto scan_number_done; + } + +scan_number_done: + // unget the character after the number (we only read it to know that + // we are done scanning a number) + unget(); + + char* endptr = nullptr; // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg) + errno = 0; + + // try to parse integers first and fall back to floats + if (number_type == token_type::value_unsigned) + { + const auto x = std::strtoull(token_buffer.data(), &endptr, 10); + + // we checked the number format before + JSON_ASSERT(endptr == token_buffer.data() + token_buffer.size()); + + if (errno == 0) + { + value_unsigned = static_cast(x); + if (value_unsigned == x) + { + return token_type::value_unsigned; + } + } + } + else if (number_type == token_type::value_integer) + { + const auto x = std::strtoll(token_buffer.data(), &endptr, 10); + + // we checked the number format before + JSON_ASSERT(endptr == token_buffer.data() + token_buffer.size()); + + if (errno == 0) + { + value_integer = static_cast(x); + if (value_integer == x) + { + return token_type::value_integer; + } + } + } + + // this code is reached if we parse a floating-point number or if an + // integer conversion above failed + strtof(value_float, token_buffer.data(), &endptr); + + // we checked the number format before + JSON_ASSERT(endptr == token_buffer.data() + token_buffer.size()); + + return token_type::value_float; + } + + /*! + @param[in] literal_text the literal text to expect + @param[in] length the length of the passed literal text + @param[in] return_type the token type to return on success + */ + JSON_HEDLEY_NON_NULL(2) + token_type scan_literal(const char_type* literal_text, const std::size_t length, + token_type return_type) + { + JSON_ASSERT(std::char_traits::to_char_type(current) == literal_text[0]); + for (std::size_t i = 1; i < length; ++i) + { + if (JSON_HEDLEY_UNLIKELY(std::char_traits::to_char_type(get()) != literal_text[i])) + { + error_message = "invalid literal"; + return token_type::parse_error; + } + } + return return_type; + } + + ///////////////////// + // input management + ///////////////////// + + /// reset token_buffer; current character is beginning of token + void reset() noexcept + { + token_buffer.clear(); + token_string.clear(); + token_string.push_back(std::char_traits::to_char_type(current)); + } + + /* + @brief get next character from the input + + This function provides the interface to the used input adapter. It does + not throw in case the input reached EOF, but returns a + `std::char_traits::eof()` in that case. Stores the scanned characters + for use in error messages. + + @return character read from the input + */ + char_int_type get() + { + ++position.chars_read_total; + ++position.chars_read_current_line; + + if (next_unget) + { + // just reset the next_unget variable and work with current + next_unget = false; + } + else + { + current = ia.get_character(); + } + + if (JSON_HEDLEY_LIKELY(current != std::char_traits::eof())) + { + token_string.push_back(std::char_traits::to_char_type(current)); + } + + if (current == '\n') + { + ++position.lines_read; + position.chars_read_current_line = 0; + } + + return current; + } + + /*! + @brief unget current character (read it again on next get) + + We implement unget by setting variable next_unget to true. The input is not + changed - we just simulate ungetting by modifying chars_read_total, + chars_read_current_line, and token_string. The next call to get() will + behave as if the unget character is read again. + */ + void unget() + { + next_unget = true; + + --position.chars_read_total; + + // in case we "unget" a newline, we have to also decrement the lines_read + if (position.chars_read_current_line == 0) + { + if (position.lines_read > 0) + { + --position.lines_read; + } + } + else + { + --position.chars_read_current_line; + } + + if (JSON_HEDLEY_LIKELY(current != std::char_traits::eof())) + { + JSON_ASSERT(!token_string.empty()); + token_string.pop_back(); + } + } + + /// add a character to token_buffer + void add(char_int_type c) + { + token_buffer.push_back(static_cast(c)); + } + + public: + ///////////////////// + // value getters + ///////////////////// + + /// return integer value + constexpr number_integer_t get_number_integer() const noexcept + { + return value_integer; + } + + /// return unsigned integer value + constexpr number_unsigned_t get_number_unsigned() const noexcept + { + return value_unsigned; + } + + /// return floating-point value + constexpr number_float_t get_number_float() const noexcept + { + return value_float; + } + + /// return current string value (implicitly resets the token; useful only once) + string_t& get_string() + { + return token_buffer; + } + + ///////////////////// + // diagnostics + ///////////////////// + + /// return position of last read token + constexpr position_t get_position() const noexcept + { + return position; + } + + /// return the last read token (for errors only). Will never contain EOF + /// (an arbitrary value that is not a valid char value, often -1), because + /// 255 may legitimately occur. May contain NUL, which should be escaped. + std::string get_token_string() const + { + // escape control characters + std::string result; + for (const auto c : token_string) + { + if (static_cast(c) <= '\x1F') + { + // escape control characters + std::array cs{{}}; + (std::snprintf)(cs.data(), cs.size(), "", static_cast(c)); // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg) + result += cs.data(); + } + else + { + // add character as is + result.push_back(static_cast(c)); + } + } + + return result; + } + + /// return syntax error message + JSON_HEDLEY_RETURNS_NON_NULL + constexpr const char* get_error_message() const noexcept + { + return error_message; + } + + ///////////////////// + // actual scanner + ///////////////////// + + /*! + @brief skip the UTF-8 byte order mark + @return true iff there is no BOM or the correct BOM has been skipped + */ + bool skip_bom() + { + if (get() == 0xEF) + { + // check if we completely parse the BOM + return get() == 0xBB && get() == 0xBF; + } + + // the first character is not the beginning of the BOM; unget it to + // process is later + unget(); + return true; + } + + void skip_whitespace() + { + do + { + get(); + } + while (current == ' ' || current == '\t' || current == '\n' || current == '\r'); + } + + token_type scan() + { + // initially, skip the BOM + if (position.chars_read_total == 0 && !skip_bom()) + { + error_message = "invalid BOM; must be 0xEF 0xBB 0xBF if given"; + return token_type::parse_error; + } + + // read next character and ignore whitespace + skip_whitespace(); + + // ignore comments + while (ignore_comments && current == '/') + { + if (!scan_comment()) + { + return token_type::parse_error; + } + + // skip following whitespace + skip_whitespace(); + } + + switch (current) + { + // structural characters + case '[': + return token_type::begin_array; + case ']': + return token_type::end_array; + case '{': + return token_type::begin_object; + case '}': + return token_type::end_object; + case ':': + return token_type::name_separator; + case ',': + return token_type::value_separator; + + // literals + case 't': + { + std::array true_literal = {{char_type('t'), char_type('r'), char_type('u'), char_type('e')}}; + return scan_literal(true_literal.data(), true_literal.size(), token_type::literal_true); + } + case 'f': + { + std::array false_literal = {{char_type('f'), char_type('a'), char_type('l'), char_type('s'), char_type('e')}}; + return scan_literal(false_literal.data(), false_literal.size(), token_type::literal_false); + } + case 'n': + { + std::array null_literal = {{char_type('n'), char_type('u'), char_type('l'), char_type('l')}}; + return scan_literal(null_literal.data(), null_literal.size(), token_type::literal_null); + } + + // string + case '\"': + return scan_string(); + + // number + case '-': + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + return scan_number(); + + // end of input (the null byte is needed when parsing from + // string literals) + case '\0': + case std::char_traits::eof(): + return token_type::end_of_input; + + // error + default: + error_message = "invalid literal"; + return token_type::parse_error; + } + } + + private: + /// input adapter + InputAdapterType ia; + + /// whether comments should be ignored (true) or signaled as errors (false) + const bool ignore_comments = false; + + /// the current character + char_int_type current = std::char_traits::eof(); + + /// whether the next get() call should just return current + bool next_unget = false; + + /// the start position of the current token + position_t position {}; + + /// raw input token string (for error messages) + std::vector token_string {}; + + /// buffer for variable-length tokens (numbers, strings) + string_t token_buffer {}; + + /// a description of occurred lexer errors + const char* error_message = ""; + + // number values + number_integer_t value_integer = 0; + number_unsigned_t value_unsigned = 0; + number_float_t value_float = 0; + + /// the decimal point + const char_int_type decimal_point_char = '.'; +}; +} // namespace detail +} // namespace nlohmann + +// #include + +// #include + + +#include // size_t +#include // declval +#include // string + +// #include + +// #include + + +namespace nlohmann +{ +namespace detail +{ +template +using null_function_t = decltype(std::declval().null()); + +template +using boolean_function_t = + decltype(std::declval().boolean(std::declval())); + +template +using number_integer_function_t = + decltype(std::declval().number_integer(std::declval())); + +template +using number_unsigned_function_t = + decltype(std::declval().number_unsigned(std::declval())); + +template +using number_float_function_t = decltype(std::declval().number_float( + std::declval(), std::declval())); + +template +using string_function_t = + decltype(std::declval().string(std::declval())); + +template +using binary_function_t = + decltype(std::declval().binary(std::declval())); + +template +using start_object_function_t = + decltype(std::declval().start_object(std::declval())); + +template +using key_function_t = + decltype(std::declval().key(std::declval())); + +template +using end_object_function_t = decltype(std::declval().end_object()); + +template +using start_array_function_t = + decltype(std::declval().start_array(std::declval())); + +template +using end_array_function_t = decltype(std::declval().end_array()); + +template +using parse_error_function_t = decltype(std::declval().parse_error( + std::declval(), std::declval(), + std::declval())); + +template +struct is_sax +{ + private: + static_assert(is_basic_json::value, + "BasicJsonType must be of type basic_json<...>"); + + using number_integer_t = typename BasicJsonType::number_integer_t; + using number_unsigned_t = typename BasicJsonType::number_unsigned_t; + using number_float_t = typename BasicJsonType::number_float_t; + using string_t = typename BasicJsonType::string_t; + using binary_t = typename BasicJsonType::binary_t; + using exception_t = typename BasicJsonType::exception; + + public: + static constexpr bool value = + is_detected_exact::value && + is_detected_exact::value && + is_detected_exact::value && + is_detected_exact::value && + is_detected_exact::value && + is_detected_exact::value && + is_detected_exact::value && + is_detected_exact::value && + is_detected_exact::value && + is_detected_exact::value && + is_detected_exact::value && + is_detected_exact::value && + is_detected_exact::value; +}; + +template +struct is_sax_static_asserts +{ + private: + static_assert(is_basic_json::value, + "BasicJsonType must be of type basic_json<...>"); + + using number_integer_t = typename BasicJsonType::number_integer_t; + using number_unsigned_t = typename BasicJsonType::number_unsigned_t; + using number_float_t = typename BasicJsonType::number_float_t; + using string_t = typename BasicJsonType::string_t; + using binary_t = typename BasicJsonType::binary_t; + using exception_t = typename BasicJsonType::exception; + + public: + static_assert(is_detected_exact::value, + "Missing/invalid function: bool null()"); + static_assert(is_detected_exact::value, + "Missing/invalid function: bool boolean(bool)"); + static_assert(is_detected_exact::value, + "Missing/invalid function: bool boolean(bool)"); + static_assert( + is_detected_exact::value, + "Missing/invalid function: bool number_integer(number_integer_t)"); + static_assert( + is_detected_exact::value, + "Missing/invalid function: bool number_unsigned(number_unsigned_t)"); + static_assert(is_detected_exact::value, + "Missing/invalid function: bool number_float(number_float_t, const string_t&)"); + static_assert( + is_detected_exact::value, + "Missing/invalid function: bool string(string_t&)"); + static_assert( + is_detected_exact::value, + "Missing/invalid function: bool binary(binary_t&)"); + static_assert(is_detected_exact::value, + "Missing/invalid function: bool start_object(std::size_t)"); + static_assert(is_detected_exact::value, + "Missing/invalid function: bool key(string_t&)"); + static_assert(is_detected_exact::value, + "Missing/invalid function: bool end_object()"); + static_assert(is_detected_exact::value, + "Missing/invalid function: bool start_array(std::size_t)"); + static_assert(is_detected_exact::value, + "Missing/invalid function: bool end_array()"); + static_assert( + is_detected_exact::value, + "Missing/invalid function: bool parse_error(std::size_t, const " + "std::string&, const exception&)"); +}; +} // namespace detail +} // namespace nlohmann + +// #include + + +namespace nlohmann +{ +namespace detail +{ + +/// how to treat CBOR tags +enum class cbor_tag_handler_t +{ + error, ///< throw a parse_error exception in case of a tag + ignore ///< ignore tags +}; + +/*! +@brief determine system byte order + +@return true if and only if system's byte order is little endian + +@note from https://stackoverflow.com/a/1001328/266378 +*/ +static inline bool little_endianess(int num = 1) noexcept +{ + return *reinterpret_cast(&num) == 1; +} + + +/////////////////// +// binary reader // +/////////////////// + +/*! +@brief deserialization of CBOR, MessagePack, and UBJSON values +*/ +template> +class binary_reader +{ + using number_integer_t = typename BasicJsonType::number_integer_t; + using number_unsigned_t = typename BasicJsonType::number_unsigned_t; + using number_float_t = typename BasicJsonType::number_float_t; + using string_t = typename BasicJsonType::string_t; + using binary_t = typename BasicJsonType::binary_t; + using json_sax_t = SAX; + using char_type = typename InputAdapterType::char_type; + using char_int_type = typename std::char_traits::int_type; + + public: + /*! + @brief create a binary reader + + @param[in] adapter input adapter to read from + */ + explicit binary_reader(InputAdapterType&& adapter) noexcept : ia(std::move(adapter)) + { + (void)detail::is_sax_static_asserts {}; + } + + // make class move-only + binary_reader(const binary_reader&) = delete; + binary_reader(binary_reader&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) + binary_reader& operator=(const binary_reader&) = delete; + binary_reader& operator=(binary_reader&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) + ~binary_reader() = default; + + /*! + @param[in] format the binary format to parse + @param[in] sax_ a SAX event processor + @param[in] strict whether to expect the input to be consumed completed + @param[in] tag_handler how to treat CBOR tags + + @return whether parsing was successful + */ + JSON_HEDLEY_NON_NULL(3) + bool sax_parse(const input_format_t format, + json_sax_t* sax_, + const bool strict = true, + const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) + { + sax = sax_; + bool result = false; + + switch (format) + { + case input_format_t::bson: + result = parse_bson_internal(); + break; + + case input_format_t::cbor: + result = parse_cbor_internal(true, tag_handler); + break; + + case input_format_t::msgpack: + result = parse_msgpack_internal(); + break; + + case input_format_t::ubjson: + result = parse_ubjson_internal(); + break; + + default: // LCOV_EXCL_LINE + JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE + } + + // strict mode: next byte must be EOF + if (result && strict) + { + if (format == input_format_t::ubjson) + { + get_ignore_noop(); + } + else + { + get(); + } + + if (JSON_HEDLEY_UNLIKELY(current != std::char_traits::eof())) + { + return sax->parse_error(chars_read, get_token_string(), + parse_error::create(110, chars_read, exception_message(format, "expected end of input; last byte: 0x" + get_token_string(), "value"), BasicJsonType())); + } + } + + return result; + } + + private: + ////////// + // BSON // + ////////// + + /*! + @brief Reads in a BSON-object and passes it to the SAX-parser. + @return whether a valid BSON-value was passed to the SAX parser + */ + bool parse_bson_internal() + { + std::int32_t document_size{}; + get_number(input_format_t::bson, document_size); + + if (JSON_HEDLEY_UNLIKELY(!sax->start_object(std::size_t(-1)))) + { + return false; + } + + if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_list(/*is_array*/false))) + { + return false; + } + + return sax->end_object(); + } + + /*! + @brief Parses a C-style string from the BSON input. + @param[in,out] result A reference to the string variable where the read + string is to be stored. + @return `true` if the \x00-byte indicating the end of the string was + encountered before the EOF; false` indicates an unexpected EOF. + */ + bool get_bson_cstr(string_t& result) + { + auto out = std::back_inserter(result); + while (true) + { + get(); + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::bson, "cstring"))) + { + return false; + } + if (current == 0x00) + { + return true; + } + *out++ = static_cast(current); + } + } + + /*! + @brief Parses a zero-terminated string of length @a len from the BSON + input. + @param[in] len The length (including the zero-byte at the end) of the + string to be read. + @param[in,out] result A reference to the string variable where the read + string is to be stored. + @tparam NumberType The type of the length @a len + @pre len >= 1 + @return `true` if the string was successfully parsed + */ + template + bool get_bson_string(const NumberType len, string_t& result) + { + if (JSON_HEDLEY_UNLIKELY(len < 1)) + { + auto last_token = get_token_string(); + return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::bson, "string length must be at least 1, is " + std::to_string(len), "string"), BasicJsonType())); + } + + return get_string(input_format_t::bson, len - static_cast(1), result) && get() != std::char_traits::eof(); + } + + /*! + @brief Parses a byte array input of length @a len from the BSON input. + @param[in] len The length of the byte array to be read. + @param[in,out] result A reference to the binary variable where the read + array is to be stored. + @tparam NumberType The type of the length @a len + @pre len >= 0 + @return `true` if the byte array was successfully parsed + */ + template + bool get_bson_binary(const NumberType len, binary_t& result) + { + if (JSON_HEDLEY_UNLIKELY(len < 0)) + { + auto last_token = get_token_string(); + return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::bson, "byte array length cannot be negative, is " + std::to_string(len), "binary"), BasicJsonType())); + } + + // All BSON binary values have a subtype + std::uint8_t subtype{}; + get_number(input_format_t::bson, subtype); + result.set_subtype(subtype); + + return get_binary(input_format_t::bson, len, result); + } + + /*! + @brief Read a BSON document element of the given @a element_type. + @param[in] element_type The BSON element type, c.f. http://bsonspec.org/spec.html + @param[in] element_type_parse_position The position in the input stream, + where the `element_type` was read. + @warning Not all BSON element types are supported yet. An unsupported + @a element_type will give rise to a parse_error.114: + Unsupported BSON record type 0x... + @return whether a valid BSON-object/array was passed to the SAX parser + */ + bool parse_bson_element_internal(const char_int_type element_type, + const std::size_t element_type_parse_position) + { + switch (element_type) + { + case 0x01: // double + { + double number{}; + return get_number(input_format_t::bson, number) && sax->number_float(static_cast(number), ""); + } + + case 0x02: // string + { + std::int32_t len{}; + string_t value; + return get_number(input_format_t::bson, len) && get_bson_string(len, value) && sax->string(value); + } + + case 0x03: // object + { + return parse_bson_internal(); + } + + case 0x04: // array + { + return parse_bson_array(); + } + + case 0x05: // binary + { + std::int32_t len{}; + binary_t value; + return get_number(input_format_t::bson, len) && get_bson_binary(len, value) && sax->binary(value); + } + + case 0x08: // boolean + { + return sax->boolean(get() != 0); + } + + case 0x0A: // null + { + return sax->null(); + } + + case 0x10: // int32 + { + std::int32_t value{}; + return get_number(input_format_t::bson, value) && sax->number_integer(value); + } + + case 0x12: // int64 + { + std::int64_t value{}; + return get_number(input_format_t::bson, value) && sax->number_integer(value); + } + + default: // anything else not supported (yet) + { + std::array cr{{}}; + (std::snprintf)(cr.data(), cr.size(), "%.2hhX", static_cast(element_type)); // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg) + return sax->parse_error(element_type_parse_position, std::string(cr.data()), parse_error::create(114, element_type_parse_position, "Unsupported BSON record type 0x" + std::string(cr.data()), BasicJsonType())); + } + } + } + + /*! + @brief Read a BSON element list (as specified in the BSON-spec) + + The same binary layout is used for objects and arrays, hence it must be + indicated with the argument @a is_array which one is expected + (true --> array, false --> object). + + @param[in] is_array Determines if the element list being read is to be + treated as an object (@a is_array == false), or as an + array (@a is_array == true). + @return whether a valid BSON-object/array was passed to the SAX parser + */ + bool parse_bson_element_list(const bool is_array) + { + string_t key; + + while (auto element_type = get()) + { + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::bson, "element list"))) + { + return false; + } + + const std::size_t element_type_parse_position = chars_read; + if (JSON_HEDLEY_UNLIKELY(!get_bson_cstr(key))) + { + return false; + } + + if (!is_array && !sax->key(key)) + { + return false; + } + + if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_internal(element_type, element_type_parse_position))) + { + return false; + } + + // get_bson_cstr only appends + key.clear(); + } + + return true; + } + + /*! + @brief Reads an array from the BSON input and passes it to the SAX-parser. + @return whether a valid BSON-array was passed to the SAX parser + */ + bool parse_bson_array() + { + std::int32_t document_size{}; + get_number(input_format_t::bson, document_size); + + if (JSON_HEDLEY_UNLIKELY(!sax->start_array(std::size_t(-1)))) + { + return false; + } + + if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_list(/*is_array*/true))) + { + return false; + } + + return sax->end_array(); + } + + ////////// + // CBOR // + ////////// + + /*! + @param[in] get_char whether a new character should be retrieved from the + input (true) or whether the last read character should + be considered instead (false) + @param[in] tag_handler how CBOR tags should be treated + + @return whether a valid CBOR value was passed to the SAX parser + */ + bool parse_cbor_internal(const bool get_char, + const cbor_tag_handler_t tag_handler) + { + switch (get_char ? get() : current) + { + // EOF + case std::char_traits::eof(): + return unexpect_eof(input_format_t::cbor, "value"); + + // Integer 0x00..0x17 (0..23) + case 0x00: + case 0x01: + case 0x02: + case 0x03: + case 0x04: + case 0x05: + case 0x06: + case 0x07: + case 0x08: + case 0x09: + case 0x0A: + case 0x0B: + case 0x0C: + case 0x0D: + case 0x0E: + case 0x0F: + case 0x10: + case 0x11: + case 0x12: + case 0x13: + case 0x14: + case 0x15: + case 0x16: + case 0x17: + return sax->number_unsigned(static_cast(current)); + + case 0x18: // Unsigned integer (one-byte uint8_t follows) + { + std::uint8_t number{}; + return get_number(input_format_t::cbor, number) && sax->number_unsigned(number); + } + + case 0x19: // Unsigned integer (two-byte uint16_t follows) + { + std::uint16_t number{}; + return get_number(input_format_t::cbor, number) && sax->number_unsigned(number); + } + + case 0x1A: // Unsigned integer (four-byte uint32_t follows) + { + std::uint32_t number{}; + return get_number(input_format_t::cbor, number) && sax->number_unsigned(number); + } + + case 0x1B: // Unsigned integer (eight-byte uint64_t follows) + { + std::uint64_t number{}; + return get_number(input_format_t::cbor, number) && sax->number_unsigned(number); + } + + // Negative integer -1-0x00..-1-0x17 (-1..-24) + case 0x20: + case 0x21: + case 0x22: + case 0x23: + case 0x24: + case 0x25: + case 0x26: + case 0x27: + case 0x28: + case 0x29: + case 0x2A: + case 0x2B: + case 0x2C: + case 0x2D: + case 0x2E: + case 0x2F: + case 0x30: + case 0x31: + case 0x32: + case 0x33: + case 0x34: + case 0x35: + case 0x36: + case 0x37: + return sax->number_integer(static_cast(0x20 - 1 - current)); + + case 0x38: // Negative integer (one-byte uint8_t follows) + { + std::uint8_t number{}; + return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast(-1) - number); + } + + case 0x39: // Negative integer -1-n (two-byte uint16_t follows) + { + std::uint16_t number{}; + return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast(-1) - number); + } + + case 0x3A: // Negative integer -1-n (four-byte uint32_t follows) + { + std::uint32_t number{}; + return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast(-1) - number); + } + + case 0x3B: // Negative integer -1-n (eight-byte uint64_t follows) + { + std::uint64_t number{}; + return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast(-1) + - static_cast(number)); + } + + // Binary data (0x00..0x17 bytes follow) + case 0x40: + case 0x41: + case 0x42: + case 0x43: + case 0x44: + case 0x45: + case 0x46: + case 0x47: + case 0x48: + case 0x49: + case 0x4A: + case 0x4B: + case 0x4C: + case 0x4D: + case 0x4E: + case 0x4F: + case 0x50: + case 0x51: + case 0x52: + case 0x53: + case 0x54: + case 0x55: + case 0x56: + case 0x57: + case 0x58: // Binary data (one-byte uint8_t for n follows) + case 0x59: // Binary data (two-byte uint16_t for n follow) + case 0x5A: // Binary data (four-byte uint32_t for n follow) + case 0x5B: // Binary data (eight-byte uint64_t for n follow) + case 0x5F: // Binary data (indefinite length) + { + binary_t b; + return get_cbor_binary(b) && sax->binary(b); + } + + // UTF-8 string (0x00..0x17 bytes follow) + case 0x60: + case 0x61: + case 0x62: + case 0x63: + case 0x64: + case 0x65: + case 0x66: + case 0x67: + case 0x68: + case 0x69: + case 0x6A: + case 0x6B: + case 0x6C: + case 0x6D: + case 0x6E: + case 0x6F: + case 0x70: + case 0x71: + case 0x72: + case 0x73: + case 0x74: + case 0x75: + case 0x76: + case 0x77: + case 0x78: // UTF-8 string (one-byte uint8_t for n follows) + case 0x79: // UTF-8 string (two-byte uint16_t for n follow) + case 0x7A: // UTF-8 string (four-byte uint32_t for n follow) + case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow) + case 0x7F: // UTF-8 string (indefinite length) + { + string_t s; + return get_cbor_string(s) && sax->string(s); + } + + // array (0x00..0x17 data items follow) + case 0x80: + case 0x81: + case 0x82: + case 0x83: + case 0x84: + case 0x85: + case 0x86: + case 0x87: + case 0x88: + case 0x89: + case 0x8A: + case 0x8B: + case 0x8C: + case 0x8D: + case 0x8E: + case 0x8F: + case 0x90: + case 0x91: + case 0x92: + case 0x93: + case 0x94: + case 0x95: + case 0x96: + case 0x97: + return get_cbor_array(static_cast(static_cast(current) & 0x1Fu), tag_handler); + + case 0x98: // array (one-byte uint8_t for n follows) + { + std::uint8_t len{}; + return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast(len), tag_handler); + } + + case 0x99: // array (two-byte uint16_t for n follow) + { + std::uint16_t len{}; + return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast(len), tag_handler); + } + + case 0x9A: // array (four-byte uint32_t for n follow) + { + std::uint32_t len{}; + return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast(len), tag_handler); + } + + case 0x9B: // array (eight-byte uint64_t for n follow) + { + std::uint64_t len{}; + return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast(len), tag_handler); + } + + case 0x9F: // array (indefinite length) + return get_cbor_array(std::size_t(-1), tag_handler); + + // map (0x00..0x17 pairs of data items follow) + case 0xA0: + case 0xA1: + case 0xA2: + case 0xA3: + case 0xA4: + case 0xA5: + case 0xA6: + case 0xA7: + case 0xA8: + case 0xA9: + case 0xAA: + case 0xAB: + case 0xAC: + case 0xAD: + case 0xAE: + case 0xAF: + case 0xB0: + case 0xB1: + case 0xB2: + case 0xB3: + case 0xB4: + case 0xB5: + case 0xB6: + case 0xB7: + return get_cbor_object(static_cast(static_cast(current) & 0x1Fu), tag_handler); + + case 0xB8: // map (one-byte uint8_t for n follows) + { + std::uint8_t len{}; + return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast(len), tag_handler); + } + + case 0xB9: // map (two-byte uint16_t for n follow) + { + std::uint16_t len{}; + return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast(len), tag_handler); + } + + case 0xBA: // map (four-byte uint32_t for n follow) + { + std::uint32_t len{}; + return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast(len), tag_handler); + } + + case 0xBB: // map (eight-byte uint64_t for n follow) + { + std::uint64_t len{}; + return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast(len), tag_handler); + } + + case 0xBF: // map (indefinite length) + return get_cbor_object(std::size_t(-1), tag_handler); + + case 0xC6: // tagged item + case 0xC7: + case 0xC8: + case 0xC9: + case 0xCA: + case 0xCB: + case 0xCC: + case 0xCD: + case 0xCE: + case 0xCF: + case 0xD0: + case 0xD1: + case 0xD2: + case 0xD3: + case 0xD4: + case 0xD8: // tagged item (1 bytes follow) + case 0xD9: // tagged item (2 bytes follow) + case 0xDA: // tagged item (4 bytes follow) + case 0xDB: // tagged item (8 bytes follow) + { + switch (tag_handler) + { + case cbor_tag_handler_t::error: + { + auto last_token = get_token_string(); + return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::cbor, "invalid byte: 0x" + last_token, "value"), BasicJsonType())); + } + + case cbor_tag_handler_t::ignore: + { + switch (current) + { + case 0xD8: + { + std::uint8_t len{}; + get_number(input_format_t::cbor, len); + break; + } + case 0xD9: + { + std::uint16_t len{}; + get_number(input_format_t::cbor, len); + break; + } + case 0xDA: + { + std::uint32_t len{}; + get_number(input_format_t::cbor, len); + break; + } + case 0xDB: + { + std::uint64_t len{}; + get_number(input_format_t::cbor, len); + break; + } + default: + break; + } + return parse_cbor_internal(true, tag_handler); + } + + default: // LCOV_EXCL_LINE + JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE + return false; // LCOV_EXCL_LINE + } + } + + case 0xF4: // false + return sax->boolean(false); + + case 0xF5: // true + return sax->boolean(true); + + case 0xF6: // null + return sax->null(); + + case 0xF9: // Half-Precision Float (two-byte IEEE 754) + { + const auto byte1_raw = get(); + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "number"))) + { + return false; + } + const auto byte2_raw = get(); + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "number"))) + { + return false; + } + + const auto byte1 = static_cast(byte1_raw); + const auto byte2 = static_cast(byte2_raw); + + // code from RFC 7049, Appendix D, Figure 3: + // As half-precision floating-point numbers were only added + // to IEEE 754 in 2008, today's programming platforms often + // still only have limited support for them. It is very + // easy to include at least decoding support for them even + // without such support. An example of a small decoder for + // half-precision floating-point numbers in the C language + // is shown in Fig. 3. + const auto half = static_cast((byte1 << 8u) + byte2); + const double val = [&half] + { + const int exp = (half >> 10u) & 0x1Fu; + const unsigned int mant = half & 0x3FFu; + JSON_ASSERT(0 <= exp&& exp <= 32); + JSON_ASSERT(mant <= 1024); + switch (exp) + { + case 0: + return std::ldexp(mant, -24); + case 31: + return (mant == 0) + ? std::numeric_limits::infinity() + : std::numeric_limits::quiet_NaN(); + default: + return std::ldexp(mant + 1024, exp - 25); + } + }(); + return sax->number_float((half & 0x8000u) != 0 + ? static_cast(-val) + : static_cast(val), ""); + } + + case 0xFA: // Single-Precision Float (four-byte IEEE 754) + { + float number{}; + return get_number(input_format_t::cbor, number) && sax->number_float(static_cast(number), ""); + } + + case 0xFB: // Double-Precision Float (eight-byte IEEE 754) + { + double number{}; + return get_number(input_format_t::cbor, number) && sax->number_float(static_cast(number), ""); + } + + default: // anything else (0xFF is handled inside the other types) + { + auto last_token = get_token_string(); + return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::cbor, "invalid byte: 0x" + last_token, "value"), BasicJsonType())); + } + } + } + + /*! + @brief reads a CBOR string + + This function first reads starting bytes to determine the expected + string length and then copies this number of bytes into a string. + Additionally, CBOR's strings with indefinite lengths are supported. + + @param[out] result created string + + @return whether string creation completed + */ + bool get_cbor_string(string_t& result) + { + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "string"))) + { + return false; + } + + switch (current) + { + // UTF-8 string (0x00..0x17 bytes follow) + case 0x60: + case 0x61: + case 0x62: + case 0x63: + case 0x64: + case 0x65: + case 0x66: + case 0x67: + case 0x68: + case 0x69: + case 0x6A: + case 0x6B: + case 0x6C: + case 0x6D: + case 0x6E: + case 0x6F: + case 0x70: + case 0x71: + case 0x72: + case 0x73: + case 0x74: + case 0x75: + case 0x76: + case 0x77: + { + return get_string(input_format_t::cbor, static_cast(current) & 0x1Fu, result); + } + + case 0x78: // UTF-8 string (one-byte uint8_t for n follows) + { + std::uint8_t len{}; + return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result); + } + + case 0x79: // UTF-8 string (two-byte uint16_t for n follow) + { + std::uint16_t len{}; + return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result); + } + + case 0x7A: // UTF-8 string (four-byte uint32_t for n follow) + { + std::uint32_t len{}; + return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result); + } + + case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow) + { + std::uint64_t len{}; + return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result); + } + + case 0x7F: // UTF-8 string (indefinite length) + { + while (get() != 0xFF) + { + string_t chunk; + if (!get_cbor_string(chunk)) + { + return false; + } + result.append(chunk); + } + return true; + } + + default: + { + auto last_token = get_token_string(); + return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::cbor, "expected length specification (0x60-0x7B) or indefinite string type (0x7F); last byte: 0x" + last_token, "string"), BasicJsonType())); + } + } + } + + /*! + @brief reads a CBOR byte array + + This function first reads starting bytes to determine the expected + byte array length and then copies this number of bytes into the byte array. + Additionally, CBOR's byte arrays with indefinite lengths are supported. + + @param[out] result created byte array + + @return whether byte array creation completed + */ + bool get_cbor_binary(binary_t& result) + { + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "binary"))) + { + return false; + } + + switch (current) + { + // Binary data (0x00..0x17 bytes follow) + case 0x40: + case 0x41: + case 0x42: + case 0x43: + case 0x44: + case 0x45: + case 0x46: + case 0x47: + case 0x48: + case 0x49: + case 0x4A: + case 0x4B: + case 0x4C: + case 0x4D: + case 0x4E: + case 0x4F: + case 0x50: + case 0x51: + case 0x52: + case 0x53: + case 0x54: + case 0x55: + case 0x56: + case 0x57: + { + return get_binary(input_format_t::cbor, static_cast(current) & 0x1Fu, result); + } + + case 0x58: // Binary data (one-byte uint8_t for n follows) + { + std::uint8_t len{}; + return get_number(input_format_t::cbor, len) && + get_binary(input_format_t::cbor, len, result); + } + + case 0x59: // Binary data (two-byte uint16_t for n follow) + { + std::uint16_t len{}; + return get_number(input_format_t::cbor, len) && + get_binary(input_format_t::cbor, len, result); + } + + case 0x5A: // Binary data (four-byte uint32_t for n follow) + { + std::uint32_t len{}; + return get_number(input_format_t::cbor, len) && + get_binary(input_format_t::cbor, len, result); + } + + case 0x5B: // Binary data (eight-byte uint64_t for n follow) + { + std::uint64_t len{}; + return get_number(input_format_t::cbor, len) && + get_binary(input_format_t::cbor, len, result); + } + + case 0x5F: // Binary data (indefinite length) + { + while (get() != 0xFF) + { + binary_t chunk; + if (!get_cbor_binary(chunk)) + { + return false; + } + result.insert(result.end(), chunk.begin(), chunk.end()); + } + return true; + } + + default: + { + auto last_token = get_token_string(); + return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::cbor, "expected length specification (0x40-0x5B) or indefinite binary array type (0x5F); last byte: 0x" + last_token, "binary"), BasicJsonType())); + } + } + } + + /*! + @param[in] len the length of the array or std::size_t(-1) for an + array of indefinite size + @param[in] tag_handler how CBOR tags should be treated + @return whether array creation completed + */ + bool get_cbor_array(const std::size_t len, + const cbor_tag_handler_t tag_handler) + { + if (JSON_HEDLEY_UNLIKELY(!sax->start_array(len))) + { + return false; + } + + if (len != std::size_t(-1)) + { + for (std::size_t i = 0; i < len; ++i) + { + if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(true, tag_handler))) + { + return false; + } + } + } + else + { + while (get() != 0xFF) + { + if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(false, tag_handler))) + { + return false; + } + } + } + + return sax->end_array(); + } + + /*! + @param[in] len the length of the object or std::size_t(-1) for an + object of indefinite size + @param[in] tag_handler how CBOR tags should be treated + @return whether object creation completed + */ + bool get_cbor_object(const std::size_t len, + const cbor_tag_handler_t tag_handler) + { + if (JSON_HEDLEY_UNLIKELY(!sax->start_object(len))) + { + return false; + } + + string_t key; + if (len != std::size_t(-1)) + { + for (std::size_t i = 0; i < len; ++i) + { + get(); + if (JSON_HEDLEY_UNLIKELY(!get_cbor_string(key) || !sax->key(key))) + { + return false; + } + + if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(true, tag_handler))) + { + return false; + } + key.clear(); + } + } + else + { + while (get() != 0xFF) + { + if (JSON_HEDLEY_UNLIKELY(!get_cbor_string(key) || !sax->key(key))) + { + return false; + } + + if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(true, tag_handler))) + { + return false; + } + key.clear(); + } + } + + return sax->end_object(); + } + + ///////////// + // MsgPack // + ///////////// + + /*! + @return whether a valid MessagePack value was passed to the SAX parser + */ + bool parse_msgpack_internal() + { + switch (get()) + { + // EOF + case std::char_traits::eof(): + return unexpect_eof(input_format_t::msgpack, "value"); + + // positive fixint + case 0x00: + case 0x01: + case 0x02: + case 0x03: + case 0x04: + case 0x05: + case 0x06: + case 0x07: + case 0x08: + case 0x09: + case 0x0A: + case 0x0B: + case 0x0C: + case 0x0D: + case 0x0E: + case 0x0F: + case 0x10: + case 0x11: + case 0x12: + case 0x13: + case 0x14: + case 0x15: + case 0x16: + case 0x17: + case 0x18: + case 0x19: + case 0x1A: + case 0x1B: + case 0x1C: + case 0x1D: + case 0x1E: + case 0x1F: + case 0x20: + case 0x21: + case 0x22: + case 0x23: + case 0x24: + case 0x25: + case 0x26: + case 0x27: + case 0x28: + case 0x29: + case 0x2A: + case 0x2B: + case 0x2C: + case 0x2D: + case 0x2E: + case 0x2F: + case 0x30: + case 0x31: + case 0x32: + case 0x33: + case 0x34: + case 0x35: + case 0x36: + case 0x37: + case 0x38: + case 0x39: + case 0x3A: + case 0x3B: + case 0x3C: + case 0x3D: + case 0x3E: + case 0x3F: + case 0x40: + case 0x41: + case 0x42: + case 0x43: + case 0x44: + case 0x45: + case 0x46: + case 0x47: + case 0x48: + case 0x49: + case 0x4A: + case 0x4B: + case 0x4C: + case 0x4D: + case 0x4E: + case 0x4F: + case 0x50: + case 0x51: + case 0x52: + case 0x53: + case 0x54: + case 0x55: + case 0x56: + case 0x57: + case 0x58: + case 0x59: + case 0x5A: + case 0x5B: + case 0x5C: + case 0x5D: + case 0x5E: + case 0x5F: + case 0x60: + case 0x61: + case 0x62: + case 0x63: + case 0x64: + case 0x65: + case 0x66: + case 0x67: + case 0x68: + case 0x69: + case 0x6A: + case 0x6B: + case 0x6C: + case 0x6D: + case 0x6E: + case 0x6F: + case 0x70: + case 0x71: + case 0x72: + case 0x73: + case 0x74: + case 0x75: + case 0x76: + case 0x77: + case 0x78: + case 0x79: + case 0x7A: + case 0x7B: + case 0x7C: + case 0x7D: + case 0x7E: + case 0x7F: + return sax->number_unsigned(static_cast(current)); + + // fixmap + case 0x80: + case 0x81: + case 0x82: + case 0x83: + case 0x84: + case 0x85: + case 0x86: + case 0x87: + case 0x88: + case 0x89: + case 0x8A: + case 0x8B: + case 0x8C: + case 0x8D: + case 0x8E: + case 0x8F: + return get_msgpack_object(static_cast(static_cast(current) & 0x0Fu)); + + // fixarray + case 0x90: + case 0x91: + case 0x92: + case 0x93: + case 0x94: + case 0x95: + case 0x96: + case 0x97: + case 0x98: + case 0x99: + case 0x9A: + case 0x9B: + case 0x9C: + case 0x9D: + case 0x9E: + case 0x9F: + return get_msgpack_array(static_cast(static_cast(current) & 0x0Fu)); + + // fixstr + case 0xA0: + case 0xA1: + case 0xA2: + case 0xA3: + case 0xA4: + case 0xA5: + case 0xA6: + case 0xA7: + case 0xA8: + case 0xA9: + case 0xAA: + case 0xAB: + case 0xAC: + case 0xAD: + case 0xAE: + case 0xAF: + case 0xB0: + case 0xB1: + case 0xB2: + case 0xB3: + case 0xB4: + case 0xB5: + case 0xB6: + case 0xB7: + case 0xB8: + case 0xB9: + case 0xBA: + case 0xBB: + case 0xBC: + case 0xBD: + case 0xBE: + case 0xBF: + case 0xD9: // str 8 + case 0xDA: // str 16 + case 0xDB: // str 32 + { + string_t s; + return get_msgpack_string(s) && sax->string(s); + } + + case 0xC0: // nil + return sax->null(); + + case 0xC2: // false + return sax->boolean(false); + + case 0xC3: // true + return sax->boolean(true); + + case 0xC4: // bin 8 + case 0xC5: // bin 16 + case 0xC6: // bin 32 + case 0xC7: // ext 8 + case 0xC8: // ext 16 + case 0xC9: // ext 32 + case 0xD4: // fixext 1 + case 0xD5: // fixext 2 + case 0xD6: // fixext 4 + case 0xD7: // fixext 8 + case 0xD8: // fixext 16 + { + binary_t b; + return get_msgpack_binary(b) && sax->binary(b); + } + + case 0xCA: // float 32 + { + float number{}; + return get_number(input_format_t::msgpack, number) && sax->number_float(static_cast(number), ""); + } + + case 0xCB: // float 64 + { + double number{}; + return get_number(input_format_t::msgpack, number) && sax->number_float(static_cast(number), ""); + } + + case 0xCC: // uint 8 + { + std::uint8_t number{}; + return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number); + } + + case 0xCD: // uint 16 + { + std::uint16_t number{}; + return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number); + } + + case 0xCE: // uint 32 + { + std::uint32_t number{}; + return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number); + } + + case 0xCF: // uint 64 + { + std::uint64_t number{}; + return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number); + } + + case 0xD0: // int 8 + { + std::int8_t number{}; + return get_number(input_format_t::msgpack, number) && sax->number_integer(number); + } + + case 0xD1: // int 16 + { + std::int16_t number{}; + return get_number(input_format_t::msgpack, number) && sax->number_integer(number); + } + + case 0xD2: // int 32 + { + std::int32_t number{}; + return get_number(input_format_t::msgpack, number) && sax->number_integer(number); + } + + case 0xD3: // int 64 + { + std::int64_t number{}; + return get_number(input_format_t::msgpack, number) && sax->number_integer(number); + } + + case 0xDC: // array 16 + { + std::uint16_t len{}; + return get_number(input_format_t::msgpack, len) && get_msgpack_array(static_cast(len)); + } + + case 0xDD: // array 32 + { + std::uint32_t len{}; + return get_number(input_format_t::msgpack, len) && get_msgpack_array(static_cast(len)); + } + + case 0xDE: // map 16 + { + std::uint16_t len{}; + return get_number(input_format_t::msgpack, len) && get_msgpack_object(static_cast(len)); + } + + case 0xDF: // map 32 + { + std::uint32_t len{}; + return get_number(input_format_t::msgpack, len) && get_msgpack_object(static_cast(len)); + } + + // negative fixint + case 0xE0: + case 0xE1: + case 0xE2: + case 0xE3: + case 0xE4: + case 0xE5: + case 0xE6: + case 0xE7: + case 0xE8: + case 0xE9: + case 0xEA: + case 0xEB: + case 0xEC: + case 0xED: + case 0xEE: + case 0xEF: + case 0xF0: + case 0xF1: + case 0xF2: + case 0xF3: + case 0xF4: + case 0xF5: + case 0xF6: + case 0xF7: + case 0xF8: + case 0xF9: + case 0xFA: + case 0xFB: + case 0xFC: + case 0xFD: + case 0xFE: + case 0xFF: + return sax->number_integer(static_cast(current)); + + default: // anything else + { + auto last_token = get_token_string(); + return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::msgpack, "invalid byte: 0x" + last_token, "value"), BasicJsonType())); + } + } + } + + /*! + @brief reads a MessagePack string + + This function first reads starting bytes to determine the expected + string length and then copies this number of bytes into a string. + + @param[out] result created string + + @return whether string creation completed + */ + bool get_msgpack_string(string_t& result) + { + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::msgpack, "string"))) + { + return false; + } + + switch (current) + { + // fixstr + case 0xA0: + case 0xA1: + case 0xA2: + case 0xA3: + case 0xA4: + case 0xA5: + case 0xA6: + case 0xA7: + case 0xA8: + case 0xA9: + case 0xAA: + case 0xAB: + case 0xAC: + case 0xAD: + case 0xAE: + case 0xAF: + case 0xB0: + case 0xB1: + case 0xB2: + case 0xB3: + case 0xB4: + case 0xB5: + case 0xB6: + case 0xB7: + case 0xB8: + case 0xB9: + case 0xBA: + case 0xBB: + case 0xBC: + case 0xBD: + case 0xBE: + case 0xBF: + { + return get_string(input_format_t::msgpack, static_cast(current) & 0x1Fu, result); + } + + case 0xD9: // str 8 + { + std::uint8_t len{}; + return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result); + } + + case 0xDA: // str 16 + { + std::uint16_t len{}; + return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result); + } + + case 0xDB: // str 32 + { + std::uint32_t len{}; + return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result); + } + + default: + { + auto last_token = get_token_string(); + return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::msgpack, "expected length specification (0xA0-0xBF, 0xD9-0xDB); last byte: 0x" + last_token, "string"), BasicJsonType())); + } + } + } + + /*! + @brief reads a MessagePack byte array + + This function first reads starting bytes to determine the expected + byte array length and then copies this number of bytes into a byte array. + + @param[out] result created byte array + + @return whether byte array creation completed + */ + bool get_msgpack_binary(binary_t& result) + { + // helper function to set the subtype + auto assign_and_return_true = [&result](std::int8_t subtype) + { + result.set_subtype(static_cast(subtype)); + return true; + }; + + switch (current) + { + case 0xC4: // bin 8 + { + std::uint8_t len{}; + return get_number(input_format_t::msgpack, len) && + get_binary(input_format_t::msgpack, len, result); + } + + case 0xC5: // bin 16 + { + std::uint16_t len{}; + return get_number(input_format_t::msgpack, len) && + get_binary(input_format_t::msgpack, len, result); + } + + case 0xC6: // bin 32 + { + std::uint32_t len{}; + return get_number(input_format_t::msgpack, len) && + get_binary(input_format_t::msgpack, len, result); + } + + case 0xC7: // ext 8 + { + std::uint8_t len{}; + std::int8_t subtype{}; + return get_number(input_format_t::msgpack, len) && + get_number(input_format_t::msgpack, subtype) && + get_binary(input_format_t::msgpack, len, result) && + assign_and_return_true(subtype); + } + + case 0xC8: // ext 16 + { + std::uint16_t len{}; + std::int8_t subtype{}; + return get_number(input_format_t::msgpack, len) && + get_number(input_format_t::msgpack, subtype) && + get_binary(input_format_t::msgpack, len, result) && + assign_and_return_true(subtype); + } + + case 0xC9: // ext 32 + { + std::uint32_t len{}; + std::int8_t subtype{}; + return get_number(input_format_t::msgpack, len) && + get_number(input_format_t::msgpack, subtype) && + get_binary(input_format_t::msgpack, len, result) && + assign_and_return_true(subtype); + } + + case 0xD4: // fixext 1 + { + std::int8_t subtype{}; + return get_number(input_format_t::msgpack, subtype) && + get_binary(input_format_t::msgpack, 1, result) && + assign_and_return_true(subtype); + } + + case 0xD5: // fixext 2 + { + std::int8_t subtype{}; + return get_number(input_format_t::msgpack, subtype) && + get_binary(input_format_t::msgpack, 2, result) && + assign_and_return_true(subtype); + } + + case 0xD6: // fixext 4 + { + std::int8_t subtype{}; + return get_number(input_format_t::msgpack, subtype) && + get_binary(input_format_t::msgpack, 4, result) && + assign_and_return_true(subtype); + } + + case 0xD7: // fixext 8 + { + std::int8_t subtype{}; + return get_number(input_format_t::msgpack, subtype) && + get_binary(input_format_t::msgpack, 8, result) && + assign_and_return_true(subtype); + } + + case 0xD8: // fixext 16 + { + std::int8_t subtype{}; + return get_number(input_format_t::msgpack, subtype) && + get_binary(input_format_t::msgpack, 16, result) && + assign_and_return_true(subtype); + } + + default: // LCOV_EXCL_LINE + return false; // LCOV_EXCL_LINE + } + } + + /*! + @param[in] len the length of the array + @return whether array creation completed + */ + bool get_msgpack_array(const std::size_t len) + { + if (JSON_HEDLEY_UNLIKELY(!sax->start_array(len))) + { + return false; + } + + for (std::size_t i = 0; i < len; ++i) + { + if (JSON_HEDLEY_UNLIKELY(!parse_msgpack_internal())) + { + return false; + } + } + + return sax->end_array(); + } + + /*! + @param[in] len the length of the object + @return whether object creation completed + */ + bool get_msgpack_object(const std::size_t len) + { + if (JSON_HEDLEY_UNLIKELY(!sax->start_object(len))) + { + return false; + } + + string_t key; + for (std::size_t i = 0; i < len; ++i) + { + get(); + if (JSON_HEDLEY_UNLIKELY(!get_msgpack_string(key) || !sax->key(key))) + { + return false; + } + + if (JSON_HEDLEY_UNLIKELY(!parse_msgpack_internal())) + { + return false; + } + key.clear(); + } + + return sax->end_object(); + } + + //////////// + // UBJSON // + //////////// + + /*! + @param[in] get_char whether a new character should be retrieved from the + input (true, default) or whether the last read + character should be considered instead + + @return whether a valid UBJSON value was passed to the SAX parser + */ + bool parse_ubjson_internal(const bool get_char = true) + { + return get_ubjson_value(get_char ? get_ignore_noop() : current); + } + + /*! + @brief reads a UBJSON string + + This function is either called after reading the 'S' byte explicitly + indicating a string, or in case of an object key where the 'S' byte can be + left out. + + @param[out] result created string + @param[in] get_char whether a new character should be retrieved from the + input (true, default) or whether the last read + character should be considered instead + + @return whether string creation completed + */ + bool get_ubjson_string(string_t& result, const bool get_char = true) + { + if (get_char) + { + get(); // TODO(niels): may we ignore N here? + } + + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "value"))) + { + return false; + } + + switch (current) + { + case 'U': + { + std::uint8_t len{}; + return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result); + } + + case 'i': + { + std::int8_t len{}; + return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result); + } + + case 'I': + { + std::int16_t len{}; + return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result); + } + + case 'l': + { + std::int32_t len{}; + return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result); + } + + case 'L': + { + std::int64_t len{}; + return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result); + } + + default: + auto last_token = get_token_string(); + return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::ubjson, "expected length type specification (U, i, I, l, L); last byte: 0x" + last_token, "string"), BasicJsonType())); + } + } + + /*! + @param[out] result determined size + @return whether size determination completed + */ + bool get_ubjson_size_value(std::size_t& result) + { + switch (get_ignore_noop()) + { + case 'U': + { + std::uint8_t number{}; + if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number))) + { + return false; + } + result = static_cast(number); + return true; + } + + case 'i': + { + std::int8_t number{}; + if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number))) + { + return false; + } + result = static_cast(number); // NOLINT(bugprone-signed-char-misuse,cert-str34-c): number is not a char + return true; + } + + case 'I': + { + std::int16_t number{}; + if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number))) + { + return false; + } + result = static_cast(number); + return true; + } + + case 'l': + { + std::int32_t number{}; + if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number))) + { + return false; + } + result = static_cast(number); + return true; + } + + case 'L': + { + std::int64_t number{}; + if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number))) + { + return false; + } + result = static_cast(number); + return true; + } + + default: + { + auto last_token = get_token_string(); + return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::ubjson, "expected length type specification (U, i, I, l, L) after '#'; last byte: 0x" + last_token, "size"), BasicJsonType())); + } + } + } + + /*! + @brief determine the type and size for a container + + In the optimized UBJSON format, a type and a size can be provided to allow + for a more compact representation. + + @param[out] result pair of the size and the type + + @return whether pair creation completed + */ + bool get_ubjson_size_type(std::pair& result) + { + result.first = string_t::npos; // size + result.second = 0; // type + + get_ignore_noop(); + + if (current == '$') + { + result.second = get(); // must not ignore 'N', because 'N' maybe the type + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "type"))) + { + return false; + } + + get_ignore_noop(); + if (JSON_HEDLEY_UNLIKELY(current != '#')) + { + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "value"))) + { + return false; + } + auto last_token = get_token_string(); + return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::ubjson, "expected '#' after type information; last byte: 0x" + last_token, "size"), BasicJsonType())); + } + + return get_ubjson_size_value(result.first); + } + + if (current == '#') + { + return get_ubjson_size_value(result.first); + } + + return true; + } + + /*! + @param prefix the previously read or set type prefix + @return whether value creation completed + */ + bool get_ubjson_value(const char_int_type prefix) + { + switch (prefix) + { + case std::char_traits::eof(): // EOF + return unexpect_eof(input_format_t::ubjson, "value"); + + case 'T': // true + return sax->boolean(true); + case 'F': // false + return sax->boolean(false); + + case 'Z': // null + return sax->null(); + + case 'U': + { + std::uint8_t number{}; + return get_number(input_format_t::ubjson, number) && sax->number_unsigned(number); + } + + case 'i': + { + std::int8_t number{}; + return get_number(input_format_t::ubjson, number) && sax->number_integer(number); + } + + case 'I': + { + std::int16_t number{}; + return get_number(input_format_t::ubjson, number) && sax->number_integer(number); + } + + case 'l': + { + std::int32_t number{}; + return get_number(input_format_t::ubjson, number) && sax->number_integer(number); + } + + case 'L': + { + std::int64_t number{}; + return get_number(input_format_t::ubjson, number) && sax->number_integer(number); + } + + case 'd': + { + float number{}; + return get_number(input_format_t::ubjson, number) && sax->number_float(static_cast(number), ""); + } + + case 'D': + { + double number{}; + return get_number(input_format_t::ubjson, number) && sax->number_float(static_cast(number), ""); + } + + case 'H': + { + return get_ubjson_high_precision_number(); + } + + case 'C': // char + { + get(); + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "char"))) + { + return false; + } + if (JSON_HEDLEY_UNLIKELY(current > 127)) + { + auto last_token = get_token_string(); + return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::ubjson, "byte after 'C' must be in range 0x00..0x7F; last byte: 0x" + last_token, "char"), BasicJsonType())); + } + string_t s(1, static_cast(current)); + return sax->string(s); + } + + case 'S': // string + { + string_t s; + return get_ubjson_string(s) && sax->string(s); + } + + case '[': // array + return get_ubjson_array(); + + case '{': // object + return get_ubjson_object(); + + default: // anything else + { + auto last_token = get_token_string(); + return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::ubjson, "invalid byte: 0x" + last_token, "value"), BasicJsonType())); + } + } + } + + /*! + @return whether array creation completed + */ + bool get_ubjson_array() + { + std::pair size_and_type; + if (JSON_HEDLEY_UNLIKELY(!get_ubjson_size_type(size_and_type))) + { + return false; + } + + if (size_and_type.first != string_t::npos) + { + if (JSON_HEDLEY_UNLIKELY(!sax->start_array(size_and_type.first))) + { + return false; + } + + if (size_and_type.second != 0) + { + if (size_and_type.second != 'N') + { + for (std::size_t i = 0; i < size_and_type.first; ++i) + { + if (JSON_HEDLEY_UNLIKELY(!get_ubjson_value(size_and_type.second))) + { + return false; + } + } + } + } + else + { + for (std::size_t i = 0; i < size_and_type.first; ++i) + { + if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal())) + { + return false; + } + } + } + } + else + { + if (JSON_HEDLEY_UNLIKELY(!sax->start_array(std::size_t(-1)))) + { + return false; + } + + while (current != ']') + { + if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal(false))) + { + return false; + } + get_ignore_noop(); + } + } + + return sax->end_array(); + } + + /*! + @return whether object creation completed + */ + bool get_ubjson_object() + { + std::pair size_and_type; + if (JSON_HEDLEY_UNLIKELY(!get_ubjson_size_type(size_and_type))) + { + return false; + } + + string_t key; + if (size_and_type.first != string_t::npos) + { + if (JSON_HEDLEY_UNLIKELY(!sax->start_object(size_and_type.first))) + { + return false; + } + + if (size_and_type.second != 0) + { + for (std::size_t i = 0; i < size_and_type.first; ++i) + { + if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key) || !sax->key(key))) + { + return false; + } + if (JSON_HEDLEY_UNLIKELY(!get_ubjson_value(size_and_type.second))) + { + return false; + } + key.clear(); + } + } + else + { + for (std::size_t i = 0; i < size_and_type.first; ++i) + { + if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key) || !sax->key(key))) + { + return false; + } + if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal())) + { + return false; + } + key.clear(); + } + } + } + else + { + if (JSON_HEDLEY_UNLIKELY(!sax->start_object(std::size_t(-1)))) + { + return false; + } + + while (current != '}') + { + if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key, false) || !sax->key(key))) + { + return false; + } + if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal())) + { + return false; + } + get_ignore_noop(); + key.clear(); + } + } + + return sax->end_object(); + } + + // Note, no reader for UBJSON binary types is implemented because they do + // not exist + + bool get_ubjson_high_precision_number() + { + // get size of following number string + std::size_t size{}; + auto res = get_ubjson_size_value(size); + if (JSON_HEDLEY_UNLIKELY(!res)) + { + return res; + } + + // get number string + std::vector number_vector; + for (std::size_t i = 0; i < size; ++i) + { + get(); + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "number"))) + { + return false; + } + number_vector.push_back(static_cast(current)); + } + + // parse number string + using ia_type = decltype(detail::input_adapter(number_vector)); + auto number_lexer = detail::lexer(detail::input_adapter(number_vector), false); + const auto result_number = number_lexer.scan(); + const auto number_string = number_lexer.get_token_string(); + const auto result_remainder = number_lexer.scan(); + + using token_type = typename detail::lexer_base::token_type; + + if (JSON_HEDLEY_UNLIKELY(result_remainder != token_type::end_of_input)) + { + return sax->parse_error(chars_read, number_string, parse_error::create(115, chars_read, exception_message(input_format_t::ubjson, "invalid number text: " + number_lexer.get_token_string(), "high-precision number"), BasicJsonType())); + } + + switch (result_number) + { + case token_type::value_integer: + return sax->number_integer(number_lexer.get_number_integer()); + case token_type::value_unsigned: + return sax->number_unsigned(number_lexer.get_number_unsigned()); + case token_type::value_float: + return sax->number_float(number_lexer.get_number_float(), std::move(number_string)); + default: + return sax->parse_error(chars_read, number_string, parse_error::create(115, chars_read, exception_message(input_format_t::ubjson, "invalid number text: " + number_lexer.get_token_string(), "high-precision number"), BasicJsonType())); + } + } + + /////////////////////// + // Utility functions // + /////////////////////// + + /*! + @brief get next character from the input + + This function provides the interface to the used input adapter. It does + not throw in case the input reached EOF, but returns a -'ve valued + `std::char_traits::eof()` in that case. + + @return character read from the input + */ + char_int_type get() + { + ++chars_read; + return current = ia.get_character(); + } + + /*! + @return character read from the input after ignoring all 'N' entries + */ + char_int_type get_ignore_noop() + { + do + { + get(); + } + while (current == 'N'); + + return current; + } + + /* + @brief read a number from the input + + @tparam NumberType the type of the number + @param[in] format the current format (for diagnostics) + @param[out] result number of type @a NumberType + + @return whether conversion completed + + @note This function needs to respect the system's endianess, because + bytes in CBOR, MessagePack, and UBJSON are stored in network order + (big endian) and therefore need reordering on little endian systems. + */ + template + bool get_number(const input_format_t format, NumberType& result) + { + // step 1: read input into array with system's byte order + std::array vec{}; + for (std::size_t i = 0; i < sizeof(NumberType); ++i) + { + get(); + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(format, "number"))) + { + return false; + } + + // reverse byte order prior to conversion if necessary + if (is_little_endian != InputIsLittleEndian) + { + vec[sizeof(NumberType) - i - 1] = static_cast(current); + } + else + { + vec[i] = static_cast(current); // LCOV_EXCL_LINE + } + } + + // step 2: convert array into number of type T and return + std::memcpy(&result, vec.data(), sizeof(NumberType)); + return true; + } + + /*! + @brief create a string by reading characters from the input + + @tparam NumberType the type of the number + @param[in] format the current format (for diagnostics) + @param[in] len number of characters to read + @param[out] result string created by reading @a len bytes + + @return whether string creation completed + + @note We can not reserve @a len bytes for the result, because @a len + may be too large. Usually, @ref unexpect_eof() detects the end of + the input before we run out of string memory. + */ + template + bool get_string(const input_format_t format, + const NumberType len, + string_t& result) + { + bool success = true; + for (NumberType i = 0; i < len; i++) + { + get(); + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(format, "string"))) + { + success = false; + break; + } + result.push_back(static_cast(current)); + } + return success; + } + + /*! + @brief create a byte array by reading bytes from the input + + @tparam NumberType the type of the number + @param[in] format the current format (for diagnostics) + @param[in] len number of bytes to read + @param[out] result byte array created by reading @a len bytes + + @return whether byte array creation completed + + @note We can not reserve @a len bytes for the result, because @a len + may be too large. Usually, @ref unexpect_eof() detects the end of + the input before we run out of memory. + */ + template + bool get_binary(const input_format_t format, + const NumberType len, + binary_t& result) + { + bool success = true; + for (NumberType i = 0; i < len; i++) + { + get(); + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(format, "binary"))) + { + success = false; + break; + } + result.push_back(static_cast(current)); + } + return success; + } + + /*! + @param[in] format the current format (for diagnostics) + @param[in] context further context information (for diagnostics) + @return whether the last read character is not EOF + */ + JSON_HEDLEY_NON_NULL(3) + bool unexpect_eof(const input_format_t format, const char* context) const + { + if (JSON_HEDLEY_UNLIKELY(current == std::char_traits::eof())) + { + return sax->parse_error(chars_read, "", + parse_error::create(110, chars_read, exception_message(format, "unexpected end of input", context), BasicJsonType())); + } + return true; + } + + /*! + @return a string representation of the last read byte + */ + std::string get_token_string() const + { + std::array cr{{}}; + (std::snprintf)(cr.data(), cr.size(), "%.2hhX", static_cast(current)); // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg) + return std::string{cr.data()}; + } + + /*! + @param[in] format the current format + @param[in] detail a detailed error message + @param[in] context further context information + @return a message string to use in the parse_error exceptions + */ + std::string exception_message(const input_format_t format, + const std::string& detail, + const std::string& context) const + { + std::string error_msg = "syntax error while parsing "; + + switch (format) + { + case input_format_t::cbor: + error_msg += "CBOR"; + break; + + case input_format_t::msgpack: + error_msg += "MessagePack"; + break; + + case input_format_t::ubjson: + error_msg += "UBJSON"; + break; + + case input_format_t::bson: + error_msg += "BSON"; + break; + + default: // LCOV_EXCL_LINE + JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE + } + + return error_msg + " " + context + ": " + detail; + } + + private: + /// input adapter + InputAdapterType ia; + + /// the current character + char_int_type current = std::char_traits::eof(); + + /// the number of characters read + std::size_t chars_read = 0; + + /// whether we can assume little endianess + const bool is_little_endian = little_endianess(); + + /// the SAX parser + json_sax_t* sax = nullptr; +}; +} // namespace detail +} // namespace nlohmann + +// #include + +// #include + +// #include + + +#include // isfinite +#include // uint8_t +#include // function +#include // string +#include // move +#include // vector + +// #include + +// #include + +// #include + +// #include + +// #include + +// #include + +// #include + + +namespace nlohmann +{ +namespace detail +{ +//////////// +// parser // +//////////// + +enum class parse_event_t : uint8_t +{ + /// the parser read `{` and started to process a JSON object + object_start, + /// the parser read `}` and finished processing a JSON object + object_end, + /// the parser read `[` and started to process a JSON array + array_start, + /// the parser read `]` and finished processing a JSON array + array_end, + /// the parser read a key of a value in an object + key, + /// the parser finished reading a JSON value + value +}; + +template +using parser_callback_t = + std::function; + +/*! +@brief syntax analysis + +This class implements a recursive descent parser. +*/ +template +class parser +{ + using number_integer_t = typename BasicJsonType::number_integer_t; + using number_unsigned_t = typename BasicJsonType::number_unsigned_t; + using number_float_t = typename BasicJsonType::number_float_t; + using string_t = typename BasicJsonType::string_t; + using lexer_t = lexer; + using token_type = typename lexer_t::token_type; + + public: + /// a parser reading from an input adapter + explicit parser(InputAdapterType&& adapter, + const parser_callback_t cb = nullptr, + const bool allow_exceptions_ = true, + const bool skip_comments = false) + : callback(cb) + , m_lexer(std::move(adapter), skip_comments) + , allow_exceptions(allow_exceptions_) + { + // read first token + get_token(); + } + + /*! + @brief public parser interface + + @param[in] strict whether to expect the last token to be EOF + @param[in,out] result parsed JSON value + + @throw parse_error.101 in case of an unexpected token + @throw parse_error.102 if to_unicode fails or surrogate error + @throw parse_error.103 if to_unicode fails + */ + void parse(const bool strict, BasicJsonType& result) + { + if (callback) + { + json_sax_dom_callback_parser sdp(result, callback, allow_exceptions); + sax_parse_internal(&sdp); + + // in strict mode, input must be completely read + if (strict && (get_token() != token_type::end_of_input)) + { + sdp.parse_error(m_lexer.get_position(), + m_lexer.get_token_string(), + parse_error::create(101, m_lexer.get_position(), + exception_message(token_type::end_of_input, "value"), BasicJsonType())); + } + + // in case of an error, return discarded value + if (sdp.is_errored()) + { + result = value_t::discarded; + return; + } + + // set top-level value to null if it was discarded by the callback + // function + if (result.is_discarded()) + { + result = nullptr; + } + } + else + { + json_sax_dom_parser sdp(result, allow_exceptions); + sax_parse_internal(&sdp); + + // in strict mode, input must be completely read + if (strict && (get_token() != token_type::end_of_input)) + { + sdp.parse_error(m_lexer.get_position(), + m_lexer.get_token_string(), + parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_of_input, "value"), BasicJsonType())); + } + + // in case of an error, return discarded value + if (sdp.is_errored()) + { + result = value_t::discarded; + return; + } + } + + result.assert_invariant(); + } + + /*! + @brief public accept interface + + @param[in] strict whether to expect the last token to be EOF + @return whether the input is a proper JSON text + */ + bool accept(const bool strict = true) + { + json_sax_acceptor sax_acceptor; + return sax_parse(&sax_acceptor, strict); + } + + template + JSON_HEDLEY_NON_NULL(2) + bool sax_parse(SAX* sax, const bool strict = true) + { + (void)detail::is_sax_static_asserts {}; + const bool result = sax_parse_internal(sax); + + // strict mode: next byte must be EOF + if (result && strict && (get_token() != token_type::end_of_input)) + { + return sax->parse_error(m_lexer.get_position(), + m_lexer.get_token_string(), + parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_of_input, "value"), BasicJsonType())); + } + + return result; + } + + private: + template + JSON_HEDLEY_NON_NULL(2) + bool sax_parse_internal(SAX* sax) + { + // stack to remember the hierarchy of structured values we are parsing + // true = array; false = object + std::vector states; + // value to avoid a goto (see comment where set to true) + bool skip_to_state_evaluation = false; + + while (true) + { + if (!skip_to_state_evaluation) + { + // invariant: get_token() was called before each iteration + switch (last_token) + { + case token_type::begin_object: + { + if (JSON_HEDLEY_UNLIKELY(!sax->start_object(std::size_t(-1)))) + { + return false; + } + + // closing } -> we are done + if (get_token() == token_type::end_object) + { + if (JSON_HEDLEY_UNLIKELY(!sax->end_object())) + { + return false; + } + break; + } + + // parse key + if (JSON_HEDLEY_UNLIKELY(last_token != token_type::value_string)) + { + return sax->parse_error(m_lexer.get_position(), + m_lexer.get_token_string(), + parse_error::create(101, m_lexer.get_position(), exception_message(token_type::value_string, "object key"), BasicJsonType())); + } + if (JSON_HEDLEY_UNLIKELY(!sax->key(m_lexer.get_string()))) + { + return false; + } + + // parse separator (:) + if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::name_separator)) + { + return sax->parse_error(m_lexer.get_position(), + m_lexer.get_token_string(), + parse_error::create(101, m_lexer.get_position(), exception_message(token_type::name_separator, "object separator"), BasicJsonType())); + } + + // remember we are now inside an object + states.push_back(false); + + // parse values + get_token(); + continue; + } + + case token_type::begin_array: + { + if (JSON_HEDLEY_UNLIKELY(!sax->start_array(std::size_t(-1)))) + { + return false; + } + + // closing ] -> we are done + if (get_token() == token_type::end_array) + { + if (JSON_HEDLEY_UNLIKELY(!sax->end_array())) + { + return false; + } + break; + } + + // remember we are now inside an array + states.push_back(true); + + // parse values (no need to call get_token) + continue; + } + + case token_type::value_float: + { + const auto res = m_lexer.get_number_float(); + + if (JSON_HEDLEY_UNLIKELY(!std::isfinite(res))) + { + return sax->parse_error(m_lexer.get_position(), + m_lexer.get_token_string(), + out_of_range::create(406, "number overflow parsing '" + m_lexer.get_token_string() + "'", BasicJsonType())); + } + + if (JSON_HEDLEY_UNLIKELY(!sax->number_float(res, m_lexer.get_string()))) + { + return false; + } + + break; + } + + case token_type::literal_false: + { + if (JSON_HEDLEY_UNLIKELY(!sax->boolean(false))) + { + return false; + } + break; + } + + case token_type::literal_null: + { + if (JSON_HEDLEY_UNLIKELY(!sax->null())) + { + return false; + } + break; + } + + case token_type::literal_true: + { + if (JSON_HEDLEY_UNLIKELY(!sax->boolean(true))) + { + return false; + } + break; + } + + case token_type::value_integer: + { + if (JSON_HEDLEY_UNLIKELY(!sax->number_integer(m_lexer.get_number_integer()))) + { + return false; + } + break; + } + + case token_type::value_string: + { + if (JSON_HEDLEY_UNLIKELY(!sax->string(m_lexer.get_string()))) + { + return false; + } + break; + } + + case token_type::value_unsigned: + { + if (JSON_HEDLEY_UNLIKELY(!sax->number_unsigned(m_lexer.get_number_unsigned()))) + { + return false; + } + break; + } + + case token_type::parse_error: + { + // using "uninitialized" to avoid "expected" message + return sax->parse_error(m_lexer.get_position(), + m_lexer.get_token_string(), + parse_error::create(101, m_lexer.get_position(), exception_message(token_type::uninitialized, "value"), BasicJsonType())); + } + + default: // the last token was unexpected + { + return sax->parse_error(m_lexer.get_position(), + m_lexer.get_token_string(), + parse_error::create(101, m_lexer.get_position(), exception_message(token_type::literal_or_value, "value"), BasicJsonType())); + } + } + } + else + { + skip_to_state_evaluation = false; + } + + // we reached this line after we successfully parsed a value + if (states.empty()) + { + // empty stack: we reached the end of the hierarchy: done + return true; + } + + if (states.back()) // array + { + // comma -> next value + if (get_token() == token_type::value_separator) + { + // parse a new value + get_token(); + continue; + } + + // closing ] + if (JSON_HEDLEY_LIKELY(last_token == token_type::end_array)) + { + if (JSON_HEDLEY_UNLIKELY(!sax->end_array())) + { + return false; + } + + // We are done with this array. Before we can parse a + // new value, we need to evaluate the new state first. + // By setting skip_to_state_evaluation to false, we + // are effectively jumping to the beginning of this if. + JSON_ASSERT(!states.empty()); + states.pop_back(); + skip_to_state_evaluation = true; + continue; + } + + return sax->parse_error(m_lexer.get_position(), + m_lexer.get_token_string(), + parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_array, "array"), BasicJsonType())); + } + + // states.back() is false -> object + + // comma -> next value + if (get_token() == token_type::value_separator) + { + // parse key + if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::value_string)) + { + return sax->parse_error(m_lexer.get_position(), + m_lexer.get_token_string(), + parse_error::create(101, m_lexer.get_position(), exception_message(token_type::value_string, "object key"), BasicJsonType())); + } + + if (JSON_HEDLEY_UNLIKELY(!sax->key(m_lexer.get_string()))) + { + return false; + } + + // parse separator (:) + if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::name_separator)) + { + return sax->parse_error(m_lexer.get_position(), + m_lexer.get_token_string(), + parse_error::create(101, m_lexer.get_position(), exception_message(token_type::name_separator, "object separator"), BasicJsonType())); + } + + // parse values + get_token(); + continue; + } + + // closing } + if (JSON_HEDLEY_LIKELY(last_token == token_type::end_object)) + { + if (JSON_HEDLEY_UNLIKELY(!sax->end_object())) + { + return false; + } + + // We are done with this object. Before we can parse a + // new value, we need to evaluate the new state first. + // By setting skip_to_state_evaluation to false, we + // are effectively jumping to the beginning of this if. + JSON_ASSERT(!states.empty()); + states.pop_back(); + skip_to_state_evaluation = true; + continue; + } + + return sax->parse_error(m_lexer.get_position(), + m_lexer.get_token_string(), + parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_object, "object"), BasicJsonType())); + } + } + + /// get next token from lexer + token_type get_token() + { + return last_token = m_lexer.scan(); + } + + std::string exception_message(const token_type expected, const std::string& context) + { + std::string error_msg = "syntax error "; + + if (!context.empty()) + { + error_msg += "while parsing " + context + " "; + } + + error_msg += "- "; + + if (last_token == token_type::parse_error) + { + error_msg += std::string(m_lexer.get_error_message()) + "; last read: '" + + m_lexer.get_token_string() + "'"; + } + else + { + error_msg += "unexpected " + std::string(lexer_t::token_type_name(last_token)); + } + + if (expected != token_type::uninitialized) + { + error_msg += "; expected " + std::string(lexer_t::token_type_name(expected)); + } + + return error_msg; + } + + private: + /// callback function + const parser_callback_t callback = nullptr; + /// the type of the last read token + token_type last_token = token_type::uninitialized; + /// the lexer + lexer_t m_lexer; + /// whether to throw exceptions in case of errors + const bool allow_exceptions = true; +}; + +} // namespace detail +} // namespace nlohmann + +// #include + + +// #include + + +#include // ptrdiff_t +#include // numeric_limits + +// #include + + +namespace nlohmann +{ +namespace detail +{ +/* +@brief an iterator for primitive JSON types + +This class models an iterator for primitive JSON types (boolean, number, +string). It's only purpose is to allow the iterator/const_iterator classes +to "iterate" over primitive values. Internally, the iterator is modeled by +a `difference_type` variable. Value begin_value (`0`) models the begin, +end_value (`1`) models past the end. +*/ +class primitive_iterator_t +{ + private: + using difference_type = std::ptrdiff_t; + static constexpr difference_type begin_value = 0; + static constexpr difference_type end_value = begin_value + 1; + + JSON_PRIVATE_UNLESS_TESTED: + /// iterator as signed integer type + difference_type m_it = (std::numeric_limits::min)(); + + public: + constexpr difference_type get_value() const noexcept + { + return m_it; + } + + /// set iterator to a defined beginning + void set_begin() noexcept + { + m_it = begin_value; + } + + /// set iterator to a defined past the end + void set_end() noexcept + { + m_it = end_value; + } + + /// return whether the iterator can be dereferenced + constexpr bool is_begin() const noexcept + { + return m_it == begin_value; + } + + /// return whether the iterator is at end + constexpr bool is_end() const noexcept + { + return m_it == end_value; + } + + friend constexpr bool operator==(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept + { + return lhs.m_it == rhs.m_it; + } + + friend constexpr bool operator<(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept + { + return lhs.m_it < rhs.m_it; + } + + primitive_iterator_t operator+(difference_type n) noexcept + { + auto result = *this; + result += n; + return result; + } + + friend constexpr difference_type operator-(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept + { + return lhs.m_it - rhs.m_it; + } + + primitive_iterator_t& operator++() noexcept + { + ++m_it; + return *this; + } + + primitive_iterator_t const operator++(int) noexcept // NOLINT(readability-const-return-type) + { + auto result = *this; + ++m_it; + return result; + } + + primitive_iterator_t& operator--() noexcept + { + --m_it; + return *this; + } + + primitive_iterator_t const operator--(int) noexcept // NOLINT(readability-const-return-type) + { + auto result = *this; + --m_it; + return result; + } + + primitive_iterator_t& operator+=(difference_type n) noexcept + { + m_it += n; + return *this; + } + + primitive_iterator_t& operator-=(difference_type n) noexcept + { + m_it -= n; + return *this; + } +}; +} // namespace detail +} // namespace nlohmann + + +namespace nlohmann +{ +namespace detail +{ +/*! +@brief an iterator value + +@note This structure could easily be a union, but MSVC currently does not allow +unions members with complex constructors, see https://github.com/nlohmann/json/pull/105. +*/ +template struct internal_iterator +{ + /// iterator for JSON objects + typename BasicJsonType::object_t::iterator object_iterator {}; + /// iterator for JSON arrays + typename BasicJsonType::array_t::iterator array_iterator {}; + /// generic iterator for all other types + primitive_iterator_t primitive_iterator {}; +}; +} // namespace detail +} // namespace nlohmann + +// #include + + +#include // iterator, random_access_iterator_tag, bidirectional_iterator_tag, advance, next +#include // conditional, is_const, remove_const + +// #include + +// #include + +// #include + +// #include + +// #include + +// #include + +// #include + + +namespace nlohmann +{ +namespace detail +{ +// forward declare, to be able to friend it later on +template class iteration_proxy; +template class iteration_proxy_value; + +/*! +@brief a template for a bidirectional iterator for the @ref basic_json class +This class implements a both iterators (iterator and const_iterator) for the +@ref basic_json class. +@note An iterator is called *initialized* when a pointer to a JSON value has + been set (e.g., by a constructor or a copy assignment). If the iterator is + default-constructed, it is *uninitialized* and most methods are undefined. + **The library uses assertions to detect calls on uninitialized iterators.** +@requirement The class satisfies the following concept requirements: +- +[BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator): + The iterator that can be moved can be moved in both directions (i.e. + incremented and decremented). +@since version 1.0.0, simplified in version 2.0.9, change to bidirectional + iterators in version 3.0.0 (see https://github.com/nlohmann/json/issues/593) +*/ +template +class iter_impl +{ + /// the iterator with BasicJsonType of different const-ness + using other_iter_impl = iter_impl::value, typename std::remove_const::type, const BasicJsonType>::type>; + /// allow basic_json to access private members + friend other_iter_impl; + friend BasicJsonType; + friend iteration_proxy; + friend iteration_proxy_value; + + using object_t = typename BasicJsonType::object_t; + using array_t = typename BasicJsonType::array_t; + // make sure BasicJsonType is basic_json or const basic_json + static_assert(is_basic_json::type>::value, + "iter_impl only accepts (const) basic_json"); + + public: + + /// The std::iterator class template (used as a base class to provide typedefs) is deprecated in C++17. + /// The C++ Standard has never required user-defined iterators to derive from std::iterator. + /// A user-defined iterator should provide publicly accessible typedefs named + /// iterator_category, value_type, difference_type, pointer, and reference. + /// Note that value_type is required to be non-const, even for constant iterators. + using iterator_category = std::bidirectional_iterator_tag; + + /// the type of the values when the iterator is dereferenced + using value_type = typename BasicJsonType::value_type; + /// a type to represent differences between iterators + using difference_type = typename BasicJsonType::difference_type; + /// defines a pointer to the type iterated over (value_type) + using pointer = typename std::conditional::value, + typename BasicJsonType::const_pointer, + typename BasicJsonType::pointer>::type; + /// defines a reference to the type iterated over (value_type) + using reference = + typename std::conditional::value, + typename BasicJsonType::const_reference, + typename BasicJsonType::reference>::type; + + iter_impl() = default; + ~iter_impl() = default; + iter_impl(iter_impl&&) noexcept = default; + iter_impl& operator=(iter_impl&&) noexcept = default; + + /*! + @brief constructor for a given JSON instance + @param[in] object pointer to a JSON object for this iterator + @pre object != nullptr + @post The iterator is initialized; i.e. `m_object != nullptr`. + */ + explicit iter_impl(pointer object) noexcept : m_object(object) + { + JSON_ASSERT(m_object != nullptr); + + switch (m_object->m_type) + { + case value_t::object: + { + m_it.object_iterator = typename object_t::iterator(); + break; + } + + case value_t::array: + { + m_it.array_iterator = typename array_t::iterator(); + break; + } + + default: + { + m_it.primitive_iterator = primitive_iterator_t(); + break; + } + } + } + + /*! + @note The conventional copy constructor and copy assignment are implicitly + defined. Combined with the following converting constructor and + assignment, they support: (1) copy from iterator to iterator, (2) + copy from const iterator to const iterator, and (3) conversion from + iterator to const iterator. However conversion from const iterator + to iterator is not defined. + */ + + /*! + @brief const copy constructor + @param[in] other const iterator to copy from + @note This copy constructor had to be defined explicitly to circumvent a bug + occurring on msvc v19.0 compiler (VS 2015) debug build. For more + information refer to: https://github.com/nlohmann/json/issues/1608 + */ + iter_impl(const iter_impl& other) noexcept + : m_object(other.m_object), m_it(other.m_it) + {} + + /*! + @brief converting assignment + @param[in] other const iterator to copy from + @return const/non-const iterator + @note It is not checked whether @a other is initialized. + */ + iter_impl& operator=(const iter_impl& other) noexcept + { + if (&other != this) + { + m_object = other.m_object; + m_it = other.m_it; + } + return *this; + } + + /*! + @brief converting constructor + @param[in] other non-const iterator to copy from + @note It is not checked whether @a other is initialized. + */ + iter_impl(const iter_impl::type>& other) noexcept + : m_object(other.m_object), m_it(other.m_it) + {} + + /*! + @brief converting assignment + @param[in] other non-const iterator to copy from + @return const/non-const iterator + @note It is not checked whether @a other is initialized. + */ + iter_impl& operator=(const iter_impl::type>& other) noexcept // NOLINT(cert-oop54-cpp) + { + m_object = other.m_object; + m_it = other.m_it; + return *this; + } + + JSON_PRIVATE_UNLESS_TESTED: + /*! + @brief set the iterator to the first value + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + void set_begin() noexcept + { + JSON_ASSERT(m_object != nullptr); + + switch (m_object->m_type) + { + case value_t::object: + { + m_it.object_iterator = m_object->m_value.object->begin(); + break; + } + + case value_t::array: + { + m_it.array_iterator = m_object->m_value.array->begin(); + break; + } + + case value_t::null: + { + // set to end so begin()==end() is true: null is empty + m_it.primitive_iterator.set_end(); + break; + } + + default: + { + m_it.primitive_iterator.set_begin(); + break; + } + } + } + + /*! + @brief set the iterator past the last value + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + void set_end() noexcept + { + JSON_ASSERT(m_object != nullptr); + + switch (m_object->m_type) + { + case value_t::object: + { + m_it.object_iterator = m_object->m_value.object->end(); + break; + } + + case value_t::array: + { + m_it.array_iterator = m_object->m_value.array->end(); + break; + } + + default: + { + m_it.primitive_iterator.set_end(); + break; + } + } + } + + public: + /*! + @brief return a reference to the value pointed to by the iterator + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + reference operator*() const + { + JSON_ASSERT(m_object != nullptr); + + switch (m_object->m_type) + { + case value_t::object: + { + JSON_ASSERT(m_it.object_iterator != m_object->m_value.object->end()); + return m_it.object_iterator->second; + } + + case value_t::array: + { + JSON_ASSERT(m_it.array_iterator != m_object->m_value.array->end()); + return *m_it.array_iterator; + } + + case value_t::null: + JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object)); + + default: + { + if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.is_begin())) + { + return *m_object; + } + + JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object)); + } + } + } + + /*! + @brief dereference the iterator + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + pointer operator->() const + { + JSON_ASSERT(m_object != nullptr); + + switch (m_object->m_type) + { + case value_t::object: + { + JSON_ASSERT(m_it.object_iterator != m_object->m_value.object->end()); + return &(m_it.object_iterator->second); + } + + case value_t::array: + { + JSON_ASSERT(m_it.array_iterator != m_object->m_value.array->end()); + return &*m_it.array_iterator; + } + + default: + { + if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.is_begin())) + { + return m_object; + } + + JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object)); + } + } + } + + /*! + @brief post-increment (it++) + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + iter_impl const operator++(int) // NOLINT(readability-const-return-type) + { + auto result = *this; + ++(*this); + return result; + } + + /*! + @brief pre-increment (++it) + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + iter_impl& operator++() + { + JSON_ASSERT(m_object != nullptr); + + switch (m_object->m_type) + { + case value_t::object: + { + std::advance(m_it.object_iterator, 1); + break; + } + + case value_t::array: + { + std::advance(m_it.array_iterator, 1); + break; + } + + default: + { + ++m_it.primitive_iterator; + break; + } + } + + return *this; + } + + /*! + @brief post-decrement (it--) + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + iter_impl const operator--(int) // NOLINT(readability-const-return-type) + { + auto result = *this; + --(*this); + return result; + } + + /*! + @brief pre-decrement (--it) + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + iter_impl& operator--() + { + JSON_ASSERT(m_object != nullptr); + + switch (m_object->m_type) + { + case value_t::object: + { + std::advance(m_it.object_iterator, -1); + break; + } + + case value_t::array: + { + std::advance(m_it.array_iterator, -1); + break; + } + + default: + { + --m_it.primitive_iterator; + break; + } + } + + return *this; + } + + /*! + @brief comparison: equal + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + template < typename IterImpl, detail::enable_if_t < (std::is_same::value || std::is_same::value), std::nullptr_t > = nullptr > + bool operator==(const IterImpl& other) const + { + // if objects are not the same, the comparison is undefined + if (JSON_HEDLEY_UNLIKELY(m_object != other.m_object)) + { + JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers", *m_object)); + } + + JSON_ASSERT(m_object != nullptr); + + switch (m_object->m_type) + { + case value_t::object: + return (m_it.object_iterator == other.m_it.object_iterator); + + case value_t::array: + return (m_it.array_iterator == other.m_it.array_iterator); + + default: + return (m_it.primitive_iterator == other.m_it.primitive_iterator); + } + } + + /*! + @brief comparison: not equal + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + template < typename IterImpl, detail::enable_if_t < (std::is_same::value || std::is_same::value), std::nullptr_t > = nullptr > + bool operator!=(const IterImpl& other) const + { + return !operator==(other); + } + + /*! + @brief comparison: smaller + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + bool operator<(const iter_impl& other) const + { + // if objects are not the same, the comparison is undefined + if (JSON_HEDLEY_UNLIKELY(m_object != other.m_object)) + { + JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers", *m_object)); + } + + JSON_ASSERT(m_object != nullptr); + + switch (m_object->m_type) + { + case value_t::object: + JSON_THROW(invalid_iterator::create(213, "cannot compare order of object iterators", *m_object)); + + case value_t::array: + return (m_it.array_iterator < other.m_it.array_iterator); + + default: + return (m_it.primitive_iterator < other.m_it.primitive_iterator); + } + } + + /*! + @brief comparison: less than or equal + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + bool operator<=(const iter_impl& other) const + { + return !other.operator < (*this); + } + + /*! + @brief comparison: greater than + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + bool operator>(const iter_impl& other) const + { + return !operator<=(other); + } + + /*! + @brief comparison: greater than or equal + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + bool operator>=(const iter_impl& other) const + { + return !operator<(other); + } + + /*! + @brief add to iterator + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + iter_impl& operator+=(difference_type i) + { + JSON_ASSERT(m_object != nullptr); + + switch (m_object->m_type) + { + case value_t::object: + JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators", *m_object)); + + case value_t::array: + { + std::advance(m_it.array_iterator, i); + break; + } + + default: + { + m_it.primitive_iterator += i; + break; + } + } + + return *this; + } + + /*! + @brief subtract from iterator + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + iter_impl& operator-=(difference_type i) + { + return operator+=(-i); + } + + /*! + @brief add to iterator + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + iter_impl operator+(difference_type i) const + { + auto result = *this; + result += i; + return result; + } + + /*! + @brief addition of distance and iterator + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + friend iter_impl operator+(difference_type i, const iter_impl& it) + { + auto result = it; + result += i; + return result; + } + + /*! + @brief subtract from iterator + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + iter_impl operator-(difference_type i) const + { + auto result = *this; + result -= i; + return result; + } + + /*! + @brief return difference + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + difference_type operator-(const iter_impl& other) const + { + JSON_ASSERT(m_object != nullptr); + + switch (m_object->m_type) + { + case value_t::object: + JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators", *m_object)); + + case value_t::array: + return m_it.array_iterator - other.m_it.array_iterator; + + default: + return m_it.primitive_iterator - other.m_it.primitive_iterator; + } + } + + /*! + @brief access to successor + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + reference operator[](difference_type n) const + { + JSON_ASSERT(m_object != nullptr); + + switch (m_object->m_type) + { + case value_t::object: + JSON_THROW(invalid_iterator::create(208, "cannot use operator[] for object iterators", *m_object)); + + case value_t::array: + return *std::next(m_it.array_iterator, n); + + case value_t::null: + JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object)); + + default: + { + if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.get_value() == -n)) + { + return *m_object; + } + + JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object)); + } + } + } + + /*! + @brief return the key of an object iterator + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + const typename object_t::key_type& key() const + { + JSON_ASSERT(m_object != nullptr); + + if (JSON_HEDLEY_LIKELY(m_object->is_object())) + { + return m_it.object_iterator->first; + } + + JSON_THROW(invalid_iterator::create(207, "cannot use key() for non-object iterators", *m_object)); + } + + /*! + @brief return the value of an iterator + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + reference value() const + { + return operator*(); + } + + JSON_PRIVATE_UNLESS_TESTED: + /// associated JSON instance + pointer m_object = nullptr; + /// the actual iterator of the associated instance + internal_iterator::type> m_it {}; +}; +} // namespace detail +} // namespace nlohmann + +// #include + +// #include + + +#include // ptrdiff_t +#include // reverse_iterator +#include // declval + +namespace nlohmann +{ +namespace detail +{ +////////////////////// +// reverse_iterator // +////////////////////// + +/*! +@brief a template for a reverse iterator class + +@tparam Base the base iterator type to reverse. Valid types are @ref +iterator (to create @ref reverse_iterator) and @ref const_iterator (to +create @ref const_reverse_iterator). + +@requirement The class satisfies the following concept requirements: +- +[BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator): + The iterator that can be moved can be moved in both directions (i.e. + incremented and decremented). +- [OutputIterator](https://en.cppreference.com/w/cpp/named_req/OutputIterator): + It is possible to write to the pointed-to element (only if @a Base is + @ref iterator). + +@since version 1.0.0 +*/ +template +class json_reverse_iterator : public std::reverse_iterator +{ + public: + using difference_type = std::ptrdiff_t; + /// shortcut to the reverse iterator adapter + using base_iterator = std::reverse_iterator; + /// the reference type for the pointed-to element + using reference = typename Base::reference; + + /// create reverse iterator from iterator + explicit json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept + : base_iterator(it) {} + + /// create reverse iterator from base class + explicit json_reverse_iterator(const base_iterator& it) noexcept : base_iterator(it) {} + + /// post-increment (it++) + json_reverse_iterator const operator++(int) // NOLINT(readability-const-return-type) + { + return static_cast(base_iterator::operator++(1)); + } + + /// pre-increment (++it) + json_reverse_iterator& operator++() + { + return static_cast(base_iterator::operator++()); + } + + /// post-decrement (it--) + json_reverse_iterator const operator--(int) // NOLINT(readability-const-return-type) + { + return static_cast(base_iterator::operator--(1)); + } + + /// pre-decrement (--it) + json_reverse_iterator& operator--() + { + return static_cast(base_iterator::operator--()); + } + + /// add to iterator + json_reverse_iterator& operator+=(difference_type i) + { + return static_cast(base_iterator::operator+=(i)); + } + + /// add to iterator + json_reverse_iterator operator+(difference_type i) const + { + return static_cast(base_iterator::operator+(i)); + } + + /// subtract from iterator + json_reverse_iterator operator-(difference_type i) const + { + return static_cast(base_iterator::operator-(i)); + } + + /// return difference + difference_type operator-(const json_reverse_iterator& other) const + { + return base_iterator(*this) - base_iterator(other); + } + + /// access to successor + reference operator[](difference_type n) const + { + return *(this->operator+(n)); + } + + /// return the key of an object iterator + auto key() const -> decltype(std::declval().key()) + { + auto it = --this->base(); + return it.key(); + } + + /// return the value of an iterator + reference value() const + { + auto it = --this->base(); + return it.operator * (); + } +}; +} // namespace detail +} // namespace nlohmann + +// #include + +// #include + + +#include // all_of +#include // isdigit +#include // max +#include // accumulate +#include // string +#include // move +#include // vector + +// #include + +// #include + +// #include + +// #include + + +namespace nlohmann +{ +template +class json_pointer +{ + // allow basic_json to access private members + NLOHMANN_BASIC_JSON_TPL_DECLARATION + friend class basic_json; + + public: + /*! + @brief create JSON pointer + + Create a JSON pointer according to the syntax described in + [Section 3 of RFC6901](https://tools.ietf.org/html/rfc6901#section-3). + + @param[in] s string representing the JSON pointer; if omitted, the empty + string is assumed which references the whole JSON value + + @throw parse_error.107 if the given JSON pointer @a s is nonempty and does + not begin with a slash (`/`); see example below + + @throw parse_error.108 if a tilde (`~`) in the given JSON pointer @a s is + not followed by `0` (representing `~`) or `1` (representing `/`); see + example below + + @liveexample{The example shows the construction several valid JSON pointers + as well as the exceptional behavior.,json_pointer} + + @since version 2.0.0 + */ + explicit json_pointer(const std::string& s = "") + : reference_tokens(split(s)) + {} + + /*! + @brief return a string representation of the JSON pointer + + @invariant For each JSON pointer `ptr`, it holds: + @code {.cpp} + ptr == json_pointer(ptr.to_string()); + @endcode + + @return a string representation of the JSON pointer + + @liveexample{The example shows the result of `to_string`.,json_pointer__to_string} + + @since version 2.0.0 + */ + std::string to_string() const + { + return std::accumulate(reference_tokens.begin(), reference_tokens.end(), + std::string{}, + [](const std::string & a, const std::string & b) + { + return a + "/" + detail::escape(b); + }); + } + + /// @copydoc to_string() + operator std::string() const + { + return to_string(); + } + + /*! + @brief append another JSON pointer at the end of this JSON pointer + + @param[in] ptr JSON pointer to append + @return JSON pointer with @a ptr appended + + @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add} + + @complexity Linear in the length of @a ptr. + + @sa see @ref operator/=(std::string) to append a reference token + @sa see @ref operator/=(std::size_t) to append an array index + @sa see @ref operator/(const json_pointer&, const json_pointer&) for a binary operator + + @since version 3.6.0 + */ + json_pointer& operator/=(const json_pointer& ptr) + { + reference_tokens.insert(reference_tokens.end(), + ptr.reference_tokens.begin(), + ptr.reference_tokens.end()); + return *this; + } + + /*! + @brief append an unescaped reference token at the end of this JSON pointer + + @param[in] token reference token to append + @return JSON pointer with @a token appended without escaping @a token + + @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add} + + @complexity Amortized constant. + + @sa see @ref operator/=(const json_pointer&) to append a JSON pointer + @sa see @ref operator/=(std::size_t) to append an array index + @sa see @ref operator/(const json_pointer&, std::size_t) for a binary operator + + @since version 3.6.0 + */ + json_pointer& operator/=(std::string token) + { + push_back(std::move(token)); + return *this; + } + + /*! + @brief append an array index at the end of this JSON pointer + + @param[in] array_idx array index to append + @return JSON pointer with @a array_idx appended + + @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add} + + @complexity Amortized constant. + + @sa see @ref operator/=(const json_pointer&) to append a JSON pointer + @sa see @ref operator/=(std::string) to append a reference token + @sa see @ref operator/(const json_pointer&, std::string) for a binary operator + + @since version 3.6.0 + */ + json_pointer& operator/=(std::size_t array_idx) + { + return *this /= std::to_string(array_idx); + } + + /*! + @brief create a new JSON pointer by appending the right JSON pointer at the end of the left JSON pointer + + @param[in] lhs JSON pointer + @param[in] rhs JSON pointer + @return a new JSON pointer with @a rhs appended to @a lhs + + @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary} + + @complexity Linear in the length of @a lhs and @a rhs. + + @sa see @ref operator/=(const json_pointer&) to append a JSON pointer + + @since version 3.6.0 + */ + friend json_pointer operator/(const json_pointer& lhs, + const json_pointer& rhs) + { + return json_pointer(lhs) /= rhs; + } + + /*! + @brief create a new JSON pointer by appending the unescaped token at the end of the JSON pointer + + @param[in] ptr JSON pointer + @param[in] token reference token + @return a new JSON pointer with unescaped @a token appended to @a ptr + + @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary} + + @complexity Linear in the length of @a ptr. + + @sa see @ref operator/=(std::string) to append a reference token + + @since version 3.6.0 + */ + friend json_pointer operator/(const json_pointer& ptr, std::string token) // NOLINT(performance-unnecessary-value-param) + { + return json_pointer(ptr) /= std::move(token); + } + + /*! + @brief create a new JSON pointer by appending the array-index-token at the end of the JSON pointer + + @param[in] ptr JSON pointer + @param[in] array_idx array index + @return a new JSON pointer with @a array_idx appended to @a ptr + + @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary} + + @complexity Linear in the length of @a ptr. + + @sa see @ref operator/=(std::size_t) to append an array index + + @since version 3.6.0 + */ + friend json_pointer operator/(const json_pointer& ptr, std::size_t array_idx) + { + return json_pointer(ptr) /= array_idx; + } + + /*! + @brief returns the parent of this JSON pointer + + @return parent of this JSON pointer; in case this JSON pointer is the root, + the root itself is returned + + @complexity Linear in the length of the JSON pointer. + + @liveexample{The example shows the result of `parent_pointer` for different + JSON Pointers.,json_pointer__parent_pointer} + + @since version 3.6.0 + */ + json_pointer parent_pointer() const + { + if (empty()) + { + return *this; + } + + json_pointer res = *this; + res.pop_back(); + return res; + } + + /*! + @brief remove last reference token + + @pre not `empty()` + + @liveexample{The example shows the usage of `pop_back`.,json_pointer__pop_back} + + @complexity Constant. + + @throw out_of_range.405 if JSON pointer has no parent + + @since version 3.6.0 + */ + void pop_back() + { + if (JSON_HEDLEY_UNLIKELY(empty())) + { + JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent", BasicJsonType())); + } + + reference_tokens.pop_back(); + } + + /*! + @brief return last reference token + + @pre not `empty()` + @return last reference token + + @liveexample{The example shows the usage of `back`.,json_pointer__back} + + @complexity Constant. + + @throw out_of_range.405 if JSON pointer has no parent + + @since version 3.6.0 + */ + const std::string& back() const + { + if (JSON_HEDLEY_UNLIKELY(empty())) + { + JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent", BasicJsonType())); + } + + return reference_tokens.back(); + } + + /*! + @brief append an unescaped token at the end of the reference pointer + + @param[in] token token to add + + @complexity Amortized constant. + + @liveexample{The example shows the result of `push_back` for different + JSON Pointers.,json_pointer__push_back} + + @since version 3.6.0 + */ + void push_back(const std::string& token) + { + reference_tokens.push_back(token); + } + + /// @copydoc push_back(const std::string&) + void push_back(std::string&& token) + { + reference_tokens.push_back(std::move(token)); + } + + /*! + @brief return whether pointer points to the root document + + @return true iff the JSON pointer points to the root document + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this function never throws exceptions. + + @liveexample{The example shows the result of `empty` for different JSON + Pointers.,json_pointer__empty} + + @since version 3.6.0 + */ + bool empty() const noexcept + { + return reference_tokens.empty(); + } + + private: + /*! + @param[in] s reference token to be converted into an array index + + @return integer representation of @a s + + @throw parse_error.106 if an array index begins with '0' + @throw parse_error.109 if an array index begins not with a digit + @throw out_of_range.404 if string @a s could not be converted to an integer + @throw out_of_range.410 if an array index exceeds size_type + */ + static typename BasicJsonType::size_type array_index(const std::string& s) + { + using size_type = typename BasicJsonType::size_type; + + // error condition (cf. RFC 6901, Sect. 4) + if (JSON_HEDLEY_UNLIKELY(s.size() > 1 && s[0] == '0')) + { + JSON_THROW(detail::parse_error::create(106, 0, "array index '" + s + "' must not begin with '0'", BasicJsonType())); + } + + // error condition (cf. RFC 6901, Sect. 4) + if (JSON_HEDLEY_UNLIKELY(s.size() > 1 && !(s[0] >= '1' && s[0] <= '9'))) + { + JSON_THROW(detail::parse_error::create(109, 0, "array index '" + s + "' is not a number", BasicJsonType())); + } + + std::size_t processed_chars = 0; + unsigned long long res = 0; // NOLINT(runtime/int) + JSON_TRY + { + res = std::stoull(s, &processed_chars); + } + JSON_CATCH(std::out_of_range&) + { + JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + s + "'", BasicJsonType())); + } + + // check if the string was completely read + if (JSON_HEDLEY_UNLIKELY(processed_chars != s.size())) + { + JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + s + "'", BasicJsonType())); + } + + // only triggered on special platforms (like 32bit), see also + // https://github.com/nlohmann/json/pull/2203 + if (res >= static_cast((std::numeric_limits::max)())) // NOLINT(runtime/int) + { + JSON_THROW(detail::out_of_range::create(410, "array index " + s + " exceeds size_type", BasicJsonType())); // LCOV_EXCL_LINE + } + + return static_cast(res); + } + + JSON_PRIVATE_UNLESS_TESTED: + json_pointer top() const + { + if (JSON_HEDLEY_UNLIKELY(empty())) + { + JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent", BasicJsonType())); + } + + json_pointer result = *this; + result.reference_tokens = {reference_tokens[0]}; + return result; + } + + private: + /*! + @brief create and return a reference to the pointed to value + + @complexity Linear in the number of reference tokens. + + @throw parse_error.109 if array index is not a number + @throw type_error.313 if value cannot be unflattened + */ + BasicJsonType& get_and_create(BasicJsonType& j) const + { + auto* result = &j; + + // in case no reference tokens exist, return a reference to the JSON value + // j which will be overwritten by a primitive value + for (const auto& reference_token : reference_tokens) + { + switch (result->type()) + { + case detail::value_t::null: + { + if (reference_token == "0") + { + // start a new array if reference token is 0 + result = &result->operator[](0); + } + else + { + // start a new object otherwise + result = &result->operator[](reference_token); + } + break; + } + + case detail::value_t::object: + { + // create an entry in the object + result = &result->operator[](reference_token); + break; + } + + case detail::value_t::array: + { + // create an entry in the array + result = &result->operator[](array_index(reference_token)); + break; + } + + /* + The following code is only reached if there exists a reference + token _and_ the current value is primitive. In this case, we have + an error situation, because primitive values may only occur as + single value; that is, with an empty list of reference tokens. + */ + default: + JSON_THROW(detail::type_error::create(313, "invalid value to unflatten", j)); + } + } + + return *result; + } + + /*! + @brief return a reference to the pointed to value + + @note This version does not throw if a value is not present, but tries to + create nested values instead. For instance, calling this function + with pointer `"/this/that"` on a null value is equivalent to calling + `operator[]("this").operator[]("that")` on that value, effectively + changing the null value to an object. + + @param[in] ptr a JSON value + + @return reference to the JSON value pointed to by the JSON pointer + + @complexity Linear in the length of the JSON pointer. + + @throw parse_error.106 if an array index begins with '0' + @throw parse_error.109 if an array index was not a number + @throw out_of_range.404 if the JSON pointer can not be resolved + */ + BasicJsonType& get_unchecked(BasicJsonType* ptr) const + { + for (const auto& reference_token : reference_tokens) + { + // convert null values to arrays or objects before continuing + if (ptr->is_null()) + { + // check if reference token is a number + const bool nums = + std::all_of(reference_token.begin(), reference_token.end(), + [](const unsigned char x) + { + return std::isdigit(x); + }); + + // change value to array for numbers or "-" or to object otherwise + *ptr = (nums || reference_token == "-") + ? detail::value_t::array + : detail::value_t::object; + } + + switch (ptr->type()) + { + case detail::value_t::object: + { + // use unchecked object access + ptr = &ptr->operator[](reference_token); + break; + } + + case detail::value_t::array: + { + if (reference_token == "-") + { + // explicitly treat "-" as index beyond the end + ptr = &ptr->operator[](ptr->m_value.array->size()); + } + else + { + // convert array index to number; unchecked access + ptr = &ptr->operator[](array_index(reference_token)); + } + break; + } + + default: + JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'", *ptr)); + } + } + + return *ptr; + } + + /*! + @throw parse_error.106 if an array index begins with '0' + @throw parse_error.109 if an array index was not a number + @throw out_of_range.402 if the array index '-' is used + @throw out_of_range.404 if the JSON pointer can not be resolved + */ + BasicJsonType& get_checked(BasicJsonType* ptr) const + { + for (const auto& reference_token : reference_tokens) + { + switch (ptr->type()) + { + case detail::value_t::object: + { + // note: at performs range check + ptr = &ptr->at(reference_token); + break; + } + + case detail::value_t::array: + { + if (JSON_HEDLEY_UNLIKELY(reference_token == "-")) + { + // "-" always fails the range check + JSON_THROW(detail::out_of_range::create(402, + "array index '-' (" + std::to_string(ptr->m_value.array->size()) + + ") is out of range", *ptr)); + } + + // note: at performs range check + ptr = &ptr->at(array_index(reference_token)); + break; + } + + default: + JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'", *ptr)); + } + } + + return *ptr; + } + + /*! + @brief return a const reference to the pointed to value + + @param[in] ptr a JSON value + + @return const reference to the JSON value pointed to by the JSON + pointer + + @throw parse_error.106 if an array index begins with '0' + @throw parse_error.109 if an array index was not a number + @throw out_of_range.402 if the array index '-' is used + @throw out_of_range.404 if the JSON pointer can not be resolved + */ + const BasicJsonType& get_unchecked(const BasicJsonType* ptr) const + { + for (const auto& reference_token : reference_tokens) + { + switch (ptr->type()) + { + case detail::value_t::object: + { + // use unchecked object access + ptr = &ptr->operator[](reference_token); + break; + } + + case detail::value_t::array: + { + if (JSON_HEDLEY_UNLIKELY(reference_token == "-")) + { + // "-" cannot be used for const access + JSON_THROW(detail::out_of_range::create(402, "array index '-' (" + std::to_string(ptr->m_value.array->size()) + ") is out of range", *ptr)); + } + + // use unchecked array access + ptr = &ptr->operator[](array_index(reference_token)); + break; + } + + default: + JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'", *ptr)); + } + } + + return *ptr; + } + + /*! + @throw parse_error.106 if an array index begins with '0' + @throw parse_error.109 if an array index was not a number + @throw out_of_range.402 if the array index '-' is used + @throw out_of_range.404 if the JSON pointer can not be resolved + */ + const BasicJsonType& get_checked(const BasicJsonType* ptr) const + { + for (const auto& reference_token : reference_tokens) + { + switch (ptr->type()) + { + case detail::value_t::object: + { + // note: at performs range check + ptr = &ptr->at(reference_token); + break; + } + + case detail::value_t::array: + { + if (JSON_HEDLEY_UNLIKELY(reference_token == "-")) + { + // "-" always fails the range check + JSON_THROW(detail::out_of_range::create(402, + "array index '-' (" + std::to_string(ptr->m_value.array->size()) + + ") is out of range", *ptr)); + } + + // note: at performs range check + ptr = &ptr->at(array_index(reference_token)); + break; + } + + default: + JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'", *ptr)); + } + } + + return *ptr; + } + + /*! + @throw parse_error.106 if an array index begins with '0' + @throw parse_error.109 if an array index was not a number + */ + bool contains(const BasicJsonType* ptr) const + { + for (const auto& reference_token : reference_tokens) + { + switch (ptr->type()) + { + case detail::value_t::object: + { + if (!ptr->contains(reference_token)) + { + // we did not find the key in the object + return false; + } + + ptr = &ptr->operator[](reference_token); + break; + } + + case detail::value_t::array: + { + if (JSON_HEDLEY_UNLIKELY(reference_token == "-")) + { + // "-" always fails the range check + return false; + } + if (JSON_HEDLEY_UNLIKELY(reference_token.size() == 1 && !("0" <= reference_token && reference_token <= "9"))) + { + // invalid char + return false; + } + if (JSON_HEDLEY_UNLIKELY(reference_token.size() > 1)) + { + if (JSON_HEDLEY_UNLIKELY(!('1' <= reference_token[0] && reference_token[0] <= '9'))) + { + // first char should be between '1' and '9' + return false; + } + for (std::size_t i = 1; i < reference_token.size(); i++) + { + if (JSON_HEDLEY_UNLIKELY(!('0' <= reference_token[i] && reference_token[i] <= '9'))) + { + // other char should be between '0' and '9' + return false; + } + } + } + + const auto idx = array_index(reference_token); + if (idx >= ptr->size()) + { + // index out of range + return false; + } + + ptr = &ptr->operator[](idx); + break; + } + + default: + { + // we do not expect primitive values if there is still a + // reference token to process + return false; + } + } + } + + // no reference token left means we found a primitive value + return true; + } + + /*! + @brief split the string input to reference tokens + + @note This function is only called by the json_pointer constructor. + All exceptions below are documented there. + + @throw parse_error.107 if the pointer is not empty or begins with '/' + @throw parse_error.108 if character '~' is not followed by '0' or '1' + */ + static std::vector split(const std::string& reference_string) + { + std::vector result; + + // special case: empty reference string -> no reference tokens + if (reference_string.empty()) + { + return result; + } + + // check if nonempty reference string begins with slash + if (JSON_HEDLEY_UNLIKELY(reference_string[0] != '/')) + { + JSON_THROW(detail::parse_error::create(107, 1, "JSON pointer must be empty or begin with '/' - was: '" + reference_string + "'", BasicJsonType())); + } + + // extract the reference tokens: + // - slash: position of the last read slash (or end of string) + // - start: position after the previous slash + for ( + // search for the first slash after the first character + std::size_t slash = reference_string.find_first_of('/', 1), + // set the beginning of the first reference token + start = 1; + // we can stop if start == 0 (if slash == std::string::npos) + start != 0; + // set the beginning of the next reference token + // (will eventually be 0 if slash == std::string::npos) + start = (slash == std::string::npos) ? 0 : slash + 1, + // find next slash + slash = reference_string.find_first_of('/', start)) + { + // use the text between the beginning of the reference token + // (start) and the last slash (slash). + auto reference_token = reference_string.substr(start, slash - start); + + // check reference tokens are properly escaped + for (std::size_t pos = reference_token.find_first_of('~'); + pos != std::string::npos; + pos = reference_token.find_first_of('~', pos + 1)) + { + JSON_ASSERT(reference_token[pos] == '~'); + + // ~ must be followed by 0 or 1 + if (JSON_HEDLEY_UNLIKELY(pos == reference_token.size() - 1 || + (reference_token[pos + 1] != '0' && + reference_token[pos + 1] != '1'))) + { + JSON_THROW(detail::parse_error::create(108, 0, "escape character '~' must be followed with '0' or '1'", BasicJsonType())); + } + } + + // finally, store the reference token + detail::unescape(reference_token); + result.push_back(reference_token); + } + + return result; + } + + private: + /*! + @param[in] reference_string the reference string to the current value + @param[in] value the value to consider + @param[in,out] result the result object to insert values to + + @note Empty objects or arrays are flattened to `null`. + */ + static void flatten(const std::string& reference_string, + const BasicJsonType& value, + BasicJsonType& result) + { + switch (value.type()) + { + case detail::value_t::array: + { + if (value.m_value.array->empty()) + { + // flatten empty array as null + result[reference_string] = nullptr; + } + else + { + // iterate array and use index as reference string + for (std::size_t i = 0; i < value.m_value.array->size(); ++i) + { + flatten(reference_string + "/" + std::to_string(i), + value.m_value.array->operator[](i), result); + } + } + break; + } + + case detail::value_t::object: + { + if (value.m_value.object->empty()) + { + // flatten empty object as null + result[reference_string] = nullptr; + } + else + { + // iterate object and use keys as reference string + for (const auto& element : *value.m_value.object) + { + flatten(reference_string + "/" + detail::escape(element.first), element.second, result); + } + } + break; + } + + default: + { + // add primitive value with its reference string + result[reference_string] = value; + break; + } + } + } + + /*! + @param[in] value flattened JSON + + @return unflattened JSON + + @throw parse_error.109 if array index is not a number + @throw type_error.314 if value is not an object + @throw type_error.315 if object values are not primitive + @throw type_error.313 if value cannot be unflattened + */ + static BasicJsonType + unflatten(const BasicJsonType& value) + { + if (JSON_HEDLEY_UNLIKELY(!value.is_object())) + { + JSON_THROW(detail::type_error::create(314, "only objects can be unflattened", value)); + } + + BasicJsonType result; + + // iterate the JSON object values + for (const auto& element : *value.m_value.object) + { + if (JSON_HEDLEY_UNLIKELY(!element.second.is_primitive())) + { + JSON_THROW(detail::type_error::create(315, "values in object must be primitive", element.second)); + } + + // assign value to reference pointed to by JSON pointer; Note that if + // the JSON pointer is "" (i.e., points to the whole value), function + // get_and_create returns a reference to result itself. An assignment + // will then create a primitive value. + json_pointer(element.first).get_and_create(result) = element.second; + } + + return result; + } + + /*! + @brief compares two JSON pointers for equality + + @param[in] lhs JSON pointer to compare + @param[in] rhs JSON pointer to compare + @return whether @a lhs is equal to @a rhs + + @complexity Linear in the length of the JSON pointer + + @exceptionsafety No-throw guarantee: this function never throws exceptions. + */ + friend bool operator==(json_pointer const& lhs, + json_pointer const& rhs) noexcept + { + return lhs.reference_tokens == rhs.reference_tokens; + } + + /*! + @brief compares two JSON pointers for inequality + + @param[in] lhs JSON pointer to compare + @param[in] rhs JSON pointer to compare + @return whether @a lhs is not equal @a rhs + + @complexity Linear in the length of the JSON pointer + + @exceptionsafety No-throw guarantee: this function never throws exceptions. + */ + friend bool operator!=(json_pointer const& lhs, + json_pointer const& rhs) noexcept + { + return !(lhs == rhs); + } + + /// the reference tokens + std::vector reference_tokens; +}; +} // namespace nlohmann + +// #include + + +#include +#include + +// #include + + +namespace nlohmann +{ +namespace detail +{ +template +class json_ref +{ + public: + using value_type = BasicJsonType; + + json_ref(value_type&& value) + : owned_value(std::move(value)) + {} + + json_ref(const value_type& value) + : value_ref(&value) + {} + + json_ref(std::initializer_list init) + : owned_value(init) + {} + + template < + class... Args, + enable_if_t::value, int> = 0 > + json_ref(Args && ... args) + : owned_value(std::forward(args)...) + {} + + // class should be movable only + json_ref(json_ref&&) noexcept = default; + json_ref(const json_ref&) = delete; + json_ref& operator=(const json_ref&) = delete; + json_ref& operator=(json_ref&&) = delete; + ~json_ref() = default; + + value_type moved_or_copied() const + { + if (value_ref == nullptr) + { + return std::move(owned_value); + } + return *value_ref; + } + + value_type const& operator*() const + { + return value_ref ? *value_ref : owned_value; + } + + value_type const* operator->() const + { + return &** this; + } + + private: + mutable value_type owned_value = nullptr; + value_type const* value_ref = nullptr; +}; +} // namespace detail +} // namespace nlohmann + +// #include + +// #include + +// #include + +// #include + +// #include + + +#include // reverse +#include // array +#include // isnan, isinf +#include // uint8_t, uint16_t, uint32_t, uint64_t +#include // memcpy +#include // numeric_limits +#include // string +#include // move + +// #include + +// #include + +// #include + + +#include // copy +#include // size_t +#include // streamsize +#include // back_inserter +#include // shared_ptr, make_shared +#include // basic_ostream +#include // basic_string +#include // vector +// #include + + +namespace nlohmann +{ +namespace detail +{ +/// abstract output adapter interface +template struct output_adapter_protocol +{ + virtual void write_character(CharType c) = 0; + virtual void write_characters(const CharType* s, std::size_t length) = 0; + virtual ~output_adapter_protocol() = default; + + output_adapter_protocol() = default; + output_adapter_protocol(const output_adapter_protocol&) = default; + output_adapter_protocol(output_adapter_protocol&&) noexcept = default; + output_adapter_protocol& operator=(const output_adapter_protocol&) = default; + output_adapter_protocol& operator=(output_adapter_protocol&&) noexcept = default; +}; + +/// a type to simplify interfaces +template +using output_adapter_t = std::shared_ptr>; + +/// output adapter for byte vectors +template +class output_vector_adapter : public output_adapter_protocol +{ + public: + explicit output_vector_adapter(std::vector& vec) noexcept + : v(vec) + {} + + void write_character(CharType c) override + { + v.push_back(c); + } + + JSON_HEDLEY_NON_NULL(2) + void write_characters(const CharType* s, std::size_t length) override + { + std::copy(s, s + length, std::back_inserter(v)); + } + + private: + std::vector& v; +}; + +/// output adapter for output streams +template +class output_stream_adapter : public output_adapter_protocol +{ + public: + explicit output_stream_adapter(std::basic_ostream& s) noexcept + : stream(s) + {} + + void write_character(CharType c) override + { + stream.put(c); + } + + JSON_HEDLEY_NON_NULL(2) + void write_characters(const CharType* s, std::size_t length) override + { + stream.write(s, static_cast(length)); + } + + private: + std::basic_ostream& stream; +}; + +/// output adapter for basic_string +template> +class output_string_adapter : public output_adapter_protocol +{ + public: + explicit output_string_adapter(StringType& s) noexcept + : str(s) + {} + + void write_character(CharType c) override + { + str.push_back(c); + } + + JSON_HEDLEY_NON_NULL(2) + void write_characters(const CharType* s, std::size_t length) override + { + str.append(s, length); + } + + private: + StringType& str; +}; + +template> +class output_adapter +{ + public: + output_adapter(std::vector& vec) + : oa(std::make_shared>(vec)) {} + + output_adapter(std::basic_ostream& s) + : oa(std::make_shared>(s)) {} + + output_adapter(StringType& s) + : oa(std::make_shared>(s)) {} + + operator output_adapter_t() + { + return oa; + } + + private: + output_adapter_t oa = nullptr; +}; +} // namespace detail +} // namespace nlohmann + + +namespace nlohmann +{ +namespace detail +{ +/////////////////// +// binary writer // +/////////////////// + +/*! +@brief serialization to CBOR and MessagePack values +*/ +template +class binary_writer +{ + using string_t = typename BasicJsonType::string_t; + using binary_t = typename BasicJsonType::binary_t; + using number_float_t = typename BasicJsonType::number_float_t; + + public: + /*! + @brief create a binary writer + + @param[in] adapter output adapter to write to + */ + explicit binary_writer(output_adapter_t adapter) : oa(std::move(adapter)) + { + JSON_ASSERT(oa); + } + + /*! + @param[in] j JSON value to serialize + @pre j.type() == value_t::object + */ + void write_bson(const BasicJsonType& j) + { + switch (j.type()) + { + case value_t::object: + { + write_bson_object(*j.m_value.object); + break; + } + + default: + { + JSON_THROW(type_error::create(317, "to serialize to BSON, top-level type must be object, but is " + std::string(j.type_name()), j));; + } + } + } + + /*! + @param[in] j JSON value to serialize + */ + void write_cbor(const BasicJsonType& j) + { + switch (j.type()) + { + case value_t::null: + { + oa->write_character(to_char_type(0xF6)); + break; + } + + case value_t::boolean: + { + oa->write_character(j.m_value.boolean + ? to_char_type(0xF5) + : to_char_type(0xF4)); + break; + } + + case value_t::number_integer: + { + if (j.m_value.number_integer >= 0) + { + // CBOR does not differentiate between positive signed + // integers and unsigned integers. Therefore, we used the + // code from the value_t::number_unsigned case here. + if (j.m_value.number_integer <= 0x17) + { + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_integer <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x18)); + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_integer <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x19)); + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_integer <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x1A)); + write_number(static_cast(j.m_value.number_integer)); + } + else + { + oa->write_character(to_char_type(0x1B)); + write_number(static_cast(j.m_value.number_integer)); + } + } + else + { + // The conversions below encode the sign in the first + // byte, and the value is converted to a positive number. + const auto positive_number = -1 - j.m_value.number_integer; + if (j.m_value.number_integer >= -24) + { + write_number(static_cast(0x20 + positive_number)); + } + else if (positive_number <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x38)); + write_number(static_cast(positive_number)); + } + else if (positive_number <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x39)); + write_number(static_cast(positive_number)); + } + else if (positive_number <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x3A)); + write_number(static_cast(positive_number)); + } + else + { + oa->write_character(to_char_type(0x3B)); + write_number(static_cast(positive_number)); + } + } + break; + } + + case value_t::number_unsigned: + { + if (j.m_value.number_unsigned <= 0x17) + { + write_number(static_cast(j.m_value.number_unsigned)); + } + else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x18)); + write_number(static_cast(j.m_value.number_unsigned)); + } + else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x19)); + write_number(static_cast(j.m_value.number_unsigned)); + } + else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x1A)); + write_number(static_cast(j.m_value.number_unsigned)); + } + else + { + oa->write_character(to_char_type(0x1B)); + write_number(static_cast(j.m_value.number_unsigned)); + } + break; + } + + case value_t::number_float: + { + if (std::isnan(j.m_value.number_float)) + { + // NaN is 0xf97e00 in CBOR + oa->write_character(to_char_type(0xF9)); + oa->write_character(to_char_type(0x7E)); + oa->write_character(to_char_type(0x00)); + } + else if (std::isinf(j.m_value.number_float)) + { + // Infinity is 0xf97c00, -Infinity is 0xf9fc00 + oa->write_character(to_char_type(0xf9)); + oa->write_character(j.m_value.number_float > 0 ? to_char_type(0x7C) : to_char_type(0xFC)); + oa->write_character(to_char_type(0x00)); + } + else + { + write_compact_float(j.m_value.number_float, detail::input_format_t::cbor); + } + break; + } + + case value_t::string: + { + // step 1: write control byte and the string length + const auto N = j.m_value.string->size(); + if (N <= 0x17) + { + write_number(static_cast(0x60 + N)); + } + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x78)); + write_number(static_cast(N)); + } + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x79)); + write_number(static_cast(N)); + } + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x7A)); + write_number(static_cast(N)); + } + // LCOV_EXCL_START + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x7B)); + write_number(static_cast(N)); + } + // LCOV_EXCL_STOP + + // step 2: write the string + oa->write_characters( + reinterpret_cast(j.m_value.string->c_str()), + j.m_value.string->size()); + break; + } + + case value_t::array: + { + // step 1: write control byte and the array size + const auto N = j.m_value.array->size(); + if (N <= 0x17) + { + write_number(static_cast(0x80 + N)); + } + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x98)); + write_number(static_cast(N)); + } + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x99)); + write_number(static_cast(N)); + } + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x9A)); + write_number(static_cast(N)); + } + // LCOV_EXCL_START + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x9B)); + write_number(static_cast(N)); + } + // LCOV_EXCL_STOP + + // step 2: write each element + for (const auto& el : *j.m_value.array) + { + write_cbor(el); + } + break; + } + + case value_t::binary: + { + if (j.m_value.binary->has_subtype()) + { + write_number(static_cast(0xd8)); + write_number(j.m_value.binary->subtype()); + } + + // step 1: write control byte and the binary array size + const auto N = j.m_value.binary->size(); + if (N <= 0x17) + { + write_number(static_cast(0x40 + N)); + } + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x58)); + write_number(static_cast(N)); + } + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x59)); + write_number(static_cast(N)); + } + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x5A)); + write_number(static_cast(N)); + } + // LCOV_EXCL_START + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x5B)); + write_number(static_cast(N)); + } + // LCOV_EXCL_STOP + + // step 2: write each element + oa->write_characters( + reinterpret_cast(j.m_value.binary->data()), + N); + + break; + } + + case value_t::object: + { + // step 1: write control byte and the object size + const auto N = j.m_value.object->size(); + if (N <= 0x17) + { + write_number(static_cast(0xA0 + N)); + } + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0xB8)); + write_number(static_cast(N)); + } + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0xB9)); + write_number(static_cast(N)); + } + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0xBA)); + write_number(static_cast(N)); + } + // LCOV_EXCL_START + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0xBB)); + write_number(static_cast(N)); + } + // LCOV_EXCL_STOP + + // step 2: write each element + for (const auto& el : *j.m_value.object) + { + write_cbor(el.first); + write_cbor(el.second); + } + break; + } + + default: + break; + } + } + + /*! + @param[in] j JSON value to serialize + */ + void write_msgpack(const BasicJsonType& j) + { + switch (j.type()) + { + case value_t::null: // nil + { + oa->write_character(to_char_type(0xC0)); + break; + } + + case value_t::boolean: // true and false + { + oa->write_character(j.m_value.boolean + ? to_char_type(0xC3) + : to_char_type(0xC2)); + break; + } + + case value_t::number_integer: + { + if (j.m_value.number_integer >= 0) + { + // MessagePack does not differentiate between positive + // signed integers and unsigned integers. Therefore, we used + // the code from the value_t::number_unsigned case here. + if (j.m_value.number_unsigned < 128) + { + // positive fixnum + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) + { + // uint 8 + oa->write_character(to_char_type(0xCC)); + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) + { + // uint 16 + oa->write_character(to_char_type(0xCD)); + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) + { + // uint 32 + oa->write_character(to_char_type(0xCE)); + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) + { + // uint 64 + oa->write_character(to_char_type(0xCF)); + write_number(static_cast(j.m_value.number_integer)); + } + } + else + { + if (j.m_value.number_integer >= -32) + { + // negative fixnum + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_integer >= (std::numeric_limits::min)() && + j.m_value.number_integer <= (std::numeric_limits::max)()) + { + // int 8 + oa->write_character(to_char_type(0xD0)); + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_integer >= (std::numeric_limits::min)() && + j.m_value.number_integer <= (std::numeric_limits::max)()) + { + // int 16 + oa->write_character(to_char_type(0xD1)); + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_integer >= (std::numeric_limits::min)() && + j.m_value.number_integer <= (std::numeric_limits::max)()) + { + // int 32 + oa->write_character(to_char_type(0xD2)); + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_integer >= (std::numeric_limits::min)() && + j.m_value.number_integer <= (std::numeric_limits::max)()) + { + // int 64 + oa->write_character(to_char_type(0xD3)); + write_number(static_cast(j.m_value.number_integer)); + } + } + break; + } + + case value_t::number_unsigned: + { + if (j.m_value.number_unsigned < 128) + { + // positive fixnum + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) + { + // uint 8 + oa->write_character(to_char_type(0xCC)); + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) + { + // uint 16 + oa->write_character(to_char_type(0xCD)); + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) + { + // uint 32 + oa->write_character(to_char_type(0xCE)); + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) + { + // uint 64 + oa->write_character(to_char_type(0xCF)); + write_number(static_cast(j.m_value.number_integer)); + } + break; + } + + case value_t::number_float: + { + write_compact_float(j.m_value.number_float, detail::input_format_t::msgpack); + break; + } + + case value_t::string: + { + // step 1: write control byte and the string length + const auto N = j.m_value.string->size(); + if (N <= 31) + { + // fixstr + write_number(static_cast(0xA0 | N)); + } + else if (N <= (std::numeric_limits::max)()) + { + // str 8 + oa->write_character(to_char_type(0xD9)); + write_number(static_cast(N)); + } + else if (N <= (std::numeric_limits::max)()) + { + // str 16 + oa->write_character(to_char_type(0xDA)); + write_number(static_cast(N)); + } + else if (N <= (std::numeric_limits::max)()) + { + // str 32 + oa->write_character(to_char_type(0xDB)); + write_number(static_cast(N)); + } + + // step 2: write the string + oa->write_characters( + reinterpret_cast(j.m_value.string->c_str()), + j.m_value.string->size()); + break; + } + + case value_t::array: + { + // step 1: write control byte and the array size + const auto N = j.m_value.array->size(); + if (N <= 15) + { + // fixarray + write_number(static_cast(0x90 | N)); + } + else if (N <= (std::numeric_limits::max)()) + { + // array 16 + oa->write_character(to_char_type(0xDC)); + write_number(static_cast(N)); + } + else if (N <= (std::numeric_limits::max)()) + { + // array 32 + oa->write_character(to_char_type(0xDD)); + write_number(static_cast(N)); + } + + // step 2: write each element + for (const auto& el : *j.m_value.array) + { + write_msgpack(el); + } + break; + } + + case value_t::binary: + { + // step 0: determine if the binary type has a set subtype to + // determine whether or not to use the ext or fixext types + const bool use_ext = j.m_value.binary->has_subtype(); + + // step 1: write control byte and the byte string length + const auto N = j.m_value.binary->size(); + if (N <= (std::numeric_limits::max)()) + { + std::uint8_t output_type{}; + bool fixed = true; + if (use_ext) + { + switch (N) + { + case 1: + output_type = 0xD4; // fixext 1 + break; + case 2: + output_type = 0xD5; // fixext 2 + break; + case 4: + output_type = 0xD6; // fixext 4 + break; + case 8: + output_type = 0xD7; // fixext 8 + break; + case 16: + output_type = 0xD8; // fixext 16 + break; + default: + output_type = 0xC7; // ext 8 + fixed = false; + break; + } + + } + else + { + output_type = 0xC4; // bin 8 + fixed = false; + } + + oa->write_character(to_char_type(output_type)); + if (!fixed) + { + write_number(static_cast(N)); + } + } + else if (N <= (std::numeric_limits::max)()) + { + std::uint8_t output_type = use_ext + ? 0xC8 // ext 16 + : 0xC5; // bin 16 + + oa->write_character(to_char_type(output_type)); + write_number(static_cast(N)); + } + else if (N <= (std::numeric_limits::max)()) + { + std::uint8_t output_type = use_ext + ? 0xC9 // ext 32 + : 0xC6; // bin 32 + + oa->write_character(to_char_type(output_type)); + write_number(static_cast(N)); + } + + // step 1.5: if this is an ext type, write the subtype + if (use_ext) + { + write_number(static_cast(j.m_value.binary->subtype())); + } + + // step 2: write the byte string + oa->write_characters( + reinterpret_cast(j.m_value.binary->data()), + N); + + break; + } + + case value_t::object: + { + // step 1: write control byte and the object size + const auto N = j.m_value.object->size(); + if (N <= 15) + { + // fixmap + write_number(static_cast(0x80 | (N & 0xF))); + } + else if (N <= (std::numeric_limits::max)()) + { + // map 16 + oa->write_character(to_char_type(0xDE)); + write_number(static_cast(N)); + } + else if (N <= (std::numeric_limits::max)()) + { + // map 32 + oa->write_character(to_char_type(0xDF)); + write_number(static_cast(N)); + } + + // step 2: write each element + for (const auto& el : *j.m_value.object) + { + write_msgpack(el.first); + write_msgpack(el.second); + } + break; + } + + default: + break; + } + } + + /*! + @param[in] j JSON value to serialize + @param[in] use_count whether to use '#' prefixes (optimized format) + @param[in] use_type whether to use '$' prefixes (optimized format) + @param[in] add_prefix whether prefixes need to be used for this value + */ + void write_ubjson(const BasicJsonType& j, const bool use_count, + const bool use_type, const bool add_prefix = true) + { + switch (j.type()) + { + case value_t::null: + { + if (add_prefix) + { + oa->write_character(to_char_type('Z')); + } + break; + } + + case value_t::boolean: + { + if (add_prefix) + { + oa->write_character(j.m_value.boolean + ? to_char_type('T') + : to_char_type('F')); + } + break; + } + + case value_t::number_integer: + { + write_number_with_ubjson_prefix(j.m_value.number_integer, add_prefix); + break; + } + + case value_t::number_unsigned: + { + write_number_with_ubjson_prefix(j.m_value.number_unsigned, add_prefix); + break; + } + + case value_t::number_float: + { + write_number_with_ubjson_prefix(j.m_value.number_float, add_prefix); + break; + } + + case value_t::string: + { + if (add_prefix) + { + oa->write_character(to_char_type('S')); + } + write_number_with_ubjson_prefix(j.m_value.string->size(), true); + oa->write_characters( + reinterpret_cast(j.m_value.string->c_str()), + j.m_value.string->size()); + break; + } + + case value_t::array: + { + if (add_prefix) + { + oa->write_character(to_char_type('[')); + } + + bool prefix_required = true; + if (use_type && !j.m_value.array->empty()) + { + JSON_ASSERT(use_count); + const CharType first_prefix = ubjson_prefix(j.front()); + const bool same_prefix = std::all_of(j.begin() + 1, j.end(), + [this, first_prefix](const BasicJsonType & v) + { + return ubjson_prefix(v) == first_prefix; + }); + + if (same_prefix) + { + prefix_required = false; + oa->write_character(to_char_type('$')); + oa->write_character(first_prefix); + } + } + + if (use_count) + { + oa->write_character(to_char_type('#')); + write_number_with_ubjson_prefix(j.m_value.array->size(), true); + } + + for (const auto& el : *j.m_value.array) + { + write_ubjson(el, use_count, use_type, prefix_required); + } + + if (!use_count) + { + oa->write_character(to_char_type(']')); + } + + break; + } + + case value_t::binary: + { + if (add_prefix) + { + oa->write_character(to_char_type('[')); + } + + if (use_type && !j.m_value.binary->empty()) + { + JSON_ASSERT(use_count); + oa->write_character(to_char_type('$')); + oa->write_character('U'); + } + + if (use_count) + { + oa->write_character(to_char_type('#')); + write_number_with_ubjson_prefix(j.m_value.binary->size(), true); + } + + if (use_type) + { + oa->write_characters( + reinterpret_cast(j.m_value.binary->data()), + j.m_value.binary->size()); + } + else + { + for (size_t i = 0; i < j.m_value.binary->size(); ++i) + { + oa->write_character(to_char_type('U')); + oa->write_character(j.m_value.binary->data()[i]); + } + } + + if (!use_count) + { + oa->write_character(to_char_type(']')); + } + + break; + } + + case value_t::object: + { + if (add_prefix) + { + oa->write_character(to_char_type('{')); + } + + bool prefix_required = true; + if (use_type && !j.m_value.object->empty()) + { + JSON_ASSERT(use_count); + const CharType first_prefix = ubjson_prefix(j.front()); + const bool same_prefix = std::all_of(j.begin(), j.end(), + [this, first_prefix](const BasicJsonType & v) + { + return ubjson_prefix(v) == first_prefix; + }); + + if (same_prefix) + { + prefix_required = false; + oa->write_character(to_char_type('$')); + oa->write_character(first_prefix); + } + } + + if (use_count) + { + oa->write_character(to_char_type('#')); + write_number_with_ubjson_prefix(j.m_value.object->size(), true); + } + + for (const auto& el : *j.m_value.object) + { + write_number_with_ubjson_prefix(el.first.size(), true); + oa->write_characters( + reinterpret_cast(el.first.c_str()), + el.first.size()); + write_ubjson(el.second, use_count, use_type, prefix_required); + } + + if (!use_count) + { + oa->write_character(to_char_type('}')); + } + + break; + } + + default: + break; + } + } + + private: + ////////// + // BSON // + ////////// + + /*! + @return The size of a BSON document entry header, including the id marker + and the entry name size (and its null-terminator). + */ + static std::size_t calc_bson_entry_header_size(const string_t& name, const BasicJsonType& j) + { + const auto it = name.find(static_cast(0)); + if (JSON_HEDLEY_UNLIKELY(it != BasicJsonType::string_t::npos)) + { + JSON_THROW(out_of_range::create(409, "BSON key cannot contain code point U+0000 (at byte " + std::to_string(it) + ")", j)); + } + + return /*id*/ 1ul + name.size() + /*zero-terminator*/1u; + } + + /*! + @brief Writes the given @a element_type and @a name to the output adapter + */ + void write_bson_entry_header(const string_t& name, + const std::uint8_t element_type) + { + oa->write_character(to_char_type(element_type)); // boolean + oa->write_characters( + reinterpret_cast(name.c_str()), + name.size() + 1u); + } + + /*! + @brief Writes a BSON element with key @a name and boolean value @a value + */ + void write_bson_boolean(const string_t& name, + const bool value) + { + write_bson_entry_header(name, 0x08); + oa->write_character(value ? to_char_type(0x01) : to_char_type(0x00)); + } + + /*! + @brief Writes a BSON element with key @a name and double value @a value + */ + void write_bson_double(const string_t& name, + const double value) + { + write_bson_entry_header(name, 0x01); + write_number(value); + } + + /*! + @return The size of the BSON-encoded string in @a value + */ + static std::size_t calc_bson_string_size(const string_t& value) + { + return sizeof(std::int32_t) + value.size() + 1ul; + } + + /*! + @brief Writes a BSON element with key @a name and string value @a value + */ + void write_bson_string(const string_t& name, + const string_t& value) + { + write_bson_entry_header(name, 0x02); + + write_number(static_cast(value.size() + 1ul)); + oa->write_characters( + reinterpret_cast(value.c_str()), + value.size() + 1); + } + + /*! + @brief Writes a BSON element with key @a name and null value + */ + void write_bson_null(const string_t& name) + { + write_bson_entry_header(name, 0x0A); + } + + /*! + @return The size of the BSON-encoded integer @a value + */ + static std::size_t calc_bson_integer_size(const std::int64_t value) + { + return (std::numeric_limits::min)() <= value && value <= (std::numeric_limits::max)() + ? sizeof(std::int32_t) + : sizeof(std::int64_t); + } + + /*! + @brief Writes a BSON element with key @a name and integer @a value + */ + void write_bson_integer(const string_t& name, + const std::int64_t value) + { + if ((std::numeric_limits::min)() <= value && value <= (std::numeric_limits::max)()) + { + write_bson_entry_header(name, 0x10); // int32 + write_number(static_cast(value)); + } + else + { + write_bson_entry_header(name, 0x12); // int64 + write_number(static_cast(value)); + } + } + + /*! + @return The size of the BSON-encoded unsigned integer in @a j + */ + static constexpr std::size_t calc_bson_unsigned_size(const std::uint64_t value) noexcept + { + return (value <= static_cast((std::numeric_limits::max)())) + ? sizeof(std::int32_t) + : sizeof(std::int64_t); + } + + /*! + @brief Writes a BSON element with key @a name and unsigned @a value + */ + void write_bson_unsigned(const string_t& name, + const BasicJsonType& j) + { + if (j.m_value.number_unsigned <= static_cast((std::numeric_limits::max)())) + { + write_bson_entry_header(name, 0x10 /* int32 */); + write_number(static_cast(j.m_value.number_unsigned)); + } + else if (j.m_value.number_unsigned <= static_cast((std::numeric_limits::max)())) + { + write_bson_entry_header(name, 0x12 /* int64 */); + write_number(static_cast(j.m_value.number_unsigned)); + } + else + { + JSON_THROW(out_of_range::create(407, "integer number " + std::to_string(j.m_value.number_unsigned) + " cannot be represented by BSON as it does not fit int64", j)); + } + } + + /*! + @brief Writes a BSON element with key @a name and object @a value + */ + void write_bson_object_entry(const string_t& name, + const typename BasicJsonType::object_t& value) + { + write_bson_entry_header(name, 0x03); // object + write_bson_object(value); + } + + /*! + @return The size of the BSON-encoded array @a value + */ + static std::size_t calc_bson_array_size(const typename BasicJsonType::array_t& value) + { + std::size_t array_index = 0ul; + + const std::size_t embedded_document_size = std::accumulate(std::begin(value), std::end(value), std::size_t(0), [&array_index](std::size_t result, const typename BasicJsonType::array_t::value_type & el) + { + return result + calc_bson_element_size(std::to_string(array_index++), el); + }); + + return sizeof(std::int32_t) + embedded_document_size + 1ul; + } + + /*! + @return The size of the BSON-encoded binary array @a value + */ + static std::size_t calc_bson_binary_size(const typename BasicJsonType::binary_t& value) + { + return sizeof(std::int32_t) + value.size() + 1ul; + } + + /*! + @brief Writes a BSON element with key @a name and array @a value + */ + void write_bson_array(const string_t& name, + const typename BasicJsonType::array_t& value) + { + write_bson_entry_header(name, 0x04); // array + write_number(static_cast(calc_bson_array_size(value))); + + std::size_t array_index = 0ul; + + for (const auto& el : value) + { + write_bson_element(std::to_string(array_index++), el); + } + + oa->write_character(to_char_type(0x00)); + } + + /*! + @brief Writes a BSON element with key @a name and binary value @a value + */ + void write_bson_binary(const string_t& name, + const binary_t& value) + { + write_bson_entry_header(name, 0x05); + + write_number(static_cast(value.size())); + write_number(value.has_subtype() ? value.subtype() : std::uint8_t(0x00)); + + oa->write_characters(reinterpret_cast(value.data()), value.size()); + } + + /*! + @brief Calculates the size necessary to serialize the JSON value @a j with its @a name + @return The calculated size for the BSON document entry for @a j with the given @a name. + */ + static std::size_t calc_bson_element_size(const string_t& name, + const BasicJsonType& j) + { + const auto header_size = calc_bson_entry_header_size(name, j); + switch (j.type()) + { + case value_t::object: + return header_size + calc_bson_object_size(*j.m_value.object); + + case value_t::array: + return header_size + calc_bson_array_size(*j.m_value.array); + + case value_t::binary: + return header_size + calc_bson_binary_size(*j.m_value.binary); + + case value_t::boolean: + return header_size + 1ul; + + case value_t::number_float: + return header_size + 8ul; + + case value_t::number_integer: + return header_size + calc_bson_integer_size(j.m_value.number_integer); + + case value_t::number_unsigned: + return header_size + calc_bson_unsigned_size(j.m_value.number_unsigned); + + case value_t::string: + return header_size + calc_bson_string_size(*j.m_value.string); + + case value_t::null: + return header_size + 0ul; + + // LCOV_EXCL_START + default: + JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) + return 0ul; + // LCOV_EXCL_STOP + } + } + + /*! + @brief Serializes the JSON value @a j to BSON and associates it with the + key @a name. + @param name The name to associate with the JSON entity @a j within the + current BSON document + */ + void write_bson_element(const string_t& name, + const BasicJsonType& j) + { + switch (j.type()) + { + case value_t::object: + return write_bson_object_entry(name, *j.m_value.object); + + case value_t::array: + return write_bson_array(name, *j.m_value.array); + + case value_t::binary: + return write_bson_binary(name, *j.m_value.binary); + + case value_t::boolean: + return write_bson_boolean(name, j.m_value.boolean); + + case value_t::number_float: + return write_bson_double(name, j.m_value.number_float); + + case value_t::number_integer: + return write_bson_integer(name, j.m_value.number_integer); + + case value_t::number_unsigned: + return write_bson_unsigned(name, j); + + case value_t::string: + return write_bson_string(name, *j.m_value.string); + + case value_t::null: + return write_bson_null(name); + + // LCOV_EXCL_START + default: + JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) + return; + // LCOV_EXCL_STOP + } + } + + /*! + @brief Calculates the size of the BSON serialization of the given + JSON-object @a j. + @param[in] value JSON value to serialize + @pre value.type() == value_t::object + */ + static std::size_t calc_bson_object_size(const typename BasicJsonType::object_t& value) + { + std::size_t document_size = std::accumulate(value.begin(), value.end(), std::size_t(0), + [](size_t result, const typename BasicJsonType::object_t::value_type & el) + { + return result += calc_bson_element_size(el.first, el.second); + }); + + return sizeof(std::int32_t) + document_size + 1ul; + } + + /*! + @param[in] value JSON value to serialize + @pre value.type() == value_t::object + */ + void write_bson_object(const typename BasicJsonType::object_t& value) + { + write_number(static_cast(calc_bson_object_size(value))); + + for (const auto& el : value) + { + write_bson_element(el.first, el.second); + } + + oa->write_character(to_char_type(0x00)); + } + + ////////// + // CBOR // + ////////// + + static constexpr CharType get_cbor_float_prefix(float /*unused*/) + { + return to_char_type(0xFA); // Single-Precision Float + } + + static constexpr CharType get_cbor_float_prefix(double /*unused*/) + { + return to_char_type(0xFB); // Double-Precision Float + } + + ///////////// + // MsgPack // + ///////////// + + static constexpr CharType get_msgpack_float_prefix(float /*unused*/) + { + return to_char_type(0xCA); // float 32 + } + + static constexpr CharType get_msgpack_float_prefix(double /*unused*/) + { + return to_char_type(0xCB); // float 64 + } + + //////////// + // UBJSON // + //////////// + + // UBJSON: write number (floating point) + template::value, int>::type = 0> + void write_number_with_ubjson_prefix(const NumberType n, + const bool add_prefix) + { + if (add_prefix) + { + oa->write_character(get_ubjson_float_prefix(n)); + } + write_number(n); + } + + // UBJSON: write number (unsigned integer) + template::value, int>::type = 0> + void write_number_with_ubjson_prefix(const NumberType n, + const bool add_prefix) + { + if (n <= static_cast((std::numeric_limits::max)())) + { + if (add_prefix) + { + oa->write_character(to_char_type('i')); // int8 + } + write_number(static_cast(n)); + } + else if (n <= (std::numeric_limits::max)()) + { + if (add_prefix) + { + oa->write_character(to_char_type('U')); // uint8 + } + write_number(static_cast(n)); + } + else if (n <= static_cast((std::numeric_limits::max)())) + { + if (add_prefix) + { + oa->write_character(to_char_type('I')); // int16 + } + write_number(static_cast(n)); + } + else if (n <= static_cast((std::numeric_limits::max)())) + { + if (add_prefix) + { + oa->write_character(to_char_type('l')); // int32 + } + write_number(static_cast(n)); + } + else if (n <= static_cast((std::numeric_limits::max)())) + { + if (add_prefix) + { + oa->write_character(to_char_type('L')); // int64 + } + write_number(static_cast(n)); + } + else + { + if (add_prefix) + { + oa->write_character(to_char_type('H')); // high-precision number + } + + const auto number = BasicJsonType(n).dump(); + write_number_with_ubjson_prefix(number.size(), true); + for (std::size_t i = 0; i < number.size(); ++i) + { + oa->write_character(to_char_type(static_cast(number[i]))); + } + } + } + + // UBJSON: write number (signed integer) + template < typename NumberType, typename std::enable_if < + std::is_signed::value&& + !std::is_floating_point::value, int >::type = 0 > + void write_number_with_ubjson_prefix(const NumberType n, + const bool add_prefix) + { + if ((std::numeric_limits::min)() <= n && n <= (std::numeric_limits::max)()) + { + if (add_prefix) + { + oa->write_character(to_char_type('i')); // int8 + } + write_number(static_cast(n)); + } + else if (static_cast((std::numeric_limits::min)()) <= n && n <= static_cast((std::numeric_limits::max)())) + { + if (add_prefix) + { + oa->write_character(to_char_type('U')); // uint8 + } + write_number(static_cast(n)); + } + else if ((std::numeric_limits::min)() <= n && n <= (std::numeric_limits::max)()) + { + if (add_prefix) + { + oa->write_character(to_char_type('I')); // int16 + } + write_number(static_cast(n)); + } + else if ((std::numeric_limits::min)() <= n && n <= (std::numeric_limits::max)()) + { + if (add_prefix) + { + oa->write_character(to_char_type('l')); // int32 + } + write_number(static_cast(n)); + } + else if ((std::numeric_limits::min)() <= n && n <= (std::numeric_limits::max)()) + { + if (add_prefix) + { + oa->write_character(to_char_type('L')); // int64 + } + write_number(static_cast(n)); + } + // LCOV_EXCL_START + else + { + if (add_prefix) + { + oa->write_character(to_char_type('H')); // high-precision number + } + + const auto number = BasicJsonType(n).dump(); + write_number_with_ubjson_prefix(number.size(), true); + for (std::size_t i = 0; i < number.size(); ++i) + { + oa->write_character(to_char_type(static_cast(number[i]))); + } + } + // LCOV_EXCL_STOP + } + + /*! + @brief determine the type prefix of container values + */ + CharType ubjson_prefix(const BasicJsonType& j) const noexcept + { + switch (j.type()) + { + case value_t::null: + return 'Z'; + + case value_t::boolean: + return j.m_value.boolean ? 'T' : 'F'; + + case value_t::number_integer: + { + if ((std::numeric_limits::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits::max)()) + { + return 'i'; + } + if ((std::numeric_limits::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits::max)()) + { + return 'U'; + } + if ((std::numeric_limits::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits::max)()) + { + return 'I'; + } + if ((std::numeric_limits::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits::max)()) + { + return 'l'; + } + if ((std::numeric_limits::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits::max)()) + { + return 'L'; + } + // anything else is treated as high-precision number + return 'H'; // LCOV_EXCL_LINE + } + + case value_t::number_unsigned: + { + if (j.m_value.number_unsigned <= static_cast((std::numeric_limits::max)())) + { + return 'i'; + } + if (j.m_value.number_unsigned <= static_cast((std::numeric_limits::max)())) + { + return 'U'; + } + if (j.m_value.number_unsigned <= static_cast((std::numeric_limits::max)())) + { + return 'I'; + } + if (j.m_value.number_unsigned <= static_cast((std::numeric_limits::max)())) + { + return 'l'; + } + if (j.m_value.number_unsigned <= static_cast((std::numeric_limits::max)())) + { + return 'L'; + } + // anything else is treated as high-precision number + return 'H'; // LCOV_EXCL_LINE + } + + case value_t::number_float: + return get_ubjson_float_prefix(j.m_value.number_float); + + case value_t::string: + return 'S'; + + case value_t::array: // fallthrough + case value_t::binary: + return '['; + + case value_t::object: + return '{'; + + default: // discarded values + return 'N'; + } + } + + static constexpr CharType get_ubjson_float_prefix(float /*unused*/) + { + return 'd'; // float 32 + } + + static constexpr CharType get_ubjson_float_prefix(double /*unused*/) + { + return 'D'; // float 64 + } + + /////////////////////// + // Utility functions // + /////////////////////// + + /* + @brief write a number to output input + @param[in] n number of type @a NumberType + @tparam NumberType the type of the number + @tparam OutputIsLittleEndian Set to true if output data is + required to be little endian + + @note This function needs to respect the system's endianess, because bytes + in CBOR, MessagePack, and UBJSON are stored in network order (big + endian) and therefore need reordering on little endian systems. + */ + template + void write_number(const NumberType n) + { + // step 1: write number to array of length NumberType + std::array vec{}; + std::memcpy(vec.data(), &n, sizeof(NumberType)); + + // step 2: write array to output (with possible reordering) + if (is_little_endian != OutputIsLittleEndian) + { + // reverse byte order prior to conversion if necessary + std::reverse(vec.begin(), vec.end()); + } + + oa->write_characters(vec.data(), sizeof(NumberType)); + } + + void write_compact_float(const number_float_t n, detail::input_format_t format) + { + if (static_cast(n) >= static_cast(std::numeric_limits::lowest()) && + static_cast(n) <= static_cast((std::numeric_limits::max)()) && + static_cast(static_cast(n)) == static_cast(n)) + { + oa->write_character(format == detail::input_format_t::cbor + ? get_cbor_float_prefix(static_cast(n)) + : get_msgpack_float_prefix(static_cast(n))); + write_number(static_cast(n)); + } + else + { + oa->write_character(format == detail::input_format_t::cbor + ? get_cbor_float_prefix(n) + : get_msgpack_float_prefix(n)); + write_number(n); + } + } + + public: + // The following to_char_type functions are implement the conversion + // between uint8_t and CharType. In case CharType is not unsigned, + // such a conversion is required to allow values greater than 128. + // See for a discussion. + template < typename C = CharType, + enable_if_t < std::is_signed::value && std::is_signed::value > * = nullptr > + static constexpr CharType to_char_type(std::uint8_t x) noexcept + { + return *reinterpret_cast(&x); + } + + template < typename C = CharType, + enable_if_t < std::is_signed::value && std::is_unsigned::value > * = nullptr > + static CharType to_char_type(std::uint8_t x) noexcept + { + static_assert(sizeof(std::uint8_t) == sizeof(CharType), "size of CharType must be equal to std::uint8_t"); + static_assert(std::is_trivial::value, "CharType must be trivial"); + CharType result; + std::memcpy(&result, &x, sizeof(x)); + return result; + } + + template::value>* = nullptr> + static constexpr CharType to_char_type(std::uint8_t x) noexcept + { + return x; + } + + template < typename InputCharType, typename C = CharType, + enable_if_t < + std::is_signed::value && + std::is_signed::value && + std::is_same::type>::value + > * = nullptr > + static constexpr CharType to_char_type(InputCharType x) noexcept + { + return x; + } + + private: + /// whether we can assume little endianess + const bool is_little_endian = little_endianess(); + + /// the output + output_adapter_t oa = nullptr; +}; +} // namespace detail +} // namespace nlohmann + +// #include + +// #include + + +#include // reverse, remove, fill, find, none_of +#include // array +#include // localeconv, lconv +#include // labs, isfinite, isnan, signbit +#include // size_t, ptrdiff_t +#include // uint8_t +#include // snprintf +#include // numeric_limits +#include // string, char_traits +#include // is_same +#include // move + +// #include + + +#include // array +#include // signbit, isfinite +#include // intN_t, uintN_t +#include // memcpy, memmove +#include // numeric_limits +#include // conditional + +// #include + + +namespace nlohmann +{ +namespace detail +{ + +/*! +@brief implements the Grisu2 algorithm for binary to decimal floating-point +conversion. + +This implementation is a slightly modified version of the reference +implementation which may be obtained from +http://florian.loitsch.com/publications (bench.tar.gz). + +The code is distributed under the MIT license, Copyright (c) 2009 Florian Loitsch. + +For a detailed description of the algorithm see: + +[1] Loitsch, "Printing Floating-Point Numbers Quickly and Accurately with + Integers", Proceedings of the ACM SIGPLAN 2010 Conference on Programming + Language Design and Implementation, PLDI 2010 +[2] Burger, Dybvig, "Printing Floating-Point Numbers Quickly and Accurately", + Proceedings of the ACM SIGPLAN 1996 Conference on Programming Language + Design and Implementation, PLDI 1996 +*/ +namespace dtoa_impl +{ + +template +Target reinterpret_bits(const Source source) +{ + static_assert(sizeof(Target) == sizeof(Source), "size mismatch"); + + Target target; + std::memcpy(&target, &source, sizeof(Source)); + return target; +} + +struct diyfp // f * 2^e +{ + static constexpr int kPrecision = 64; // = q + + std::uint64_t f = 0; + int e = 0; + + constexpr diyfp(std::uint64_t f_, int e_) noexcept : f(f_), e(e_) {} + + /*! + @brief returns x - y + @pre x.e == y.e and x.f >= y.f + */ + static diyfp sub(const diyfp& x, const diyfp& y) noexcept + { + JSON_ASSERT(x.e == y.e); + JSON_ASSERT(x.f >= y.f); + + return {x.f - y.f, x.e}; + } + + /*! + @brief returns x * y + @note The result is rounded. (Only the upper q bits are returned.) + */ + static diyfp mul(const diyfp& x, const diyfp& y) noexcept + { + static_assert(kPrecision == 64, "internal error"); + + // Computes: + // f = round((x.f * y.f) / 2^q) + // e = x.e + y.e + q + + // Emulate the 64-bit * 64-bit multiplication: + // + // p = u * v + // = (u_lo + 2^32 u_hi) (v_lo + 2^32 v_hi) + // = (u_lo v_lo ) + 2^32 ((u_lo v_hi ) + (u_hi v_lo )) + 2^64 (u_hi v_hi ) + // = (p0 ) + 2^32 ((p1 ) + (p2 )) + 2^64 (p3 ) + // = (p0_lo + 2^32 p0_hi) + 2^32 ((p1_lo + 2^32 p1_hi) + (p2_lo + 2^32 p2_hi)) + 2^64 (p3 ) + // = (p0_lo ) + 2^32 (p0_hi + p1_lo + p2_lo ) + 2^64 (p1_hi + p2_hi + p3) + // = (p0_lo ) + 2^32 (Q ) + 2^64 (H ) + // = (p0_lo ) + 2^32 (Q_lo + 2^32 Q_hi ) + 2^64 (H ) + // + // (Since Q might be larger than 2^32 - 1) + // + // = (p0_lo + 2^32 Q_lo) + 2^64 (Q_hi + H) + // + // (Q_hi + H does not overflow a 64-bit int) + // + // = p_lo + 2^64 p_hi + + const std::uint64_t u_lo = x.f & 0xFFFFFFFFu; + const std::uint64_t u_hi = x.f >> 32u; + const std::uint64_t v_lo = y.f & 0xFFFFFFFFu; + const std::uint64_t v_hi = y.f >> 32u; + + const std::uint64_t p0 = u_lo * v_lo; + const std::uint64_t p1 = u_lo * v_hi; + const std::uint64_t p2 = u_hi * v_lo; + const std::uint64_t p3 = u_hi * v_hi; + + const std::uint64_t p0_hi = p0 >> 32u; + const std::uint64_t p1_lo = p1 & 0xFFFFFFFFu; + const std::uint64_t p1_hi = p1 >> 32u; + const std::uint64_t p2_lo = p2 & 0xFFFFFFFFu; + const std::uint64_t p2_hi = p2 >> 32u; + + std::uint64_t Q = p0_hi + p1_lo + p2_lo; + + // The full product might now be computed as + // + // p_hi = p3 + p2_hi + p1_hi + (Q >> 32) + // p_lo = p0_lo + (Q << 32) + // + // But in this particular case here, the full p_lo is not required. + // Effectively we only need to add the highest bit in p_lo to p_hi (and + // Q_hi + 1 does not overflow). + + Q += std::uint64_t{1} << (64u - 32u - 1u); // round, ties up + + const std::uint64_t h = p3 + p2_hi + p1_hi + (Q >> 32u); + + return {h, x.e + y.e + 64}; + } + + /*! + @brief normalize x such that the significand is >= 2^(q-1) + @pre x.f != 0 + */ + static diyfp normalize(diyfp x) noexcept + { + JSON_ASSERT(x.f != 0); + + while ((x.f >> 63u) == 0) + { + x.f <<= 1u; + x.e--; + } + + return x; + } + + /*! + @brief normalize x such that the result has the exponent E + @pre e >= x.e and the upper e - x.e bits of x.f must be zero. + */ + static diyfp normalize_to(const diyfp& x, const int target_exponent) noexcept + { + const int delta = x.e - target_exponent; + + JSON_ASSERT(delta >= 0); + JSON_ASSERT(((x.f << delta) >> delta) == x.f); + + return {x.f << delta, target_exponent}; + } +}; + +struct boundaries +{ + diyfp w; + diyfp minus; + diyfp plus; +}; + +/*! +Compute the (normalized) diyfp representing the input number 'value' and its +boundaries. + +@pre value must be finite and positive +*/ +template +boundaries compute_boundaries(FloatType value) +{ + JSON_ASSERT(std::isfinite(value)); + JSON_ASSERT(value > 0); + + // Convert the IEEE representation into a diyfp. + // + // If v is denormal: + // value = 0.F * 2^(1 - bias) = ( F) * 2^(1 - bias - (p-1)) + // If v is normalized: + // value = 1.F * 2^(E - bias) = (2^(p-1) + F) * 2^(E - bias - (p-1)) + + static_assert(std::numeric_limits::is_iec559, + "internal error: dtoa_short requires an IEEE-754 floating-point implementation"); + + constexpr int kPrecision = std::numeric_limits::digits; // = p (includes the hidden bit) + constexpr int kBias = std::numeric_limits::max_exponent - 1 + (kPrecision - 1); + constexpr int kMinExp = 1 - kBias; + constexpr std::uint64_t kHiddenBit = std::uint64_t{1} << (kPrecision - 1); // = 2^(p-1) + + using bits_type = typename std::conditional::type; + + const auto bits = static_cast(reinterpret_bits(value)); + const std::uint64_t E = bits >> (kPrecision - 1); + const std::uint64_t F = bits & (kHiddenBit - 1); + + const bool is_denormal = E == 0; + const diyfp v = is_denormal + ? diyfp(F, kMinExp) + : diyfp(F + kHiddenBit, static_cast(E) - kBias); + + // Compute the boundaries m- and m+ of the floating-point value + // v = f * 2^e. + // + // Determine v- and v+, the floating-point predecessor and successor if v, + // respectively. + // + // v- = v - 2^e if f != 2^(p-1) or e == e_min (A) + // = v - 2^(e-1) if f == 2^(p-1) and e > e_min (B) + // + // v+ = v + 2^e + // + // Let m- = (v- + v) / 2 and m+ = (v + v+) / 2. All real numbers _strictly_ + // between m- and m+ round to v, regardless of how the input rounding + // algorithm breaks ties. + // + // ---+-------------+-------------+-------------+-------------+--- (A) + // v- m- v m+ v+ + // + // -----------------+------+------+-------------+-------------+--- (B) + // v- m- v m+ v+ + + const bool lower_boundary_is_closer = F == 0 && E > 1; + const diyfp m_plus = diyfp(2 * v.f + 1, v.e - 1); + const diyfp m_minus = lower_boundary_is_closer + ? diyfp(4 * v.f - 1, v.e - 2) // (B) + : diyfp(2 * v.f - 1, v.e - 1); // (A) + + // Determine the normalized w+ = m+. + const diyfp w_plus = diyfp::normalize(m_plus); + + // Determine w- = m- such that e_(w-) = e_(w+). + const diyfp w_minus = diyfp::normalize_to(m_minus, w_plus.e); + + return {diyfp::normalize(v), w_minus, w_plus}; +} + +// Given normalized diyfp w, Grisu needs to find a (normalized) cached +// power-of-ten c, such that the exponent of the product c * w = f * 2^e lies +// within a certain range [alpha, gamma] (Definition 3.2 from [1]) +// +// alpha <= e = e_c + e_w + q <= gamma +// +// or +// +// f_c * f_w * 2^alpha <= f_c 2^(e_c) * f_w 2^(e_w) * 2^q +// <= f_c * f_w * 2^gamma +// +// Since c and w are normalized, i.e. 2^(q-1) <= f < 2^q, this implies +// +// 2^(q-1) * 2^(q-1) * 2^alpha <= c * w * 2^q < 2^q * 2^q * 2^gamma +// +// or +// +// 2^(q - 2 + alpha) <= c * w < 2^(q + gamma) +// +// The choice of (alpha,gamma) determines the size of the table and the form of +// the digit generation procedure. Using (alpha,gamma)=(-60,-32) works out well +// in practice: +// +// The idea is to cut the number c * w = f * 2^e into two parts, which can be +// processed independently: An integral part p1, and a fractional part p2: +// +// f * 2^e = ( (f div 2^-e) * 2^-e + (f mod 2^-e) ) * 2^e +// = (f div 2^-e) + (f mod 2^-e) * 2^e +// = p1 + p2 * 2^e +// +// The conversion of p1 into decimal form requires a series of divisions and +// modulos by (a power of) 10. These operations are faster for 32-bit than for +// 64-bit integers, so p1 should ideally fit into a 32-bit integer. This can be +// achieved by choosing +// +// -e >= 32 or e <= -32 := gamma +// +// In order to convert the fractional part +// +// p2 * 2^e = p2 / 2^-e = d[-1] / 10^1 + d[-2] / 10^2 + ... +// +// into decimal form, the fraction is repeatedly multiplied by 10 and the digits +// d[-i] are extracted in order: +// +// (10 * p2) div 2^-e = d[-1] +// (10 * p2) mod 2^-e = d[-2] / 10^1 + ... +// +// The multiplication by 10 must not overflow. It is sufficient to choose +// +// 10 * p2 < 16 * p2 = 2^4 * p2 <= 2^64. +// +// Since p2 = f mod 2^-e < 2^-e, +// +// -e <= 60 or e >= -60 := alpha + +constexpr int kAlpha = -60; +constexpr int kGamma = -32; + +struct cached_power // c = f * 2^e ~= 10^k +{ + std::uint64_t f; + int e; + int k; +}; + +/*! +For a normalized diyfp w = f * 2^e, this function returns a (normalized) cached +power-of-ten c = f_c * 2^e_c, such that the exponent of the product w * c +satisfies (Definition 3.2 from [1]) + + alpha <= e_c + e + q <= gamma. +*/ +inline cached_power get_cached_power_for_binary_exponent(int e) +{ + // Now + // + // alpha <= e_c + e + q <= gamma (1) + // ==> f_c * 2^alpha <= c * 2^e * 2^q + // + // and since the c's are normalized, 2^(q-1) <= f_c, + // + // ==> 2^(q - 1 + alpha) <= c * 2^(e + q) + // ==> 2^(alpha - e - 1) <= c + // + // If c were an exact power of ten, i.e. c = 10^k, one may determine k as + // + // k = ceil( log_10( 2^(alpha - e - 1) ) ) + // = ceil( (alpha - e - 1) * log_10(2) ) + // + // From the paper: + // "In theory the result of the procedure could be wrong since c is rounded, + // and the computation itself is approximated [...]. In practice, however, + // this simple function is sufficient." + // + // For IEEE double precision floating-point numbers converted into + // normalized diyfp's w = f * 2^e, with q = 64, + // + // e >= -1022 (min IEEE exponent) + // -52 (p - 1) + // -52 (p - 1, possibly normalize denormal IEEE numbers) + // -11 (normalize the diyfp) + // = -1137 + // + // and + // + // e <= +1023 (max IEEE exponent) + // -52 (p - 1) + // -11 (normalize the diyfp) + // = 960 + // + // This binary exponent range [-1137,960] results in a decimal exponent + // range [-307,324]. One does not need to store a cached power for each + // k in this range. For each such k it suffices to find a cached power + // such that the exponent of the product lies in [alpha,gamma]. + // This implies that the difference of the decimal exponents of adjacent + // table entries must be less than or equal to + // + // floor( (gamma - alpha) * log_10(2) ) = 8. + // + // (A smaller distance gamma-alpha would require a larger table.) + + // NB: + // Actually this function returns c, such that -60 <= e_c + e + 64 <= -34. + + constexpr int kCachedPowersMinDecExp = -300; + constexpr int kCachedPowersDecStep = 8; + + static constexpr std::array kCachedPowers = + { + { + { 0xAB70FE17C79AC6CA, -1060, -300 }, + { 0xFF77B1FCBEBCDC4F, -1034, -292 }, + { 0xBE5691EF416BD60C, -1007, -284 }, + { 0x8DD01FAD907FFC3C, -980, -276 }, + { 0xD3515C2831559A83, -954, -268 }, + { 0x9D71AC8FADA6C9B5, -927, -260 }, + { 0xEA9C227723EE8BCB, -901, -252 }, + { 0xAECC49914078536D, -874, -244 }, + { 0x823C12795DB6CE57, -847, -236 }, + { 0xC21094364DFB5637, -821, -228 }, + { 0x9096EA6F3848984F, -794, -220 }, + { 0xD77485CB25823AC7, -768, -212 }, + { 0xA086CFCD97BF97F4, -741, -204 }, + { 0xEF340A98172AACE5, -715, -196 }, + { 0xB23867FB2A35B28E, -688, -188 }, + { 0x84C8D4DFD2C63F3B, -661, -180 }, + { 0xC5DD44271AD3CDBA, -635, -172 }, + { 0x936B9FCEBB25C996, -608, -164 }, + { 0xDBAC6C247D62A584, -582, -156 }, + { 0xA3AB66580D5FDAF6, -555, -148 }, + { 0xF3E2F893DEC3F126, -529, -140 }, + { 0xB5B5ADA8AAFF80B8, -502, -132 }, + { 0x87625F056C7C4A8B, -475, -124 }, + { 0xC9BCFF6034C13053, -449, -116 }, + { 0x964E858C91BA2655, -422, -108 }, + { 0xDFF9772470297EBD, -396, -100 }, + { 0xA6DFBD9FB8E5B88F, -369, -92 }, + { 0xF8A95FCF88747D94, -343, -84 }, + { 0xB94470938FA89BCF, -316, -76 }, + { 0x8A08F0F8BF0F156B, -289, -68 }, + { 0xCDB02555653131B6, -263, -60 }, + { 0x993FE2C6D07B7FAC, -236, -52 }, + { 0xE45C10C42A2B3B06, -210, -44 }, + { 0xAA242499697392D3, -183, -36 }, + { 0xFD87B5F28300CA0E, -157, -28 }, + { 0xBCE5086492111AEB, -130, -20 }, + { 0x8CBCCC096F5088CC, -103, -12 }, + { 0xD1B71758E219652C, -77, -4 }, + { 0x9C40000000000000, -50, 4 }, + { 0xE8D4A51000000000, -24, 12 }, + { 0xAD78EBC5AC620000, 3, 20 }, + { 0x813F3978F8940984, 30, 28 }, + { 0xC097CE7BC90715B3, 56, 36 }, + { 0x8F7E32CE7BEA5C70, 83, 44 }, + { 0xD5D238A4ABE98068, 109, 52 }, + { 0x9F4F2726179A2245, 136, 60 }, + { 0xED63A231D4C4FB27, 162, 68 }, + { 0xB0DE65388CC8ADA8, 189, 76 }, + { 0x83C7088E1AAB65DB, 216, 84 }, + { 0xC45D1DF942711D9A, 242, 92 }, + { 0x924D692CA61BE758, 269, 100 }, + { 0xDA01EE641A708DEA, 295, 108 }, + { 0xA26DA3999AEF774A, 322, 116 }, + { 0xF209787BB47D6B85, 348, 124 }, + { 0xB454E4A179DD1877, 375, 132 }, + { 0x865B86925B9BC5C2, 402, 140 }, + { 0xC83553C5C8965D3D, 428, 148 }, + { 0x952AB45CFA97A0B3, 455, 156 }, + { 0xDE469FBD99A05FE3, 481, 164 }, + { 0xA59BC234DB398C25, 508, 172 }, + { 0xF6C69A72A3989F5C, 534, 180 }, + { 0xB7DCBF5354E9BECE, 561, 188 }, + { 0x88FCF317F22241E2, 588, 196 }, + { 0xCC20CE9BD35C78A5, 614, 204 }, + { 0x98165AF37B2153DF, 641, 212 }, + { 0xE2A0B5DC971F303A, 667, 220 }, + { 0xA8D9D1535CE3B396, 694, 228 }, + { 0xFB9B7CD9A4A7443C, 720, 236 }, + { 0xBB764C4CA7A44410, 747, 244 }, + { 0x8BAB8EEFB6409C1A, 774, 252 }, + { 0xD01FEF10A657842C, 800, 260 }, + { 0x9B10A4E5E9913129, 827, 268 }, + { 0xE7109BFBA19C0C9D, 853, 276 }, + { 0xAC2820D9623BF429, 880, 284 }, + { 0x80444B5E7AA7CF85, 907, 292 }, + { 0xBF21E44003ACDD2D, 933, 300 }, + { 0x8E679C2F5E44FF8F, 960, 308 }, + { 0xD433179D9C8CB841, 986, 316 }, + { 0x9E19DB92B4E31BA9, 1013, 324 }, + } + }; + + // This computation gives exactly the same results for k as + // k = ceil((kAlpha - e - 1) * 0.30102999566398114) + // for |e| <= 1500, but doesn't require floating-point operations. + // NB: log_10(2) ~= 78913 / 2^18 + JSON_ASSERT(e >= -1500); + JSON_ASSERT(e <= 1500); + const int f = kAlpha - e - 1; + const int k = (f * 78913) / (1 << 18) + static_cast(f > 0); + + const int index = (-kCachedPowersMinDecExp + k + (kCachedPowersDecStep - 1)) / kCachedPowersDecStep; + JSON_ASSERT(index >= 0); + JSON_ASSERT(static_cast(index) < kCachedPowers.size()); + + const cached_power cached = kCachedPowers[static_cast(index)]; + JSON_ASSERT(kAlpha <= cached.e + e + 64); + JSON_ASSERT(kGamma >= cached.e + e + 64); + + return cached; +} + +/*! +For n != 0, returns k, such that pow10 := 10^(k-1) <= n < 10^k. +For n == 0, returns 1 and sets pow10 := 1. +*/ +inline int find_largest_pow10(const std::uint32_t n, std::uint32_t& pow10) +{ + // LCOV_EXCL_START + if (n >= 1000000000) + { + pow10 = 1000000000; + return 10; + } + // LCOV_EXCL_STOP + if (n >= 100000000) + { + pow10 = 100000000; + return 9; + } + if (n >= 10000000) + { + pow10 = 10000000; + return 8; + } + if (n >= 1000000) + { + pow10 = 1000000; + return 7; + } + if (n >= 100000) + { + pow10 = 100000; + return 6; + } + if (n >= 10000) + { + pow10 = 10000; + return 5; + } + if (n >= 1000) + { + pow10 = 1000; + return 4; + } + if (n >= 100) + { + pow10 = 100; + return 3; + } + if (n >= 10) + { + pow10 = 10; + return 2; + } + + pow10 = 1; + return 1; +} + +inline void grisu2_round(char* buf, int len, std::uint64_t dist, std::uint64_t delta, + std::uint64_t rest, std::uint64_t ten_k) +{ + JSON_ASSERT(len >= 1); + JSON_ASSERT(dist <= delta); + JSON_ASSERT(rest <= delta); + JSON_ASSERT(ten_k > 0); + + // <--------------------------- delta ----> + // <---- dist ---------> + // --------------[------------------+-------------------]-------------- + // M- w M+ + // + // ten_k + // <------> + // <---- rest ----> + // --------------[------------------+----+--------------]-------------- + // w V + // = buf * 10^k + // + // ten_k represents a unit-in-the-last-place in the decimal representation + // stored in buf. + // Decrement buf by ten_k while this takes buf closer to w. + + // The tests are written in this order to avoid overflow in unsigned + // integer arithmetic. + + while (rest < dist + && delta - rest >= ten_k + && (rest + ten_k < dist || dist - rest > rest + ten_k - dist)) + { + JSON_ASSERT(buf[len - 1] != '0'); + buf[len - 1]--; + rest += ten_k; + } +} + +/*! +Generates V = buffer * 10^decimal_exponent, such that M- <= V <= M+. +M- and M+ must be normalized and share the same exponent -60 <= e <= -32. +*/ +inline void grisu2_digit_gen(char* buffer, int& length, int& decimal_exponent, + diyfp M_minus, diyfp w, diyfp M_plus) +{ + static_assert(kAlpha >= -60, "internal error"); + static_assert(kGamma <= -32, "internal error"); + + // Generates the digits (and the exponent) of a decimal floating-point + // number V = buffer * 10^decimal_exponent in the range [M-, M+]. The diyfp's + // w, M- and M+ share the same exponent e, which satisfies alpha <= e <= gamma. + // + // <--------------------------- delta ----> + // <---- dist ---------> + // --------------[------------------+-------------------]-------------- + // M- w M+ + // + // Grisu2 generates the digits of M+ from left to right and stops as soon as + // V is in [M-,M+]. + + JSON_ASSERT(M_plus.e >= kAlpha); + JSON_ASSERT(M_plus.e <= kGamma); + + std::uint64_t delta = diyfp::sub(M_plus, M_minus).f; // (significand of (M+ - M-), implicit exponent is e) + std::uint64_t dist = diyfp::sub(M_plus, w ).f; // (significand of (M+ - w ), implicit exponent is e) + + // Split M+ = f * 2^e into two parts p1 and p2 (note: e < 0): + // + // M+ = f * 2^e + // = ((f div 2^-e) * 2^-e + (f mod 2^-e)) * 2^e + // = ((p1 ) * 2^-e + (p2 )) * 2^e + // = p1 + p2 * 2^e + + const diyfp one(std::uint64_t{1} << -M_plus.e, M_plus.e); + + auto p1 = static_cast(M_plus.f >> -one.e); // p1 = f div 2^-e (Since -e >= 32, p1 fits into a 32-bit int.) + std::uint64_t p2 = M_plus.f & (one.f - 1); // p2 = f mod 2^-e + + // 1) + // + // Generate the digits of the integral part p1 = d[n-1]...d[1]d[0] + + JSON_ASSERT(p1 > 0); + + std::uint32_t pow10{}; + const int k = find_largest_pow10(p1, pow10); + + // 10^(k-1) <= p1 < 10^k, pow10 = 10^(k-1) + // + // p1 = (p1 div 10^(k-1)) * 10^(k-1) + (p1 mod 10^(k-1)) + // = (d[k-1] ) * 10^(k-1) + (p1 mod 10^(k-1)) + // + // M+ = p1 + p2 * 2^e + // = d[k-1] * 10^(k-1) + (p1 mod 10^(k-1)) + p2 * 2^e + // = d[k-1] * 10^(k-1) + ((p1 mod 10^(k-1)) * 2^-e + p2) * 2^e + // = d[k-1] * 10^(k-1) + ( rest) * 2^e + // + // Now generate the digits d[n] of p1 from left to right (n = k-1,...,0) + // + // p1 = d[k-1]...d[n] * 10^n + d[n-1]...d[0] + // + // but stop as soon as + // + // rest * 2^e = (d[n-1]...d[0] * 2^-e + p2) * 2^e <= delta * 2^e + + int n = k; + while (n > 0) + { + // Invariants: + // M+ = buffer * 10^n + (p1 + p2 * 2^e) (buffer = 0 for n = k) + // pow10 = 10^(n-1) <= p1 < 10^n + // + const std::uint32_t d = p1 / pow10; // d = p1 div 10^(n-1) + const std::uint32_t r = p1 % pow10; // r = p1 mod 10^(n-1) + // + // M+ = buffer * 10^n + (d * 10^(n-1) + r) + p2 * 2^e + // = (buffer * 10 + d) * 10^(n-1) + (r + p2 * 2^e) + // + JSON_ASSERT(d <= 9); + buffer[length++] = static_cast('0' + d); // buffer := buffer * 10 + d + // + // M+ = buffer * 10^(n-1) + (r + p2 * 2^e) + // + p1 = r; + n--; + // + // M+ = buffer * 10^n + (p1 + p2 * 2^e) + // pow10 = 10^n + // + + // Now check if enough digits have been generated. + // Compute + // + // p1 + p2 * 2^e = (p1 * 2^-e + p2) * 2^e = rest * 2^e + // + // Note: + // Since rest and delta share the same exponent e, it suffices to + // compare the significands. + const std::uint64_t rest = (std::uint64_t{p1} << -one.e) + p2; + if (rest <= delta) + { + // V = buffer * 10^n, with M- <= V <= M+. + + decimal_exponent += n; + + // We may now just stop. But instead look if the buffer could be + // decremented to bring V closer to w. + // + // pow10 = 10^n is now 1 ulp in the decimal representation V. + // The rounding procedure works with diyfp's with an implicit + // exponent of e. + // + // 10^n = (10^n * 2^-e) * 2^e = ulp * 2^e + // + const std::uint64_t ten_n = std::uint64_t{pow10} << -one.e; + grisu2_round(buffer, length, dist, delta, rest, ten_n); + + return; + } + + pow10 /= 10; + // + // pow10 = 10^(n-1) <= p1 < 10^n + // Invariants restored. + } + + // 2) + // + // The digits of the integral part have been generated: + // + // M+ = d[k-1]...d[1]d[0] + p2 * 2^e + // = buffer + p2 * 2^e + // + // Now generate the digits of the fractional part p2 * 2^e. + // + // Note: + // No decimal point is generated: the exponent is adjusted instead. + // + // p2 actually represents the fraction + // + // p2 * 2^e + // = p2 / 2^-e + // = d[-1] / 10^1 + d[-2] / 10^2 + ... + // + // Now generate the digits d[-m] of p1 from left to right (m = 1,2,...) + // + // p2 * 2^e = d[-1]d[-2]...d[-m] * 10^-m + // + 10^-m * (d[-m-1] / 10^1 + d[-m-2] / 10^2 + ...) + // + // using + // + // 10^m * p2 = ((10^m * p2) div 2^-e) * 2^-e + ((10^m * p2) mod 2^-e) + // = ( d) * 2^-e + ( r) + // + // or + // 10^m * p2 * 2^e = d + r * 2^e + // + // i.e. + // + // M+ = buffer + p2 * 2^e + // = buffer + 10^-m * (d + r * 2^e) + // = (buffer * 10^m + d) * 10^-m + 10^-m * r * 2^e + // + // and stop as soon as 10^-m * r * 2^e <= delta * 2^e + + JSON_ASSERT(p2 > delta); + + int m = 0; + for (;;) + { + // Invariant: + // M+ = buffer * 10^-m + 10^-m * (d[-m-1] / 10 + d[-m-2] / 10^2 + ...) * 2^e + // = buffer * 10^-m + 10^-m * (p2 ) * 2^e + // = buffer * 10^-m + 10^-m * (1/10 * (10 * p2) ) * 2^e + // = buffer * 10^-m + 10^-m * (1/10 * ((10*p2 div 2^-e) * 2^-e + (10*p2 mod 2^-e)) * 2^e + // + JSON_ASSERT(p2 <= (std::numeric_limits::max)() / 10); + p2 *= 10; + const std::uint64_t d = p2 >> -one.e; // d = (10 * p2) div 2^-e + const std::uint64_t r = p2 & (one.f - 1); // r = (10 * p2) mod 2^-e + // + // M+ = buffer * 10^-m + 10^-m * (1/10 * (d * 2^-e + r) * 2^e + // = buffer * 10^-m + 10^-m * (1/10 * (d + r * 2^e)) + // = (buffer * 10 + d) * 10^(-m-1) + 10^(-m-1) * r * 2^e + // + JSON_ASSERT(d <= 9); + buffer[length++] = static_cast('0' + d); // buffer := buffer * 10 + d + // + // M+ = buffer * 10^(-m-1) + 10^(-m-1) * r * 2^e + // + p2 = r; + m++; + // + // M+ = buffer * 10^-m + 10^-m * p2 * 2^e + // Invariant restored. + + // Check if enough digits have been generated. + // + // 10^-m * p2 * 2^e <= delta * 2^e + // p2 * 2^e <= 10^m * delta * 2^e + // p2 <= 10^m * delta + delta *= 10; + dist *= 10; + if (p2 <= delta) + { + break; + } + } + + // V = buffer * 10^-m, with M- <= V <= M+. + + decimal_exponent -= m; + + // 1 ulp in the decimal representation is now 10^-m. + // Since delta and dist are now scaled by 10^m, we need to do the + // same with ulp in order to keep the units in sync. + // + // 10^m * 10^-m = 1 = 2^-e * 2^e = ten_m * 2^e + // + const std::uint64_t ten_m = one.f; + grisu2_round(buffer, length, dist, delta, p2, ten_m); + + // By construction this algorithm generates the shortest possible decimal + // number (Loitsch, Theorem 6.2) which rounds back to w. + // For an input number of precision p, at least + // + // N = 1 + ceil(p * log_10(2)) + // + // decimal digits are sufficient to identify all binary floating-point + // numbers (Matula, "In-and-Out conversions"). + // This implies that the algorithm does not produce more than N decimal + // digits. + // + // N = 17 for p = 53 (IEEE double precision) + // N = 9 for p = 24 (IEEE single precision) +} + +/*! +v = buf * 10^decimal_exponent +len is the length of the buffer (number of decimal digits) +The buffer must be large enough, i.e. >= max_digits10. +*/ +JSON_HEDLEY_NON_NULL(1) +inline void grisu2(char* buf, int& len, int& decimal_exponent, + diyfp m_minus, diyfp v, diyfp m_plus) +{ + JSON_ASSERT(m_plus.e == m_minus.e); + JSON_ASSERT(m_plus.e == v.e); + + // --------(-----------------------+-----------------------)-------- (A) + // m- v m+ + // + // --------------------(-----------+-----------------------)-------- (B) + // m- v m+ + // + // First scale v (and m- and m+) such that the exponent is in the range + // [alpha, gamma]. + + const cached_power cached = get_cached_power_for_binary_exponent(m_plus.e); + + const diyfp c_minus_k(cached.f, cached.e); // = c ~= 10^-k + + // The exponent of the products is = v.e + c_minus_k.e + q and is in the range [alpha,gamma] + const diyfp w = diyfp::mul(v, c_minus_k); + const diyfp w_minus = diyfp::mul(m_minus, c_minus_k); + const diyfp w_plus = diyfp::mul(m_plus, c_minus_k); + + // ----(---+---)---------------(---+---)---------------(---+---)---- + // w- w w+ + // = c*m- = c*v = c*m+ + // + // diyfp::mul rounds its result and c_minus_k is approximated too. w, w- and + // w+ are now off by a small amount. + // In fact: + // + // w - v * 10^k < 1 ulp + // + // To account for this inaccuracy, add resp. subtract 1 ulp. + // + // --------+---[---------------(---+---)---------------]---+-------- + // w- M- w M+ w+ + // + // Now any number in [M-, M+] (bounds included) will round to w when input, + // regardless of how the input rounding algorithm breaks ties. + // + // And digit_gen generates the shortest possible such number in [M-, M+]. + // Note that this does not mean that Grisu2 always generates the shortest + // possible number in the interval (m-, m+). + const diyfp M_minus(w_minus.f + 1, w_minus.e); + const diyfp M_plus (w_plus.f - 1, w_plus.e ); + + decimal_exponent = -cached.k; // = -(-k) = k + + grisu2_digit_gen(buf, len, decimal_exponent, M_minus, w, M_plus); +} + +/*! +v = buf * 10^decimal_exponent +len is the length of the buffer (number of decimal digits) +The buffer must be large enough, i.e. >= max_digits10. +*/ +template +JSON_HEDLEY_NON_NULL(1) +void grisu2(char* buf, int& len, int& decimal_exponent, FloatType value) +{ + static_assert(diyfp::kPrecision >= std::numeric_limits::digits + 3, + "internal error: not enough precision"); + + JSON_ASSERT(std::isfinite(value)); + JSON_ASSERT(value > 0); + + // If the neighbors (and boundaries) of 'value' are always computed for double-precision + // numbers, all float's can be recovered using strtod (and strtof). However, the resulting + // decimal representations are not exactly "short". + // + // The documentation for 'std::to_chars' (https://en.cppreference.com/w/cpp/utility/to_chars) + // says "value is converted to a string as if by std::sprintf in the default ("C") locale" + // and since sprintf promotes float's to double's, I think this is exactly what 'std::to_chars' + // does. + // On the other hand, the documentation for 'std::to_chars' requires that "parsing the + // representation using the corresponding std::from_chars function recovers value exactly". That + // indicates that single precision floating-point numbers should be recovered using + // 'std::strtof'. + // + // NB: If the neighbors are computed for single-precision numbers, there is a single float + // (7.0385307e-26f) which can't be recovered using strtod. The resulting double precision + // value is off by 1 ulp. +#if 0 + const boundaries w = compute_boundaries(static_cast(value)); +#else + const boundaries w = compute_boundaries(value); +#endif + + grisu2(buf, len, decimal_exponent, w.minus, w.w, w.plus); +} + +/*! +@brief appends a decimal representation of e to buf +@return a pointer to the element following the exponent. +@pre -1000 < e < 1000 +*/ +JSON_HEDLEY_NON_NULL(1) +JSON_HEDLEY_RETURNS_NON_NULL +inline char* append_exponent(char* buf, int e) +{ + JSON_ASSERT(e > -1000); + JSON_ASSERT(e < 1000); + + if (e < 0) + { + e = -e; + *buf++ = '-'; + } + else + { + *buf++ = '+'; + } + + auto k = static_cast(e); + if (k < 10) + { + // Always print at least two digits in the exponent. + // This is for compatibility with printf("%g"). + *buf++ = '0'; + *buf++ = static_cast('0' + k); + } + else if (k < 100) + { + *buf++ = static_cast('0' + k / 10); + k %= 10; + *buf++ = static_cast('0' + k); + } + else + { + *buf++ = static_cast('0' + k / 100); + k %= 100; + *buf++ = static_cast('0' + k / 10); + k %= 10; + *buf++ = static_cast('0' + k); + } + + return buf; +} + +/*! +@brief prettify v = buf * 10^decimal_exponent + +If v is in the range [10^min_exp, 10^max_exp) it will be printed in fixed-point +notation. Otherwise it will be printed in exponential notation. + +@pre min_exp < 0 +@pre max_exp > 0 +*/ +JSON_HEDLEY_NON_NULL(1) +JSON_HEDLEY_RETURNS_NON_NULL +inline char* format_buffer(char* buf, int len, int decimal_exponent, + int min_exp, int max_exp) +{ + JSON_ASSERT(min_exp < 0); + JSON_ASSERT(max_exp > 0); + + const int k = len; + const int n = len + decimal_exponent; + + // v = buf * 10^(n-k) + // k is the length of the buffer (number of decimal digits) + // n is the position of the decimal point relative to the start of the buffer. + + if (k <= n && n <= max_exp) + { + // digits[000] + // len <= max_exp + 2 + + std::memset(buf + k, '0', static_cast(n) - static_cast(k)); + // Make it look like a floating-point number (#362, #378) + buf[n + 0] = '.'; + buf[n + 1] = '0'; + return buf + (static_cast(n) + 2); + } + + if (0 < n && n <= max_exp) + { + // dig.its + // len <= max_digits10 + 1 + + JSON_ASSERT(k > n); + + std::memmove(buf + (static_cast(n) + 1), buf + n, static_cast(k) - static_cast(n)); + buf[n] = '.'; + return buf + (static_cast(k) + 1U); + } + + if (min_exp < n && n <= 0) + { + // 0.[000]digits + // len <= 2 + (-min_exp - 1) + max_digits10 + + std::memmove(buf + (2 + static_cast(-n)), buf, static_cast(k)); + buf[0] = '0'; + buf[1] = '.'; + std::memset(buf + 2, '0', static_cast(-n)); + return buf + (2U + static_cast(-n) + static_cast(k)); + } + + if (k == 1) + { + // dE+123 + // len <= 1 + 5 + + buf += 1; + } + else + { + // d.igitsE+123 + // len <= max_digits10 + 1 + 5 + + std::memmove(buf + 2, buf + 1, static_cast(k) - 1); + buf[1] = '.'; + buf += 1 + static_cast(k); + } + + *buf++ = 'e'; + return append_exponent(buf, n - 1); +} + +} // namespace dtoa_impl + +/*! +@brief generates a decimal representation of the floating-point number value in [first, last). + +The format of the resulting decimal representation is similar to printf's %g +format. Returns an iterator pointing past-the-end of the decimal representation. + +@note The input number must be finite, i.e. NaN's and Inf's are not supported. +@note The buffer must be large enough. +@note The result is NOT null-terminated. +*/ +template +JSON_HEDLEY_NON_NULL(1, 2) +JSON_HEDLEY_RETURNS_NON_NULL +char* to_chars(char* first, const char* last, FloatType value) +{ + static_cast(last); // maybe unused - fix warning + JSON_ASSERT(std::isfinite(value)); + + // Use signbit(value) instead of (value < 0) since signbit works for -0. + if (std::signbit(value)) + { + value = -value; + *first++ = '-'; + } + + if (value == 0) // +-0 + { + *first++ = '0'; + // Make it look like a floating-point number (#362, #378) + *first++ = '.'; + *first++ = '0'; + return first; + } + + JSON_ASSERT(last - first >= std::numeric_limits::max_digits10); + + // Compute v = buffer * 10^decimal_exponent. + // The decimal digits are stored in the buffer, which needs to be interpreted + // as an unsigned decimal integer. + // len is the length of the buffer, i.e. the number of decimal digits. + int len = 0; + int decimal_exponent = 0; + dtoa_impl::grisu2(first, len, decimal_exponent, value); + + JSON_ASSERT(len <= std::numeric_limits::max_digits10); + + // Format the buffer like printf("%.*g", prec, value) + constexpr int kMinExp = -4; + // Use digits10 here to increase compatibility with version 2. + constexpr int kMaxExp = std::numeric_limits::digits10; + + JSON_ASSERT(last - first >= kMaxExp + 2); + JSON_ASSERT(last - first >= 2 + (-kMinExp - 1) + std::numeric_limits::max_digits10); + JSON_ASSERT(last - first >= std::numeric_limits::max_digits10 + 6); + + return dtoa_impl::format_buffer(first, len, decimal_exponent, kMinExp, kMaxExp); +} + +} // namespace detail +} // namespace nlohmann + +// #include + +// #include + +// #include + +// #include + +// #include + +// #include + + +namespace nlohmann +{ +namespace detail +{ +/////////////////// +// serialization // +/////////////////// + +/// how to treat decoding errors +enum class error_handler_t +{ + strict, ///< throw a type_error exception in case of invalid UTF-8 + replace, ///< replace invalid UTF-8 sequences with U+FFFD + ignore ///< ignore invalid UTF-8 sequences +}; + +template +class serializer +{ + using string_t = typename BasicJsonType::string_t; + using number_float_t = typename BasicJsonType::number_float_t; + using number_integer_t = typename BasicJsonType::number_integer_t; + using number_unsigned_t = typename BasicJsonType::number_unsigned_t; + using binary_char_t = typename BasicJsonType::binary_t::value_type; + static constexpr std::uint8_t UTF8_ACCEPT = 0; + static constexpr std::uint8_t UTF8_REJECT = 1; + + public: + /*! + @param[in] s output stream to serialize to + @param[in] ichar indentation character to use + @param[in] error_handler_ how to react on decoding errors + */ + serializer(output_adapter_t s, const char ichar, + error_handler_t error_handler_ = error_handler_t::strict) + : o(std::move(s)) + , loc(std::localeconv()) + , thousands_sep(loc->thousands_sep == nullptr ? '\0' : std::char_traits::to_char_type(* (loc->thousands_sep))) + , decimal_point(loc->decimal_point == nullptr ? '\0' : std::char_traits::to_char_type(* (loc->decimal_point))) + , indent_char(ichar) + , indent_string(512, indent_char) + , error_handler(error_handler_) + {} + + // delete because of pointer members + serializer(const serializer&) = delete; + serializer& operator=(const serializer&) = delete; + serializer(serializer&&) = delete; + serializer& operator=(serializer&&) = delete; + ~serializer() = default; + + /*! + @brief internal implementation of the serialization function + + This function is called by the public member function dump and organizes + the serialization internally. The indentation level is propagated as + additional parameter. In case of arrays and objects, the function is + called recursively. + + - strings and object keys are escaped using `escape_string()` + - integer numbers are converted implicitly via `operator<<` + - floating-point numbers are converted to a string using `"%g"` format + - binary values are serialized as objects containing the subtype and the + byte array + + @param[in] val value to serialize + @param[in] pretty_print whether the output shall be pretty-printed + @param[in] ensure_ascii If @a ensure_ascii is true, all non-ASCII characters + in the output are escaped with `\uXXXX` sequences, and the result consists + of ASCII characters only. + @param[in] indent_step the indent level + @param[in] current_indent the current indent level (only used internally) + */ + void dump(const BasicJsonType& val, + const bool pretty_print, + const bool ensure_ascii, + const unsigned int indent_step, + const unsigned int current_indent = 0) + { + switch (val.m_type) + { + case value_t::object: + { + if (val.m_value.object->empty()) + { + o->write_characters("{}", 2); + return; + } + + if (pretty_print) + { + o->write_characters("{\n", 2); + + // variable to hold indentation for recursive calls + const auto new_indent = current_indent + indent_step; + if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent)) + { + indent_string.resize(indent_string.size() * 2, ' '); + } + + // first n-1 elements + auto i = val.m_value.object->cbegin(); + for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i) + { + o->write_characters(indent_string.c_str(), new_indent); + o->write_character('\"'); + dump_escaped(i->first, ensure_ascii); + o->write_characters("\": ", 3); + dump(i->second, true, ensure_ascii, indent_step, new_indent); + o->write_characters(",\n", 2); + } + + // last element + JSON_ASSERT(i != val.m_value.object->cend()); + JSON_ASSERT(std::next(i) == val.m_value.object->cend()); + o->write_characters(indent_string.c_str(), new_indent); + o->write_character('\"'); + dump_escaped(i->first, ensure_ascii); + o->write_characters("\": ", 3); + dump(i->second, true, ensure_ascii, indent_step, new_indent); + + o->write_character('\n'); + o->write_characters(indent_string.c_str(), current_indent); + o->write_character('}'); + } + else + { + o->write_character('{'); + + // first n-1 elements + auto i = val.m_value.object->cbegin(); + for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i) + { + o->write_character('\"'); + dump_escaped(i->first, ensure_ascii); + o->write_characters("\":", 2); + dump(i->second, false, ensure_ascii, indent_step, current_indent); + o->write_character(','); + } + + // last element + JSON_ASSERT(i != val.m_value.object->cend()); + JSON_ASSERT(std::next(i) == val.m_value.object->cend()); + o->write_character('\"'); + dump_escaped(i->first, ensure_ascii); + o->write_characters("\":", 2); + dump(i->second, false, ensure_ascii, indent_step, current_indent); + + o->write_character('}'); + } + + return; + } + + case value_t::array: + { + if (val.m_value.array->empty()) + { + o->write_characters("[]", 2); + return; + } + + if (pretty_print) + { + o->write_characters("[\n", 2); + + // variable to hold indentation for recursive calls + const auto new_indent = current_indent + indent_step; + if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent)) + { + indent_string.resize(indent_string.size() * 2, ' '); + } + + // first n-1 elements + for (auto i = val.m_value.array->cbegin(); + i != val.m_value.array->cend() - 1; ++i) + { + o->write_characters(indent_string.c_str(), new_indent); + dump(*i, true, ensure_ascii, indent_step, new_indent); + o->write_characters(",\n", 2); + } + + // last element + JSON_ASSERT(!val.m_value.array->empty()); + o->write_characters(indent_string.c_str(), new_indent); + dump(val.m_value.array->back(), true, ensure_ascii, indent_step, new_indent); + + o->write_character('\n'); + o->write_characters(indent_string.c_str(), current_indent); + o->write_character(']'); + } + else + { + o->write_character('['); + + // first n-1 elements + for (auto i = val.m_value.array->cbegin(); + i != val.m_value.array->cend() - 1; ++i) + { + dump(*i, false, ensure_ascii, indent_step, current_indent); + o->write_character(','); + } + + // last element + JSON_ASSERT(!val.m_value.array->empty()); + dump(val.m_value.array->back(), false, ensure_ascii, indent_step, current_indent); + + o->write_character(']'); + } + + return; + } + + case value_t::string: + { + o->write_character('\"'); + dump_escaped(*val.m_value.string, ensure_ascii); + o->write_character('\"'); + return; + } + + case value_t::binary: + { + if (pretty_print) + { + o->write_characters("{\n", 2); + + // variable to hold indentation for recursive calls + const auto new_indent = current_indent + indent_step; + if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent)) + { + indent_string.resize(indent_string.size() * 2, ' '); + } + + o->write_characters(indent_string.c_str(), new_indent); + + o->write_characters("\"bytes\": [", 10); + + if (!val.m_value.binary->empty()) + { + for (auto i = val.m_value.binary->cbegin(); + i != val.m_value.binary->cend() - 1; ++i) + { + dump_integer(*i); + o->write_characters(", ", 2); + } + dump_integer(val.m_value.binary->back()); + } + + o->write_characters("],\n", 3); + o->write_characters(indent_string.c_str(), new_indent); + + o->write_characters("\"subtype\": ", 11); + if (val.m_value.binary->has_subtype()) + { + dump_integer(val.m_value.binary->subtype()); + } + else + { + o->write_characters("null", 4); + } + o->write_character('\n'); + o->write_characters(indent_string.c_str(), current_indent); + o->write_character('}'); + } + else + { + o->write_characters("{\"bytes\":[", 10); + + if (!val.m_value.binary->empty()) + { + for (auto i = val.m_value.binary->cbegin(); + i != val.m_value.binary->cend() - 1; ++i) + { + dump_integer(*i); + o->write_character(','); + } + dump_integer(val.m_value.binary->back()); + } + + o->write_characters("],\"subtype\":", 12); + if (val.m_value.binary->has_subtype()) + { + dump_integer(val.m_value.binary->subtype()); + o->write_character('}'); + } + else + { + o->write_characters("null}", 5); + } + } + return; + } + + case value_t::boolean: + { + if (val.m_value.boolean) + { + o->write_characters("true", 4); + } + else + { + o->write_characters("false", 5); + } + return; + } + + case value_t::number_integer: + { + dump_integer(val.m_value.number_integer); + return; + } + + case value_t::number_unsigned: + { + dump_integer(val.m_value.number_unsigned); + return; + } + + case value_t::number_float: + { + dump_float(val.m_value.number_float); + return; + } + + case value_t::discarded: + { + o->write_characters("", 11); + return; + } + + case value_t::null: + { + o->write_characters("null", 4); + return; + } + + default: // LCOV_EXCL_LINE + JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE + } + } + + JSON_PRIVATE_UNLESS_TESTED: + /*! + @brief dump escaped string + + Escape a string by replacing certain special characters by a sequence of an + escape character (backslash) and another character and other control + characters by a sequence of "\u" followed by a four-digit hex + representation. The escaped string is written to output stream @a o. + + @param[in] s the string to escape + @param[in] ensure_ascii whether to escape non-ASCII characters with + \uXXXX sequences + + @complexity Linear in the length of string @a s. + */ + void dump_escaped(const string_t& s, const bool ensure_ascii) + { + std::uint32_t codepoint{}; + std::uint8_t state = UTF8_ACCEPT; + std::size_t bytes = 0; // number of bytes written to string_buffer + + // number of bytes written at the point of the last valid byte + std::size_t bytes_after_last_accept = 0; + std::size_t undumped_chars = 0; + + for (std::size_t i = 0; i < s.size(); ++i) + { + const auto byte = static_cast(s[i]); + + switch (decode(state, codepoint, byte)) + { + case UTF8_ACCEPT: // decode found a new code point + { + switch (codepoint) + { + case 0x08: // backspace + { + string_buffer[bytes++] = '\\'; + string_buffer[bytes++] = 'b'; + break; + } + + case 0x09: // horizontal tab + { + string_buffer[bytes++] = '\\'; + string_buffer[bytes++] = 't'; + break; + } + + case 0x0A: // newline + { + string_buffer[bytes++] = '\\'; + string_buffer[bytes++] = 'n'; + break; + } + + case 0x0C: // formfeed + { + string_buffer[bytes++] = '\\'; + string_buffer[bytes++] = 'f'; + break; + } + + case 0x0D: // carriage return + { + string_buffer[bytes++] = '\\'; + string_buffer[bytes++] = 'r'; + break; + } + + case 0x22: // quotation mark + { + string_buffer[bytes++] = '\\'; + string_buffer[bytes++] = '\"'; + break; + } + + case 0x5C: // reverse solidus + { + string_buffer[bytes++] = '\\'; + string_buffer[bytes++] = '\\'; + break; + } + + default: + { + // escape control characters (0x00..0x1F) or, if + // ensure_ascii parameter is used, non-ASCII characters + if ((codepoint <= 0x1F) || (ensure_ascii && (codepoint >= 0x7F))) + { + if (codepoint <= 0xFFFF) + { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg) + (std::snprintf)(string_buffer.data() + bytes, 7, "\\u%04x", + static_cast(codepoint)); + bytes += 6; + } + else + { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg) + (std::snprintf)(string_buffer.data() + bytes, 13, "\\u%04x\\u%04x", + static_cast(0xD7C0u + (codepoint >> 10u)), + static_cast(0xDC00u + (codepoint & 0x3FFu))); + bytes += 12; + } + } + else + { + // copy byte to buffer (all previous bytes + // been copied have in default case above) + string_buffer[bytes++] = s[i]; + } + break; + } + } + + // write buffer and reset index; there must be 13 bytes + // left, as this is the maximal number of bytes to be + // written ("\uxxxx\uxxxx\0") for one code point + if (string_buffer.size() - bytes < 13) + { + o->write_characters(string_buffer.data(), bytes); + bytes = 0; + } + + // remember the byte position of this accept + bytes_after_last_accept = bytes; + undumped_chars = 0; + break; + } + + case UTF8_REJECT: // decode found invalid UTF-8 byte + { + switch (error_handler) + { + case error_handler_t::strict: + { + std::string sn(3, '\0'); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg) + (std::snprintf)(&sn[0], sn.size(), "%.2X", byte); + JSON_THROW(type_error::create(316, "invalid UTF-8 byte at index " + std::to_string(i) + ": 0x" + sn, BasicJsonType())); + } + + case error_handler_t::ignore: + case error_handler_t::replace: + { + // in case we saw this character the first time, we + // would like to read it again, because the byte + // may be OK for itself, but just not OK for the + // previous sequence + if (undumped_chars > 0) + { + --i; + } + + // reset length buffer to the last accepted index; + // thus removing/ignoring the invalid characters + bytes = bytes_after_last_accept; + + if (error_handler == error_handler_t::replace) + { + // add a replacement character + if (ensure_ascii) + { + string_buffer[bytes++] = '\\'; + string_buffer[bytes++] = 'u'; + string_buffer[bytes++] = 'f'; + string_buffer[bytes++] = 'f'; + string_buffer[bytes++] = 'f'; + string_buffer[bytes++] = 'd'; + } + else + { + string_buffer[bytes++] = detail::binary_writer::to_char_type('\xEF'); + string_buffer[bytes++] = detail::binary_writer::to_char_type('\xBF'); + string_buffer[bytes++] = detail::binary_writer::to_char_type('\xBD'); + } + + // write buffer and reset index; there must be 13 bytes + // left, as this is the maximal number of bytes to be + // written ("\uxxxx\uxxxx\0") for one code point + if (string_buffer.size() - bytes < 13) + { + o->write_characters(string_buffer.data(), bytes); + bytes = 0; + } + + bytes_after_last_accept = bytes; + } + + undumped_chars = 0; + + // continue processing the string + state = UTF8_ACCEPT; + break; + } + + default: // LCOV_EXCL_LINE + JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE + } + break; + } + + default: // decode found yet incomplete multi-byte code point + { + if (!ensure_ascii) + { + // code point will not be escaped - copy byte to buffer + string_buffer[bytes++] = s[i]; + } + ++undumped_chars; + break; + } + } + } + + // we finished processing the string + if (JSON_HEDLEY_LIKELY(state == UTF8_ACCEPT)) + { + // write buffer + if (bytes > 0) + { + o->write_characters(string_buffer.data(), bytes); + } + } + else + { + // we finish reading, but do not accept: string was incomplete + switch (error_handler) + { + case error_handler_t::strict: + { + std::string sn(3, '\0'); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg) + (std::snprintf)(&sn[0], sn.size(), "%.2X", static_cast(s.back())); + JSON_THROW(type_error::create(316, "incomplete UTF-8 string; last byte: 0x" + sn, BasicJsonType())); + } + + case error_handler_t::ignore: + { + // write all accepted bytes + o->write_characters(string_buffer.data(), bytes_after_last_accept); + break; + } + + case error_handler_t::replace: + { + // write all accepted bytes + o->write_characters(string_buffer.data(), bytes_after_last_accept); + // add a replacement character + if (ensure_ascii) + { + o->write_characters("\\ufffd", 6); + } + else + { + o->write_characters("\xEF\xBF\xBD", 3); + } + break; + } + + default: // LCOV_EXCL_LINE + JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE + } + } + } + + private: + /*! + @brief count digits + + Count the number of decimal (base 10) digits for an input unsigned integer. + + @param[in] x unsigned integer number to count its digits + @return number of decimal digits + */ + inline unsigned int count_digits(number_unsigned_t x) noexcept + { + unsigned int n_digits = 1; + for (;;) + { + if (x < 10) + { + return n_digits; + } + if (x < 100) + { + return n_digits + 1; + } + if (x < 1000) + { + return n_digits + 2; + } + if (x < 10000) + { + return n_digits + 3; + } + x = x / 10000u; + n_digits += 4; + } + } + + /*! + @brief dump an integer + + Dump a given integer to output stream @a o. Works internally with + @a number_buffer. + + @param[in] x integer number (signed or unsigned) to dump + @tparam NumberType either @a number_integer_t or @a number_unsigned_t + */ + template < typename NumberType, detail::enable_if_t < + std::is_same::value || + std::is_same::value || + std::is_same::value, + int > = 0 > + void dump_integer(NumberType x) + { + static constexpr std::array, 100> digits_to_99 + { + { + {{'0', '0'}}, {{'0', '1'}}, {{'0', '2'}}, {{'0', '3'}}, {{'0', '4'}}, {{'0', '5'}}, {{'0', '6'}}, {{'0', '7'}}, {{'0', '8'}}, {{'0', '9'}}, + {{'1', '0'}}, {{'1', '1'}}, {{'1', '2'}}, {{'1', '3'}}, {{'1', '4'}}, {{'1', '5'}}, {{'1', '6'}}, {{'1', '7'}}, {{'1', '8'}}, {{'1', '9'}}, + {{'2', '0'}}, {{'2', '1'}}, {{'2', '2'}}, {{'2', '3'}}, {{'2', '4'}}, {{'2', '5'}}, {{'2', '6'}}, {{'2', '7'}}, {{'2', '8'}}, {{'2', '9'}}, + {{'3', '0'}}, {{'3', '1'}}, {{'3', '2'}}, {{'3', '3'}}, {{'3', '4'}}, {{'3', '5'}}, {{'3', '6'}}, {{'3', '7'}}, {{'3', '8'}}, {{'3', '9'}}, + {{'4', '0'}}, {{'4', '1'}}, {{'4', '2'}}, {{'4', '3'}}, {{'4', '4'}}, {{'4', '5'}}, {{'4', '6'}}, {{'4', '7'}}, {{'4', '8'}}, {{'4', '9'}}, + {{'5', '0'}}, {{'5', '1'}}, {{'5', '2'}}, {{'5', '3'}}, {{'5', '4'}}, {{'5', '5'}}, {{'5', '6'}}, {{'5', '7'}}, {{'5', '8'}}, {{'5', '9'}}, + {{'6', '0'}}, {{'6', '1'}}, {{'6', '2'}}, {{'6', '3'}}, {{'6', '4'}}, {{'6', '5'}}, {{'6', '6'}}, {{'6', '7'}}, {{'6', '8'}}, {{'6', '9'}}, + {{'7', '0'}}, {{'7', '1'}}, {{'7', '2'}}, {{'7', '3'}}, {{'7', '4'}}, {{'7', '5'}}, {{'7', '6'}}, {{'7', '7'}}, {{'7', '8'}}, {{'7', '9'}}, + {{'8', '0'}}, {{'8', '1'}}, {{'8', '2'}}, {{'8', '3'}}, {{'8', '4'}}, {{'8', '5'}}, {{'8', '6'}}, {{'8', '7'}}, {{'8', '8'}}, {{'8', '9'}}, + {{'9', '0'}}, {{'9', '1'}}, {{'9', '2'}}, {{'9', '3'}}, {{'9', '4'}}, {{'9', '5'}}, {{'9', '6'}}, {{'9', '7'}}, {{'9', '8'}}, {{'9', '9'}}, + } + }; + + // special case for "0" + if (x == 0) + { + o->write_character('0'); + return; + } + + // use a pointer to fill the buffer + auto buffer_ptr = number_buffer.begin(); // NOLINT(llvm-qualified-auto,readability-qualified-auto,cppcoreguidelines-pro-type-vararg,hicpp-vararg) + + const bool is_negative = std::is_same::value && !(x >= 0); // see issue #755 + number_unsigned_t abs_value; + + unsigned int n_chars{}; + + if (is_negative) + { + *buffer_ptr = '-'; + abs_value = remove_sign(static_cast(x)); + + // account one more byte for the minus sign + n_chars = 1 + count_digits(abs_value); + } + else + { + abs_value = static_cast(x); + n_chars = count_digits(abs_value); + } + + // spare 1 byte for '\0' + JSON_ASSERT(n_chars < number_buffer.size() - 1); + + // jump to the end to generate the string from backward + // so we later avoid reversing the result + buffer_ptr += n_chars; + + // Fast int2ascii implementation inspired by "Fastware" talk by Andrei Alexandrescu + // See: https://www.youtube.com/watch?v=o4-CwDo2zpg + while (abs_value >= 100) + { + const auto digits_index = static_cast((abs_value % 100)); + abs_value /= 100; + *(--buffer_ptr) = digits_to_99[digits_index][1]; + *(--buffer_ptr) = digits_to_99[digits_index][0]; + } + + if (abs_value >= 10) + { + const auto digits_index = static_cast(abs_value); + *(--buffer_ptr) = digits_to_99[digits_index][1]; + *(--buffer_ptr) = digits_to_99[digits_index][0]; + } + else + { + *(--buffer_ptr) = static_cast('0' + abs_value); + } + + o->write_characters(number_buffer.data(), n_chars); + } + + /*! + @brief dump a floating-point number + + Dump a given floating-point number to output stream @a o. Works internally + with @a number_buffer. + + @param[in] x floating-point number to dump + */ + void dump_float(number_float_t x) + { + // NaN / inf + if (!std::isfinite(x)) + { + o->write_characters("null", 4); + return; + } + + // If number_float_t is an IEEE-754 single or double precision number, + // use the Grisu2 algorithm to produce short numbers which are + // guaranteed to round-trip, using strtof and strtod, resp. + // + // NB: The test below works if == . + static constexpr bool is_ieee_single_or_double + = (std::numeric_limits::is_iec559 && std::numeric_limits::digits == 24 && std::numeric_limits::max_exponent == 128) || + (std::numeric_limits::is_iec559 && std::numeric_limits::digits == 53 && std::numeric_limits::max_exponent == 1024); + + dump_float(x, std::integral_constant()); + } + + void dump_float(number_float_t x, std::true_type /*is_ieee_single_or_double*/) + { + auto* begin = number_buffer.data(); + auto* end = ::nlohmann::detail::to_chars(begin, begin + number_buffer.size(), x); + + o->write_characters(begin, static_cast(end - begin)); + } + + void dump_float(number_float_t x, std::false_type /*is_ieee_single_or_double*/) + { + // get number of digits for a float -> text -> float round-trip + static constexpr auto d = std::numeric_limits::max_digits10; + + // the actual conversion + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg) + std::ptrdiff_t len = (std::snprintf)(number_buffer.data(), number_buffer.size(), "%.*g", d, x); + + // negative value indicates an error + JSON_ASSERT(len > 0); + // check if buffer was large enough + JSON_ASSERT(static_cast(len) < number_buffer.size()); + + // erase thousands separator + if (thousands_sep != '\0') + { + auto* const end = std::remove(number_buffer.begin(), + number_buffer.begin() + len, thousands_sep); + std::fill(end, number_buffer.end(), '\0'); + JSON_ASSERT((end - number_buffer.begin()) <= len); + len = (end - number_buffer.begin()); + } + + // convert decimal point to '.' + if (decimal_point != '\0' && decimal_point != '.') + { + auto* const dec_pos = std::find(number_buffer.begin(), number_buffer.end(), decimal_point); + if (dec_pos != number_buffer.end()) + { + *dec_pos = '.'; + } + } + + o->write_characters(number_buffer.data(), static_cast(len)); + + // determine if need to append ".0" + const bool value_is_int_like = + std::none_of(number_buffer.begin(), number_buffer.begin() + len + 1, + [](char c) + { + return c == '.' || c == 'e'; + }); + + if (value_is_int_like) + { + o->write_characters(".0", 2); + } + } + + /*! + @brief check whether a string is UTF-8 encoded + + The function checks each byte of a string whether it is UTF-8 encoded. The + result of the check is stored in the @a state parameter. The function must + be called initially with state 0 (accept). State 1 means the string must + be rejected, because the current byte is not allowed. If the string is + completely processed, but the state is non-zero, the string ended + prematurely; that is, the last byte indicated more bytes should have + followed. + + @param[in,out] state the state of the decoding + @param[in,out] codep codepoint (valid only if resulting state is UTF8_ACCEPT) + @param[in] byte next byte to decode + @return new state + + @note The function has been edited: a std::array is used. + + @copyright Copyright (c) 2008-2009 Bjoern Hoehrmann + @sa http://bjoern.hoehrmann.de/utf-8/decoder/dfa/ + */ + static std::uint8_t decode(std::uint8_t& state, std::uint32_t& codep, const std::uint8_t byte) noexcept + { + static const std::array utf8d = + { + { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 00..1F + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 20..3F + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 40..5F + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 60..7F + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, // 80..9F + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, // A0..BF + 8, 8, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // C0..DF + 0xA, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x4, 0x3, 0x3, // E0..EF + 0xB, 0x6, 0x6, 0x6, 0x5, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, // F0..FF + 0x0, 0x1, 0x2, 0x3, 0x5, 0x8, 0x7, 0x1, 0x1, 0x1, 0x4, 0x6, 0x1, 0x1, 0x1, 0x1, // s0..s0 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, // s1..s2 + 1, 2, 1, 1, 1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, // s3..s4 + 1, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, // s5..s6 + 1, 3, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // s7..s8 + } + }; + + JSON_ASSERT(byte < utf8d.size()); + const std::uint8_t type = utf8d[byte]; + + codep = (state != UTF8_ACCEPT) + ? (byte & 0x3fu) | (codep << 6u) + : (0xFFu >> type) & (byte); + + std::size_t index = 256u + static_cast(state) * 16u + static_cast(type); + JSON_ASSERT(index < 400); + state = utf8d[index]; + return state; + } + + /* + * Overload to make the compiler happy while it is instantiating + * dump_integer for number_unsigned_t. + * Must never be called. + */ + number_unsigned_t remove_sign(number_unsigned_t x) + { + JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE + return x; // LCOV_EXCL_LINE + } + + /* + * Helper function for dump_integer + * + * This function takes a negative signed integer and returns its absolute + * value as unsigned integer. The plus/minus shuffling is necessary as we can + * not directly remove the sign of an arbitrary signed integer as the + * absolute values of INT_MIN and INT_MAX are usually not the same. See + * #1708 for details. + */ + inline number_unsigned_t remove_sign(number_integer_t x) noexcept + { + JSON_ASSERT(x < 0 && x < (std::numeric_limits::max)()); // NOLINT(misc-redundant-expression) + return static_cast(-(x + 1)) + 1; + } + + private: + /// the output of the serializer + output_adapter_t o = nullptr; + + /// a (hopefully) large enough character buffer + std::array number_buffer{{}}; + + /// the locale + const std::lconv* loc = nullptr; + /// the locale's thousand separator character + const char thousands_sep = '\0'; + /// the locale's decimal point character + const char decimal_point = '\0'; + + /// string buffer + std::array string_buffer{{}}; + + /// the indentation character + const char indent_char; + /// the indentation string + string_t indent_string; + + /// error_handler how to react on decoding errors + const error_handler_t error_handler; +}; +} // namespace detail +} // namespace nlohmann + +// #include + +// #include + +// #include + + +#include // less +#include // initializer_list +#include // input_iterator_tag, iterator_traits +#include // allocator +#include // for out_of_range +#include // enable_if, is_convertible +#include // pair +#include // vector + +// #include + + +namespace nlohmann +{ + +/// ordered_map: a minimal map-like container that preserves insertion order +/// for use within nlohmann::basic_json +template , + class Allocator = std::allocator>> + struct ordered_map : std::vector, Allocator> +{ + using key_type = Key; + using mapped_type = T; + using Container = std::vector, Allocator>; + using typename Container::iterator; + using typename Container::const_iterator; + using typename Container::size_type; + using typename Container::value_type; + + // Explicit constructors instead of `using Container::Container` + // otherwise older compilers choke on it (GCC <= 5.5, xcode <= 9.4) + ordered_map(const Allocator& alloc = Allocator()) : Container{alloc} {} + template + ordered_map(It first, It last, const Allocator& alloc = Allocator()) + : Container{first, last, alloc} {} + ordered_map(std::initializer_list init, const Allocator& alloc = Allocator() ) + : Container{init, alloc} {} + + std::pair emplace(const key_type& key, T&& t) + { + for (auto it = this->begin(); it != this->end(); ++it) + { + if (it->first == key) + { + return {it, false}; + } + } + Container::emplace_back(key, t); + return {--this->end(), true}; + } + + T& operator[](const Key& key) + { + return emplace(key, T{}).first->second; + } + + const T& operator[](const Key& key) const + { + return at(key); + } + + T& at(const Key& key) + { + for (auto it = this->begin(); it != this->end(); ++it) + { + if (it->first == key) + { + return it->second; + } + } + + JSON_THROW(std::out_of_range("key not found")); + } + + const T& at(const Key& key) const + { + for (auto it = this->begin(); it != this->end(); ++it) + { + if (it->first == key) + { + return it->second; + } + } + + JSON_THROW(std::out_of_range("key not found")); + } + + size_type erase(const Key& key) + { + for (auto it = this->begin(); it != this->end(); ++it) + { + if (it->first == key) + { + // Since we cannot move const Keys, re-construct them in place + for (auto next = it; ++next != this->end(); ++it) + { + it->~value_type(); // Destroy but keep allocation + new (&*it) value_type{std::move(*next)}; + } + Container::pop_back(); + return 1; + } + } + return 0; + } + + iterator erase(iterator pos) + { + auto it = pos; + + // Since we cannot move const Keys, re-construct them in place + for (auto next = it; ++next != this->end(); ++it) + { + it->~value_type(); // Destroy but keep allocation + new (&*it) value_type{std::move(*next)}; + } + Container::pop_back(); + return pos; + } + + size_type count(const Key& key) const + { + for (auto it = this->begin(); it != this->end(); ++it) + { + if (it->first == key) + { + return 1; + } + } + return 0; + } + + iterator find(const Key& key) + { + for (auto it = this->begin(); it != this->end(); ++it) + { + if (it->first == key) + { + return it; + } + } + return Container::end(); + } + + const_iterator find(const Key& key) const + { + for (auto it = this->begin(); it != this->end(); ++it) + { + if (it->first == key) + { + return it; + } + } + return Container::end(); + } + + std::pair insert( value_type&& value ) + { + return emplace(value.first, std::move(value.second)); + } + + std::pair insert( const value_type& value ) + { + for (auto it = this->begin(); it != this->end(); ++it) + { + if (it->first == value.first) + { + return {it, false}; + } + } + Container::push_back(value); + return {--this->end(), true}; + } + + template + using require_input_iter = typename std::enable_if::iterator_category, + std::input_iterator_tag>::value>::type; + + template> + void insert(InputIt first, InputIt last) + { + for (auto it = first; it != last; ++it) + { + insert(*it); + } + } +}; + +} // namespace nlohmann + + +#if defined(JSON_HAS_CPP_17) + #include +#endif + +/*! +@brief namespace for Niels Lohmann +@see https://github.com/nlohmann +@since version 1.0.0 +*/ +namespace nlohmann +{ + +/*! +@brief a class to store JSON values + +@tparam ObjectType type for JSON objects (`std::map` by default; will be used +in @ref object_t) +@tparam ArrayType type for JSON arrays (`std::vector` by default; will be used +in @ref array_t) +@tparam StringType type for JSON strings and object keys (`std::string` by +default; will be used in @ref string_t) +@tparam BooleanType type for JSON booleans (`bool` by default; will be used +in @ref boolean_t) +@tparam NumberIntegerType type for JSON integer numbers (`int64_t` by +default; will be used in @ref number_integer_t) +@tparam NumberUnsignedType type for JSON unsigned integer numbers (@c +`uint64_t` by default; will be used in @ref number_unsigned_t) +@tparam NumberFloatType type for JSON floating-point numbers (`double` by +default; will be used in @ref number_float_t) +@tparam BinaryType type for packed binary data for compatibility with binary +serialization formats (`std::vector` by default; will be used in +@ref binary_t) +@tparam AllocatorType type of the allocator to use (`std::allocator` by +default) +@tparam JSONSerializer the serializer to resolve internal calls to `to_json()` +and `from_json()` (@ref adl_serializer by default) + +@requirement The class satisfies the following concept requirements: +- Basic + - [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible): + JSON values can be default constructed. The result will be a JSON null + value. + - [MoveConstructible](https://en.cppreference.com/w/cpp/named_req/MoveConstructible): + A JSON value can be constructed from an rvalue argument. + - [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible): + A JSON value can be copy-constructed from an lvalue expression. + - [MoveAssignable](https://en.cppreference.com/w/cpp/named_req/MoveAssignable): + A JSON value van be assigned from an rvalue argument. + - [CopyAssignable](https://en.cppreference.com/w/cpp/named_req/CopyAssignable): + A JSON value can be copy-assigned from an lvalue expression. + - [Destructible](https://en.cppreference.com/w/cpp/named_req/Destructible): + JSON values can be destructed. +- Layout + - [StandardLayoutType](https://en.cppreference.com/w/cpp/named_req/StandardLayoutType): + JSON values have + [standard layout](https://en.cppreference.com/w/cpp/language/data_members#Standard_layout): + All non-static data members are private and standard layout types, the + class has no virtual functions or (virtual) base classes. +- Library-wide + - [EqualityComparable](https://en.cppreference.com/w/cpp/named_req/EqualityComparable): + JSON values can be compared with `==`, see @ref + operator==(const_reference,const_reference). + - [LessThanComparable](https://en.cppreference.com/w/cpp/named_req/LessThanComparable): + JSON values can be compared with `<`, see @ref + operator<(const_reference,const_reference). + - [Swappable](https://en.cppreference.com/w/cpp/named_req/Swappable): + Any JSON lvalue or rvalue of can be swapped with any lvalue or rvalue of + other compatible types, using unqualified function call @ref swap(). + - [NullablePointer](https://en.cppreference.com/w/cpp/named_req/NullablePointer): + JSON values can be compared against `std::nullptr_t` objects which are used + to model the `null` value. +- Container + - [Container](https://en.cppreference.com/w/cpp/named_req/Container): + JSON values can be used like STL containers and provide iterator access. + - [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer); + JSON values can be used like STL containers and provide reverse iterator + access. + +@invariant The member variables @a m_value and @a m_type have the following +relationship: +- If `m_type == value_t::object`, then `m_value.object != nullptr`. +- If `m_type == value_t::array`, then `m_value.array != nullptr`. +- If `m_type == value_t::string`, then `m_value.string != nullptr`. +The invariants are checked by member function assert_invariant(). + +@internal +@note ObjectType trick from https://stackoverflow.com/a/9860911 +@endinternal + +@see [RFC 8259: The JavaScript Object Notation (JSON) Data Interchange +Format](https://tools.ietf.org/html/rfc8259) + +@since version 1.0.0 + +@nosubgrouping +*/ +NLOHMANN_BASIC_JSON_TPL_DECLARATION +class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-special-member-functions) +{ + private: + template friend struct detail::external_constructor; + friend ::nlohmann::json_pointer; + + template + friend class ::nlohmann::detail::parser; + friend ::nlohmann::detail::serializer; + template + friend class ::nlohmann::detail::iter_impl; + template + friend class ::nlohmann::detail::binary_writer; + template + friend class ::nlohmann::detail::binary_reader; + template + friend class ::nlohmann::detail::json_sax_dom_parser; + template + friend class ::nlohmann::detail::json_sax_dom_callback_parser; + friend class ::nlohmann::detail::exception; + + /// workaround type for MSVC + using basic_json_t = NLOHMANN_BASIC_JSON_TPL; + + JSON_PRIVATE_UNLESS_TESTED: + // convenience aliases for types residing in namespace detail; + using lexer = ::nlohmann::detail::lexer_base; + + template + static ::nlohmann::detail::parser parser( + InputAdapterType adapter, + detail::parser_callback_tcb = nullptr, + const bool allow_exceptions = true, + const bool ignore_comments = false + ) + { + return ::nlohmann::detail::parser(std::move(adapter), + std::move(cb), allow_exceptions, ignore_comments); + } + + private: + using primitive_iterator_t = ::nlohmann::detail::primitive_iterator_t; + template + using internal_iterator = ::nlohmann::detail::internal_iterator; + template + using iter_impl = ::nlohmann::detail::iter_impl; + template + using iteration_proxy = ::nlohmann::detail::iteration_proxy; + template using json_reverse_iterator = ::nlohmann::detail::json_reverse_iterator; + + template + using output_adapter_t = ::nlohmann::detail::output_adapter_t; + + template + using binary_reader = ::nlohmann::detail::binary_reader; + template using binary_writer = ::nlohmann::detail::binary_writer; + + JSON_PRIVATE_UNLESS_TESTED: + using serializer = ::nlohmann::detail::serializer; + + public: + using value_t = detail::value_t; + /// JSON Pointer, see @ref nlohmann::json_pointer + using json_pointer = ::nlohmann::json_pointer; + template + using json_serializer = JSONSerializer; + /// how to treat decoding errors + using error_handler_t = detail::error_handler_t; + /// how to treat CBOR tags + using cbor_tag_handler_t = detail::cbor_tag_handler_t; + /// helper type for initializer lists of basic_json values + using initializer_list_t = std::initializer_list>; + + using input_format_t = detail::input_format_t; + /// SAX interface type, see @ref nlohmann::json_sax + using json_sax_t = json_sax; + + //////////////// + // exceptions // + //////////////// + + /// @name exceptions + /// Classes to implement user-defined exceptions. + /// @{ + + /// @copydoc detail::exception + using exception = detail::exception; + /// @copydoc detail::parse_error + using parse_error = detail::parse_error; + /// @copydoc detail::invalid_iterator + using invalid_iterator = detail::invalid_iterator; + /// @copydoc detail::type_error + using type_error = detail::type_error; + /// @copydoc detail::out_of_range + using out_of_range = detail::out_of_range; + /// @copydoc detail::other_error + using other_error = detail::other_error; + + /// @} + + + ///////////////////// + // container types // + ///////////////////// + + /// @name container types + /// The canonic container types to use @ref basic_json like any other STL + /// container. + /// @{ + + /// the type of elements in a basic_json container + using value_type = basic_json; + + /// the type of an element reference + using reference = value_type&; + /// the type of an element const reference + using const_reference = const value_type&; + + /// a type to represent differences between iterators + using difference_type = std::ptrdiff_t; + /// a type to represent container sizes + using size_type = std::size_t; + + /// the allocator type + using allocator_type = AllocatorType; + + /// the type of an element pointer + using pointer = typename std::allocator_traits::pointer; + /// the type of an element const pointer + using const_pointer = typename std::allocator_traits::const_pointer; + + /// an iterator for a basic_json container + using iterator = iter_impl; + /// a const iterator for a basic_json container + using const_iterator = iter_impl; + /// a reverse iterator for a basic_json container + using reverse_iterator = json_reverse_iterator; + /// a const reverse iterator for a basic_json container + using const_reverse_iterator = json_reverse_iterator; + + /// @} + + + /*! + @brief returns the allocator associated with the container + */ + static allocator_type get_allocator() + { + return allocator_type(); + } + + /*! + @brief returns version information on the library + + This function returns a JSON object with information about the library, + including the version number and information on the platform and compiler. + + @return JSON object holding version information + key | description + ----------- | --------------- + `compiler` | Information on the used compiler. It is an object with the following keys: `c++` (the used C++ standard), `family` (the compiler family; possible values are `clang`, `icc`, `gcc`, `ilecpp`, `msvc`, `pgcpp`, `sunpro`, and `unknown`), and `version` (the compiler version). + `copyright` | The copyright line for the library as string. + `name` | The name of the library as string. + `platform` | The used platform as string. Possible values are `win32`, `linux`, `apple`, `unix`, and `unknown`. + `url` | The URL of the project as string. + `version` | The version of the library. It is an object with the following keys: `major`, `minor`, and `patch` as defined by [Semantic Versioning](http://semver.org), and `string` (the version string). + + @liveexample{The following code shows an example output of the `meta()` + function.,meta} + + @exceptionsafety Strong guarantee: if an exception is thrown, there are no + changes to any JSON value. + + @complexity Constant. + + @since 2.1.0 + */ + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json meta() + { + basic_json result; + + result["copyright"] = "(C) 2013-2021 Niels Lohmann"; + result["name"] = "JSON for Modern C++"; + result["url"] = "https://github.com/nlohmann/json"; + result["version"]["string"] = + std::to_string(NLOHMANN_JSON_VERSION_MAJOR) + "." + + std::to_string(NLOHMANN_JSON_VERSION_MINOR) + "." + + std::to_string(NLOHMANN_JSON_VERSION_PATCH); + result["version"]["major"] = NLOHMANN_JSON_VERSION_MAJOR; + result["version"]["minor"] = NLOHMANN_JSON_VERSION_MINOR; + result["version"]["patch"] = NLOHMANN_JSON_VERSION_PATCH; + +#ifdef _WIN32 + result["platform"] = "win32"; +#elif defined __linux__ + result["platform"] = "linux"; +#elif defined __APPLE__ + result["platform"] = "apple"; +#elif defined __unix__ + result["platform"] = "unix"; +#else + result["platform"] = "unknown"; +#endif + +#if defined(__ICC) || defined(__INTEL_COMPILER) + result["compiler"] = {{"family", "icc"}, {"version", __INTEL_COMPILER}}; +#elif defined(__clang__) + result["compiler"] = {{"family", "clang"}, {"version", __clang_version__}}; +#elif defined(__GNUC__) || defined(__GNUG__) + result["compiler"] = {{"family", "gcc"}, {"version", std::to_string(__GNUC__) + "." + std::to_string(__GNUC_MINOR__) + "." + std::to_string(__GNUC_PATCHLEVEL__)}}; +#elif defined(__HP_cc) || defined(__HP_aCC) + result["compiler"] = "hp" +#elif defined(__IBMCPP__) + result["compiler"] = {{"family", "ilecpp"}, {"version", __IBMCPP__}}; +#elif defined(_MSC_VER) + result["compiler"] = {{"family", "msvc"}, {"version", _MSC_VER}}; +#elif defined(__PGI) + result["compiler"] = {{"family", "pgcpp"}, {"version", __PGI}}; +#elif defined(__SUNPRO_CC) + result["compiler"] = {{"family", "sunpro"}, {"version", __SUNPRO_CC}}; +#else + result["compiler"] = {{"family", "unknown"}, {"version", "unknown"}}; +#endif + +#ifdef __cplusplus + result["compiler"]["c++"] = std::to_string(__cplusplus); +#else + result["compiler"]["c++"] = "unknown"; +#endif + return result; + } + + + /////////////////////////// + // JSON value data types // + /////////////////////////// + + /// @name JSON value data types + /// The data types to store a JSON value. These types are derived from + /// the template arguments passed to class @ref basic_json. + /// @{ + +#if defined(JSON_HAS_CPP_14) + // Use transparent comparator if possible, combined with perfect forwarding + // on find() and count() calls prevents unnecessary string construction. + using object_comparator_t = std::less<>; +#else + using object_comparator_t = std::less; +#endif + + /*! + @brief a type for an object + + [RFC 8259](https://tools.ietf.org/html/rfc8259) describes JSON objects as follows: + > An object is an unordered collection of zero or more name/value pairs, + > where a name is a string and a value is a string, number, boolean, null, + > object, or array. + + To store objects in C++, a type is defined by the template parameters + described below. + + @tparam ObjectType the container to store objects (e.g., `std::map` or + `std::unordered_map`) + @tparam StringType the type of the keys or names (e.g., `std::string`). + The comparison function `std::less` is used to order elements + inside the container. + @tparam AllocatorType the allocator to use for objects (e.g., + `std::allocator`) + + #### Default type + + With the default values for @a ObjectType (`std::map`), @a StringType + (`std::string`), and @a AllocatorType (`std::allocator`), the default + value for @a object_t is: + + @code {.cpp} + std::map< + std::string, // key_type + basic_json, // value_type + std::less, // key_compare + std::allocator> // allocator_type + > + @endcode + + #### Behavior + + The choice of @a object_t influences the behavior of the JSON class. With + the default type, objects have the following behavior: + + - When all names are unique, objects will be interoperable in the sense + that all software implementations receiving that object will agree on + the name-value mappings. + - When the names within an object are not unique, it is unspecified which + one of the values for a given key will be chosen. For instance, + `{"key": 2, "key": 1}` could be equal to either `{"key": 1}` or + `{"key": 2}`. + - Internally, name/value pairs are stored in lexicographical order of the + names. Objects will also be serialized (see @ref dump) in this order. + For instance, `{"b": 1, "a": 2}` and `{"a": 2, "b": 1}` will be stored + and serialized as `{"a": 2, "b": 1}`. + - When comparing objects, the order of the name/value pairs is irrelevant. + This makes objects interoperable in the sense that they will not be + affected by these differences. For instance, `{"b": 1, "a": 2}` and + `{"a": 2, "b": 1}` will be treated as equal. + + #### Limits + + [RFC 8259](https://tools.ietf.org/html/rfc8259) specifies: + > An implementation may set limits on the maximum depth of nesting. + + In this class, the object's limit of nesting is not explicitly constrained. + However, a maximum depth of nesting may be introduced by the compiler or + runtime environment. A theoretical limit can be queried by calling the + @ref max_size function of a JSON object. + + #### Storage + + Objects are stored as pointers in a @ref basic_json type. That is, for any + access to object values, a pointer of type `object_t*` must be + dereferenced. + + @sa see @ref array_t -- type for an array value + + @since version 1.0.0 + + @note The order name/value pairs are added to the object is *not* + preserved by the library. Therefore, iterating an object may return + name/value pairs in a different order than they were originally stored. In + fact, keys will be traversed in alphabetical order as `std::map` with + `std::less` is used by default. Please note this behavior conforms to [RFC + 8259](https://tools.ietf.org/html/rfc8259), because any order implements the + specified "unordered" nature of JSON objects. + */ + using object_t = ObjectType>>; + + /*! + @brief a type for an array + + [RFC 8259](https://tools.ietf.org/html/rfc8259) describes JSON arrays as follows: + > An array is an ordered sequence of zero or more values. + + To store objects in C++, a type is defined by the template parameters + explained below. + + @tparam ArrayType container type to store arrays (e.g., `std::vector` or + `std::list`) + @tparam AllocatorType allocator to use for arrays (e.g., `std::allocator`) + + #### Default type + + With the default values for @a ArrayType (`std::vector`) and @a + AllocatorType (`std::allocator`), the default value for @a array_t is: + + @code {.cpp} + std::vector< + basic_json, // value_type + std::allocator // allocator_type + > + @endcode + + #### Limits + + [RFC 8259](https://tools.ietf.org/html/rfc8259) specifies: + > An implementation may set limits on the maximum depth of nesting. + + In this class, the array's limit of nesting is not explicitly constrained. + However, a maximum depth of nesting may be introduced by the compiler or + runtime environment. A theoretical limit can be queried by calling the + @ref max_size function of a JSON array. + + #### Storage + + Arrays are stored as pointers in a @ref basic_json type. That is, for any + access to array values, a pointer of type `array_t*` must be dereferenced. + + @sa see @ref object_t -- type for an object value + + @since version 1.0.0 + */ + using array_t = ArrayType>; + + /*! + @brief a type for a string + + [RFC 8259](https://tools.ietf.org/html/rfc8259) describes JSON strings as follows: + > A string is a sequence of zero or more Unicode characters. + + To store objects in C++, a type is defined by the template parameter + described below. Unicode values are split by the JSON class into + byte-sized characters during deserialization. + + @tparam StringType the container to store strings (e.g., `std::string`). + Note this container is used for keys/names in objects, see @ref object_t. + + #### Default type + + With the default values for @a StringType (`std::string`), the default + value for @a string_t is: + + @code {.cpp} + std::string + @endcode + + #### Encoding + + Strings are stored in UTF-8 encoding. Therefore, functions like + `std::string::size()` or `std::string::length()` return the number of + bytes in the string rather than the number of characters or glyphs. + + #### String comparison + + [RFC 8259](https://tools.ietf.org/html/rfc8259) states: + > Software implementations are typically required to test names of object + > members for equality. Implementations that transform the textual + > representation into sequences of Unicode code units and then perform the + > comparison numerically, code unit by code unit, are interoperable in the + > sense that implementations will agree in all cases on equality or + > inequality of two strings. For example, implementations that compare + > strings with escaped characters unconverted may incorrectly find that + > `"a\\b"` and `"a\u005Cb"` are not equal. + + This implementation is interoperable as it does compare strings code unit + by code unit. + + #### Storage + + String values are stored as pointers in a @ref basic_json type. That is, + for any access to string values, a pointer of type `string_t*` must be + dereferenced. + + @since version 1.0.0 + */ + using string_t = StringType; + + /*! + @brief a type for a boolean + + [RFC 8259](https://tools.ietf.org/html/rfc8259) implicitly describes a boolean as a + type which differentiates the two literals `true` and `false`. + + To store objects in C++, a type is defined by the template parameter @a + BooleanType which chooses the type to use. + + #### Default type + + With the default values for @a BooleanType (`bool`), the default value for + @a boolean_t is: + + @code {.cpp} + bool + @endcode + + #### Storage + + Boolean values are stored directly inside a @ref basic_json type. + + @since version 1.0.0 + */ + using boolean_t = BooleanType; + + /*! + @brief a type for a number (integer) + + [RFC 8259](https://tools.ietf.org/html/rfc8259) describes numbers as follows: + > The representation of numbers is similar to that used in most + > programming languages. A number is represented in base 10 using decimal + > digits. It contains an integer component that may be prefixed with an + > optional minus sign, which may be followed by a fraction part and/or an + > exponent part. Leading zeros are not allowed. (...) Numeric values that + > cannot be represented in the grammar below (such as Infinity and NaN) + > are not permitted. + + This description includes both integer and floating-point numbers. + However, C++ allows more precise storage if it is known whether the number + is a signed integer, an unsigned integer or a floating-point number. + Therefore, three different types, @ref number_integer_t, @ref + number_unsigned_t and @ref number_float_t are used. + + To store integer numbers in C++, a type is defined by the template + parameter @a NumberIntegerType which chooses the type to use. + + #### Default type + + With the default values for @a NumberIntegerType (`int64_t`), the default + value for @a number_integer_t is: + + @code {.cpp} + int64_t + @endcode + + #### Default behavior + + - The restrictions about leading zeros is not enforced in C++. Instead, + leading zeros in integer literals lead to an interpretation as octal + number. Internally, the value will be stored as decimal number. For + instance, the C++ integer literal `010` will be serialized to `8`. + During deserialization, leading zeros yield an error. + - Not-a-number (NaN) values will be serialized to `null`. + + #### Limits + + [RFC 8259](https://tools.ietf.org/html/rfc8259) specifies: + > An implementation may set limits on the range and precision of numbers. + + When the default type is used, the maximal integer number that can be + stored is `9223372036854775807` (INT64_MAX) and the minimal integer number + that can be stored is `-9223372036854775808` (INT64_MIN). Integer numbers + that are out of range will yield over/underflow when used in a + constructor. During deserialization, too large or small integer numbers + will be automatically be stored as @ref number_unsigned_t or @ref + number_float_t. + + [RFC 8259](https://tools.ietf.org/html/rfc8259) further states: + > Note that when such software is used, numbers that are integers and are + > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense + > that implementations will agree exactly on their numeric values. + + As this range is a subrange of the exactly supported range [INT64_MIN, + INT64_MAX], this class's integer type is interoperable. + + #### Storage + + Integer number values are stored directly inside a @ref basic_json type. + + @sa see @ref number_float_t -- type for number values (floating-point) + + @sa see @ref number_unsigned_t -- type for number values (unsigned integer) + + @since version 1.0.0 + */ + using number_integer_t = NumberIntegerType; + + /*! + @brief a type for a number (unsigned) + + [RFC 8259](https://tools.ietf.org/html/rfc8259) describes numbers as follows: + > The representation of numbers is similar to that used in most + > programming languages. A number is represented in base 10 using decimal + > digits. It contains an integer component that may be prefixed with an + > optional minus sign, which may be followed by a fraction part and/or an + > exponent part. Leading zeros are not allowed. (...) Numeric values that + > cannot be represented in the grammar below (such as Infinity and NaN) + > are not permitted. + + This description includes both integer and floating-point numbers. + However, C++ allows more precise storage if it is known whether the number + is a signed integer, an unsigned integer or a floating-point number. + Therefore, three different types, @ref number_integer_t, @ref + number_unsigned_t and @ref number_float_t are used. + + To store unsigned integer numbers in C++, a type is defined by the + template parameter @a NumberUnsignedType which chooses the type to use. + + #### Default type + + With the default values for @a NumberUnsignedType (`uint64_t`), the + default value for @a number_unsigned_t is: + + @code {.cpp} + uint64_t + @endcode + + #### Default behavior + + - The restrictions about leading zeros is not enforced in C++. Instead, + leading zeros in integer literals lead to an interpretation as octal + number. Internally, the value will be stored as decimal number. For + instance, the C++ integer literal `010` will be serialized to `8`. + During deserialization, leading zeros yield an error. + - Not-a-number (NaN) values will be serialized to `null`. + + #### Limits + + [RFC 8259](https://tools.ietf.org/html/rfc8259) specifies: + > An implementation may set limits on the range and precision of numbers. + + When the default type is used, the maximal integer number that can be + stored is `18446744073709551615` (UINT64_MAX) and the minimal integer + number that can be stored is `0`. Integer numbers that are out of range + will yield over/underflow when used in a constructor. During + deserialization, too large or small integer numbers will be automatically + be stored as @ref number_integer_t or @ref number_float_t. + + [RFC 8259](https://tools.ietf.org/html/rfc8259) further states: + > Note that when such software is used, numbers that are integers and are + > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense + > that implementations will agree exactly on their numeric values. + + As this range is a subrange (when considered in conjunction with the + number_integer_t type) of the exactly supported range [0, UINT64_MAX], + this class's integer type is interoperable. + + #### Storage + + Integer number values are stored directly inside a @ref basic_json type. + + @sa see @ref number_float_t -- type for number values (floating-point) + @sa see @ref number_integer_t -- type for number values (integer) + + @since version 2.0.0 + */ + using number_unsigned_t = NumberUnsignedType; + + /*! + @brief a type for a number (floating-point) + + [RFC 8259](https://tools.ietf.org/html/rfc8259) describes numbers as follows: + > The representation of numbers is similar to that used in most + > programming languages. A number is represented in base 10 using decimal + > digits. It contains an integer component that may be prefixed with an + > optional minus sign, which may be followed by a fraction part and/or an + > exponent part. Leading zeros are not allowed. (...) Numeric values that + > cannot be represented in the grammar below (such as Infinity and NaN) + > are not permitted. + + This description includes both integer and floating-point numbers. + However, C++ allows more precise storage if it is known whether the number + is a signed integer, an unsigned integer or a floating-point number. + Therefore, three different types, @ref number_integer_t, @ref + number_unsigned_t and @ref number_float_t are used. + + To store floating-point numbers in C++, a type is defined by the template + parameter @a NumberFloatType which chooses the type to use. + + #### Default type + + With the default values for @a NumberFloatType (`double`), the default + value for @a number_float_t is: + + @code {.cpp} + double + @endcode + + #### Default behavior + + - The restrictions about leading zeros is not enforced in C++. Instead, + leading zeros in floating-point literals will be ignored. Internally, + the value will be stored as decimal number. For instance, the C++ + floating-point literal `01.2` will be serialized to `1.2`. During + deserialization, leading zeros yield an error. + - Not-a-number (NaN) values will be serialized to `null`. + + #### Limits + + [RFC 8259](https://tools.ietf.org/html/rfc8259) states: + > This specification allows implementations to set limits on the range and + > precision of numbers accepted. Since software that implements IEEE + > 754-2008 binary64 (double precision) numbers is generally available and + > widely used, good interoperability can be achieved by implementations + > that expect no more precision or range than these provide, in the sense + > that implementations will approximate JSON numbers within the expected + > precision. + + This implementation does exactly follow this approach, as it uses double + precision floating-point numbers. Note values smaller than + `-1.79769313486232e+308` and values greater than `1.79769313486232e+308` + will be stored as NaN internally and be serialized to `null`. + + #### Storage + + Floating-point number values are stored directly inside a @ref basic_json + type. + + @sa see @ref number_integer_t -- type for number values (integer) + + @sa see @ref number_unsigned_t -- type for number values (unsigned integer) + + @since version 1.0.0 + */ + using number_float_t = NumberFloatType; + + /*! + @brief a type for a packed binary type + + This type is a type designed to carry binary data that appears in various + serialized formats, such as CBOR's Major Type 2, MessagePack's bin, and + BSON's generic binary subtype. This type is NOT a part of standard JSON and + exists solely for compatibility with these binary types. As such, it is + simply defined as an ordered sequence of zero or more byte values. + + Additionally, as an implementation detail, the subtype of the binary data is + carried around as a `std::uint8_t`, which is compatible with both of the + binary data formats that use binary subtyping, (though the specific + numbering is incompatible with each other, and it is up to the user to + translate between them). + + [CBOR's RFC 7049](https://tools.ietf.org/html/rfc7049) describes this type + as: + > Major type 2: a byte string. The string's length in bytes is represented + > following the rules for positive integers (major type 0). + + [MessagePack's documentation on the bin type + family](https://github.com/msgpack/msgpack/blob/master/spec.md#bin-format-family) + describes this type as: + > Bin format family stores an byte array in 2, 3, or 5 bytes of extra bytes + > in addition to the size of the byte array. + + [BSON's specifications](http://bsonspec.org/spec.html) describe several + binary types; however, this type is intended to represent the generic binary + type which has the description: + > Generic binary subtype - This is the most commonly used binary subtype and + > should be the 'default' for drivers and tools. + + None of these impose any limitations on the internal representation other + than the basic unit of storage be some type of array whose parts are + decomposable into bytes. + + The default representation of this binary format is a + `std::vector`, which is a very common way to represent a byte + array in modern C++. + + #### Default type + + The default values for @a BinaryType is `std::vector` + + #### Storage + + Binary Arrays are stored as pointers in a @ref basic_json type. That is, + for any access to array values, a pointer of the type `binary_t*` must be + dereferenced. + + #### Notes on subtypes + + - CBOR + - Binary values are represented as byte strings. No subtypes are + supported and will be ignored when CBOR is written. + - MessagePack + - If a subtype is given and the binary array contains exactly 1, 2, 4, 8, + or 16 elements, the fixext family (fixext1, fixext2, fixext4, fixext8) + is used. For other sizes, the ext family (ext8, ext16, ext32) is used. + The subtype is then added as singed 8-bit integer. + - If no subtype is given, the bin family (bin8, bin16, bin32) is used. + - BSON + - If a subtype is given, it is used and added as unsigned 8-bit integer. + - If no subtype is given, the generic binary subtype 0x00 is used. + + @sa see @ref binary -- create a binary array + + @since version 3.8.0 + */ + using binary_t = nlohmann::byte_container_with_subtype; + /// @} + + private: + + /// helper for exception-safe object creation + template + JSON_HEDLEY_RETURNS_NON_NULL + static T* create(Args&& ... args) + { + AllocatorType alloc; + using AllocatorTraits = std::allocator_traits>; + + auto deleter = [&](T * obj) + { + AllocatorTraits::deallocate(alloc, obj, 1); + }; + std::unique_ptr obj(AllocatorTraits::allocate(alloc, 1), deleter); + AllocatorTraits::construct(alloc, obj.get(), std::forward(args)...); + JSON_ASSERT(obj != nullptr); + return obj.release(); + } + + //////////////////////// + // JSON value storage // + //////////////////////// + + JSON_PRIVATE_UNLESS_TESTED: + /*! + @brief a JSON value + + The actual storage for a JSON value of the @ref basic_json class. This + union combines the different storage types for the JSON value types + defined in @ref value_t. + + JSON type | value_t type | used type + --------- | --------------- | ------------------------ + object | object | pointer to @ref object_t + array | array | pointer to @ref array_t + string | string | pointer to @ref string_t + boolean | boolean | @ref boolean_t + number | number_integer | @ref number_integer_t + number | number_unsigned | @ref number_unsigned_t + number | number_float | @ref number_float_t + binary | binary | pointer to @ref binary_t + null | null | *no value is stored* + + @note Variable-length types (objects, arrays, and strings) are stored as + pointers. The size of the union should not exceed 64 bits if the default + value types are used. + + @since version 1.0.0 + */ + union json_value + { + /// object (stored with pointer to save storage) + object_t* object; + /// array (stored with pointer to save storage) + array_t* array; + /// string (stored with pointer to save storage) + string_t* string; + /// binary (stored with pointer to save storage) + binary_t* binary; + /// boolean + boolean_t boolean; + /// number (integer) + number_integer_t number_integer; + /// number (unsigned integer) + number_unsigned_t number_unsigned; + /// number (floating-point) + number_float_t number_float; + + /// default constructor (for null values) + json_value() = default; + /// constructor for booleans + json_value(boolean_t v) noexcept : boolean(v) {} + /// constructor for numbers (integer) + json_value(number_integer_t v) noexcept : number_integer(v) {} + /// constructor for numbers (unsigned) + json_value(number_unsigned_t v) noexcept : number_unsigned(v) {} + /// constructor for numbers (floating-point) + json_value(number_float_t v) noexcept : number_float(v) {} + /// constructor for empty values of a given type + json_value(value_t t) + { + switch (t) + { + case value_t::object: + { + object = create(); + break; + } + + case value_t::array: + { + array = create(); + break; + } + + case value_t::string: + { + string = create(""); + break; + } + + case value_t::binary: + { + binary = create(); + break; + } + + case value_t::boolean: + { + boolean = boolean_t(false); + break; + } + + case value_t::number_integer: + { + number_integer = number_integer_t(0); + break; + } + + case value_t::number_unsigned: + { + number_unsigned = number_unsigned_t(0); + break; + } + + case value_t::number_float: + { + number_float = number_float_t(0.0); + break; + } + + case value_t::null: + { + object = nullptr; // silence warning, see #821 + break; + } + + default: + { + object = nullptr; // silence warning, see #821 + if (JSON_HEDLEY_UNLIKELY(t == value_t::null)) + { + JSON_THROW(other_error::create(500, "961c151d2e87f2686a955a9be24d316f1362bf21 3.9.1", basic_json())); // LCOV_EXCL_LINE + } + break; + } + } + } + + /// constructor for strings + json_value(const string_t& value) + { + string = create(value); + } + + /// constructor for rvalue strings + json_value(string_t&& value) + { + string = create(std::move(value)); + } + + /// constructor for objects + json_value(const object_t& value) + { + object = create(value); + } + + /// constructor for rvalue objects + json_value(object_t&& value) + { + object = create(std::move(value)); + } + + /// constructor for arrays + json_value(const array_t& value) + { + array = create(value); + } + + /// constructor for rvalue arrays + json_value(array_t&& value) + { + array = create(std::move(value)); + } + + /// constructor for binary arrays + json_value(const typename binary_t::container_type& value) + { + binary = create(value); + } + + /// constructor for rvalue binary arrays + json_value(typename binary_t::container_type&& value) + { + binary = create(std::move(value)); + } + + /// constructor for binary arrays (internal type) + json_value(const binary_t& value) + { + binary = create(value); + } + + /// constructor for rvalue binary arrays (internal type) + json_value(binary_t&& value) + { + binary = create(std::move(value)); + } + + void destroy(value_t t) noexcept + { + // flatten the current json_value to a heap-allocated stack + std::vector stack; + + // move the top-level items to stack + if (t == value_t::array) + { + stack.reserve(array->size()); + std::move(array->begin(), array->end(), std::back_inserter(stack)); + } + else if (t == value_t::object) + { + stack.reserve(object->size()); + for (auto&& it : *object) + { + stack.push_back(std::move(it.second)); + } + } + + while (!stack.empty()) + { + // move the last item to local variable to be processed + basic_json current_item(std::move(stack.back())); + stack.pop_back(); + + // if current_item is array/object, move + // its children to the stack to be processed later + if (current_item.is_array()) + { + std::move(current_item.m_value.array->begin(), current_item.m_value.array->end(), + std::back_inserter(stack)); + + current_item.m_value.array->clear(); + } + else if (current_item.is_object()) + { + for (auto&& it : *current_item.m_value.object) + { + stack.push_back(std::move(it.second)); + } + + current_item.m_value.object->clear(); + } + + // it's now safe that current_item get destructed + // since it doesn't have any children + } + + switch (t) + { + case value_t::object: + { + AllocatorType alloc; + std::allocator_traits::destroy(alloc, object); + std::allocator_traits::deallocate(alloc, object, 1); + break; + } + + case value_t::array: + { + AllocatorType alloc; + std::allocator_traits::destroy(alloc, array); + std::allocator_traits::deallocate(alloc, array, 1); + break; + } + + case value_t::string: + { + AllocatorType alloc; + std::allocator_traits::destroy(alloc, string); + std::allocator_traits::deallocate(alloc, string, 1); + break; + } + + case value_t::binary: + { + AllocatorType alloc; + std::allocator_traits::destroy(alloc, binary); + std::allocator_traits::deallocate(alloc, binary, 1); + break; + } + + default: + { + break; + } + } + } + }; + + private: + /*! + @brief checks the class invariants + + This function asserts the class invariants. It needs to be called at the + end of every constructor to make sure that created objects respect the + invariant. Furthermore, it has to be called each time the type of a JSON + value is changed, because the invariant expresses a relationship between + @a m_type and @a m_value. + + Furthermore, the parent relation is checked for arrays and objects: If + @a check_parents true and the value is an array or object, then the + container's elements must have the current value as parent. + + @param[in] check_parents whether the parent relation should be checked. + The value is true by default and should only be set to false + during destruction of objects when the invariant does not + need to hold. + */ + void assert_invariant(bool check_parents = true) const noexcept + { + JSON_ASSERT(m_type != value_t::object || m_value.object != nullptr); + JSON_ASSERT(m_type != value_t::array || m_value.array != nullptr); + JSON_ASSERT(m_type != value_t::string || m_value.string != nullptr); + JSON_ASSERT(m_type != value_t::binary || m_value.binary != nullptr); + +#if JSON_DIAGNOSTICS + JSON_TRY + { + // cppcheck-suppress assertWithSideEffect + JSON_ASSERT(!check_parents || !is_structured() || std::all_of(begin(), end(), [this](const basic_json & j) + { + return j.m_parent == this; + })); + } + JSON_CATCH(...) {} // LCOV_EXCL_LINE +#endif + static_cast(check_parents); + } + + void set_parents() + { +#if JSON_DIAGNOSTICS + switch (m_type) + { + case value_t::array: + { + for (auto& element : *m_value.array) + { + element.m_parent = this; + } + break; + } + + case value_t::object: + { + for (auto& element : *m_value.object) + { + element.second.m_parent = this; + } + break; + } + + default: + break; + } +#endif + } + + iterator set_parents(iterator it, typename iterator::difference_type count) + { +#if JSON_DIAGNOSTICS + for (typename iterator::difference_type i = 0; i < count; ++i) + { + (it + i)->m_parent = this; + } +#else + static_cast(count); +#endif + return it; + } + + reference set_parent(reference j) + { +#if JSON_DIAGNOSTICS + j.m_parent = this; +#else + static_cast(j); +#endif + return j; + } + + public: + ////////////////////////// + // JSON parser callback // + ////////////////////////// + + /*! + @brief parser event types + + The parser callback distinguishes the following events: + - `object_start`: the parser read `{` and started to process a JSON object + - `key`: the parser read a key of a value in an object + - `object_end`: the parser read `}` and finished processing a JSON object + - `array_start`: the parser read `[` and started to process a JSON array + - `array_end`: the parser read `]` and finished processing a JSON array + - `value`: the parser finished reading a JSON value + + @image html callback_events.png "Example when certain parse events are triggered" + + @sa see @ref parser_callback_t for more information and examples + */ + using parse_event_t = detail::parse_event_t; + + /*! + @brief per-element parser callback type + + With a parser callback function, the result of parsing a JSON text can be + influenced. When passed to @ref parse, it is called on certain events + (passed as @ref parse_event_t via parameter @a event) with a set recursion + depth @a depth and context JSON value @a parsed. The return value of the + callback function is a boolean indicating whether the element that emitted + the callback shall be kept or not. + + We distinguish six scenarios (determined by the event type) in which the + callback function can be called. The following table describes the values + of the parameters @a depth, @a event, and @a parsed. + + parameter @a event | description | parameter @a depth | parameter @a parsed + ------------------ | ----------- | ------------------ | ------------------- + parse_event_t::object_start | the parser read `{` and started to process a JSON object | depth of the parent of the JSON object | a JSON value with type discarded + parse_event_t::key | the parser read a key of a value in an object | depth of the currently parsed JSON object | a JSON string containing the key + parse_event_t::object_end | the parser read `}` and finished processing a JSON object | depth of the parent of the JSON object | the parsed JSON object + parse_event_t::array_start | the parser read `[` and started to process a JSON array | depth of the parent of the JSON array | a JSON value with type discarded + parse_event_t::array_end | the parser read `]` and finished processing a JSON array | depth of the parent of the JSON array | the parsed JSON array + parse_event_t::value | the parser finished reading a JSON value | depth of the value | the parsed JSON value + + @image html callback_events.png "Example when certain parse events are triggered" + + Discarding a value (i.e., returning `false`) has different effects + depending on the context in which function was called: + + - Discarded values in structured types are skipped. That is, the parser + will behave as if the discarded value was never read. + - In case a value outside a structured type is skipped, it is replaced + with `null`. This case happens if the top-level element is skipped. + + @param[in] depth the depth of the recursion during parsing + + @param[in] event an event of type parse_event_t indicating the context in + the callback function has been called + + @param[in,out] parsed the current intermediate parse result; note that + writing to this value has no effect for parse_event_t::key events + + @return Whether the JSON value which called the function during parsing + should be kept (`true`) or not (`false`). In the latter case, it is either + skipped completely or replaced by an empty discarded object. + + @sa see @ref parse for examples + + @since version 1.0.0 + */ + using parser_callback_t = detail::parser_callback_t; + + ////////////////// + // constructors // + ////////////////// + + /// @name constructors and destructors + /// Constructors of class @ref basic_json, copy/move constructor, copy + /// assignment, static functions creating objects, and the destructor. + /// @{ + + /*! + @brief create an empty value with a given type + + Create an empty JSON value with a given type. The value will be default + initialized with an empty value which depends on the type: + + Value type | initial value + ----------- | ------------- + null | `null` + boolean | `false` + string | `""` + number | `0` + object | `{}` + array | `[]` + binary | empty array + + @param[in] v the type of the value to create + + @complexity Constant. + + @exceptionsafety Strong guarantee: if an exception is thrown, there are no + changes to any JSON value. + + @liveexample{The following code shows the constructor for different @ref + value_t values,basic_json__value_t} + + @sa see @ref clear() -- restores the postcondition of this constructor + + @since version 1.0.0 + */ + basic_json(const value_t v) + : m_type(v), m_value(v) + { + assert_invariant(); + } + + /*! + @brief create a null object + + Create a `null` JSON value. It either takes a null pointer as parameter + (explicitly creating `null`) or no parameter (implicitly creating `null`). + The passed null pointer itself is not read -- it is only used to choose + the right constructor. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this constructor never throws + exceptions. + + @liveexample{The following code shows the constructor with and without a + null pointer parameter.,basic_json__nullptr_t} + + @since version 1.0.0 + */ + basic_json(std::nullptr_t = nullptr) noexcept + : basic_json(value_t::null) + { + assert_invariant(); + } + + /*! + @brief create a JSON value + + This is a "catch all" constructor for all compatible JSON types; that is, + types for which a `to_json()` method exists. The constructor forwards the + parameter @a val to that method (to `json_serializer::to_json` method + with `U = uncvref_t`, to be exact). + + Template type @a CompatibleType includes, but is not limited to, the + following types: + - **arrays**: @ref array_t and all kinds of compatible containers such as + `std::vector`, `std::deque`, `std::list`, `std::forward_list`, + `std::array`, `std::valarray`, `std::set`, `std::unordered_set`, + `std::multiset`, and `std::unordered_multiset` with a `value_type` from + which a @ref basic_json value can be constructed. + - **objects**: @ref object_t and all kinds of compatible associative + containers such as `std::map`, `std::unordered_map`, `std::multimap`, + and `std::unordered_multimap` with a `key_type` compatible to + @ref string_t and a `value_type` from which a @ref basic_json value can + be constructed. + - **strings**: @ref string_t, string literals, and all compatible string + containers can be used. + - **numbers**: @ref number_integer_t, @ref number_unsigned_t, + @ref number_float_t, and all convertible number types such as `int`, + `size_t`, `int64_t`, `float` or `double` can be used. + - **boolean**: @ref boolean_t / `bool` can be used. + - **binary**: @ref binary_t / `std::vector` may be used, + unfortunately because string literals cannot be distinguished from binary + character arrays by the C++ type system, all types compatible with `const + char*` will be directed to the string constructor instead. This is both + for backwards compatibility, and due to the fact that a binary type is not + a standard JSON type. + + See the examples below. + + @tparam CompatibleType a type such that: + - @a CompatibleType is not derived from `std::istream`, + - @a CompatibleType is not @ref basic_json (to avoid hijacking copy/move + constructors), + - @a CompatibleType is not a different @ref basic_json type (i.e. with different template arguments) + - @a CompatibleType is not a @ref basic_json nested type (e.g., + @ref json_pointer, @ref iterator, etc ...) + - `json_serializer` has a `to_json(basic_json_t&, CompatibleType&&)` method + + @tparam U = `uncvref_t` + + @param[in] val the value to be forwarded to the respective constructor + + @complexity Usually linear in the size of the passed @a val, also + depending on the implementation of the called `to_json()` + method. + + @exceptionsafety Depends on the called constructor. For types directly + supported by the library (i.e., all types for which no `to_json()` function + was provided), strong guarantee holds: if an exception is thrown, there are + no changes to any JSON value. + + @liveexample{The following code shows the constructor with several + compatible types.,basic_json__CompatibleType} + + @since version 2.1.0 + */ + template < typename CompatibleType, + typename U = detail::uncvref_t, + detail::enable_if_t < + !detail::is_basic_json::value && detail::is_compatible_type::value, int > = 0 > + basic_json(CompatibleType && val) noexcept(noexcept( // NOLINT(bugprone-forwarding-reference-overload,bugprone-exception-escape) + JSONSerializer::to_json(std::declval(), + std::forward(val)))) + { + JSONSerializer::to_json(*this, std::forward(val)); + set_parents(); + assert_invariant(); + } + + /*! + @brief create a JSON value from an existing one + + This is a constructor for existing @ref basic_json types. + It does not hijack copy/move constructors, since the parameter has different + template arguments than the current ones. + + The constructor tries to convert the internal @ref m_value of the parameter. + + @tparam BasicJsonType a type such that: + - @a BasicJsonType is a @ref basic_json type. + - @a BasicJsonType has different template arguments than @ref basic_json_t. + + @param[in] val the @ref basic_json value to be converted. + + @complexity Usually linear in the size of the passed @a val, also + depending on the implementation of the called `to_json()` + method. + + @exceptionsafety Depends on the called constructor. For types directly + supported by the library (i.e., all types for which no `to_json()` function + was provided), strong guarantee holds: if an exception is thrown, there are + no changes to any JSON value. + + @since version 3.2.0 + */ + template < typename BasicJsonType, + detail::enable_if_t < + detail::is_basic_json::value&& !std::is_same::value, int > = 0 > + basic_json(const BasicJsonType& val) + { + using other_boolean_t = typename BasicJsonType::boolean_t; + using other_number_float_t = typename BasicJsonType::number_float_t; + using other_number_integer_t = typename BasicJsonType::number_integer_t; + using other_number_unsigned_t = typename BasicJsonType::number_unsigned_t; + using other_string_t = typename BasicJsonType::string_t; + using other_object_t = typename BasicJsonType::object_t; + using other_array_t = typename BasicJsonType::array_t; + using other_binary_t = typename BasicJsonType::binary_t; + + switch (val.type()) + { + case value_t::boolean: + JSONSerializer::to_json(*this, val.template get()); + break; + case value_t::number_float: + JSONSerializer::to_json(*this, val.template get()); + break; + case value_t::number_integer: + JSONSerializer::to_json(*this, val.template get()); + break; + case value_t::number_unsigned: + JSONSerializer::to_json(*this, val.template get()); + break; + case value_t::string: + JSONSerializer::to_json(*this, val.template get_ref()); + break; + case value_t::object: + JSONSerializer::to_json(*this, val.template get_ref()); + break; + case value_t::array: + JSONSerializer::to_json(*this, val.template get_ref()); + break; + case value_t::binary: + JSONSerializer::to_json(*this, val.template get_ref()); + break; + case value_t::null: + *this = nullptr; + break; + case value_t::discarded: + m_type = value_t::discarded; + break; + default: // LCOV_EXCL_LINE + JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE + } + set_parents(); + assert_invariant(); + } + + /*! + @brief create a container (array or object) from an initializer list + + Creates a JSON value of type array or object from the passed initializer + list @a init. In case @a type_deduction is `true` (default), the type of + the JSON value to be created is deducted from the initializer list @a init + according to the following rules: + + 1. If the list is empty, an empty JSON object value `{}` is created. + 2. If the list consists of pairs whose first element is a string, a JSON + object value is created where the first elements of the pairs are + treated as keys and the second elements are as values. + 3. In all other cases, an array is created. + + The rules aim to create the best fit between a C++ initializer list and + JSON values. The rationale is as follows: + + 1. The empty initializer list is written as `{}` which is exactly an empty + JSON object. + 2. C++ has no way of describing mapped types other than to list a list of + pairs. As JSON requires that keys must be of type string, rule 2 is the + weakest constraint one can pose on initializer lists to interpret them + as an object. + 3. In all other cases, the initializer list could not be interpreted as + JSON object type, so interpreting it as JSON array type is safe. + + With the rules described above, the following JSON values cannot be + expressed by an initializer list: + + - the empty array (`[]`): use @ref array(initializer_list_t) + with an empty initializer list in this case + - arrays whose elements satisfy rule 2: use @ref + array(initializer_list_t) with the same initializer list + in this case + + @note When used without parentheses around an empty initializer list, @ref + basic_json() is called instead of this function, yielding the JSON null + value. + + @param[in] init initializer list with JSON values + + @param[in] type_deduction internal parameter; when set to `true`, the type + of the JSON value is deducted from the initializer list @a init; when set + to `false`, the type provided via @a manual_type is forced. This mode is + used by the functions @ref array(initializer_list_t) and + @ref object(initializer_list_t). + + @param[in] manual_type internal parameter; when @a type_deduction is set + to `false`, the created JSON value will use the provided type (only @ref + value_t::array and @ref value_t::object are valid); when @a type_deduction + is set to `true`, this parameter has no effect + + @throw type_error.301 if @a type_deduction is `false`, @a manual_type is + `value_t::object`, but @a init contains an element which is not a pair + whose first element is a string. In this case, the constructor could not + create an object. If @a type_deduction would have be `true`, an array + would have been created. See @ref object(initializer_list_t) + for an example. + + @complexity Linear in the size of the initializer list @a init. + + @exceptionsafety Strong guarantee: if an exception is thrown, there are no + changes to any JSON value. + + @liveexample{The example below shows how JSON values are created from + initializer lists.,basic_json__list_init_t} + + @sa see @ref array(initializer_list_t) -- create a JSON array + value from an initializer list + @sa see @ref object(initializer_list_t) -- create a JSON object + value from an initializer list + + @since version 1.0.0 + */ + basic_json(initializer_list_t init, + bool type_deduction = true, + value_t manual_type = value_t::array) + { + // check if each element is an array with two elements whose first + // element is a string + bool is_an_object = std::all_of(init.begin(), init.end(), + [](const detail::json_ref& element_ref) + { + return element_ref->is_array() && element_ref->size() == 2 && (*element_ref)[0].is_string(); + }); + + // adjust type if type deduction is not wanted + if (!type_deduction) + { + // if array is wanted, do not create an object though possible + if (manual_type == value_t::array) + { + is_an_object = false; + } + + // if object is wanted but impossible, throw an exception + if (JSON_HEDLEY_UNLIKELY(manual_type == value_t::object && !is_an_object)) + { + JSON_THROW(type_error::create(301, "cannot create object from initializer list", basic_json())); + } + } + + if (is_an_object) + { + // the initializer list is a list of pairs -> create object + m_type = value_t::object; + m_value = value_t::object; + + for (auto& element_ref : init) + { + auto element = element_ref.moved_or_copied(); + m_value.object->emplace( + std::move(*((*element.m_value.array)[0].m_value.string)), + std::move((*element.m_value.array)[1])); + } + } + else + { + // the initializer list describes an array -> create array + m_type = value_t::array; + m_value.array = create(init.begin(), init.end()); + } + + set_parents(); + assert_invariant(); + } + + /*! + @brief explicitly create a binary array (without subtype) + + Creates a JSON binary array value from a given binary container. Binary + values are part of various binary formats, such as CBOR, MessagePack, and + BSON. This constructor is used to create a value for serialization to those + formats. + + @note Note, this function exists because of the difficulty in correctly + specifying the correct template overload in the standard value ctor, as both + JSON arrays and JSON binary arrays are backed with some form of a + `std::vector`. Because JSON binary arrays are a non-standard extension it + was decided that it would be best to prevent automatic initialization of a + binary array type, for backwards compatibility and so it does not happen on + accident. + + @param[in] init container containing bytes to use as binary type + + @return JSON binary array value + + @complexity Linear in the size of @a init. + + @exceptionsafety Strong guarantee: if an exception is thrown, there are no + changes to any JSON value. + + @since version 3.8.0 + */ + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json binary(const typename binary_t::container_type& init) + { + auto res = basic_json(); + res.m_type = value_t::binary; + res.m_value = init; + return res; + } + + /*! + @brief explicitly create a binary array (with subtype) + + Creates a JSON binary array value from a given binary container. Binary + values are part of various binary formats, such as CBOR, MessagePack, and + BSON. This constructor is used to create a value for serialization to those + formats. + + @note Note, this function exists because of the difficulty in correctly + specifying the correct template overload in the standard value ctor, as both + JSON arrays and JSON binary arrays are backed with some form of a + `std::vector`. Because JSON binary arrays are a non-standard extension it + was decided that it would be best to prevent automatic initialization of a + binary array type, for backwards compatibility and so it does not happen on + accident. + + @param[in] init container containing bytes to use as binary type + @param[in] subtype subtype to use in MessagePack and BSON + + @return JSON binary array value + + @complexity Linear in the size of @a init. + + @exceptionsafety Strong guarantee: if an exception is thrown, there are no + changes to any JSON value. + + @since version 3.8.0 + */ + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json binary(const typename binary_t::container_type& init, std::uint8_t subtype) + { + auto res = basic_json(); + res.m_type = value_t::binary; + res.m_value = binary_t(init, subtype); + return res; + } + + /// @copydoc binary(const typename binary_t::container_type&) + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json binary(typename binary_t::container_type&& init) + { + auto res = basic_json(); + res.m_type = value_t::binary; + res.m_value = std::move(init); + return res; + } + + /// @copydoc binary(const typename binary_t::container_type&, std::uint8_t) + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json binary(typename binary_t::container_type&& init, std::uint8_t subtype) + { + auto res = basic_json(); + res.m_type = value_t::binary; + res.m_value = binary_t(std::move(init), subtype); + return res; + } + + /*! + @brief explicitly create an array from an initializer list + + Creates a JSON array value from a given initializer list. That is, given a + list of values `a, b, c`, creates the JSON value `[a, b, c]`. If the + initializer list is empty, the empty array `[]` is created. + + @note This function is only needed to express two edge cases that cannot + be realized with the initializer list constructor (@ref + basic_json(initializer_list_t, bool, value_t)). These cases + are: + 1. creating an array whose elements are all pairs whose first element is a + string -- in this case, the initializer list constructor would create an + object, taking the first elements as keys + 2. creating an empty array -- passing the empty initializer list to the + initializer list constructor yields an empty object + + @param[in] init initializer list with JSON values to create an array from + (optional) + + @return JSON array value + + @complexity Linear in the size of @a init. + + @exceptionsafety Strong guarantee: if an exception is thrown, there are no + changes to any JSON value. + + @liveexample{The following code shows an example for the `array` + function.,array} + + @sa see @ref basic_json(initializer_list_t, bool, value_t) -- + create a JSON value from an initializer list + @sa see @ref object(initializer_list_t) -- create a JSON object + value from an initializer list + + @since version 1.0.0 + */ + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json array(initializer_list_t init = {}) + { + return basic_json(init, false, value_t::array); + } + + /*! + @brief explicitly create an object from an initializer list + + Creates a JSON object value from a given initializer list. The initializer + lists elements must be pairs, and their first elements must be strings. If + the initializer list is empty, the empty object `{}` is created. + + @note This function is only added for symmetry reasons. In contrast to the + related function @ref array(initializer_list_t), there are + no cases which can only be expressed by this function. That is, any + initializer list @a init can also be passed to the initializer list + constructor @ref basic_json(initializer_list_t, bool, value_t). + + @param[in] init initializer list to create an object from (optional) + + @return JSON object value + + @throw type_error.301 if @a init is not a list of pairs whose first + elements are strings. In this case, no object can be created. When such a + value is passed to @ref basic_json(initializer_list_t, bool, value_t), + an array would have been created from the passed initializer list @a init. + See example below. + + @complexity Linear in the size of @a init. + + @exceptionsafety Strong guarantee: if an exception is thrown, there are no + changes to any JSON value. + + @liveexample{The following code shows an example for the `object` + function.,object} + + @sa see @ref basic_json(initializer_list_t, bool, value_t) -- + create a JSON value from an initializer list + @sa see @ref array(initializer_list_t) -- create a JSON array + value from an initializer list + + @since version 1.0.0 + */ + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json object(initializer_list_t init = {}) + { + return basic_json(init, false, value_t::object); + } + + /*! + @brief construct an array with count copies of given value + + Constructs a JSON array value by creating @a cnt copies of a passed value. + In case @a cnt is `0`, an empty array is created. + + @param[in] cnt the number of JSON copies of @a val to create + @param[in] val the JSON value to copy + + @post `std::distance(begin(),end()) == cnt` holds. + + @complexity Linear in @a cnt. + + @exceptionsafety Strong guarantee: if an exception is thrown, there are no + changes to any JSON value. + + @liveexample{The following code shows examples for the @ref + basic_json(size_type\, const basic_json&) + constructor.,basic_json__size_type_basic_json} + + @since version 1.0.0 + */ + basic_json(size_type cnt, const basic_json& val) + : m_type(value_t::array) + { + m_value.array = create(cnt, val); + set_parents(); + assert_invariant(); + } + + /*! + @brief construct a JSON container given an iterator range + + Constructs the JSON value with the contents of the range `[first, last)`. + The semantics depends on the different types a JSON value can have: + - In case of a null type, invalid_iterator.206 is thrown. + - In case of other primitive types (number, boolean, or string), @a first + must be `begin()` and @a last must be `end()`. In this case, the value is + copied. Otherwise, invalid_iterator.204 is thrown. + - In case of structured types (array, object), the constructor behaves as + similar versions for `std::vector` or `std::map`; that is, a JSON array + or object is constructed from the values in the range. + + @tparam InputIT an input iterator type (@ref iterator or @ref + const_iterator) + + @param[in] first begin of the range to copy from (included) + @param[in] last end of the range to copy from (excluded) + + @pre Iterators @a first and @a last must be initialized. **This + precondition is enforced with an assertion (see warning).** If + assertions are switched off, a violation of this precondition yields + undefined behavior. + + @pre Range `[first, last)` is valid. Usually, this precondition cannot be + checked efficiently. Only certain edge cases are detected; see the + description of the exceptions below. A violation of this precondition + yields undefined behavior. + + @warning A precondition is enforced with a runtime assertion that will + result in calling `std::abort` if this precondition is not met. + Assertions can be disabled by defining `NDEBUG` at compile time. + See https://en.cppreference.com/w/cpp/error/assert for more + information. + + @throw invalid_iterator.201 if iterators @a first and @a last are not + compatible (i.e., do not belong to the same JSON value). In this case, + the range `[first, last)` is undefined. + @throw invalid_iterator.204 if iterators @a first and @a last belong to a + primitive type (number, boolean, or string), but @a first does not point + to the first element any more. In this case, the range `[first, last)` is + undefined. See example code below. + @throw invalid_iterator.206 if iterators @a first and @a last belong to a + null value. In this case, the range `[first, last)` is undefined. + + @complexity Linear in distance between @a first and @a last. + + @exceptionsafety Strong guarantee: if an exception is thrown, there are no + changes to any JSON value. + + @liveexample{The example below shows several ways to create JSON values by + specifying a subrange with iterators.,basic_json__InputIt_InputIt} + + @since version 1.0.0 + */ + template < class InputIT, typename std::enable_if < + std::is_same::value || + std::is_same::value, int >::type = 0 > + basic_json(InputIT first, InputIT last) + { + JSON_ASSERT(first.m_object != nullptr); + JSON_ASSERT(last.m_object != nullptr); + + // make sure iterator fits the current value + if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object)) + { + JSON_THROW(invalid_iterator::create(201, "iterators are not compatible", basic_json())); + } + + // copy type from first iterator + m_type = first.m_object->m_type; + + // check if iterator range is complete for primitive values + switch (m_type) + { + case value_t::boolean: + case value_t::number_float: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::string: + { + if (JSON_HEDLEY_UNLIKELY(!first.m_it.primitive_iterator.is_begin() + || !last.m_it.primitive_iterator.is_end())) + { + JSON_THROW(invalid_iterator::create(204, "iterators out of range", *first.m_object)); + } + break; + } + + default: + break; + } + + switch (m_type) + { + case value_t::number_integer: + { + m_value.number_integer = first.m_object->m_value.number_integer; + break; + } + + case value_t::number_unsigned: + { + m_value.number_unsigned = first.m_object->m_value.number_unsigned; + break; + } + + case value_t::number_float: + { + m_value.number_float = first.m_object->m_value.number_float; + break; + } + + case value_t::boolean: + { + m_value.boolean = first.m_object->m_value.boolean; + break; + } + + case value_t::string: + { + m_value = *first.m_object->m_value.string; + break; + } + + case value_t::object: + { + m_value.object = create(first.m_it.object_iterator, + last.m_it.object_iterator); + break; + } + + case value_t::array: + { + m_value.array = create(first.m_it.array_iterator, + last.m_it.array_iterator); + break; + } + + case value_t::binary: + { + m_value = *first.m_object->m_value.binary; + break; + } + + default: + JSON_THROW(invalid_iterator::create(206, "cannot construct with iterators from " + std::string(first.m_object->type_name()), *first.m_object)); + } + + set_parents(); + assert_invariant(); + } + + + /////////////////////////////////////// + // other constructors and destructor // + /////////////////////////////////////// + + template, + std::is_same>::value, int> = 0 > + basic_json(const JsonRef& ref) : basic_json(ref.moved_or_copied()) {} + + /*! + @brief copy constructor + + Creates a copy of a given JSON value. + + @param[in] other the JSON value to copy + + @post `*this == other` + + @complexity Linear in the size of @a other. + + @exceptionsafety Strong guarantee: if an exception is thrown, there are no + changes to any JSON value. + + @requirement This function helps `basic_json` satisfying the + [Container](https://en.cppreference.com/w/cpp/named_req/Container) + requirements: + - The complexity is linear. + - As postcondition, it holds: `other == basic_json(other)`. + + @liveexample{The following code shows an example for the copy + constructor.,basic_json__basic_json} + + @since version 1.0.0 + */ + basic_json(const basic_json& other) + : m_type(other.m_type) + { + // check of passed value is valid + other.assert_invariant(); + + switch (m_type) + { + case value_t::object: + { + m_value = *other.m_value.object; + break; + } + + case value_t::array: + { + m_value = *other.m_value.array; + break; + } + + case value_t::string: + { + m_value = *other.m_value.string; + break; + } + + case value_t::boolean: + { + m_value = other.m_value.boolean; + break; + } + + case value_t::number_integer: + { + m_value = other.m_value.number_integer; + break; + } + + case value_t::number_unsigned: + { + m_value = other.m_value.number_unsigned; + break; + } + + case value_t::number_float: + { + m_value = other.m_value.number_float; + break; + } + + case value_t::binary: + { + m_value = *other.m_value.binary; + break; + } + + default: + break; + } + + set_parents(); + assert_invariant(); + } + + /*! + @brief move constructor + + Move constructor. Constructs a JSON value with the contents of the given + value @a other using move semantics. It "steals" the resources from @a + other and leaves it as JSON null value. + + @param[in,out] other value to move to this object + + @post `*this` has the same value as @a other before the call. + @post @a other is a JSON null value. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this constructor never throws + exceptions. + + @requirement This function helps `basic_json` satisfying the + [MoveConstructible](https://en.cppreference.com/w/cpp/named_req/MoveConstructible) + requirements. + + @liveexample{The code below shows the move constructor explicitly called + via std::move.,basic_json__moveconstructor} + + @since version 1.0.0 + */ + basic_json(basic_json&& other) noexcept + : m_type(std::move(other.m_type)), + m_value(std::move(other.m_value)) + { + // check that passed value is valid + other.assert_invariant(false); + + // invalidate payload + other.m_type = value_t::null; + other.m_value = {}; + + set_parents(); + assert_invariant(); + } + + /*! + @brief copy assignment + + Copy assignment operator. Copies a JSON value via the "copy and swap" + strategy: It is expressed in terms of the copy constructor, destructor, + and the `swap()` member function. + + @param[in] other value to copy from + + @complexity Linear. + + @requirement This function helps `basic_json` satisfying the + [Container](https://en.cppreference.com/w/cpp/named_req/Container) + requirements: + - The complexity is linear. + + @liveexample{The code below shows and example for the copy assignment. It + creates a copy of value `a` which is then swapped with `b`. Finally\, the + copy of `a` (which is the null value after the swap) is + destroyed.,basic_json__copyassignment} + + @since version 1.0.0 + */ + basic_json& operator=(basic_json other) noexcept ( + std::is_nothrow_move_constructible::value&& + std::is_nothrow_move_assignable::value&& + std::is_nothrow_move_constructible::value&& + std::is_nothrow_move_assignable::value + ) + { + // check that passed value is valid + other.assert_invariant(); + + using std::swap; + swap(m_type, other.m_type); + swap(m_value, other.m_value); + + set_parents(); + assert_invariant(); + return *this; + } + + /*! + @brief destructor + + Destroys the JSON value and frees all allocated memory. + + @complexity Linear. + + @requirement This function helps `basic_json` satisfying the + [Container](https://en.cppreference.com/w/cpp/named_req/Container) + requirements: + - The complexity is linear. + - All stored elements are destroyed and all memory is freed. + + @since version 1.0.0 + */ + ~basic_json() noexcept + { + assert_invariant(false); + m_value.destroy(m_type); + } + + /// @} + + public: + /////////////////////// + // object inspection // + /////////////////////// + + /// @name object inspection + /// Functions to inspect the type of a JSON value. + /// @{ + + /*! + @brief serialization + + Serialization function for JSON values. The function tries to mimic + Python's `json.dumps()` function, and currently supports its @a indent + and @a ensure_ascii parameters. + + @param[in] indent If indent is nonnegative, then array elements and object + members will be pretty-printed with that indent level. An indent level of + `0` will only insert newlines. `-1` (the default) selects the most compact + representation. + @param[in] indent_char The character to use for indentation if @a indent is + greater than `0`. The default is ` ` (space). + @param[in] ensure_ascii If @a ensure_ascii is true, all non-ASCII characters + in the output are escaped with `\uXXXX` sequences, and the result consists + of ASCII characters only. + @param[in] error_handler how to react on decoding errors; there are three + possible values: `strict` (throws and exception in case a decoding error + occurs; default), `replace` (replace invalid UTF-8 sequences with U+FFFD), + and `ignore` (ignore invalid UTF-8 sequences during serialization; all + bytes are copied to the output unchanged). + + @return string containing the serialization of the JSON value + + @throw type_error.316 if a string stored inside the JSON value is not + UTF-8 encoded and @a error_handler is set to strict + + @note Binary values are serialized as object containing two keys: + - "bytes": an array of bytes as integers + - "subtype": the subtype as integer or "null" if the binary has no subtype + + @complexity Linear. + + @exceptionsafety Strong guarantee: if an exception is thrown, there are no + changes in the JSON value. + + @liveexample{The following example shows the effect of different @a indent\, + @a indent_char\, and @a ensure_ascii parameters to the result of the + serialization.,dump} + + @see https://docs.python.org/2/library/json.html#json.dump + + @since version 1.0.0; indentation character @a indent_char, option + @a ensure_ascii and exceptions added in version 3.0.0; error + handlers added in version 3.4.0; serialization of binary values added + in version 3.8.0. + */ + string_t dump(const int indent = -1, + const char indent_char = ' ', + const bool ensure_ascii = false, + const error_handler_t error_handler = error_handler_t::strict) const + { + string_t result; + serializer s(detail::output_adapter(result), indent_char, error_handler); + + if (indent >= 0) + { + s.dump(*this, true, ensure_ascii, static_cast(indent)); + } + else + { + s.dump(*this, false, ensure_ascii, 0); + } + + return result; + } + + /*! + @brief return the type of the JSON value (explicit) + + Return the type of the JSON value as a value from the @ref value_t + enumeration. + + @return the type of the JSON value + Value type | return value + ------------------------- | ------------------------- + null | value_t::null + boolean | value_t::boolean + string | value_t::string + number (integer) | value_t::number_integer + number (unsigned integer) | value_t::number_unsigned + number (floating-point) | value_t::number_float + object | value_t::object + array | value_t::array + binary | value_t::binary + discarded | value_t::discarded + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies `type()` for all JSON + types.,type} + + @sa see @ref operator value_t() -- return the type of the JSON value (implicit) + @sa see @ref type_name() -- return the type as string + + @since version 1.0.0 + */ + constexpr value_t type() const noexcept + { + return m_type; + } + + /*! + @brief return whether type is primitive + + This function returns true if and only if the JSON type is primitive + (string, number, boolean, or null). + + @return `true` if type is primitive (string, number, boolean, or null), + `false` otherwise. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies `is_primitive()` for all JSON + types.,is_primitive} + + @sa see @ref is_structured() -- returns whether JSON value is structured + @sa see @ref is_null() -- returns whether JSON value is `null` + @sa see @ref is_string() -- returns whether JSON value is a string + @sa see @ref is_boolean() -- returns whether JSON value is a boolean + @sa see @ref is_number() -- returns whether JSON value is a number + @sa see @ref is_binary() -- returns whether JSON value is a binary array + + @since version 1.0.0 + */ + constexpr bool is_primitive() const noexcept + { + return is_null() || is_string() || is_boolean() || is_number() || is_binary(); + } + + /*! + @brief return whether type is structured + + This function returns true if and only if the JSON type is structured + (array or object). + + @return `true` if type is structured (array or object), `false` otherwise. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies `is_structured()` for all JSON + types.,is_structured} + + @sa see @ref is_primitive() -- returns whether value is primitive + @sa see @ref is_array() -- returns whether value is an array + @sa see @ref is_object() -- returns whether value is an object + + @since version 1.0.0 + */ + constexpr bool is_structured() const noexcept + { + return is_array() || is_object(); + } + + /*! + @brief return whether value is null + + This function returns true if and only if the JSON value is null. + + @return `true` if type is null, `false` otherwise. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies `is_null()` for all JSON + types.,is_null} + + @since version 1.0.0 + */ + constexpr bool is_null() const noexcept + { + return m_type == value_t::null; + } + + /*! + @brief return whether value is a boolean + + This function returns true if and only if the JSON value is a boolean. + + @return `true` if type is boolean, `false` otherwise. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies `is_boolean()` for all JSON + types.,is_boolean} + + @since version 1.0.0 + */ + constexpr bool is_boolean() const noexcept + { + return m_type == value_t::boolean; + } + + /*! + @brief return whether value is a number + + This function returns true if and only if the JSON value is a number. This + includes both integer (signed and unsigned) and floating-point values. + + @return `true` if type is number (regardless whether integer, unsigned + integer or floating-type), `false` otherwise. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies `is_number()` for all JSON + types.,is_number} + + @sa see @ref is_number_integer() -- check if value is an integer or unsigned + integer number + @sa see @ref is_number_unsigned() -- check if value is an unsigned integer + number + @sa see @ref is_number_float() -- check if value is a floating-point number + + @since version 1.0.0 + */ + constexpr bool is_number() const noexcept + { + return is_number_integer() || is_number_float(); + } + + /*! + @brief return whether value is an integer number + + This function returns true if and only if the JSON value is a signed or + unsigned integer number. This excludes floating-point values. + + @return `true` if type is an integer or unsigned integer number, `false` + otherwise. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies `is_number_integer()` for all + JSON types.,is_number_integer} + + @sa see @ref is_number() -- check if value is a number + @sa see @ref is_number_unsigned() -- check if value is an unsigned integer + number + @sa see @ref is_number_float() -- check if value is a floating-point number + + @since version 1.0.0 + */ + constexpr bool is_number_integer() const noexcept + { + return m_type == value_t::number_integer || m_type == value_t::number_unsigned; + } + + /*! + @brief return whether value is an unsigned integer number + + This function returns true if and only if the JSON value is an unsigned + integer number. This excludes floating-point and signed integer values. + + @return `true` if type is an unsigned integer number, `false` otherwise. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies `is_number_unsigned()` for all + JSON types.,is_number_unsigned} + + @sa see @ref is_number() -- check if value is a number + @sa see @ref is_number_integer() -- check if value is an integer or unsigned + integer number + @sa see @ref is_number_float() -- check if value is a floating-point number + + @since version 2.0.0 + */ + constexpr bool is_number_unsigned() const noexcept + { + return m_type == value_t::number_unsigned; + } + + /*! + @brief return whether value is a floating-point number + + This function returns true if and only if the JSON value is a + floating-point number. This excludes signed and unsigned integer values. + + @return `true` if type is a floating-point number, `false` otherwise. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies `is_number_float()` for all + JSON types.,is_number_float} + + @sa see @ref is_number() -- check if value is number + @sa see @ref is_number_integer() -- check if value is an integer number + @sa see @ref is_number_unsigned() -- check if value is an unsigned integer + number + + @since version 1.0.0 + */ + constexpr bool is_number_float() const noexcept + { + return m_type == value_t::number_float; + } + + /*! + @brief return whether value is an object + + This function returns true if and only if the JSON value is an object. + + @return `true` if type is object, `false` otherwise. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies `is_object()` for all JSON + types.,is_object} + + @since version 1.0.0 + */ + constexpr bool is_object() const noexcept + { + return m_type == value_t::object; + } + + /*! + @brief return whether value is an array + + This function returns true if and only if the JSON value is an array. + + @return `true` if type is array, `false` otherwise. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies `is_array()` for all JSON + types.,is_array} + + @since version 1.0.0 + */ + constexpr bool is_array() const noexcept + { + return m_type == value_t::array; + } + + /*! + @brief return whether value is a string + + This function returns true if and only if the JSON value is a string. + + @return `true` if type is string, `false` otherwise. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies `is_string()` for all JSON + types.,is_string} + + @since version 1.0.0 + */ + constexpr bool is_string() const noexcept + { + return m_type == value_t::string; + } + + /*! + @brief return whether value is a binary array + + This function returns true if and only if the JSON value is a binary array. + + @return `true` if type is binary array, `false` otherwise. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies `is_binary()` for all JSON + types.,is_binary} + + @since version 3.8.0 + */ + constexpr bool is_binary() const noexcept + { + return m_type == value_t::binary; + } + + /*! + @brief return whether value is discarded + + This function returns true if and only if the JSON value was discarded + during parsing with a callback function (see @ref parser_callback_t). + + @note This function will always be `false` for JSON values after parsing. + That is, discarded values can only occur during parsing, but will be + removed when inside a structured value or replaced by null in other cases. + + @return `true` if type is discarded, `false` otherwise. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies `is_discarded()` for all JSON + types.,is_discarded} + + @since version 1.0.0 + */ + constexpr bool is_discarded() const noexcept + { + return m_type == value_t::discarded; + } + + /*! + @brief return the type of the JSON value (implicit) + + Implicitly return the type of the JSON value as a value from the @ref + value_t enumeration. + + @return the type of the JSON value + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies the @ref value_t operator for + all JSON types.,operator__value_t} + + @sa see @ref type() -- return the type of the JSON value (explicit) + @sa see @ref type_name() -- return the type as string + + @since version 1.0.0 + */ + constexpr operator value_t() const noexcept + { + return m_type; + } + + /// @} + + private: + ////////////////// + // value access // + ////////////////// + + /// get a boolean (explicit) + boolean_t get_impl(boolean_t* /*unused*/) const + { + if (JSON_HEDLEY_LIKELY(is_boolean())) + { + return m_value.boolean; + } + + JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(type_name()), *this)); + } + + /// get a pointer to the value (object) + object_t* get_impl_ptr(object_t* /*unused*/) noexcept + { + return is_object() ? m_value.object : nullptr; + } + + /// get a pointer to the value (object) + constexpr const object_t* get_impl_ptr(const object_t* /*unused*/) const noexcept + { + return is_object() ? m_value.object : nullptr; + } + + /// get a pointer to the value (array) + array_t* get_impl_ptr(array_t* /*unused*/) noexcept + { + return is_array() ? m_value.array : nullptr; + } + + /// get a pointer to the value (array) + constexpr const array_t* get_impl_ptr(const array_t* /*unused*/) const noexcept + { + return is_array() ? m_value.array : nullptr; + } + + /// get a pointer to the value (string) + string_t* get_impl_ptr(string_t* /*unused*/) noexcept + { + return is_string() ? m_value.string : nullptr; + } + + /// get a pointer to the value (string) + constexpr const string_t* get_impl_ptr(const string_t* /*unused*/) const noexcept + { + return is_string() ? m_value.string : nullptr; + } + + /// get a pointer to the value (boolean) + boolean_t* get_impl_ptr(boolean_t* /*unused*/) noexcept + { + return is_boolean() ? &m_value.boolean : nullptr; + } + + /// get a pointer to the value (boolean) + constexpr const boolean_t* get_impl_ptr(const boolean_t* /*unused*/) const noexcept + { + return is_boolean() ? &m_value.boolean : nullptr; + } + + /// get a pointer to the value (integer number) + number_integer_t* get_impl_ptr(number_integer_t* /*unused*/) noexcept + { + return is_number_integer() ? &m_value.number_integer : nullptr; + } + + /// get a pointer to the value (integer number) + constexpr const number_integer_t* get_impl_ptr(const number_integer_t* /*unused*/) const noexcept + { + return is_number_integer() ? &m_value.number_integer : nullptr; + } + + /// get a pointer to the value (unsigned number) + number_unsigned_t* get_impl_ptr(number_unsigned_t* /*unused*/) noexcept + { + return is_number_unsigned() ? &m_value.number_unsigned : nullptr; + } + + /// get a pointer to the value (unsigned number) + constexpr const number_unsigned_t* get_impl_ptr(const number_unsigned_t* /*unused*/) const noexcept + { + return is_number_unsigned() ? &m_value.number_unsigned : nullptr; + } + + /// get a pointer to the value (floating-point number) + number_float_t* get_impl_ptr(number_float_t* /*unused*/) noexcept + { + return is_number_float() ? &m_value.number_float : nullptr; + } + + /// get a pointer to the value (floating-point number) + constexpr const number_float_t* get_impl_ptr(const number_float_t* /*unused*/) const noexcept + { + return is_number_float() ? &m_value.number_float : nullptr; + } + + /// get a pointer to the value (binary) + binary_t* get_impl_ptr(binary_t* /*unused*/) noexcept + { + return is_binary() ? m_value.binary : nullptr; + } + + /// get a pointer to the value (binary) + constexpr const binary_t* get_impl_ptr(const binary_t* /*unused*/) const noexcept + { + return is_binary() ? m_value.binary : nullptr; + } + + /*! + @brief helper function to implement get_ref() + + This function helps to implement get_ref() without code duplication for + const and non-const overloads + + @tparam ThisType will be deduced as `basic_json` or `const basic_json` + + @throw type_error.303 if ReferenceType does not match underlying value + type of the current JSON + */ + template + static ReferenceType get_ref_impl(ThisType& obj) + { + // delegate the call to get_ptr<>() + auto* ptr = obj.template get_ptr::type>(); + + if (JSON_HEDLEY_LIKELY(ptr != nullptr)) + { + return *ptr; + } + + JSON_THROW(type_error::create(303, "incompatible ReferenceType for get_ref, actual type is " + std::string(obj.type_name()), obj)); + } + + public: + /// @name value access + /// Direct access to the stored value of a JSON value. + /// @{ + + /*! + @brief get a pointer value (implicit) + + Implicit pointer access to the internally stored JSON value. No copies are + made. + + @warning Writing data to the pointee of the result yields an undefined + state. + + @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref + object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, + @ref number_unsigned_t, or @ref number_float_t. Enforced by a static + assertion. + + @return pointer to the internally stored JSON value if the requested + pointer type @a PointerType fits to the JSON value; `nullptr` otherwise + + @complexity Constant. + + @liveexample{The example below shows how pointers to internal values of a + JSON value can be requested. Note that no type conversions are made and a + `nullptr` is returned if the value and the requested pointer type does not + match.,get_ptr} + + @since version 1.0.0 + */ + template::value, int>::type = 0> + auto get_ptr() noexcept -> decltype(std::declval().get_impl_ptr(std::declval())) + { + // delegate the call to get_impl_ptr<>() + return get_impl_ptr(static_cast(nullptr)); + } + + /*! + @brief get a pointer value (implicit) + @copydoc get_ptr() + */ + template < typename PointerType, typename std::enable_if < + std::is_pointer::value&& + std::is_const::type>::value, int >::type = 0 > + constexpr auto get_ptr() const noexcept -> decltype(std::declval().get_impl_ptr(std::declval())) + { + // delegate the call to get_impl_ptr<>() const + return get_impl_ptr(static_cast(nullptr)); + } + + private: + /*! + @brief get a value (explicit) + + Explicit type conversion between the JSON value and a compatible value + which is [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible) + and [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible). + The value is converted by calling the @ref json_serializer + `from_json()` method. + + The function is equivalent to executing + @code {.cpp} + ValueType ret; + JSONSerializer::from_json(*this, ret); + return ret; + @endcode + + This overloads is chosen if: + - @a ValueType is not @ref basic_json, + - @ref json_serializer has a `from_json()` method of the form + `void from_json(const basic_json&, ValueType&)`, and + - @ref json_serializer does not have a `from_json()` method of + the form `ValueType from_json(const basic_json&)` + + @tparam ValueType the returned value type + + @return copy of the JSON value, converted to @a ValueType + + @throw what @ref json_serializer `from_json()` method throws + + @liveexample{The example below shows several conversions from JSON values + to other types. There a few things to note: (1) Floating-point numbers can + be converted to integers\, (2) A JSON array can be converted to a standard + `std::vector`\, (3) A JSON object can be converted to C++ + associative containers such as `std::unordered_map`.,get__ValueType_const} + + @since version 2.1.0 + */ + template < typename ValueType, + detail::enable_if_t < + detail::is_default_constructible::value&& + detail::has_from_json::value, + int > = 0 > + ValueType get_impl(detail::priority_tag<0> /*unused*/) const noexcept(noexcept( + JSONSerializer::from_json(std::declval(), std::declval()))) + { + ValueType ret{}; + JSONSerializer::from_json(*this, ret); + return ret; + } + + /*! + @brief get a value (explicit); special case + + Explicit type conversion between the JSON value and a compatible value + which is **not** [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible) + and **not** [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible). + The value is converted by calling the @ref json_serializer + `from_json()` method. + + The function is equivalent to executing + @code {.cpp} + return JSONSerializer::from_json(*this); + @endcode + + This overloads is chosen if: + - @a ValueType is not @ref basic_json and + - @ref json_serializer has a `from_json()` method of the form + `ValueType from_json(const basic_json&)` + + @note If @ref json_serializer has both overloads of + `from_json()`, this one is chosen. + + @tparam ValueType the returned value type + + @return copy of the JSON value, converted to @a ValueType + + @throw what @ref json_serializer `from_json()` method throws + + @since version 2.1.0 + */ + template < typename ValueType, + detail::enable_if_t < + detail::has_non_default_from_json::value, + int > = 0 > + ValueType get_impl(detail::priority_tag<1> /*unused*/) const noexcept(noexcept( + JSONSerializer::from_json(std::declval()))) + { + return JSONSerializer::from_json(*this); + } + + /*! + @brief get special-case overload + + This overloads converts the current @ref basic_json in a different + @ref basic_json type + + @tparam BasicJsonType == @ref basic_json + + @return a copy of *this, converted into @a BasicJsonType + + @complexity Depending on the implementation of the called `from_json()` + method. + + @since version 3.2.0 + */ + template < typename BasicJsonType, + detail::enable_if_t < + detail::is_basic_json::value, + int > = 0 > + BasicJsonType get_impl(detail::priority_tag<2> /*unused*/) const + { + return *this; + } + + /*! + @brief get special-case overload + + This overloads avoids a lot of template boilerplate, it can be seen as the + identity method + + @tparam BasicJsonType == @ref basic_json + + @return a copy of *this + + @complexity Constant. + + @since version 2.1.0 + */ + template::value, + int> = 0> + basic_json get_impl(detail::priority_tag<3> /*unused*/) const + { + return *this; + } + + /*! + @brief get a pointer value (explicit) + @copydoc get() + */ + template::value, + int> = 0> + constexpr auto get_impl(detail::priority_tag<4> /*unused*/) const noexcept + -> decltype(std::declval().template get_ptr()) + { + // delegate the call to get_ptr + return get_ptr(); + } + + public: + /*! + @brief get a (pointer) value (explicit) + + Performs explicit type conversion between the JSON value and a compatible value if required. + + - If the requested type is a pointer to the internally stored JSON value that pointer is returned. + No copies are made. + + - If the requested type is the current @ref basic_json, or a different @ref basic_json convertible + from the current @ref basic_json. + + - Otherwise the value is converted by calling the @ref json_serializer `from_json()` + method. + + @tparam ValueTypeCV the provided value type + @tparam ValueType the returned value type + + @return copy of the JSON value, converted to @tparam ValueType if necessary + + @throw what @ref json_serializer `from_json()` method throws if conversion is required + + @since version 2.1.0 + */ + template < typename ValueTypeCV, typename ValueType = detail::uncvref_t> +#if defined(JSON_HAS_CPP_14) + constexpr +#endif + auto get() const noexcept( + noexcept(std::declval().template get_impl(detail::priority_tag<4> {}))) + -> decltype(std::declval().template get_impl(detail::priority_tag<4> {})) + { + // we cannot static_assert on ValueTypeCV being non-const, because + // there is support for get(), which is why we + // still need the uncvref + static_assert(!std::is_reference::value, + "get() cannot be used with reference types, you might want to use get_ref()"); + return get_impl(detail::priority_tag<4> {}); + } + + /*! + @brief get a pointer value (explicit) + + Explicit pointer access to the internally stored JSON value. No copies are + made. + + @warning The pointer becomes invalid if the underlying JSON object + changes. + + @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref + object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, + @ref number_unsigned_t, or @ref number_float_t. + + @return pointer to the internally stored JSON value if the requested + pointer type @a PointerType fits to the JSON value; `nullptr` otherwise + + @complexity Constant. + + @liveexample{The example below shows how pointers to internal values of a + JSON value can be requested. Note that no type conversions are made and a + `nullptr` is returned if the value and the requested pointer type does not + match.,get__PointerType} + + @sa see @ref get_ptr() for explicit pointer-member access + + @since version 1.0.0 + */ + template::value, int>::type = 0> + auto get() noexcept -> decltype(std::declval().template get_ptr()) + { + // delegate the call to get_ptr + return get_ptr(); + } + + /*! + @brief get a value (explicit) + + Explicit type conversion between the JSON value and a compatible value. + The value is filled into the input parameter by calling the @ref json_serializer + `from_json()` method. + + The function is equivalent to executing + @code {.cpp} + ValueType v; + JSONSerializer::from_json(*this, v); + @endcode + + This overloads is chosen if: + - @a ValueType is not @ref basic_json, + - @ref json_serializer has a `from_json()` method of the form + `void from_json(const basic_json&, ValueType&)`, and + + @tparam ValueType the input parameter type. + + @return the input parameter, allowing chaining calls. + + @throw what @ref json_serializer `from_json()` method throws + + @liveexample{The example below shows several conversions from JSON values + to other types. There a few things to note: (1) Floating-point numbers can + be converted to integers\, (2) A JSON array can be converted to a standard + `std::vector`\, (3) A JSON object can be converted to C++ + associative containers such as `std::unordered_map`.,get_to} + + @since version 3.3.0 + */ + template < typename ValueType, + detail::enable_if_t < + !detail::is_basic_json::value&& + detail::has_from_json::value, + int > = 0 > + ValueType & get_to(ValueType& v) const noexcept(noexcept( + JSONSerializer::from_json(std::declval(), v))) + { + JSONSerializer::from_json(*this, v); + return v; + } + + // specialization to allow to call get_to with a basic_json value + // see https://github.com/nlohmann/json/issues/2175 + template::value, + int> = 0> + ValueType & get_to(ValueType& v) const + { + v = *this; + return v; + } + + template < + typename T, std::size_t N, + typename Array = T (&)[N], // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) + detail::enable_if_t < + detail::has_from_json::value, int > = 0 > + Array get_to(T (&v)[N]) const // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) + noexcept(noexcept(JSONSerializer::from_json( + std::declval(), v))) + { + JSONSerializer::from_json(*this, v); + return v; + } + + /*! + @brief get a reference value (implicit) + + Implicit reference access to the internally stored JSON value. No copies + are made. + + @warning Writing data to the referee of the result yields an undefined + state. + + @tparam ReferenceType reference type; must be a reference to @ref array_t, + @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, or + @ref number_float_t. Enforced by static assertion. + + @return reference to the internally stored JSON value if the requested + reference type @a ReferenceType fits to the JSON value; throws + type_error.303 otherwise + + @throw type_error.303 in case passed type @a ReferenceType is incompatible + with the stored JSON value; see example below + + @complexity Constant. + + @liveexample{The example shows several calls to `get_ref()`.,get_ref} + + @since version 1.1.0 + */ + template::value, int>::type = 0> + ReferenceType get_ref() + { + // delegate call to get_ref_impl + return get_ref_impl(*this); + } + + /*! + @brief get a reference value (implicit) + @copydoc get_ref() + */ + template < typename ReferenceType, typename std::enable_if < + std::is_reference::value&& + std::is_const::type>::value, int >::type = 0 > + ReferenceType get_ref() const + { + // delegate call to get_ref_impl + return get_ref_impl(*this); + } + + /*! + @brief get a value (implicit) + + Implicit type conversion between the JSON value and a compatible value. + The call is realized by calling @ref get() const. + + @tparam ValueType non-pointer type compatible to the JSON value, for + instance `int` for JSON integer numbers, `bool` for JSON booleans, or + `std::vector` types for JSON arrays. The character type of @ref string_t + as well as an initializer list of this type is excluded to avoid + ambiguities as these types implicitly convert to `std::string`. + + @return copy of the JSON value, converted to type @a ValueType + + @throw type_error.302 in case passed type @a ValueType is incompatible + to the JSON value type (e.g., the JSON value is of type boolean, but a + string is requested); see example below + + @complexity Linear in the size of the JSON value. + + @liveexample{The example below shows several conversions from JSON values + to other types. There a few things to note: (1) Floating-point numbers can + be converted to integers\, (2) A JSON array can be converted to a standard + `std::vector`\, (3) A JSON object can be converted to C++ + associative containers such as `std::unordered_map`.,operator__ValueType} + + @since version 1.0.0 + */ + template < typename ValueType, typename std::enable_if < + !std::is_pointer::value&& + !std::is_same>::value&& + !std::is_same::value&& + !detail::is_basic_json::value + && !std::is_same>::value +#if defined(JSON_HAS_CPP_17) && (defined(__GNUC__) || (defined(_MSC_VER) && _MSC_VER >= 1910 && _MSC_VER <= 1914)) + && !std::is_same::value +#endif + && detail::is_detected::value + , int >::type = 0 > + JSON_EXPLICIT operator ValueType() const + { + // delegate the call to get<>() const + return get(); + } + + /*! + @return reference to the binary value + + @throw type_error.302 if the value is not binary + + @sa see @ref is_binary() to check if the value is binary + + @since version 3.8.0 + */ + binary_t& get_binary() + { + if (!is_binary()) + { + JSON_THROW(type_error::create(302, "type must be binary, but is " + std::string(type_name()), *this)); + } + + return *get_ptr(); + } + + /// @copydoc get_binary() + const binary_t& get_binary() const + { + if (!is_binary()) + { + JSON_THROW(type_error::create(302, "type must be binary, but is " + std::string(type_name()), *this)); + } + + return *get_ptr(); + } + + /// @} + + + //////////////////// + // element access // + //////////////////// + + /// @name element access + /// Access to the JSON value. + /// @{ + + /*! + @brief access specified array element with bounds checking + + Returns a reference to the element at specified location @a idx, with + bounds checking. + + @param[in] idx index of the element to access + + @return reference to the element at index @a idx + + @throw type_error.304 if the JSON value is not an array; in this case, + calling `at` with an index makes no sense. See example below. + @throw out_of_range.401 if the index @a idx is out of range of the array; + that is, `idx >= size()`. See example below. + + @exceptionsafety Strong guarantee: if an exception is thrown, there are no + changes in the JSON value. + + @complexity Constant. + + @since version 1.0.0 + + @liveexample{The example below shows how array elements can be read and + written using `at()`. It also demonstrates the different exceptions that + can be thrown.,at__size_type} + */ + reference at(size_type idx) + { + // at only works for arrays + if (JSON_HEDLEY_LIKELY(is_array())) + { + JSON_TRY + { + return set_parent(m_value.array->at(idx)); + } + JSON_CATCH (std::out_of_range&) + { + // create better exception explanation + JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range", *this)); + } + } + else + { + JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()), *this)); + } + } + + /*! + @brief access specified array element with bounds checking + + Returns a const reference to the element at specified location @a idx, + with bounds checking. + + @param[in] idx index of the element to access + + @return const reference to the element at index @a idx + + @throw type_error.304 if the JSON value is not an array; in this case, + calling `at` with an index makes no sense. See example below. + @throw out_of_range.401 if the index @a idx is out of range of the array; + that is, `idx >= size()`. See example below. + + @exceptionsafety Strong guarantee: if an exception is thrown, there are no + changes in the JSON value. + + @complexity Constant. + + @since version 1.0.0 + + @liveexample{The example below shows how array elements can be read using + `at()`. It also demonstrates the different exceptions that can be thrown., + at__size_type_const} + */ + const_reference at(size_type idx) const + { + // at only works for arrays + if (JSON_HEDLEY_LIKELY(is_array())) + { + JSON_TRY + { + return m_value.array->at(idx); + } + JSON_CATCH (std::out_of_range&) + { + // create better exception explanation + JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range", *this)); + } + } + else + { + JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()), *this)); + } + } + + /*! + @brief access specified object element with bounds checking + + Returns a reference to the element at with specified key @a key, with + bounds checking. + + @param[in] key key of the element to access + + @return reference to the element at key @a key + + @throw type_error.304 if the JSON value is not an object; in this case, + calling `at` with a key makes no sense. See example below. + @throw out_of_range.403 if the key @a key is is not stored in the object; + that is, `find(key) == end()`. See example below. + + @exceptionsafety Strong guarantee: if an exception is thrown, there are no + changes in the JSON value. + + @complexity Logarithmic in the size of the container. + + @sa see @ref operator[](const typename object_t::key_type&) for unchecked + access by reference + @sa see @ref value() for access by value with a default value + + @since version 1.0.0 + + @liveexample{The example below shows how object elements can be read and + written using `at()`. It also demonstrates the different exceptions that + can be thrown.,at__object_t_key_type} + */ + reference at(const typename object_t::key_type& key) + { + // at only works for objects + if (JSON_HEDLEY_LIKELY(is_object())) + { + JSON_TRY + { + return set_parent(m_value.object->at(key)); + } + JSON_CATCH (std::out_of_range&) + { + // create better exception explanation + JSON_THROW(out_of_range::create(403, "key '" + key + "' not found", *this)); + } + } + else + { + JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()), *this)); + } + } + + /*! + @brief access specified object element with bounds checking + + Returns a const reference to the element at with specified key @a key, + with bounds checking. + + @param[in] key key of the element to access + + @return const reference to the element at key @a key + + @throw type_error.304 if the JSON value is not an object; in this case, + calling `at` with a key makes no sense. See example below. + @throw out_of_range.403 if the key @a key is is not stored in the object; + that is, `find(key) == end()`. See example below. + + @exceptionsafety Strong guarantee: if an exception is thrown, there are no + changes in the JSON value. + + @complexity Logarithmic in the size of the container. + + @sa see @ref operator[](const typename object_t::key_type&) for unchecked + access by reference + @sa see @ref value() for access by value with a default value + + @since version 1.0.0 + + @liveexample{The example below shows how object elements can be read using + `at()`. It also demonstrates the different exceptions that can be thrown., + at__object_t_key_type_const} + */ + const_reference at(const typename object_t::key_type& key) const + { + // at only works for objects + if (JSON_HEDLEY_LIKELY(is_object())) + { + JSON_TRY + { + return m_value.object->at(key); + } + JSON_CATCH (std::out_of_range&) + { + // create better exception explanation + JSON_THROW(out_of_range::create(403, "key '" + key + "' not found", *this)); + } + } + else + { + JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()), *this)); + } + } + + /*! + @brief access specified array element + + Returns a reference to the element at specified location @a idx. + + @note If @a idx is beyond the range of the array (i.e., `idx >= size()`), + then the array is silently filled up with `null` values to make `idx` a + valid reference to the last stored element. + + @param[in] idx index of the element to access + + @return reference to the element at index @a idx + + @throw type_error.305 if the JSON value is not an array or null; in that + cases, using the [] operator with an index makes no sense. + + @complexity Constant if @a idx is in the range of the array. Otherwise + linear in `idx - size()`. + + @liveexample{The example below shows how array elements can be read and + written using `[]` operator. Note the addition of `null` + values.,operatorarray__size_type} + + @since version 1.0.0 + */ + reference operator[](size_type idx) + { + // implicitly convert null value to an empty array + if (is_null()) + { + m_type = value_t::array; + m_value.array = create(); + assert_invariant(); + } + + // operator[] only works for arrays + if (JSON_HEDLEY_LIKELY(is_array())) + { + // fill up array with null values if given idx is outside range + if (idx >= m_value.array->size()) + { +#if JSON_DIAGNOSTICS + // remember array size before resizing + const auto previous_size = m_value.array->size(); +#endif + m_value.array->resize(idx + 1); + +#if JSON_DIAGNOSTICS + // set parent for values added above + set_parents(begin() + static_cast(previous_size), static_cast(idx + 1 - previous_size)); +#endif + } + + return m_value.array->operator[](idx); + } + + JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name()), *this)); + } + + /*! + @brief access specified array element + + Returns a const reference to the element at specified location @a idx. + + @param[in] idx index of the element to access + + @return const reference to the element at index @a idx + + @throw type_error.305 if the JSON value is not an array; in that case, + using the [] operator with an index makes no sense. + + @complexity Constant. + + @liveexample{The example below shows how array elements can be read using + the `[]` operator.,operatorarray__size_type_const} + + @since version 1.0.0 + */ + const_reference operator[](size_type idx) const + { + // const operator[] only works for arrays + if (JSON_HEDLEY_LIKELY(is_array())) + { + return m_value.array->operator[](idx); + } + + JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name()), *this)); + } + + /*! + @brief access specified object element + + Returns a reference to the element at with specified key @a key. + + @note If @a key is not found in the object, then it is silently added to + the object and filled with a `null` value to make `key` a valid reference. + In case the value was `null` before, it is converted to an object. + + @param[in] key key of the element to access + + @return reference to the element at key @a key + + @throw type_error.305 if the JSON value is not an object or null; in that + cases, using the [] operator with a key makes no sense. + + @complexity Logarithmic in the size of the container. + + @liveexample{The example below shows how object elements can be read and + written using the `[]` operator.,operatorarray__key_type} + + @sa see @ref at(const typename object_t::key_type&) for access by reference + with range checking + @sa see @ref value() for access by value with a default value + + @since version 1.0.0 + */ + reference operator[](const typename object_t::key_type& key) + { + // implicitly convert null value to an empty object + if (is_null()) + { + m_type = value_t::object; + m_value.object = create(); + assert_invariant(); + } + + // operator[] only works for objects + if (JSON_HEDLEY_LIKELY(is_object())) + { + return set_parent(m_value.object->operator[](key)); + } + + JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()), *this)); + } + + /*! + @brief read-only access specified object element + + Returns a const reference to the element at with specified key @a key. No + bounds checking is performed. + + @warning If the element with key @a key does not exist, the behavior is + undefined. + + @param[in] key key of the element to access + + @return const reference to the element at key @a key + + @pre The element with key @a key must exist. **This precondition is + enforced with an assertion.** + + @throw type_error.305 if the JSON value is not an object; in that case, + using the [] operator with a key makes no sense. + + @complexity Logarithmic in the size of the container. + + @liveexample{The example below shows how object elements can be read using + the `[]` operator.,operatorarray__key_type_const} + + @sa see @ref at(const typename object_t::key_type&) for access by reference + with range checking + @sa see @ref value() for access by value with a default value + + @since version 1.0.0 + */ + const_reference operator[](const typename object_t::key_type& key) const + { + // const operator[] only works for objects + if (JSON_HEDLEY_LIKELY(is_object())) + { + JSON_ASSERT(m_value.object->find(key) != m_value.object->end()); + return m_value.object->find(key)->second; + } + + JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()), *this)); + } + + /*! + @brief access specified object element + + Returns a reference to the element at with specified key @a key. + + @note If @a key is not found in the object, then it is silently added to + the object and filled with a `null` value to make `key` a valid reference. + In case the value was `null` before, it is converted to an object. + + @param[in] key key of the element to access + + @return reference to the element at key @a key + + @throw type_error.305 if the JSON value is not an object or null; in that + cases, using the [] operator with a key makes no sense. + + @complexity Logarithmic in the size of the container. + + @liveexample{The example below shows how object elements can be read and + written using the `[]` operator.,operatorarray__key_type} + + @sa see @ref at(const typename object_t::key_type&) for access by reference + with range checking + @sa see @ref value() for access by value with a default value + + @since version 1.1.0 + */ + template + JSON_HEDLEY_NON_NULL(2) + reference operator[](T* key) + { + // implicitly convert null to object + if (is_null()) + { + m_type = value_t::object; + m_value = value_t::object; + assert_invariant(); + } + + // at only works for objects + if (JSON_HEDLEY_LIKELY(is_object())) + { + return set_parent(m_value.object->operator[](key)); + } + + JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()), *this)); + } + + /*! + @brief read-only access specified object element + + Returns a const reference to the element at with specified key @a key. No + bounds checking is performed. + + @warning If the element with key @a key does not exist, the behavior is + undefined. + + @param[in] key key of the element to access + + @return const reference to the element at key @a key + + @pre The element with key @a key must exist. **This precondition is + enforced with an assertion.** + + @throw type_error.305 if the JSON value is not an object; in that case, + using the [] operator with a key makes no sense. + + @complexity Logarithmic in the size of the container. + + @liveexample{The example below shows how object elements can be read using + the `[]` operator.,operatorarray__key_type_const} + + @sa see @ref at(const typename object_t::key_type&) for access by reference + with range checking + @sa see @ref value() for access by value with a default value + + @since version 1.1.0 + */ + template + JSON_HEDLEY_NON_NULL(2) + const_reference operator[](T* key) const + { + // at only works for objects + if (JSON_HEDLEY_LIKELY(is_object())) + { + JSON_ASSERT(m_value.object->find(key) != m_value.object->end()); + return m_value.object->find(key)->second; + } + + JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()), *this)); + } + + /*! + @brief access specified object element with default value + + Returns either a copy of an object's element at the specified key @a key + or a given default value if no element with key @a key exists. + + The function is basically equivalent to executing + @code {.cpp} + try { + return at(key); + } catch(out_of_range) { + return default_value; + } + @endcode + + @note Unlike @ref at(const typename object_t::key_type&), this function + does not throw if the given key @a key was not found. + + @note Unlike @ref operator[](const typename object_t::key_type& key), this + function does not implicitly add an element to the position defined by @a + key. This function is furthermore also applicable to const objects. + + @param[in] key key of the element to access + @param[in] default_value the value to return if @a key is not found + + @tparam ValueType type compatible to JSON values, for instance `int` for + JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for + JSON arrays. Note the type of the expected value at @a key and the default + value @a default_value must be compatible. + + @return copy of the element at key @a key or @a default_value if @a key + is not found + + @throw type_error.302 if @a default_value does not match the type of the + value at @a key + @throw type_error.306 if the JSON value is not an object; in that case, + using `value()` with a key makes no sense. + + @complexity Logarithmic in the size of the container. + + @liveexample{The example below shows how object elements can be queried + with a default value.,basic_json__value} + + @sa see @ref at(const typename object_t::key_type&) for access by reference + with range checking + @sa see @ref operator[](const typename object_t::key_type&) for unchecked + access by reference + + @since version 1.0.0 + */ + // using std::is_convertible in a std::enable_if will fail when using explicit conversions + template < class ValueType, typename std::enable_if < + detail::is_getable::value + && !std::is_same::value, int >::type = 0 > + ValueType value(const typename object_t::key_type& key, const ValueType& default_value) const + { + // at only works for objects + if (JSON_HEDLEY_LIKELY(is_object())) + { + // if key is found, return value and given default value otherwise + const auto it = find(key); + if (it != end()) + { + return it->template get(); + } + + return default_value; + } + + JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name()), *this)); + } + + /*! + @brief overload for a default value of type const char* + @copydoc basic_json::value(const typename object_t::key_type&, const ValueType&) const + */ + string_t value(const typename object_t::key_type& key, const char* default_value) const + { + return value(key, string_t(default_value)); + } + + /*! + @brief access specified object element via JSON Pointer with default value + + Returns either a copy of an object's element at the specified key @a key + or a given default value if no element with key @a key exists. + + The function is basically equivalent to executing + @code {.cpp} + try { + return at(ptr); + } catch(out_of_range) { + return default_value; + } + @endcode + + @note Unlike @ref at(const json_pointer&), this function does not throw + if the given key @a key was not found. + + @param[in] ptr a JSON pointer to the element to access + @param[in] default_value the value to return if @a ptr found no value + + @tparam ValueType type compatible to JSON values, for instance `int` for + JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for + JSON arrays. Note the type of the expected value at @a key and the default + value @a default_value must be compatible. + + @return copy of the element at key @a key or @a default_value if @a key + is not found + + @throw type_error.302 if @a default_value does not match the type of the + value at @a ptr + @throw type_error.306 if the JSON value is not an object; in that case, + using `value()` with a key makes no sense. + + @complexity Logarithmic in the size of the container. + + @liveexample{The example below shows how object elements can be queried + with a default value.,basic_json__value_ptr} + + @sa see @ref operator[](const json_pointer&) for unchecked access by reference + + @since version 2.0.2 + */ + template::value, int>::type = 0> + ValueType value(const json_pointer& ptr, const ValueType& default_value) const + { + // at only works for objects + if (JSON_HEDLEY_LIKELY(is_object())) + { + // if pointer resolves a value, return it or use default value + JSON_TRY + { + return ptr.get_checked(this).template get(); + } + JSON_INTERNAL_CATCH (out_of_range&) + { + return default_value; + } + } + + JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name()), *this)); + } + + /*! + @brief overload for a default value of type const char* + @copydoc basic_json::value(const json_pointer&, ValueType) const + */ + JSON_HEDLEY_NON_NULL(3) + string_t value(const json_pointer& ptr, const char* default_value) const + { + return value(ptr, string_t(default_value)); + } + + /*! + @brief access the first element + + Returns a reference to the first element in the container. For a JSON + container `c`, the expression `c.front()` is equivalent to `*c.begin()`. + + @return In case of a structured type (array or object), a reference to the + first element is returned. In case of number, string, boolean, or binary + values, a reference to the value is returned. + + @complexity Constant. + + @pre The JSON value must not be `null` (would throw `std::out_of_range`) + or an empty array or object (undefined behavior, **guarded by + assertions**). + @post The JSON value remains unchanged. + + @throw invalid_iterator.214 when called on `null` value + + @liveexample{The following code shows an example for `front()`.,front} + + @sa see @ref back() -- access the last element + + @since version 1.0.0 + */ + reference front() + { + return *begin(); + } + + /*! + @copydoc basic_json::front() + */ + const_reference front() const + { + return *cbegin(); + } + + /*! + @brief access the last element + + Returns a reference to the last element in the container. For a JSON + container `c`, the expression `c.back()` is equivalent to + @code {.cpp} + auto tmp = c.end(); + --tmp; + return *tmp; + @endcode + + @return In case of a structured type (array or object), a reference to the + last element is returned. In case of number, string, boolean, or binary + values, a reference to the value is returned. + + @complexity Constant. + + @pre The JSON value must not be `null` (would throw `std::out_of_range`) + or an empty array or object (undefined behavior, **guarded by + assertions**). + @post The JSON value remains unchanged. + + @throw invalid_iterator.214 when called on a `null` value. See example + below. + + @liveexample{The following code shows an example for `back()`.,back} + + @sa see @ref front() -- access the first element + + @since version 1.0.0 + */ + reference back() + { + auto tmp = end(); + --tmp; + return *tmp; + } + + /*! + @copydoc basic_json::back() + */ + const_reference back() const + { + auto tmp = cend(); + --tmp; + return *tmp; + } + + /*! + @brief remove element given an iterator + + Removes the element specified by iterator @a pos. The iterator @a pos must + be valid and dereferenceable. Thus the `end()` iterator (which is valid, + but is not dereferenceable) cannot be used as a value for @a pos. + + If called on a primitive type other than `null`, the resulting JSON value + will be `null`. + + @param[in] pos iterator to the element to remove + @return Iterator following the last removed element. If the iterator @a + pos refers to the last element, the `end()` iterator is returned. + + @tparam IteratorType an @ref iterator or @ref const_iterator + + @post Invalidates iterators and references at or after the point of the + erase, including the `end()` iterator. + + @throw type_error.307 if called on a `null` value; example: `"cannot use + erase() with null"` + @throw invalid_iterator.202 if called on an iterator which does not belong + to the current JSON value; example: `"iterator does not fit current + value"` + @throw invalid_iterator.205 if called on a primitive type with invalid + iterator (i.e., any iterator which is not `begin()`); example: `"iterator + out of range"` + + @complexity The complexity depends on the type: + - objects: amortized constant + - arrays: linear in distance between @a pos and the end of the container + - strings and binary: linear in the length of the member + - other types: constant + + @liveexample{The example shows the result of `erase()` for different JSON + types.,erase__IteratorType} + + @sa see @ref erase(IteratorType, IteratorType) -- removes the elements in + the given range + @sa see @ref erase(const typename object_t::key_type&) -- removes the element + from an object at the given key + @sa see @ref erase(const size_type) -- removes the element from an array at + the given index + + @since version 1.0.0 + */ + template < class IteratorType, typename std::enable_if < + std::is_same::value || + std::is_same::value, int >::type + = 0 > + IteratorType erase(IteratorType pos) + { + // make sure iterator fits the current value + if (JSON_HEDLEY_UNLIKELY(this != pos.m_object)) + { + JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this)); + } + + IteratorType result = end(); + + switch (m_type) + { + case value_t::boolean: + case value_t::number_float: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::string: + case value_t::binary: + { + if (JSON_HEDLEY_UNLIKELY(!pos.m_it.primitive_iterator.is_begin())) + { + JSON_THROW(invalid_iterator::create(205, "iterator out of range", *this)); + } + + if (is_string()) + { + AllocatorType alloc; + std::allocator_traits::destroy(alloc, m_value.string); + std::allocator_traits::deallocate(alloc, m_value.string, 1); + m_value.string = nullptr; + } + else if (is_binary()) + { + AllocatorType alloc; + std::allocator_traits::destroy(alloc, m_value.binary); + std::allocator_traits::deallocate(alloc, m_value.binary, 1); + m_value.binary = nullptr; + } + + m_type = value_t::null; + assert_invariant(); + break; + } + + case value_t::object: + { + result.m_it.object_iterator = m_value.object->erase(pos.m_it.object_iterator); + break; + } + + case value_t::array: + { + result.m_it.array_iterator = m_value.array->erase(pos.m_it.array_iterator); + break; + } + + default: + JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()), *this)); + } + + return result; + } + + /*! + @brief remove elements given an iterator range + + Removes the element specified by the range `[first; last)`. The iterator + @a first does not need to be dereferenceable if `first == last`: erasing + an empty range is a no-op. + + If called on a primitive type other than `null`, the resulting JSON value + will be `null`. + + @param[in] first iterator to the beginning of the range to remove + @param[in] last iterator past the end of the range to remove + @return Iterator following the last removed element. If the iterator @a + second refers to the last element, the `end()` iterator is returned. + + @tparam IteratorType an @ref iterator or @ref const_iterator + + @post Invalidates iterators and references at or after the point of the + erase, including the `end()` iterator. + + @throw type_error.307 if called on a `null` value; example: `"cannot use + erase() with null"` + @throw invalid_iterator.203 if called on iterators which does not belong + to the current JSON value; example: `"iterators do not fit current value"` + @throw invalid_iterator.204 if called on a primitive type with invalid + iterators (i.e., if `first != begin()` and `last != end()`); example: + `"iterators out of range"` + + @complexity The complexity depends on the type: + - objects: `log(size()) + std::distance(first, last)` + - arrays: linear in the distance between @a first and @a last, plus linear + in the distance between @a last and end of the container + - strings and binary: linear in the length of the member + - other types: constant + + @liveexample{The example shows the result of `erase()` for different JSON + types.,erase__IteratorType_IteratorType} + + @sa see @ref erase(IteratorType) -- removes the element at a given position + @sa see @ref erase(const typename object_t::key_type&) -- removes the element + from an object at the given key + @sa see @ref erase(const size_type) -- removes the element from an array at + the given index + + @since version 1.0.0 + */ + template < class IteratorType, typename std::enable_if < + std::is_same::value || + std::is_same::value, int >::type + = 0 > + IteratorType erase(IteratorType first, IteratorType last) + { + // make sure iterator fits the current value + if (JSON_HEDLEY_UNLIKELY(this != first.m_object || this != last.m_object)) + { + JSON_THROW(invalid_iterator::create(203, "iterators do not fit current value", *this)); + } + + IteratorType result = end(); + + switch (m_type) + { + case value_t::boolean: + case value_t::number_float: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::string: + case value_t::binary: + { + if (JSON_HEDLEY_LIKELY(!first.m_it.primitive_iterator.is_begin() + || !last.m_it.primitive_iterator.is_end())) + { + JSON_THROW(invalid_iterator::create(204, "iterators out of range", *this)); + } + + if (is_string()) + { + AllocatorType alloc; + std::allocator_traits::destroy(alloc, m_value.string); + std::allocator_traits::deallocate(alloc, m_value.string, 1); + m_value.string = nullptr; + } + else if (is_binary()) + { + AllocatorType alloc; + std::allocator_traits::destroy(alloc, m_value.binary); + std::allocator_traits::deallocate(alloc, m_value.binary, 1); + m_value.binary = nullptr; + } + + m_type = value_t::null; + assert_invariant(); + break; + } + + case value_t::object: + { + result.m_it.object_iterator = m_value.object->erase(first.m_it.object_iterator, + last.m_it.object_iterator); + break; + } + + case value_t::array: + { + result.m_it.array_iterator = m_value.array->erase(first.m_it.array_iterator, + last.m_it.array_iterator); + break; + } + + default: + JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()), *this)); + } + + return result; + } + + /*! + @brief remove element from a JSON object given a key + + Removes elements from a JSON object with the key value @a key. + + @param[in] key value of the elements to remove + + @return Number of elements removed. If @a ObjectType is the default + `std::map` type, the return value will always be `0` (@a key was not + found) or `1` (@a key was found). + + @post References and iterators to the erased elements are invalidated. + Other references and iterators are not affected. + + @throw type_error.307 when called on a type other than JSON object; + example: `"cannot use erase() with null"` + + @complexity `log(size()) + count(key)` + + @liveexample{The example shows the effect of `erase()`.,erase__key_type} + + @sa see @ref erase(IteratorType) -- removes the element at a given position + @sa see @ref erase(IteratorType, IteratorType) -- removes the elements in + the given range + @sa see @ref erase(const size_type) -- removes the element from an array at + the given index + + @since version 1.0.0 + */ + size_type erase(const typename object_t::key_type& key) + { + // this erase only works for objects + if (JSON_HEDLEY_LIKELY(is_object())) + { + return m_value.object->erase(key); + } + + JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()), *this)); + } + + /*! + @brief remove element from a JSON array given an index + + Removes element from a JSON array at the index @a idx. + + @param[in] idx index of the element to remove + + @throw type_error.307 when called on a type other than JSON object; + example: `"cannot use erase() with null"` + @throw out_of_range.401 when `idx >= size()`; example: `"array index 17 + is out of range"` + + @complexity Linear in distance between @a idx and the end of the container. + + @liveexample{The example shows the effect of `erase()`.,erase__size_type} + + @sa see @ref erase(IteratorType) -- removes the element at a given position + @sa see @ref erase(IteratorType, IteratorType) -- removes the elements in + the given range + @sa see @ref erase(const typename object_t::key_type&) -- removes the element + from an object at the given key + + @since version 1.0.0 + */ + void erase(const size_type idx) + { + // this erase only works for arrays + if (JSON_HEDLEY_LIKELY(is_array())) + { + if (JSON_HEDLEY_UNLIKELY(idx >= size())) + { + JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range", *this)); + } + + m_value.array->erase(m_value.array->begin() + static_cast(idx)); + } + else + { + JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()), *this)); + } + } + + /// @} + + + //////////// + // lookup // + //////////// + + /// @name lookup + /// @{ + + /*! + @brief find an element in a JSON object + + Finds an element in a JSON object with key equivalent to @a key. If the + element is not found or the JSON value is not an object, end() is + returned. + + @note This method always returns @ref end() when executed on a JSON type + that is not an object. + + @param[in] key key value of the element to search for. + + @return Iterator to an element with key equivalent to @a key. If no such + element is found or the JSON value is not an object, past-the-end (see + @ref end()) iterator is returned. + + @complexity Logarithmic in the size of the JSON object. + + @liveexample{The example shows how `find()` is used.,find__key_type} + + @sa see @ref contains(KeyT&&) const -- checks whether a key exists + + @since version 1.0.0 + */ + template + iterator find(KeyT&& key) + { + auto result = end(); + + if (is_object()) + { + result.m_it.object_iterator = m_value.object->find(std::forward(key)); + } + + return result; + } + + /*! + @brief find an element in a JSON object + @copydoc find(KeyT&&) + */ + template + const_iterator find(KeyT&& key) const + { + auto result = cend(); + + if (is_object()) + { + result.m_it.object_iterator = m_value.object->find(std::forward(key)); + } + + return result; + } + + /*! + @brief returns the number of occurrences of a key in a JSON object + + Returns the number of elements with key @a key. If ObjectType is the + default `std::map` type, the return value will always be `0` (@a key was + not found) or `1` (@a key was found). + + @note This method always returns `0` when executed on a JSON type that is + not an object. + + @param[in] key key value of the element to count + + @return Number of elements with key @a key. If the JSON value is not an + object, the return value will be `0`. + + @complexity Logarithmic in the size of the JSON object. + + @liveexample{The example shows how `count()` is used.,count} + + @since version 1.0.0 + */ + template + size_type count(KeyT&& key) const + { + // return 0 for all nonobject types + return is_object() ? m_value.object->count(std::forward(key)) : 0; + } + + /*! + @brief check the existence of an element in a JSON object + + Check whether an element exists in a JSON object with key equivalent to + @a key. If the element is not found or the JSON value is not an object, + false is returned. + + @note This method always returns false when executed on a JSON type + that is not an object. + + @param[in] key key value to check its existence. + + @return true if an element with specified @a key exists. If no such + element with such key is found or the JSON value is not an object, + false is returned. + + @complexity Logarithmic in the size of the JSON object. + + @liveexample{The following code shows an example for `contains()`.,contains} + + @sa see @ref find(KeyT&&) -- returns an iterator to an object element + @sa see @ref contains(const json_pointer&) const -- checks the existence for a JSON pointer + + @since version 3.6.0 + */ + template < typename KeyT, typename std::enable_if < + !std::is_same::type, json_pointer>::value, int >::type = 0 > + bool contains(KeyT && key) const + { + return is_object() && m_value.object->find(std::forward(key)) != m_value.object->end(); + } + + /*! + @brief check the existence of an element in a JSON object given a JSON pointer + + Check whether the given JSON pointer @a ptr can be resolved in the current + JSON value. + + @note This method can be executed on any JSON value type. + + @param[in] ptr JSON pointer to check its existence. + + @return true if the JSON pointer can be resolved to a stored value, false + otherwise. + + @post If `j.contains(ptr)` returns true, it is safe to call `j[ptr]`. + + @throw parse_error.106 if an array index begins with '0' + @throw parse_error.109 if an array index was not a number + + @complexity Logarithmic in the size of the JSON object. + + @liveexample{The following code shows an example for `contains()`.,contains_json_pointer} + + @sa see @ref contains(KeyT &&) const -- checks the existence of a key + + @since version 3.7.0 + */ + bool contains(const json_pointer& ptr) const + { + return ptr.contains(this); + } + + /// @} + + + /////////////// + // iterators // + /////////////// + + /// @name iterators + /// @{ + + /*! + @brief returns an iterator to the first element + + Returns an iterator to the first element. + + @image html range-begin-end.svg "Illustration from cppreference.com" + + @return iterator to the first element + + @complexity Constant. + + @requirement This function helps `basic_json` satisfying the + [Container](https://en.cppreference.com/w/cpp/named_req/Container) + requirements: + - The complexity is constant. + + @liveexample{The following code shows an example for `begin()`.,begin} + + @sa see @ref cbegin() -- returns a const iterator to the beginning + @sa see @ref end() -- returns an iterator to the end + @sa see @ref cend() -- returns a const iterator to the end + + @since version 1.0.0 + */ + iterator begin() noexcept + { + iterator result(this); + result.set_begin(); + return result; + } + + /*! + @copydoc basic_json::cbegin() + */ + const_iterator begin() const noexcept + { + return cbegin(); + } + + /*! + @brief returns a const iterator to the first element + + Returns a const iterator to the first element. + + @image html range-begin-end.svg "Illustration from cppreference.com" + + @return const iterator to the first element + + @complexity Constant. + + @requirement This function helps `basic_json` satisfying the + [Container](https://en.cppreference.com/w/cpp/named_req/Container) + requirements: + - The complexity is constant. + - Has the semantics of `const_cast(*this).begin()`. + + @liveexample{The following code shows an example for `cbegin()`.,cbegin} + + @sa see @ref begin() -- returns an iterator to the beginning + @sa see @ref end() -- returns an iterator to the end + @sa see @ref cend() -- returns a const iterator to the end + + @since version 1.0.0 + */ + const_iterator cbegin() const noexcept + { + const_iterator result(this); + result.set_begin(); + return result; + } + + /*! + @brief returns an iterator to one past the last element + + Returns an iterator to one past the last element. + + @image html range-begin-end.svg "Illustration from cppreference.com" + + @return iterator one past the last element + + @complexity Constant. + + @requirement This function helps `basic_json` satisfying the + [Container](https://en.cppreference.com/w/cpp/named_req/Container) + requirements: + - The complexity is constant. + + @liveexample{The following code shows an example for `end()`.,end} + + @sa see @ref cend() -- returns a const iterator to the end + @sa see @ref begin() -- returns an iterator to the beginning + @sa see @ref cbegin() -- returns a const iterator to the beginning + + @since version 1.0.0 + */ + iterator end() noexcept + { + iterator result(this); + result.set_end(); + return result; + } + + /*! + @copydoc basic_json::cend() + */ + const_iterator end() const noexcept + { + return cend(); + } + + /*! + @brief returns a const iterator to one past the last element + + Returns a const iterator to one past the last element. + + @image html range-begin-end.svg "Illustration from cppreference.com" + + @return const iterator one past the last element + + @complexity Constant. + + @requirement This function helps `basic_json` satisfying the + [Container](https://en.cppreference.com/w/cpp/named_req/Container) + requirements: + - The complexity is constant. + - Has the semantics of `const_cast(*this).end()`. + + @liveexample{The following code shows an example for `cend()`.,cend} + + @sa see @ref end() -- returns an iterator to the end + @sa see @ref begin() -- returns an iterator to the beginning + @sa see @ref cbegin() -- returns a const iterator to the beginning + + @since version 1.0.0 + */ + const_iterator cend() const noexcept + { + const_iterator result(this); + result.set_end(); + return result; + } + + /*! + @brief returns an iterator to the reverse-beginning + + Returns an iterator to the reverse-beginning; that is, the last element. + + @image html range-rbegin-rend.svg "Illustration from cppreference.com" + + @complexity Constant. + + @requirement This function helps `basic_json` satisfying the + [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer) + requirements: + - The complexity is constant. + - Has the semantics of `reverse_iterator(end())`. + + @liveexample{The following code shows an example for `rbegin()`.,rbegin} + + @sa see @ref crbegin() -- returns a const reverse iterator to the beginning + @sa see @ref rend() -- returns a reverse iterator to the end + @sa see @ref crend() -- returns a const reverse iterator to the end + + @since version 1.0.0 + */ + reverse_iterator rbegin() noexcept + { + return reverse_iterator(end()); + } + + /*! + @copydoc basic_json::crbegin() + */ + const_reverse_iterator rbegin() const noexcept + { + return crbegin(); + } + + /*! + @brief returns an iterator to the reverse-end + + Returns an iterator to the reverse-end; that is, one before the first + element. + + @image html range-rbegin-rend.svg "Illustration from cppreference.com" + + @complexity Constant. + + @requirement This function helps `basic_json` satisfying the + [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer) + requirements: + - The complexity is constant. + - Has the semantics of `reverse_iterator(begin())`. + + @liveexample{The following code shows an example for `rend()`.,rend} + + @sa see @ref crend() -- returns a const reverse iterator to the end + @sa see @ref rbegin() -- returns a reverse iterator to the beginning + @sa see @ref crbegin() -- returns a const reverse iterator to the beginning + + @since version 1.0.0 + */ + reverse_iterator rend() noexcept + { + return reverse_iterator(begin()); + } + + /*! + @copydoc basic_json::crend() + */ + const_reverse_iterator rend() const noexcept + { + return crend(); + } + + /*! + @brief returns a const reverse iterator to the last element + + Returns a const iterator to the reverse-beginning; that is, the last + element. + + @image html range-rbegin-rend.svg "Illustration from cppreference.com" + + @complexity Constant. + + @requirement This function helps `basic_json` satisfying the + [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer) + requirements: + - The complexity is constant. + - Has the semantics of `const_cast(*this).rbegin()`. + + @liveexample{The following code shows an example for `crbegin()`.,crbegin} + + @sa see @ref rbegin() -- returns a reverse iterator to the beginning + @sa see @ref rend() -- returns a reverse iterator to the end + @sa see @ref crend() -- returns a const reverse iterator to the end + + @since version 1.0.0 + */ + const_reverse_iterator crbegin() const noexcept + { + return const_reverse_iterator(cend()); + } + + /*! + @brief returns a const reverse iterator to one before the first + + Returns a const reverse iterator to the reverse-end; that is, one before + the first element. + + @image html range-rbegin-rend.svg "Illustration from cppreference.com" + + @complexity Constant. + + @requirement This function helps `basic_json` satisfying the + [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer) + requirements: + - The complexity is constant. + - Has the semantics of `const_cast(*this).rend()`. + + @liveexample{The following code shows an example for `crend()`.,crend} + + @sa see @ref rend() -- returns a reverse iterator to the end + @sa see @ref rbegin() -- returns a reverse iterator to the beginning + @sa see @ref crbegin() -- returns a const reverse iterator to the beginning + + @since version 1.0.0 + */ + const_reverse_iterator crend() const noexcept + { + return const_reverse_iterator(cbegin()); + } + + public: + /*! + @brief wrapper to access iterator member functions in range-based for + + This function allows to access @ref iterator::key() and @ref + iterator::value() during range-based for loops. In these loops, a + reference to the JSON values is returned, so there is no access to the + underlying iterator. + + For loop without iterator_wrapper: + + @code{cpp} + for (auto it = j_object.begin(); it != j_object.end(); ++it) + { + std::cout << "key: " << it.key() << ", value:" << it.value() << '\n'; + } + @endcode + + Range-based for loop without iterator proxy: + + @code{cpp} + for (auto it : j_object) + { + // "it" is of type json::reference and has no key() member + std::cout << "value: " << it << '\n'; + } + @endcode + + Range-based for loop with iterator proxy: + + @code{cpp} + for (auto it : json::iterator_wrapper(j_object)) + { + std::cout << "key: " << it.key() << ", value:" << it.value() << '\n'; + } + @endcode + + @note When iterating over an array, `key()` will return the index of the + element as string (see example). + + @param[in] ref reference to a JSON value + @return iteration proxy object wrapping @a ref with an interface to use in + range-based for loops + + @liveexample{The following code shows how the wrapper is used,iterator_wrapper} + + @exceptionsafety Strong guarantee: if an exception is thrown, there are no + changes in the JSON value. + + @complexity Constant. + + @note The name of this function is not yet final and may change in the + future. + + @deprecated This stream operator is deprecated and will be removed in + future 4.0.0 of the library. Please use @ref items() instead; + that is, replace `json::iterator_wrapper(j)` with `j.items()`. + */ + JSON_HEDLEY_DEPRECATED_FOR(3.1.0, items()) + static iteration_proxy iterator_wrapper(reference ref) noexcept + { + return ref.items(); + } + + /*! + @copydoc iterator_wrapper(reference) + */ + JSON_HEDLEY_DEPRECATED_FOR(3.1.0, items()) + static iteration_proxy iterator_wrapper(const_reference ref) noexcept + { + return ref.items(); + } + + /*! + @brief helper to access iterator member functions in range-based for + + This function allows to access @ref iterator::key() and @ref + iterator::value() during range-based for loops. In these loops, a + reference to the JSON values is returned, so there is no access to the + underlying iterator. + + For loop without `items()` function: + + @code{cpp} + for (auto it = j_object.begin(); it != j_object.end(); ++it) + { + std::cout << "key: " << it.key() << ", value:" << it.value() << '\n'; + } + @endcode + + Range-based for loop without `items()` function: + + @code{cpp} + for (auto it : j_object) + { + // "it" is of type json::reference and has no key() member + std::cout << "value: " << it << '\n'; + } + @endcode + + Range-based for loop with `items()` function: + + @code{cpp} + for (auto& el : j_object.items()) + { + std::cout << "key: " << el.key() << ", value:" << el.value() << '\n'; + } + @endcode + + The `items()` function also allows to use + [structured bindings](https://en.cppreference.com/w/cpp/language/structured_binding) + (C++17): + + @code{cpp} + for (auto& [key, val] : j_object.items()) + { + std::cout << "key: " << key << ", value:" << val << '\n'; + } + @endcode + + @note When iterating over an array, `key()` will return the index of the + element as string (see example). For primitive types (e.g., numbers), + `key()` returns an empty string. + + @warning Using `items()` on temporary objects is dangerous. Make sure the + object's lifetime exeeds the iteration. See + for more + information. + + @return iteration proxy object wrapping @a ref with an interface to use in + range-based for loops + + @liveexample{The following code shows how the function is used.,items} + + @exceptionsafety Strong guarantee: if an exception is thrown, there are no + changes in the JSON value. + + @complexity Constant. + + @since version 3.1.0, structured bindings support since 3.5.0. + */ + iteration_proxy items() noexcept + { + return iteration_proxy(*this); + } + + /*! + @copydoc items() + */ + iteration_proxy items() const noexcept + { + return iteration_proxy(*this); + } + + /// @} + + + ////////////// + // capacity // + ////////////// + + /// @name capacity + /// @{ + + /*! + @brief checks whether the container is empty. + + Checks if a JSON value has no elements (i.e. whether its @ref size is `0`). + + @return The return value depends on the different types and is + defined as follows: + Value type | return value + ----------- | ------------- + null | `true` + boolean | `false` + string | `false` + number | `false` + binary | `false` + object | result of function `object_t::empty()` + array | result of function `array_t::empty()` + + @liveexample{The following code uses `empty()` to check if a JSON + object contains any elements.,empty} + + @complexity Constant, as long as @ref array_t and @ref object_t satisfy + the Container concept; that is, their `empty()` functions have constant + complexity. + + @iterators No changes. + + @exceptionsafety No-throw guarantee: this function never throws exceptions. + + @note This function does not return whether a string stored as JSON value + is empty - it returns whether the JSON container itself is empty which is + false in the case of a string. + + @requirement This function helps `basic_json` satisfying the + [Container](https://en.cppreference.com/w/cpp/named_req/Container) + requirements: + - The complexity is constant. + - Has the semantics of `begin() == end()`. + + @sa see @ref size() -- returns the number of elements + + @since version 1.0.0 + */ + bool empty() const noexcept + { + switch (m_type) + { + case value_t::null: + { + // null values are empty + return true; + } + + case value_t::array: + { + // delegate call to array_t::empty() + return m_value.array->empty(); + } + + case value_t::object: + { + // delegate call to object_t::empty() + return m_value.object->empty(); + } + + default: + { + // all other types are nonempty + return false; + } + } + } + + /*! + @brief returns the number of elements + + Returns the number of elements in a JSON value. + + @return The return value depends on the different types and is + defined as follows: + Value type | return value + ----------- | ------------- + null | `0` + boolean | `1` + string | `1` + number | `1` + binary | `1` + object | result of function object_t::size() + array | result of function array_t::size() + + @liveexample{The following code calls `size()` on the different value + types.,size} + + @complexity Constant, as long as @ref array_t and @ref object_t satisfy + the Container concept; that is, their size() functions have constant + complexity. + + @iterators No changes. + + @exceptionsafety No-throw guarantee: this function never throws exceptions. + + @note This function does not return the length of a string stored as JSON + value - it returns the number of elements in the JSON value which is 1 in + the case of a string. + + @requirement This function helps `basic_json` satisfying the + [Container](https://en.cppreference.com/w/cpp/named_req/Container) + requirements: + - The complexity is constant. + - Has the semantics of `std::distance(begin(), end())`. + + @sa see @ref empty() -- checks whether the container is empty + @sa see @ref max_size() -- returns the maximal number of elements + + @since version 1.0.0 + */ + size_type size() const noexcept + { + switch (m_type) + { + case value_t::null: + { + // null values are empty + return 0; + } + + case value_t::array: + { + // delegate call to array_t::size() + return m_value.array->size(); + } + + case value_t::object: + { + // delegate call to object_t::size() + return m_value.object->size(); + } + + default: + { + // all other types have size 1 + return 1; + } + } + } + + /*! + @brief returns the maximum possible number of elements + + Returns the maximum number of elements a JSON value is able to hold due to + system or library implementation limitations, i.e. `std::distance(begin(), + end())` for the JSON value. + + @return The return value depends on the different types and is + defined as follows: + Value type | return value + ----------- | ------------- + null | `0` (same as `size()`) + boolean | `1` (same as `size()`) + string | `1` (same as `size()`) + number | `1` (same as `size()`) + binary | `1` (same as `size()`) + object | result of function `object_t::max_size()` + array | result of function `array_t::max_size()` + + @liveexample{The following code calls `max_size()` on the different value + types. Note the output is implementation specific.,max_size} + + @complexity Constant, as long as @ref array_t and @ref object_t satisfy + the Container concept; that is, their `max_size()` functions have constant + complexity. + + @iterators No changes. + + @exceptionsafety No-throw guarantee: this function never throws exceptions. + + @requirement This function helps `basic_json` satisfying the + [Container](https://en.cppreference.com/w/cpp/named_req/Container) + requirements: + - The complexity is constant. + - Has the semantics of returning `b.size()` where `b` is the largest + possible JSON value. + + @sa see @ref size() -- returns the number of elements + + @since version 1.0.0 + */ + size_type max_size() const noexcept + { + switch (m_type) + { + case value_t::array: + { + // delegate call to array_t::max_size() + return m_value.array->max_size(); + } + + case value_t::object: + { + // delegate call to object_t::max_size() + return m_value.object->max_size(); + } + + default: + { + // all other types have max_size() == size() + return size(); + } + } + } + + /// @} + + + /////////////// + // modifiers // + /////////////// + + /// @name modifiers + /// @{ + + /*! + @brief clears the contents + + Clears the content of a JSON value and resets it to the default value as + if @ref basic_json(value_t) would have been called with the current value + type from @ref type(): + + Value type | initial value + ----------- | ------------- + null | `null` + boolean | `false` + string | `""` + number | `0` + binary | An empty byte vector + object | `{}` + array | `[]` + + @post Has the same effect as calling + @code {.cpp} + *this = basic_json(type()); + @endcode + + @liveexample{The example below shows the effect of `clear()` to different + JSON types.,clear} + + @complexity Linear in the size of the JSON value. + + @iterators All iterators, pointers and references related to this container + are invalidated. + + @exceptionsafety No-throw guarantee: this function never throws exceptions. + + @sa see @ref basic_json(value_t) -- constructor that creates an object with the + same value than calling `clear()` + + @since version 1.0.0 + */ + void clear() noexcept + { + switch (m_type) + { + case value_t::number_integer: + { + m_value.number_integer = 0; + break; + } + + case value_t::number_unsigned: + { + m_value.number_unsigned = 0; + break; + } + + case value_t::number_float: + { + m_value.number_float = 0.0; + break; + } + + case value_t::boolean: + { + m_value.boolean = false; + break; + } + + case value_t::string: + { + m_value.string->clear(); + break; + } + + case value_t::binary: + { + m_value.binary->clear(); + break; + } + + case value_t::array: + { + m_value.array->clear(); + break; + } + + case value_t::object: + { + m_value.object->clear(); + break; + } + + default: + break; + } + } + + /*! + @brief add an object to an array + + Appends the given element @a val to the end of the JSON value. If the + function is called on a JSON null value, an empty array is created before + appending @a val. + + @param[in] val the value to add to the JSON array + + @throw type_error.308 when called on a type other than JSON array or + null; example: `"cannot use push_back() with number"` + + @complexity Amortized constant. + + @liveexample{The example shows how `push_back()` and `+=` can be used to + add elements to a JSON array. Note how the `null` value was silently + converted to a JSON array.,push_back} + + @since version 1.0.0 + */ + void push_back(basic_json&& val) + { + // push_back only works for null objects or arrays + if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array()))) + { + JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()), *this)); + } + + // transform null object into an array + if (is_null()) + { + m_type = value_t::array; + m_value = value_t::array; + assert_invariant(); + } + + // add element to array (move semantics) + m_value.array->push_back(std::move(val)); + set_parent(m_value.array->back()); + // if val is moved from, basic_json move constructor marks it null so we do not call the destructor + } + + /*! + @brief add an object to an array + @copydoc push_back(basic_json&&) + */ + reference operator+=(basic_json&& val) + { + push_back(std::move(val)); + return *this; + } + + /*! + @brief add an object to an array + @copydoc push_back(basic_json&&) + */ + void push_back(const basic_json& val) + { + // push_back only works for null objects or arrays + if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array()))) + { + JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()), *this)); + } + + // transform null object into an array + if (is_null()) + { + m_type = value_t::array; + m_value = value_t::array; + assert_invariant(); + } + + // add element to array + m_value.array->push_back(val); + set_parent(m_value.array->back()); + } + + /*! + @brief add an object to an array + @copydoc push_back(basic_json&&) + */ + reference operator+=(const basic_json& val) + { + push_back(val); + return *this; + } + + /*! + @brief add an object to an object + + Inserts the given element @a val to the JSON object. If the function is + called on a JSON null value, an empty object is created before inserting + @a val. + + @param[in] val the value to add to the JSON object + + @throw type_error.308 when called on a type other than JSON object or + null; example: `"cannot use push_back() with number"` + + @complexity Logarithmic in the size of the container, O(log(`size()`)). + + @liveexample{The example shows how `push_back()` and `+=` can be used to + add elements to a JSON object. Note how the `null` value was silently + converted to a JSON object.,push_back__object_t__value} + + @since version 1.0.0 + */ + void push_back(const typename object_t::value_type& val) + { + // push_back only works for null objects or objects + if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_object()))) + { + JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()), *this)); + } + + // transform null object into an object + if (is_null()) + { + m_type = value_t::object; + m_value = value_t::object; + assert_invariant(); + } + + // add element to object + auto res = m_value.object->insert(val); + set_parent(res.first->second); + } + + /*! + @brief add an object to an object + @copydoc push_back(const typename object_t::value_type&) + */ + reference operator+=(const typename object_t::value_type& val) + { + push_back(val); + return *this; + } + + /*! + @brief add an object to an object + + This function allows to use `push_back` with an initializer list. In case + + 1. the current value is an object, + 2. the initializer list @a init contains only two elements, and + 3. the first element of @a init is a string, + + @a init is converted into an object element and added using + @ref push_back(const typename object_t::value_type&). Otherwise, @a init + is converted to a JSON value and added using @ref push_back(basic_json&&). + + @param[in] init an initializer list + + @complexity Linear in the size of the initializer list @a init. + + @note This function is required to resolve an ambiguous overload error, + because pairs like `{"key", "value"}` can be both interpreted as + `object_t::value_type` or `std::initializer_list`, see + https://github.com/nlohmann/json/issues/235 for more information. + + @liveexample{The example shows how initializer lists are treated as + objects when possible.,push_back__initializer_list} + */ + void push_back(initializer_list_t init) + { + if (is_object() && init.size() == 2 && (*init.begin())->is_string()) + { + basic_json&& key = init.begin()->moved_or_copied(); + push_back(typename object_t::value_type( + std::move(key.get_ref()), (init.begin() + 1)->moved_or_copied())); + } + else + { + push_back(basic_json(init)); + } + } + + /*! + @brief add an object to an object + @copydoc push_back(initializer_list_t) + */ + reference operator+=(initializer_list_t init) + { + push_back(init); + return *this; + } + + /*! + @brief add an object to an array + + Creates a JSON value from the passed parameters @a args to the end of the + JSON value. If the function is called on a JSON null value, an empty array + is created before appending the value created from @a args. + + @param[in] args arguments to forward to a constructor of @ref basic_json + @tparam Args compatible types to create a @ref basic_json object + + @return reference to the inserted element + + @throw type_error.311 when called on a type other than JSON array or + null; example: `"cannot use emplace_back() with number"` + + @complexity Amortized constant. + + @liveexample{The example shows how `push_back()` can be used to add + elements to a JSON array. Note how the `null` value was silently converted + to a JSON array.,emplace_back} + + @since version 2.0.8, returns reference since 3.7.0 + */ + template + reference emplace_back(Args&& ... args) + { + // emplace_back only works for null objects or arrays + if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array()))) + { + JSON_THROW(type_error::create(311, "cannot use emplace_back() with " + std::string(type_name()), *this)); + } + + // transform null object into an array + if (is_null()) + { + m_type = value_t::array; + m_value = value_t::array; + assert_invariant(); + } + + // add element to array (perfect forwarding) +#ifdef JSON_HAS_CPP_17 + return set_parent(m_value.array->emplace_back(std::forward(args)...)); +#else + m_value.array->emplace_back(std::forward(args)...); + return set_parent(m_value.array->back()); +#endif + } + + /*! + @brief add an object to an object if key does not exist + + Inserts a new element into a JSON object constructed in-place with the + given @a args if there is no element with the key in the container. If the + function is called on a JSON null value, an empty object is created before + appending the value created from @a args. + + @param[in] args arguments to forward to a constructor of @ref basic_json + @tparam Args compatible types to create a @ref basic_json object + + @return a pair consisting of an iterator to the inserted element, or the + already-existing element if no insertion happened, and a bool + denoting whether the insertion took place. + + @throw type_error.311 when called on a type other than JSON object or + null; example: `"cannot use emplace() with number"` + + @complexity Logarithmic in the size of the container, O(log(`size()`)). + + @liveexample{The example shows how `emplace()` can be used to add elements + to a JSON object. Note how the `null` value was silently converted to a + JSON object. Further note how no value is added if there was already one + value stored with the same key.,emplace} + + @since version 2.0.8 + */ + template + std::pair emplace(Args&& ... args) + { + // emplace only works for null objects or arrays + if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_object()))) + { + JSON_THROW(type_error::create(311, "cannot use emplace() with " + std::string(type_name()), *this)); + } + + // transform null object into an object + if (is_null()) + { + m_type = value_t::object; + m_value = value_t::object; + assert_invariant(); + } + + // add element to array (perfect forwarding) + auto res = m_value.object->emplace(std::forward(args)...); + set_parent(res.first->second); + + // create result iterator and set iterator to the result of emplace + auto it = begin(); + it.m_it.object_iterator = res.first; + + // return pair of iterator and boolean + return {it, res.second}; + } + + /// Helper for insertion of an iterator + /// @note: This uses std::distance to support GCC 4.8, + /// see https://github.com/nlohmann/json/pull/1257 + template + iterator insert_iterator(const_iterator pos, Args&& ... args) + { + iterator result(this); + JSON_ASSERT(m_value.array != nullptr); + + auto insert_pos = std::distance(m_value.array->begin(), pos.m_it.array_iterator); + m_value.array->insert(pos.m_it.array_iterator, std::forward(args)...); + result.m_it.array_iterator = m_value.array->begin() + insert_pos; + + // This could have been written as: + // result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, cnt, val); + // but the return value of insert is missing in GCC 4.8, so it is written this way instead. + + return result; + } + + /*! + @brief inserts element + + Inserts element @a val before iterator @a pos. + + @param[in] pos iterator before which the content will be inserted; may be + the end() iterator + @param[in] val element to insert + @return iterator pointing to the inserted @a val. + + @throw type_error.309 if called on JSON values other than arrays; + example: `"cannot use insert() with string"` + @throw invalid_iterator.202 if @a pos is not an iterator of *this; + example: `"iterator does not fit current value"` + + @complexity Constant plus linear in the distance between @a pos and end of + the container. + + @liveexample{The example shows how `insert()` is used.,insert} + + @since version 1.0.0 + */ + iterator insert(const_iterator pos, const basic_json& val) + { + // insert only works for arrays + if (JSON_HEDLEY_LIKELY(is_array())) + { + // check if iterator pos fits to this JSON value + if (JSON_HEDLEY_UNLIKELY(pos.m_object != this)) + { + JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this)); + } + + // insert to array and return iterator + return set_parents(insert_iterator(pos, val), static_cast(1)); + } + + JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this)); + } + + /*! + @brief inserts element + @copydoc insert(const_iterator, const basic_json&) + */ + iterator insert(const_iterator pos, basic_json&& val) + { + return insert(pos, val); + } + + /*! + @brief inserts elements + + Inserts @a cnt copies of @a val before iterator @a pos. + + @param[in] pos iterator before which the content will be inserted; may be + the end() iterator + @param[in] cnt number of copies of @a val to insert + @param[in] val element to insert + @return iterator pointing to the first element inserted, or @a pos if + `cnt==0` + + @throw type_error.309 if called on JSON values other than arrays; example: + `"cannot use insert() with string"` + @throw invalid_iterator.202 if @a pos is not an iterator of *this; + example: `"iterator does not fit current value"` + + @complexity Linear in @a cnt plus linear in the distance between @a pos + and end of the container. + + @liveexample{The example shows how `insert()` is used.,insert__count} + + @since version 1.0.0 + */ + iterator insert(const_iterator pos, size_type cnt, const basic_json& val) + { + // insert only works for arrays + if (JSON_HEDLEY_LIKELY(is_array())) + { + // check if iterator pos fits to this JSON value + if (JSON_HEDLEY_UNLIKELY(pos.m_object != this)) + { + JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this)); + } + + // insert to array and return iterator + return set_parents(insert_iterator(pos, cnt, val), static_cast(cnt)); + } + + JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this)); + } + + /*! + @brief inserts elements + + Inserts elements from range `[first, last)` before iterator @a pos. + + @param[in] pos iterator before which the content will be inserted; may be + the end() iterator + @param[in] first begin of the range of elements to insert + @param[in] last end of the range of elements to insert + + @throw type_error.309 if called on JSON values other than arrays; example: + `"cannot use insert() with string"` + @throw invalid_iterator.202 if @a pos is not an iterator of *this; + example: `"iterator does not fit current value"` + @throw invalid_iterator.210 if @a first and @a last do not belong to the + same JSON value; example: `"iterators do not fit"` + @throw invalid_iterator.211 if @a first or @a last are iterators into + container for which insert is called; example: `"passed iterators may not + belong to container"` + + @return iterator pointing to the first element inserted, or @a pos if + `first==last` + + @complexity Linear in `std::distance(first, last)` plus linear in the + distance between @a pos and end of the container. + + @liveexample{The example shows how `insert()` is used.,insert__range} + + @since version 1.0.0 + */ + iterator insert(const_iterator pos, const_iterator first, const_iterator last) + { + // insert only works for arrays + if (JSON_HEDLEY_UNLIKELY(!is_array())) + { + JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this)); + } + + // check if iterator pos fits to this JSON value + if (JSON_HEDLEY_UNLIKELY(pos.m_object != this)) + { + JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this)); + } + + // check if range iterators belong to the same JSON object + if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object)) + { + JSON_THROW(invalid_iterator::create(210, "iterators do not fit", *this)); + } + + if (JSON_HEDLEY_UNLIKELY(first.m_object == this)) + { + JSON_THROW(invalid_iterator::create(211, "passed iterators may not belong to container", *this)); + } + + // insert to array and return iterator + return set_parents(insert_iterator(pos, first.m_it.array_iterator, last.m_it.array_iterator), std::distance(first, last)); + } + + /*! + @brief inserts elements + + Inserts elements from initializer list @a ilist before iterator @a pos. + + @param[in] pos iterator before which the content will be inserted; may be + the end() iterator + @param[in] ilist initializer list to insert the values from + + @throw type_error.309 if called on JSON values other than arrays; example: + `"cannot use insert() with string"` + @throw invalid_iterator.202 if @a pos is not an iterator of *this; + example: `"iterator does not fit current value"` + + @return iterator pointing to the first element inserted, or @a pos if + `ilist` is empty + + @complexity Linear in `ilist.size()` plus linear in the distance between + @a pos and end of the container. + + @liveexample{The example shows how `insert()` is used.,insert__ilist} + + @since version 1.0.0 + */ + iterator insert(const_iterator pos, initializer_list_t ilist) + { + // insert only works for arrays + if (JSON_HEDLEY_UNLIKELY(!is_array())) + { + JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this)); + } + + // check if iterator pos fits to this JSON value + if (JSON_HEDLEY_UNLIKELY(pos.m_object != this)) + { + JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this)); + } + + // insert to array and return iterator + return set_parents(insert_iterator(pos, ilist.begin(), ilist.end()), static_cast(ilist.size())); + } + + /*! + @brief inserts elements + + Inserts elements from range `[first, last)`. + + @param[in] first begin of the range of elements to insert + @param[in] last end of the range of elements to insert + + @throw type_error.309 if called on JSON values other than objects; example: + `"cannot use insert() with string"` + @throw invalid_iterator.202 if iterator @a first or @a last does does not + point to an object; example: `"iterators first and last must point to + objects"` + @throw invalid_iterator.210 if @a first and @a last do not belong to the + same JSON value; example: `"iterators do not fit"` + + @complexity Logarithmic: `O(N*log(size() + N))`, where `N` is the number + of elements to insert. + + @liveexample{The example shows how `insert()` is used.,insert__range_object} + + @since version 3.0.0 + */ + void insert(const_iterator first, const_iterator last) + { + // insert only works for objects + if (JSON_HEDLEY_UNLIKELY(!is_object())) + { + JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this)); + } + + // check if range iterators belong to the same JSON object + if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object)) + { + JSON_THROW(invalid_iterator::create(210, "iterators do not fit", *this)); + } + + // passed iterators must belong to objects + if (JSON_HEDLEY_UNLIKELY(!first.m_object->is_object())) + { + JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects", *this)); + } + + m_value.object->insert(first.m_it.object_iterator, last.m_it.object_iterator); + } + + /*! + @brief updates a JSON object from another object, overwriting existing keys + + Inserts all values from JSON object @a j and overwrites existing keys. + + @param[in] j JSON object to read values from + + @throw type_error.312 if called on JSON values other than objects; example: + `"cannot use update() with string"` + + @complexity O(N*log(size() + N)), where N is the number of elements to + insert. + + @liveexample{The example shows how `update()` is used.,update} + + @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update + + @since version 3.0.0 + */ + void update(const_reference j) + { + // implicitly convert null value to an empty object + if (is_null()) + { + m_type = value_t::object; + m_value.object = create(); + assert_invariant(); + } + + if (JSON_HEDLEY_UNLIKELY(!is_object())) + { + JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name()), *this)); + } + if (JSON_HEDLEY_UNLIKELY(!j.is_object())) + { + JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(j.type_name()), *this)); + } + + for (auto it = j.cbegin(); it != j.cend(); ++it) + { + m_value.object->operator[](it.key()) = it.value(); + } + } + + /*! + @brief updates a JSON object from another object, overwriting existing keys + + Inserts all values from from range `[first, last)` and overwrites existing + keys. + + @param[in] first begin of the range of elements to insert + @param[in] last end of the range of elements to insert + + @throw type_error.312 if called on JSON values other than objects; example: + `"cannot use update() with string"` + @throw invalid_iterator.202 if iterator @a first or @a last does does not + point to an object; example: `"iterators first and last must point to + objects"` + @throw invalid_iterator.210 if @a first and @a last do not belong to the + same JSON value; example: `"iterators do not fit"` + + @complexity O(N*log(size() + N)), where N is the number of elements to + insert. + + @liveexample{The example shows how `update()` is used__range.,update} + + @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update + + @since version 3.0.0 + */ + void update(const_iterator first, const_iterator last) + { + // implicitly convert null value to an empty object + if (is_null()) + { + m_type = value_t::object; + m_value.object = create(); + assert_invariant(); + } + + if (JSON_HEDLEY_UNLIKELY(!is_object())) + { + JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name()), *this)); + } + + // check if range iterators belong to the same JSON object + if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object)) + { + JSON_THROW(invalid_iterator::create(210, "iterators do not fit", *this)); + } + + // passed iterators must belong to objects + if (JSON_HEDLEY_UNLIKELY(!first.m_object->is_object() + || !last.m_object->is_object())) + { + JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects", *this)); + } + + for (auto it = first; it != last; ++it) + { + m_value.object->operator[](it.key()) = it.value(); + } + } + + /*! + @brief exchanges the values + + Exchanges the contents of the JSON value with those of @a other. Does not + invoke any move, copy, or swap operations on individual elements. All + iterators and references remain valid. The past-the-end iterator is + invalidated. + + @param[in,out] other JSON value to exchange the contents with + + @complexity Constant. + + @liveexample{The example below shows how JSON values can be swapped with + `swap()`.,swap__reference} + + @since version 1.0.0 + */ + void swap(reference other) noexcept ( + std::is_nothrow_move_constructible::value&& + std::is_nothrow_move_assignable::value&& + std::is_nothrow_move_constructible::value&& + std::is_nothrow_move_assignable::value + ) + { + std::swap(m_type, other.m_type); + std::swap(m_value, other.m_value); + + set_parents(); + other.set_parents(); + assert_invariant(); + } + + /*! + @brief exchanges the values + + Exchanges the contents of the JSON value from @a left with those of @a right. Does not + invoke any move, copy, or swap operations on individual elements. All + iterators and references remain valid. The past-the-end iterator is + invalidated. implemented as a friend function callable via ADL. + + @param[in,out] left JSON value to exchange the contents with + @param[in,out] right JSON value to exchange the contents with + + @complexity Constant. + + @liveexample{The example below shows how JSON values can be swapped with + `swap()`.,swap__reference} + + @since version 1.0.0 + */ + friend void swap(reference left, reference right) noexcept ( + std::is_nothrow_move_constructible::value&& + std::is_nothrow_move_assignable::value&& + std::is_nothrow_move_constructible::value&& + std::is_nothrow_move_assignable::value + ) + { + left.swap(right); + } + + /*! + @brief exchanges the values + + Exchanges the contents of a JSON array with those of @a other. Does not + invoke any move, copy, or swap operations on individual elements. All + iterators and references remain valid. The past-the-end iterator is + invalidated. + + @param[in,out] other array to exchange the contents with + + @throw type_error.310 when JSON value is not an array; example: `"cannot + use swap() with string"` + + @complexity Constant. + + @liveexample{The example below shows how arrays can be swapped with + `swap()`.,swap__array_t} + + @since version 1.0.0 + */ + void swap(array_t& other) // NOLINT(bugprone-exception-escape) + { + // swap only works for arrays + if (JSON_HEDLEY_LIKELY(is_array())) + { + std::swap(*(m_value.array), other); + } + else + { + JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this)); + } + } + + /*! + @brief exchanges the values + + Exchanges the contents of a JSON object with those of @a other. Does not + invoke any move, copy, or swap operations on individual elements. All + iterators and references remain valid. The past-the-end iterator is + invalidated. + + @param[in,out] other object to exchange the contents with + + @throw type_error.310 when JSON value is not an object; example: + `"cannot use swap() with string"` + + @complexity Constant. + + @liveexample{The example below shows how objects can be swapped with + `swap()`.,swap__object_t} + + @since version 1.0.0 + */ + void swap(object_t& other) // NOLINT(bugprone-exception-escape) + { + // swap only works for objects + if (JSON_HEDLEY_LIKELY(is_object())) + { + std::swap(*(m_value.object), other); + } + else + { + JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this)); + } + } + + /*! + @brief exchanges the values + + Exchanges the contents of a JSON string with those of @a other. Does not + invoke any move, copy, or swap operations on individual elements. All + iterators and references remain valid. The past-the-end iterator is + invalidated. + + @param[in,out] other string to exchange the contents with + + @throw type_error.310 when JSON value is not a string; example: `"cannot + use swap() with boolean"` + + @complexity Constant. + + @liveexample{The example below shows how strings can be swapped with + `swap()`.,swap__string_t} + + @since version 1.0.0 + */ + void swap(string_t& other) // NOLINT(bugprone-exception-escape) + { + // swap only works for strings + if (JSON_HEDLEY_LIKELY(is_string())) + { + std::swap(*(m_value.string), other); + } + else + { + JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this)); + } + } + + /*! + @brief exchanges the values + + Exchanges the contents of a JSON string with those of @a other. Does not + invoke any move, copy, or swap operations on individual elements. All + iterators and references remain valid. The past-the-end iterator is + invalidated. + + @param[in,out] other binary to exchange the contents with + + @throw type_error.310 when JSON value is not a string; example: `"cannot + use swap() with boolean"` + + @complexity Constant. + + @liveexample{The example below shows how strings can be swapped with + `swap()`.,swap__binary_t} + + @since version 3.8.0 + */ + void swap(binary_t& other) // NOLINT(bugprone-exception-escape) + { + // swap only works for strings + if (JSON_HEDLEY_LIKELY(is_binary())) + { + std::swap(*(m_value.binary), other); + } + else + { + JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this)); + } + } + + /// @copydoc swap(binary_t&) + void swap(typename binary_t::container_type& other) // NOLINT(bugprone-exception-escape) + { + // swap only works for strings + if (JSON_HEDLEY_LIKELY(is_binary())) + { + std::swap(*(m_value.binary), other); + } + else + { + JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this)); + } + } + + /// @} + + public: + ////////////////////////////////////////// + // lexicographical comparison operators // + ////////////////////////////////////////// + + /// @name lexicographical comparison operators + /// @{ + + /*! + @brief comparison: equal + + Compares two JSON values for equality according to the following rules: + - Two JSON values are equal if (1) they are from the same type and (2) + their stored values are the same according to their respective + `operator==`. + - Integer and floating-point numbers are automatically converted before + comparison. Note that two NaN values are always treated as unequal. + - Two JSON null values are equal. + + @note Floating-point inside JSON values numbers are compared with + `json::number_float_t::operator==` which is `double::operator==` by + default. To compare floating-point while respecting an epsilon, an alternative + [comparison function](https://github.com/mariokonrad/marnav/blob/master/include/marnav/math/floatingpoint.hpp#L34-#L39) + could be used, for instance + @code {.cpp} + template::value, T>::type> + inline bool is_same(T a, T b, T epsilon = std::numeric_limits::epsilon()) noexcept + { + return std::abs(a - b) <= epsilon; + } + @endcode + Or you can self-defined operator equal function like this: + @code {.cpp} + bool my_equal(const_reference lhs, const_reference rhs) { + const auto lhs_type lhs.type(); + const auto rhs_type rhs.type(); + if (lhs_type == rhs_type) { + switch(lhs_type) + // self_defined case + case value_t::number_float: + return std::abs(lhs - rhs) <= std::numeric_limits::epsilon(); + // other cases remain the same with the original + ... + } + ... + } + @endcode + + @note NaN values never compare equal to themselves or to other NaN values. + + @param[in] lhs first JSON value to consider + @param[in] rhs second JSON value to consider + @return whether the values @a lhs and @a rhs are equal + + @exceptionsafety No-throw guarantee: this function never throws exceptions. + + @complexity Linear. + + @liveexample{The example demonstrates comparing several JSON + types.,operator__equal} + + @since version 1.0.0 + */ + friend bool operator==(const_reference lhs, const_reference rhs) noexcept + { + const auto lhs_type = lhs.type(); + const auto rhs_type = rhs.type(); + + if (lhs_type == rhs_type) + { + switch (lhs_type) + { + case value_t::array: + return *lhs.m_value.array == *rhs.m_value.array; + + case value_t::object: + return *lhs.m_value.object == *rhs.m_value.object; + + case value_t::null: + return true; + + case value_t::string: + return *lhs.m_value.string == *rhs.m_value.string; + + case value_t::boolean: + return lhs.m_value.boolean == rhs.m_value.boolean; + + case value_t::number_integer: + return lhs.m_value.number_integer == rhs.m_value.number_integer; + + case value_t::number_unsigned: + return lhs.m_value.number_unsigned == rhs.m_value.number_unsigned; + + case value_t::number_float: + return lhs.m_value.number_float == rhs.m_value.number_float; + + case value_t::binary: + return *lhs.m_value.binary == *rhs.m_value.binary; + + default: + return false; + } + } + else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_float) + { + return static_cast(lhs.m_value.number_integer) == rhs.m_value.number_float; + } + else if (lhs_type == value_t::number_float && rhs_type == value_t::number_integer) + { + return lhs.m_value.number_float == static_cast(rhs.m_value.number_integer); + } + else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_float) + { + return static_cast(lhs.m_value.number_unsigned) == rhs.m_value.number_float; + } + else if (lhs_type == value_t::number_float && rhs_type == value_t::number_unsigned) + { + return lhs.m_value.number_float == static_cast(rhs.m_value.number_unsigned); + } + else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_integer) + { + return static_cast(lhs.m_value.number_unsigned) == rhs.m_value.number_integer; + } + else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_unsigned) + { + return lhs.m_value.number_integer == static_cast(rhs.m_value.number_unsigned); + } + + return false; + } + + /*! + @brief comparison: equal + @copydoc operator==(const_reference, const_reference) + */ + template::value, int>::type = 0> + friend bool operator==(const_reference lhs, ScalarType rhs) noexcept + { + return lhs == basic_json(rhs); + } + + /*! + @brief comparison: equal + @copydoc operator==(const_reference, const_reference) + */ + template::value, int>::type = 0> + friend bool operator==(ScalarType lhs, const_reference rhs) noexcept + { + return basic_json(lhs) == rhs; + } + + /*! + @brief comparison: not equal + + Compares two JSON values for inequality by calculating `not (lhs == rhs)`. + + @param[in] lhs first JSON value to consider + @param[in] rhs second JSON value to consider + @return whether the values @a lhs and @a rhs are not equal + + @complexity Linear. + + @exceptionsafety No-throw guarantee: this function never throws exceptions. + + @liveexample{The example demonstrates comparing several JSON + types.,operator__notequal} + + @since version 1.0.0 + */ + friend bool operator!=(const_reference lhs, const_reference rhs) noexcept + { + return !(lhs == rhs); + } + + /*! + @brief comparison: not equal + @copydoc operator!=(const_reference, const_reference) + */ + template::value, int>::type = 0> + friend bool operator!=(const_reference lhs, ScalarType rhs) noexcept + { + return lhs != basic_json(rhs); + } + + /*! + @brief comparison: not equal + @copydoc operator!=(const_reference, const_reference) + */ + template::value, int>::type = 0> + friend bool operator!=(ScalarType lhs, const_reference rhs) noexcept + { + return basic_json(lhs) != rhs; + } + + /*! + @brief comparison: less than + + Compares whether one JSON value @a lhs is less than another JSON value @a + rhs according to the following rules: + - If @a lhs and @a rhs have the same type, the values are compared using + the default `<` operator. + - Integer and floating-point numbers are automatically converted before + comparison + - In case @a lhs and @a rhs have different types, the values are ignored + and the order of the types is considered, see + @ref operator<(const value_t, const value_t). + + @param[in] lhs first JSON value to consider + @param[in] rhs second JSON value to consider + @return whether @a lhs is less than @a rhs + + @complexity Linear. + + @exceptionsafety No-throw guarantee: this function never throws exceptions. + + @liveexample{The example demonstrates comparing several JSON + types.,operator__less} + + @since version 1.0.0 + */ + friend bool operator<(const_reference lhs, const_reference rhs) noexcept + { + const auto lhs_type = lhs.type(); + const auto rhs_type = rhs.type(); + + if (lhs_type == rhs_type) + { + switch (lhs_type) + { + case value_t::array: + // note parentheses are necessary, see + // https://github.com/nlohmann/json/issues/1530 + return (*lhs.m_value.array) < (*rhs.m_value.array); + + case value_t::object: + return (*lhs.m_value.object) < (*rhs.m_value.object); + + case value_t::null: + return false; + + case value_t::string: + return (*lhs.m_value.string) < (*rhs.m_value.string); + + case value_t::boolean: + return (lhs.m_value.boolean) < (rhs.m_value.boolean); + + case value_t::number_integer: + return (lhs.m_value.number_integer) < (rhs.m_value.number_integer); + + case value_t::number_unsigned: + return (lhs.m_value.number_unsigned) < (rhs.m_value.number_unsigned); + + case value_t::number_float: + return (lhs.m_value.number_float) < (rhs.m_value.number_float); + + case value_t::binary: + return (*lhs.m_value.binary) < (*rhs.m_value.binary); + + default: + return false; + } + } + else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_float) + { + return static_cast(lhs.m_value.number_integer) < rhs.m_value.number_float; + } + else if (lhs_type == value_t::number_float && rhs_type == value_t::number_integer) + { + return lhs.m_value.number_float < static_cast(rhs.m_value.number_integer); + } + else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_float) + { + return static_cast(lhs.m_value.number_unsigned) < rhs.m_value.number_float; + } + else if (lhs_type == value_t::number_float && rhs_type == value_t::number_unsigned) + { + return lhs.m_value.number_float < static_cast(rhs.m_value.number_unsigned); + } + else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_unsigned) + { + return lhs.m_value.number_integer < static_cast(rhs.m_value.number_unsigned); + } + else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_integer) + { + return static_cast(lhs.m_value.number_unsigned) < rhs.m_value.number_integer; + } + + // We only reach this line if we cannot compare values. In that case, + // we compare types. Note we have to call the operator explicitly, + // because MSVC has problems otherwise. + return operator<(lhs_type, rhs_type); + } + + /*! + @brief comparison: less than + @copydoc operator<(const_reference, const_reference) + */ + template::value, int>::type = 0> + friend bool operator<(const_reference lhs, ScalarType rhs) noexcept + { + return lhs < basic_json(rhs); + } + + /*! + @brief comparison: less than + @copydoc operator<(const_reference, const_reference) + */ + template::value, int>::type = 0> + friend bool operator<(ScalarType lhs, const_reference rhs) noexcept + { + return basic_json(lhs) < rhs; + } + + /*! + @brief comparison: less than or equal + + Compares whether one JSON value @a lhs is less than or equal to another + JSON value by calculating `not (rhs < lhs)`. + + @param[in] lhs first JSON value to consider + @param[in] rhs second JSON value to consider + @return whether @a lhs is less than or equal to @a rhs + + @complexity Linear. + + @exceptionsafety No-throw guarantee: this function never throws exceptions. + + @liveexample{The example demonstrates comparing several JSON + types.,operator__greater} + + @since version 1.0.0 + */ + friend bool operator<=(const_reference lhs, const_reference rhs) noexcept + { + return !(rhs < lhs); + } + + /*! + @brief comparison: less than or equal + @copydoc operator<=(const_reference, const_reference) + */ + template::value, int>::type = 0> + friend bool operator<=(const_reference lhs, ScalarType rhs) noexcept + { + return lhs <= basic_json(rhs); + } + + /*! + @brief comparison: less than or equal + @copydoc operator<=(const_reference, const_reference) + */ + template::value, int>::type = 0> + friend bool operator<=(ScalarType lhs, const_reference rhs) noexcept + { + return basic_json(lhs) <= rhs; + } + + /*! + @brief comparison: greater than + + Compares whether one JSON value @a lhs is greater than another + JSON value by calculating `not (lhs <= rhs)`. + + @param[in] lhs first JSON value to consider + @param[in] rhs second JSON value to consider + @return whether @a lhs is greater than to @a rhs + + @complexity Linear. + + @exceptionsafety No-throw guarantee: this function never throws exceptions. + + @liveexample{The example demonstrates comparing several JSON + types.,operator__lessequal} + + @since version 1.0.0 + */ + friend bool operator>(const_reference lhs, const_reference rhs) noexcept + { + return !(lhs <= rhs); + } + + /*! + @brief comparison: greater than + @copydoc operator>(const_reference, const_reference) + */ + template::value, int>::type = 0> + friend bool operator>(const_reference lhs, ScalarType rhs) noexcept + { + return lhs > basic_json(rhs); + } + + /*! + @brief comparison: greater than + @copydoc operator>(const_reference, const_reference) + */ + template::value, int>::type = 0> + friend bool operator>(ScalarType lhs, const_reference rhs) noexcept + { + return basic_json(lhs) > rhs; + } + + /*! + @brief comparison: greater than or equal + + Compares whether one JSON value @a lhs is greater than or equal to another + JSON value by calculating `not (lhs < rhs)`. + + @param[in] lhs first JSON value to consider + @param[in] rhs second JSON value to consider + @return whether @a lhs is greater than or equal to @a rhs + + @complexity Linear. + + @exceptionsafety No-throw guarantee: this function never throws exceptions. + + @liveexample{The example demonstrates comparing several JSON + types.,operator__greaterequal} + + @since version 1.0.0 + */ + friend bool operator>=(const_reference lhs, const_reference rhs) noexcept + { + return !(lhs < rhs); + } + + /*! + @brief comparison: greater than or equal + @copydoc operator>=(const_reference, const_reference) + */ + template::value, int>::type = 0> + friend bool operator>=(const_reference lhs, ScalarType rhs) noexcept + { + return lhs >= basic_json(rhs); + } + + /*! + @brief comparison: greater than or equal + @copydoc operator>=(const_reference, const_reference) + */ + template::value, int>::type = 0> + friend bool operator>=(ScalarType lhs, const_reference rhs) noexcept + { + return basic_json(lhs) >= rhs; + } + + /// @} + + /////////////////// + // serialization // + /////////////////// + + /// @name serialization + /// @{ + + /*! + @brief serialize to stream + + Serialize the given JSON value @a j to the output stream @a o. The JSON + value will be serialized using the @ref dump member function. + + - The indentation of the output can be controlled with the member variable + `width` of the output stream @a o. For instance, using the manipulator + `std::setw(4)` on @a o sets the indentation level to `4` and the + serialization result is the same as calling `dump(4)`. + + - The indentation character can be controlled with the member variable + `fill` of the output stream @a o. For instance, the manipulator + `std::setfill('\\t')` sets indentation to use a tab character rather than + the default space character. + + @param[in,out] o stream to serialize to + @param[in] j JSON value to serialize + + @return the stream @a o + + @throw type_error.316 if a string stored inside the JSON value is not + UTF-8 encoded + + @complexity Linear. + + @liveexample{The example below shows the serialization with different + parameters to `width` to adjust the indentation level.,operator_serialize} + + @since version 1.0.0; indentation character added in version 3.0.0 + */ + friend std::ostream& operator<<(std::ostream& o, const basic_json& j) + { + // read width member and use it as indentation parameter if nonzero + const bool pretty_print = o.width() > 0; + const auto indentation = pretty_print ? o.width() : 0; + + // reset width to 0 for subsequent calls to this stream + o.width(0); + + // do the actual serialization + serializer s(detail::output_adapter(o), o.fill()); + s.dump(j, pretty_print, false, static_cast(indentation)); + return o; + } + + /*! + @brief serialize to stream + @deprecated This stream operator is deprecated and will be removed in + future 4.0.0 of the library. Please use + @ref operator<<(std::ostream&, const basic_json&) + instead; that is, replace calls like `j >> o;` with `o << j;`. + @since version 1.0.0; deprecated since version 3.0.0 + */ + JSON_HEDLEY_DEPRECATED_FOR(3.0.0, operator<<(std::ostream&, const basic_json&)) + friend std::ostream& operator>>(const basic_json& j, std::ostream& o) + { + return o << j; + } + + /// @} + + + ///////////////////// + // deserialization // + ///////////////////// + + /// @name deserialization + /// @{ + + /*! + @brief deserialize from a compatible input + + @tparam InputType A compatible input, for instance + - an std::istream object + - a FILE pointer + - a C-style array of characters + - a pointer to a null-terminated string of single byte characters + - an object obj for which begin(obj) and end(obj) produces a valid pair of + iterators. + + @param[in] i input to read from + @param[in] cb a parser callback function of type @ref parser_callback_t + which is used to control the deserialization by filtering unwanted values + (optional) + @param[in] allow_exceptions whether to throw exceptions in case of a + parse error (optional, true by default) + @param[in] ignore_comments whether comments should be ignored and treated + like whitespace (true) or yield a parse error (true); (optional, false by + default) + + @return deserialized JSON value; in case of a parse error and + @a allow_exceptions set to `false`, the return value will be + value_t::discarded. + + @throw parse_error.101 if a parse error occurs; example: `""unexpected end + of input; expected string literal""` + @throw parse_error.102 if to_unicode fails or surrogate error + @throw parse_error.103 if to_unicode fails + + @complexity Linear in the length of the input. The parser is a predictive + LL(1) parser. The complexity can be higher if the parser callback function + @a cb or reading from the input @a i has a super-linear complexity. + + @note A UTF-8 byte order mark is silently ignored. + + @liveexample{The example below demonstrates the `parse()` function reading + from an array.,parse__array__parser_callback_t} + + @liveexample{The example below demonstrates the `parse()` function with + and without callback function.,parse__string__parser_callback_t} + + @liveexample{The example below demonstrates the `parse()` function with + and without callback function.,parse__istream__parser_callback_t} + + @liveexample{The example below demonstrates the `parse()` function reading + from a contiguous container.,parse__contiguouscontainer__parser_callback_t} + + @since version 2.0.3 (contiguous containers); version 3.9.0 allowed to + ignore comments. + */ + template + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json parse(InputType&& i, + const parser_callback_t cb = nullptr, + const bool allow_exceptions = true, + const bool ignore_comments = false) + { + basic_json result; + parser(detail::input_adapter(std::forward(i)), cb, allow_exceptions, ignore_comments).parse(true, result); + return result; + } + + /*! + @brief deserialize from a pair of character iterators + + The value_type of the iterator must be a integral type with size of 1, 2 or + 4 bytes, which will be interpreted respectively as UTF-8, UTF-16 and UTF-32. + + @param[in] first iterator to start of character range + @param[in] last iterator to end of character range + @param[in] cb a parser callback function of type @ref parser_callback_t + which is used to control the deserialization by filtering unwanted values + (optional) + @param[in] allow_exceptions whether to throw exceptions in case of a + parse error (optional, true by default) + @param[in] ignore_comments whether comments should be ignored and treated + like whitespace (true) or yield a parse error (true); (optional, false by + default) + + @return deserialized JSON value; in case of a parse error and + @a allow_exceptions set to `false`, the return value will be + value_t::discarded. + + @throw parse_error.101 if a parse error occurs; example: `""unexpected end + of input; expected string literal""` + @throw parse_error.102 if to_unicode fails or surrogate error + @throw parse_error.103 if to_unicode fails + */ + template + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json parse(IteratorType first, + IteratorType last, + const parser_callback_t cb = nullptr, + const bool allow_exceptions = true, + const bool ignore_comments = false) + { + basic_json result; + parser(detail::input_adapter(std::move(first), std::move(last)), cb, allow_exceptions, ignore_comments).parse(true, result); + return result; + } + + JSON_HEDLEY_WARN_UNUSED_RESULT + JSON_HEDLEY_DEPRECATED_FOR(3.8.0, parse(ptr, ptr + len)) + static basic_json parse(detail::span_input_adapter&& i, + const parser_callback_t cb = nullptr, + const bool allow_exceptions = true, + const bool ignore_comments = false) + { + basic_json result; + parser(i.get(), cb, allow_exceptions, ignore_comments).parse(true, result); + return result; + } + + /*! + @brief check if the input is valid JSON + + Unlike the @ref parse(InputType&&, const parser_callback_t,const bool) + function, this function neither throws an exception in case of invalid JSON + input (i.e., a parse error) nor creates diagnostic information. + + @tparam InputType A compatible input, for instance + - an std::istream object + - a FILE pointer + - a C-style array of characters + - a pointer to a null-terminated string of single byte characters + - an object obj for which begin(obj) and end(obj) produces a valid pair of + iterators. + + @param[in] i input to read from + @param[in] ignore_comments whether comments should be ignored and treated + like whitespace (true) or yield a parse error (true); (optional, false by + default) + + @return Whether the input read from @a i is valid JSON. + + @complexity Linear in the length of the input. The parser is a predictive + LL(1) parser. + + @note A UTF-8 byte order mark is silently ignored. + + @liveexample{The example below demonstrates the `accept()` function reading + from a string.,accept__string} + */ + template + static bool accept(InputType&& i, + const bool ignore_comments = false) + { + return parser(detail::input_adapter(std::forward(i)), nullptr, false, ignore_comments).accept(true); + } + + template + static bool accept(IteratorType first, IteratorType last, + const bool ignore_comments = false) + { + return parser(detail::input_adapter(std::move(first), std::move(last)), nullptr, false, ignore_comments).accept(true); + } + + JSON_HEDLEY_WARN_UNUSED_RESULT + JSON_HEDLEY_DEPRECATED_FOR(3.8.0, accept(ptr, ptr + len)) + static bool accept(detail::span_input_adapter&& i, + const bool ignore_comments = false) + { + return parser(i.get(), nullptr, false, ignore_comments).accept(true); + } + + /*! + @brief generate SAX events + + The SAX event lister must follow the interface of @ref json_sax. + + This function reads from a compatible input. Examples are: + - an std::istream object + - a FILE pointer + - a C-style array of characters + - a pointer to a null-terminated string of single byte characters + - an object obj for which begin(obj) and end(obj) produces a valid pair of + iterators. + + @param[in] i input to read from + @param[in,out] sax SAX event listener + @param[in] format the format to parse (JSON, CBOR, MessagePack, or UBJSON) + @param[in] strict whether the input has to be consumed completely + @param[in] ignore_comments whether comments should be ignored and treated + like whitespace (true) or yield a parse error (true); (optional, false by + default); only applies to the JSON file format. + + @return return value of the last processed SAX event + + @throw parse_error.101 if a parse error occurs; example: `""unexpected end + of input; expected string literal""` + @throw parse_error.102 if to_unicode fails or surrogate error + @throw parse_error.103 if to_unicode fails + + @complexity Linear in the length of the input. The parser is a predictive + LL(1) parser. The complexity can be higher if the SAX consumer @a sax has + a super-linear complexity. + + @note A UTF-8 byte order mark is silently ignored. + + @liveexample{The example below demonstrates the `sax_parse()` function + reading from string and processing the events with a user-defined SAX + event consumer.,sax_parse} + + @since version 3.2.0 + */ + template + JSON_HEDLEY_NON_NULL(2) + static bool sax_parse(InputType&& i, SAX* sax, + input_format_t format = input_format_t::json, + const bool strict = true, + const bool ignore_comments = false) + { + auto ia = detail::input_adapter(std::forward(i)); + return format == input_format_t::json + ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict) + : detail::binary_reader(std::move(ia)).sax_parse(format, sax, strict); + } + + template + JSON_HEDLEY_NON_NULL(3) + static bool sax_parse(IteratorType first, IteratorType last, SAX* sax, + input_format_t format = input_format_t::json, + const bool strict = true, + const bool ignore_comments = false) + { + auto ia = detail::input_adapter(std::move(first), std::move(last)); + return format == input_format_t::json + ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict) + : detail::binary_reader(std::move(ia)).sax_parse(format, sax, strict); + } + + template + JSON_HEDLEY_DEPRECATED_FOR(3.8.0, sax_parse(ptr, ptr + len, ...)) + JSON_HEDLEY_NON_NULL(2) + static bool sax_parse(detail::span_input_adapter&& i, SAX* sax, + input_format_t format = input_format_t::json, + const bool strict = true, + const bool ignore_comments = false) + { + auto ia = i.get(); + return format == input_format_t::json + // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg) + ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict) + // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg) + : detail::binary_reader(std::move(ia)).sax_parse(format, sax, strict); + } + + /*! + @brief deserialize from stream + @deprecated This stream operator is deprecated and will be removed in + version 4.0.0 of the library. Please use + @ref operator>>(std::istream&, basic_json&) + instead; that is, replace calls like `j << i;` with `i >> j;`. + @since version 1.0.0; deprecated since version 3.0.0 + */ + JSON_HEDLEY_DEPRECATED_FOR(3.0.0, operator>>(std::istream&, basic_json&)) + friend std::istream& operator<<(basic_json& j, std::istream& i) + { + return operator>>(i, j); + } + + /*! + @brief deserialize from stream + + Deserializes an input stream to a JSON value. + + @param[in,out] i input stream to read a serialized JSON value from + @param[in,out] j JSON value to write the deserialized input to + + @throw parse_error.101 in case of an unexpected token + @throw parse_error.102 if to_unicode fails or surrogate error + @throw parse_error.103 if to_unicode fails + + @complexity Linear in the length of the input. The parser is a predictive + LL(1) parser. + + @note A UTF-8 byte order mark is silently ignored. + + @liveexample{The example below shows how a JSON value is constructed by + reading a serialization from a stream.,operator_deserialize} + + @sa parse(std::istream&, const parser_callback_t) for a variant with a + parser callback function to filter values while parsing + + @since version 1.0.0 + */ + friend std::istream& operator>>(std::istream& i, basic_json& j) + { + parser(detail::input_adapter(i)).parse(false, j); + return i; + } + + /// @} + + /////////////////////////// + // convenience functions // + /////////////////////////// + + /*! + @brief return the type as string + + Returns the type name as string to be used in error messages - usually to + indicate that a function was called on a wrong JSON type. + + @return a string representation of a the @a m_type member: + Value type | return value + ----------- | ------------- + null | `"null"` + boolean | `"boolean"` + string | `"string"` + number | `"number"` (for all number types) + object | `"object"` + array | `"array"` + binary | `"binary"` + discarded | `"discarded"` + + @exceptionsafety No-throw guarantee: this function never throws exceptions. + + @complexity Constant. + + @liveexample{The following code exemplifies `type_name()` for all JSON + types.,type_name} + + @sa see @ref type() -- return the type of the JSON value + @sa see @ref operator value_t() -- return the type of the JSON value (implicit) + + @since version 1.0.0, public since 2.1.0, `const char*` and `noexcept` + since 3.0.0 + */ + JSON_HEDLEY_RETURNS_NON_NULL + const char* type_name() const noexcept + { + { + switch (m_type) + { + case value_t::null: + return "null"; + case value_t::object: + return "object"; + case value_t::array: + return "array"; + case value_t::string: + return "string"; + case value_t::boolean: + return "boolean"; + case value_t::binary: + return "binary"; + case value_t::discarded: + return "discarded"; + default: + return "number"; + } + } + } + + + JSON_PRIVATE_UNLESS_TESTED: + ////////////////////// + // member variables // + ////////////////////// + + /// the type of the current element + value_t m_type = value_t::null; + + /// the value of the current element + json_value m_value = {}; + +#if JSON_DIAGNOSTICS + /// a pointer to a parent value (for debugging purposes) + basic_json* m_parent = nullptr; +#endif + + ////////////////////////////////////////// + // binary serialization/deserialization // + ////////////////////////////////////////// + + /// @name binary serialization/deserialization support + /// @{ + + public: + /*! + @brief create a CBOR serialization of a given JSON value + + Serializes a given JSON value @a j to a byte vector using the CBOR (Concise + Binary Object Representation) serialization format. CBOR is a binary + serialization format which aims to be more compact than JSON itself, yet + more efficient to parse. + + The library uses the following mapping from JSON values types to + CBOR types according to the CBOR specification (RFC 7049): + + JSON value type | value/range | CBOR type | first byte + --------------- | ------------------------------------------ | ---------------------------------- | --------------- + null | `null` | Null | 0xF6 + boolean | `true` | True | 0xF5 + boolean | `false` | False | 0xF4 + number_integer | -9223372036854775808..-2147483649 | Negative integer (8 bytes follow) | 0x3B + number_integer | -2147483648..-32769 | Negative integer (4 bytes follow) | 0x3A + number_integer | -32768..-129 | Negative integer (2 bytes follow) | 0x39 + number_integer | -128..-25 | Negative integer (1 byte follow) | 0x38 + number_integer | -24..-1 | Negative integer | 0x20..0x37 + number_integer | 0..23 | Integer | 0x00..0x17 + number_integer | 24..255 | Unsigned integer (1 byte follow) | 0x18 + number_integer | 256..65535 | Unsigned integer (2 bytes follow) | 0x19 + number_integer | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A + number_integer | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B + number_unsigned | 0..23 | Integer | 0x00..0x17 + number_unsigned | 24..255 | Unsigned integer (1 byte follow) | 0x18 + number_unsigned | 256..65535 | Unsigned integer (2 bytes follow) | 0x19 + number_unsigned | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A + number_unsigned | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B + number_float | *any value representable by a float* | Single-Precision Float | 0xFA + number_float | *any value NOT representable by a float* | Double-Precision Float | 0xFB + string | *length*: 0..23 | UTF-8 string | 0x60..0x77 + string | *length*: 23..255 | UTF-8 string (1 byte follow) | 0x78 + string | *length*: 256..65535 | UTF-8 string (2 bytes follow) | 0x79 + string | *length*: 65536..4294967295 | UTF-8 string (4 bytes follow) | 0x7A + string | *length*: 4294967296..18446744073709551615 | UTF-8 string (8 bytes follow) | 0x7B + array | *size*: 0..23 | array | 0x80..0x97 + array | *size*: 23..255 | array (1 byte follow) | 0x98 + array | *size*: 256..65535 | array (2 bytes follow) | 0x99 + array | *size*: 65536..4294967295 | array (4 bytes follow) | 0x9A + array | *size*: 4294967296..18446744073709551615 | array (8 bytes follow) | 0x9B + object | *size*: 0..23 | map | 0xA0..0xB7 + object | *size*: 23..255 | map (1 byte follow) | 0xB8 + object | *size*: 256..65535 | map (2 bytes follow) | 0xB9 + object | *size*: 65536..4294967295 | map (4 bytes follow) | 0xBA + object | *size*: 4294967296..18446744073709551615 | map (8 bytes follow) | 0xBB + binary | *size*: 0..23 | byte string | 0x40..0x57 + binary | *size*: 23..255 | byte string (1 byte follow) | 0x58 + binary | *size*: 256..65535 | byte string (2 bytes follow) | 0x59 + binary | *size*: 65536..4294967295 | byte string (4 bytes follow) | 0x5A + binary | *size*: 4294967296..18446744073709551615 | byte string (8 bytes follow) | 0x5B + + @note The mapping is **complete** in the sense that any JSON value type + can be converted to a CBOR value. + + @note If NaN or Infinity are stored inside a JSON number, they are + serialized properly. This behavior differs from the @ref dump() + function which serializes NaN or Infinity to `null`. + + @note The following CBOR types are not used in the conversion: + - UTF-8 strings terminated by "break" (0x7F) + - arrays terminated by "break" (0x9F) + - maps terminated by "break" (0xBF) + - byte strings terminated by "break" (0x5F) + - date/time (0xC0..0xC1) + - bignum (0xC2..0xC3) + - decimal fraction (0xC4) + - bigfloat (0xC5) + - expected conversions (0xD5..0xD7) + - simple values (0xE0..0xF3, 0xF8) + - undefined (0xF7) + - half-precision floats (0xF9) + - break (0xFF) + + @param[in] j JSON value to serialize + @return CBOR serialization as byte vector + + @complexity Linear in the size of the JSON value @a j. + + @liveexample{The example shows the serialization of a JSON value to a byte + vector in CBOR format.,to_cbor} + + @sa http://cbor.io + @sa see @ref from_cbor(InputType&&, const bool, const bool, const cbor_tag_handler_t) for the + analogous deserialization + @sa see @ref to_msgpack(const basic_json&) for the related MessagePack format + @sa see @ref to_ubjson(const basic_json&, const bool, const bool) for the + related UBJSON format + + @since version 2.0.9; compact representation of floating-point numbers + since version 3.8.0 + */ + static std::vector to_cbor(const basic_json& j) + { + std::vector result; + to_cbor(j, result); + return result; + } + + static void to_cbor(const basic_json& j, detail::output_adapter o) + { + binary_writer(o).write_cbor(j); + } + + static void to_cbor(const basic_json& j, detail::output_adapter o) + { + binary_writer(o).write_cbor(j); + } + + /*! + @brief create a MessagePack serialization of a given JSON value + + Serializes a given JSON value @a j to a byte vector using the MessagePack + serialization format. MessagePack is a binary serialization format which + aims to be more compact than JSON itself, yet more efficient to parse. + + The library uses the following mapping from JSON values types to + MessagePack types according to the MessagePack specification: + + JSON value type | value/range | MessagePack type | first byte + --------------- | --------------------------------- | ---------------- | ---------- + null | `null` | nil | 0xC0 + boolean | `true` | true | 0xC3 + boolean | `false` | false | 0xC2 + number_integer | -9223372036854775808..-2147483649 | int64 | 0xD3 + number_integer | -2147483648..-32769 | int32 | 0xD2 + number_integer | -32768..-129 | int16 | 0xD1 + number_integer | -128..-33 | int8 | 0xD0 + number_integer | -32..-1 | negative fixint | 0xE0..0xFF + number_integer | 0..127 | positive fixint | 0x00..0x7F + number_integer | 128..255 | uint 8 | 0xCC + number_integer | 256..65535 | uint 16 | 0xCD + number_integer | 65536..4294967295 | uint 32 | 0xCE + number_integer | 4294967296..18446744073709551615 | uint 64 | 0xCF + number_unsigned | 0..127 | positive fixint | 0x00..0x7F + number_unsigned | 128..255 | uint 8 | 0xCC + number_unsigned | 256..65535 | uint 16 | 0xCD + number_unsigned | 65536..4294967295 | uint 32 | 0xCE + number_unsigned | 4294967296..18446744073709551615 | uint 64 | 0xCF + number_float | *any value representable by a float* | float 32 | 0xCA + number_float | *any value NOT representable by a float* | float 64 | 0xCB + string | *length*: 0..31 | fixstr | 0xA0..0xBF + string | *length*: 32..255 | str 8 | 0xD9 + string | *length*: 256..65535 | str 16 | 0xDA + string | *length*: 65536..4294967295 | str 32 | 0xDB + array | *size*: 0..15 | fixarray | 0x90..0x9F + array | *size*: 16..65535 | array 16 | 0xDC + array | *size*: 65536..4294967295 | array 32 | 0xDD + object | *size*: 0..15 | fix map | 0x80..0x8F + object | *size*: 16..65535 | map 16 | 0xDE + object | *size*: 65536..4294967295 | map 32 | 0xDF + binary | *size*: 0..255 | bin 8 | 0xC4 + binary | *size*: 256..65535 | bin 16 | 0xC5 + binary | *size*: 65536..4294967295 | bin 32 | 0xC6 + + @note The mapping is **complete** in the sense that any JSON value type + can be converted to a MessagePack value. + + @note The following values can **not** be converted to a MessagePack value: + - strings with more than 4294967295 bytes + - byte strings with more than 4294967295 bytes + - arrays with more than 4294967295 elements + - objects with more than 4294967295 elements + + @note Any MessagePack output created @ref to_msgpack can be successfully + parsed by @ref from_msgpack. + + @note If NaN or Infinity are stored inside a JSON number, they are + serialized properly. This behavior differs from the @ref dump() + function which serializes NaN or Infinity to `null`. + + @param[in] j JSON value to serialize + @return MessagePack serialization as byte vector + + @complexity Linear in the size of the JSON value @a j. + + @liveexample{The example shows the serialization of a JSON value to a byte + vector in MessagePack format.,to_msgpack} + + @sa http://msgpack.org + @sa see @ref from_msgpack for the analogous deserialization + @sa see @ref to_cbor(const basic_json& for the related CBOR format + @sa see @ref to_ubjson(const basic_json&, const bool, const bool) for the + related UBJSON format + + @since version 2.0.9 + */ + static std::vector to_msgpack(const basic_json& j) + { + std::vector result; + to_msgpack(j, result); + return result; + } + + static void to_msgpack(const basic_json& j, detail::output_adapter o) + { + binary_writer(o).write_msgpack(j); + } + + static void to_msgpack(const basic_json& j, detail::output_adapter o) + { + binary_writer(o).write_msgpack(j); + } + + /*! + @brief create a UBJSON serialization of a given JSON value + + Serializes a given JSON value @a j to a byte vector using the UBJSON + (Universal Binary JSON) serialization format. UBJSON aims to be more compact + than JSON itself, yet more efficient to parse. + + The library uses the following mapping from JSON values types to + UBJSON types according to the UBJSON specification: + + JSON value type | value/range | UBJSON type | marker + --------------- | --------------------------------- | ----------- | ------ + null | `null` | null | `Z` + boolean | `true` | true | `T` + boolean | `false` | false | `F` + number_integer | -9223372036854775808..-2147483649 | int64 | `L` + number_integer | -2147483648..-32769 | int32 | `l` + number_integer | -32768..-129 | int16 | `I` + number_integer | -128..127 | int8 | `i` + number_integer | 128..255 | uint8 | `U` + number_integer | 256..32767 | int16 | `I` + number_integer | 32768..2147483647 | int32 | `l` + number_integer | 2147483648..9223372036854775807 | int64 | `L` + number_unsigned | 0..127 | int8 | `i` + number_unsigned | 128..255 | uint8 | `U` + number_unsigned | 256..32767 | int16 | `I` + number_unsigned | 32768..2147483647 | int32 | `l` + number_unsigned | 2147483648..9223372036854775807 | int64 | `L` + number_unsigned | 2147483649..18446744073709551615 | high-precision | `H` + number_float | *any value* | float64 | `D` + string | *with shortest length indicator* | string | `S` + array | *see notes on optimized format* | array | `[` + object | *see notes on optimized format* | map | `{` + + @note The mapping is **complete** in the sense that any JSON value type + can be converted to a UBJSON value. + + @note The following values can **not** be converted to a UBJSON value: + - strings with more than 9223372036854775807 bytes (theoretical) + + @note The following markers are not used in the conversion: + - `Z`: no-op values are not created. + - `C`: single-byte strings are serialized with `S` markers. + + @note Any UBJSON output created @ref to_ubjson can be successfully parsed + by @ref from_ubjson. + + @note If NaN or Infinity are stored inside a JSON number, they are + serialized properly. This behavior differs from the @ref dump() + function which serializes NaN or Infinity to `null`. + + @note The optimized formats for containers are supported: Parameter + @a use_size adds size information to the beginning of a container and + removes the closing marker. Parameter @a use_type further checks + whether all elements of a container have the same type and adds the + type marker to the beginning of the container. The @a use_type + parameter must only be used together with @a use_size = true. Note + that @a use_size = true alone may result in larger representations - + the benefit of this parameter is that the receiving side is + immediately informed on the number of elements of the container. + + @note If the JSON data contains the binary type, the value stored is a list + of integers, as suggested by the UBJSON documentation. In particular, + this means that serialization and the deserialization of a JSON + containing binary values into UBJSON and back will result in a + different JSON object. + + @param[in] j JSON value to serialize + @param[in] use_size whether to add size annotations to container types + @param[in] use_type whether to add type annotations to container types + (must be combined with @a use_size = true) + @return UBJSON serialization as byte vector + + @complexity Linear in the size of the JSON value @a j. + + @liveexample{The example shows the serialization of a JSON value to a byte + vector in UBJSON format.,to_ubjson} + + @sa http://ubjson.org + @sa see @ref from_ubjson(InputType&&, const bool, const bool) for the + analogous deserialization + @sa see @ref to_cbor(const basic_json& for the related CBOR format + @sa see @ref to_msgpack(const basic_json&) for the related MessagePack format + + @since version 3.1.0 + */ + static std::vector to_ubjson(const basic_json& j, + const bool use_size = false, + const bool use_type = false) + { + std::vector result; + to_ubjson(j, result, use_size, use_type); + return result; + } + + static void to_ubjson(const basic_json& j, detail::output_adapter o, + const bool use_size = false, const bool use_type = false) + { + binary_writer(o).write_ubjson(j, use_size, use_type); + } + + static void to_ubjson(const basic_json& j, detail::output_adapter o, + const bool use_size = false, const bool use_type = false) + { + binary_writer(o).write_ubjson(j, use_size, use_type); + } + + + /*! + @brief Serializes the given JSON object `j` to BSON and returns a vector + containing the corresponding BSON-representation. + + BSON (Binary JSON) is a binary format in which zero or more ordered key/value pairs are + stored as a single entity (a so-called document). + + The library uses the following mapping from JSON values types to BSON types: + + JSON value type | value/range | BSON type | marker + --------------- | --------------------------------- | ----------- | ------ + null | `null` | null | 0x0A + boolean | `true`, `false` | boolean | 0x08 + number_integer | -9223372036854775808..-2147483649 | int64 | 0x12 + number_integer | -2147483648..2147483647 | int32 | 0x10 + number_integer | 2147483648..9223372036854775807 | int64 | 0x12 + number_unsigned | 0..2147483647 | int32 | 0x10 + number_unsigned | 2147483648..9223372036854775807 | int64 | 0x12 + number_unsigned | 9223372036854775808..18446744073709551615| -- | -- + number_float | *any value* | double | 0x01 + string | *any value* | string | 0x02 + array | *any value* | document | 0x04 + object | *any value* | document | 0x03 + binary | *any value* | binary | 0x05 + + @warning The mapping is **incomplete**, since only JSON-objects (and things + contained therein) can be serialized to BSON. + Also, integers larger than 9223372036854775807 cannot be serialized to BSON, + and the keys may not contain U+0000, since they are serialized a + zero-terminated c-strings. + + @throw out_of_range.407 if `j.is_number_unsigned() && j.get() > 9223372036854775807` + @throw out_of_range.409 if a key in `j` contains a NULL (U+0000) + @throw type_error.317 if `!j.is_object()` + + @pre The input `j` is required to be an object: `j.is_object() == true`. + + @note Any BSON output created via @ref to_bson can be successfully parsed + by @ref from_bson. + + @param[in] j JSON value to serialize + @return BSON serialization as byte vector + + @complexity Linear in the size of the JSON value @a j. + + @liveexample{The example shows the serialization of a JSON value to a byte + vector in BSON format.,to_bson} + + @sa http://bsonspec.org/spec.html + @sa see @ref from_bson(detail::input_adapter&&, const bool strict) for the + analogous deserialization + @sa see @ref to_ubjson(const basic_json&, const bool, const bool) for the + related UBJSON format + @sa see @ref to_cbor(const basic_json&) for the related CBOR format + @sa see @ref to_msgpack(const basic_json&) for the related MessagePack format + */ + static std::vector to_bson(const basic_json& j) + { + std::vector result; + to_bson(j, result); + return result; + } + + /*! + @brief Serializes the given JSON object `j` to BSON and forwards the + corresponding BSON-representation to the given output_adapter `o`. + @param j The JSON object to convert to BSON. + @param o The output adapter that receives the binary BSON representation. + @pre The input `j` shall be an object: `j.is_object() == true` + @sa see @ref to_bson(const basic_json&) + */ + static void to_bson(const basic_json& j, detail::output_adapter o) + { + binary_writer(o).write_bson(j); + } + + /*! + @copydoc to_bson(const basic_json&, detail::output_adapter) + */ + static void to_bson(const basic_json& j, detail::output_adapter o) + { + binary_writer(o).write_bson(j); + } + + + /*! + @brief create a JSON value from an input in CBOR format + + Deserializes a given input @a i to a JSON value using the CBOR (Concise + Binary Object Representation) serialization format. + + The library maps CBOR types to JSON value types as follows: + + CBOR type | JSON value type | first byte + ---------------------- | --------------- | ---------- + Integer | number_unsigned | 0x00..0x17 + Unsigned integer | number_unsigned | 0x18 + Unsigned integer | number_unsigned | 0x19 + Unsigned integer | number_unsigned | 0x1A + Unsigned integer | number_unsigned | 0x1B + Negative integer | number_integer | 0x20..0x37 + Negative integer | number_integer | 0x38 + Negative integer | number_integer | 0x39 + Negative integer | number_integer | 0x3A + Negative integer | number_integer | 0x3B + Byte string | binary | 0x40..0x57 + Byte string | binary | 0x58 + Byte string | binary | 0x59 + Byte string | binary | 0x5A + Byte string | binary | 0x5B + UTF-8 string | string | 0x60..0x77 + UTF-8 string | string | 0x78 + UTF-8 string | string | 0x79 + UTF-8 string | string | 0x7A + UTF-8 string | string | 0x7B + UTF-8 string | string | 0x7F + array | array | 0x80..0x97 + array | array | 0x98 + array | array | 0x99 + array | array | 0x9A + array | array | 0x9B + array | array | 0x9F + map | object | 0xA0..0xB7 + map | object | 0xB8 + map | object | 0xB9 + map | object | 0xBA + map | object | 0xBB + map | object | 0xBF + False | `false` | 0xF4 + True | `true` | 0xF5 + Null | `null` | 0xF6 + Half-Precision Float | number_float | 0xF9 + Single-Precision Float | number_float | 0xFA + Double-Precision Float | number_float | 0xFB + + @warning The mapping is **incomplete** in the sense that not all CBOR + types can be converted to a JSON value. The following CBOR types + are not supported and will yield parse errors (parse_error.112): + - date/time (0xC0..0xC1) + - bignum (0xC2..0xC3) + - decimal fraction (0xC4) + - bigfloat (0xC5) + - expected conversions (0xD5..0xD7) + - simple values (0xE0..0xF3, 0xF8) + - undefined (0xF7) + + @warning CBOR allows map keys of any type, whereas JSON only allows + strings as keys in object values. Therefore, CBOR maps with keys + other than UTF-8 strings are rejected (parse_error.113). + + @note Any CBOR output created @ref to_cbor can be successfully parsed by + @ref from_cbor. + + @param[in] i an input in CBOR format convertible to an input adapter + @param[in] strict whether to expect the input to be consumed until EOF + (true by default) + @param[in] allow_exceptions whether to throw exceptions in case of a + parse error (optional, true by default) + @param[in] tag_handler how to treat CBOR tags (optional, error by default) + + @return deserialized JSON value; in case of a parse error and + @a allow_exceptions set to `false`, the return value will be + value_t::discarded. + + @throw parse_error.110 if the given input ends prematurely or the end of + file was not reached when @a strict was set to true + @throw parse_error.112 if unsupported features from CBOR were + used in the given input @a v or if the input is not valid CBOR + @throw parse_error.113 if a string was expected as map key, but not found + + @complexity Linear in the size of the input @a i. + + @liveexample{The example shows the deserialization of a byte vector in CBOR + format to a JSON value.,from_cbor} + + @sa http://cbor.io + @sa see @ref to_cbor(const basic_json&) for the analogous serialization + @sa see @ref from_msgpack(InputType&&, const bool, const bool) for the + related MessagePack format + @sa see @ref from_ubjson(InputType&&, const bool, const bool) for the + related UBJSON format + + @since version 2.0.9; parameter @a start_index since 2.1.1; changed to + consume input adapters, removed start_index parameter, and added + @a strict parameter since 3.0.0; added @a allow_exceptions parameter + since 3.2.0; added @a tag_handler parameter since 3.9.0. + */ + template + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json from_cbor(InputType&& i, + const bool strict = true, + const bool allow_exceptions = true, + const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) + { + basic_json result; + detail::json_sax_dom_parser sdp(result, allow_exceptions); + auto ia = detail::input_adapter(std::forward(i)); + const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler); + return res ? result : basic_json(value_t::discarded); + } + + /*! + @copydoc from_cbor(InputType&&, const bool, const bool, const cbor_tag_handler_t) + */ + template + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json from_cbor(IteratorType first, IteratorType last, + const bool strict = true, + const bool allow_exceptions = true, + const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) + { + basic_json result; + detail::json_sax_dom_parser sdp(result, allow_exceptions); + auto ia = detail::input_adapter(std::move(first), std::move(last)); + const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler); + return res ? result : basic_json(value_t::discarded); + } + + template + JSON_HEDLEY_WARN_UNUSED_RESULT + JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_cbor(ptr, ptr + len)) + static basic_json from_cbor(const T* ptr, std::size_t len, + const bool strict = true, + const bool allow_exceptions = true, + const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) + { + return from_cbor(ptr, ptr + len, strict, allow_exceptions, tag_handler); + } + + + JSON_HEDLEY_WARN_UNUSED_RESULT + JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_cbor(ptr, ptr + len)) + static basic_json from_cbor(detail::span_input_adapter&& i, + const bool strict = true, + const bool allow_exceptions = true, + const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) + { + basic_json result; + detail::json_sax_dom_parser sdp(result, allow_exceptions); + auto ia = i.get(); + // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg) + const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler); + return res ? result : basic_json(value_t::discarded); + } + + /*! + @brief create a JSON value from an input in MessagePack format + + Deserializes a given input @a i to a JSON value using the MessagePack + serialization format. + + The library maps MessagePack types to JSON value types as follows: + + MessagePack type | JSON value type | first byte + ---------------- | --------------- | ---------- + positive fixint | number_unsigned | 0x00..0x7F + fixmap | object | 0x80..0x8F + fixarray | array | 0x90..0x9F + fixstr | string | 0xA0..0xBF + nil | `null` | 0xC0 + false | `false` | 0xC2 + true | `true` | 0xC3 + float 32 | number_float | 0xCA + float 64 | number_float | 0xCB + uint 8 | number_unsigned | 0xCC + uint 16 | number_unsigned | 0xCD + uint 32 | number_unsigned | 0xCE + uint 64 | number_unsigned | 0xCF + int 8 | number_integer | 0xD0 + int 16 | number_integer | 0xD1 + int 32 | number_integer | 0xD2 + int 64 | number_integer | 0xD3 + str 8 | string | 0xD9 + str 16 | string | 0xDA + str 32 | string | 0xDB + array 16 | array | 0xDC + array 32 | array | 0xDD + map 16 | object | 0xDE + map 32 | object | 0xDF + bin 8 | binary | 0xC4 + bin 16 | binary | 0xC5 + bin 32 | binary | 0xC6 + ext 8 | binary | 0xC7 + ext 16 | binary | 0xC8 + ext 32 | binary | 0xC9 + fixext 1 | binary | 0xD4 + fixext 2 | binary | 0xD5 + fixext 4 | binary | 0xD6 + fixext 8 | binary | 0xD7 + fixext 16 | binary | 0xD8 + negative fixint | number_integer | 0xE0-0xFF + + @note Any MessagePack output created @ref to_msgpack can be successfully + parsed by @ref from_msgpack. + + @param[in] i an input in MessagePack format convertible to an input + adapter + @param[in] strict whether to expect the input to be consumed until EOF + (true by default) + @param[in] allow_exceptions whether to throw exceptions in case of a + parse error (optional, true by default) + + @return deserialized JSON value; in case of a parse error and + @a allow_exceptions set to `false`, the return value will be + value_t::discarded. + + @throw parse_error.110 if the given input ends prematurely or the end of + file was not reached when @a strict was set to true + @throw parse_error.112 if unsupported features from MessagePack were + used in the given input @a i or if the input is not valid MessagePack + @throw parse_error.113 if a string was expected as map key, but not found + + @complexity Linear in the size of the input @a i. + + @liveexample{The example shows the deserialization of a byte vector in + MessagePack format to a JSON value.,from_msgpack} + + @sa http://msgpack.org + @sa see @ref to_msgpack(const basic_json&) for the analogous serialization + @sa see @ref from_cbor(InputType&&, const bool, const bool, const cbor_tag_handler_t) for the + related CBOR format + @sa see @ref from_ubjson(InputType&&, const bool, const bool) for + the related UBJSON format + @sa see @ref from_bson(InputType&&, const bool, const bool) for + the related BSON format + + @since version 2.0.9; parameter @a start_index since 2.1.1; changed to + consume input adapters, removed start_index parameter, and added + @a strict parameter since 3.0.0; added @a allow_exceptions parameter + since 3.2.0 + */ + template + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json from_msgpack(InputType&& i, + const bool strict = true, + const bool allow_exceptions = true) + { + basic_json result; + detail::json_sax_dom_parser sdp(result, allow_exceptions); + auto ia = detail::input_adapter(std::forward(i)); + const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::msgpack, &sdp, strict); + return res ? result : basic_json(value_t::discarded); + } + + /*! + @copydoc from_msgpack(InputType&&, const bool, const bool) + */ + template + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json from_msgpack(IteratorType first, IteratorType last, + const bool strict = true, + const bool allow_exceptions = true) + { + basic_json result; + detail::json_sax_dom_parser sdp(result, allow_exceptions); + auto ia = detail::input_adapter(std::move(first), std::move(last)); + const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::msgpack, &sdp, strict); + return res ? result : basic_json(value_t::discarded); + } + + + template + JSON_HEDLEY_WARN_UNUSED_RESULT + JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_msgpack(ptr, ptr + len)) + static basic_json from_msgpack(const T* ptr, std::size_t len, + const bool strict = true, + const bool allow_exceptions = true) + { + return from_msgpack(ptr, ptr + len, strict, allow_exceptions); + } + + JSON_HEDLEY_WARN_UNUSED_RESULT + JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_msgpack(ptr, ptr + len)) + static basic_json from_msgpack(detail::span_input_adapter&& i, + const bool strict = true, + const bool allow_exceptions = true) + { + basic_json result; + detail::json_sax_dom_parser sdp(result, allow_exceptions); + auto ia = i.get(); + // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg) + const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::msgpack, &sdp, strict); + return res ? result : basic_json(value_t::discarded); + } + + + /*! + @brief create a JSON value from an input in UBJSON format + + Deserializes a given input @a i to a JSON value using the UBJSON (Universal + Binary JSON) serialization format. + + The library maps UBJSON types to JSON value types as follows: + + UBJSON type | JSON value type | marker + ----------- | --------------------------------------- | ------ + no-op | *no value, next value is read* | `N` + null | `null` | `Z` + false | `false` | `F` + true | `true` | `T` + float32 | number_float | `d` + float64 | number_float | `D` + uint8 | number_unsigned | `U` + int8 | number_integer | `i` + int16 | number_integer | `I` + int32 | number_integer | `l` + int64 | number_integer | `L` + high-precision number | number_integer, number_unsigned, or number_float - depends on number string | 'H' + string | string | `S` + char | string | `C` + array | array (optimized values are supported) | `[` + object | object (optimized values are supported) | `{` + + @note The mapping is **complete** in the sense that any UBJSON value can + be converted to a JSON value. + + @param[in] i an input in UBJSON format convertible to an input adapter + @param[in] strict whether to expect the input to be consumed until EOF + (true by default) + @param[in] allow_exceptions whether to throw exceptions in case of a + parse error (optional, true by default) + + @return deserialized JSON value; in case of a parse error and + @a allow_exceptions set to `false`, the return value will be + value_t::discarded. + + @throw parse_error.110 if the given input ends prematurely or the end of + file was not reached when @a strict was set to true + @throw parse_error.112 if a parse error occurs + @throw parse_error.113 if a string could not be parsed successfully + + @complexity Linear in the size of the input @a i. + + @liveexample{The example shows the deserialization of a byte vector in + UBJSON format to a JSON value.,from_ubjson} + + @sa http://ubjson.org + @sa see @ref to_ubjson(const basic_json&, const bool, const bool) for the + analogous serialization + @sa see @ref from_cbor(InputType&&, const bool, const bool, const cbor_tag_handler_t) for the + related CBOR format + @sa see @ref from_msgpack(InputType&&, const bool, const bool) for + the related MessagePack format + @sa see @ref from_bson(InputType&&, const bool, const bool) for + the related BSON format + + @since version 3.1.0; added @a allow_exceptions parameter since 3.2.0 + */ + template + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json from_ubjson(InputType&& i, + const bool strict = true, + const bool allow_exceptions = true) + { + basic_json result; + detail::json_sax_dom_parser sdp(result, allow_exceptions); + auto ia = detail::input_adapter(std::forward(i)); + const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::ubjson, &sdp, strict); + return res ? result : basic_json(value_t::discarded); + } + + /*! + @copydoc from_ubjson(InputType&&, const bool, const bool) + */ + template + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json from_ubjson(IteratorType first, IteratorType last, + const bool strict = true, + const bool allow_exceptions = true) + { + basic_json result; + detail::json_sax_dom_parser sdp(result, allow_exceptions); + auto ia = detail::input_adapter(std::move(first), std::move(last)); + const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::ubjson, &sdp, strict); + return res ? result : basic_json(value_t::discarded); + } + + template + JSON_HEDLEY_WARN_UNUSED_RESULT + JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_ubjson(ptr, ptr + len)) + static basic_json from_ubjson(const T* ptr, std::size_t len, + const bool strict = true, + const bool allow_exceptions = true) + { + return from_ubjson(ptr, ptr + len, strict, allow_exceptions); + } + + JSON_HEDLEY_WARN_UNUSED_RESULT + JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_ubjson(ptr, ptr + len)) + static basic_json from_ubjson(detail::span_input_adapter&& i, + const bool strict = true, + const bool allow_exceptions = true) + { + basic_json result; + detail::json_sax_dom_parser sdp(result, allow_exceptions); + auto ia = i.get(); + // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg) + const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::ubjson, &sdp, strict); + return res ? result : basic_json(value_t::discarded); + } + + + /*! + @brief Create a JSON value from an input in BSON format + + Deserializes a given input @a i to a JSON value using the BSON (Binary JSON) + serialization format. + + The library maps BSON record types to JSON value types as follows: + + BSON type | BSON marker byte | JSON value type + --------------- | ---------------- | --------------------------- + double | 0x01 | number_float + string | 0x02 | string + document | 0x03 | object + array | 0x04 | array + binary | 0x05 | binary + undefined | 0x06 | still unsupported + ObjectId | 0x07 | still unsupported + boolean | 0x08 | boolean + UTC Date-Time | 0x09 | still unsupported + null | 0x0A | null + Regular Expr. | 0x0B | still unsupported + DB Pointer | 0x0C | still unsupported + JavaScript Code | 0x0D | still unsupported + Symbol | 0x0E | still unsupported + JavaScript Code | 0x0F | still unsupported + int32 | 0x10 | number_integer + Timestamp | 0x11 | still unsupported + 128-bit decimal float | 0x13 | still unsupported + Max Key | 0x7F | still unsupported + Min Key | 0xFF | still unsupported + + @warning The mapping is **incomplete**. The unsupported mappings + are indicated in the table above. + + @param[in] i an input in BSON format convertible to an input adapter + @param[in] strict whether to expect the input to be consumed until EOF + (true by default) + @param[in] allow_exceptions whether to throw exceptions in case of a + parse error (optional, true by default) + + @return deserialized JSON value; in case of a parse error and + @a allow_exceptions set to `false`, the return value will be + value_t::discarded. + + @throw parse_error.114 if an unsupported BSON record type is encountered + + @complexity Linear in the size of the input @a i. + + @liveexample{The example shows the deserialization of a byte vector in + BSON format to a JSON value.,from_bson} + + @sa http://bsonspec.org/spec.html + @sa see @ref to_bson(const basic_json&) for the analogous serialization + @sa see @ref from_cbor(InputType&&, const bool, const bool, const cbor_tag_handler_t) for the + related CBOR format + @sa see @ref from_msgpack(InputType&&, const bool, const bool) for + the related MessagePack format + @sa see @ref from_ubjson(InputType&&, const bool, const bool) for the + related UBJSON format + */ + template + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json from_bson(InputType&& i, + const bool strict = true, + const bool allow_exceptions = true) + { + basic_json result; + detail::json_sax_dom_parser sdp(result, allow_exceptions); + auto ia = detail::input_adapter(std::forward(i)); + const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::bson, &sdp, strict); + return res ? result : basic_json(value_t::discarded); + } + + /*! + @copydoc from_bson(InputType&&, const bool, const bool) + */ + template + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json from_bson(IteratorType first, IteratorType last, + const bool strict = true, + const bool allow_exceptions = true) + { + basic_json result; + detail::json_sax_dom_parser sdp(result, allow_exceptions); + auto ia = detail::input_adapter(std::move(first), std::move(last)); + const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::bson, &sdp, strict); + return res ? result : basic_json(value_t::discarded); + } + + template + JSON_HEDLEY_WARN_UNUSED_RESULT + JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_bson(ptr, ptr + len)) + static basic_json from_bson(const T* ptr, std::size_t len, + const bool strict = true, + const bool allow_exceptions = true) + { + return from_bson(ptr, ptr + len, strict, allow_exceptions); + } + + JSON_HEDLEY_WARN_UNUSED_RESULT + JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_bson(ptr, ptr + len)) + static basic_json from_bson(detail::span_input_adapter&& i, + const bool strict = true, + const bool allow_exceptions = true) + { + basic_json result; + detail::json_sax_dom_parser sdp(result, allow_exceptions); + auto ia = i.get(); + // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg) + const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::bson, &sdp, strict); + return res ? result : basic_json(value_t::discarded); + } + /// @} + + ////////////////////////// + // JSON Pointer support // + ////////////////////////// + + /// @name JSON Pointer functions + /// @{ + + /*! + @brief access specified element via JSON Pointer + + Uses a JSON pointer to retrieve a reference to the respective JSON value. + No bound checking is performed. Similar to @ref operator[](const typename + object_t::key_type&), `null` values are created in arrays and objects if + necessary. + + In particular: + - If the JSON pointer points to an object key that does not exist, it + is created an filled with a `null` value before a reference to it + is returned. + - If the JSON pointer points to an array index that does not exist, it + is created an filled with a `null` value before a reference to it + is returned. All indices between the current maximum and the given + index are also filled with `null`. + - The special value `-` is treated as a synonym for the index past the + end. + + @param[in] ptr a JSON pointer + + @return reference to the element pointed to by @a ptr + + @complexity Constant. + + @throw parse_error.106 if an array index begins with '0' + @throw parse_error.109 if an array index was not a number + @throw out_of_range.404 if the JSON pointer can not be resolved + + @liveexample{The behavior is shown in the example.,operatorjson_pointer} + + @since version 2.0.0 + */ + reference operator[](const json_pointer& ptr) + { + return ptr.get_unchecked(this); + } + + /*! + @brief access specified element via JSON Pointer + + Uses a JSON pointer to retrieve a reference to the respective JSON value. + No bound checking is performed. The function does not change the JSON + value; no `null` values are created. In particular, the special value + `-` yields an exception. + + @param[in] ptr JSON pointer to the desired element + + @return const reference to the element pointed to by @a ptr + + @complexity Constant. + + @throw parse_error.106 if an array index begins with '0' + @throw parse_error.109 if an array index was not a number + @throw out_of_range.402 if the array index '-' is used + @throw out_of_range.404 if the JSON pointer can not be resolved + + @liveexample{The behavior is shown in the example.,operatorjson_pointer_const} + + @since version 2.0.0 + */ + const_reference operator[](const json_pointer& ptr) const + { + return ptr.get_unchecked(this); + } + + /*! + @brief access specified element via JSON Pointer + + Returns a reference to the element at with specified JSON pointer @a ptr, + with bounds checking. + + @param[in] ptr JSON pointer to the desired element + + @return reference to the element pointed to by @a ptr + + @throw parse_error.106 if an array index in the passed JSON pointer @a ptr + begins with '0'. See example below. + + @throw parse_error.109 if an array index in the passed JSON pointer @a ptr + is not a number. See example below. + + @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr + is out of range. See example below. + + @throw out_of_range.402 if the array index '-' is used in the passed JSON + pointer @a ptr. As `at` provides checked access (and no elements are + implicitly inserted), the index '-' is always invalid. See example below. + + @throw out_of_range.403 if the JSON pointer describes a key of an object + which cannot be found. See example below. + + @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved. + See example below. + + @exceptionsafety Strong guarantee: if an exception is thrown, there are no + changes in the JSON value. + + @complexity Constant. + + @since version 2.0.0 + + @liveexample{The behavior is shown in the example.,at_json_pointer} + */ + reference at(const json_pointer& ptr) + { + return ptr.get_checked(this); + } + + /*! + @brief access specified element via JSON Pointer + + Returns a const reference to the element at with specified JSON pointer @a + ptr, with bounds checking. + + @param[in] ptr JSON pointer to the desired element + + @return reference to the element pointed to by @a ptr + + @throw parse_error.106 if an array index in the passed JSON pointer @a ptr + begins with '0'. See example below. + + @throw parse_error.109 if an array index in the passed JSON pointer @a ptr + is not a number. See example below. + + @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr + is out of range. See example below. + + @throw out_of_range.402 if the array index '-' is used in the passed JSON + pointer @a ptr. As `at` provides checked access (and no elements are + implicitly inserted), the index '-' is always invalid. See example below. + + @throw out_of_range.403 if the JSON pointer describes a key of an object + which cannot be found. See example below. + + @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved. + See example below. + + @exceptionsafety Strong guarantee: if an exception is thrown, there are no + changes in the JSON value. + + @complexity Constant. + + @since version 2.0.0 + + @liveexample{The behavior is shown in the example.,at_json_pointer_const} + */ + const_reference at(const json_pointer& ptr) const + { + return ptr.get_checked(this); + } + + /*! + @brief return flattened JSON value + + The function creates a JSON object whose keys are JSON pointers (see [RFC + 6901](https://tools.ietf.org/html/rfc6901)) and whose values are all + primitive. The original JSON value can be restored using the @ref + unflatten() function. + + @return an object that maps JSON pointers to primitive values + + @note Empty objects and arrays are flattened to `null` and will not be + reconstructed correctly by the @ref unflatten() function. + + @complexity Linear in the size the JSON value. + + @liveexample{The following code shows how a JSON object is flattened to an + object whose keys consist of JSON pointers.,flatten} + + @sa see @ref unflatten() for the reverse function + + @since version 2.0.0 + */ + basic_json flatten() const + { + basic_json result(value_t::object); + json_pointer::flatten("", *this, result); + return result; + } + + /*! + @brief unflatten a previously flattened JSON value + + The function restores the arbitrary nesting of a JSON value that has been + flattened before using the @ref flatten() function. The JSON value must + meet certain constraints: + 1. The value must be an object. + 2. The keys must be JSON pointers (see + [RFC 6901](https://tools.ietf.org/html/rfc6901)) + 3. The mapped values must be primitive JSON types. + + @return the original JSON from a flattened version + + @note Empty objects and arrays are flattened by @ref flatten() to `null` + values and can not unflattened to their original type. Apart from + this example, for a JSON value `j`, the following is always true: + `j == j.flatten().unflatten()`. + + @complexity Linear in the size the JSON value. + + @throw type_error.314 if value is not an object + @throw type_error.315 if object values are not primitive + + @liveexample{The following code shows how a flattened JSON object is + unflattened into the original nested JSON object.,unflatten} + + @sa see @ref flatten() for the reverse function + + @since version 2.0.0 + */ + basic_json unflatten() const + { + return json_pointer::unflatten(*this); + } + + /// @} + + ////////////////////////// + // JSON Patch functions // + ////////////////////////// + + /// @name JSON Patch functions + /// @{ + + /*! + @brief applies a JSON patch + + [JSON Patch](http://jsonpatch.com) defines a JSON document structure for + expressing a sequence of operations to apply to a JSON) document. With + this function, a JSON Patch is applied to the current JSON value by + executing all operations from the patch. + + @param[in] json_patch JSON patch document + @return patched document + + @note The application of a patch is atomic: Either all operations succeed + and the patched document is returned or an exception is thrown. In + any case, the original value is not changed: the patch is applied + to a copy of the value. + + @throw parse_error.104 if the JSON patch does not consist of an array of + objects + + @throw parse_error.105 if the JSON patch is malformed (e.g., mandatory + attributes are missing); example: `"operation add must have member path"` + + @throw out_of_range.401 if an array index is out of range. + + @throw out_of_range.403 if a JSON pointer inside the patch could not be + resolved successfully in the current JSON value; example: `"key baz not + found"` + + @throw out_of_range.405 if JSON pointer has no parent ("add", "remove", + "move") + + @throw other_error.501 if "test" operation was unsuccessful + + @complexity Linear in the size of the JSON value and the length of the + JSON patch. As usually only a fraction of the JSON value is affected by + the patch, the complexity can usually be neglected. + + @liveexample{The following code shows how a JSON patch is applied to a + value.,patch} + + @sa see @ref diff -- create a JSON patch by comparing two JSON values + + @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902) + @sa [RFC 6901 (JSON Pointer)](https://tools.ietf.org/html/rfc6901) + + @since version 2.0.0 + */ + basic_json patch(const basic_json& json_patch) const + { + // make a working copy to apply the patch to + basic_json result = *this; + + // the valid JSON Patch operations + enum class patch_operations {add, remove, replace, move, copy, test, invalid}; + + const auto get_op = [](const std::string & op) + { + if (op == "add") + { + return patch_operations::add; + } + if (op == "remove") + { + return patch_operations::remove; + } + if (op == "replace") + { + return patch_operations::replace; + } + if (op == "move") + { + return patch_operations::move; + } + if (op == "copy") + { + return patch_operations::copy; + } + if (op == "test") + { + return patch_operations::test; + } + + return patch_operations::invalid; + }; + + // wrapper for "add" operation; add value at ptr + const auto operation_add = [&result](json_pointer & ptr, basic_json val) + { + // adding to the root of the target document means replacing it + if (ptr.empty()) + { + result = val; + return; + } + + // make sure the top element of the pointer exists + json_pointer top_pointer = ptr.top(); + if (top_pointer != ptr) + { + result.at(top_pointer); + } + + // get reference to parent of JSON pointer ptr + const auto last_path = ptr.back(); + ptr.pop_back(); + basic_json& parent = result[ptr]; + + switch (parent.m_type) + { + case value_t::null: + case value_t::object: + { + // use operator[] to add value + parent[last_path] = val; + break; + } + + case value_t::array: + { + if (last_path == "-") + { + // special case: append to back + parent.push_back(val); + } + else + { + const auto idx = json_pointer::array_index(last_path); + if (JSON_HEDLEY_UNLIKELY(idx > parent.size())) + { + // avoid undefined behavior + JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range", parent)); + } + + // default case: insert add offset + parent.insert(parent.begin() + static_cast(idx), val); + } + break; + } + + // if there exists a parent it cannot be primitive + default: // LCOV_EXCL_LINE + JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE + } + }; + + // wrapper for "remove" operation; remove value at ptr + const auto operation_remove = [this, &result](json_pointer & ptr) + { + // get reference to parent of JSON pointer ptr + const auto last_path = ptr.back(); + ptr.pop_back(); + basic_json& parent = result.at(ptr); + + // remove child + if (parent.is_object()) + { + // perform range check + auto it = parent.find(last_path); + if (JSON_HEDLEY_LIKELY(it != parent.end())) + { + parent.erase(it); + } + else + { + JSON_THROW(out_of_range::create(403, "key '" + last_path + "' not found", *this)); + } + } + else if (parent.is_array()) + { + // note erase performs range check + parent.erase(json_pointer::array_index(last_path)); + } + }; + + // type check: top level value must be an array + if (JSON_HEDLEY_UNLIKELY(!json_patch.is_array())) + { + JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects", json_patch)); + } + + // iterate and apply the operations + for (const auto& val : json_patch) + { + // wrapper to get a value for an operation + const auto get_value = [&val](const std::string & op, + const std::string & member, + bool string_type) -> basic_json & + { + // find value + auto it = val.m_value.object->find(member); + + // context-sensitive error message + const auto error_msg = (op == "op") ? "operation" : "operation '" + op + "'"; + + // check if desired value is present + if (JSON_HEDLEY_UNLIKELY(it == val.m_value.object->end())) + { + // NOLINTNEXTLINE(performance-inefficient-string-concatenation) + JSON_THROW(parse_error::create(105, 0, error_msg + " must have member '" + member + "'", val)); + } + + // check if result is of type string + if (JSON_HEDLEY_UNLIKELY(string_type && !it->second.is_string())) + { + // NOLINTNEXTLINE(performance-inefficient-string-concatenation) + JSON_THROW(parse_error::create(105, 0, error_msg + " must have string member '" + member + "'", val)); + } + + // no error: return value + return it->second; + }; + + // type check: every element of the array must be an object + if (JSON_HEDLEY_UNLIKELY(!val.is_object())) + { + JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects", val)); + } + + // collect mandatory members + const auto op = get_value("op", "op", true).template get(); + const auto path = get_value(op, "path", true).template get(); + json_pointer ptr(path); + + switch (get_op(op)) + { + case patch_operations::add: + { + operation_add(ptr, get_value("add", "value", false)); + break; + } + + case patch_operations::remove: + { + operation_remove(ptr); + break; + } + + case patch_operations::replace: + { + // the "path" location must exist - use at() + result.at(ptr) = get_value("replace", "value", false); + break; + } + + case patch_operations::move: + { + const auto from_path = get_value("move", "from", true).template get(); + json_pointer from_ptr(from_path); + + // the "from" location must exist - use at() + basic_json v = result.at(from_ptr); + + // The move operation is functionally identical to a + // "remove" operation on the "from" location, followed + // immediately by an "add" operation at the target + // location with the value that was just removed. + operation_remove(from_ptr); + operation_add(ptr, v); + break; + } + + case patch_operations::copy: + { + const auto from_path = get_value("copy", "from", true).template get(); + const json_pointer from_ptr(from_path); + + // the "from" location must exist - use at() + basic_json v = result.at(from_ptr); + + // The copy is functionally identical to an "add" + // operation at the target location using the value + // specified in the "from" member. + operation_add(ptr, v); + break; + } + + case patch_operations::test: + { + bool success = false; + JSON_TRY + { + // check if "value" matches the one at "path" + // the "path" location must exist - use at() + success = (result.at(ptr) == get_value("test", "value", false)); + } + JSON_INTERNAL_CATCH (out_of_range&) + { + // ignore out of range errors: success remains false + } + + // throw an exception if test fails + if (JSON_HEDLEY_UNLIKELY(!success)) + { + JSON_THROW(other_error::create(501, "unsuccessful: " + val.dump(), val)); + } + + break; + } + + default: + { + // op must be "add", "remove", "replace", "move", "copy", or + // "test" + JSON_THROW(parse_error::create(105, 0, "operation value '" + op + "' is invalid", val)); + } + } + } + + return result; + } + + /*! + @brief creates a diff as a JSON patch + + Creates a [JSON Patch](http://jsonpatch.com) so that value @a source can + be changed into the value @a target by calling @ref patch function. + + @invariant For two JSON values @a source and @a target, the following code + yields always `true`: + @code {.cpp} + source.patch(diff(source, target)) == target; + @endcode + + @note Currently, only `remove`, `add`, and `replace` operations are + generated. + + @param[in] source JSON value to compare from + @param[in] target JSON value to compare against + @param[in] path helper value to create JSON pointers + + @return a JSON patch to convert the @a source to @a target + + @complexity Linear in the lengths of @a source and @a target. + + @liveexample{The following code shows how a JSON patch is created as a + diff for two JSON values.,diff} + + @sa see @ref patch -- apply a JSON patch + @sa see @ref merge_patch -- apply a JSON Merge Patch + + @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902) + + @since version 2.0.0 + */ + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json diff(const basic_json& source, const basic_json& target, + const std::string& path = "") + { + // the patch + basic_json result(value_t::array); + + // if the values are the same, return empty patch + if (source == target) + { + return result; + } + + if (source.type() != target.type()) + { + // different types: replace value + result.push_back( + { + {"op", "replace"}, {"path", path}, {"value", target} + }); + return result; + } + + switch (source.type()) + { + case value_t::array: + { + // first pass: traverse common elements + std::size_t i = 0; + while (i < source.size() && i < target.size()) + { + // recursive call to compare array values at index i + auto temp_diff = diff(source[i], target[i], path + "/" + std::to_string(i)); + result.insert(result.end(), temp_diff.begin(), temp_diff.end()); + ++i; + } + + // i now reached the end of at least one array + // in a second pass, traverse the remaining elements + + // remove my remaining elements + const auto end_index = static_cast(result.size()); + while (i < source.size()) + { + // add operations in reverse order to avoid invalid + // indices + result.insert(result.begin() + end_index, object( + { + {"op", "remove"}, + {"path", path + "/" + std::to_string(i)} + })); + ++i; + } + + // add other remaining elements + while (i < target.size()) + { + result.push_back( + { + {"op", "add"}, + {"path", path + "/-"}, + {"value", target[i]} + }); + ++i; + } + + break; + } + + case value_t::object: + { + // first pass: traverse this object's elements + for (auto it = source.cbegin(); it != source.cend(); ++it) + { + // escape the key name to be used in a JSON patch + const auto path_key = path + "/" + detail::escape(it.key()); + + if (target.find(it.key()) != target.end()) + { + // recursive call to compare object values at key it + auto temp_diff = diff(it.value(), target[it.key()], path_key); + result.insert(result.end(), temp_diff.begin(), temp_diff.end()); + } + else + { + // found a key that is not in o -> remove it + result.push_back(object( + { + {"op", "remove"}, {"path", path_key} + })); + } + } + + // second pass: traverse other object's elements + for (auto it = target.cbegin(); it != target.cend(); ++it) + { + if (source.find(it.key()) == source.end()) + { + // found a key that is not in this -> add it + const auto path_key = path + "/" + detail::escape(it.key()); + result.push_back( + { + {"op", "add"}, {"path", path_key}, + {"value", it.value()} + }); + } + } + + break; + } + + default: + { + // both primitive type: replace value + result.push_back( + { + {"op", "replace"}, {"path", path}, {"value", target} + }); + break; + } + } + + return result; + } + + /// @} + + //////////////////////////////// + // JSON Merge Patch functions // + //////////////////////////////// + + /// @name JSON Merge Patch functions + /// @{ + + /*! + @brief applies a JSON Merge Patch + + The merge patch format is primarily intended for use with the HTTP PATCH + method as a means of describing a set of modifications to a target + resource's content. This function applies a merge patch to the current + JSON value. + + The function implements the following algorithm from Section 2 of + [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396): + + ``` + define MergePatch(Target, Patch): + if Patch is an Object: + if Target is not an Object: + Target = {} // Ignore the contents and set it to an empty Object + for each Name/Value pair in Patch: + if Value is null: + if Name exists in Target: + remove the Name/Value pair from Target + else: + Target[Name] = MergePatch(Target[Name], Value) + return Target + else: + return Patch + ``` + + Thereby, `Target` is the current object; that is, the patch is applied to + the current value. + + @param[in] apply_patch the patch to apply + + @complexity Linear in the lengths of @a patch. + + @liveexample{The following code shows how a JSON Merge Patch is applied to + a JSON document.,merge_patch} + + @sa see @ref patch -- apply a JSON patch + @sa [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396) + + @since version 3.0.0 + */ + void merge_patch(const basic_json& apply_patch) + { + if (apply_patch.is_object()) + { + if (!is_object()) + { + *this = object(); + } + for (auto it = apply_patch.begin(); it != apply_patch.end(); ++it) + { + if (it.value().is_null()) + { + erase(it.key()); + } + else + { + operator[](it.key()).merge_patch(it.value()); + } + } + } + else + { + *this = apply_patch; + } + } + + /// @} +}; + +/*! +@brief user-defined to_string function for JSON values + +This function implements a user-defined to_string for JSON objects. + +@param[in] j a JSON object +@return a std::string object +*/ + +NLOHMANN_BASIC_JSON_TPL_DECLARATION +std::string to_string(const NLOHMANN_BASIC_JSON_TPL& j) +{ + return j.dump(); +} +} // namespace nlohmann + +/////////////////////// +// nonmember support // +/////////////////////// + +// specialization of std::swap, and std::hash +namespace std +{ + +/// hash value for JSON objects +template<> +struct hash +{ + /*! + @brief return a hash value for a JSON object + + @since version 1.0.0 + */ + std::size_t operator()(const nlohmann::json& j) const + { + return nlohmann::detail::hash(j); + } +}; + +/// specialization for std::less +/// @note: do not remove the space after '<', +/// see https://github.com/nlohmann/json/pull/679 +template<> +struct less<::nlohmann::detail::value_t> +{ + /*! + @brief compare two value_t enum values + @since version 3.0.0 + */ + bool operator()(nlohmann::detail::value_t lhs, + nlohmann::detail::value_t rhs) const noexcept + { + return nlohmann::detail::operator<(lhs, rhs); + } +}; + +// C++20 prohibit function specialization in the std namespace. +#ifndef JSON_HAS_CPP_20 + +/*! +@brief exchanges the values of two JSON objects + +@since version 1.0.0 +*/ +template<> +inline void swap(nlohmann::json& j1, nlohmann::json& j2) noexcept( // NOLINT(readability-inconsistent-declaration-parameter-name) + is_nothrow_move_constructible::value&& // NOLINT(misc-redundant-expression) + is_nothrow_move_assignable::value + ) +{ + j1.swap(j2); +} + +#endif + +} // namespace std + +/*! +@brief user-defined string literal for JSON values + +This operator implements a user-defined string literal for JSON objects. It +can be used by adding `"_json"` to a string literal and returns a JSON object +if no parse error occurred. + +@param[in] s a string representation of a JSON object +@param[in] n the length of string @a s +@return a JSON object + +@since version 1.0.0 +*/ +JSON_HEDLEY_NON_NULL(1) +inline nlohmann::json operator "" _json(const char* s, std::size_t n) +{ + return nlohmann::json::parse(s, s + n); +} + +/*! +@brief user-defined string literal for JSON pointer + +This operator implements a user-defined string literal for JSON Pointers. It +can be used by adding `"_json_pointer"` to a string literal and returns a JSON pointer +object if no parse error occurred. + +@param[in] s a string representation of a JSON Pointer +@param[in] n the length of string @a s +@return a JSON pointer object + +@since version 2.0.0 +*/ +JSON_HEDLEY_NON_NULL(1) +inline nlohmann::json::json_pointer operator "" _json_pointer(const char* s, std::size_t n) +{ + return nlohmann::json::json_pointer(std::string(s, n)); +} + +// #include + + +// restore GCC/clang diagnostic settings +#if defined(__clang__) + #pragma GCC diagnostic pop +#endif + +// clean up +#undef JSON_ASSERT +#undef JSON_INTERNAL_CATCH +#undef JSON_CATCH +#undef JSON_THROW +#undef JSON_TRY +#undef JSON_PRIVATE_UNLESS_TESTED +#undef JSON_HAS_CPP_11 +#undef JSON_HAS_CPP_14 +#undef JSON_HAS_CPP_17 +#undef JSON_HAS_CPP_20 +#undef NLOHMANN_BASIC_JSON_TPL_DECLARATION +#undef NLOHMANN_BASIC_JSON_TPL +#undef JSON_EXPLICIT + +// #include + + +#undef JSON_HEDLEY_ALWAYS_INLINE +#undef JSON_HEDLEY_ARM_VERSION +#undef JSON_HEDLEY_ARM_VERSION_CHECK +#undef JSON_HEDLEY_ARRAY_PARAM +#undef JSON_HEDLEY_ASSUME +#undef JSON_HEDLEY_BEGIN_C_DECLS +#undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE +#undef JSON_HEDLEY_CLANG_HAS_BUILTIN +#undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE +#undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE +#undef JSON_HEDLEY_CLANG_HAS_EXTENSION +#undef JSON_HEDLEY_CLANG_HAS_FEATURE +#undef JSON_HEDLEY_CLANG_HAS_WARNING +#undef JSON_HEDLEY_COMPCERT_VERSION +#undef JSON_HEDLEY_COMPCERT_VERSION_CHECK +#undef JSON_HEDLEY_CONCAT +#undef JSON_HEDLEY_CONCAT3 +#undef JSON_HEDLEY_CONCAT3_EX +#undef JSON_HEDLEY_CONCAT_EX +#undef JSON_HEDLEY_CONST +#undef JSON_HEDLEY_CONSTEXPR +#undef JSON_HEDLEY_CONST_CAST +#undef JSON_HEDLEY_CPP_CAST +#undef JSON_HEDLEY_CRAY_VERSION +#undef JSON_HEDLEY_CRAY_VERSION_CHECK +#undef JSON_HEDLEY_C_DECL +#undef JSON_HEDLEY_DEPRECATED +#undef JSON_HEDLEY_DEPRECATED_FOR +#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL +#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ +#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED +#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES +#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS +#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION +#undef JSON_HEDLEY_DIAGNOSTIC_POP +#undef JSON_HEDLEY_DIAGNOSTIC_PUSH +#undef JSON_HEDLEY_DMC_VERSION +#undef JSON_HEDLEY_DMC_VERSION_CHECK +#undef JSON_HEDLEY_EMPTY_BASES +#undef JSON_HEDLEY_EMSCRIPTEN_VERSION +#undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK +#undef JSON_HEDLEY_END_C_DECLS +#undef JSON_HEDLEY_FLAGS +#undef JSON_HEDLEY_FLAGS_CAST +#undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE +#undef JSON_HEDLEY_GCC_HAS_BUILTIN +#undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE +#undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE +#undef JSON_HEDLEY_GCC_HAS_EXTENSION +#undef JSON_HEDLEY_GCC_HAS_FEATURE +#undef JSON_HEDLEY_GCC_HAS_WARNING +#undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK +#undef JSON_HEDLEY_GCC_VERSION +#undef JSON_HEDLEY_GCC_VERSION_CHECK +#undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE +#undef JSON_HEDLEY_GNUC_HAS_BUILTIN +#undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE +#undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE +#undef JSON_HEDLEY_GNUC_HAS_EXTENSION +#undef JSON_HEDLEY_GNUC_HAS_FEATURE +#undef JSON_HEDLEY_GNUC_HAS_WARNING +#undef JSON_HEDLEY_GNUC_VERSION +#undef JSON_HEDLEY_GNUC_VERSION_CHECK +#undef JSON_HEDLEY_HAS_ATTRIBUTE +#undef JSON_HEDLEY_HAS_BUILTIN +#undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE +#undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS +#undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE +#undef JSON_HEDLEY_HAS_EXTENSION +#undef JSON_HEDLEY_HAS_FEATURE +#undef JSON_HEDLEY_HAS_WARNING +#undef JSON_HEDLEY_IAR_VERSION +#undef JSON_HEDLEY_IAR_VERSION_CHECK +#undef JSON_HEDLEY_IBM_VERSION +#undef JSON_HEDLEY_IBM_VERSION_CHECK +#undef JSON_HEDLEY_IMPORT +#undef JSON_HEDLEY_INLINE +#undef JSON_HEDLEY_INTEL_CL_VERSION +#undef JSON_HEDLEY_INTEL_CL_VERSION_CHECK +#undef JSON_HEDLEY_INTEL_VERSION +#undef JSON_HEDLEY_INTEL_VERSION_CHECK +#undef JSON_HEDLEY_IS_CONSTANT +#undef JSON_HEDLEY_IS_CONSTEXPR_ +#undef JSON_HEDLEY_LIKELY +#undef JSON_HEDLEY_MALLOC +#undef JSON_HEDLEY_MCST_LCC_VERSION +#undef JSON_HEDLEY_MCST_LCC_VERSION_CHECK +#undef JSON_HEDLEY_MESSAGE +#undef JSON_HEDLEY_MSVC_VERSION +#undef JSON_HEDLEY_MSVC_VERSION_CHECK +#undef JSON_HEDLEY_NEVER_INLINE +#undef JSON_HEDLEY_NON_NULL +#undef JSON_HEDLEY_NO_ESCAPE +#undef JSON_HEDLEY_NO_RETURN +#undef JSON_HEDLEY_NO_THROW +#undef JSON_HEDLEY_NULL +#undef JSON_HEDLEY_PELLES_VERSION +#undef JSON_HEDLEY_PELLES_VERSION_CHECK +#undef JSON_HEDLEY_PGI_VERSION +#undef JSON_HEDLEY_PGI_VERSION_CHECK +#undef JSON_HEDLEY_PREDICT +#undef JSON_HEDLEY_PRINTF_FORMAT +#undef JSON_HEDLEY_PRIVATE +#undef JSON_HEDLEY_PUBLIC +#undef JSON_HEDLEY_PURE +#undef JSON_HEDLEY_REINTERPRET_CAST +#undef JSON_HEDLEY_REQUIRE +#undef JSON_HEDLEY_REQUIRE_CONSTEXPR +#undef JSON_HEDLEY_REQUIRE_MSG +#undef JSON_HEDLEY_RESTRICT +#undef JSON_HEDLEY_RETURNS_NON_NULL +#undef JSON_HEDLEY_SENTINEL +#undef JSON_HEDLEY_STATIC_ASSERT +#undef JSON_HEDLEY_STATIC_CAST +#undef JSON_HEDLEY_STRINGIFY +#undef JSON_HEDLEY_STRINGIFY_EX +#undef JSON_HEDLEY_SUNPRO_VERSION +#undef JSON_HEDLEY_SUNPRO_VERSION_CHECK +#undef JSON_HEDLEY_TINYC_VERSION +#undef JSON_HEDLEY_TINYC_VERSION_CHECK +#undef JSON_HEDLEY_TI_ARMCL_VERSION +#undef JSON_HEDLEY_TI_ARMCL_VERSION_CHECK +#undef JSON_HEDLEY_TI_CL2000_VERSION +#undef JSON_HEDLEY_TI_CL2000_VERSION_CHECK +#undef JSON_HEDLEY_TI_CL430_VERSION +#undef JSON_HEDLEY_TI_CL430_VERSION_CHECK +#undef JSON_HEDLEY_TI_CL6X_VERSION +#undef JSON_HEDLEY_TI_CL6X_VERSION_CHECK +#undef JSON_HEDLEY_TI_CL7X_VERSION +#undef JSON_HEDLEY_TI_CL7X_VERSION_CHECK +#undef JSON_HEDLEY_TI_CLPRU_VERSION +#undef JSON_HEDLEY_TI_CLPRU_VERSION_CHECK +#undef JSON_HEDLEY_TI_VERSION +#undef JSON_HEDLEY_TI_VERSION_CHECK +#undef JSON_HEDLEY_UNAVAILABLE +#undef JSON_HEDLEY_UNLIKELY +#undef JSON_HEDLEY_UNPREDICTABLE +#undef JSON_HEDLEY_UNREACHABLE +#undef JSON_HEDLEY_UNREACHABLE_RETURN +#undef JSON_HEDLEY_VERSION +#undef JSON_HEDLEY_VERSION_DECODE_MAJOR +#undef JSON_HEDLEY_VERSION_DECODE_MINOR +#undef JSON_HEDLEY_VERSION_DECODE_REVISION +#undef JSON_HEDLEY_VERSION_ENCODE +#undef JSON_HEDLEY_WARNING +#undef JSON_HEDLEY_WARN_UNUSED_RESULT +#undef JSON_HEDLEY_WARN_UNUSED_RESULT_MSG +#undef JSON_HEDLEY_FALL_THROUGH + + + +#endif // INCLUDE_NLOHMANN_JSON_HPP_ diff --git a/vendor/DPP/include/dpp/nlohmann/json_fwd.hpp b/vendor/DPP/include/dpp/nlohmann/json_fwd.hpp new file mode 100644 index 00000000..332227c1 --- /dev/null +++ b/vendor/DPP/include/dpp/nlohmann/json_fwd.hpp @@ -0,0 +1,78 @@ +#ifndef INCLUDE_NLOHMANN_JSON_FWD_HPP_ +#define INCLUDE_NLOHMANN_JSON_FWD_HPP_ + +#include // int64_t, uint64_t +#include // map +#include // allocator +#include // string +#include // vector + +/*! +@brief namespace for Niels Lohmann +@see https://github.com/nlohmann +@since version 1.0.0 +*/ +namespace nlohmann +{ +/*! +@brief default JSONSerializer template argument + +This serializer ignores the template arguments and uses ADL +([argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl)) +for serialization. +*/ +template +struct adl_serializer; + +template class ObjectType = + std::map, + template class ArrayType = std::vector, + class StringType = std::string, class BooleanType = bool, + class NumberIntegerType = std::int64_t, + class NumberUnsignedType = std::uint64_t, + class NumberFloatType = double, + template class AllocatorType = std::allocator, + template class JSONSerializer = + adl_serializer, + class BinaryType = std::vector> +class basic_json; + +/*! +@brief JSON Pointer + +A JSON pointer defines a string syntax for identifying a specific value +within a JSON document. It can be used with functions `at` and +`operator[]`. Furthermore, JSON pointers are the base for JSON patches. + +@sa [RFC 6901](https://tools.ietf.org/html/rfc6901) + +@since version 2.0.0 +*/ +template +class json_pointer; + +/*! +@brief default JSON class + +This type is the default specialization of the @ref basic_json class which +uses the standard template types. + +@since version 1.0.0 +*/ +using json = basic_json<>; + +template +struct ordered_map; + +/*! +@brief ordered JSON class + +This type preserves the insertion order of object keys. + +@since version 3.9.0 +*/ +using ordered_json = basic_json; + +} // namespace nlohmann + +#endif // INCLUDE_NLOHMANN_JSON_FWD_HPP_ diff --git a/vendor/DPP/include/dpp/presence.h b/vendor/DPP/include/dpp/presence.h new file mode 100644 index 00000000..3652fa4c --- /dev/null +++ b/vendor/DPP/include/dpp/presence.h @@ -0,0 +1,252 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include + +namespace dpp { + +/** + * @brief Presence flags bitmask + */ +enum presence_flags { + /// Desktop: Online + p_desktop_online = 0b00000001, + /// Desktop: DND + p_desktop_dnd = 0b00000010, + /// Desktop: Idle + p_desktop_idle = 0b00000011, + /// Web: Online + p_web_online = 0b00000100, + /// Web: DND + p_web_dnd = 0b00001000, + /// Web: Idle + p_web_idle = 0b00001100, + /// Mobile: Online + p_mobile_online = 0b00010000, + /// Mobile: DND + p_mobile_dnd = 0b00100000, + /// Mobile: Idle + p_mobile_idle = 0b00110000, + /// General: Online + p_status_online = 0b01000000, + /// General: DND + p_status_dnd = 0b10000000, + /// General: Idle + p_status_idle = 0b11000000 +}; + +/** + * @brief Online presence status values + */ +enum presence_status : uint8_t { + /// Offline + ps_offline = 0, + /// Online + ps_online = 1, + /// DND + ps_dnd = 2, + /// Idle + ps_idle = 3 +}; + +/** + * @brief Bit shift for desktop status + */ +#define PF_SHIFT_DESKTOP 0 +/** Bit shift for web status */ +#define PF_SHIFT_WEB 2 +/** Bit shift for mobile status */ +#define PF_SHIFT_MOBILE 4 +/** Bit shift for main status */ +#define PF_SHIFT_MAIN 6 +/** Bit mask for status */ +#define PF_STATUS_MASK 0b00000011 +/** Bit mask for clearing desktop status */ +#define PF_CLEAR_DESKTOP 0b11111100 +/** Bit mask for clearing web status */ +#define PF_CLEAR_WEB 0b11110011 +/** Bit mask for clearing mobile status */ +#define PF_CLEAR_MOBILE 0b11001111 +/** Bit mask for clearing main status */ +#define PF_CLEAR_STATUS 0b00111111 + +/** + * @brief Game types + */ +enum activity_type : uint8_t { + /// "Playing ..." + at_game = 0, + /// "Streaming ..." + at_streaming = 1, + /// "Listening to..." + at_listening = 2, + /// "Watching..." + at_custom = 3, + /// "Competing in..." + at_competing = 4 +}; + +/** + * @brief Activity types for rich presence + */ +enum activity_flags { + /// In an instance + af_instance = 0b00000001, + /// Joining + af_join = 0b00000010, + /// Spectating + af_spectate = 0b00000100, + /// Sending join request + af_join_request = 0b00001000, + /// Synchronising + af_sync = 0b00010000, + /// Playing + af_play = 0b00100000 +}; + +/** + * @brief An activity is a representation of what a user is doing. It might be a game, or a website, or a movie. Whatever. + */ +class CoreExport activity { +public: + /** Name of ativity + * e.g. "Fortnite" + */ + std::string name; + /** State of activity. + * e.g. "Waiting in lobby" + */ + std::string state; + /** URL. + * Only applicable for certain sites such a YouTube + * Alias: details + */ + std::string url; + /** Activity type + */ + activity_type type; + /** Time activity was created + */ + time_t created_at; + /** Start time. e.g. when game was started + */ + time_t start; + /** End time, e.g. for songs on spotify + */ + time_t end; + /** Creating application (e.g. a linked account on the user's client) + */ + snowflake application_id; + /** Flags bitmask from activity_flags + */ + uint8_t flags; + + activity() = default; + + /** + * @brief Construct a new activity + * + * @param typ + * @param nam + * @param stat + * @param url_ + */ + activity(const activity_type typ, const std::string& nam, const std::string& stat, const std::string& url_); +}; + +/** + * @brief Represents user presence, e.g. what game they are playing and if they are online + */ +class CoreExport presence { +public: + /** The user the presence applies to */ + snowflake user_id; + + /** Guild ID. Apparently, Discord supports this internally but the client doesnt... */ + snowflake guild_id; + + /** Flags bitmask containing presence_flags */ + uint8_t flags; + + /** List of activities */ + std::vector activities; + + /** Constructor */ + presence(); + + /** + * @brief Construct a new presence object with some parameters for sending to a websocket + * + * @param status + * @param type + * @param activity_description + */ + presence(presence_status status, activity_type type, const std::string& activity_description); + + /** + * @brief Construct a new presence object with some parameters for sending to a websocket + * + * @param status + * @param a Activity itself + */ + presence(presence_status status, activity a); + + /** Destructor */ + ~presence(); + + /** Fill this object from json. + * @param j JSON object to fill from + * @return A reference to self + */ + presence& fill_from_json(nlohmann::json* j); + + /** Build JSON from this object. + * @return The JSON text of the presence + */ + std::string build_json() const; + + /** The users status on desktop + * @return The user's status on desktop + */ + presence_status desktop_status() const; + + /** The user's status on web + * @return The user's status on web + */ + presence_status web_status() const; + + /** The user's status on mobile + * @return The user's status on mobile + */ + presence_status mobile_status() const; + + /** The user's status as shown to other users + * @return The user's status as shown to other users + */ + presence_status status() const; +}; + +/** A container of presences */ +typedef std::unordered_map presence_map; + +}; diff --git a/vendor/DPP/include/dpp/prune.h b/vendor/DPP/include/dpp/prune.h new file mode 100644 index 00000000..04b24daf --- /dev/null +++ b/vendor/DPP/include/dpp/prune.h @@ -0,0 +1,57 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include + +namespace dpp { + +/** + * @brief Defines a request to count prunable users, or start a prune operation + */ +struct CoreExport prune { + /** Number of days to include in the prune + */ + uint32_t days = 0; + /** Roles to include in the prune (empty to include everyone) + */ + std::vector include_roles; + /** True if the count of pruneable users should be returned + * (discord recommend not using this on big guilds) + */ + bool compute_prune_count; + + /** Fill this object from json. + * @param j JSON object to fill from + * @return A reference to self + */ + prune& fill_from_json(nlohmann::json* j); + + /** Build JSON from this object. + * @param with_prune_count True if the prune count boolean is to be set in the built JSON + * @return The JSON text of the prune object + */ + std::string build_json(bool with_prune_count) const; + +}; + +}; diff --git a/vendor/DPP/include/dpp/queues.h b/vendor/DPP/include/dpp/queues.h new file mode 100644 index 00000000..1f979aa3 --- /dev/null +++ b/vendor/DPP/include/dpp/queues.h @@ -0,0 +1,270 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace dpp { + +/** Encodes a url parameter similar to php urlencode() */ +std::string url_encode(const std::string &value); + +/** Error values. Don't change the order or add extra values here, + * as they map onto the error values of cpp-httplib + */ +enum http_error { + /// Request successful + h_success = 0, + /// Status unknown + h_unknown, + /// Connect failed + h_connection, + /// Invalid local ip address + h_bind_ip_address, + /// Read error + h_read, + /// Write error + h_write, + /// Too many 30x redirects + h_exceed_redirect_count, + /// Request cancelled + h_canceled, + /// SSL connection error + h_ssl_connection, + /// SSL cert loading error + h_ssl_loading_certs, + /// SSL server verification error + h_ssl_server_verification, + /// Unsupported multipart boundary characters + h_unsupported_multipart_boundary_chars, + /// Compression error + h_compression, +}; + +/** + * @brief The result of any HTTP request. Contains the headers, vital + * rate limit figures, and returned request body. + */ +struct CoreExport http_request_completion_t { + /** HTTP headers of response */ + std::map headers; + /** HTTP status, e.g. 200 = OK, 404 = Not found, 429 = Rate limited */ + uint16_t status = 0; + /** Error status (e.g. if the request could not connect at all) */ + http_error error = h_success; + /** Ratelimit bucket */ + std::string ratelimit_bucket; + /** Ratelimit limit of requests */ + uint64_t ratelimit_limit = 0; + /** Ratelimit remaining requests */ + uint64_t ratelimit_remaining = 0; + /** Ratelimit reset after (seconds) */ + uint64_t ratelimit_reset_after = 0; + /** Ratelimit retry after (seconds) */ + uint64_t ratelimit_retry_after = 0; + /** True if this request has caused us to be globally rate limited */ + bool ratelimit_global = false; + /** Reply body */ + std::string body; +}; + +/** + * @brief Results of HTTP requests are called back to these std::function types. + * @note Returned http_completion_events are called ASYNCRONOUSLY in your + * code which means they execute in a separate thread. The completion events + * arrive in order. + */ +typedef std::function http_completion_event; + +/** Various types of http method supported by the Discord API + */ +enum http_method { + /// GET + m_get, + /// POST + m_post, + /// PUT + m_put, + /// PATCH + m_patch, + /// DELETE + m_delete +}; + +/** + * @brief A HTTP request. + * + * You should instantiate one of these objects via its constructor, + * and pass a pointer to it into an instance of request_queue. Although you can + * directly call the Run() method of the object and it will make a HTTP call, be + * aware that if you do this, it will be a **BLOCKING call** (not asynchronous) and + * will not respect rate limits, as both of these functions are managed by the + * request_queue class. + */ +class CoreExport http_request { + /** Completion callback */ + http_completion_event complete_handler; + /** True if request has been made */ + bool completed; +public: + /** Endpoint name e.g. /api/users */ + std::string endpoint; + /** Major and minor parameters */ + std::string parameters; + /** Postdata for POST and PUT */ + std::string postdata; + /** HTTP method for request */ + http_method method; + /** Upload file name (server side) */ + std::string file_name; + /** Upload file contents (binary) */ + std::string file_content; + + /** Constructor. When constructing one of these objects it should be passed to request_queue::post_request(). + * @param _endpoint The API endpoint, e.g. /api/guilds + * @param _parameters Major and minor parameters for the endpoint e.g. a user id or guild id + * @param completion completion event to call when done + * @param _postdata Data to send in POST and PUT requests + * @param method The HTTP method to use from dpp::http_method + * @param filename The filename (server side) of any uploaded file + * @param filecontent The binary content of any uploaded file for the request + */ + http_request(const std::string &_endpoint, const std::string &_parameters, http_completion_event completion, const std::string &_postdata = "", http_method method = m_get, const std::string &filename = "", const std::string &filecontent = ""); + + /** Destructor */ + ~http_request(); + + /** Call the completion callback, if the request is complete. + * @param c callback to call + */ + void complete(const http_request_completion_t &c); + + /** Execute the HTTP request and mark the request complete. + * @param owner creating cluster + */ + http_request_completion_t Run(const class cluster* owner); + + /** Returns true if the request is complete */ + bool is_completed(); +}; + +/** A rate limit bucket. The library builds one of these for + * each endpoint. + */ +struct CoreExport bucket_t { + /** Request limit */ + uint64_t limit; + /** Requests remaining */ + uint64_t remaining; + /** Ratelimit of this bucket resets after this many seconds */ + uint64_t reset_after; + /** Ratelimit of this bucket can be retried after this many seconds */ + uint64_t retry_after; + /** Timestamp this buckets counters were updated */ + time_t timestamp; +}; + +/** + * @brief The request_queue class manages rate limits and marshalls HTTP requests that have + * been built as http_request objects. + * + * It ensures asynchronous delivery of events and queueing of requests. + * + * It will spawn two threads, one to make outbound HTTP requests and push the returned + * results into a queue, and the second to call the callback methods with these results. + * They are separated so that if the user decides to take a long time processing a reply + * in their callback it won't affect when other requests are sent, and if a HTTP request + * takes a long time due to latency, it won't hold up user processing. + * + * There is usually only one request_queue object in each dpp::cluster, which is used + * internally for the various REST methods such as sending messages. + */ +class CoreExport request_queue { +private: + /** The cluster that owns this request_queue */ + const class cluster* creator; + /** Mutexes for thread safety */ + std::mutex in_mutex; + std::mutex out_mutex; + /** In and out threads */ + std::thread* in_thread; + std::thread* out_thread; + /** Ratelimit bucket counters */ + std::map buckets; + /** Queue of requests to be made */ + std::map> requests_in; + /** Completed requests queue */ + std::queue> responses_out; + /** Completed requests to delete */ + std::multimap> responses_to_delete; + + /** Set to true if the threads should terminate */ + bool terminating; + /** True if globally rate limited - makes the entire request thread wait */ + bool globally_ratelimited; + /** How many seconds we are globally rate limited for, if globally_ratelimited is true */ + uint64_t globally_limited_for; + + /** Ports for notifications of request completion. + * Why are we using sockets here instead of std::condition_variable? Because + * in the future we will want to notify across clusters of completion and state, + * and we can't do this across processes with condition variables. + */ + int in_queue_port; + int out_queue_port; + int in_queue_listen_sock; + int in_queue_connect_sock; + int out_queue_listen_sock; + int out_queue_connect_sock; + + /** Thread loop functions */ + void in_loop(); + void out_loop(); + + /** Notify request thread of a new request */ + void emit_in_queue_signal(); + + /** Notify completion thread of new completed request */ + void emit_out_queue_signal(); +public: + /** Constructor + * @param owner The creating cluster + */ + request_queue(const class cluster* owner); + + /** Destructor */ + ~request_queue(); + + /** Put a http_request into the request queue. You should ALWAYS "new" an object + * to pass to here -- don't submit an object that's on the stack! + * @param req request to add + */ + void post_request(http_request *req); +}; + +}; diff --git a/vendor/DPP/include/dpp/role.h b/vendor/DPP/include/dpp/role.h new file mode 100644 index 00000000..96e2502c --- /dev/null +++ b/vendor/DPP/include/dpp/role.h @@ -0,0 +1,202 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include + +namespace dpp { + +/** Various flags related to dpp::role */ +enum role_flags { + r_hoist = 0b00000001, //!< Hoisted role + r_managed = 0b00000010, //!< Managed role (introduced by a bot or application) + r_mentionable = 0b00000100, //!< Mentionable with an @ping + r_premium_subscriber = 0b00001000, //!< This is set for the role given to nitro +}; + +/** + * @brief Represents the various discord permissions + */ +enum role_permissions : uint64_t { + p_create_instant_invite = 0x00000001, //!< allows creationboosters of instant invites + p_kick_members = 0x00000002, //!< allows kicking members + p_ban_members = 0x00000004, //!< allows banning members + p_administrator = 0x00000008, //!< allows all permissions and bypasses channel permission overwrites + p_manage_channels = 0x00000010, //!< allows management and editing of channels + p_manage_guild = 0x00000020, //!< allows management and editing of the guild + p_add_reactions = 0x00000040, //!< allows for the addition of reactions to messages + p_view_audit_log = 0x00000080, //!< allows for viewing of audit logs + p_priority_speaker = 0x00000100, //!< allows for using priority speaker in a voice channel + p_stream = 0x00000200, //!< allows the user to go live + p_view_channel = 0x00000400, //!< allows guild members to view a channel, which includes reading messages in text channels + p_send_messages = 0x00000800, //!< allows for sending messages in a channel + p_send_tts_messages = 0x00001000, //!< allows for sending of /tts messages + p_manage_messages = 0x00002000, //!< allows for deletion of other users messages + p_embed_links = 0x00004000, //!< links sent by users with this permission will be auto-embedded + p_attach_files = 0x0000008000, //!< allows for uploading images and files + p_read_message_history = 0x0000010000, //!< allows for reading of message history + p_mention_everyone = 0x0000020000, //!< allows for using the @everyone and the @here tag to notify users in a channel + p_use_external_emojis = 0x0000040000, //!< allows the usage of custom emojis from other servers + p_view_guild_insights = 0x0000080000, //!< allows for viewing guild insights + p_connect = 0x0000100000, //!< allows for joining of a voice channel + p_speak = 0x0000200000, //!< allows for speaking in a voice channel + p_mute_members = 0x0000400000, //!< allows for muting members in a voice channel + p_deafen_members = 0x0000800000, //!< allows for deafening of members in a voice channel + p_move_members = 0x0001000000, //!< allows for moving of members between voice channels + p_use_vad = 0x0002000000, //!< allows for using voice-activity-detection in a voice channel + p_change_nickname = 0x0004000000, //!< allows for modification of own nickname + p_manage_nicknames = 0x0008000000, //!< allows for modification of other users nicknames + p_manage_roles = 0x0010000000, //!< allows management and editing of roles + p_manage_webhooks = 0x0020000000, //!< allows management and editing of webhooks + p_manage_emojis = 0x0040000000, //!< allows management and editing of emojis + p_use_slash_commands = 0x0080000000, //!< allows members to use slash commands + p_request_to_speak = 0x0100000000, //!< allows for requesting to speak in stage channels. (Discord: This permission is under active development and may be changed or removed.) + p_manage_threads = 0x0400000000, //!< allows for deleting and archiving threads, and viewing all private threads + p_use_public_threads = 0x0800000000, //!< allows for creating and participating in thread + p_use_private_threads = 0x1000000000, //!< allows for creating and participating in private thread +}; + +/** + * @brief Represents a role within a dpp::guild + */ +class CoreExport role : public managed { +public: + /** Role name */ + std::string name; + /** Guild id */ + snowflake guild_id; + /** Role colour */ + uint32_t colour; + /** Role position */ + uint8_t position; + /** Role permissions bitmask values from dpp::role_permissions */ + uint64_t permissions; + /** Role flags from dpp::role_flags */ + uint8_t flags; + /** Integration id if any (e.g. role is a bot's role created when it was invited) */ + snowflake integration_id; + /** Bot id if any (e.g. role is a bot's role created when it was invited) */ + snowflake bot_id; + + /** Default constructor */ + role(); + + /** Default destructor */ + virtual ~role(); + + /** Fill this role from json. + * @param guild_id the guild id to place in the json + * @param j The json data + * @return A reference to self + */ + role& fill_from_json(snowflake guild_id, nlohmann::json* j); + + /** Build a json string from this object. + * @param with_id true if the ID is to be included in the json text + * @return The json of the role + */ + std::string build_json(bool with_id = false) const; + + /** True if the role is hoisted */ + bool is_hoisted() const; + /** True if the role is mentionable */ + bool is_mentionable() const; + /** True if the role is managed (belongs to a bot or application) */ + bool is_managed() const; + /** True if has create instant invite permission */ + bool has_create_instant_invite() const; + /** True if has the kick members permission */ + bool has_kick_members() const; + /** True if has the ban members permission */ + bool has_ban_members() const; + /** True if has the administrator permission */ + bool has_administrator() const; + /** True if has the manage channels permission */ + bool has_manage_channels() const; + /** True if has the manage guild permission */ + bool has_manage_guild() const; + /** True if has the add reactions permission */ + bool has_add_reactions() const; + /** True if has the view audit log permission */ + bool has_view_audit_log() const; + /** True if has the priority speaker permission */ + bool has_priority_speaker() const; + /** True if has the stream permission */ + bool has_stream() const; + /** True if has the view channel permission */ + bool has_view_channel() const; + /** True if has the send messages permission */ + bool has_send_messages() const; + /** True if has the send TTS messages permission */ + bool has_send_tts_messages() const; + /** True if has the manage messages permission */ + bool has_manage_messages() const; + /** True if has the embed links permission */ + bool has_embed_links() const; + /** True if has the attach files permission */ + bool has_attach_files() const; + /** True if has the read message history permission */ + bool has_read_message_history() const; + /** True if has the mention \@everyone and \@here permission */ + bool has_mention_everyone() const; + /** True if has the use external emojis permission */ + bool has_use_external_emojis() const; + /** True if has the view guild insights permission */ + bool has_view_guild_insights() const; + /** True if has the connect voice permission */ + bool has_connect() const; + /** True if has the speak permission */ + bool has_speak() const; + /** True if has the mute members permission */ + bool has_mute_members() const; + /** True if has the deafen members permission */ + bool has_deafen_members() const; + /** True if has the move members permission */ + bool has_move_members() const; + /** True if has use voice activity detection permission */ + bool has_use_vad() const; + /** True if has the change nickname permission */ + bool has_change_nickname() const; + /** True if has the manage nicknames permission */ + bool has_manage_nicknames() const; + /** True if has the manage roles permission */ + bool has_manage_roles() const; + /** True if has the manage webhooks permission */ + bool has_manage_webhooks() const; + /** True if has the manage emojis permission */ + bool has_manage_emojis() const; + /** True if has the use slash commands permission*/ + bool has_use_slash_commands() const; + /** True if has the request to speak permission*/ + bool has_request_to_speak() const; + /** True if has the manage threads permission*/ + bool has_manage_threads() const; + /** True if has the use public threads permission*/ + bool has_use_public_threads() const; + /** True if has the use private threads permission*/ + bool has_use_private_threads() const; +}; + +/** A group of roles */ +typedef std::unordered_map role_map; + +}; + diff --git a/vendor/DPP/include/dpp/slashcommand.h b/vendor/DPP/include/dpp/slashcommand.h new file mode 100644 index 00000000..209ea5f4 --- /dev/null +++ b/vendor/DPP/include/dpp/slashcommand.h @@ -0,0 +1,555 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief Represents command option types. + * These are the possible parameter value types. + */ +enum command_option_type : uint8_t { + /** A sub-command */ + co_sub_command = 1, + /** A sub-command group */ + co_sub_command_group = 2, + /** A string value */ + co_string = 3, + /** An integer value */ + co_integer = 4, + /** A boolean value */ + co_boolean = 5, + /** A user snowflake id */ + co_user = 6, + /** A channel snowflake id */ + co_channel = 7, + /** A role snowflake id */ + co_role = 8 +}; + +/** + * @brief This type is a variant that can hold any of the potential + * native data types represented by the enum above. + * It is used in interactions. + */ +typedef std::variant command_value; + +/** + * @brief This struct represents choices in a multiple choice option + * for a command parameter. + * It has both a string name, and a value parameter which is a variant, + * meaning it can hold different potential types (see dpp::command_value) + * that you can retrieve with std::get(). + */ +struct CoreExport command_option_choice { + std::string name; //!< Option name (1-32 chars) + command_value value; //!< Option value + + /** + * @brief Construct a new command option choice object + */ + command_option_choice() = default; + + /** + * @brief Construct a new command option choice object + * + * @param n name to initialise with + * @param v value to initialise with + */ + command_option_choice(const std::string &n, command_value v); +}; + +/** + * @brief helper function to serialize a command_option_choice to json + * + * @see https://github.com/nlohmann/json#arbitrary-types-conversions + * + * @param j output json object + * @param choice command_option_choice to be serialized + */ +void to_json(nlohmann::json& j, const command_option_choice& choice); + +/** + * @brief Each command option is a command line parameter. + * It can have a type (see dpp::command_option_type), a name, + * a description, can be required or optional, and can have + * zero or more choices (for multiple choice), plus options. + * Adding options acts like sub-commands and can contain more + * options. + */ +struct CoreExport command_option { + command_option_type type; //!< Option type (what type of value is accepted) + std::string name; //!< Option name (1-32 chars) + std::string description; //!< Option description (1-100 chars) + bool required; //!< True if this is a mandatory parameter + std::vector choices; //!< List of choices for multiple choice command + std::vector options; //!< Sub-commands + + /** + * @brief Construct a new command option object + */ + command_option() = default; + + /** + * @brief Construct a new command option object + * + * @param t Option type + * @param name Option name + * @param description Option description + * @param required True if this is a mandatory parameter + */ + command_option(command_option_type t, const std::string &name, const std::string &description, bool required = false); + + /** + * @brief Add a multiple choice option + * + * @param o choice to add + * @return command_option& returns a reference to self for chaining of calls + */ + command_option& add_choice(const command_option_choice &o); + + /** + * @brief Add a sub-command option + * + * @param o Sub-command option to add + * @return command_option& return a reference to self for chaining of calls + */ + command_option& add_option(const command_option &o); +}; + +/** + * @brief helper function to serialize a command_option to json + * + * @see https://github.com/nlohmann/json#arbitrary-types-conversions + * + * @param j output json object + * @param opt command_option to be serialized + */ +void to_json(nlohmann::json& j, const command_option& opt); + +/** + * @brief Response types when responding to an interaction within on_interaction_create. + * Do not use ir_acknowledge or ir::channel_message, as these are deprecated in the + * Discord API spec. They are listed in this enum for completeness. + */ +enum interaction_response_type { + ir_pong = 1, //!< ACK a Ping + ir_acknowledge = 2, //!< DEPRECATED ACK a command without sending a message, eating the user's input + ir_channel_message = 3, //!< DEPRECATED respond with a message, eating the user's input + ir_channel_message_with_source = 4, //!< respond to an interaction with a message + ir_deferred_channel_message_with_source = 5, //!< ACK an interaction and edit a response later, the user sees a loading state + ir_deferred_update_message = 6, //!< for components, ACK an interaction and edit the original message later; the user does not see a loading state + ir_update_message = 7 //!< for components, edit the message the component was attached to +}; + +/** + * @brief A response to an interaction, used to reply to a command and initiate + * a message, which can be hidden from others (ephemeral) or visible to all. + * + * The dpp::interaction_response object wraps a dpp::message object. To set the + * message as 'ephemeral' (e.g. only the command issuer can see it) you should + * add the dpp::m_ephemeral flag to the dpp::message::flags field. e.g.: + * + * `mymessage.flags |= dpp::m_ephemeral;` + */ +struct CoreExport interaction_response { + + /** + * @brief Response type from dpp::interaction_response_type. + * Should be one of ir_pong, ir_channel_message_with_source, + * or ir_deferred_channel_message_with_source. + */ + interaction_response_type type; + + /** + * @brief A message object. This pointer is always valid + * while the containing interaction_response exists. + */ + struct message* msg; + + /** + * @brief Construct a new interaction response object + */ + interaction_response(); + + /** + * @brief Construct a new interaction response object + * + * @param t Type of reply + * @param m Message to reply with + */ + interaction_response(interaction_response_type t, const struct message& m); + + /** + * @brief Fill object properties from JSON + * + * @param j JSON to fill from + * @return interaction_response& Reference to self + */ + interaction_response& fill_from_json(nlohmann::json* j); + + /** + * @brief Build a json string for this object + * + * @return std::string JSON string + */ + std::string build_json() const; + + /** + * @brief Destroy the interaction response object + */ + ~interaction_response(); + +}; + +/** + * @brief Resolved snowflake ids to usernames. + * TODO: Needs implementation. Not needed something that + * functions as we have cache. + */ +struct CoreExport command_resolved { +}; + +/** + * @brief Values in the command interaction. + * These are the values specified by the user when actually issuing + * the command on a channel or in DM. + */ +struct CoreExport command_data_option { + std::string name; //!< the name of the parameter + command_option_type type; //!< value of ApplicationCommandOptionType + command_value value; //!< Optional: the value of the pair + std::vector options; //!< Optional: present if this option is a group or subcommand + dpp::snowflake target_id; //!< Non-zero target ID for context menu actions +}; + +/** + * @brief helper function to deserialize a command_data_option from json + * + * @see https://github.com/nlohmann/json#arbitrary-types-conversions + * + * @param j output json object + * @param cdo command_data_option to be deserialized + */ +void from_json(const nlohmann::json& j, command_data_option& cdo); + +/** Types of interaction in the dpp::interaction class + */ +enum interaction_type { + it_ping = 1, //!< ping + it_application_command = 2, //!< application command (slash command) + it_component_button = 3 //!< button click (component interaction) +}; + +/** + * @brief Details of a command within an interaction. + * This subobject represents the application command associated + * with the interaction. + */ +struct CoreExport command_interaction { + snowflake id; //!< the ID of the invoked command + std::string name; //!< the name of the invoked command + command_resolved resolved; //!< Optional: converted users + roles + channels + std::vector options; //!< Optional: the params + values from the user +}; + +/** + * @brief helper function to deserialize a command_interaction from json + * + * @see https://github.com/nlohmann/json#arbitrary-types-conversions + * + * @param j output json object + * @param ci command_interaction to be deserialized + */ +void from_json(const nlohmann::json& j, command_interaction& ci); + +enum component_type_t { + cotype_button = 2, + cotype_select = 3 +}; + +/** + * @brief A button click for a button component + */ +struct CoreExport component_interaction { + uint8_t component_type; + std::string custom_id; + std::vector values; +}; + +/** + * @brief helper function to deserialize a component_interaction from json + * + * @see https://github.com/nlohmann/json#arbitrary-types-conversions + * + * @param j output json object + * @param bi button_interaction to be deserialized + */ +void from_json(const nlohmann::json& j, component_interaction& bi); + +/** + * @brief An interaction represents a user running a command and arrives + * via the dpp::cluster::on_interaction_create event. + */ +class CoreExport interaction : public managed { +public: + snowflake application_id; //!< id of the application this interaction is for + uint8_t type; //!< the type of interaction + std::variant data; //!< Optional: the command data payload + snowflake guild_id; //!< Optional: the guild it was sent from + snowflake channel_id; //!< Optional: the channel it was sent from + snowflake message_id; //!< Originating message id + guild_member member; //!< Optional: guild member data for the invoking user, including permissions + user usr; //!< Optional: user object for the invoking user, if invoked in a DM + std::string token; //!< a continuation token for responding to the interaction + uint8_t version; //!< read-only property, always 1 + + /** + * @brief Fill object properties from JSON + * + * @param j JSON to fill from + * @return interaction& Reference to self + */ + interaction& fill_from_json(nlohmann::json* j); + + /** + * @brief Build a json string for this object + * + * @param with_id True if to include the ID in the JSON + * @return std::string JSON string + */ + std::string build_json(bool with_id = false) const; +}; + +/** + * @brief helper function to deserialize an interaction from json + * + * @see https://github.com/nlohmann/json#arbitrary-types-conversions + * + * @param j output json object + * @param i interaction to be deserialized + */ +void from_json(const nlohmann::json& j, interaction& i); + +/** + * @brief type of permission in the dpp::command_permission class + */ +enum command_permission_type { + cpt_role = 1, + cpt_user = 2, +}; + +/** + * @brief Application command permissions allow you to enable or + * disable commands for specific users or roles within a guild + */ +class CoreExport command_permission { +public: + snowflake id; //!< the ID of the role or uses + command_permission_type type; //!< the type of permission + bool permission; //!< true to allow, false, to disallow +}; + +/** + * @brief helper function to serialize a command_permission to json + * + * @see https://github.com/nlohmann/json#arbitrary-types-conversions + * + * @param j output json object + * @param cp command_permission to be serialized + */ +void to_json(nlohmann::json& j, const command_permission& cp); + +/** + * @brief Returned when fetching the permissions for a command in a guild. + */ +class CoreExport guild_command_permissions { +public: + snowflake id; //!< the id of the command + snowflake application_id; //!< the id of the application the command belongs to + snowflake guild_id; //!< the id of the guild + std::vector permissions; //!< the permissions for the command in the guild +}; + +/** + * @brief helper function to serialize a guild_command_permissions to json + * + * @see https://github.com/nlohmann/json#arbitrary-types-conversions + * + * @param j output json object + * @param gcp guild_command_permissions to be serialized + */ +void to_json(nlohmann::json& j, const guild_command_permissions& gcp); + +enum slashcommand_contextmenu_type { + ctxm_none = 0, + ctxm_chat_input = 1, //!< DEFAULT, these are the slash commands you're used to + ctxm_user = 2, //!< Add command to user context menu + ctxm_message = 3 //!< Add command to message context menu +}; + +/** + * @brief Represents an application command, created by your bot + * either globally, or on a guild. + */ +class CoreExport slashcommand : public managed { +public: + /** + * @brief Application id (usually matches your bots id) + */ + snowflake application_id; + + /** + * @brief Context menu type, defaults to none + * + */ + slashcommand_contextmenu_type type; + + /** + * @brief Command name (1-32 chars) + */ + std::string name; + + /** + * @brief Command description (1-100 chars) + */ + std::string description; + + /** + * @brief Command options (parameters) + */ + std::vector options; + + /** + * @brief whether the command is enabled by default when the app is added to a guild + */ + bool default_permission; + + /** + * @brief command permissions + */ + std::vector permissions; + + /** + * @brief Construct a new slashcommand object + */ + slashcommand(); + + /** + * @brief Destroy the slashcommand object + */ + ~slashcommand(); + + /** + * @brief Add an option (parameter) + * + * @param o option (parameter) to add + * @return slashcommand& reference to self for chaining of calls + */ + slashcommand& add_option(const command_option &o); + + /** + * @brief Set the type of the slash command (only for context menu entries) + * + * @param _type Type of context menu entry this command represents + * @return slashcommand& reference to self for chaining of calls + */ + slashcommand& set_type(slashcommand_contextmenu_type _type); + + /** + * @brief Set the name of the command + * + * @param n name of command + * @return slashcommand& reference to self for chaining of calls + */ + slashcommand& set_name(const std::string &n); + + /** + * @brief Set the description of the command + * + * @param d description + * @return slashcommand& reference to self for chaining of calls + */ + slashcommand& set_description(const std::string &d); + + /** + * @brief Set the application id of the command + * + * @param i application id + * @return slashcommand& reference to self for chaining of calls + */ + slashcommand& set_application_id(snowflake i); + + /** + * @brief Adds a permission to the command + * + * @param p permission to add + * @return slashcommand& reference to self for chaining of calls + */ + slashcommand& add_permission(const command_permission& p); + + /** + * @brief Disable default permissions, command will be unusable unless + * permissions are overriden with add_permission and + * dpp::guild_command_edit_permissions + * + * @return slashcommand& reference to self for chaining of calls + */ + slashcommand& disable_default_permissions(); + + /** + * @brief Fill object properties from JSON + * + * @param j JSON to fill from + * @return slashcommand& Reference to self + */ + slashcommand& fill_from_json(nlohmann::json* j); + + /** + * @brief Build a json string for this object + * + * @param with_id True if to include the ID in the JSON + * @return std::string JSON string + */ + std::string build_json(bool with_id = false) const; +}; + +/** + * @brief helper function to serialize a slashcommand to json + * + * @see https://github.com/nlohmann/json#arbitrary-types-conversions + * + * @param j output json object + * @param cmd slashcommand to be serialized + */ +void to_json(nlohmann::json& j, const slashcommand& cmd); + +/** + * @brief A group of application slash commands + */ +typedef std::unordered_map slashcommand_map; + +}; diff --git a/vendor/DPP/include/dpp/sslclient.h b/vendor/DPP/include/dpp/sslclient.h new file mode 100644 index 00000000..6730eae6 --- /dev/null +++ b/vendor/DPP/include/dpp/sslclient.h @@ -0,0 +1,165 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include + +namespace dpp { + +/** This is an opaque class containing openssl library specific structures. + * We define it this way so that the public facing D++ library doesnt require + * the openssl headers be available to build against it. + */ +class opensslcontext; + +/** + * @brief Implements a simple non-blocking SSL stream client. + * + * Note that although the design is non-blocking the Run() method will + * execute in an infinite loop until the socket disconnects. This is intended + * to be run within a std::thread. + */ +class CoreExport ssl_client +{ +protected: + /** Input buffer received from openssl */ + std::string buffer; + + /** Output buffer for sending to openssl */ + std::string obuffer; + + /** True if in nonblocking mode. The socket switches to nonblocking mode + * once ReadLoop is called. + */ + bool nonblocking; + + /** Raw file descriptor of connection */ + SOCKET sfd; + + /** Openssl opaque contexts */ + opensslcontext* ssl; + + /** SSL cipher in use */ + std::string cipher; + + /** For timers */ + time_t last_tick; + + /** Hostname connected to */ + std::string hostname; + + /** Port connected to */ + std::string port; + + /** Bytes out */ + uint64_t bytes_out; + + /** Bytes in */ + uint64_t bytes_in; + + /** Called every second */ + virtual void one_second_timer(); + + /** Start connection */ + virtual void Connect(); +public: + /** Get total bytes sent */ + uint64_t get_bytes_out(); + + /** Get total bytes received */ + uint64_t get_bytes_in(); + + /** Get SSL cipher name */ + std::string get_cipher(); + + /** + * @brief Attaching an additional file descriptor to this function will send notifications when there is data to read. + * + * NOTE: Only hook this if you NEED it as it can increase CPU usage of the thread! + * Returning -1 means that you don't want to be notified. + */ + std::function custom_readable_fd; + + /** + * @brief Attaching an additional file descriptor to this function will send notifications when you are able to write + * to the socket. + * + * NOTE: Only hook this if you NEED it as it can increase CPU usage of the thread! You should toggle this + * to -1 when you do not have anything to write otherwise it'll keep triggering repeatedly (it is level triggered). + */ + std::function custom_writeable_fd; + + /** + * @brief This event will be called when you can read from the custom fd + */ + std::function custom_readable_ready; + + /** + * @brief This event will be called when you can write to a custom fd + */ + std::function custom_writeable_ready; + + /** + * @brief Connect to a specified host and port. Throws std::runtime_error on fatal error. + * @param _hostname The hostname to connect to + * @param _port the Port number to connect to + */ + ssl_client(const std::string &_hostname, const std::string &_port = "443"); + + /** + * @brief Nonblocking I/O loop + */ + void read_loop(); + + /** + * @brief Destroy the ssl_client object + */ + virtual ~ssl_client(); + + /** + * @brief Handle input from the input buffer. + * @param buffer the buffer content. Will be modified removing any processed front elements + */ + virtual bool handle_buffer(std::string &buffer); + + /** + * @brief Write to the output buffer. + * @param data Data to be written to the buffer + */ + virtual void write(const std::string &data); + + /** + * @brief Close SSL connection + */ + virtual void close(); + + /** + * @brief Log a message + * + * @param severity severity of log message + * @param msg Log message to send + */ + virtual void log(dpp::loglevel severity, const std::string &msg) const; +}; + +}; \ No newline at end of file diff --git a/vendor/DPP/include/dpp/stringops.h b/vendor/DPP/include/dpp/stringops.h new file mode 100644 index 00000000..46f26fd2 --- /dev/null +++ b/vendor/DPP/include/dpp/stringops.h @@ -0,0 +1,128 @@ +/************************************************************************************ + * + * D++ - A Lightweight C++ Library for Discord + * + * stringops.h taken from TriviaBot + * + * Copyright 2004 Craig Edwards + * + * Core based on Sporks, the Learning Discord Bot, Craig Edwards (c) 2019. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ + +#pragma once +#include +#include +#include +#include +#include +#include + +/** + * @brief Convert a string to lowercase using tolower() + * + * @tparam T type of string + * @param s String to lowercase + * @return std::basic_string lowercased string + */ +template std::basic_string lowercase(const std::basic_string& s) +{ + std::basic_string s2 = s; + std::transform(s2.begin(), s2.end(), s2.begin(), tolower); + return std::move(s2); +} + +/** + * @brief Convert a string to uppercase using toupper() + * + * @tparam T type of string + * @param s String to uppercase + * @return std::basic_string uppercased string + */ +template std::basic_string uppercase(const std::basic_string& s) +{ + std::basic_string s2 = s; + std::transform(s2.begin(), s2.end(), s2.begin(), toupper); + return std::move(s2); +} + +/** + * @brief trim from end of string (right) + * + * @param s String to trim + * @return std::string trimmed string + */ +inline std::string rtrim(std::string s) +{ + s.erase(s.find_last_not_of(" \t\n\r\f\v") + 1); + return s; +} + +/** + * @brief trim from beginning of string (left) + * + * @param s string to trim + * @return std::string trimmed string + */ +inline std::string ltrim(std::string s) +{ + s.erase(0, s.find_first_not_of(" \t\n\r\f\v")); + return s; +} + +/** + * @brief Trim from both ends of string (right then left) + * + * @param s string to trim + * @return std::string trimmed string + */ +inline std::string trim(std::string s) +{ + return ltrim(rtrim(s)); +} + +/** + * @brief Add commas to a string (or dots) based on current locale server-side + * + * @tparam T type of numeric value + * @param value Value + * @return std::string number with commas added + */ +template std::string Comma(T value) +{ + std::stringstream ss; + ss.imbue(std::locale("")); + ss << std::fixed << value; + return ss.str(); +} + +/** + * @brief Convert any value from a string to another type using stringstream. + * The optional second parameter indicates the format of the input string, + * e.g. std::dec for decimal, std::hex for hex, std::oct for octal. + * + * @tparam T Type to convert to + * @param s String to convert from + * @param f Numeric base, e.g. `std::dec` or `std::hex` + * @return T Returned numeric value + */ +template T from_string(const std::string &s, std::ios_base & (*f)(std::ios_base&)) +{ + T t; + std::istringstream iss(s); + iss >> f, iss >> t; + return t; +} + diff --git a/vendor/DPP/include/dpp/user.h b/vendor/DPP/include/dpp/user.h new file mode 100644 index 00000000..ba361e25 --- /dev/null +++ b/vendor/DPP/include/dpp/user.h @@ -0,0 +1,249 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include + +namespace dpp { + +/** + * @brief Various bitmask flags used to represent information about a dpp::user + */ +enum user_flags { + /// User is a bot + u_bot = 0b00000000000000000000001, + /// User is a system user (Clyde!) + u_system = 0b00000000000000000000010, + /// User has multi-factor authentication enabled + u_mfa_enabled = 0b00000000000000000000100, + /// User is verified (verified email address) + u_verified = 0b00000000000000000001000, + /// User has full nitro + u_nitro_full = 0b00000000000000000010000, + /// User has nitro classic + u_nitro_classic = 0b00000000000000000100000, + /// User is discord staff + u_discord_employee = 0b00000000000000001000000, + /// User owns a partnered server + u_partnered_owner = 0b00000000000000010000000, + /// User is a member of hypesquad events + u_hypesquad_events = 0b00000000000000100000000, + /// User has BugHunter level 1 + u_bughunter_1 = 0b00000000000001000000000, + /// User is a member of House Bravery + u_house_bravery = 0b00000000000010000000000, + /// User is a member of House Brilliance + u_house_brilliance = 0b00000000000100000000000, + /// User is a member of House Balance + u_house_balanace = 0b00000000001000000000000, + /// User is an early supporter + u_early_supporter = 0b00000000010000000000000, + /// User is a team user + u_team_user = 0b00000000100000000000000, + /// User is has Bug Hunter level 2 + u_bughunter_2 = 0b00000001000000000000000, + /// User is a verified bot + u_verified_bot = 0b00000010000000000000000, + /// User has the Early Verified Bot Developer badge + u_verified_bot_dev = 0b00000100000000000000000, + /// User's icon is animated + u_animated_icon = 0b00001000000000000000000, + /// User is a certified moderator + u_certified_moderator = 0b00010000000000000000000 +}; + +/** + * @brief Represents a user on discord. May or may not be a member of a dpp::guild. + */ +class CoreExport user : public managed { +public: + /** Discord username */ + std::string username; + /** Discriminator (aka tag), 4 digits usually displayed with leading zeroes */ + uint16_t discriminator; + /** Avatar hash */ + utility::iconhash avatar; + /** Flags built from a bitmask of values in dpp::user_flags */ + uint32_t flags; + /** Reference count of how many guilds this user is in */ + uint8_t refcount; + + /** + * @brief Construct a new user object + */ + user(); + + /** + * @brief Destroy the user object + */ + virtual ~user(); + + /** Fill this record from json. + * @param j The json to fill this record from + * @return Reference to self + */ + user& fill_from_json(nlohmann::json* j); + + /** + * @brief Get the avatar url of the user object + * + * @return std::string avatar url + */ + std::string get_avatar_url() const; + + /** + * @brief User is a bot + * + * @return True if the user is a bot + */ + bool is_bot() const; + /** + * @brief User is a system user (Clyde) + * + * @return true if user is a system user + */ + bool is_system() const; + /** + * @brief User has multi-factor authentication enabled + * + * @return true if multi-factor is enabled + */ + bool is_mfa_enabled() const; + /** + * @brief Return true if user has verified account + * + * @return true if verified + */ + bool is_verified() const; + /** + * @brief Return true if user has full nitro. + * This is mutually exclusive with full nitro. + * + * @return true if user has full nitro + */ + bool has_nitro_full() const; + /** + * @brief Return true if user has nitro classic. + * This is mutually exclusive with nitro classic. + * + * @return true if user has nitro classic + */ + bool has_nitro_classic() const; + /** + * @brief Return true if user is a discord employee + * + * @return true if user is discord staff + */ + bool is_discord_employee() const; + /** + * @brief Return true if user owns a partnered server + * + * @return true if user has partnered server + */ + bool is_partnered_owner() const; + /** + * @brief Return true if user has hypesquad events + * + * @return true if has hypesquad events + */ + bool has_hypesquad_events() const; + /** + * @brief Return true if user has the bughunter level 1 badge + * + * @return true if has bughunter level 1 + */ + bool is_bughunter_1() const; + /** + * @brief Return true if user is in house bravery + * + * @return true if in house bravery + */ + bool is_house_bravery() const; + /** + * @brief Return true if user is in house brilliance + * + * @return true if in house brilliance + */ + bool is_house_brilliance() const; + /** + * @brief Return true if user is in house balance + * + * @return true if in house brilliance + */ + bool is_house_balanace() const; + /** + * @brief Return true if user is an early supporter + * + * @return true if early supporter + */ + bool is_early_supporter() const; + /** + * @brief Return true if user is a team user + * + * @return true if a team user + */ + bool is_team_user() const; + /** + * @brief Return true if user has the bughunter level 2 badge + * + * @return true if has bughunter level 2 + */ + bool is_bughunter_2() const; + /** + * @brief Return true if user has the verified bot badge + * + * @return true if verified bot + */ + bool is_verified_bot() const; + /** + * @brief Return true if user is an early verified bot developer + * + * @return true if verified bot developer + */ + bool is_verified_bot_dev() const; + /** + * @brief Return true if user is a certified moderator + * + * @return true if certified moderator + */ + bool is_certified_moderator() const; + /** + * @brief Return true if user has an animated icon + * + * @return true if icon is animated (gif) + */ + bool has_animated_icon() const; +}; + +/** + * @brief helper function to deserialize a user from json + * + * @see https://github.com/nlohmann/json#arbitrary-types-conversions + * + * @param j output json object + * @param u user to be deserialized + */ +void from_json(const nlohmann::json& j, user& u); + +/** A group of users */ +typedef std::unordered_map user_map; + +}; diff --git a/vendor/DPP/include/dpp/version.h b/vendor/DPP/include/dpp/version.h new file mode 100644 index 00000000..be31cd72 --- /dev/null +++ b/vendor/DPP/include/dpp/version.h @@ -0,0 +1,31 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once + +#if !defined(DPP_VERSION_LONG) +#define DPP_VERSION_LONG 0x00090003 +#define DPP_VERSION_SHORT 090003 +#define DPP_VERSION_TEXT "D++ 9.0.3 (05-Sep-2021)" + +#define DPP_VERSION_MAJOR ((DPP_VERSION_LONG & 0x00ff0000) >> 16) +#define DPP_VERSION_MINOR ((DPP_VERSION_LONG & 0x0000ff00) >> 8) +#define DPP_VERSION_PATCH (DPP_VERSION_LONG & 0x000000ff) +#endif diff --git a/vendor/DPP/include/dpp/voiceregion.h b/vendor/DPP/include/dpp/voiceregion.h new file mode 100644 index 00000000..8ab17818 --- /dev/null +++ b/vendor/DPP/include/dpp/voiceregion.h @@ -0,0 +1,117 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include + +namespace dpp { + +/** + * @brief Flags related to a voice region + */ +enum voiceregion_flags { + v_optimal = 0x00000001, + v_deprecated = 0x00000010, + v_custom = 0x00000100, + v_vip = 0x00001000 +}; + +/** + * @brief Represents a voice region on discord + */ +class CoreExport voiceregion { +public: + /** + * @brief Voice server ID + */ + std::string id; + + /** + * @brief Voice server name + */ + std::string name; + + /** + * @brief Flags bitmap + */ + uint8_t flags; + + /** + * @brief Construct a new voiceregion object + */ + voiceregion(); + + /** + * @brief Destroy the voiceregion object + */ + ~voiceregion(); + + /** + * @brief Fill object properties from JSON + * + * @param j JSON to fill from + * @return voiceregion& Reference to self + */ + voiceregion& fill_from_json(nlohmann::json* j); + + /** + * @brief Build a json string for this object + * + * @return std::string JSON string + */ + std::string build_json() const; + + /** + * @brief True if is the optimal voice server + * + * @return true if optimal + */ + bool is_optimal() const; + + /** + * @brief True if is a deprecated voice server + * + * @return true if deprecated + */ + bool is_deprecated() const; + + /** + * @brief True if is a custom voice server + * + * @return true if custom + */ + bool is_custom() const; + + /** + * @brief True if is a VIP voice server + * + * @return true if VIP + */ + bool is_vip() const; +}; + +/** + * @brief A group of voice regions + */ +typedef std::unordered_map voiceregion_map; + +}; diff --git a/vendor/DPP/include/dpp/voicestate.h b/vendor/DPP/include/dpp/voicestate.h new file mode 100644 index 00000000..8c461ef8 --- /dev/null +++ b/vendor/DPP/include/dpp/voicestate.h @@ -0,0 +1,105 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include + +namespace dpp { + +/** + * @brief Bit mask flags relating to voice states + */ +enum voicestate_flags { + vs_deaf = 0b00000001, //!< Deafened + vs_mute = 0b00000010, //!< Muted + vs_self_mute = 0b00000100, //!< Self Muted + vs_self_deaf = 0b00001000, //!< Self Deafened + vs_self_stream = 0b00010000, //!< Self Streaming + vs_self_video = 0b00100000, //!< Self Video + vs_supress = 0b01000000 //!< Supression +}; + +/** + * @brief Represents the voice state of a user on a guild + * These are stored in the dpp::guild object, and accessible there, + * or via dpp::channel::get_voice_members + */ +class CoreExport voicestate { +public: + class discord_client* shard; //!< Owning shard + snowflake guild_id; //!< Optional: the guild id this voice state is for + snowflake channel_id; //!< the channel id this user is connected to (may be empty) + snowflake user_id; //!< the user id this voice state is for + std::string session_id; //!< the session id for this voice state + uint8_t flags; //!< Voice state flags + + /** + * @brief Construct a new voicestate object + */ + voicestate(); + + /** + * @brief Destroy the voicestate object + */ + ~voicestate(); + + /** + * @brief Fill voicestate object from json data + * + * @param j JSON data to fill from + * @return voicestate& Reference to self + */ + voicestate& fill_from_json(nlohmann::json* j); + + /** + * @brief Build json representation of the object + * + * @return std::string JSON string + */ + std::string build_json() const; + + /// Return true if user is deafened + bool is_deaf() const; + + /// Return true if user is muted + bool is_mute() const; + + /// Return true if user muted themselves + bool is_self_mute() const; + + /// Return true if user deafened themselves + bool is_self_deaf() const; + + /// Return true if the user is streamig + bool self_stream() const; + + /// Return true if the user is in video + bool self_video() const; + + /// Return true if user is surpressed. + /// "HELP HELP I'M BEING SUPRESSED!" + bool is_supressed() const; +}; + +/** A container of voicestates */ +typedef std::unordered_map voicestate_map; + +}; diff --git a/vendor/DPP/include/dpp/webhook.h b/vendor/DPP/include/dpp/webhook.h new file mode 100644 index 00000000..d6ad5114 --- /dev/null +++ b/vendor/DPP/include/dpp/webhook.h @@ -0,0 +1,92 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include + +namespace dpp { + +/** + * @brief Defines types of webhook + */ +enum webhook_type { + w_incoming = 1, //!< Incoming webhook + w_channel_follower = 2 //!< Channel following webhook +}; + +/** + * @brief Represents a discord webhook + */ +class CoreExport webhook : public managed { +public: + uint8_t type; //!< the type of the webhook + snowflake guild_id; //!< Optional: the guild id this webhook is for + snowflake channel_id; //!< the channel id this webhook is for + snowflake user_id; //!< Optional: the user this webhook was created by (not returned when getting a webhook with its token) + std::string name; //!< the default name of the webhook (may be empty) + std::string avatar; //!< the default avatar of the webhook (may be empty) + std::string token; //!< Optional: the secure token of the webhook (returned for Incoming Webhooks) + snowflake application_id; //!< the bot/OAuth2 application that created this webhook (may be empty) + std::string* image_data; //!< base64 encoded image data if uploading a new image + + /** + * @brief Construct a new webhook object + */ + webhook(); + + /** + * @brief Destroy the webhook object + */ + ~webhook(); + + /** + * @brief Fill in object from json data + * + * @param j JSON data + * @return webhook& Reference to self + */ + webhook& fill_from_json(nlohmann::json* j); + + /** + * @brief Build JSON string from object + * + * @param with_id Include the ID of the webhook in the json + * @return std::string JSON encoded object + */ + std::string build_json(bool with_id = false) const; + + /** + * @brief Base64 encode image data and allocate it to image_data + * + * @param image_blob Binary image data + * @param type Image type + * @return webhook& Reference to self + */ + webhook& load_image(const std::string &image_blob, image_type type); +}; + +/** + * @brief A group of webhooks + */ +typedef std::unordered_map webhook_map; + +}; diff --git a/vendor/DPP/include/dpp/wsclient.h b/vendor/DPP/include/dpp/wsclient.h new file mode 100644 index 00000000..06d20f12 --- /dev/null +++ b/vendor/DPP/include/dpp/wsclient.h @@ -0,0 +1,156 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief Websocket connection status + */ +enum ws_state { + /** Sending/receiving HTTP headers prior to protocol switch */ + HTTP_HEADERS, + /** Connected, upgraded and sending/receiving frames */ + CONNECTED +}; + +/** + * @brief Low-level websocket opcodes for frames + */ +enum ws_opcode +{ + OP_CONTINUATION = 0x00, //!< Continuation + OP_TEXT = 0x01, //!< Text frame + OP_BINARY = 0x02, //!< Binary frame + OP_CLOSE = 0x08, //!< Close notification with close code + OP_PING = 0x09, //!< Low level ping + OP_PONG = 0x0a //!< Low level pong +}; + +/** + * @brief Implements a websocket client based on the SSL client + */ +class CoreExport websocket_client : public ssl_client +{ + /** Connection key used in the HTTP headers */ + std::string key; + + /** Current websocket state */ + ws_state state; + + /** Path part of URL for websocket */ + std::string path; + + /** HTTP headers received on connecting/upgrading */ + std::map HTTPHeaders; + + /** Parse headers for a websocket frame from the buffer. + * @param buffer The buffer to operate on. Will modify the string removing completed items from the head of the queue + */ + bool parseheader(std::string &buffer); + + /** Unpack a frame and pass completed frames up the stack. + * @param buffer The buffer to operate on. Gets modified to remove completed frames on the head of the buffer + * @param offset The offset to start at (reserved for future use) + * @param first True if is the first element (reserved for future use) + */ + bool unpack(std::string &buffer, uint32_t offset, bool first = true); + + /** Fill a header for outbound messages + * @param outbuf The raw frame to fill + * @param sendlength The size of the data to encapsulate + * @param ws_opcode the opcode to send in the header + */ + size_t FillHeader(unsigned char* outbuf, size_t sendlength, ws_opcode opcode); + + /** Handle ping and pong requests. + * @param ping True if this is a ping, false if it is a pong + * @param payload The ping payload, to be returned as-is for a ping + */ + void HandlePingPong(bool ping, const std::string &payload); + +protected: + + /** (Re)connect */ + virtual void Connect(); + + /** Get websocket state + * @return websocket state + */ + ws_state GetState(); + +public: + + /** Connect to a specific websocket server. + * @param hostname Hostname to connect to + * @param port Port to connect to + * @param urlpath The URL path components of the HTTP request to send + */ + websocket_client(const std::string &hostname, const std::string &port = "443", const std::string &urlpath = ""); + + /** Destructor */ + virtual ~websocket_client(); + + /** + * @brief Write to websocket. Encapsulates data in frames if the status is CONNECTED. + * + * @param data The data to send. + */ + virtual void write(const std::string &data); + + /** + * @brief Processes incoming frames from the SSL socket input buffer. + * + * @param buffer The buffer contents. Can modify this value removing the head elements when processed. + */ + virtual bool handle_buffer(std::string &buffer); + + /** + * @brief Close websocket + */ + virtual void close(); + + /** + * @brief Receives raw frame content only without headers + * + * @param buffer The buffer contents + * @return True if the frame was successfully handled. False if no valid frame is in the buffer. + */ + virtual bool HandleFrame(const std::string &buffer); + + /** + * @brief Called upon error frame. + * + * @param errorcode The error code from the websocket server + */ + virtual void Error(uint32_t errorcode); + + /** Fires every second from the underlying socket I/O loop, used for sending webscocket pings */ + virtual void one_second_timer(); +}; + +}; \ No newline at end of file diff --git a/vendor/DPP/src/dpp/auditlog.cpp b/vendor/DPP/src/dpp/auditlog.cpp new file mode 100644 index 00000000..c995d0d7 --- /dev/null +++ b/vendor/DPP/src/dpp/auditlog.cpp @@ -0,0 +1,77 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include + +namespace dpp { + +using json = nlohmann::json; + +auditlog::auditlog() +{ +} + +auditlog::~auditlog() { +} + +auditlog& auditlog::fill_from_json(nlohmann::json* j) { + for (auto & ai : (*j)["audit_log_entries"]) { + audit_entry ae; + ae.id = SnowflakeNotNull(&ai, "id"); + ae.event = (audit_type)Int8NotNull(&ai, "action_type"); + ae.user_id = SnowflakeNotNull(&ai, "user_id"); + ae.target_id = SnowflakeNotNull(&ai, "target_id"); + ae.reason = StringNotNull(&ai, "reason"); + if (j->find("changes") != j->end()) { + auto &c = ai["changes"]; + for (auto & change : c) { + audit_change ac; + ac.key = StringNotNull(&change, "key"); + if (change.find("new_value") != change.end()) { + ac.new_value = change["new_value"].dump(); + } + if (change.find("old_value") != change.end()) { + ac.old_value = change["old_value"].dump(); + } + } + } + if (j->find("options") != j->end()) { + auto &o = ai["options"]; + audit_extra opts; + opts.channel_id = SnowflakeNotNull(&o, "channel_id"); + opts.count = StringNotNull(&o, "count"); + opts.delete_member_days = StringNotNull(&o, "delete_member_days"); + opts.id = SnowflakeNotNull(&o, "id"); + opts.members_removed = StringNotNull(&o, "members_removed"); + opts.message_id = SnowflakeNotNull(&o, "message_id"); + opts.role_name = StringNotNull(&o, "role_name"); + opts.type = StringNotNull(&o, "type"); + ae.options = opts; + } + this->entries.push_back(ae); + } + return *this; +} + +}; + diff --git a/vendor/DPP/src/dpp/ban.cpp b/vendor/DPP/src/dpp/ban.cpp new file mode 100644 index 00000000..ade909db --- /dev/null +++ b/vendor/DPP/src/dpp/ban.cpp @@ -0,0 +1,52 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include + +namespace dpp { + +using json = nlohmann::json; + +ban::ban() : user_id(0) +{ +} + +ban::~ban() { +} + +ban& ban::fill_from_json(nlohmann::json* j) { + reason = StringNotNull(j, "reason"); + if (j->find("user") != j->end()) { + json & user = (*j)["user"]; + user_id = SnowflakeNotNull(&user, "id"); + } + return *this; +} + +std::string ban::build_json() const { + /* This is an unused stub, because sending a ban is simple as a user id and a reason */ + return "{}"; +} + +}; + diff --git a/vendor/DPP/src/dpp/cache.cpp b/vendor/DPP/src/dpp/cache.cpp new file mode 100644 index 00000000..1afc6a92 --- /dev/null +++ b/vendor/DPP/src/dpp/cache.cpp @@ -0,0 +1,161 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include + +namespace dpp { + +std::unordered_map deletion_queue; +std::mutex deletion_mutex; + +#define cache_helper(type, cache_name, setter, getter, counter) \ +cache* cache_name = nullptr; \ +type * setter (snowflake id) { \ + return cache_name ? ( type * ) cache_name ->find(id) : nullptr; \ +} \ +cache* getter () { \ + if (! cache_name ) { \ + cache_name = new cache(); \ + } \ + return cache_name ; \ +} \ +uint64_t counter () { \ + return ( cache_name ? cache_name ->count() : 0 ); \ +} + + +/* Because other threads and systems may run for a short while after an event is received, we don't immediately + * delete pointers when objects are replaced. We put them into a queue, and periodically delete pointers in the + * queue. This also rehashes unordered_maps to ensure they free their memory. + */ +void garbage_collection() { + time_t now = time(NULL); + bool repeat = false; + { + std::lock_guard delete_lock(deletion_mutex); + do { + repeat = false; + for (auto g = deletion_queue.begin(); g != deletion_queue.end(); ++g) { + if (now > g->second + 60) { + delete g->first; + deletion_queue.erase(g); + repeat = true; + break; + } + } + } while (repeat); + if (deletion_queue.size() == 0) { + deletion_queue = {}; + } + } + dpp::get_user_cache()->rehash(); + dpp::get_channel_cache()->rehash(); + dpp::get_guild_cache()->rehash(); + dpp::get_role_cache()->rehash(); + dpp::get_emoji_cache()->rehash(); +} + +cache::cache() { + cache_map = new cache_container(); +} + +cache::~cache() { + delete cache_map; +} + +uint64_t cache::count() { + std::lock_guard lock(this->cache_mutex); + return cache_map->size(); +} + +std::mutex& cache::get_mutex() { + return this->cache_mutex; +} + +cache_container& cache::get_container() { + return *(this->cache_map); +} + +void cache::store(managed* object) { + if (!object) { + return; + } + std::lock_guard lock(this->cache_mutex); + auto existing = cache_map->find(object->id); + if (existing == cache_map->end()) { + (*cache_map)[object->id] = object; + } else if (object != existing->second) { + /* Flag old pointer for deletion and replace */ + std::lock_guard delete_lock(deletion_mutex); + deletion_queue[existing->second] = time(NULL); + (*cache_map)[object->id] = object; + } +} + +size_t cache::bytes() { + std::lock_guard lock(cache_mutex); + return sizeof(this) + (cache_map->bucket_count() * sizeof(size_t)); +} + +void cache::rehash() { + std::lock_guard lock(cache_mutex); + cache_container* n = new cache_container(); + n->reserve(cache_map->size()); + for (auto t = cache_map->begin(); t != cache_map->end(); ++t) { + n->insert(*t); + } + delete cache_map; + cache_map = n; +} + +void cache::remove(managed* object) { + if (!object) { + return; + } + std::lock_guard lock(cache_mutex); + std::lock_guard delete_lock(deletion_mutex); + auto existing = cache_map->find(object->id); + if (existing != cache_map->end()) { + cache_map->erase(existing); + deletion_queue[object] = time(NULL); + } +} + +managed* cache::find(snowflake id) { + std::lock_guard lock(cache_mutex); + auto r = cache_map->find(id); + if (r != cache_map->end()) { + return r->second; + } + return nullptr; +} + +cache_helper(user, user_cache, find_user, get_user_cache, get_user_count); +cache_helper(channel, channel_cache, find_channel, get_channel_cache, get_channel_count); +cache_helper(role, role_cache, find_role, get_role_cache, get_role_count); +cache_helper(guild, guild_cache, find_guild, get_guild_cache, get_guild_count); +cache_helper(emoji, emoji_cache, find_emoji, get_emoji_cache, get_emoji_count); + +}; diff --git a/vendor/DPP/src/dpp/channel.cpp b/vendor/DPP/src/dpp/channel.cpp new file mode 100644 index 00000000..d81e98b6 --- /dev/null +++ b/vendor/DPP/src/dpp/channel.cpp @@ -0,0 +1,245 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { + +thread_member& thread_member::fill_from_json(nlohmann::json* j) { + SetSnowflakeNotNull(j, "id", this->thread_id); + SetSnowflakeNotNull(j, "user_id", this->user_id); + SetTimestampNotNull(j, "join_timestamp", this->joined); + SetInt32NotNull(j, "flags", this->flags); + return *this; +} + +channel::channel() : + managed(), + flags(0), + guild_id(0), + position(0), + last_message_id(0), + user_limit(0), + rate_limit_per_user(0), + owner_id(0), + parent_id(0), + last_pin_timestamp(0), + message_count(0), + member_count(0) +{ +} + +channel::~channel() +{ +} + +bool channel::is_nsfw() const { + return flags & dpp::c_nsfw; +} + +bool channel::is_text_channel() const { + return flags & dpp::c_text; +} + +bool channel::is_dm() const { + return flags & dpp::c_dm; +} + +bool channel::is_voice_channel() const { + return flags & dpp::c_voice; +} + +bool channel::is_group_dm() const { + return (flags & (dpp::c_dm | dpp::c_group)) == (dpp::c_dm | dpp::c_group); +} + +bool channel::is_category() const { + return flags & dpp::c_category; +} + +bool channel::is_stage_channel() const { + return (flags & dpp::c_stage) == dpp::c_stage; +} + +bool channel::is_news_channel() const { + /* Important: Stage/News overlap to pack more values in a byte */ + return !is_stage_channel() && (flags & dpp::c_news); +} + +bool channel::is_store_channel() const { + /* Important: Stage/Store overlap to pack more values in a byte */ + return !is_stage_channel() && (flags & dpp::c_store); +} + +channel& channel::fill_from_json(json* j) { + this->id = SnowflakeNotNull(j, "id"); + SetSnowflakeNotNull(j, "guild_id", this->guild_id); + SetInt16NotNull(j, "position", this->position); + SetStringNotNull(j, "name", this->name); + SetStringNotNull(j, "topic", this->topic); + SetSnowflakeNotNull(j, "last_message_id", this->last_message_id); + SetInt8NotNull(j, "user_limit", this->user_limit); + SetInt16NotNull(j, "rate_limit_per_user", this->rate_limit_per_user); + SetSnowflakeNotNull(j, "owner_id", this->owner_id); + SetSnowflakeNotNull(j, "parent_id", this->parent_id); + //this->last_pin_timestamp + uint8_t type = Int8NotNull(j, "type"); + this->flags |= BoolNotNull(j, "nsfw") ? dpp::c_nsfw : 0; + this->flags |= (type == GUILD_TEXT) ? dpp::c_text : 0; + this->flags |= (type == GUILD_VOICE) ? dpp::c_voice : 0; + this->flags |= (type == DM) ? dpp::c_dm : 0; + this->flags |= (type == GROUP_DM) ? (dpp::c_group | dpp::c_dm) : 0; + this->flags |= (type == GUILD_CATEGORY) ? dpp::c_category : 0; + this->flags |= (type == GUILD_NEWS) ? dpp::c_news : 0; + this->flags |= (type == GUILD_STORE) ? dpp::c_store : 0; + this->flags |= (type == GUILD_STAGE) ? dpp::c_stage : 0; + this->flags |= (type == GUILD_NEWS_THREAD) ? dpp::c_news_thread : 0; + this->flags |= (type == GUILD_PUBLIC_THREAD) ? dpp::c_public_thread : 0; + this->flags |= (type == GUILD_PRIVATE_THREAD) ? dpp::c_private_thread : 0; + + if (j->find("recipients") != j->end()) { + recipients = {}; + for (auto & r : (*j)["recipients"]) { + recipients.push_back(from_string(r["id"].get(), std::dec)); + } + } + + if (j->find("permission_overwrites") != j->end()) { + permission_overwrites = {}; + for (auto & overwrite : (*j)["permission_overwrites"]) { + permission_overwrite po; + po.id = SnowflakeNotNull(&overwrite, "id"); + po.allow = SnowflakeNotNull(&overwrite, "allow"); + po.deny = SnowflakeNotNull(&overwrite, "deny"); + po.type = Int8NotNull(&overwrite, "type"); + permission_overwrites.push_back(po); + } + } + + if (type == GUILD_NEWS_THREAD || type == GUILD_PUBLIC_THREAD || type == GUILD_PRIVATE_THREAD) { + SetInt8NotNull(j, "message_count", this->message_count); + SetInt8NotNull(j, "memeber_count", this->member_count); + dpp::thread_metadata metadata; + auto json_metadata = (*j)["thread_metadata"]; + metadata.archived = BoolNotNull(&json_metadata, "archived"); + metadata.archive_timestamp = TimestampNotNull(&json_metadata, "archive_timestamp"); + metadata.auto_archive_duration = Int16NotNull(&json_metadata, "auto_archive_duration"); + metadata.locked = BoolNotNull(&json_metadata, "locked"); + + } + + return *this; +} + +std::string channel::build_json(bool with_id) const { + json j; + if (with_id) { + j["id"] = std::to_string(id); + } + j["guild_id"] = std::to_string(guild_id); + j["position"] = position; + j["name"] = name; + j["topic"] = topic; + if (is_voice_channel()) { + j["user_limit"] = user_limit; + j["rate_limit_per_user"] = rate_limit_per_user; + } + if (!is_dm()) { + if (parent_id) { + j["parent_id"] = parent_id; + } + if (is_text_channel()) { + j["type"] = GUILD_TEXT; + } else if (is_voice_channel()) { + j["type"] = GUILD_VOICE; + } else if (is_category()) { + j["type"] = GUILD_CATEGORY; + } else if (is_stage_channel()) { + /* Order is important, as GUILD_STAGE overlaps NEWS and STORE */ + j["type"] = GUILD_STAGE; + } else if (is_news_channel()) { + j["type"] = GUILD_NEWS; + } else if (is_store_channel()) { + j["type"] = GUILD_STORE; + } + j["nsfw"] = is_nsfw(); + } else { + if (is_group_dm()) { + j["type"] = GROUP_DM; + } else { + j["type"] = DM; + } + } + + return j.dump(); +} + +uint64_t channel::get_user_permissions(const user* member) const +{ + if (member == nullptr) + return 0; + + guild* g = dpp::find_guild(guild_id); + if (g == nullptr) + return 0; + + return g->permission_overwrites(g->base_permissions(member), member, this); +} + +std::map channel::get_members() { + std::map rv; + guild* g = dpp::find_guild(guild_id); + if (g) { + for (auto m = g->members.begin(); m != g->members.end(); ++m) { + user* u = dpp::find_user(m->second.user_id); + if (u) { + if (get_user_permissions(u) & p_view_channel) { + rv[m->second.user_id] = &(m->second); + } + } + } + } + return rv; +} + +std::map channel::get_voice_members() { + std::map rv; + guild* g = dpp::find_guild(guild_id); + if (g) { + for (auto & m : g->voice_members) { + if (m.second.channel_id == this->id) { + rv[m.second.user_id] = m.second; + } + } + } + return rv; +} + + + +}; diff --git a/vendor/DPP/src/dpp/cluster.cpp b/vendor/DPP/src/dpp/cluster.cpp new file mode 100644 index 00000000..ce3efcce --- /dev/null +++ b/vendor/DPP/src/dpp/cluster.cpp @@ -0,0 +1,1943 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace dpp { + +cluster::cluster(const std::string &_token, uint32_t _intents, uint32_t _shards, uint32_t _cluster_id, uint32_t _maxclusters, bool comp, cache_policy_t policy) + : token(_token), intents(_intents), numshards(_shards), cluster_id(_cluster_id), + maxclusters(_maxclusters), last_identify(time(NULL) - 5), compressed(comp), cache_policy(policy) +{ + rest = new request_queue(this); +#ifdef _WIN32 + // Set up winsock. + WSADATA wsadata; + if (WSAStartup(MAKEWORD(2, 2), &wsadata)) { + throw dpp::exception("WSAStartup failure"); + } +#endif +} + +cluster::~cluster() +{ + delete rest; +#ifdef _WIN32 + WSACleanup(); +#endif +} + +confirmation_callback_t::confirmation_callback_t(const std::string &_type, const confirmable_t& _value, const http_request_completion_t& _http) + : type(_type), value(_value), http_info(_http) +{ + if (type == "confirmation") { + confirmation newvalue = std::get(_value); + newvalue.success = (http_info.status < 400); + value = newvalue; + } +} + +bool confirmation_callback_t::is_error() const { + if (http_info.status >= 400) { + /* Invalid JSON or 4xx/5xx response */ + return true; + } + try { + json j = json::parse(this->http_info.body); + if (j.find("code") != j.end() && j.find("errors") != j.end() && j.find("message") != j.end()) { + if (j["code"].is_number_unsigned() && j["errors"].is_object() && j["message"].is_string()) { + return true; + } else { + return false; + } + } + return false; + } + catch (const std::exception &e) { + /* JSON parse error indicates the content is not JSON. + * This means that its an empty body e.g. 204 response, and not an actual error. + */ + return false; + } +} + +error_info confirmation_callback_t::get_error() const { + if (is_error()) { + json j = json::parse(this->http_info.body); + error_info e; + + SetInt32NotNull(&j, "code", e.code); + SetStringNotNull(&j, "message", e.message); + json& errors = j["errors"]; + for (auto obj = errors.begin(); obj != errors.end(); ++obj) { + + if (obj->find("0") != obj->end()) { + /* An array of error messages */ + for (auto index = obj->begin(); index != obj->end(); ++index) { + for (auto fields = index->begin(); fields != index->end(); ++fields) { + for (auto errordetails = (*fields)["_errors"].begin(); errordetails != (*fields)["_errors"].end(); ++errordetails) { + error_detail detail; + detail.code = (*errordetails)["code"].get(); + detail.reason = (*errordetails)["message"].get(); + detail.field = fields.key(); + detail.object = obj.key(); + e.errors.push_back(detail); + } + } + } + + } else if (obj->find("_errors") != obj->end()) { + /* An object of error messages */ + for (auto errordetails = (*obj)["_errors"].begin(); errordetails != (*obj)["_errors"].end(); ++errordetails) { + error_detail detail; + detail.code = (*errordetails)["code"].get(); + detail.reason = (*errordetails)["message"].get(); + detail.object = ""; + detail.field = obj.key(); + e.errors.push_back(detail); + } + } + } + + return e; + } + return error_info(); +} + + +void cluster::auto_shard(const confirmation_callback_t &shardinfo) { + gateway g = std::get(shardinfo.value); + numshards = g.shards; + log(ll_info, fmt::format("Auto Shard: Bot requires {} shard{}", g.shards, g.shards > 1 ? "s" : "")); + if (g.shards) { + if (g.session_start_remaining < g.shards) { + log(ll_critical, fmt::format("Auto Shard: Discord indicates you cannot start any more sessions! Cluster startup aborted. Try again later.")); + } else { + log(ll_debug, fmt::format("Auto Shard: {} of {} session starts remaining", g.session_start_remaining, g.session_start_total)); + cluster::start(true); + } + } else { + log(ll_critical, "Auto Shard: Could not auto detect shard count! Cluster startup aborted."); + } +} + +void cluster::log(dpp::loglevel severity, const std::string &msg) const { + if (dispatch.log) { + /* Pass to user if theyve hooked the event */ + dpp::log_t logmsg(nullptr, msg); + logmsg.severity = severity; + logmsg.message = msg; + dispatch.log(logmsg); + } +} + +dpp::utility::uptime cluster::uptime() +{ + return dpp::utility::uptime(time(NULL) - start_time); +} + +void cluster::start(bool return_after) { + /* Start up all shards */ + if (numshards == 0) { + get_gateway_bot(std::bind(&cluster::auto_shard, this, std::placeholders::_1)); + if (!return_after) { + while (true) { + std::this_thread::sleep_for(std::chrono::seconds(86400)); + } + } + } else { + start_time = time(NULL); + + log(ll_debug, fmt::format("Starting with {} shards...", numshards)); + + for (uint32_t s = 0; s < numshards; ++s) { + /* Filter out shards that arent part of the current cluster, if the bot is clustered */ + if (s % maxclusters == cluster_id) { + /* Each discord_client spawns its own thread in its Run() */ + try { + this->shards[s] = new discord_client(this, s, numshards, token, intents, compressed); + this->shards[s]->Run(); + } + catch (const std::exception &e) { + log(dpp::ll_critical, fmt::format("Could not start shard {}: {}", s, e.what())); + } + /* Stagger the shard startups */ + std::this_thread::sleep_for(std::chrono::seconds(5)); + } + } + + /* Get all active DM channels and map them to user id -> dm id */ + this->current_user_get_dms([this](const dpp::confirmation_callback_t& completion) { + dpp::channel_map dmchannels = std::get(completion.value); + for (auto & c : dmchannels) { + for (auto & u : c.second.recipients) { + this->set_dm_channel(u, c.second.id); + } + } + }); + + log(ll_debug, "Shards started."); + + if (!return_after) { + while (true) { + std::this_thread::sleep_for(std::chrono::seconds(86400)); + } + } + } +} + +snowflake cluster::get_dm_channel(snowflake user_id) { + std::lock_guard lock(dm_list_lock); + auto i = dm_channels.find(user_id); + if (i != dm_channels.end()) { + return i->second; + } else { + return 0; + } +} + +void cluster::set_dm_channel(snowflake user_id, snowflake channel_id) { + std::lock_guard lock(dm_list_lock); + dm_channels[user_id] = channel_id; +} + +void cluster::post_rest(const std::string &endpoint, const std::string &major_parameters, const std::string ¶meters, http_method method, const std::string &postdata, json_encode_t callback, const std::string &filename, const std::string &filecontent) { + /* NOTE: This is not a memory leak! The request_queue will free the http_request once it reaches the end of its lifecycle */ + rest->post_request(new http_request(endpoint + "/" + major_parameters, parameters, [endpoint, callback, this](const http_request_completion_t& rv) { + json j; + if (rv.error == h_success && !rv.body.empty()) { + try { + j = json::parse(rv.body); + } + catch (const std::exception &e) { + /* TODO: Do something clever to handle malformed JSON */ + log(ll_error, fmt::format("post_rest() to {}: {}", endpoint, e.what())); + return; + } + } + if (callback) { + callback(j, rv); + } + }, postdata, method, filename, filecontent)); +} + +gateway::gateway(nlohmann::json* j) { + url = StringNotNull(j, "url"); + shards = Int32NotNull(j, "shards"); + session_start_total = Int32NotNull(&((*j)["session_start_limit"]), "total"); + session_start_remaining = Int32NotNull(&((*j)["session_start_limit"]), "remaining"); + session_start_reset_after = Int32NotNull(&((*j)["session_start_limit"]), "reset_after"); + session_start_max_concurrency = Int32NotNull(&((*j)["session_start_limit"]), "max_concurrency"); +} + +void cluster::set_presence(const dpp::presence &p) { + std::string string_presence = p.build_json(); + for (auto& s : shards) { + if (s.second->is_connected()) { + s.second->QueueMessage(string_presence); + } + } +} + +discord_client* cluster::get_shard(uint32_t id) { + auto i = shards.find(id); + if (i != shards.end()) { + return i->second; + } else { + return nullptr; + } +} + +const shard_list& cluster::get_shards() { + return shards; +} + +void cluster::get_gateway_bot(command_completion_event_t callback) { + this->post_rest(API_PATH "/gateway", "bot", "", m_get, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("gateway", gateway(&j), http)); + } + }); +} + +void cluster::direct_message_create(snowflake user_id, const message &m, command_completion_event_t callback) { + /* Find out if a DM channel already exists */ + message msg = m; + snowflake dm_channel_id = this->get_dm_channel(user_id); + if (!dm_channel_id) { + this->create_dm_channel(user_id, [user_id, this, msg, callback](const dpp::confirmation_callback_t& completion) { + /* NOTE: We are making copies in here for a REASON. Don't try and optimise out these + * copies as if we use references, by the time the the thread completes for the callback + * the reference is invalid and we get a crash or heap corruption! + */ + message m2 = msg; + dpp::channel c = std::get(completion.value); + m2.channel_id = c.id; + this->set_dm_channel(user_id, c.id); + message_create(m2, callback); + }); + } else { + msg.channel_id = dm_channel_id; + message_create(msg, callback); + } +} + +void cluster::interaction_response_create(snowflake interaction_id, const std::string &token, const interaction_response &r, command_completion_event_t callback) { + this->post_rest(API_PATH "/interactions", std::to_string(interaction_id), url_encode(token) + "/callback", m_post, r.build_json(), [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("confirmation", confirmation(), http)); + } + }); +} + +void cluster::interaction_response_edit(const std::string &token, const message &m, command_completion_event_t callback) { + this->post_rest(API_PATH "/webhooks", std::to_string(me.id), url_encode(token) + "/messages/@original", m_patch, m.build_json(), [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("confirmation", confirmation(), http)); + } + }); +} + + +void cluster::global_command_create(slashcommand &s, command_completion_event_t callback) { + this->post_rest(API_PATH "/applications", std::to_string(me.id), "commands", m_post, s.build_json(false), [s, callback] (json &j, const http_request_completion_t& http) mutable { + if (j.contains("id")) { + s.id = SnowflakeNotNull(&j, "id"); + } + + if (callback) { + callback(confirmation_callback_t("slashcommand", slashcommand().fill_from_json(&j), http)); + } + }); +} + +void cluster::guild_command_create(slashcommand &s, snowflake guild_id, command_completion_event_t callback) { + this->post_rest(API_PATH "/applications", std::to_string(me.id), "guilds/" + std::to_string(guild_id) + "/commands", m_post, s.build_json(false), [s, this, guild_id, callback] (json &j, const http_request_completion_t& http) mutable { + if (j.contains("id")) { + s.id = SnowflakeNotNull(&j, "id"); + } + + if (callback) { + callback(confirmation_callback_t("slashcommand", slashcommand().fill_from_json(&j), http)); + } + + if (http.status < 300 && s.permissions.size()) { + guild_command_edit_permissions(s, guild_id); + } + }); +} + +void cluster::guild_bulk_command_create(const std::vector &commands, snowflake guild_id, command_completion_event_t callback) { + json j = json::array(); + for (auto & s : commands) { + j.push_back(json::parse(s.build_json(false))); + } + this->post_rest(API_PATH "/applications", std::to_string(me.id), "guilds/" + std::to_string(guild_id) + "/commands", m_put, j.dump(), [this, callback] (json &j, const http_request_completion_t& http) mutable { + slashcommand_map slashcommands; + for (auto & curr_slashcommand : j) { + slashcommands[SnowflakeNotNull(&curr_slashcommand, "id")] = slashcommand().fill_from_json(&curr_slashcommand); + } + if (callback) { + callback(confirmation_callback_t("slashcommand_map", slashcommands, http)); + } + }); +} + +void cluster::global_bulk_command_create(const std::vector &commands, command_completion_event_t callback) { + json j = json::array(); + for (auto & s : commands) { + j.push_back(json::parse(s.build_json(false))); + } + this->post_rest(API_PATH "/applications", std::to_string(me.id), "commands", m_put, j.dump(), [this, callback] (json &j, const http_request_completion_t& http) mutable { + slashcommand_map slashcommands; + for (auto & curr_slashcommand : j) { + slashcommands[SnowflakeNotNull(&curr_slashcommand, "id")] = slashcommand().fill_from_json(&curr_slashcommand); + } + if (callback) { + callback(confirmation_callback_t("slashcommand_map", slashcommands, http)); + } + }); +} + +void cluster::global_command_edit(const slashcommand &s, command_completion_event_t callback) { + this->post_rest(API_PATH "/applications", std::to_string(me.id), "commands/" + std::to_string(s.id), m_patch, s.build_json(true), [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("confirmation", confirmation(), http)); + } + }); +} + +void cluster::guild_command_edit(const slashcommand &s, snowflake guild_id, command_completion_event_t callback) { + this->post_rest(API_PATH "/applications", std::to_string(me.id), "guilds/" + std::to_string(guild_id) + "/commands/" + std::to_string(s.id), m_patch, s.build_json(true), [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("confirmation", confirmation(), http)); + } + }); +} + +void cluster::guild_command_edit_permissions(const slashcommand &s, snowflake guild_id, command_completion_event_t callback) { + json j; + + if(s.permissions.size()) { + j["permissions"] = json(); + + for(const auto& perm : s.permissions) { + json jperm = perm; + j["permissions"].push_back(jperm); + } + } + + this->post_rest(API_PATH "/applications", std::to_string(me.id), "guilds/" + std::to_string(guild_id) + "/commands/" + std::to_string(s.id) + "/permissions", m_put, j.dump(), [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("confirmation", confirmation(), http)); + } + }); +} + +void cluster::global_command_delete(snowflake id, command_completion_event_t callback) { + this->post_rest(API_PATH "/applications", std::to_string(me.id), "commands/" + std::to_string(id), m_delete, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("confirmation", confirmation(), http)); + } + }); +} + +void cluster::guild_command_delete(snowflake id, snowflake guild_id, command_completion_event_t callback) { + this->post_rest(API_PATH "/applications", std::to_string(me.id), "guilds/" + std::to_string(guild_id) + "/commands/" + std::to_string(id), m_delete, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("confirmation", confirmation(), http)); + } + }); +} + +void cluster::message_create(const message &m, command_completion_event_t callback) { + this->post_rest(API_PATH "/channels", std::to_string(m.channel_id), "messages", m_post, m.build_json(), [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("message", message().fill_from_json(&j), http)); + } + }, m.filename, m.filecontent); +} + +void cluster::message_edit(const message &m, command_completion_event_t callback) { + this->post_rest(API_PATH "/channels", std::to_string(m.channel_id), "messages/" + std::to_string(m.id), m_patch, m.build_json(true), [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("message", message().fill_from_json(&j), http)); + } + }); +} + +void cluster::guild_sticker_create(sticker &s, command_completion_event_t callback) { + this->post_rest(API_PATH "/guilds", std::to_string(s.guild_id), "stickers", m_post, s.build_json(false), [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("sticker", sticker().fill_from_json(&j), http)); + } + }, s.filename, s.filecontent); +} + +void cluster::guild_sticker_modify(sticker &s, command_completion_event_t callback) { + this->post_rest(API_PATH "/guilds", std::to_string(s.guild_id), "stickers/" + std::to_string(s.id), m_patch, s.build_json(true), [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("sticker", sticker().fill_from_json(&j), http)); + } + }); +} + +void cluster::guild_sticker_delete(snowflake sticker_id, snowflake guild_id, command_completion_event_t callback) { + this->post_rest(API_PATH "/guilds", std::to_string(guild_id), "stickers/" + std::to_string(sticker_id), m_delete, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("confirmation", confirmation(), http)); + } + }); +} + +void cluster::nitro_sticker_get(snowflake id, command_completion_event_t callback) { + this->post_rest(API_PATH "/stickers", std::to_string(id), "", m_get, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("sticker", sticker().fill_from_json(&j), http)); + } + }); +} + +void cluster::guild_sticker_get(snowflake id, snowflake guild_id, command_completion_event_t callback) { + this->post_rest(API_PATH "/guilds", std::to_string(guild_id), "stickers/" + std::to_string(id), m_get, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("sticker", sticker().fill_from_json(&j), http)); + } + }); +} + +void cluster::guild_stickers_get(snowflake guild_id, command_completion_event_t callback) { + this->post_rest(API_PATH "/guilds", std::to_string(guild_id), "stickers", m_get, "", [callback](json &j, const http_request_completion_t& http) { + sticker_map stickers; + for (auto & curr_sticker : j) { + stickers[SnowflakeNotNull(&curr_sticker, "id")] = sticker().fill_from_json(&curr_sticker); + } + if (callback) { + callback(confirmation_callback_t("sticker_map", stickers, http)); + } + }); +} + +void cluster::sticker_packs_get(command_completion_event_t callback) { + this->post_rest(API_PATH "/sticker-packs", "", "", m_get, "", [callback](json &j, const http_request_completion_t& http) { + sticker_pack_map stickerpacks; + for (auto & curr_stickerpack : j) { + stickerpacks[SnowflakeNotNull(&curr_stickerpack, "id")] = sticker_pack().fill_from_json(&curr_stickerpack); + } + if (callback) { + callback(confirmation_callback_t("sticker_pack_map", stickerpacks, http)); + } + }); +} + + +void cluster::message_crosspost(snowflake message_id, snowflake channel_id, command_completion_event_t callback) { + this->post_rest(API_PATH "/channels", std::to_string(channel_id), "messages/" + std::to_string(message_id) + "/crosspost", m_post, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("message", message().fill_from_json(&j), http)); + } + }); +} + +void cluster::message_add_reaction(const struct message &m, const std::string &reaction, command_completion_event_t callback) { + this->post_rest(API_PATH "/channels", std::to_string(m.channel_id), "messages/" + std::to_string(m.id) + "/reactions/" + dpp::url_encode(reaction) + "/@me", m_put, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("confirmation", confirmation(), http)); + } + }); +} + +void cluster::message_delete_own_reaction(const struct message &m, const std::string &reaction, command_completion_event_t callback) { + this->post_rest(API_PATH "/channels", std::to_string(m.channel_id), "messages/" + std::to_string(m.id) + "/reactions/" + dpp::url_encode(reaction) + "/@me", m_delete, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("confirmation", confirmation(), http)); + } + }); +} + +void cluster::message_delete_all_reactions(const struct message &m, command_completion_event_t callback) { + this->post_rest(API_PATH "/channels", std::to_string(m.channel_id), "messages/" + std::to_string(m.id) + "/reactions", m_delete, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("confirmation", confirmation(), http)); + } + }); +} + +void cluster::message_delete_reaction_emoji(const struct message &m, const std::string &reaction, command_completion_event_t callback) { + this->post_rest(API_PATH "/channels", std::to_string(m.channel_id), "messages/" + std::to_string(m.id) + "/reactions/" + dpp::url_encode(reaction), m_delete, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("confirmation", confirmation(), http)); + } + }); +} + + +void cluster::message_delete_reaction(const struct message &m, snowflake user_id, const std::string &reaction, command_completion_event_t callback) { + this->post_rest(API_PATH "/channels", std::to_string(m.channel_id), "messages/" + std::to_string(m.id) + "/reactions/" + dpp::url_encode(reaction) + "/" + std::to_string(user_id), m_delete, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("confirmation", confirmation(), http)); + } + }); +} + +void cluster::message_get_reactions(const struct message &m, const std::string &reaction, snowflake before, snowflake after, snowflake limit, command_completion_event_t callback) { + std::string parameters; + if (before) { + parameters.append("&before=" + std::to_string(before)); + } + if (after) { + parameters.append("&after=" + std::to_string(after)); + } + if (limit) { + parameters.append("&limit=" + std::to_string(limit)); + } + if (!parameters.empty()) { + parameters[0] = '?'; + } + this->post_rest(API_PATH "/channels", std::to_string(m.channel_id), "messages/" + std::to_string(m.id) + "/reactions/" + dpp::url_encode(reaction) + parameters, m_get, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + user_map users; + for (auto & curr_user : j) { + users[SnowflakeNotNull(&curr_user, "id")] = user().fill_from_json(&curr_user); + } + callback(confirmation_callback_t("user_map", users, http)); + } + }); +} + +void cluster::message_add_reaction(snowflake message_id, snowflake channel_id, const std::string &reaction, command_completion_event_t callback) { + message m(channel_id, ""); + m.id = message_id; + message_add_reaction(m, reaction, callback); +} + +void cluster::message_delete_own_reaction(snowflake message_id, snowflake channel_id, const std::string &reaction, command_completion_event_t callback) { + message m(channel_id, ""); + m.id = message_id; + message_delete_own_reaction(m, reaction, callback); +} + +void cluster::message_delete_reaction(snowflake message_id, snowflake channel_id, snowflake user_id, const std::string &reaction, command_completion_event_t callback) { + message m(channel_id, ""); + m.id = message_id; + message_delete_reaction(m, user_id, reaction, callback); +} + +void cluster::message_get_reactions(snowflake message_id, snowflake channel_id, const std::string &reaction, snowflake before, snowflake after, snowflake limit, command_completion_event_t callback) { + message m(channel_id, ""); + m.id = message_id; + message_get_reactions(m, reaction, before, after, limit, callback); +} + +void cluster::message_delete_all_reactions(snowflake message_id, snowflake channel_id, command_completion_event_t callback) { + message m(channel_id, ""); + m.id = message_id; + message_delete_all_reactions(m, callback); +} + +void cluster::message_delete_reaction_emoji(snowflake message_id, snowflake channel_id, const std::string &reaction, command_completion_event_t callback) { + message m(channel_id, ""); + m.id = message_id; + message_delete_reaction_emoji(m, reaction, callback); +} + +void cluster::message_get(snowflake message_id, snowflake channel_id, command_completion_event_t callback) { + this->post_rest(API_PATH "/channels", std::to_string(channel_id), "messages/" + std::to_string(message_id), m_get, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("message", message().fill_from_json(&j), http)); + } + }); +} + +void cluster::message_delete(snowflake message_id, snowflake channel_id, command_completion_event_t callback) { + this->post_rest(API_PATH "/channels", std::to_string(channel_id), "messages/" + std::to_string(message_id), m_delete, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("confirmation", confirmation(), http)); + } + }); +} + +void cluster::message_delete_bulk(const std::vector& message_ids, snowflake channel_id, command_completion_event_t callback) { + json j; + for (auto & m : message_ids) { + j.push_back(std::to_string(m)); + } + this->post_rest(API_PATH "/channels", std::to_string(channel_id), "messages/bulk-delete", m_delete, j.dump(), [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("confirmation", confirmation(), http)); + } + }); +} + +void cluster::channel_create(const class channel &c, command_completion_event_t callback) { + this->post_rest(API_PATH "/guilds", std::to_string(c.guild_id), "channels", m_post, c.build_json(), [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("channel", channel().fill_from_json(&j), http)); + } + }); +} + +void cluster::channel_edit(const class channel &c, command_completion_event_t callback) { + json j = c.build_json(true); + auto p = j.find("position"); + if (p != j.end()) { + j.erase(p); + } + this->post_rest(API_PATH "/channels", std::to_string(c.id), "", m_patch, j.dump(), [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("channel", channel().fill_from_json(&j), http)); + } + }); +} + +void cluster::channel_get(snowflake c, command_completion_event_t callback) { + this->post_rest(API_PATH "/channels", std::to_string(c), "", m_get, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("channel", channel().fill_from_json(&j), http)); + } + }); +} + +void cluster::channel_typing(const class channel &c, command_completion_event_t callback) { + this->post_rest(API_PATH "/channels", std::to_string(c.id), "typing", m_post, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("confirmation", confirmation(), http)); + } + }); +} + +void cluster::message_pin(snowflake channel_id, snowflake message_id, command_completion_event_t callback) { + this->post_rest(API_PATH "/channels", std::to_string(channel_id), "pins/" + std::to_string(message_id), m_put, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("confirmation", confirmation(), http)); + } + }); +} + +void cluster::message_unpin(snowflake channel_id, snowflake message_id, command_completion_event_t callback) { + this->post_rest(API_PATH "/channels", std::to_string(channel_id), "pins/" + std::to_string(message_id), m_delete, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("confirmation", confirmation(), http)); + } + }); +} + +void cluster::channel_edit_position(const class channel &c, command_completion_event_t callback) { + json j({ {"id", c.id}, {"position", c.position} }); + this->post_rest(API_PATH "/guilds", std::to_string(c.guild_id), "channels/" + std::to_string(c.id), m_patch, j.dump(), [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("channel", channel().fill_from_json(&j), http)); + } + }); +} + +void cluster::channel_edit_permissions(const class channel &c, snowflake overwrite_id, uint32_t allow, uint32_t deny, bool member, command_completion_event_t callback) { + json j({ {"allow", std::to_string(allow)}, {"deny", std::to_string(deny)}, {"type", member ? 1 : 0} }); + this->post_rest(API_PATH "/channels", std::to_string(c.id), "permissions/" + std::to_string(overwrite_id), m_put, j.dump(), [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("confirmation", confirmation(), http)); + } + }); +} + +void cluster::channel_follow_news(const class channel &c, snowflake target_channel_id, command_completion_event_t callback) { + json j({ {"webhook_channel_id", target_channel_id} }); + this->post_rest(API_PATH "/channels", std::to_string(c.id), "followers", m_post, j.dump(), [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("confirmation", confirmation(), http)); + } + }); +} + +void cluster::channel_delete_permission(const class channel &c, snowflake overwrite_id, command_completion_event_t callback) { + this->post_rest(API_PATH "/channels", std::to_string(c.id), "permissions/" + std::to_string(overwrite_id), m_delete, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("confirmation", confirmation(), http)); + } + }); +} + +void cluster::invite_get(const std::string &invitecode, command_completion_event_t callback) { + this->post_rest(API_PATH "/invites", dpp::url_encode(invitecode), "?with_counts=true", m_get, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("invite", invite().fill_from_json(&j), http)); + } + }); +} + +void cluster::channel_invites_get(const class channel &c, command_completion_event_t callback) { + this->post_rest(API_PATH "/channels", std::to_string(c.id), "invites", m_get, "", [callback](json &j, const http_request_completion_t& http) { + invite_map invites; + for (auto & curr_invite : j) { + invites[StringNotNull(&curr_invite, "code")] = invite().fill_from_json(&curr_invite); + } + if (callback) { + callback(confirmation_callback_t("invite_map", invites, http)); + } + }); +} + +void cluster::guild_commands_get(snowflake guild_id, command_completion_event_t callback) { + this->post_rest(API_PATH "/applications", std::to_string(me.id), "/guilds/" + std::to_string(guild_id) + "/commands", m_get, "", [callback](json &j, const http_request_completion_t& http) { + slashcommand_map slashcommands; + for (auto & curr_slashcommand : j) { + slashcommands[SnowflakeNotNull(&curr_slashcommand, "id")] = slashcommand().fill_from_json(&curr_slashcommand); + } + if (callback) { + callback(confirmation_callback_t("slashcommand_map", slashcommands, http)); + } + }); +} + +void cluster::global_commands_get(command_completion_event_t callback) { + this->post_rest(API_PATH "/applications", std::to_string(me.id), "commands", m_get, "", [callback](json &j, const http_request_completion_t& http) { + slashcommand_map slashcommands; + for (auto & curr_slashcommand : j) { + slashcommands[SnowflakeNotNull(&curr_slashcommand, "id")] = slashcommand().fill_from_json(&curr_slashcommand); + } + if (callback) { + callback(confirmation_callback_t("slashcommand_map", slashcommands, http)); + } + }); +} + + +void cluster::get_guild_invites(snowflake guild_id, command_completion_event_t callback) { + this->post_rest(API_PATH "/guilds", std::to_string(guild_id), "invites", m_get, "", [callback](json &j, const http_request_completion_t& http) { + invite_map invites; + for (auto & curr_invite : j) { + invites[StringNotNull(&curr_invite, "code")] = invite().fill_from_json(&curr_invite); + } + if (callback) { + callback(confirmation_callback_t("invite_map", invites, http)); + } + }); +} + +void cluster::guild_get_integrations(snowflake guild_id, command_completion_event_t callback) { + this->post_rest(API_PATH "/guilds", std::to_string(guild_id), "integrations", m_get, "", [callback](json &j, const http_request_completion_t& http) { + integration_map integrations; + for (auto & curr_integration : j) { + integrations[SnowflakeNotNull(&curr_integration, "id")] = integration().fill_from_json(&curr_integration); + } + if (callback) { + callback(confirmation_callback_t("integration_map", integrations, http)); + } + }); +} + +void cluster::guild_get_widget(snowflake guild_id, command_completion_event_t callback) { + this->post_rest(API_PATH "/guilds", std::to_string(guild_id), "widget", m_get, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("guild_widget", guild_widget().fill_from_json(&j), http)); + } + }); +} + +void cluster::guild_get_vanity(snowflake guild_id, command_completion_event_t callback) { + this->post_rest(API_PATH "/guilds", std::to_string(guild_id), "vanity-url", m_get, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("invite", invite().fill_from_json(&j), http)); + } + }); +} + +void cluster::guild_edit_widget(snowflake guild_id, const class guild_widget &gw, command_completion_event_t callback) { + this->post_rest(API_PATH "/guilds", std::to_string(guild_id), "widget", m_patch, gw.build_json(), [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("guild_widget", guild_widget().fill_from_json(&j), http)); + } + }); +} + +void cluster::guild_modify_integration(snowflake guild_id, const class integration &i, command_completion_event_t callback) { + this->post_rest(API_PATH "/guilds", std::to_string(guild_id), "integrations/" + std::to_string(i.id), m_patch, i.build_json(), [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("confirmation", confirmation(), http)); + } + }); +} + +void cluster::guild_delete_integration(snowflake guild_id, snowflake integration_id, command_completion_event_t callback) { + this->post_rest(API_PATH "/guilds", std::to_string(guild_id), "integrations/" + std::to_string(integration_id), m_delete, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("confirmation", confirmation(), http)); + } + }); +} + +void cluster::guild_sync_integration(snowflake guild_id, snowflake integration_id, command_completion_event_t callback) { + this->post_rest(API_PATH "/guilds", std::to_string(guild_id), "integrations/" + std::to_string(integration_id), m_post, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("confirmation", confirmation(), http)); + } + }); +} + + + +void cluster::channel_invite_create(const class channel &c, const class invite &i, command_completion_event_t callback) { + this->post_rest(API_PATH "/channels", std::to_string(c.id), "invites", m_post, i.build_json(), [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("invite", invite().fill_from_json(&j), http)); + } + }); +} + +void cluster::pins_get(snowflake channel_id, command_completion_event_t callback) { + this->post_rest(API_PATH "/channels", std::to_string(channel_id), "pins", m_get, "", [callback](json &j, const http_request_completion_t& http) { + message_map pins_messages; + for (auto & curr_message : j) { + pins_messages[SnowflakeNotNull(&curr_message, "id")] = message().fill_from_json(&curr_message); + } + if (callback) { + callback(confirmation_callback_t("message_map", pins_messages, http)); + } + }); +} + +void cluster::gdm_add(snowflake channel_id, snowflake user_id, const std::string &access_token, const std::string &nick, command_completion_event_t callback) { + json params; + params["access_token"] = access_token; + params["nick"] = nick; + this->post_rest(API_PATH "/channels", std::to_string(channel_id), "recipients/" + std::to_string(user_id), m_put, params.dump(), [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("confirmation", confirmation(), http)); + } + }); +} + +void cluster::gdm_remove(snowflake channel_id, snowflake user_id, command_completion_event_t callback) { + this->post_rest(API_PATH "/channels", std::to_string(channel_id), "recipients/" + std::to_string(user_id), m_delete, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("confirmation", confirmation(), http)); + } + }); +} + +void cluster::invite_delete(const std::string &invitecode, command_completion_event_t callback) { + this->post_rest(API_PATH "/invites", dpp::url_encode(invitecode), "", m_delete, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("invite", invite().fill_from_json(&j), http)); + } + }); +} + +void cluster::channel_delete(snowflake channel_id, command_completion_event_t callback) { + this->post_rest(API_PATH "/channels", std::to_string(channel_id), "", m_delete, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("confirmation", confirmation(), http)); + } + }); +} + +void cluster::guild_create(const class guild &g, command_completion_event_t callback) { + this->post_rest(API_PATH "/guilds", "", "", m_post, g.build_json(), [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("guild", guild().fill_from_json(nullptr, &j), http)); + } + }); +} + +void cluster::guild_edit(const class guild &g, command_completion_event_t callback) { + this->post_rest(API_PATH "/guilds", std::to_string(g.id), "", m_patch, g.build_json(true), [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("guild", guild().fill_from_json(nullptr, &j), http)); + } + }); +} + +void cluster::guild_get(snowflake guild_id, command_completion_event_t callback) { + this->post_rest(API_PATH "/guilds", std::to_string(guild_id), "", m_get, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("guild", guild().fill_from_json(nullptr, &j), http)); + } + }); +} + +void cluster::guild_get_preview(snowflake guild_id, command_completion_event_t callback) { + this->post_rest(API_PATH "/guilds", std::to_string(guild_id), "preview", m_get, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("guild", guild().fill_from_json(nullptr, &j), http)); + } + }); +} + +void cluster::guild_get_member(snowflake guild_id, snowflake user_id, command_completion_event_t callback) { + this->post_rest(API_PATH "/guilds", std::to_string(guild_id), "member/" + std::to_string(user_id), m_get, "", [callback, guild_id, user_id](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("guild_member", guild_member().fill_from_json(&j, guild_id, user_id), http)); + } + }); +} + +void cluster::guild_add_member(const guild_member& gm, const std::string &access_token, command_completion_event_t callback) { + json j; + try { + j = json::parse(gm.build_json()); + } + catch (const std::exception &e) { + log(ll_error, fmt::format("guild_add_member(): {}", e.what())); + return; + } + j["access_token"] = access_token; + this->post_rest(API_PATH "/guilds", std::to_string(gm.guild_id), "members/" + std::to_string(gm.user_id), m_put, j.dump(), [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("confirmation", confirmation(), http)); + } + }); +} + +void cluster::guild_edit_member(const guild_member& gm, command_completion_event_t callback) { + this->post_rest(API_PATH "/guilds", std::to_string(gm.guild_id), "members/" + std::to_string(gm.user_id), m_patch, gm.build_json(), [&gm, callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("guild_member", guild_member().fill_from_json(&j, gm.guild_id, gm.user_id), http)); + } + }); +} + +void cluster::guild_member_move(const snowflake channel_id, const snowflake guild_id, const snowflake user_id, command_completion_event_t callback) { + json j; + j["channel_id"] = channel_id; + + this->post_rest(API_PATH "/guilds", std::to_string(guild_id), "members/" + std::to_string(user_id), m_patch, j.dump(), [guild_id, user_id, callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("guild_member", guild_member().fill_from_json(&j, guild_id, user_id), http)); + } + }); +} + +void cluster::guild_set_nickname(snowflake guild_id, const std::string &nickname, command_completion_event_t callback) { + std::string o; + if (nickname.empty()) { + o = "{\"nickname\": null}"; + } else { + o = json({{"nickname", nickname}}).dump(); + } + this->post_rest(API_PATH "/guilds", std::to_string(guild_id), "members/@me/nick", m_patch, o, [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("confirmation", confirmation(), http)); + } + }); +} + +void cluster::guild_member_add_role(snowflake guild_id, snowflake user_id, snowflake role_id, command_completion_event_t callback) { + this->post_rest(API_PATH "/guilds", std::to_string(guild_id), "members/" + std::to_string(user_id) + "/roles/" + std::to_string(role_id), m_put, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("confirmation", confirmation(), http)); + } + }); +} + +void cluster::guild_member_delete_role(snowflake guild_id, snowflake user_id, snowflake role_id, command_completion_event_t callback) { + this->post_rest(API_PATH "/guilds", std::to_string(guild_id), "members/" + std::to_string(user_id) + "/roles/" + std::to_string(role_id), m_delete, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("confirmation", confirmation(), http)); + } + }); +} + +void cluster::guild_member_delete(snowflake guild_id, snowflake user_id, command_completion_event_t callback) { + this->post_rest(API_PATH "/guilds", std::to_string(guild_id), "members/" + std::to_string(user_id), m_delete, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("confirmation", confirmation(), http)); + } + }); +} + +void cluster::guild_ban_add(snowflake guild_id, snowflake user_id, uint32_t delete_message_days, const std::string &reason, command_completion_event_t callback) { + json j; + if (delete_message_days > 7) + delete_message_days = 7; + if (!reason.empty()) + j["reason"] = reason; + if (delete_message_days) + j["delete_message_days"] = delete_message_days; + this->post_rest(API_PATH "/guilds", std::to_string(guild_id), "bans/" + std::to_string(user_id), m_put, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("confirmation", confirmation(), http)); + } + }); +} + +void cluster::guild_ban_delete(snowflake guild_id, snowflake user_id, command_completion_event_t callback) { + this->post_rest(API_PATH "/guilds", std::to_string(guild_id), "bans/" + std::to_string(user_id), m_delete, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("confirmation", confirmation(), http)); + } + }); +} + + + +void cluster::guild_get_members(snowflake guild_id, command_completion_event_t callback) { + this->post_rest(API_PATH "/guilds", std::to_string(guild_id), "members", m_get, "", [callback, guild_id](json &j, const http_request_completion_t& http) { + guild_member_map guild_members; + for (auto & curr_member : j) { + guild_member gm; + snowflake user_id = 0; + if (curr_member.find("user") != curr_member.end()) { + user_id = SnowflakeNotNull(&(curr_member["user"]), "id"); + } + guild_members[SnowflakeNotNull(&curr_member, "id")] = guild_member().fill_from_json(&curr_member, guild_id, user_id); + } + if (callback) { + callback(confirmation_callback_t("guild_member_map", guild_members, http)); + } + }); +} + + +void cluster::template_get(const std::string &code, command_completion_event_t callback) { + this->post_rest(API_PATH "/guilds", "templates", code, m_get, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("dtemplate", dtemplate().fill_from_json(&j), http)); + } + }); +} + +void cluster::guild_create_from_template(const std::string &code, const std::string &name, command_completion_event_t callback) { + json params; + params["name"] = name; + this->post_rest(API_PATH "/guilds", "templates", code, m_post, params.dump(), [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("guild", guild().fill_from_json(nullptr, &j), http)); + } + }); +} + +void cluster::guild_templates_get(snowflake guild_id, command_completion_event_t callback) { + this->post_rest(API_PATH "/guilds", std::to_string(guild_id), "templates", m_get, "", [callback](json &j, const http_request_completion_t& http) { + dtemplate_map dtemplates; + for (auto & curr_dtemplate : j) { + dtemplates[SnowflakeNotNull(&curr_dtemplate, "id")] = dtemplate().fill_from_json(&curr_dtemplate); + } + if (callback) { + callback(confirmation_callback_t("dtemplate_map", dtemplates, http)); + } + }); +} + +void cluster::guild_template_create(snowflake guild_id, const std::string &name, const std::string &description, command_completion_event_t callback) { + json params; + params["name"] = name; + params["description"] = description; + this->post_rest(API_PATH "/guilds", std::to_string(guild_id), "templates", m_post, params.dump(), [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("dtemplate", dtemplate().fill_from_json(&j), http)); + } + }); +} + +void cluster::guild_template_sync(snowflake guild_id, const std::string &code, command_completion_event_t callback) { + this->post_rest(API_PATH "/guilds", std::to_string(guild_id), "templates/" + code, m_put, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("dtemplate", dtemplate().fill_from_json(&j), http)); + } + }); +} + +void cluster::guild_template_modify(snowflake guild_id, const std::string &code, const std::string &name, const std::string &description, command_completion_event_t callback) { + json params; + params["name"] = name; + params["description"] = description; + this->post_rest(API_PATH "/guilds", std::to_string(guild_id), "templates/" + code, m_patch, params.dump(), [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("dtemplate", dtemplate().fill_from_json(&j), http)); + } + }); +} + +void cluster::guild_template_delete(snowflake guild_id, const std::string &code, command_completion_event_t callback) { + this->post_rest(API_PATH "/guilds", std::to_string(guild_id), "templates/" + code, m_delete, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("dtemplate", dtemplate().fill_from_json(&j), http)); + } + }); +} + +void cluster::user_get(snowflake user_id, command_completion_event_t callback) { + this->post_rest(API_PATH "/users", std::to_string(user_id), "", m_get, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("user", user().fill_from_json(&j), http)); + } + }); +} + +void cluster::current_user_get(command_completion_event_t callback) { + this->post_rest(API_PATH "/users", "@me", "", m_get, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("user", user().fill_from_json(&j), http)); + } + }); +} + +void cluster::current_user_get_guilds(command_completion_event_t callback) { + this->post_rest(API_PATH "/users", "@me", "guilds", m_get, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + guild_map guilds; + for (auto & curr_guild : j) { + guilds[SnowflakeNotNull(&curr_guild, "id")] = guild().fill_from_json(nullptr, &curr_guild); + } + callback(confirmation_callback_t("guild_map", guilds, http)); + } + }); +} + +void cluster::guild_delete(snowflake guild_id, command_completion_event_t callback) { + this->post_rest(API_PATH "/guilds", std::to_string(guild_id), "", m_delete, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("confirmation", confirmation(), http)); + } + }); +} + +void cluster::role_create(const class role &r, command_completion_event_t callback) { + this->post_rest(API_PATH "/channels", std::to_string(r.guild_id), "roles", m_post, r.build_json(), [r, callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("role", role().fill_from_json(r.guild_id, &j), http)); + } + }); +} + +void cluster::role_edit(const class role &r, command_completion_event_t callback) { + json j = r.build_json(true); + auto p = j.find("position"); + if (p != j.end()) { + j.erase(p); + } + this->post_rest(API_PATH "/guilds", std::to_string(r.guild_id), "roles/" + std::to_string(r.id) , m_patch, j.dump(), [r, callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("role", role().fill_from_json(r.guild_id, &j), http)); + } + }); +} + +void cluster::guild_get_bans(snowflake guild_id, command_completion_event_t callback) { + this->post_rest(API_PATH "/guilds", std::to_string(guild_id), "bans", m_get, "", [callback](json &j, const http_request_completion_t& http) { + ban_map bans; + for (auto & curr_ban : j) { + bans[SnowflakeNotNull(&curr_ban, "user_id")] = ban().fill_from_json(&curr_ban); + } + if (callback) { + callback(confirmation_callback_t("ban_map", bans, http)); + } + }); +} + +void cluster::guild_get_ban(snowflake guild_id, snowflake user_id, command_completion_event_t callback) { + this->post_rest(API_PATH "/guilds", std::to_string(guild_id), "bans/" + std::to_string(user_id), m_get, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("ban", ban().fill_from_json(&j), http)); + } + }); +} + +void cluster::guild_emojis_get(snowflake guild_id, command_completion_event_t callback) { + this->post_rest(API_PATH "/guilds", std::to_string(guild_id), "emojis", m_get, "", [guild_id, callback](json &j, const http_request_completion_t& http) { + if (callback) { + emoji_map emojis; + for (auto & curr_emoji : j) { + emojis[SnowflakeNotNull(&curr_emoji, "id")] = emoji().fill_from_json(&curr_emoji); + } + callback(confirmation_callback_t("emoji_map", emojis, http)); + } + }); +} + +void cluster::guild_emoji_get(snowflake guild_id, snowflake emoji_id, command_completion_event_t callback) { + this->post_rest(API_PATH "/guilds", std::to_string(guild_id), "emojis/" + std::to_string(emoji_id), m_get, "", [guild_id, callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("emoji", emoji().fill_from_json(&j), http)); + } + }); +} + +void cluster::guild_emoji_create(snowflake guild_id, const class emoji& newemoji, command_completion_event_t callback) { + this->post_rest(API_PATH "/guilds", std::to_string(guild_id), "emojis", m_post, newemoji.build_json(), [guild_id, callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("emoji", emoji().fill_from_json(&j), http)); + } + }); +} + +void cluster::guild_emoji_edit(snowflake guild_id, const class emoji& newemoji, command_completion_event_t callback) { + this->post_rest(API_PATH "/guilds", std::to_string(guild_id), "emojis/" + std::to_string(newemoji.id), m_patch, newemoji.build_json(), [guild_id, callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("emoji", emoji().fill_from_json(&j), http)); + } + }); +} + +void cluster::guild_emoji_delete(snowflake guild_id, snowflake emoji_id, command_completion_event_t callback) { + this->post_rest(API_PATH "/guilds", std::to_string(guild_id), "emojis/" + std::to_string(emoji_id), m_delete, "", [guild_id, callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("confirmation", confirmation(), http)); + } + }); +} + +void cluster::guild_get_prune_counts(snowflake guild_id, const struct prune& pruneinfo, command_completion_event_t callback) { + this->post_rest(API_PATH "/guilds", std::to_string(guild_id), "prune", m_get, pruneinfo.build_json(false), [guild_id, callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("prune", prune().fill_from_json(&j), http)); + } + }); +} + +void cluster::guild_begin_prune(snowflake guild_id, const struct prune& pruneinfo, command_completion_event_t callback) { + this->post_rest(API_PATH "/guilds", std::to_string(guild_id), "prune", m_get, pruneinfo.build_json(true), [guild_id, callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("prune", prune().fill_from_json(&j), http)); + } + }); +} + +void cluster::guild_get_voice_regions(snowflake guild_id, command_completion_event_t callback) { + this->post_rest(API_PATH "/guilds", std::to_string(guild_id), "regions", m_get, "", [guild_id, callback](json &j, const http_request_completion_t& http) { + voiceregion_map voiceregions; + for (auto & curr_region : j) { + voiceregions[StringNotNull(&curr_region, "id")] = voiceregion().fill_from_json(&j); + } + callback(confirmation_callback_t("voiceregion_map", voiceregions, http)); + }); +} + +void cluster::get_voice_regions(command_completion_event_t callback) { + this->post_rest("/voice/v9/regions", "", "", m_get, "", [callback](json &j, const http_request_completion_t& http) { + voiceregion_map voiceregions; + for (auto & curr_region : j) { + voiceregions[StringNotNull(&curr_region, "id")] = voiceregion().fill_from_json(&j); + } + callback(confirmation_callback_t("voiceregion_map", voiceregions, http)); + }); +} + + +void cluster::roles_get(snowflake guild_id, command_completion_event_t callback) { + this->post_rest(API_PATH "/guilds", std::to_string(guild_id), "roles", m_get, "", [guild_id, callback](json &j, const http_request_completion_t& http) { + if (callback) { + role_map roles; + for (auto & curr_role : j) { + roles[SnowflakeNotNull(&curr_role, "id")] = role().fill_from_json(guild_id, &curr_role); + } + callback(confirmation_callback_t("role_map", roles, http)); + } + }); +} + +void cluster::channels_get(snowflake guild_id, command_completion_event_t callback) { + this->post_rest(API_PATH "/guilds", std::to_string(guild_id), "channels", m_get, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + channel_map channels; + for (auto & curr_channel: j) { + channels[SnowflakeNotNull(&curr_channel, "id")] = channel().fill_from_json(&curr_channel); + } + callback(confirmation_callback_t("channel_map", channels, http)); + } + }); +} + +void cluster::messages_get(snowflake channel_id, snowflake around, snowflake before, snowflake after, snowflake limit, command_completion_event_t callback) { + std::string parameters; + if (around) { + parameters.append("&around=" + std::to_string(around)); + } + if (before) { + parameters.append("&before=" + std::to_string(before)); + } + if (after) { + parameters.append("&after=" + std::to_string(after)); + } + if (limit) { + parameters.append("&limit=" + std::to_string(limit)); + } + if (!parameters.empty()) { + parameters[0] = '?'; + } + this->post_rest(API_PATH "/channels", std::to_string(channel_id), "messages" + parameters, m_get, json(), [channel_id, callback](json &j, const http_request_completion_t& http) { + if (callback) { + message_map messages; + for (auto & curr_message : j) { + messages[SnowflakeNotNull(&curr_message, "id")] = message().fill_from_json(&curr_message); + } + callback(confirmation_callback_t("message_map", messages, http)); + } + }); +} + +void cluster::role_edit_position(const class role &r, command_completion_event_t callback) { + json j({ {"id", r.id}, {"position", r.position} }); + this->post_rest(API_PATH "/guilds", std::to_string(r.guild_id), "roles/" + std::to_string(r.id), m_patch, j.dump(), [r, callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("role", role().fill_from_json(r.guild_id, &j), http)); + } + }); +} + +void cluster::role_delete(snowflake guild_id, snowflake role_id, command_completion_event_t callback) { + this->post_rest(API_PATH "/guilds", std::to_string(guild_id), "roles/" + std::to_string(role_id), m_delete, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("confirmation", confirmation(), http)); + } + }); +} + +void cluster::current_user_edit(const std::string &nickname, const std::string& image_blob, image_type type, command_completion_event_t callback) { + json j = json::parse("{\"nickname\": null}"); + if (!nickname.empty()) { + j["nickname"] = nickname; + } + if (!image_blob.empty()) { + static std::map mimetypes = { + { i_gif, "image/gif" }, + { i_jpg, "image/jpeg" }, + { i_png, "image/png" } + }; + if (image_blob.size() > MAX_EMOJI_SIZE) { + throw dpp::exception("User icon file exceeds discord limit of 256 kilobytes"); + } + j["avatar"] = "data:" + mimetypes[type] + ";base64," + base64_encode((unsigned char const*)image_blob.data(), image_blob.length()); + } + this->post_rest(API_PATH "/users", "@me", "", m_patch, j.dump(), [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("user", user().fill_from_json(&j), http)); + } + }); +} + +void cluster::current_user_leave_guild(snowflake guild_id, command_completion_event_t callback) { + this->post_rest(API_PATH "/users", "@me", "guilds/" + std::to_string(guild_id), m_delete, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("confirmation", confirmation(), http)); + } + }); +} + +void cluster::thread_create(const std::string& thread_name, snowflake channel_id, uint16_t auto_archive_duration, channel_type thread_type, command_completion_event_t callback) +{ + json j; + j["name"] = thread_name; + j["auto_archive_duration"] = auto_archive_duration; + j["type"] = thread_type; + this->post_rest(API_PATH "/channels", std::to_string(channel_id), "threads", m_post, j.dump(), [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("channel", channel().fill_from_json(&j), http)); + } + }); +} +void cluster::thread_create_with_message(const std::string& thread_name, snowflake channel_id, snowflake message_id, uint16_t auto_archive_duration, command_completion_event_t callback) +{ + json j; + j["name"] = thread_name; + j["auto_archive_duration"] = auto_archive_duration; + this->post_rest(API_PATH "/channels", std::to_string(channel_id), "messages/" + std::to_string(message_id) + "/threads", m_post, j.dump(), [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("channel", channel().fill_from_json(&j), http)); + } + }); +} + +void cluster::current_user_join_thread(snowflake thread_id, command_completion_event_t callback) { + this->post_rest(API_PATH "/channels", std::to_string(thread_id), "/thread-members/@me", m_put, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("confirmation", confirmation(), http)); + } + }); +} + +void cluster::current_user_leave_thread(snowflake thread_id, command_completion_event_t callback) { + this->post_rest(API_PATH "/channels", std::to_string(thread_id), "/thread-members/@me", m_delete, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("confirmation", confirmation(), http)); + } + }); +} + +void cluster::thread_member_add(snowflake thread_id, snowflake user_id, command_completion_event_t callback) { + this->post_rest(API_PATH "/channels", std::to_string(thread_id), "/thread-members/" + std::to_string(user_id), m_put, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("confirmation", confirmation(), http)); + } + }); +} + +void cluster::thread_member_remove(snowflake thread_id, snowflake user_id, command_completion_event_t callback) { + this->post_rest(API_PATH "/channels", std::to_string(thread_id), "/thread-members/" + std::to_string(user_id), m_delete, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("confirmation", confirmation(), http)); + } + }); +} + +void cluster::get_thread_members(snowflake thread_id, command_completion_event_t callback) { + this->post_rest(API_PATH "/channels", std::to_string(thread_id), "/threads-members", m_get, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + thread_member_map thread_members; + for (auto& curr_member : j) { + thread_members[SnowflakeNotNull(&curr_member, "user_id")] = thread_member().fill_from_json(&curr_member); + } + callback(confirmation_callback_t("thread_member_map", thread_members, http)); + } + }); +} + +void cluster::get_active_threads(snowflake channel_id, command_completion_event_t callback) { + this->post_rest(API_PATH "/channels", std::to_string(channel_id), "/threads/active", m_get, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + channel_map threads; + for (auto &curr_thread : j) { + threads[SnowflakeNotNull(&curr_thread, "id")] = channel().fill_from_json(&curr_thread); + } + callback(confirmation_callback_t("channel_map", threads, http)); + } + }); +} + +void cluster::get_public_archived_threads(snowflake channel_id, time_t before_timestamp, uint16_t limit, command_completion_event_t callback) { + std::string parameters; + if (before_timestamp) { + parameters.append("&before=" + std::to_string(before_timestamp)); + } + if (limit) { + parameters.append("&limit=" + std::to_string(limit)); + } + this->post_rest(API_PATH "/channels", std::to_string(channel_id), "/threads/archived/public" + parameters, m_get, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + channel_map threads; + for (auto &curr_thread : j) { + threads[SnowflakeNotNull(&curr_thread, "id")] = channel().fill_from_json(&curr_thread); + } + callback(confirmation_callback_t("channel_map", threads, http)); + } + }); +} + +void cluster::get_private_archived_threads(snowflake channel_id, time_t before_timestamp, uint16_t limit, command_completion_event_t callback) { + std::string parameters; + if (before_timestamp) { + parameters.append("&before=" + std::to_string(before_timestamp)); + } + if (limit) { + parameters.append("&limit=" + std::to_string(limit)); + } + this->post_rest(API_PATH "/channels", std::to_string(channel_id), "/threads/archived/private" + parameters, m_get, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + channel_map threads; + for (auto &curr_thread : j) { + threads[SnowflakeNotNull(&curr_thread, "id")] = channel().fill_from_json(&curr_thread); + } + callback(confirmation_callback_t("channel_map", threads, http)); + } + }); +} + +void cluster::get_joined_private_archived_threads(snowflake channel_id, snowflake before_id, uint16_t limit, command_completion_event_t callback) { + std::string parameters; + if (before_id) { + parameters.append("&before=" + std::to_string(before_id)); + } + if (limit) { + parameters.append("&limit=" + std::to_string(limit)); + } + this->post_rest(API_PATH "/channels", std::to_string(channel_id), "/users/@me/threads/archived/private" + parameters, m_get, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + channel_map threads; + for (auto &curr_thread : j) { + threads[SnowflakeNotNull(&curr_thread, "id")] = channel().fill_from_json(&curr_thread); + } + callback(confirmation_callback_t("channel_map", threads, http)); + } + }); +} +void cluster::current_user_get_dms(command_completion_event_t callback) { + this->post_rest(API_PATH "/users", "@me", "channels", m_get, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + channel_map channels; + for (auto & curr_channel: j) { + channels[SnowflakeNotNull(&curr_channel, "id")] = channel().fill_from_json(&curr_channel); + } + callback(confirmation_callback_t("channel_map", channels, http)); + } + }); +} + +void cluster::create_dm_channel(snowflake user_id, command_completion_event_t callback) { + this->post_rest(API_PATH "/users", "@me", "channels", m_post, json({{"recipient_id", std::to_string(user_id)}}).dump(), [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("channel", channel().fill_from_json(&j), http)); + } + }); +} + +void cluster::create_webhook(const class webhook &w, command_completion_event_t callback) { + this->post_rest(API_PATH "/channels", std::to_string(w.channel_id), "webhooks", m_post, w.build_json(false), [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("webhook", webhook().fill_from_json(&j), http)); + } + }); +} + +void cluster::get_guild_webhooks(snowflake guild_id, command_completion_event_t callback) { + this->post_rest(API_PATH "/guilds", std::to_string(guild_id), "webhooks", m_get, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + webhook_map webhooks; + for (auto & curr_webhook: j) { + webhooks[SnowflakeNotNull(&curr_webhook, "id")] = webhook().fill_from_json(&curr_webhook); + } + callback(confirmation_callback_t("webhook_map", webhooks, http)); + } + }); +} + +void cluster::get_channel_webhooks(snowflake channel_id, command_completion_event_t callback) { + this->post_rest(API_PATH "/channels", std::to_string(channel_id), "webhooks", m_get, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + webhook_map webhooks; + for (auto & curr_webhook: j) { + webhooks[SnowflakeNotNull(&curr_webhook, "id")] = webhook().fill_from_json(&curr_webhook); + } + callback(confirmation_callback_t("webhook_map", webhooks, http)); + } + }); +} + +void cluster::get_webhook(snowflake webhook_id, command_completion_event_t callback) { + this->post_rest(API_PATH "/webhooks", std::to_string(webhook_id), "", m_get, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("webhook", webhook().fill_from_json(&j), http)); + } + }); +} + +void cluster::get_webhook_with_token(snowflake webhook_id, const std::string &token, command_completion_event_t callback) { + this->post_rest(API_PATH "/webhooks", std::to_string(webhook_id), dpp::url_encode(token), m_get, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("webhook", webhook().fill_from_json(&j), http)); + } + }); +} + +void cluster::edit_webhook(const class webhook& wh, command_completion_event_t callback) { + this->post_rest(API_PATH "/webhooks", std::to_string(wh.id), "", m_patch, wh.build_json(true), [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("webhook", webhook().fill_from_json(&j), http)); + } + }); +} + +void cluster::edit_webhook_with_token(const class webhook& wh, command_completion_event_t callback) { + json jwh; + try { + jwh = json::parse(wh.build_json(true)); + } + catch (const std::exception &e) { + log(ll_error, fmt::format("edit_webhook_with_token(): {}", e.what())); + return; + } + if (jwh.find("channel_id") != jwh.end()) { + jwh.erase(jwh.find("channel_id")); + } + this->post_rest(API_PATH "/webhooks", std::to_string(wh.id), dpp::url_encode(wh.token), m_patch, jwh.dump(), [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("webhook", webhook().fill_from_json(&j), http)); + } + }); +} + +void cluster::delete_webhook(snowflake webhook_id, command_completion_event_t callback) { + this->post_rest(API_PATH "/webhooks", std::to_string(webhook_id), "", m_delete, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("confirmation", confirmation(), http)); + } + }); +} + +void cluster::delete_webhook_with_token(snowflake webhook_id, const std::string &token, command_completion_event_t callback) { + this->post_rest(API_PATH "/webhooks", std::to_string(webhook_id), dpp::url_encode(token), m_get, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("confirmation", confirmation(), http)); + } + }); +} + +void cluster::execute_webhook(const class webhook &wh, const struct message& m, bool wait, snowflake thread_id, command_completion_event_t callback) { + std::string parameters; + if (wait) { + parameters.append("&wait=true"); + } + if (thread_id) { + parameters.append("&thread_id=" + std::to_string(thread_id)); + } + this->post_rest(API_PATH "/webhooks", std::to_string(wh.id), dpp::url_encode(token), m_post, m.build_json(false), [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("message", message().fill_from_json(&j), http)); + } + }); +} + +void cluster::get_webhook_message(const class webhook &wh, command_completion_event_t callback) +{ + this->post_rest(API_PATH "/webhooks", std::to_string(wh.id), dpp::url_encode(token) + "/messages/@original", m_get, "", [callback](json &j, const http_request_completion_t &http){ + if (callback){ + callback(confirmation_callback_t("message", message().fill_from_json(&j), http)); + } + }); +} + +void cluster::edit_webhook_message(const class webhook &wh, const struct message& m, command_completion_event_t callback) { + this->post_rest(API_PATH "/webhooks", std::to_string(wh.id), dpp::url_encode(token) + "/messages/" + std::to_string(m.id), m_patch, m.build_json(false), [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("message", message().fill_from_json(&j), http)); + } + }); +} + +void cluster::delete_webhook_message(const class webhook &wh, snowflake message_id, command_completion_event_t callback) { + this->post_rest(API_PATH "/webhooks", std::to_string(wh.id), dpp::url_encode(token) + "/messages/" + std::to_string(message_id), m_delete, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("confirmation", confirmation(), http)); + } + }); +} + +void cluster::guild_auditlog_get(snowflake guild_id, command_completion_event_t callback) { + this->post_rest(API_PATH "/guilds", std::to_string(guild_id), "audit-logs", m_get, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("auditlog", auditlog().fill_from_json(&j), http)); + } + }); +} + +void cluster::on_log (std::function _log) { + this->dispatch.log = _log; +} + +void cluster::on_voice_state_update (std::function _voice_state_update) { + this->dispatch.voice_state_update = _voice_state_update; +} + +void cluster::on_stage_instance_create (std::function _stage_instance_create) { + this->dispatch.stage_instance_create = _stage_instance_create; +} + +void cluster::on_stage_instance_delete (std::function _stage_instance_delete) { + this->dispatch.stage_instance_delete = _stage_instance_delete; +} + +void cluster::on_interaction_create (std::function _interaction_create) { + this->dispatch.interaction_create = _interaction_create; +} + +void cluster::on_button_click (std::function _button_click) { + this->dispatch.button_click = _button_click; +} + +void cluster::on_select_click (std::function _select_click) { + this->dispatch.select_click = _select_click; +} + +void cluster::on_guild_delete (std::function _guild_delete) { + this->dispatch.guild_delete = _guild_delete; +} + +void cluster::on_channel_delete (std::function _channel_delete) { + this->dispatch.channel_delete = _channel_delete; +} + +void cluster::on_channel_update (std::function _channel_update) { + this->dispatch.channel_update = _channel_update; +} + +void cluster::on_ready (std::function _ready) { + this->dispatch.ready = _ready; +} + +void cluster::on_message_delete (std::function _message_delete) { + this->dispatch.message_delete = _message_delete; +} + +void cluster::on_application_command_delete (std::function _application_command_delete) { + this->dispatch.application_command_delete = _application_command_delete; +} + +void cluster::on_guild_member_remove (std::function _guild_member_remove) { + this->dispatch.guild_member_remove = _guild_member_remove; +} + +void cluster::on_application_command_create (std::function _application_command_create) { + this->dispatch.application_command_create = _application_command_create; +} + +void cluster::on_resumed (std::function _resumed) { + this->dispatch.resumed = _resumed; +} + +void cluster::on_guild_role_create (std::function _guild_role_create) { + this->dispatch.guild_role_create = _guild_role_create; +} + +void cluster::on_typing_start (std::function _typing_start) { + this->dispatch.typing_start = _typing_start; +} + +void cluster::on_message_reaction_add (std::function _message_reaction_add) { + this->dispatch.message_reaction_add = _message_reaction_add; +} + +void cluster::on_guild_members_chunk (std::function _guild_members_chunk) { + this->dispatch.guild_members_chunk = _guild_members_chunk; +} + +void cluster::on_message_reaction_remove (std::function _message_reaction_remove) { + this->dispatch.message_reaction_remove = _message_reaction_remove; +} + +void cluster::on_guild_create (std::function _guild_create) { + this->dispatch.guild_create = _guild_create; +} + +void cluster::on_channel_create (std::function _channel_create) { + this->dispatch.channel_create = _channel_create; +} + +void cluster::on_message_reaction_remove_emoji (std::function _message_reaction_remove_emoji) { + this->dispatch.message_reaction_remove_emoji = _message_reaction_remove_emoji; +} + +void cluster::on_message_delete_bulk (std::function _message_delete_bulk) { + this->dispatch.message_delete_bulk = _message_delete_bulk; +} + +void cluster::on_guild_role_update (std::function _guild_role_update) { + this->dispatch.guild_role_update = _guild_role_update; +} + +void cluster::on_guild_role_delete (std::function _guild_role_delete) { + this->dispatch.guild_role_delete = _guild_role_delete; +} + +void cluster::on_channel_pins_update (std::function _channel_pins_update) { + this->dispatch.channel_pins_update = _channel_pins_update; +} + +void cluster::on_message_reaction_remove_all (std::function _message_reaction_remove_all) { + this->dispatch.message_reaction_remove_all = _message_reaction_remove_all; +} + +void cluster::on_thread_create (std::function _thread_create) { + this->dispatch.thread_create = _thread_create; +} + +void cluster::on_thread_update (std::function _thread_update) { + this->dispatch.thread_update = _thread_update; +} + +void cluster::on_thread_delete (std::function _thread_delete) { + this->dispatch.thread_delete = _thread_delete; +} + +void cluster::on_thread_list_sync (std::function _thread_list_sync) { + this->dispatch.thread_list_sync = _thread_list_sync; +} + +void cluster::on_thread_member_update (std::function _thread_member_update) { + this->dispatch.thread_member_update = _thread_member_update; +} + +void cluster::on_thread_members_update (std::function _thread_members_update) { + this->dispatch.thread_members_update = _thread_members_update; +} + +void cluster::on_voice_server_update (std::function _voice_server_update) { + this->dispatch.voice_server_update = _voice_server_update; +} + +void cluster::on_guild_emojis_update (std::function _guild_emojis_update) { + this->dispatch.guild_emojis_update = _guild_emojis_update; +} + +void cluster::on_guild_stickers_update (std::function _guild_stickers_update) { + this->dispatch.stickers_update = _guild_stickers_update; +} + +void cluster::on_presence_update (std::function _presence_update) { + this->dispatch.presence_update = _presence_update; +} + +void cluster::on_webhooks_update (std::function _webhooks_update) { + this->dispatch.webhooks_update = _webhooks_update; +} + +void cluster::on_guild_member_add (std::function _guild_member_add) { + this->dispatch.guild_member_add = _guild_member_add; +} + +void cluster::on_invite_delete (std::function _invite_delete) { + this->dispatch.invite_delete = _invite_delete; +} + +void cluster::on_guild_update (std::function _guild_update) { + this->dispatch.guild_update = _guild_update; +} + +void cluster::on_guild_integrations_update (std::function _guild_integrations_update) { + this->dispatch.guild_integrations_update = _guild_integrations_update; +} + +void cluster::on_guild_member_update (std::function _guild_member_update) { + this->dispatch.guild_member_update = _guild_member_update; +} + +void cluster::on_application_command_update (std::function _application_command_update) { + this->dispatch.application_command_update = _application_command_update; +} + +void cluster::on_invite_create (std::function _invite_create) { + this->dispatch.invite_create = _invite_create; +} + +void cluster::on_message_update (std::function _message_update) { + this->dispatch.message_update = _message_update; +} + +void cluster::on_user_update (std::function _user_update) { + this->dispatch.user_update = _user_update; +} + +void cluster::on_message_create (std::function _message_create) { + this->dispatch.message_create = _message_create; +} + +void cluster::on_guild_ban_add (std::function _guild_ban_add) { + this->dispatch.guild_ban_add = _guild_ban_add; +} + +void cluster::on_guild_ban_remove (std::function _guild_ban_remove) { + this->dispatch.guild_ban_remove = _guild_ban_remove; +} + +void cluster::on_integration_create (std::function _integration_create) { + this->dispatch.integration_create = _integration_create; +} + +void cluster::on_integration_update (std::function _integration_update) { + this->dispatch.integration_update = _integration_update; +} + +void cluster::on_integration_delete (std::function _integration_delete) { + this->dispatch.integration_delete = _integration_delete; +} + +void cluster::on_voice_buffer_send (std::function _voice_buffer_send) { + this->dispatch.voice_buffer_send = _voice_buffer_send; +} + +void cluster::on_voice_user_talking (std::function _voice_user_talking) { + this->dispatch.voice_user_talking = _voice_user_talking; +} + +void cluster::on_voice_ready (std::function _voice_ready) { + this->dispatch.voice_ready = _voice_ready; +} + +void cluster::on_voice_receive (std::function _voice_receive) { + this->dispatch.voice_receive = _voice_receive; +} + +void cluster::on_voice_track_marker (std::function _voice_track_marker) { + this->dispatch.voice_track_marker = _voice_track_marker; +} + +void cluster::on_guild_join_request_delete(std::function _guild_join_request_delete) { + this->dispatch.guild_join_request_delete = _guild_join_request_delete; +} + +}; diff --git a/vendor/DPP/src/dpp/commandhandler.cpp b/vendor/DPP/src/dpp/commandhandler.cpp new file mode 100644 index 00000000..df793bff --- /dev/null +++ b/vendor/DPP/src/dpp/commandhandler.cpp @@ -0,0 +1,360 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace dpp { + +param_info::param_info(parameter_type t, bool o, const std::string &d, const std::map &opts) : type(t), optional(o), description(d), choices(opts) +{ +} + +commandhandler::commandhandler(cluster* o, bool auto_hook_events, snowflake application_id) : slash_commands_enabled(false), owner(o), app_id(application_id) +{ + if (!application_id && o->me.id) { + app_id = o->me.id; + } + if (auto_hook_events) { + o->on_interaction_create([this](const dpp::interaction_create_t &event) { + this->route(event); + }); + o->on_message_create([this](const dpp::message_create_t & event) { + this->route(*event.msg); + }); + } + +} + +commandhandler& commandhandler::set_owner(cluster* o) +{ + owner = o; + return *this; +} + +commandhandler::~commandhandler() +{ +} + +commandhandler& commandhandler::add_prefix(const std::string &prefix) +{ + prefixes.push_back(prefix); + if (prefix == "/") { + if (!slash_commands_enabled) { + /* Register existing slash commands */ + slash_commands_enabled = true; + } else { + slash_commands_enabled = true; + } + } + return *this; +} + +commandhandler& commandhandler::add_command(const std::string &command, const parameter_registration_t ¶meters, command_handler handler, const std::string &description, snowflake guild_id) +{ + command_info_t i; + i.func = handler; + i.guild_id = guild_id; + i.parameters = parameters; + commands[lowercase(command)] = i; + if (slash_commands_enabled) { + if (this->app_id == 0) { + if (owner->me.id == 0) { + throw dpp::exception("Command handler not ready (i don't know my application ID)"); + } else { + this->app_id = owner->me.id; + } + } + dpp::slashcommand newcommand; + /* Create a new global command on ready event */ + newcommand.set_name(lowercase(command)).set_description(description).set_application_id(this->app_id); + + for (auto& parameter : parameters) { + command_option_type cot; + switch (parameter.second.type) { + case pt_boolean: + cot = co_boolean; + break; + case pt_integer: + cot = co_integer; + break; + case pt_string: + cot = co_string; + break; + case pt_user: + cot = co_user; + break; + case pt_role: + cot = co_role; + break; + case pt_channel: + cot = co_channel; + break; + } + + command_option opt(cot, parameter.first, parameter.second.description, !parameter.second.optional); + if (!parameter.second.choices.empty()) { + for (auto& c : parameter.second.choices) { + opt.add_choice(dpp::command_option_choice(c.second, c.first)); + } + } + newcommand.add_option(opt); + } + /* Register the command */ + if (guild_id) { + owner->guild_command_create(newcommand, guild_id, [command, this](const dpp::confirmation_callback_t &callback) { + if (callback.is_error()) { + this->owner->log(dpp::ll_error, fmt::format("Failed to register guild slash command '{}': {}", command, callback.http_info.body)); + } + }); + } else { + owner->global_command_create(newcommand, [command, this](const dpp::confirmation_callback_t &callback) { + if (callback.is_error()) { + this->owner->log(dpp::ll_error, fmt::format("Failed to register global slash command '{}': {}", command, callback.http_info.body)); + } + }); + } + } + return *this; +} + +bool commandhandler::string_has_prefix(std::string &str) +{ + size_t str_length = utility::utf8len(str); + for (auto& p : prefixes) { + size_t prefix_length = utility::utf8len(p); + if (utility::utf8substr(str, 0, prefix_length) == p) { + str.erase(str.begin(), str.begin() + prefix_length); + return true; + } + } + return false; +} + +void commandhandler::route(const dpp::message& msg) +{ + std::string msg_content = msg.content; + if (string_has_prefix(msg_content)) { + /* Put the string into stringstream to parse parameters at spaces. + * We use stringstream as it handles multiple spaces etc nicely. + */ + std::stringstream ss(msg_content); + std::string command; + ss >> command; + /* Prefixed command, the prefix was removed */ + auto found_cmd = commands.find(lowercase(command)); + if (found_cmd != commands.end()) { + /* Filter out guild specific commands that are not for the current guild */ + if (found_cmd->second.guild_id && found_cmd->second.guild_id != msg.guild_id) { + return; + } + + parameter_list_t call_params; + + /* Command found; parse parameters */ + for (auto& p : found_cmd->second.parameters) { + command_parameter param; + + /* Check for end of stream */ + if (!ss) { + /* If it's an optional param, we dont care */ + if (!p.second.optional) { + /* Trigger missing parameter handler? */ + } + break; + } + + switch (p.second.type) { + case pt_string: { + std::string x; + ss >> x; + param = x; + } + break; + case pt_role: { + std::string x; + ss >> x; + if (x.length() > 4 && x[0] == '<' && x[1] == '&') { + snowflake rid = from_string(x.substr(2, x.length() - 1), std::dec); + role* r = dpp::find_role(rid); + if (r) { + param = *r; + } + } + } + break; + case pt_channel: { + std::string x; + ss >> x; + if (x.length() > 4 && x[0] == '<' && x[1] == '#') { + snowflake cid = from_string(x.substr(2, x.length() - 1), std::dec); + channel* c = dpp::find_channel(cid); + if (c) { + param = *c; + } + } + } + break; + case pt_user: { + std::string x; + ss >> x; + if (x.length() > 4 && x[0] == '<' && x[1] == '@') { + snowflake uid = from_string(x.substr(2, x.length() - 1), std::dec); + user* u = dpp::find_user(uid); + if (u) { + param = *u; + } + } + } + break; + case pt_integer: { + int32_t x = 0; + ss >> x; + param = x; + } + case pt_boolean: { + std::string x; + bool y = false; + ss >> x; + x = lowercase(x); + if (x == "yes" || x == "1" || x == "true") { + y = true; + } + param = y; + } + break; + } + + /* Add parameter to the list */ + call_params.push_back(std::make_pair(p.first, param)); + } + + /* Call command handler */ + command_source source; + source.command_id = 0; + source.guild_id = msg.guild_id; + source.channel_id = msg.channel_id; + source.issuer = msg.author; + found_cmd->second.func(command, call_params, source); + } + } +} + +void commandhandler::route(const interaction_create_t & event) +{ + /* We don't need to check for prefixes here, slash command interactions + * dont have prefixes at all. + */ + command_interaction cmd = std::get(event.command.data); + auto found_cmd = commands.find(lowercase(cmd.name)); + if (found_cmd != commands.end()) { + /* Command found; parse parameters */ + parameter_list_t call_params; + for (auto& p : found_cmd->second.parameters) { + command_parameter param; + const command_value& slash_parameter = event.get_parameter(p.first); + + if (p.second.optional && slash_parameter.valueless_by_exception()) { + /* Missing optional parameter, skip this */ + continue; + } + + try { + switch (p.second.type) { + case pt_string: { + std::string s = std::get(slash_parameter); + param = s; + } + break; + case pt_role: { + snowflake rid = std::get(slash_parameter); + role* r = dpp::find_role(rid); + if (r) { + param = *r; + } + } + break; + case pt_channel: { + snowflake cid = std::get(slash_parameter); + channel* c = dpp::find_channel(cid); + if (c) { + param = *c; + } + } + break; + case pt_user: { + snowflake uid = std::get(slash_parameter); + user* u = dpp::find_user(uid); + if (u) { + param = *u; + } + } + break; + case pt_integer: { + int32_t i = std::get(slash_parameter); + param = i; + } + case pt_boolean: { + bool b = std::get(slash_parameter); + param = b; + } + break; + } + } + catch (const std::bad_variant_access& e) { + /* Missing optional parameter, skip this */ + continue; + } + + /* Add parameter to the list */ + call_params.push_back(std::make_pair(p.first, param)); + } + + /* Call command handler */ + command_source source; + source.command_id = event.command.id; + source.command_token = event.command.token; + source.guild_id = event.command.guild_id; + source.channel_id = event.command.channel_id; + source.issuer = (user*)&event.command.usr; + found_cmd->second.func(cmd.name, call_params, source); + } +} + +void commandhandler::reply(const dpp::message &m, command_source source) +{ + dpp::message msg = m; + msg.guild_id = source.guild_id; + msg.channel_id = source.channel_id; + if (!source.command_token.empty() && source.command_id) { + owner->interaction_response_create(source.command_id, source.command_token, dpp::interaction_response(ir_channel_message_with_source, msg)); + } else { + owner->message_create(msg); + } +} + +}; \ No newline at end of file diff --git a/vendor/DPP/src/dpp/discordclient.cpp b/vendor/DPP/src/dpp/discordclient.cpp new file mode 100644 index 00000000..fe34f898 --- /dev/null +++ b/vendor/DPP/src/dpp/discordclient.cpp @@ -0,0 +1,625 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#ifndef WIN32 +#include +#endif +#include +#include +#include +#include +#include +#include +#include + +#define PATH_UNCOMPRESSED "/?v=" DISCORD_API_VERSION "&encoding=json" +#define PATH_COMPRESSED "/?v=" DISCORD_API_VERSION "&encoding=json&compress=zlib-stream" +#define DECOMP_BUFFER_SIZE 512 * 1024 + +namespace dpp { + +/* This is an internal class, defined externally as just a forward declaration for an opaque pointer. + * This is because we don't want an external dependency on zlib's headers + */ +class zlibcontext { +public: + z_stream d_stream; +}; + +discord_client::discord_client(dpp::cluster* _cluster, uint32_t _shard_id, uint32_t _max_shards, const std::string &_token, uint32_t _intents, bool comp) + : websocket_client(DEFAULT_GATEWAY, "443", comp ? PATH_COMPRESSED : PATH_UNCOMPRESSED), + creator(_cluster), + shard_id(_shard_id), + max_shards(_max_shards), + token(_token), + last_heartbeat(time(NULL)), + heartbeat_interval(0), + reconnects(0), + resumes(0), + last_seq(0), + sessionid(""), + intents(_intents), + runner(nullptr), + compressed(comp), + decompressed_total(0), + decomp_buffer(nullptr), + ready(false), + ping_start(0.0), + websocket_ping(0.0) +{ + zlib = new zlibcontext(); + Connect(); +} + +discord_client::~discord_client() +{ + if (runner) { + runner->join(); + delete runner; + } + delete zlib; +} + +uint64_t discord_client::get_decompressed_bytes_in() +{ + return decompressed_total; +} + +void discord_client::SetupZLib() +{ + if (compressed) { + zlib->d_stream.zalloc = (alloc_func)0; + zlib->d_stream.zfree = (free_func)0; + zlib->d_stream.opaque = (voidpf)0; + if (inflateInit(&(zlib->d_stream)) != Z_OK) { + throw dpp::exception("Can't initialise stream compression!"); + } + this->decomp_buffer = new unsigned char[DECOMP_BUFFER_SIZE]; + } + +} + +void discord_client::EndZLib() +{ + if (compressed) { + inflateEnd(&(zlib->d_stream)); + if (this->decomp_buffer) { + delete[] this->decomp_buffer; + this->decomp_buffer = nullptr; + } + } +} + +void discord_client::ThreadRun() +{ + SetupZLib(); + do { + bool error = false; + ready = false; + message_queue.clear(); + ssl_client::read_loop(); + ssl_client::close(); + EndZLib(); + SetupZLib(); + do { + error = false; + try { + ssl_client::Connect(); + websocket_client::Connect(); + } + catch (const std::exception &e) { + log(dpp::ll_error, std::string("Error establishing connection, retry in 5 seconds: ") + e.what()); + ssl_client::close(); + std::this_thread::sleep_for(std::chrono::seconds(5)); + error = true; + } + } while (error); + } while(true); +} + +void discord_client::Run() +{ + this->runner = new std::thread(&discord_client::ThreadRun, this); + this->thread_id = runner->native_handle(); +} + +bool discord_client::HandleFrame(const std::string &buffer) +{ + std::string& data = (std::string&)buffer; + + /* gzip compression is a special case */ + if (compressed) { + /* Check that we have a complete compressed frame */ + if ((uint8_t)buffer[buffer.size() - 4] == 0x00 && (uint8_t)buffer[buffer.size() - 3] == 0x00 && (uint8_t)buffer[buffer.size() - 2] == 0xFF + && (uint8_t)buffer[buffer.size() - 1] == 0xFF) { + /* Decompress buffer */ + decompressed.clear(); + zlib->d_stream.next_in = (Bytef *)buffer.c_str(); + zlib->d_stream.avail_in = buffer.size(); + do { + int have = 0; + zlib->d_stream.next_out = (Bytef*)decomp_buffer; + zlib->d_stream.avail_out = DECOMP_BUFFER_SIZE; + int ret = inflate(&(zlib->d_stream), Z_NO_FLUSH); + have = DECOMP_BUFFER_SIZE - zlib->d_stream.avail_out; + switch (ret) + { + case Z_NEED_DICT: + case Z_STREAM_ERROR: + this->Error(6000); + this->close(); + return true; + break; + case Z_DATA_ERROR: + this->Error(6001); + this->close(); + return true; + break; + case Z_MEM_ERROR: + this->Error(6002); + this->close(); + return true; + break; + case Z_OK: + this->decompressed.append((const char*)decomp_buffer, have); + this->decompressed_total += have; + break; + default: + /* Stub */ + break; + } + } while (zlib->d_stream.avail_out == 0); + data = decompressed; + } else { + /* No complete compressed frame yet */ + return false; + } + } + + + log(dpp::ll_trace, fmt::format("R: {}", data)); + json j; + + try { + j = json::parse(data); + } + catch (const std::exception &e) { + log(dpp::ll_error, fmt::format("discord_client::HandleFrame {} [{}]", e.what(), data)); + return true; + } + + if (j.find("s") != j.end() && !j["s"].is_null()) { + last_seq = j["s"].get(); + } + + if (j.find("op") != j.end()) { + uint32_t op = j["op"]; + + switch (op) { + case 9: + /* Reset session state and fall through to 10 */ + op = 10; + log(dpp::ll_debug, fmt::format("Failed to resume session {}, will reidentify", sessionid)); + this->sessionid = ""; + this->last_seq = 0; + /* No break here, falls through to state 10 to cause a reidentify */ + case 10: + /* Need to check carefully for the existence of this before we try to access it! */ + if (j.find("d") != j.end() && j["d"].find("heartbeat_interval") != j["d"].end() && !j["d"]["heartbeat_interval"].is_null()) { + this->heartbeat_interval = j["d"]["heartbeat_interval"].get(); + } + + if (last_seq && !sessionid.empty()) { + /* Resume */ + log(dpp::ll_debug, fmt::format("Resuming session {} with seq={}", sessionid, last_seq)); + json obj = { + { "op", 6 }, + { "d", { + {"token", this->token }, + {"session_id", this->sessionid }, + {"seq", this->last_seq } + } + } + }; + this->write(obj.dump()); + resumes++; + } else { + /* Full connect */ + while (time(NULL) < creator->last_identify + 5) { + uint32_t wait = (creator->last_identify + 5) - time(NULL); + log(dpp::ll_debug, fmt::format("Waiting {} seconds before identifying for session...", wait)); + std::this_thread::sleep_for(std::chrono::seconds(wait)); + } + log(dpp::ll_debug, "Connecting new session..."); + json obj = { + { "op", 2 }, + { + "d", + { + { "token", this->token }, + { "properties", + { + { "$os", "Linux" }, + { "$browser", "D++" }, + { "$device", "D++" } + } + }, + { "shard", json::array({ shard_id, max_shards }) }, + { "compress", false }, + { "large_threshold", 250 } + } + } + }; + if (this->intents) { + obj["d"]["intents"] = this->intents; + } + this->write(obj.dump()); + this->connect_time = creator->last_identify = time(NULL); + reconnects++; + } + this->last_heartbeat_ack = time(nullptr); + websocket_ping = 0; + break; + case 0: { + std::string event = j.find("t") != j.end() && !j["t"].is_null() ? j["t"] : ""; + + HandleEvent(event, j, data); + } + break; + case 7: + log(dpp::ll_debug, fmt::format("Reconnection requested, closing socket {}", sessionid)); + message_queue.clear(); + + shutdown(sfd, 2); + #ifdef _WIN32 + if (sfd >= 0 && sfd < FD_SETSIZE) { + closesocket(sfd); + } + #else + ::close(sfd); + #endif + + break; + /* Heartbeat ack */ + case 11: + this->last_heartbeat_ack = time(nullptr); + websocket_ping = utility::time_f() - ping_start; + break; + } + } + return true; +} + +dpp::utility::uptime discord_client::get_uptime() +{ + return dpp::utility::uptime(time(NULL) - connect_time); +} + +bool discord_client::is_connected() +{ + return (this->GetState() == CONNECTED) && (this->ready); +} + +void discord_client::Error(uint32_t errorcode) +{ + std::map errortext = { + { 1000, "Socket shutdown" }, + { 1001, "Client is leaving" }, + { 1002, "Endpoint received a malformed frame" }, + { 1003, "Endpoint received an unsupported frame" }, + { 1004, "Reserved code" }, + { 1005, "Expected close status, received none" }, + { 1006, "No close code frame has been receieved" }, + { 1007, "Endpoint received inconsistent message (e.g. malformed UTF-8)" }, + { 1008, "Generic error" }, + { 1009, "Endpoint won't process large frame" }, + { 1010, "Client wanted an extension which server did not negotiate" }, + { 1011, "Internal server error while operating" }, + { 1012, "Server/service is restarting" }, + { 1013, "Temporary server condition forced blocking client's request" }, + { 1014, "Server acting as gateway received an invalid response" }, + { 1015, "Transport Layer Security handshake failure" }, + { 4000, "Unknown error" }, + { 4001, "Unknown opcode" }, + { 4002, "Decode error" }, + { 4003, "Not authenticated" }, + { 4004, "Authentication failed" }, + { 4005, "Already authenticated" }, + { 4007, "Invalid seq" }, + { 4008, "Rate limited" }, + { 4009, "Session timed out" }, + { 4010, "Invalid shard" }, + { 4011, "Sharding required" }, + { 4012, "Invalid API version" }, + { 4013, "Invalid intent(s)" }, + { 4014, "Disallowed intent(s)" }, + { 6000, "ZLib Stream Error" }, + { 6001, "ZLib Data Error" }, + { 6002, "ZLib Memory Error" }, + { 6666, "Hell freezing over" } + }; + std::string error = "Unknown error"; + auto i = errortext.find(errorcode); + if (i != errortext.end()) { + error = i->second; + } + log(dpp::ll_warning, fmt::format("OOF! Error from underlying websocket: {}: {}", errorcode, error)); +} + +void discord_client::log(dpp::loglevel severity, const std::string &msg) const +{ + if (creator->dispatch.log) { + /* Pass to user if theyve hooked the event */ + dpp::log_t logmsg(nullptr, msg); + logmsg.severity = severity; + logmsg.message = msg; + creator->dispatch.log(logmsg); + } +} + +void discord_client::QueueMessage(const std::string &j, bool to_front) +{ + std::lock_guard locker(queue_mutex); + if (to_front) { + message_queue.push_front(j); + } else { + message_queue.push_back(j); + } +} + +void discord_client::ClearQueue() +{ + std::lock_guard locker(queue_mutex); + message_queue.clear(); +} + +size_t discord_client::GetQueueSize() +{ + std::lock_guard locker(queue_mutex); + return message_queue.size(); +} + +void discord_client::one_second_timer() +{ + + websocket_client::one_second_timer(); + + /* Every minute, rehash all containers from first shard. + * We can't just get shard with the id 0 because this won't + * work on a clustered environment + */ + auto shards = creator->get_shards(); + auto first_iter = shards.begin(); + if (first_iter != shards.end()) { + dpp::discord_client* first_shard = first_iter->second; + if ((time(NULL) % 60) == 0 && first_shard == this) { + dpp::garbage_collection(); + } + } + + /* This all only triggers if we are connected (have completed websocket, and received READY or RESUMED) */ + if (this->is_connected()) { + + /* If we stopped getting heartbeat acknowledgements, this means the connections is dead. + * This can happen to TCP connections which is why we have heartbeats in the first place. + * Miss two ACKS, forces a reconnection. + */ + if ((time(nullptr) - this->last_heartbeat_ack) > heartbeat_interval * 2) { + log(dpp::ll_warning, fmt::format("Missed heartbeat ACK, forcing reconnection to session {}", sessionid)); + message_queue.clear(); + + shutdown(sfd, 2); + #ifdef _WIN32 + if (sfd >= 0 && sfd < FD_SETSIZE) { + closesocket(sfd); + } + #else + ::close(sfd); + #endif + + return; + } + + /* Rate limit outbound messages, 1 every odd second, 2 every even second */ + for (int x = 0; x < (time(NULL) % 2) + 1; ++x) { + std::lock_guard locker(queue_mutex); + if (message_queue.size()) { + std::string message = message_queue.front(); + message_queue.pop_front(); + /* Checking here with .find() saves us having to deserialise the json + * to find pings in our queue. The assumption is that the format of the + * ping isn't going to change. + */ + if (message.find("\"op\":1}") != std::string::npos) { + ping_start = utility::time_f(); + } + this->write(message); + } + } + + /* Send pings (heartbeat opcodes) before each interval. We send them slightly more regular than expected, + * just to be safe. + */ + if (this->heartbeat_interval && this->last_seq) { + /* Check if we're due to emit a heartbeat */ + if (time(NULL) > last_heartbeat + ((heartbeat_interval / 1000.0) * 0.75)) { + QueueMessage(json({{"op", 1}, {"d", last_seq}}).dump(), true); + last_heartbeat = time(NULL); + } + } + } +} + +uint64_t discord_client::get_guild_count() { + uint64_t total = 0; + dpp::cache* c = dpp::get_guild_cache(); + dpp::cache_container& gc = c->get_container(); + /* IMPORTANT: We must lock the container to iterate it */ + std::lock_guard lock(c->get_mutex()); + for (auto g = gc.begin(); g != gc.end(); ++g) { + dpp::guild* gp = (dpp::guild*)g->second; + if (gp->shard_id == this->shard_id) { + total++; + } + } + return total; +} + +uint64_t discord_client::get_member_count() { + uint64_t total = 0; + dpp::cache* c = dpp::get_guild_cache(); + dpp::cache_container& gc = c->get_container(); + /* IMPORTANT: We must lock the container to iterate it */ + std::lock_guard lock(c->get_mutex()); + for (auto g = gc.begin(); g != gc.end(); ++g) { + dpp::guild* gp = (dpp::guild*)g->second; + if (gp->shard_id == this->shard_id) { + if (creator->cache_policy.user_policy == dpp::cp_aggressive) { + /* We can use actual member count if we are using full user caching */ + total += gp->members.size(); + } else { + /* Otherwise we use approximate guild member counts from guild_create */ + total += gp->member_count; + } + } + } + return total; +} + +uint64_t discord_client::get_channel_count() { + uint64_t total = 0; + dpp::cache* c = dpp::get_guild_cache(); + dpp::cache_container& gc = c->get_container(); + /* IMPORTANT: We must lock the container to iterate it */ + std::lock_guard lock(c->get_mutex()); + for (auto g = gc.begin(); g != gc.end(); ++g) { + dpp::guild* gp = (dpp::guild*)g->second; + if (gp->shard_id == this->shard_id) { + total += gp->channels.size(); + } + } + return total; +} + +void discord_client::connect_voice(snowflake guild_id, snowflake channel_id) { +#ifdef HAVE_VOICE + std::lock_guard lock(voice_mutex); + if (connecting_voice_channels.find(guild_id) == connecting_voice_channels.end()) { + connecting_voice_channels[guild_id] = new voiceconn(this, channel_id); + /* Once sent, this expects two events (in any order) on the websocket: + * VOICE_SERVER_UPDATE and VOICE_STATUS_UPDATE + */ + log(ll_debug, fmt::format("Sending op 4, guild {}", guild_id)); + QueueMessage(json({ + { "op", 4 }, + { "d", { + { "guild_id", std::to_string(guild_id) }, + { "channel_id", std::to_string(channel_id) }, + { "self_mute", false }, + { "self_deaf", false }, + } + } + }).dump(), false); + } +#endif +} + +void discord_client::disconnect_voice(snowflake guild_id) { +#ifdef HAVE_VOICE + std::lock_guard lock(voice_mutex); + auto v = connecting_voice_channels.find(guild_id); + if (v != connecting_voice_channels.end()) { + log(ll_debug, fmt::format("Disconnecting voice, guild: {}", guild_id)); + QueueMessage(json({ + { "op", 4 }, + { "d", { + { "guild_id", std::to_string(guild_id) }, + { "channel_id", json::value_t::null }, + { "self_mute", false }, + { "self_deaf", false }, + } + } + }).dump(), false); + delete v->second; + v->second = nullptr; + connecting_voice_channels.erase(v); + } +#endif +} + +voiceconn* discord_client::get_voice(snowflake guild_id) { +#ifdef HAVE_VOICE + std::lock_guard lock(voice_mutex); + auto v = connecting_voice_channels.find(guild_id); + if (v != connecting_voice_channels.end()) { + return v->second; + } +#endif + return nullptr; +} + + +voiceconn::voiceconn(discord_client* o, snowflake _channel_id) : creator(o), channel_id(_channel_id), voiceclient(nullptr) { +} + +bool voiceconn::is_ready() { + return (!websocket_hostname.empty() && !session_id.empty() && !token.empty()); +} + +bool voiceconn::is_active() { + return voiceclient != nullptr; +} + +void voiceconn::disconnect() { + if (this->is_active()) { + voiceclient->terminating = true; + voiceclient->close(); + delete voiceclient; + voiceclient = nullptr; + } +} + +voiceconn::~voiceconn() { + this->disconnect(); +} + +void voiceconn::connect(snowflake guild_id) { + if (this->is_ready() && !this->is_active()) { + /* This is wrapped in a thread because instantiating discord_voice_client can initiate a blocking SSL_connect() */ + auto t = std::thread([guild_id, this]() { + try { + this->creator->log(ll_debug, fmt::format("Connecting voice for guild {} channel {}", guild_id, this->channel_id)); + this->voiceclient = new discord_voice_client(creator->creator, this->channel_id, guild_id, this->token, this->session_id, this->websocket_hostname); + /* Note: Spawns thread! */ + this->voiceclient->Run(); + } + catch (std::exception &e) { + this->creator->log(ll_error, fmt::format("Can't connect to voice websocket (guild_id: {}, channel_id: {}): {}", guild_id, this->channel_id, e.what())); + } + }); + t.detach(); + } +} + + +}; \ No newline at end of file diff --git a/vendor/DPP/src/dpp/discordevents.cpp b/vendor/DPP/src/dpp/discordevents.cpp new file mode 100644 index 00000000..6d770f40 --- /dev/null +++ b/vendor/DPP/src/dpp/discordevents.cpp @@ -0,0 +1,325 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#define _XOPEN_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef _WIN32 +#include +#include +#include + +char* strptime(const char* s, const char* f, struct tm* tm) { + std::istringstream input(s); + input.imbue(std::locale(setlocale(LC_ALL, nullptr))); + input >> std::get_time(tm, f); + if (input.fail()) { + return const_cast< char* >(""); + } + return (char*)(s + input.tellg()); +} +#endif + +namespace dpp { + +uint64_t SnowflakeNotNull(const json* j, const char *keyname) { + /* Snowflakes are a special case. Pun intended. + * Because discord drinks the javascript kool-aid, they have to send 64 bit integers as strings as js can't deal with them + * even though we can. So, all snowflakes are sent and received wrapped as string values and must be read by nlohmann::json + * as string types, then converted from string to uint64_t. Checks for existence of the value, and that it is a string containing + * a number. If not, then this function returns 0. + */ + auto k = j->find(keyname); + if (k != j->end()) { + return !k->is_null() && k->is_string() ? strtoull(k->get().c_str(), nullptr, 10) : 0; + } else { + return 0; + } +} + +void SetSnowflakeNotNull(const json* j, const char *keyname, uint64_t &v) { + auto k = j->find(keyname); + if (k != j->end()) { + v = !k->is_null() && k->is_string() ? strtoull(k->get().c_str(), nullptr, 10) : 0; + } +} + + +std::string StringNotNull(const json* j, const char *keyname) { + /* Returns empty string if the value is not a string, or is null or not defined */ + auto k = j->find(keyname); + if (k != j->end()) { + return !k->is_null() && k->is_string() ? k->get() : ""; + } else { + return ""; + } +} + +void SetStringNotNull(const json* j, const char *keyname, std::string &v) { + /* Returns empty string if the value is not a string, or is null or not defined */ + auto k = j->find(keyname); + if (k != j->end()) { + v = !k->is_null() && k->is_string() ? k->get() : ""; + } +} + +uint64_t Int64NotNull(const json* j, const char *keyname) { + auto k = j->find(keyname); + if (k != j->end()) { + return !k->is_null() && !k->is_string() ? k->get() : 0; + } else { + return 0; + } +} + +void SetInt64NotNull(const json* j, const char *keyname, uint64_t &v) { + auto k = j->find(keyname); + if (k != j->end()) { + v = !k->is_null() && !k->is_string() ? k->get() : 0; + } +} + + +uint32_t Int32NotNull(const json* j, const char *keyname) { + auto k = j->find(keyname); + if (k != j->end()) { + return !k->is_null() && !k->is_string() ? k->get() : 0; + } else { + return 0; + } +} + +void SetInt32NotNull(const json* j, const char *keyname, uint32_t &v) { + auto k = j->find(keyname); + if (k != j->end()) { + v = !k->is_null() && !k->is_string() ? k->get() : 0; + } +} + +uint16_t Int16NotNull(const json* j, const char *keyname) { + auto k = j->find(keyname); + if (k != j->end()) { + return !k->is_null() && !k->is_string() ? k->get() : 0; + } else { + return 0; + } +} + +void SetInt16NotNull(const json* j, const char *keyname, uint16_t &v) { + auto k = j->find(keyname); + if (k != j->end()) { + v = !k->is_null() && !k->is_string() ? k->get() : 0; + } +} + +uint8_t Int8NotNull(const json* j, const char *keyname) { + auto k = j->find(keyname); + if (k != j->end()) { + return !k->is_null() && !k->is_string() ? k->get() : 0; + } else { + return 0; + } +} + +void SetInt8NotNull(const json* j, const char *keyname, uint8_t &v) { + auto k = j->find(keyname); + if (k != j->end()) { + v = !k->is_null() && !k->is_string() ? k->get() : 0; + } +} + +bool BoolNotNull(const json* j, const char *keyname) { + auto k = j->find(keyname); + if (k != j->end()) { + return !k->is_null() ? (k->get() == true) : false; + } else { + return false; + } +} + +void SetBoolNotNull(const json* j, const char *keyname, bool &v) { + auto k = j->find(keyname); + if (k != j->end()) { + v = !k->is_null() ? (k->get() == true) : false; + } +} + +std::string base64_encode(unsigned char const* buf, unsigned int buffer_length) { + /* Quick and dirty base64 encode */ + static const char to_base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + size_t ret_size = buffer_length + 2; + + ret_size = 4 * ret_size / 3; + + std::string ret; + ret.reserve(ret_size); + + for (unsigned int i=0; i> 2) ]); + ret.push_back(to_base64[ ((b3[0] & 0x03) << 4) + ((b3[1] & 0xf0) >> 4) ]); + ret.push_back(to_base64[ ((b3[1] & 0x0f) << 2) + ((b3[2] & 0xc0) >> 6) ]); + ret.push_back(to_base64[ ((b3[2] & 0x3f)) ]); + } + + return ret; +} + +time_t TimestampNotNull(const json* j, const char* keyname) +{ + /* Parses discord ISO 8061 timestamps to time_t, accounting for local time adjustment. + * Note that discord timestamps contain a decimal seconds part, which time_t and struct tm + * can't handle. We strip these out. + */ + time_t retval = 0; + if (j->find(keyname) != j->end() && !(*j)[keyname].is_null() && (*j)[keyname].is_string()) { + tm timestamp = {}; + std::string timedate = (*j)[keyname].get(); + if (timedate.find('+') != std::string::npos && timedate.find('.') != std::string::npos) { + std::string tzpart = timedate.substr(timedate.find('+'), timedate.length()); + timedate = timedate.substr(0, timedate.find('.')) + tzpart ; + strptime(timedate.substr(0, 19).c_str(), "%FT%TZ%z", ×tamp); + timestamp.tm_isdst = 0; + retval = mktime(×tamp); + } else { + strptime(timedate.substr(0, 19).c_str(), "%F %T", ×tamp); + retval = mktime(×tamp); + } + } + return retval; +} + +void SetTimestampNotNull(const json* j, const char* keyname, time_t &v) +{ + /* Parses discord ISO 8061 timestamps to time_t, accounting for local time adjustment. + * Note that discord timestamps contain a decimal seconds part, which time_t and struct tm + * can't handle. We strip these out. + */ + time_t retval = 0; + if (j->find(keyname) != j->end() && !(*j)[keyname].is_null() && (*j)[keyname].is_string()) { + tm timestamp = {}; + std::string timedate = (*j)[keyname].get(); + if (timedate.find('+') != std::string::npos && timedate.find('.') != std::string::npos) { + std::string tzpart = timedate.substr(timedate.find('+'), timedate.length()); + timedate = timedate.substr(0, timedate.find('.')) + tzpart ; + strptime(timedate.substr(0, 19).c_str(), "%FT%TZ%z", ×tamp); + timestamp.tm_isdst = 0; + retval = mktime(×tamp); + } else { + strptime(timedate.substr(0, 19).c_str(), "%F %T", ×tamp); + retval = mktime(×tamp); + } + v = retval; + } +} + +std::map eventmap = { + { "__LOG__", new dpp::events::logger() }, + { "GUILD_CREATE", new dpp::events::guild_create() }, + { "GUILD_UPDATE", new dpp::events::guild_update() }, + { "GUILD_DELETE", new dpp::events::guild_delete() }, + { "GUILD_MEMBER_UPDATE", new dpp::events::guild_member_update() }, + { "RESUMED", new dpp::events::resumed() }, + { "READY", new dpp::events::ready() }, + { "CHANNEL_CREATE", new dpp::events::channel_create() }, + { "CHANNEL_UPDATE", new dpp::events::channel_update() }, + { "CHANNEL_DELETE", new dpp::events::channel_delete() }, + { "PRESENCE_UPDATE", new dpp::events::presence_update() }, + { "TYPING_START", new dpp::events::typing_start() }, + { "MESSAGE_CREATE", new dpp::events::message_create() }, + { "MESSAGE_UPDATE", new dpp::events::message_update() }, + { "MESSAGE_DELETE", new dpp::events::message_delete() }, + { "MESSAGE_DELETE_BULK", new dpp::events::message_delete_bulk() }, + { "MESSAGE_REACTION_ADD", new dpp::events::message_reaction_add() }, + { "MESSAGE_REACTION_REMOVE", new dpp::events::message_reaction_remove() }, + { "MESSAGE_REACTION_REMOVE_ALL", new dpp::events::message_reaction_remove_all() }, + { "MESSAGE_REACTION_REMOVE_EMOJI", new dpp::events::message_reaction_remove_emoji() }, + { "CHANNEL_PINS_UPDATE", new dpp::events::channel_pins_update() }, + { "GUILD_BAN_ADD", new dpp::events::guild_ban_add() }, + { "GUILD_BAN_REMOVE", new dpp::events::guild_ban_remove() }, + { "GUILD_EMOJIS_UPDATE", new dpp::events::guild_emojis_update() }, + { "GUILD_INTEGRATIONS_UPDATE", new dpp::events::guild_integrations_update() }, + { "INTEGRATION_CREATE", new dpp::events::integration_create() }, + { "INTEGRATION_UPDATE", new dpp::events::integration_update() }, + { "INTEGRATION_DELETE", new dpp::events::integration_delete() }, + { "GUILD_MEMBER_ADD", new dpp::events::guild_member_add() }, + { "GUILD_MEMBER_REMOVE", new dpp::events::guild_member_remove() }, + { "GUILD_MEMBERS_CHUNK", new dpp::events::guild_members_chunk() }, + { "GUILD_ROLE_CREATE", new dpp::events::guild_role_create() }, + { "GUILD_ROLE_UPDATE", new dpp::events::guild_role_update() }, + { "GUILD_ROLE_DELETE", new dpp::events::guild_role_delete() }, + { "VOICE_STATE_UPDATE", new dpp::events::voice_state_update() }, + { "VOICE_SERVER_UPDATE", new dpp::events::voice_server_update() }, + { "WEBHOOKS_UPDATE", new dpp::events::webhooks_update() }, + { "INVITE_CREATE", new dpp::events::invite_create() }, + { "INVITE_DELETE", new dpp::events::invite_delete() }, + { "APPLICATION_COMMAND_CREATE", new dpp::events::application_command_create() }, + { "APPLICATION_COMMAND_UPDATE", new dpp::events::application_command_update() }, + { "APPLICATION_COMMAND_DELETE", new dpp::events::application_command_delete() }, + { "INTERACTION_CREATE", new dpp::events::interaction_create() }, + { "USER_UPDATE", new dpp::events::user_update() }, + { "GUILD_JOIN_REQUEST_DELETE", new dpp::events::guild_join_request_delete() }, + { "STAGE_INSTANCE_CREATE", new dpp::events::stage_instance_create() }, + { "STAGE_INSTANCE_DELETE", new dpp::events::stage_instance_delete() }, + { "THREAD_CREATE", new dpp::events::thread_create() }, + { "THREAD_UPDATE", new dpp::events::thread_update() }, + { "THREAD_DELETE", new dpp::events::thread_delete() }, + { "THREAD_LIST_SYNC", new dpp::events::thread_list_sync() }, + { "THREAD_MEMBER_UPDATE", new dpp::events::thread_member_update() }, + { "THREAD_MEMBERS_UPDATE", new dpp::events::thread_members_update() }, + { "GUILD_APPLICATION_COMMAND_COUNTS_UPDATE", nullptr }, + { "GUILD_STICKERS_UPDATE", new dpp::events::guild_stickers_update() }, + { "APPLICATION_COMMAND_PERMISSIONS_UPDATE", nullptr }, +}; + +void discord_client::HandleEvent(const std::string &event, json &j, const std::string &raw) +{ + auto ev_iter = eventmap.find(event); + if (ev_iter != eventmap.end()) { + /* A handler with nullptr is silently ignored. We don't plan to make a handler for it + * so this usually some user-only thing thats crept into the API and shown to bots + * that we dont care about. + */ + if (ev_iter->second != nullptr) { + ev_iter->second->handle(this, j, raw); + } + } else { + log(dpp::ll_debug, fmt::format("Unhandled event: {}, {}", event, j.dump())); + } +} + +}; diff --git a/vendor/DPP/src/dpp/discordvoiceclient.cpp b/vendor/DPP/src/dpp/discordvoiceclient.cpp new file mode 100644 index 00000000..2b079e2f --- /dev/null +++ b/vendor/DPP/src/dpp/discordvoiceclient.cpp @@ -0,0 +1,747 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#ifndef WIN32 +#include +#include +#endif +#include +#include +#include +#include +#include +#include +#include + +namespace dpp { + +std::string external_ip; + +/** + * @brief Represents an RTP packet. Size should always be exactly 12. + */ +struct rtp_header { + uint16_t constant; + uint16_t sequence; + uint32_t timestamp; + uint32_t ssrc; + + rtp_header(uint16_t _seq, uint32_t _ts, uint32_t _ssrc) : constant(htons(0x8078)), sequence(htons(_seq)), timestamp(htonl(_ts)), ssrc(htonl(_ssrc)) { + } +}; + +bool discord_voice_client::sodium_initialised = false; + +discord_voice_client::discord_voice_client(dpp::cluster* _cluster, snowflake _channel_id, snowflake _server_id, const std::string &_token, const std::string &_session_id, const std::string &_host) + : websocket_client(_host.substr(0, _host.find(":")), _host.substr(_host.find(":") + 1, _host.length()), "/?v=4"), + creator(_cluster), + channel_id(_channel_id), + server_id(_server_id), + token(_token), + last_heartbeat(time(NULL)), + heartbeat_interval(0), + sessionid(_session_id), + runner(nullptr), + terminating(false), + fd(-1), + secret_key(nullptr), + sequence(0), + timestamp(0), + sending(false), + paused(false), + tracks(0) +{ +#if HAVE_VOICE + if (!discord_voice_client::sodium_initialised) { + if (sodium_init() < 0) { + throw dpp::exception("discord_voice_client::discord_voice_client; sodium_init() failed"); + } + int opusError = 0; + encoder = opus_encoder_create(48000, 2, OPUS_APPLICATION_VOIP, &opusError); + if (opusError) { + throw dpp::exception(fmt::format("discord_voice_client::discord_voice_client; opus_encoder_create() failed: {}", opusError)); + } + opusError = 0; + decoder = opus_decoder_create(48000, 2, &opusError); + if (opusError) { + throw dpp::exception(fmt::format("discord_voice_client::discord_voice_client; opus_decoder_create() failed: {}", opusError)); + } + repacketizer = opus_repacketizer_create(); + discord_voice_client::sodium_initialised = true; + } + Connect(); +#endif +} + +discord_voice_client::~discord_voice_client() +{ + if (runner) { + this->terminating = true; + runner->join(); + delete runner; + runner = nullptr; + } +#if HAVE_VOICE + if (encoder) { + opus_encoder_destroy(encoder); + encoder = nullptr; + } + if (decoder) { + opus_decoder_destroy(decoder); + decoder = nullptr; + } + if (repacketizer) { + opus_repacketizer_destroy(repacketizer); + repacketizer = nullptr; + } +#endif + if (secret_key) { + delete[] secret_key; + secret_key = nullptr; + } +} + +bool discord_voice_client::is_ready() { + return secret_key != nullptr; +} + +bool discord_voice_client::is_playing() { + std::lock_guard lock(this->stream_mutex); + return (!this->outbuf.empty()); +} + +void discord_voice_client::ThreadRun() +{ + do { + ssl_client::read_loop(); + ssl_client::close(); + if (!terminating) { + ssl_client::Connect(); + websocket_client::Connect(); + } + } while(!terminating); +} + +void discord_voice_client::Run() +{ + this->runner = new std::thread(&discord_voice_client::ThreadRun, this); + this->thread_id = runner->native_handle(); +} + +int discord_voice_client::UDPSend(const char* data, size_t length) +{ + memset(&servaddr, 0, sizeof(servaddr)); + servaddr.sin_family = AF_INET; + servaddr.sin_port = htons(this->port); + servaddr.sin_addr.s_addr = inet_addr(this->ip.c_str()); + return sendto(this->fd, data, length, 0, (const struct sockaddr*)&servaddr, sizeof(sockaddr_in)); +} + +int discord_voice_client::UDPRecv(char* data, size_t max_length) +{ + struct sockaddr sa; + socklen_t sl; + return recvfrom(this->fd, data, max_length, 0, (struct sockaddr*)&sa, &sl); +} + +bool discord_voice_client::HandleFrame(const std::string &data) +{ + log(dpp::ll_trace, fmt::format("R: {}", data)); + json j; + + try { + j = json::parse(data); + } + catch (const std::exception &e) { + log(dpp::ll_error, fmt::format("discord_voice_client::HandleFrame {} [{}]", e.what(), data)); + return true; + } + + if (j.find("op") != j.end()) { + uint32_t op = j["op"]; + + switch (op) { + /* Voice resume */ + case 9: + log(ll_debug, "Voice connection resumed"); + break; + /* Voice HELLO */ + case 8: { + if (j.find("d") != j.end() && j["d"].find("heartbeat_interval") != j["d"].end() && !j["d"]["heartbeat_interval"].is_null()) { + this->heartbeat_interval = j["d"]["heartbeat_interval"].get(); + } + + if (modes.size()) { + log(dpp::ll_debug, "Resuming voice session..."); + json obj = { + { "op", 7 }, + { + "d", + { + { "server_id", std::to_string(this->server_id) }, + { "session_id", this->sessionid }, + { "token", this->token }, + } + } + }; + this->write(obj.dump()); + } else { + log(dpp::ll_debug, "Connecting new voice session..."); + json obj = { + { "op", 0 }, + { + "d", + { + { "user_id", creator->me.id }, + { "server_id", std::to_string(this->server_id) }, + { "session_id", this->sessionid }, + { "token", this->token }, + } + } + }; + this->write(obj.dump()); + } + this->connect_time = time(NULL); + } + break; + /* Session description */ + case 4: { + json &d = j["d"]; + secret_key = new uint8_t[32]; + size_t ofs = 0; + for (auto & c : d["secret_key"]) { + *(secret_key + ofs) = (uint8_t)c; + ofs++; + if (ofs > 31) { + break; + } + } + if (creator->dispatch.voice_ready) { + voice_ready_t rdy(nullptr, data); + rdy.voice_client = this; + rdy.voice_channel_id = this->channel_id; + creator->dispatch.voice_ready(rdy); + } + } + break; + /* Voice ready */ + case 2: { + /* Video stream stuff comes in this frame too, but we can't use it (YET!) */ + json &d = j["d"]; + this->ip = d["ip"].get(); + this->port = d["port"].get(); + this->ssrc = d["ssrc"].get(); + // Modes + for (auto & m : d["modes"]) { + this->modes.push_back(m.get()); + } + log(ll_debug, fmt::format("Voice websocket established; UDP endpoint: {}:{} [ssrc={}] with {} modes", ip, port, ssrc, modes.size())); + + external_ip = discover_ip(); + + int newfd = -1; + if ((newfd = socket(AF_INET, SOCK_DGRAM, 0)) >= 0) { + + sockaddr_in servaddr; + memset(&servaddr, 0, sizeof(sockaddr_in)); + servaddr.sin_family = AF_INET; + servaddr.sin_addr.s_addr = htonl(INADDR_ANY); + servaddr.sin_port = htons(0); + + if (bind(newfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) < 0) { + throw dpp::exception("Can't bind() client UDP socket"); + } + +#ifdef _WIN32 + u_long mode = 1; + int result = ioctlsocket(newfd, FIONBIO, &mode); + if (result != NO_ERROR) + throw dpp::exception("Can't switch socket to non-blocking mode!"); +#else + int ofcmode; + ofcmode = fcntl(newfd, F_GETFL, 0); + ofcmode |= O_NDELAY; + if (fcntl(newfd, F_SETFL, ofcmode)) { + throw dpp::exception("Can't switch socket to non-blocking mode!"); + } +#endif + /* Hook select() in the ssl_client to add a new file descriptor */ + this->fd = newfd; + this->custom_writeable_fd = std::bind(&discord_voice_client::WantWrite, this); + this->custom_readable_fd = std::bind(&discord_voice_client::WantRead, this); + this->custom_writeable_ready = std::bind(&discord_voice_client::WriteReady, this); + this->custom_readable_ready = std::bind(&discord_voice_client::ReadReady, this); + + int bound_port = 0; + struct sockaddr_in sin; + socklen_t len = sizeof(sin); + if (getsockname(this->fd, (struct sockaddr *)&sin, &len) > -1) { + bound_port = ntohs(sin.sin_port); + } + + log(ll_debug, fmt::format("External IP address: {}", external_ip)); + + this->write(json({ + { "op", 1 }, + { "d", { + { "protocol", "udp" }, + { "data", { + { "address", external_ip }, + { "port", bound_port }, + { "mode", "xsalsa20_poly1305" } + } + } + } + } + }).dump()); + } + } + break; + } + } + return true; +} + +void discord_voice_client::pause_audio(bool pause) { + this->paused = pause; +} + +bool discord_voice_client::is_paused() { + return this->paused; +} + +float discord_voice_client::get_secs_remaining() { + std::lock_guard lock(this->stream_mutex); + /* Audio stream sends one packet every 60ms which means there are 16.666 packets per second */ + return (outbuf.size() / 16.666666); +} + +dpp::utility::uptime discord_voice_client::get_remaining() { + float fp_secs = get_secs_remaining(); + return dpp::utility::uptime((time_t)ceil(fp_secs)); +} + +void discord_voice_client::stop_audio() { + std::lock_guard lock(this->stream_mutex); + outbuf.clear(); +} + +void discord_voice_client::Send(const char* packet, size_t len) { + std::lock_guard lock(this->stream_mutex); + outbuf.push_back(std::string(packet, len)); +} + +void discord_voice_client::ReadReady() +{ + /* XXX Decoding of voice not currently supported. + * Audio stream will always be a nullptr until then. + * See: https://github.com/discord/discord-api-docs/issues/365 + * See also: https://github.com/discord/discord-api-docs/issues/1337 + */ + uint8_t buffer[65535]; + int r = this->UDPRecv((char*)buffer, sizeof(buffer)); + if (r > 0 && creator->dispatch.voice_receive) { + voice_receive_t vr(nullptr, std::string((const char*)buffer, r)); + vr.voice_client = this; + vr.audio = nullptr; + vr.audio_size = 0; + creator->dispatch.voice_receive(vr); + } +} + +void discord_voice_client::WriteReady() +{ + bool call_event = false; + bool track_marker_found = false; + uint64_t bufsize = 0; + { + std::lock_guard lock(this->stream_mutex); + if (!this->paused && outbuf.size()) { + + if (outbuf[0].size() == 2 && ((uint16_t)(*(outbuf[0].data()))) == AUDIO_TRACK_MARKER) { + outbuf.erase(outbuf.begin()); + track_marker_found = true; + if (tracks > 0) + tracks--; + } + if (outbuf.size()) { + if (this->UDPSend(outbuf[0].data(), outbuf[0].length()) == outbuf[0].length()) { + outbuf.erase(outbuf.begin()); + call_event = true; + bufsize = outbuf.size(); + } + } + } + } + if (call_event) { + std::this_thread::sleep_for(std::chrono::milliseconds(60)); + if (creator->dispatch.voice_buffer_send) { + voice_buffer_send_t snd(nullptr, ""); + snd.buffer_size = bufsize; + snd.voice_client = this; + creator->dispatch.voice_buffer_send(snd); + } + } + if (track_marker_found) { + if (creator->dispatch.voice_track_marker) { + voice_track_marker_t vtm(nullptr, ""); + vtm.voice_client = this; + { + std::lock_guard lock(this->stream_mutex); + if (track_meta.size()) { + vtm.track_meta = track_meta[0]; + track_meta.erase(track_meta.begin()); + } + } + creator->dispatch.voice_track_marker(vtm); + } + } +} + +dpp::utility::uptime discord_voice_client::get_uptime() +{ + return dpp::utility::uptime(time(NULL) - connect_time); +} + +bool discord_voice_client::is_connected() +{ + return (this->GetState() == CONNECTED); +} + +int discord_voice_client::WantWrite() { + std::lock_guard lock(this->stream_mutex); + if (!this->paused && outbuf.size()) { + return fd; + } else { + return -1; + } +} + +int discord_voice_client::WantRead() { + return fd; +} + +void discord_voice_client::Error(uint32_t errorcode) +{ + std::map errortext = { + { 1000, "Socket shutdown" }, + { 1001, "Client is leaving" }, + { 1002, "Endpoint received a malformed frame" }, + { 1003, "Endpoint received an unsupported frame" }, + { 1004, "Reserved code" }, + { 1005, "Expected close status, received none" }, + { 1006, "No close code frame has been receieved" }, + { 1007, "Endpoint received inconsistent message (e.g. malformed UTF-8)" }, + { 1008, "Generic error" }, + { 1009, "Endpoint won't process large frame" }, + { 1010, "Client wanted an extension which server did not negotiate" }, + { 1011, "Internal server error while operating" }, + { 1012, "Server/service is restarting" }, + { 1013, "Temporary server condition forced blocking client's request" }, + { 1014, "Server acting as gateway received an invalid response" }, + { 1015, "Transport Layer Security handshake failure" }, + { 4001, "Unknown opcode" }, + { 4002, "Failed to decode payload" }, + { 4003, "Not authenticated" }, + { 4004, "Authentication failed" }, + { 4005, "Already authenticated" }, + { 4006, "Session no longer valid" }, + { 4009, "Session timeout" }, + { 4011, "Server not found" }, + { 4012, "Unknown protocol" }, + { 4014, "Disconnected" }, + { 4015, "Voice server crashed" }, + { 4016, "Unknown encryption mode" } + }; + std::string error = "Unknown error"; + auto i = errortext.find(errorcode); + if (i != errortext.end()) { + error = i->second; + } + log(dpp::ll_warning, fmt::format("Voice session error: {} on channel {}: {}", errorcode, channel_id, error)); + + /* Errors 4004...4016 except 4014 are fatal and cause termination of the voice session */ + if (errorcode >= 4003 && errorcode != 4014) { + stop_audio(); + this->terminating = true; + log(dpp::ll_error, "This is a non-recoverable error, giving up on voice connection"); + } +} + +void discord_voice_client::log(dpp::loglevel severity, const std::string &msg) +{ + creator->log(severity, msg); +} + +void discord_voice_client::QueueMessage(const std::string &j, bool to_front) +{ + std::lock_guard locker(queue_mutex); + if (to_front) { + message_queue.push_front(j); + } else { + message_queue.push_back(j); + } +} + +void discord_voice_client::ClearQueue() +{ + std::lock_guard locker(queue_mutex); + message_queue.clear(); +} + +size_t discord_voice_client::GetQueueSize() +{ + std::lock_guard locker(queue_mutex); + return message_queue.size(); +} + +const std::vector discord_voice_client::get_marker_metadata() { + std::lock_guard locker(queue_mutex); + return track_meta; +} + +void discord_voice_client::one_second_timer() +{ + if (terminating) { + throw dpp::exception("Terminating voice connection"); + } + /* Rate limit outbound messages, 1 every odd second, 2 every even second */ + if (this->GetState() == CONNECTED) { + for (int x = 0; x < (time(NULL) % 2) + 1; ++x) { + std::lock_guard locker(queue_mutex); + if (message_queue.size()) { + std::string message = message_queue.front(); + message_queue.pop_front(); + this->write(message); + } + } + + if (this->heartbeat_interval) { + /* Check if we're due to emit a heartbeat */ + if (time(NULL) > last_heartbeat + ((heartbeat_interval / 1000.0) * 0.75)) { + QueueMessage(json({{"op", 3}, {"d", rand()}}).dump(), true); + last_heartbeat = time(NULL); + } + } + } +} + +size_t discord_voice_client::encode(uint8_t *input, size_t inDataSize, uint8_t *output, size_t &outDataSize) +{ +#if HAVE_VOICE + outDataSize = 0; + int mEncFrameBytes = 11520; + int mEncFrameSize = 2880; + if (0 == (inDataSize % mEncFrameBytes)) { + bool isOk = true; + size_t cur = 0; + uint8_t *out = encode_buffer; + + memset(out, 0, sizeof(encode_buffer)); + repacketizer = opus_repacketizer_init(repacketizer); + for (size_t i = 0; i < (inDataSize / mEncFrameBytes); ++ i) { + const opus_int16* pcm = (opus_int16*)(input + i * mEncFrameBytes); + int ret = opus_encode(encoder, pcm, mEncFrameSize, out, 65536); + if (ret > 0) { + int retval = opus_repacketizer_cat(repacketizer, out, ret); + if (retval != OPUS_OK) { + isOk = false; + log(ll_warning, fmt::format("opus_repacketizer_cat(): {}", opus_strerror(retval))); + break; + } + out += ret; + cur += ret; + } else { + isOk = false; + log(ll_warning, fmt::format("opus_encode(): {}", opus_strerror(ret))); + break; + } + } + if (isOk) { + int ret = opus_repacketizer_out(repacketizer, output, 65536); + if (ret > 0) { + outDataSize = ret; + } else { + log(ll_warning, fmt::format("opus_repacketizer_out(): {}", opus_strerror(ret))); + } + } + } else { + throw dpp::exception(fmt::format("Invalid input data length: {}, must be n times of {}", inDataSize, mEncFrameBytes)); + } +#endif + return outDataSize; +} + +void discord_voice_client::insert_marker(const std::string& metadata) { + /* Insert a track marker. A track marker is a single 16 bit value of 0xFFFF. + * This is too small to be a valid RTP packet so the send function knows not + * to actually send it, and instead to skip it + */ + uint16_t tm = AUDIO_TRACK_MARKER; + Send((const char*)&tm, sizeof(uint16_t)); + { + std::lock_guard lock(this->stream_mutex); + track_meta.push_back(metadata); + tracks++; + } +} + +uint32_t discord_voice_client::get_tracks_remaining() { + std::lock_guard lock(this->stream_mutex); + if (outbuf.size() == 0) + return 0; + else + return tracks + 1; +} + +void discord_voice_client::skip_to_next_marker() { + std::lock_guard lock(this->stream_mutex); + /* Keep popping the first entry off the outbuf until the first entry is a track marker */ + while (outbuf.size() && outbuf[0].size() != sizeof(uint16_t) && ((uint16_t)(*(outbuf[0].data()))) != AUDIO_TRACK_MARKER) { + outbuf.erase(outbuf.begin()); + } + if (outbuf.size()) { + /* Remove the actual track marker out of the buffer */ + outbuf.erase(outbuf.begin()); + } + if (tracks > 0) + tracks--; + if (track_meta.size()) { + track_meta.erase(track_meta.begin()); + } +} + +void discord_voice_client::send_audio(uint16_t* audio_data, const size_t length, bool use_opus) { +#if HAVE_VOICE + + const size_t max_frame_bytes = 11520; + uint8_t pad[max_frame_bytes] = { 0 }; + if (length > max_frame_bytes && use_opus) { + std::string s_audio_data((const char*)audio_data, length); + while (s_audio_data.length() > max_frame_bytes) { + std::string packet(s_audio_data.substr(0, max_frame_bytes)); + s_audio_data.erase(s_audio_data.begin(), s_audio_data.begin() + max_frame_bytes); + if (packet.size() < max_frame_bytes) { + packet.resize(max_frame_bytes, 0); + } + send_audio((uint16_t*)packet.data(), max_frame_bytes, use_opus); + } + + return; + + } + + + int frameSize = 2880; + opus_int32 encodedAudioMaxLength = length; + std::vector encodedAudioData(encodedAudioMaxLength); + size_t encodedAudioLength = encodedAudioMaxLength; + if (use_opus) { + encodedAudioLength = this->encode((uint8_t*)audio_data, length, encodedAudioData.data(), encodedAudioLength); + } else { + } + + ++sequence; + const int headerSize = 12; + const int nonceSize = 24; + rtp_header header(sequence, timestamp, ssrc); + + int8_t nonce[nonceSize]; + std::memcpy(nonce, &header, sizeof(header)); + std::memset(nonce + sizeof(header), 0, sizeof(nonce) - sizeof(header)); + + std::vector audioDataPacket(sizeof(header) + encodedAudioLength + crypto_secretbox_MACBYTES); + std::memcpy(audioDataPacket.data(), &header, sizeof(header)); + + crypto_secretbox_easy(audioDataPacket.data() + sizeof(header), encodedAudioData.data(), encodedAudioLength, (const unsigned char*)nonce, secret_key); + + Send((const char*)audioDataPacket.data(), audioDataPacket.size()); + timestamp += frameSize; + + if (!this->sending) { + this->QueueMessage(json({ + {"op", 5}, + {"d", { + {"speaking", 1}, + {"delay", 0}, + {"ssrc", ssrc} + }} + }).dump(), true); + sending = true; + } + +#endif +} + +std::string discord_voice_client::discover_ip() { + SOCKET newfd = -1; + unsigned char packet[74] = { 0 }; + (*(uint16_t*)(packet)) = htons(0x01); + (*(uint16_t*)(packet + 2)) = htons(70); + (*(uint32_t*)(packet + 4)) = htonl(this->ssrc); + if ((newfd = socket(AF_INET, SOCK_DGRAM, 0)) >= 0) { + sockaddr_in servaddr; + socklen_t sl = sizeof(servaddr); + memset(&servaddr, 0, sizeof(sockaddr_in)); + servaddr.sin_family = AF_INET; + servaddr.sin_addr.s_addr = htonl(INADDR_ANY); + servaddr.sin_port = htons(0); + if (bind(newfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) < 0) { + log(ll_warning, "Could not bind socket for IP discovery"); + return ""; + } + memset(&servaddr, 0, sizeof(servaddr)); + servaddr.sin_family = AF_INET; + servaddr.sin_port = htons(this->port); + servaddr.sin_addr.s_addr = inet_addr(this->ip.c_str()); + if (::connect(newfd, (const struct sockaddr*)&servaddr, sizeof(sockaddr_in)) < 0) { + log(ll_warning, "Could not connect socket for IP discovery"); + return ""; + } + if (send(newfd, (const char*)packet, 74, 0) == -1) { + log(ll_warning, "Could not send packet for IP discovery"); + return ""; + } + if (recv(newfd, (char*)packet, 74, 0) == -1) { + log(ll_warning, "Could not receive packet for IP discovery"); + return ""; + } + + shutdown(newfd, 2); + #ifdef _WIN32 + if (newfd >= 0 && newfd < FD_SETSIZE) { + closesocket(newfd); + } + #else + ::close(newfd); + #endif + + //utility::debug_dump(packet, 74); + return std::string((const char*)(packet + 8)); + } + return ""; +} + + + +}; \ No newline at end of file diff --git a/vendor/DPP/src/dpp/dispatcher.cpp b/vendor/DPP/src/dpp/dispatcher.cpp new file mode 100644 index 00000000..b7611704 --- /dev/null +++ b/vendor/DPP/src/dpp/dispatcher.cpp @@ -0,0 +1,155 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include + +#define event_ctor(a, b) a::a(discord_client* client, const std::string &raw) : b(client, raw) {} + +namespace dpp { + +event_dispatch_t::event_dispatch_t(discord_client* client, const std::string &raw) : from(client), raw_event(raw) +{ +} + +void interaction_create_t::reply(interaction_response_type t, const message & m) const +{ + from->creator->interaction_response_create(this->command.id, this->command.token, dpp::interaction_response(t, m)); +} + +void interaction_create_t::reply(interaction_response_type t, const std::string & mt) const +{ + this->reply(t, dpp::message(this->command.channel_id, mt, mt_application_command)); +} + +void interaction_create_t::get_original_response(command_completion_event_t callback) const +{ + from->creator->post_rest(API_PATH "/webhooks", std::to_string(command.application_id), command.token + "/messages/@original", m_get, "", [callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t("message", message().fill_from_json(&j), http)); + } + }); +} + +void interaction_create_t::edit_response(const message & m) const +{ + from->creator->interaction_response_edit(this->command.token, m); +} + +void interaction_create_t::edit_response(const std::string & mt) const +{ + this->edit_response(dpp::message(this->command.channel_id, mt, mt_application_command)); +} + +const command_value& interaction_create_t::get_parameter(const std::string& name) const +{ + /* Dummy STATIC return value for unknown options so we arent returning a value off the stack */ + static command_value dummy_value = {}; + const command_interaction& ci = std::get(command.data); + for (auto i = ci.options.begin(); i != ci.options.end(); ++i) { + if (i->name == name) { + return i->value; + } + } + return dummy_value; +} + +const command_value& button_click_t::get_parameter(const std::string& name) const +{ + /* Buttons don't have parameters, so override this */ + static command_value dummy_b_value = {}; + return dummy_b_value; +} + +const command_value& select_click_t::get_parameter(const std::string& name) const +{ + /* Selects don't have parameters, so override this */ + static command_value dummy_b_value = {}; + return dummy_b_value; +} + +/* Standard default constructors that call the parent constructor, for events */ +event_ctor(guild_join_request_delete_t, event_dispatch_t); +event_ctor(stage_instance_create_t, event_dispatch_t); +event_ctor(stage_instance_delete_t, event_dispatch_t); +event_ctor(log_t, event_dispatch_t); +event_ctor(voice_state_update_t, event_dispatch_t); +event_ctor(interaction_create_t, event_dispatch_t); +event_ctor(button_click_t, interaction_create_t); +event_ctor(select_click_t, interaction_create_t); +event_ctor(guild_delete_t, event_dispatch_t); +event_ctor(channel_delete_t, event_dispatch_t); +event_ctor(channel_update_t, event_dispatch_t); +event_ctor(ready_t, event_dispatch_t); +event_ctor(message_delete_t, event_dispatch_t); +event_ctor(application_command_delete_t, event_dispatch_t); +event_ctor(application_command_create_t, event_dispatch_t); +event_ctor(resumed_t, event_dispatch_t); +event_ctor(guild_role_create_t, event_dispatch_t); +event_ctor(typing_start_t, event_dispatch_t); +event_ctor(message_reaction_add_t, event_dispatch_t); +event_ctor(message_reaction_remove_t, event_dispatch_t); +event_ctor(guild_create_t, event_dispatch_t); +event_ctor(channel_create_t, event_dispatch_t); +event_ctor(message_reaction_remove_emoji_t, event_dispatch_t); +event_ctor(message_delete_bulk_t, event_dispatch_t); +event_ctor(guild_role_update_t, event_dispatch_t); +event_ctor(guild_role_delete_t, event_dispatch_t); +event_ctor(channel_pins_update_t, event_dispatch_t); +event_ctor(message_reaction_remove_all_t, event_dispatch_t); +event_ctor(voice_server_update_t, event_dispatch_t); +event_ctor(guild_emojis_update_t, event_dispatch_t); +event_ctor(presence_update_t, event_dispatch_t); +event_ctor(webhooks_update_t, event_dispatch_t); +event_ctor(guild_member_add_t, event_dispatch_t); +event_ctor(invite_delete_t, event_dispatch_t); +event_ctor(guild_update_t, event_dispatch_t); +event_ctor(guild_integrations_update_t, event_dispatch_t); +event_ctor(guild_member_update_t, event_dispatch_t); +event_ctor(application_command_update_t, event_dispatch_t); +event_ctor(invite_create_t, event_dispatch_t); +event_ctor(message_update_t, event_dispatch_t); +event_ctor(user_update_t, event_dispatch_t); +event_ctor(message_create_t, event_dispatch_t); +event_ctor(guild_ban_add_t, event_dispatch_t); +event_ctor(guild_ban_remove_t, event_dispatch_t); +event_ctor(integration_create_t, event_dispatch_t); +event_ctor(integration_update_t, event_dispatch_t); +event_ctor(integration_delete_t, event_dispatch_t); +event_ctor(guild_member_remove_t, event_dispatch_t); +event_ctor(guild_members_chunk_t, event_dispatch_t); +event_ctor(thread_create_t, event_dispatch_t); +event_ctor(thread_update_t, event_dispatch_t); +event_ctor(thread_delete_t, event_dispatch_t); +event_ctor(thread_list_sync_t, event_dispatch_t); +event_ctor(thread_member_update_t, event_dispatch_t); +event_ctor(thread_members_update_t, event_dispatch_t); +event_ctor(voice_buffer_send_t, event_dispatch_t); +event_ctor(voice_user_talking_t, event_dispatch_t); +event_ctor(voice_ready_t, event_dispatch_t); +event_ctor(voice_receive_t, event_dispatch_t); +event_ctor(voice_track_marker_t, event_dispatch_t); +event_ctor(guild_stickers_update_t, event_dispatch_t); + +}; diff --git a/vendor/DPP/src/dpp/dtemplate.cpp b/vendor/DPP/src/dpp/dtemplate.cpp new file mode 100644 index 00000000..456fdece --- /dev/null +++ b/vendor/DPP/src/dpp/dtemplate.cpp @@ -0,0 +1,64 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { + +dtemplate::dtemplate() : code(""), name(""), description(""), usage_count(0), creator_id(0), source_guild_id(0) +{ +} + +dtemplate::~dtemplate() { +} + + +dtemplate& dtemplate::fill_from_json(nlohmann::json* j) { + code = StringNotNull(j, "code"); + name = StringNotNull(j, "name"); + description = StringNotNull(j, "description"); + usage_count = Int32NotNull(j, "usage_count"); + creator_id = SnowflakeNotNull(j, "creator_id"); + created_at = TimestampNotNull(j, "created_at"); + updated_at = TimestampNotNull(j, "updated_at"); + source_guild_id = SnowflakeNotNull(j, "source_guild_id"); + is_dirty = BoolNotNull(j, "is_dirty"); + return *this; +} + +std::string dtemplate::build_json() const { + json j({ + {"code", code}, + {"name", name}, + {"description", description}, + {"usage_count", usage_count}, + {"creator_id", creator_id}, + {"updated_at", updated_at}, + {"source_guild_id", source_guild_id, + "is_dirty", is_dirty} + }); + return j.dump(); +} + +}; diff --git a/vendor/DPP/src/dpp/emoji.cpp b/vendor/DPP/src/dpp/emoji.cpp new file mode 100644 index 00000000..c8322f06 --- /dev/null +++ b/vendor/DPP/src/dpp/emoji.cpp @@ -0,0 +1,116 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include + +namespace dpp { + +using json = nlohmann::json; + +emoji::emoji() : managed(), user_id(0), flags(0), image_data(nullptr) +{ +} + +emoji::emoji(const std::string n, const snowflake i, const uint8_t f) + : managed(i), user_id(0), flags(f), image_data(nullptr), name(n) +{ +} + +emoji::~emoji() { + if (image_data) { + delete image_data; + } +} + +emoji& emoji::fill_from_json(nlohmann::json* j) { + id = SnowflakeNotNull(j, "id"); + name = StringNotNull(j, "name"); + if (j->find("user") != j->end()) { + json & user = (*j)["user"]; + user_id = SnowflakeNotNull(&user, "id"); + } + if (BoolNotNull(j, "require_colons")) + flags |= e_require_colons; + if (BoolNotNull(j, "managed")) + flags |= e_managed; + if (BoolNotNull(j, "animated")) + flags |= e_animated; + if (BoolNotNull(j, "available")) + flags |= e_available; + return *this; +} + +std::string emoji::build_json(bool with_id) const { + json j; + if (with_id) { + j["id"] = std::to_string(id); + } + j["name"] = name; + if (image_data) { + j["image"] = *image_data; + } + return j.dump(); +} + +bool emoji::requires_colons() const { + return flags & e_require_colons; +} + +bool emoji::is_managed() const { + return flags & e_managed; +} + +bool emoji::is_animated() const { + return flags & e_animated; +} + +bool emoji::is_available() const { + return flags & e_available; +} + +emoji& emoji::load_image(const std::string &image_blob, image_type type) { + static std::map mimetypes = { + { i_gif, "image/gif" }, + { i_jpg, "image/jpeg" }, + { i_png, "image/png" } + }; + if (image_blob.size() > MAX_EMOJI_SIZE) { + throw dpp::exception("Emoji file exceeds discord limit of 256 kilobytes"); + } + if (image_data) { + /* If there's already image data defined, free the old data, to prevent a memory leak */ + delete image_data; + } + image_data = new std::string("data:" + mimetypes[type] + ";base64," + base64_encode((unsigned char const*)image_blob.data(), image_blob.length())); + + return *this; +} + +std::string emoji::format() const +{ + return id ? (name + ":" + std::to_string(id)) : name; +} + +}; + diff --git a/vendor/DPP/src/dpp/events/application_command_create.cpp b/vendor/DPP/src/dpp/events/application_command_create.cpp new file mode 100644 index 00000000..2d6ac7db --- /dev/null +++ b/vendor/DPP/src/dpp/events/application_command_create.cpp @@ -0,0 +1,48 @@ +#include +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { namespace events { + +using namespace dpp; + +/** + * @brief Handle event + * + * @param client Websocket client (current shard) + * @param j JSON data for the event + * @param raw Raw JSON string + */ +void application_command_create::handle(discord_client* client, json &j, const std::string &raw) { +} + +}}; \ No newline at end of file diff --git a/vendor/DPP/src/dpp/events/application_command_delete.cpp b/vendor/DPP/src/dpp/events/application_command_delete.cpp new file mode 100644 index 00000000..e68e8dfb --- /dev/null +++ b/vendor/DPP/src/dpp/events/application_command_delete.cpp @@ -0,0 +1,48 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { namespace events { + +using namespace dpp; + +/** + * @brief Handle event + * + * @param client Websocket client (current shard) + * @param j JSON data for the event + * @param raw Raw JSON string + */ +void application_command_delete::handle(discord_client* client, json &j, const std::string &raw) { +} + +}}; \ No newline at end of file diff --git a/vendor/DPP/src/dpp/events/application_command_update.cpp b/vendor/DPP/src/dpp/events/application_command_update.cpp new file mode 100644 index 00000000..63fea42e --- /dev/null +++ b/vendor/DPP/src/dpp/events/application_command_update.cpp @@ -0,0 +1,48 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { namespace events { + +using namespace dpp; + +/** + * @brief Handle event + * + * @param client Websocket client (current shard) + * @param j JSON data for the event + * @param raw Raw JSON string + */ +void application_command_update::handle(discord_client* client, json &j, const std::string &raw) { +} + +}}; \ No newline at end of file diff --git a/vendor/DPP/src/dpp/events/channel_create.cpp b/vendor/DPP/src/dpp/events/channel_create.cpp new file mode 100644 index 00000000..ed290241 --- /dev/null +++ b/vendor/DPP/src/dpp/events/channel_create.cpp @@ -0,0 +1,75 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { namespace events { + +using namespace dpp; + +/** + * @brief Handle event + * + * @param client Websocket client (current shard) + * @param j JSON data for the event + * @param raw Raw JSON string + */ +void channel_create::handle(discord_client* client, json &j, const std::string &raw) { + json& d = j["d"]; + + dpp::channel* c = dpp::find_channel(SnowflakeNotNull(&d, "id")); + if (!c) { + c = new dpp::channel(); + } + c->fill_from_json(&d); + dpp::get_channel_cache()->store(c); + if (c->recipients.size()) { + for (auto & u : c->recipients) { + client->log(dpp::ll_debug, fmt::format("Got a DM channel {} for user {}", c->id, u)); + client->creator->set_dm_channel(u, c->id); + } + } + dpp::guild* g = dpp::find_guild(c->guild_id); + if (g) { + g->channels.push_back(c->id); + + if (client->creator->dispatch.channel_create) { + dpp::channel_create_t cc(client, raw); + cc.created = c; + cc.creating_guild = g; + client->creator->dispatch.channel_create(cc); + } + } +} + +}}; \ No newline at end of file diff --git a/vendor/DPP/src/dpp/events/channel_delete.cpp b/vendor/DPP/src/dpp/events/channel_delete.cpp new file mode 100644 index 00000000..4c0e3188 --- /dev/null +++ b/vendor/DPP/src/dpp/events/channel_delete.cpp @@ -0,0 +1,69 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + + +namespace dpp { namespace events { + +using namespace dpp; + +/** + * @brief Handle event + * + * @param client Websocket client (current shard) + * @param j JSON data for the event + * @param raw Raw JSON string + */ +void channel_delete::handle(discord_client* client, json &j, const std::string &raw) { + json& d = j["d"]; + dpp::channel* c = dpp::find_channel(SnowflakeNotNull(&d, "id")); + if (c) { + dpp::guild* g = dpp::find_guild(c->guild_id); + if (g) { + auto gc = std::find(g->channels.begin(), g->channels.end(), c->id); + if (gc != g->channels.end()) { + g->channels.erase(gc); + } + + if (client->creator->dispatch.channel_delete) { + dpp::channel_delete_t cd(client, raw); + cd.deleted = c; + cd.deleting_guild = g; + client->creator->dispatch.channel_delete(cd); + } + } + dpp::get_channel_cache()->remove(c); + } +} + +}}; \ No newline at end of file diff --git a/vendor/DPP/src/dpp/events/channel_pins_update.cpp b/vendor/DPP/src/dpp/events/channel_pins_update.cpp new file mode 100644 index 00000000..b526a7cb --- /dev/null +++ b/vendor/DPP/src/dpp/events/channel_pins_update.cpp @@ -0,0 +1,61 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { namespace events { + +using namespace dpp; + +/** + * @brief Handle event + * + * @param client Websocket client (current shard) + * @param j JSON data for the event + * @param raw Raw JSON string + */ +void channel_pins_update::handle(discord_client* client, json &j, const std::string &raw) { + + if (client->creator->dispatch.channel_pins_update) { + json& d = j["d"]; + dpp::channel_pins_update_t cpu(client, raw); + cpu.pin_channel = dpp::find_channel(SnowflakeNotNull(&d, "channel_id")); + cpu.pin_guild = dpp::find_guild(SnowflakeNotNull(&d, "guild_id")); + cpu.timestamp = TimestampNotNull(&d, "last_pin_timestamp"); + + client->creator->dispatch.channel_pins_update(cpu); + + } + +} + +}}; \ No newline at end of file diff --git a/vendor/DPP/src/dpp/events/channel_update.cpp b/vendor/DPP/src/dpp/events/channel_update.cpp new file mode 100644 index 00000000..1c941c4c --- /dev/null +++ b/vendor/DPP/src/dpp/events/channel_update.cpp @@ -0,0 +1,59 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { namespace events { + +using namespace dpp; + +/** + * @brief Handle event + * + * @param client Websocket client (current shard) + * @param j JSON data for the event + * @param raw Raw JSON string + */ +void channel_update::handle(discord_client* client, json &j, const std::string &raw) { + json& d = j["d"]; + dpp::channel* c = dpp::find_channel(from_string(d["id"].get(), std::dec)); + if (c) { + c->fill_from_json(&d); + if (client->creator->dispatch.channel_update) { + dpp::channel_update_t cu(client, raw); + cu.updated = c; + cu.updating_guild = dpp::find_guild(c->guild_id); + client->creator->dispatch.channel_update(cu); + } + } +} + +}}; \ No newline at end of file diff --git a/vendor/DPP/src/dpp/events/guild_ban_add.cpp b/vendor/DPP/src/dpp/events/guild_ban_add.cpp new file mode 100644 index 00000000..48dc52f7 --- /dev/null +++ b/vendor/DPP/src/dpp/events/guild_ban_add.cpp @@ -0,0 +1,57 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { namespace events { + +using namespace dpp; + + +/** + * @brief Handle event + * + * @param client Websocket client (current shard) + * @param j JSON data for the event + * @param raw Raw JSON string + */ +void guild_ban_add::handle(discord_client* client, json &j, const std::string &raw) { + if (client->creator->dispatch.guild_ban_add) { + json &d = j["d"]; + dpp::guild_ban_add_t gba(client, raw); + gba.banning_guild = dpp::find_guild(SnowflakeNotNull(&d, "guild_id")); + gba.banned = dpp::user().fill_from_json(&(d["user"])); + client->creator->dispatch.guild_ban_add(gba); + } +} + +}}; \ No newline at end of file diff --git a/vendor/DPP/src/dpp/events/guild_ban_remove.cpp b/vendor/DPP/src/dpp/events/guild_ban_remove.cpp new file mode 100644 index 00000000..12c3a00d --- /dev/null +++ b/vendor/DPP/src/dpp/events/guild_ban_remove.cpp @@ -0,0 +1,57 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { namespace events { + +using namespace dpp; + + +/** + * @brief Handle event + * + * @param client Websocket client (current shard) + * @param j JSON data for the event + * @param raw Raw JSON string + */ +void guild_ban_remove::handle(discord_client* client, json &j, const std::string &raw) { + if (client->creator->dispatch.guild_ban_remove) { + json &d = j["d"]; + dpp::guild_ban_remove_t gbr(client, raw); + gbr.unbanning_guild = dpp::find_guild(SnowflakeNotNull(&d, "guild_id")); + gbr.unbanned = dpp::user().fill_from_json(&(d["user"])); + client->creator->dispatch.guild_ban_remove(gbr); + } +} + +}}; \ No newline at end of file diff --git a/vendor/DPP/src/dpp/events/guild_create.cpp b/vendor/DPP/src/dpp/events/guild_create.cpp new file mode 100644 index 00000000..c1a94782 --- /dev/null +++ b/vendor/DPP/src/dpp/events/guild_create.cpp @@ -0,0 +1,149 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { namespace events { + +using namespace dpp; + +/** + * @brief Handle event + * + * @param client Websocket client (current shard) + * @param j JSON data for the event + * @param raw Raw JSON string + */ +void guild_create::handle(discord_client* client, json &j, const std::string &raw) { + json& d = j["d"]; + bool newguild = false; + if (SnowflakeNotNull(&d, "id") == 0) + return; + dpp::guild* g = dpp::find_guild(SnowflakeNotNull(&d, "id")); + if (!g) { + g = new dpp::guild(); + newguild = true; + } + g->fill_from_json(client, &d); + g->shard_id = client->shard_id; + if (!g->is_unavailable() && newguild) { + if (client->creator->cache_policy.role_policy != dpp::cp_none) { + /* Store guild roles */ + g->roles.clear(); + g->roles.reserve(d["roles"].size()); + for (auto & role : d["roles"]) { + dpp::role *r = dpp::find_role(SnowflakeNotNull(&role, "id")); + if (!r) { + r = new dpp::role(); + } + r->fill_from_json(g->id, &role); + dpp::get_role_cache()->store(r); + g->roles.push_back(r->id); + } + } + + /* Store guild channels */ + g->channels.clear(); + g->channels.reserve(d["channels"].size()); + for (auto & channel : d["channels"]) { + dpp::channel* c = dpp::find_channel(SnowflakeNotNull(&channel, "id")); + if (!c) { + c = new dpp::channel(); + } + c->fill_from_json(&channel); + c->guild_id = g->id; + dpp::get_channel_cache()->store(c); + g->channels.push_back(c->id); + } + + /* Store guild threads */ + g->threads.clear(); + g->threads.reserve(d["threads"].size()); + for (auto & channel : d["threads"]) { + g->threads.push_back(SnowflakeNotNull(&channel, "id")); + } + + /* Store guild members */ + if (client->creator->cache_policy.user_policy == cp_aggressive) { + g->members.reserve(d["members"].size()); + for (auto & user : d["members"]) { + snowflake userid = SnowflakeNotNull(&(user["user"]), "id"); + /* Only store ones we don't have already otherwise gm will leak */ + if (g->members.find(userid) == g->members.end()) { + dpp::user* u = dpp::find_user(userid); + if (!u) { + u = new dpp::user(); + u->fill_from_json(&(user["user"])); + dpp::get_user_cache()->store(u); + } else { + u->refcount++; + } + dpp::guild_member gm; + gm.fill_from_json(&(user["user"]), g->id, userid); + g->members[userid] = gm; + } + } + } + if (client->creator->cache_policy.emoji_policy != dpp::cp_none) { + /* Store emojis */ + g->emojis.reserve(d["emojis"].size()); + g->emojis = {}; + for (auto & emoji : d["emojis"]) { + dpp::emoji* e = dpp::find_emoji(SnowflakeNotNull(&emoji, "id")); + if (!e) { + e = new dpp::emoji(); + e->fill_from_json(&emoji); + dpp::get_emoji_cache()->store(e); + } + g->emojis.push_back(e->id); + } + } + } + dpp::get_guild_cache()->store(g); + if (newguild && g->id && (client->intents & dpp::i_guild_members)) { + if (client->creator->cache_policy.user_policy == cp_aggressive) { + json chunk_req = json({{"op", 8}, {"d", {{"guild_id",std::to_string(g->id)},{"query",""},{"limit",0}}}}); + if (client->intents & dpp::i_guild_presences) { + chunk_req["d"]["presences"] = true; + } + client->QueueMessage(chunk_req.dump()); + } + } + + if (client->creator->dispatch.guild_create) { + dpp::guild_create_t gc(client, raw); + gc.created = g; + client->creator->dispatch.guild_create(gc); + } +} + +}}; diff --git a/vendor/DPP/src/dpp/events/guild_delete.cpp b/vendor/DPP/src/dpp/events/guild_delete.cpp new file mode 100644 index 00000000..ff2cccf1 --- /dev/null +++ b/vendor/DPP/src/dpp/events/guild_delete.cpp @@ -0,0 +1,98 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { namespace events { + +using namespace dpp; + +/** + * @brief Handle event + * + * @param client Websocket client (current shard) + * @param j JSON data for the event + * @param raw Raw JSON string + */ +void guild_delete::handle(discord_client* client, json &j, const std::string &raw) { + json& d = j["d"]; + dpp::guild* g = dpp::find_guild(SnowflakeNotNull(&d, "id")); + if (g) { + if (!BoolNotNull(&d, "unavailable")) { + dpp::get_guild_cache()->remove(g); + if (client->creator->cache_policy.emoji_policy != dpp::cp_none) { + for (auto & ee : g->emojis) { + dpp::emoji* fe = dpp::find_emoji(ee); + if (fe) { + dpp::get_emoji_cache()->remove(fe); + } + } + } + if (client->creator->cache_policy.role_policy != dpp::cp_none) { + for (auto & rr : g->roles) { + dpp::role* role = dpp::find_role(rr); + if (role) { + dpp::get_role_cache()->remove(role); + } + } + } + for (auto & cc : g->channels) { + dpp::channel* ch = dpp::find_channel(cc); + if (ch) { + dpp::get_channel_cache()->remove(ch); + } + } + if (client->creator->cache_policy.user_policy != dpp::cp_none) { + for (auto gm = g->members.begin(); gm != g->members.end(); ++gm) { + dpp::user* u = dpp::find_user(gm->second.user_id); + if (u) { + u->refcount--; + if (u->refcount < 1) { + dpp::get_user_cache()->remove(u); + } + } + } + } + g->members.clear(); + } else { + g->flags |= dpp::g_unavailable; + } + + if (client->creator->dispatch.guild_delete) { + dpp::guild_delete_t gd(client, raw); + gd.deleted = g; + client->creator->dispatch.guild_delete(gd); + } + } +} + +}}; diff --git a/vendor/DPP/src/dpp/events/guild_emojis_update.cpp b/vendor/DPP/src/dpp/events/guild_emojis_update.cpp new file mode 100644 index 00000000..0ae0f3ff --- /dev/null +++ b/vendor/DPP/src/dpp/events/guild_emojis_update.cpp @@ -0,0 +1,78 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { namespace events { + +using namespace dpp; + + +/** + * @brief Handle event + * + * @param client Websocket client (current shard) + * @param j JSON data for the event + * @param raw Raw JSON string + */ +void guild_emojis_update::handle(discord_client* client, json &j, const std::string &raw) { + json& d = j["d"]; + dpp::guild* g = dpp::find_guild(SnowflakeNotNull(&d, "guild_id")); + if (g) { + if (client->creator->cache_policy.emoji_policy != dpp::cp_none) { + for (auto & ee : g->emojis) { + dpp::emoji* fe = dpp::find_emoji(ee); + if (fe) { + dpp::get_emoji_cache()->remove(fe); + } + } + g->emojis.clear(); + for (auto & emoji : d["emojis"]) { + dpp::emoji* e = dpp::find_emoji(SnowflakeNotNull(&emoji, "id")); + if (!e) { + e = new dpp::emoji(); + e->fill_from_json(&emoji); + dpp::get_emoji_cache()->store(e); + } + g->emojis.push_back(e->id); + } + } + if (client->creator->dispatch.guild_emojis_update) { + dpp::guild_emojis_update_t geu(client, raw); + geu.emojis = g->emojis; + geu.updating_guild = g; + client->creator->dispatch.guild_emojis_update(geu); + } + } +} + +}}; \ No newline at end of file diff --git a/vendor/DPP/src/dpp/events/guild_integrations_update.cpp b/vendor/DPP/src/dpp/events/guild_integrations_update.cpp new file mode 100644 index 00000000..f0c42795 --- /dev/null +++ b/vendor/DPP/src/dpp/events/guild_integrations_update.cpp @@ -0,0 +1,55 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { namespace events { + +using namespace dpp; + +/** + * @brief Handle event + * + * @param client Websocket client (current shard) + * @param j JSON data for the event + * @param raw Raw JSON string + */ +void guild_integrations_update::handle(class discord_client* client, json &j, const std::string &raw) { + if (client->creator->dispatch.guild_integrations_update) { + json& d = j["d"]; + dpp::guild_integrations_update_t giu(client, raw); + giu.updating_guild = dpp::find_guild(SnowflakeNotNull(&d, "guild_id")); + client->creator->dispatch.guild_integrations_update(giu); + } +} + +}}; \ No newline at end of file diff --git a/vendor/DPP/src/dpp/events/guild_join_request_delete.cpp b/vendor/DPP/src/dpp/events/guild_join_request_delete.cpp new file mode 100644 index 00000000..bd73c0c5 --- /dev/null +++ b/vendor/DPP/src/dpp/events/guild_join_request_delete.cpp @@ -0,0 +1,56 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { namespace events { + +using namespace dpp; + +/** + * @brief Handle event + * + * @param client Websocket client (current shard) + * @param j JSON data for the event + * @param raw Raw JSON string + */ +void guild_join_request_delete::handle(class discord_client* client, json &j, const std::string &raw) { + if (client->creator->dispatch.guild_join_request_delete) { + json& d = j["d"]; + dpp::guild_join_request_delete_t grd(client, raw); + grd.user_id = SnowflakeNotNull(&d, "user_id"); + grd.guild_id = SnowflakeNotNull(&d, "guild_id"); + client->creator->dispatch.guild_join_request_delete(grd); + } +} + +}}; \ No newline at end of file diff --git a/vendor/DPP/src/dpp/events/guild_member_add.cpp b/vendor/DPP/src/dpp/events/guild_member_add.cpp new file mode 100644 index 00000000..b042e388 --- /dev/null +++ b/vendor/DPP/src/dpp/events/guild_member_add.cpp @@ -0,0 +1,86 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { namespace events { + +using namespace dpp; + +/** + * @brief Handle event + * + * @param client Websocket client (current shard) + * @param j JSON data for the event + * @param raw Raw JSON string + */ +void guild_member_add::handle(discord_client* client, json &j, const std::string &raw) { + json d = j["d"]; + + dpp::guild* g = dpp::find_guild(SnowflakeNotNull(&d, "guild_id")); + dpp::guild_member_add_t gmr(client, raw); + if (g) { + if (client->creator->cache_policy.user_policy == dpp::cp_none) { + dpp::guild_member gm; + gm.fill_from_json(&d, g->id, SnowflakeNotNull(&(d["user"]), "id")); + gmr.added = gm; + if (client->creator->dispatch.guild_member_add) { + gmr.adding_guild = g; + client->creator->dispatch.guild_member_add(gmr); + } + } else { + dpp::user* u = dpp::find_user(SnowflakeNotNull(&(d["user"]), "id")); + if (!u) { + u = new dpp::user(); + u->fill_from_json(&(d["user"])); + dpp::get_user_cache()->store(u); + } else { + u->refcount++; + } + dpp::guild_member gm; + gmr.added = {}; + if (u && u->id && g->members.find(u->id) == g->members.end()) { + gm.fill_from_json(&d, g->id, u->id); + g->members[u->id] = gm; + gmr.added = gm; + } else if (u && u->id) { + gmr.added = g->members.find(u->id)->second; + } + if (client->creator->dispatch.guild_member_add) { + gmr.adding_guild = g; + client->creator->dispatch.guild_member_add(gmr); + } + } + } +} + +}}; \ No newline at end of file diff --git a/vendor/DPP/src/dpp/events/guild_member_remove.cpp b/vendor/DPP/src/dpp/events/guild_member_remove.cpp new file mode 100644 index 00000000..e3588878 --- /dev/null +++ b/vendor/DPP/src/dpp/events/guild_member_remove.cpp @@ -0,0 +1,83 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { namespace events { + +using namespace dpp; + +/** + * @brief Handle event + * + * @param client Websocket client (current shard) + * @param j JSON data for the event + * @param raw Raw JSON string + */ +void guild_member_remove::handle(discord_client* client, json &j, const std::string &raw) { + json d = j["d"]; + + dpp::guild_member_remove_t gmr(client, raw); + + gmr.removing_guild = dpp::find_guild(SnowflakeNotNull(&d, "guild_id")); + + if (client->creator->cache_policy.user_policy == dpp::cp_none) { + dpp::user u; + u.fill_from_json(&(d["user"])); + gmr.removed = &u; + if (client->creator->dispatch.guild_member_remove) + client->creator->dispatch.guild_member_remove(gmr); + } else { + + gmr.removed = dpp::find_user(SnowflakeNotNull(&(d["user"]), "id")); + + if (client->creator->dispatch.guild_member_remove) + client->creator->dispatch.guild_member_remove(gmr); + + if (gmr.removing_guild && gmr.removed) { + auto i = gmr.removing_guild->members.find(gmr.removed->id); + if (i != gmr.removing_guild->members.end()) { + dpp::user* u = dpp::find_user(gmr.removed->id); + if (u) { + u->refcount--; + if (u->refcount < 1) { + dpp::get_user_cache()->remove(u); + } + } + gmr.removing_guild->members.erase(i); + } + + } + } +} + +}}; \ No newline at end of file diff --git a/vendor/DPP/src/dpp/events/guild_member_update.cpp b/vendor/DPP/src/dpp/events/guild_member_update.cpp new file mode 100644 index 00000000..e77a545b --- /dev/null +++ b/vendor/DPP/src/dpp/events/guild_member_update.cpp @@ -0,0 +1,78 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { namespace events { + +using namespace dpp; + +/** + * @brief Handle event + * + * @param client Websocket client (current shard) + * @param j JSON data for the event + * @param raw Raw JSON string + */ +void guild_member_update::handle(discord_client* client, json &j, const std::string &raw) { + json& d = j["d"]; + dpp::guild* g = dpp::find_guild(from_string(d["guild_id"].get(), std::dec)); + if (client->creator->cache_policy.user_policy == dpp::cp_none) { + dpp::user u; + u.fill_from_json(&(d["user"])); + if (g && client->creator->dispatch.guild_member_update) { + dpp::guild_member_update_t gmu(client, raw); + gmu.updating_guild = g; + guild_member m; + auto& user = d;//d["user"]; // d contains roles and other member stuff already + m.fill_from_json(&user, g->id, u.id); + gmu.updated = m; + client->creator->dispatch.guild_member_update(gmu); + } + } else { + dpp::user* u = dpp::find_user(from_string(d["user"]["id"].get(), std::dec)); + if (g && u) { + auto& user = d;//d["user"]; // d contains roles and other member stuff already + guild_member m; + m.fill_from_json(&user, g->id, u->id); + g->members[u->id] = m; + + if (client->creator->dispatch.guild_member_update) { + dpp::guild_member_update_t gmu(client, raw); + gmu.updating_guild = g; + gmu.updated = m; + client->creator->dispatch.guild_member_update(gmu); + } + } + } +} + +}}; \ No newline at end of file diff --git a/vendor/DPP/src/dpp/events/guild_members_chunk.cpp b/vendor/DPP/src/dpp/events/guild_members_chunk.cpp new file mode 100644 index 00000000..d1b1a46c --- /dev/null +++ b/vendor/DPP/src/dpp/events/guild_members_chunk.cpp @@ -0,0 +1,79 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { namespace events { + +using namespace dpp; + +/** + * @brief Handle event + * + * @param client Websocket client (current shard) + * @param j JSON data for the event + * @param raw Raw JSON string + */ +void guild_members_chunk::handle(discord_client* client, json &j, const std::string &raw) { + json &d = j["d"]; + dpp::guild_member_map um; + dpp::guild* g = dpp::find_guild(SnowflakeNotNull(&d, "guild_id")); + if (g) { + /* Store guild members */ + if (client->creator->cache_policy.user_policy == cp_aggressive) { + for (auto & userrec : d["members"]) { + json & userspart = userrec["user"]; + dpp::user* u = dpp::find_user(SnowflakeNotNull(&userspart, "id")); + if (!u) { + u = new dpp::user(); + u->fill_from_json(&userspart); + dpp::get_user_cache()->store(u); + } + if (g->members.find(u->id) == g->members.end()) { + dpp::guild_member gm; + gm.fill_from_json(&userrec, g->id, u->id); + g->members[u->id] = gm; + if (client->creator->dispatch.guild_members_chunk) + um[u->id] = gm; + } + } + } + if (client->creator->dispatch.guild_members_chunk) { + dpp::guild_members_chunk_t gmc(client, raw); + gmc.adding = g; + gmc.members = &um; + client->creator->dispatch.guild_members_chunk(gmc); + } + } +} + +}}; \ No newline at end of file diff --git a/vendor/DPP/src/dpp/events/guild_role_create.cpp b/vendor/DPP/src/dpp/events/guild_role_create.cpp new file mode 100644 index 00000000..4e076667 --- /dev/null +++ b/vendor/DPP/src/dpp/events/guild_role_create.cpp @@ -0,0 +1,79 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { namespace events { + +using namespace dpp; + +/** + * @brief Handle event + * + * @param client Websocket client (current shard) + * @param j JSON data for the event + * @param raw Raw JSON string + */ +void guild_role_create::handle(discord_client* client, json &j, const std::string &raw) { + json &d = j["d"]; + dpp::guild* g = dpp::find_guild(SnowflakeNotNull(&d, "guild_id")); + if (g) { + if (client->creator->cache_policy.role_policy == dpp::cp_none) { + json &role = d["role"]; + dpp::role r; + r.fill_from_json(g->id, &role); + if (client->creator->dispatch.guild_role_create) { + dpp::guild_role_create_t grc(client, raw); + grc.creating_guild = g; + grc.created = &r; + client->creator->dispatch.guild_role_create(grc); + } + } else { + json &role = d["role"]; + dpp::role *r = dpp::find_role(SnowflakeNotNull(&role, "id")); + if (!r) { + r = new dpp::role(); + } + r->fill_from_json(g->id, &role); + dpp::get_role_cache()->store(r); + g->roles.push_back(r->id); + if (client->creator->dispatch.guild_role_create) { + dpp::guild_role_create_t grc(client, raw); + grc.creating_guild = g; + grc.created = r; + client->creator->dispatch.guild_role_create(grc); + } + } + } +} + +}}; \ No newline at end of file diff --git a/vendor/DPP/src/dpp/events/guild_role_delete.cpp b/vendor/DPP/src/dpp/events/guild_role_delete.cpp new file mode 100644 index 00000000..82ea57f6 --- /dev/null +++ b/vendor/DPP/src/dpp/events/guild_role_delete.cpp @@ -0,0 +1,80 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { namespace events { + +using namespace dpp; + +/** + * @brief Handle event + * + * @param client Websocket client (current shard) + * @param j JSON data for the event + * @param raw Raw JSON string + */ +void guild_role_delete::handle(discord_client* client, json &j, const std::string &raw) { + json &d = j["d"]; + dpp::guild* g = dpp::find_guild(SnowflakeNotNull(&d, "guild_id")); + if (g) { + if (client->creator->cache_policy.role_policy == dpp::cp_none) { + json& role = d["role"]; + dpp::role r; + r.fill_from_json(g->id, &d); + if (client->creator->dispatch.guild_role_delete) { + dpp::guild_role_delete_t grd(client, raw); + grd.deleting_guild = g; + grd.deleted = &r; + client->creator->dispatch.guild_role_delete(grd); + } + } else { + json& role = d["role"]; + dpp::role *r = dpp::find_role(SnowflakeNotNull(&role, "id")); + if (r) { + if (client->creator->dispatch.guild_role_delete) { + dpp::guild_role_delete_t grd(client, raw); + grd.deleting_guild = g; + grd.deleted = r; + client->creator->dispatch.guild_role_delete(grd); + } + auto i = std::find(g->roles.begin(), g->roles.end(), r->id); + if (i != g->roles.end()) { + g->roles.erase(i); + } + dpp::get_role_cache()->remove(r); + } + } + } +} + +}}; \ No newline at end of file diff --git a/vendor/DPP/src/dpp/events/guild_role_update.cpp b/vendor/DPP/src/dpp/events/guild_role_update.cpp new file mode 100644 index 00000000..76a334c2 --- /dev/null +++ b/vendor/DPP/src/dpp/events/guild_role_update.cpp @@ -0,0 +1,76 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { namespace events { + +using namespace dpp; + +/** + * @brief Handle event + * + * @param client Websocket client (current shard) + * @param j JSON data for the event + * @param raw Raw JSON string + */ +void guild_role_update::handle(discord_client* client, json &j, const std::string &raw) { + json &d = j["d"]; + dpp::guild* g = dpp::find_guild(SnowflakeNotNull(&d, "guild_id")); + if (g) { + if (client->creator->cache_policy.role_policy == dpp::cp_none) { + json& role = d["role"]; + dpp::role r; + r.fill_from_json(g->id, &d); + if (client->creator->dispatch.guild_role_update) { + dpp::guild_role_update_t gru(client, raw); + gru.updating_guild = g; + gru.updated = &r; + client->creator->dispatch.guild_role_update(gru); + } + } else { + json& role = d["role"]; + dpp::role *r = dpp::find_role(SnowflakeNotNull(&role, "id")); + if (r) { + r->fill_from_json(g->id, &role); + if (client->creator->dispatch.guild_role_update) { + dpp::guild_role_update_t gru(client, raw); + gru.updating_guild = g; + gru.updated = r; + client->creator->dispatch.guild_role_update(gru); + } + } + } + } +} + +}}; \ No newline at end of file diff --git a/vendor/DPP/src/dpp/events/guild_stickers_update.cpp b/vendor/DPP/src/dpp/events/guild_stickers_update.cpp new file mode 100644 index 00000000..e4427974 --- /dev/null +++ b/vendor/DPP/src/dpp/events/guild_stickers_update.cpp @@ -0,0 +1,64 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { namespace events { + +using namespace dpp; + + +/** + * @brief Handle event + * + * @param client Websocket client (current shard) + * @param j JSON data for the event + * @param raw Raw JSON string + */ +void guild_stickers_update::handle(discord_client* client, json &j, const std::string &raw) { + json& d = j["d"]; + dpp::guild* g = dpp::find_guild(SnowflakeNotNull(&d, "guild_id")); + if (g) { + if (client->creator->dispatch.stickers_update) { + dpp::guild_stickers_update_t gsu(client, raw); + for (auto & sticker : d["stickers"]) { + dpp::sticker s; + s.fill_from_json(&sticker); + gsu.stickers.push_back(s); + } + gsu.updating_guild = g; + client->creator->dispatch.stickers_update(gsu); + } + } +} + +}}; \ No newline at end of file diff --git a/vendor/DPP/src/dpp/events/guild_update.cpp b/vendor/DPP/src/dpp/events/guild_update.cpp new file mode 100644 index 00000000..311ad6f7 --- /dev/null +++ b/vendor/DPP/src/dpp/events/guild_update.cpp @@ -0,0 +1,74 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { namespace events { + +using namespace dpp; + +/** + * @brief Handle event + * + * @param client Websocket client (current shard) + * @param j JSON data for the event + * @param raw Raw JSON string + */ +void guild_update::handle(discord_client* client, json &j, const std::string &raw) { + json& d = j["d"]; + dpp::guild* g = dpp::find_guild(from_string(d["id"].get(), std::dec)); + if (g) { + g->fill_from_json(client, &d); + if (!g->is_unavailable()) { + if (client->creator->cache_policy.role_policy != dpp::cp_none && d.find("roles") != d.end()) { + for (int rc = 0; rc < g->roles.size(); ++rc) { + dpp::role* oldrole = dpp::find_role(g->roles[rc]); + dpp::get_role_cache()->remove(oldrole); + } + g->roles.clear(); + for (auto & role : d["roles"]) { + dpp::role *r = new dpp::role(); + r->fill_from_json(g->id, &role); + dpp::get_role_cache()->store(r); + g->roles.push_back(r->id); + } + } + } + + if (client->creator->dispatch.guild_update) { + dpp::guild_update_t gu(client, raw); + gu.updated = g; + client->creator->dispatch.guild_update(gu); + } + } +} + +}}; \ No newline at end of file diff --git a/vendor/DPP/src/dpp/events/integration_create.cpp b/vendor/DPP/src/dpp/events/integration_create.cpp new file mode 100644 index 00000000..11a570ae --- /dev/null +++ b/vendor/DPP/src/dpp/events/integration_create.cpp @@ -0,0 +1,56 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { namespace events { + +using namespace dpp; + + +/** + * @brief Handle event + * + * @param client Websocket client (current shard) + * @param j JSON data for the event + * @param raw Raw JSON string + */ +void integration_create::handle(discord_client* client, json &j, const std::string &raw) { + if (client->creator->dispatch.integration_create) { + json& d = j["d"]; + dpp::integration_create_t ic(client, raw); + ic.created_integration = dpp::integration().fill_from_json(&d); + client->creator->dispatch.integration_create(ic); + } +} + +}}; \ No newline at end of file diff --git a/vendor/DPP/src/dpp/events/integration_delete.cpp b/vendor/DPP/src/dpp/events/integration_delete.cpp new file mode 100644 index 00000000..02023e12 --- /dev/null +++ b/vendor/DPP/src/dpp/events/integration_delete.cpp @@ -0,0 +1,55 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { namespace events { + +using namespace dpp; + +/** + * @brief Handle event + * + * @param client Websocket client (current shard) + * @param j JSON data for the event + * @param raw Raw JSON string + */ +void integration_delete::handle(discord_client* client, json &j, const std::string &raw) { + if (client->creator->dispatch.integration_delete) { + json& d = j["d"]; + dpp::integration_delete_t id(client, raw); + id.deleted_integration = dpp::integration().fill_from_json(&d); + client->creator->dispatch.integration_delete(id); + } +} + +}}; \ No newline at end of file diff --git a/vendor/DPP/src/dpp/events/integration_update.cpp b/vendor/DPP/src/dpp/events/integration_update.cpp new file mode 100644 index 00000000..bbccb1f4 --- /dev/null +++ b/vendor/DPP/src/dpp/events/integration_update.cpp @@ -0,0 +1,55 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { namespace events { + +using namespace dpp; + +/** + * @brief Handle event + * + * @param client Websocket client (current shard) + * @param j JSON data for the event + * @param raw Raw JSON string + */ +void integration_update::handle(discord_client* client, json &j, const std::string &raw) { + if (client->creator->dispatch.integration_update) { + json& d = j["d"]; + dpp::integration_update_t iu(client, raw); + iu.updated_integration = dpp::integration().fill_from_json(&d); + client->creator->dispatch.integration_update(iu); + } +} + +}}; \ No newline at end of file diff --git a/vendor/DPP/src/dpp/events/interaction_create.cpp b/vendor/DPP/src/dpp/events/interaction_create.cpp new file mode 100644 index 00000000..05ab97da --- /dev/null +++ b/vendor/DPP/src/dpp/events/interaction_create.cpp @@ -0,0 +1,83 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { namespace events { + +using namespace dpp; + +/** + * @brief Handle event + * + * @param client Websocket client (current shard) + * @param j JSON data for the event + * @param raw Raw JSON string + */ +void interaction_create::handle(discord_client* client, json &j, const std::string &raw) { + json& d = j["d"]; + dpp::interaction i; + i.fill_from_json(&d); + /* There are two types of interactions, component interactions and + * slash command interactions. Both fire different library events + * so ensure they are dispatched properly. + */ + if (i.type == it_application_command) { + if (client->creator->dispatch.interaction_create) { + dpp::interaction_create_t ic(client, raw); + ic.command = i; + client->creator->dispatch.interaction_create(ic); + } + } else if (i.type == it_component_button) { + dpp::component_interaction bi = std::get(i.data); + if (bi.component_type == cotype_button) { + if (client->creator->dispatch.button_click) { + dpp::button_click_t ic(client, raw); + ic.command = i; + ic.custom_id = bi.custom_id; + ic.component_type = bi.component_type; + client->creator->dispatch.button_click(ic); + } + } + if (bi.component_type == cotype_select) { + if (client->creator->dispatch.select_click) { + dpp::select_click_t ic(client, raw); + ic.command = i; + ic.custom_id = bi.custom_id; + ic.component_type = bi.component_type; + ic.values = bi.values; + client->creator->dispatch.select_click(ic); + } + } + } +} + +}}; \ No newline at end of file diff --git a/vendor/DPP/src/dpp/events/invite_create.cpp b/vendor/DPP/src/dpp/events/invite_create.cpp new file mode 100644 index 00000000..81241529 --- /dev/null +++ b/vendor/DPP/src/dpp/events/invite_create.cpp @@ -0,0 +1,54 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { namespace events { + +using namespace dpp; + +/** + * @brief Handle event + * + * @param client Websocket client (current shard) + * @param j JSON data for the event + * @param raw Raw JSON string + */ +void invite_create::handle(discord_client* client, json &j, const std::string &raw) { + if (client->creator->dispatch.invite_create) { + json& d = j["d"]; + dpp::invite_create_t ci(client, raw); + ci.created_invite = dpp::invite().fill_from_json(&d); + client->creator->dispatch.invite_create(ci); + } +} + +}}; \ No newline at end of file diff --git a/vendor/DPP/src/dpp/events/invite_delete.cpp b/vendor/DPP/src/dpp/events/invite_delete.cpp new file mode 100644 index 00000000..68718a1e --- /dev/null +++ b/vendor/DPP/src/dpp/events/invite_delete.cpp @@ -0,0 +1,54 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { namespace events { + +using namespace dpp; + +/** + * @brief Handle event + * + * @param client Websocket client (current shard) + * @param j JSON data for the event + * @param raw Raw JSON string + */ +void invite_delete::handle(discord_client* client, json &j, const std::string &raw) { + if (client->creator->dispatch.invite_delete) { + json& d = j["d"]; + dpp::invite_delete_t cd(client, raw); + cd.deleted_invite = dpp::invite().fill_from_json(&d); + client->creator->dispatch.invite_delete(cd); + } +} + +}}; \ No newline at end of file diff --git a/vendor/DPP/src/dpp/events/logger.cpp b/vendor/DPP/src/dpp/events/logger.cpp new file mode 100644 index 00000000..8e1791fd --- /dev/null +++ b/vendor/DPP/src/dpp/events/logger.cpp @@ -0,0 +1,54 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { namespace events { + +using namespace dpp; + +/** + * @brief Handle event + * + * @param client Websocket client (current shard) + * @param j JSON data for the event + * @param raw Raw JSON string + */ +void logger::handle(discord_client* client, json &j, const std::string &raw) { + if (client->creator->dispatch.log) { + dpp::log_t logmsg(client, raw); + logmsg.severity = (dpp::loglevel)from_string(raw.substr(0, raw.find(';')), std::dec); + logmsg.message = raw.substr(raw.find(';') + 1, raw.length()); + client->creator->dispatch.log(logmsg); + } +} + +}}; \ No newline at end of file diff --git a/vendor/DPP/src/dpp/events/message_create.cpp b/vendor/DPP/src/dpp/events/message_create.cpp new file mode 100644 index 00000000..cda21163 --- /dev/null +++ b/vendor/DPP/src/dpp/events/message_create.cpp @@ -0,0 +1,59 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { namespace events { + +using namespace dpp; + +/** + * @brief Handle event + * + * @param client Websocket client (current shard) + * @param j JSON data for the event + * @param raw Raw JSON string + */ +void message_create::handle(discord_client* client, json &j, const std::string &raw) { + + if (client->creator->dispatch.message_create) { + json d = j["d"]; + dpp::message_create_t msg(client, raw); + dpp::message m; + m.fill_from_json(&d, client->creator->cache_policy); + msg.msg = &m; + client->creator->dispatch.message_create(msg); + } +} + +}}; \ No newline at end of file diff --git a/vendor/DPP/src/dpp/events/message_delete.cpp b/vendor/DPP/src/dpp/events/message_delete.cpp new file mode 100644 index 00000000..c204ea0d --- /dev/null +++ b/vendor/DPP/src/dpp/events/message_delete.cpp @@ -0,0 +1,57 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { namespace events { + +using namespace dpp; + +/** + * @brief Handle event + * + * @param client Websocket client (current shard) + * @param j JSON data for the event + * @param raw Raw JSON string + */ +void message_delete::handle(discord_client* client, json &j, const std::string &raw) { + if (client->creator->dispatch.message_delete) { + json d = j["d"]; + dpp::message_delete_t msg(client, raw); + dpp::message m; + m.fill_from_json(&d); + msg.deleted = &m; + client->creator->dispatch.message_delete(msg); + } + +} + +}}; \ No newline at end of file diff --git a/vendor/DPP/src/dpp/events/message_delete_bulk.cpp b/vendor/DPP/src/dpp/events/message_delete_bulk.cpp new file mode 100644 index 00000000..5ee1ab97 --- /dev/null +++ b/vendor/DPP/src/dpp/events/message_delete_bulk.cpp @@ -0,0 +1,61 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { namespace events { + +using namespace dpp; + +/** + * @brief Handle event + * + * @param client Websocket client (current shard) + * @param j JSON data for the event + * @param raw Raw JSON string + */ +void message_delete_bulk::handle(discord_client* client, json &j, const std::string &raw) { + if (client->creator->dispatch.message_delete_bulk) { + json& d = j["d"]; + dpp::message_delete_bulk_t msg(client, raw); + msg.deleting_guild = dpp::find_guild(SnowflakeNotNull(&d, "guild_id")); + msg.deleting_channel = dpp::find_channel(SnowflakeNotNull(&d, "channel_id")); + msg.deleting_user = dpp::find_user(SnowflakeNotNull(&d, "user_id")); + for (auto& m : d["ids"]) { + msg.deleted.push_back(from_string(m.get(), std::dec)); + } + client->creator->dispatch.message_delete_bulk(msg); + } + +} + +}}; \ No newline at end of file diff --git a/vendor/DPP/src/dpp/events/message_reaction_add.cpp b/vendor/DPP/src/dpp/events/message_reaction_add.cpp new file mode 100644 index 00000000..cd51a079 --- /dev/null +++ b/vendor/DPP/src/dpp/events/message_reaction_add.cpp @@ -0,0 +1,61 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { namespace events { + +using namespace dpp; + +/** + * @brief Handle event + * + * @param client Websocket client (current shard) + * @param j JSON data for the event + * @param raw Raw JSON string + */ +void message_reaction_add::handle(discord_client* client, json &j, const std::string &raw) { + if (client->creator->dispatch.message_reaction_add) { + json &d = j["d"]; + dpp::message_reaction_add_t mra(client, raw); + mra.reacting_guild = dpp::find_guild(SnowflakeNotNull(&d, "guild_id")); + mra.reacting_user = dpp::find_user(SnowflakeNotNull(&d, "user_id")); + mra.reacting_channel = dpp::find_channel(SnowflakeNotNull(&d, "channel_id")); + mra.message_id = SnowflakeNotNull(&d, "message_id"); + mra.reacting_emoji = dpp::find_emoji(SnowflakeNotNull(&(d["emoji"]), "id")); + if (mra.reacting_user && mra.reacting_channel && mra.message_id) { + client->creator->dispatch.message_reaction_add(mra); + } + } +} + +}}; \ No newline at end of file diff --git a/vendor/DPP/src/dpp/events/message_reaction_remove.cpp b/vendor/DPP/src/dpp/events/message_reaction_remove.cpp new file mode 100644 index 00000000..4b22d553 --- /dev/null +++ b/vendor/DPP/src/dpp/events/message_reaction_remove.cpp @@ -0,0 +1,61 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { namespace events { + +using namespace dpp; + +/** + * @brief Handle event + * + * @param client Websocket client (current shard) + * @param j JSON data for the event + * @param raw Raw JSON string + */ +void message_reaction_remove::handle(discord_client* client, json &j, const std::string &raw) { + if (client->creator->dispatch.message_reaction_remove) { + json &d = j["d"]; + dpp::message_reaction_remove_t mrr(client, raw); + mrr.reacting_guild = dpp::find_guild(SnowflakeNotNull(&d, "guild_id")); + mrr.reacting_user = dpp::find_user(SnowflakeNotNull(&d, "user_id")); + mrr.reacting_channel = dpp::find_channel(SnowflakeNotNull(&d, "channel_id")); + mrr.message_id = SnowflakeNotNull(&d, "message_id"); + mrr.reacting_emoji = dpp::find_emoji(SnowflakeNotNull(&(d["emoji"]), "id")); + if (mrr.reacting_user && mrr.reacting_channel && mrr.message_id) { + client->creator->dispatch.message_reaction_remove(mrr); + } + } +} + +}}; \ No newline at end of file diff --git a/vendor/DPP/src/dpp/events/message_reaction_remove_all.cpp b/vendor/DPP/src/dpp/events/message_reaction_remove_all.cpp new file mode 100644 index 00000000..0ffb4388 --- /dev/null +++ b/vendor/DPP/src/dpp/events/message_reaction_remove_all.cpp @@ -0,0 +1,59 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { namespace events { + +using namespace dpp; + +/** + * @brief Handle event + * + * @param client Websocket client (current shard) + * @param j JSON data for the event + * @param raw Raw JSON string + */ +void message_reaction_remove_all::handle(discord_client* client, json &j, const std::string &raw) { + if (client->creator->dispatch.message_reaction_remove_all) { + json &d = j["d"]; + dpp::message_reaction_remove_all_t mrra(client, raw); + mrra.reacting_guild = dpp::find_guild(SnowflakeNotNull(&d, "guild_id")); + mrra.reacting_channel = dpp::find_channel(SnowflakeNotNull(&d, "channel_id")); + mrra.message_id = SnowflakeNotNull(&d, "message_id"); + if (mrra.reacting_channel && mrra.message_id) { + client->creator->dispatch.message_reaction_remove_all(mrra); + } + } +} + +}}; \ No newline at end of file diff --git a/vendor/DPP/src/dpp/events/message_reaction_remove_emoji.cpp b/vendor/DPP/src/dpp/events/message_reaction_remove_emoji.cpp new file mode 100644 index 00000000..3e18e4e5 --- /dev/null +++ b/vendor/DPP/src/dpp/events/message_reaction_remove_emoji.cpp @@ -0,0 +1,61 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { namespace events { + +using namespace dpp; + +/** + * @brief Handle event + * + * @param client Websocket client (current shard) + * @param j JSON data for the event + * @param raw Raw JSON string + */ +void message_reaction_remove_emoji::handle(discord_client* client, json &j, const std::string &raw) { + if (client->creator->dispatch.message_reaction_remove_emoji) { + json &d = j["d"]; + dpp::message_reaction_remove_emoji_t mrre(client, raw); + mrre.reacting_guild = dpp::find_guild(SnowflakeNotNull(&d, "guild_id")); + mrre.reacting_channel = dpp::find_channel(SnowflakeNotNull(&d, "channel_id")); + mrre.message_id = SnowflakeNotNull(&d, "message_id"); + mrre.reacting_emoji = dpp::find_emoji(SnowflakeNotNull(&(d["emoji"]), "id")); + if (mrre.reacting_channel && mrre.message_id) { + client->creator->dispatch.message_reaction_remove_emoji(mrre); + } + } + +} + +}}; \ No newline at end of file diff --git a/vendor/DPP/src/dpp/events/message_update.cpp b/vendor/DPP/src/dpp/events/message_update.cpp new file mode 100644 index 00000000..c271366d --- /dev/null +++ b/vendor/DPP/src/dpp/events/message_update.cpp @@ -0,0 +1,57 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { namespace events { + +using namespace dpp; + +/** + * @brief Handle event + * + * @param client Websocket client (current shard) + * @param j JSON data for the event + * @param raw Raw JSON string + */ +void message_update::handle(discord_client* client, json &j, const std::string &raw) { + if (client->creator->dispatch.message_update) { + json d = j["d"]; + dpp::message_update_t msg(client, raw); + dpp::message m; + m.fill_from_json(&d); + msg.updated = &m; + client->creator->dispatch.message_update(msg); + } + +} + +}}; \ No newline at end of file diff --git a/vendor/DPP/src/dpp/events/presence_update.cpp b/vendor/DPP/src/dpp/events/presence_update.cpp new file mode 100644 index 00000000..410f8b09 --- /dev/null +++ b/vendor/DPP/src/dpp/events/presence_update.cpp @@ -0,0 +1,55 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { namespace events { + +using namespace dpp; + +/** + * @brief Handle event + * + * @param client Websocket client (current shard) + * @param j JSON data for the event + * @param raw Raw JSON string + */ +void presence_update::handle(discord_client* client, json &j, const std::string &raw) { + if (client->creator->dispatch.presence_update) { + json& d = j["d"]; + dpp::presence_update_t pu(client, raw); + pu.rich_presence = dpp::presence().fill_from_json(&d); + client->creator->dispatch.presence_update(pu); + } +} + +}}; \ No newline at end of file diff --git a/vendor/DPP/src/dpp/events/ready.cpp b/vendor/DPP/src/dpp/events/ready.cpp new file mode 100644 index 00000000..9298a2ff --- /dev/null +++ b/vendor/DPP/src/dpp/events/ready.cpp @@ -0,0 +1,68 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { namespace events { + +using namespace dpp; + +std::mutex protect_the_loot; + +/** + * @brief Handle event + * + * @param client Websocket client (current shard) + * @param j JSON data for the event + * @param raw Raw JSON string + */ +void ready::handle(discord_client* client, json &j, const std::string &raw) { + client->log(dpp::ll_info, fmt::format("Shard {}/{} ready!", client->shard_id, client->max_shards)); + client->sessionid = j["d"]["session_id"]; + + client->ready = true; + + /* Mutex this to make sure multiple threads don't change it at the same time */ + { + std::lock_guard lockit(protect_the_loot); + client->creator->me.fill_from_json(&(j["d"]["user"])); + } + + if (client->creator->dispatch.ready) { + dpp::ready_t r(client, raw); + r.session_id = client->sessionid; + r.shard_id = client->shard_id; + client->creator->dispatch.ready(r); + } +} + +}}; \ No newline at end of file diff --git a/vendor/DPP/src/dpp/events/resumed.cpp b/vendor/DPP/src/dpp/events/resumed.cpp new file mode 100644 index 00000000..170e89c5 --- /dev/null +++ b/vendor/DPP/src/dpp/events/resumed.cpp @@ -0,0 +1,59 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { namespace events { + +using namespace dpp; + +/** + * @brief Handle event + * + * @param client Websocket client (current shard) + * @param j JSON data for the event + * @param raw Raw JSON string + */ +void resumed::handle(discord_client* client, json &j, const std::string &raw) { + client->log(dpp::ll_debug, fmt::format("Successfully resumed session id {}", client->sessionid)); + + client->ready = true; + + if (client->creator->dispatch.resumed) { + dpp::resumed_t r(client, raw); + r.session_id = client->sessionid; + r.shard_id = client->shard_id; + client->creator->dispatch.resumed(r); + } +} + +}}; \ No newline at end of file diff --git a/vendor/DPP/src/dpp/events/stage_instance_create.cpp b/vendor/DPP/src/dpp/events/stage_instance_create.cpp new file mode 100644 index 00000000..fa7b31bf --- /dev/null +++ b/vendor/DPP/src/dpp/events/stage_instance_create.cpp @@ -0,0 +1,59 @@ +#include +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { namespace events { + +using namespace dpp; + +/** + * @brief Handle event + * + * @param client Websocket client (current shard) + * @param j JSON data for the event + * @param raw Raw JSON string + */ +void stage_instance_create::handle(discord_client* client, json &j, const std::string &raw) { + if (client->creator->dispatch.stage_instance_create) { + json& d = j["d"]; + dpp::stage_instance_create_t sic(client, raw); + sic.id = SnowflakeNotNull(&d, "id"); + sic.channel_id = SnowflakeNotNull(&d, "channel_id"); + sic.guild_id = SnowflakeNotNull(&d, "channel_id"); + sic.privacy_level = dpp::Int8NotNull(&d, "privacy_level"); + sic.topic = StringNotNull(&d, "topic"); + client->creator->dispatch.stage_instance_create(sic); + } +} + +}}; \ No newline at end of file diff --git a/vendor/DPP/src/dpp/events/stage_instance_delete.cpp b/vendor/DPP/src/dpp/events/stage_instance_delete.cpp new file mode 100644 index 00000000..4ec48d17 --- /dev/null +++ b/vendor/DPP/src/dpp/events/stage_instance_delete.cpp @@ -0,0 +1,59 @@ +#include +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { namespace events { + +using namespace dpp; + +/** + * @brief Handle event + * + * @param client Websocket client (current shard) + * @param j JSON data for the event + * @param raw Raw JSON string + */ +void stage_instance_delete::handle(discord_client* client, json &j, const std::string &raw) { + if (client->creator->dispatch.stage_instance_delete) { + json& d = j["d"]; + dpp::stage_instance_delete_t sid(client, raw); + sid.id = SnowflakeNotNull(&d, "id"); + sid.channel_id = SnowflakeNotNull(&d, "channel_id"); + sid.guild_id = SnowflakeNotNull(&d, "channel_id"); + sid.privacy_level = dpp::Int8NotNull(&d, "privacy_level"); + sid.topic = StringNotNull(&d, "topic"); + client->creator->dispatch.stage_instance_delete(sid); + } +} + +}}; \ No newline at end of file diff --git a/vendor/DPP/src/dpp/events/thread_create.cpp b/vendor/DPP/src/dpp/events/thread_create.cpp new file mode 100644 index 00000000..fc6aed15 --- /dev/null +++ b/vendor/DPP/src/dpp/events/thread_create.cpp @@ -0,0 +1,35 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { namespace events { + +using namespace dpp; +void thread_create::handle(discord_client* client, json& j, const std::string& raw) { + json& d = j["d"]; + + dpp::channel t; + t.fill_from_json(&d); + dpp::guild* g = dpp::find_guild(t.guild_id); + if (g) { + g->threads.push_back(t.id); + if (client->creator->dispatch.thread_create) { + dpp::thread_create_t tc(client, raw); + tc.created = t; + tc.creating_guild = g; + client->creator->dispatch.thread_create(tc); + } + } +} +}}; diff --git a/vendor/DPP/src/dpp/events/thread_delete.cpp b/vendor/DPP/src/dpp/events/thread_delete.cpp new file mode 100644 index 00000000..2dbccab6 --- /dev/null +++ b/vendor/DPP/src/dpp/events/thread_delete.cpp @@ -0,0 +1,38 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { namespace events { + +using namespace dpp; +void thread_delete::handle(discord_client* client, json& j, const std::string& raw) { + json& d = j["d"]; + + dpp::channel t; + t.fill_from_json(&d); + dpp::guild* g = dpp::find_guild(t.guild_id); + if (g) { + auto gt = std::find(g->threads.begin(), g->threads.end(), t.id); + if (gt != g->threads.end()) { + g->threads.erase(gt); + } + if (client->creator->dispatch.thread_delete) { + dpp::thread_delete_t tc(client, raw); + tc.deleted = t; + tc.deleting_guild = g; + client->creator->dispatch.thread_delete(tc); + } + } +} +}}; diff --git a/vendor/DPP/src/dpp/events/thread_list_sync.cpp b/vendor/DPP/src/dpp/events/thread_list_sync.cpp new file mode 100644 index 00000000..61d98787 --- /dev/null +++ b/vendor/DPP/src/dpp/events/thread_list_sync.cpp @@ -0,0 +1,46 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { namespace events { + +using namespace dpp; +void thread_list_sync::handle(discord_client* client, json& j, const std::string& raw) { + json& d = j["d"]; + + dpp::guild* g = dpp::find_guild(SnowflakeNotNull(&d, "guild_id")); + if (g) { + /** Store thread IDs*/ + if (d.find("threads") != d.end()) { + for (auto& t : d["threads"]) { + g->threads.push_back(SnowflakeNotNull(&t, "id")); + } + } + if (client->creator->dispatch.thread_list_sync) { + dpp::thread_list_sync_t tls(client, raw); + if (d.find("threads") != d.end()) { + for (auto& t : d["threads"]) { + tls.threads.push_back(channel().fill_from_json(&t)); + } + } + if (d.find("members") != d.end()) { + for (auto& tm : d["members"]) { + tls.members.push_back(thread_member().fill_from_json(&tm)); + } + } + client->creator->dispatch.thread_list_sync(tls); + } + } +} +}}; diff --git a/vendor/DPP/src/dpp/events/thread_member_update.cpp b/vendor/DPP/src/dpp/events/thread_member_update.cpp new file mode 100644 index 00000000..6ca773cf --- /dev/null +++ b/vendor/DPP/src/dpp/events/thread_member_update.cpp @@ -0,0 +1,28 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { namespace events { + +using namespace dpp; +void thread_member_update::handle(discord_client* client, json& j, const std::string& raw) { + json& d = j["d"]; + if (client->creator->dispatch.thread_member_update) { + dpp::thread_member_update_t tm(client, raw); + tm.updated = thread_member().fill_from_json(&j); + + client->creator->dispatch.thread_member_update(tm); + } +} +}}; diff --git a/vendor/DPP/src/dpp/events/thread_members_update.cpp b/vendor/DPP/src/dpp/events/thread_members_update.cpp new file mode 100644 index 00000000..187742d1 --- /dev/null +++ b/vendor/DPP/src/dpp/events/thread_members_update.cpp @@ -0,0 +1,47 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { namespace events { + +using namespace dpp; +void thread_members_update::handle(discord_client* client, json& j, const std::string& raw) { + json& d = j["d"]; + + dpp::guild* g = dpp::find_guild(SnowflakeNotNull(&d, "guild_id")); + if (g) { + if (client->creator->dispatch.thread_members_update) { + dpp::thread_members_update_t tms(client, raw); + tms.updating_guild = g; + SetSnowflakeNotNull(&d, "id", tms.thread_id); + SetInt8NotNull(&d, "member_count", tms.member_count); + if (d.find("added_members") != d.end()) { + for (auto& tm : d["added_members"]) { + tms.added.push_back(thread_member().fill_from_json(&tm)); + } + } + if (d.find("removed_member_ids") != d.end()) { + try { + for (auto& rm : d["removed_member_ids"]) { + tms.removed_ids.push_back(std::stoull(static_cast(rm))); + } + } catch (const std::exception& e) { + client->creator->log(dpp::ll_error, fmt::format("thread_members_update: {}", e.what())); + } + } + client->creator->dispatch.thread_members_update(tms); + } + } +} +}}; diff --git a/vendor/DPP/src/dpp/events/thread_update.cpp b/vendor/DPP/src/dpp/events/thread_update.cpp new file mode 100644 index 00000000..d9ea9983 --- /dev/null +++ b/vendor/DPP/src/dpp/events/thread_update.cpp @@ -0,0 +1,34 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { namespace events { + +using namespace dpp; +void thread_update::handle(discord_client* client, json& j, const std::string& raw) { + json& d = j["d"]; + + dpp::channel t; + t.fill_from_json(&d); + dpp::guild* g = dpp::find_guild(t.guild_id); + if (g) { + if (client->creator->dispatch.thread_update) { + dpp::thread_update_t tc(client, raw); + tc.updated = t; + tc.updating_guild = g; + client->creator->dispatch.thread_update(tc); + } + } +} +}}; diff --git a/vendor/DPP/src/dpp/events/typing_start.cpp b/vendor/DPP/src/dpp/events/typing_start.cpp new file mode 100644 index 00000000..f08a087d --- /dev/null +++ b/vendor/DPP/src/dpp/events/typing_start.cpp @@ -0,0 +1,58 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { namespace events { + +using namespace dpp; + +/** + * @brief Handle event + * + * @param client Websocket client (current shard) + * @param j JSON data for the event + * @param raw Raw JSON string + */ +void typing_start::handle(discord_client* client, json &j, const std::string &raw) { + if (client->creator->dispatch.typing_start) { + json& d = j["d"]; + dpp::typing_start_t ts(client, raw); + ts.typing_guild = dpp::find_guild(SnowflakeNotNull(&d, "guild_id")); + ts.typing_channel = dpp::find_channel(SnowflakeNotNull(&d, "channel_id")); + ts.typing_user = dpp::find_user(SnowflakeNotNull(&d, "user_id")); + ts.timestamp = TimestampNotNull(&d, "timestamp"); + client->creator->dispatch.typing_start(ts); + } +} + +}}; \ No newline at end of file diff --git a/vendor/DPP/src/dpp/events/user_update.cpp b/vendor/DPP/src/dpp/events/user_update.cpp new file mode 100644 index 00000000..f975b052 --- /dev/null +++ b/vendor/DPP/src/dpp/events/user_update.cpp @@ -0,0 +1,74 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { namespace events { + +using namespace dpp; + +/** + * @brief Handle event + * + * @param client Websocket client (current shard) + * @param j JSON data for the event + * @param raw Raw JSON string + */ +void user_update::handle(discord_client* client, json &j, const std::string &raw) { + json& d = j["d"]; + + dpp::snowflake user_id = SnowflakeNotNull(&d, "id"); + if (user_id) { + if (client->creator->cache_policy.user_policy != dpp::cp_none) { + dpp::user* u = dpp::find_user(user_id); + if (u) { + u->fill_from_json(&d); + } + if (client->creator->dispatch.user_update) { + dpp::user_update_t uu(client, raw); + uu.updated = *u; + client->creator->dispatch.user_update(uu); + } + } else { + if (client->creator->dispatch.user_update) { + dpp::user u; + u.fill_from_json(&d); + dpp::user_update_t uu(client, raw); + uu.updated = u; + client->creator->dispatch.user_update(uu); + } + } + + } +} + +}}; \ No newline at end of file diff --git a/vendor/DPP/src/dpp/events/voice_server_update.cpp b/vendor/DPP/src/dpp/events/voice_server_update.cpp new file mode 100644 index 00000000..a7f0c0b8 --- /dev/null +++ b/vendor/DPP/src/dpp/events/voice_server_update.cpp @@ -0,0 +1,74 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { namespace events { + +using namespace dpp; + +/** + * @brief Handle event + * + * @param client Websocket client (current shard) + * @param j JSON data for the event + * @param raw Raw JSON string + */ +void voice_server_update::handle(discord_client* client, json &j, const std::string &raw) { + + json &d = j["d"]; + dpp::voice_server_update_t vsu(client, raw); + vsu.guild_id = SnowflakeNotNull(&d, "guild_id"); + vsu.token = StringNotNull(&d, "token"); + vsu.endpoint = StringNotNull(&d, "endpoint"); + + { + std::lock_guard lock(client->voice_mutex); + auto v = client->connecting_voice_channels.find(vsu.guild_id); + /* Check to see if there is a connection in progress for a voice channel on this guild */ + if (v != client->connecting_voice_channels.end()) { + if (!v->second->is_ready()) { + v->second->token = vsu.token; + v->second->websocket_hostname = vsu.endpoint; + if (!v->second->is_active()) { + v->second->connect(vsu.guild_id); + } + } + } + } + + if (client->creator->dispatch.voice_server_update) { + client->creator->dispatch.voice_server_update(vsu); + } +} + +}}; \ No newline at end of file diff --git a/vendor/DPP/src/dpp/events/voice_state_update.cpp b/vendor/DPP/src/dpp/events/voice_state_update.cpp new file mode 100644 index 00000000..3ab6a0ec --- /dev/null +++ b/vendor/DPP/src/dpp/events/voice_state_update.cpp @@ -0,0 +1,83 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { namespace events { + +using namespace dpp; + +/** + * @brief Handle event + * + * @param client Websocket client (current shard) + * @param j JSON data for the event + * @param raw Raw JSON string + */ +void voice_state_update::handle(discord_client* client, json &j, const std::string &raw) { + + json& d = j["d"]; + dpp::voice_state_update_t vsu(client, raw); + vsu.state = dpp::voicestate().fill_from_json(&d); + vsu.state.shard = client; + + /* Update guild voice states */ + dpp::guild* g = dpp::find_guild(vsu.state.guild_id); + if (g) { + if (vsu.state.channel_id == 0) { + auto ve = g->voice_members.find(vsu.state.user_id); + if (ve != g->voice_members.end()) { + g->voice_members.erase(ve); + } + } else { + g->voice_members[vsu.state.user_id] = vsu.state; + } + } + + if (vsu.state.user_id == client->creator->me.id) + { + std::lock_guard lock(client->voice_mutex); + auto v = client->connecting_voice_channels.find(vsu.state.guild_id); + /* Check to see if we have a connection to a voice channel in progress on this guild */ + if (v != client->connecting_voice_channels.end()) { + v->second->session_id = vsu.state.session_id; + if (v->second->is_ready() && !v->second->is_active()) { + v->second->connect(vsu.state.guild_id); + } + } + } + + if (client->creator->dispatch.voice_state_update) { + client->creator->dispatch.voice_state_update(vsu); + } +} + +}}; \ No newline at end of file diff --git a/vendor/DPP/src/dpp/events/webhooks_update.cpp b/vendor/DPP/src/dpp/events/webhooks_update.cpp new file mode 100644 index 00000000..5745854f --- /dev/null +++ b/vendor/DPP/src/dpp/events/webhooks_update.cpp @@ -0,0 +1,56 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { namespace events { + +using namespace dpp; + +/** + * @brief Handle event + * + * @param client Websocket client (current shard) + * @param j JSON data for the event + * @param raw Raw JSON string + */ +void webhooks_update::handle(discord_client* client, json &j, const std::string &raw) { + if (client->creator->dispatch.webhooks_update) { + json& d = j["d"]; + dpp::webhooks_update_t wu(client, raw); + wu.webhook_guild = dpp::find_guild(SnowflakeNotNull(&d, "guild_id")); + wu.webhook_channel = dpp::find_channel(SnowflakeNotNull(&d, "channel_id")); + client->creator->dispatch.webhooks_update(wu); + } +} + +}}; \ No newline at end of file diff --git a/vendor/DPP/src/dpp/guild.cpp b/vendor/DPP/src/dpp/guild.cpp new file mode 100644 index 00000000..ba7f6b20 --- /dev/null +++ b/vendor/DPP/src/dpp/guild.cpp @@ -0,0 +1,469 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +std::map featuremap = { + {"INVITE_SPLASH", dpp::g_invite_splash }, + {"VIP_REGIONS", dpp::g_vip_regions }, + {"VANITY_URL", dpp::g_vanity_url }, + {"VERIFIED", dpp::g_verified }, + {"PARTNERED", dpp::g_partnered }, + {"COMMUNITY", dpp::g_community }, + {"COMMERCE", dpp::g_commerce }, + {"NEWS", dpp::g_news }, + {"DISCOVERABLE", dpp::g_discoverable }, + {"FEATUREABLE", dpp::g_featureable }, + {"ANIMATED_ICON", dpp::g_animated_icon }, + {"BANNER", dpp::g_banner }, + {"WELCOME_SCREEN_ENABLED", dpp::g_welcome_screen_enabled }, + {"MEMBER_VERIFICATION_GATE_ENABLED", dpp::g_member_verification_gate }, + {"PREVIEW_ENABLED", dpp::g_preview_enabled } +}; + +std::map regionmap = { + { "brazil", dpp::r_brazil }, + { "central-europe", dpp::r_central_europe }, + { "hong-kong", dpp::r_hong_kong }, + { "india", dpp::r_india }, + { "japan", dpp::r_japan }, + { "russia", dpp::r_russia }, + { "singapore", dpp::r_singapore }, + { "south-africa", dpp::r_south_africa }, + { "sydney", dpp::r_sydney }, + { "us-central", dpp::r_us_central }, + { "us-east", dpp::r_us_east }, + { "us-south", dpp::r_us_south }, + { "us-west", dpp::r_us_west }, + { "western-europe", dpp::r_western_europe } +}; + + +namespace dpp { + +guild::guild() : + managed(), + shard_id(0), + flags(0), + owner_id(0), + voice_region(r_us_central), + afk_channel_id(0), + afk_timeout(0), + widget_channel_id(0), + verification_level(0), + default_message_notifications(0), + explicit_content_filter(0), + mfa_level(0), + application_id(0), + system_channel_id(0), + rules_channel_id(0), + member_count(0), + premium_tier(0), + premium_subscription_count(0), + public_updates_channel_id(0), + max_video_channel_users(0) +{ +} + + +guild_member::guild_member() : + joined_at(0), + premium_since(0), + flags(0) +{ +} + +guild_member& guild_member::fill_from_json(nlohmann::json* j, snowflake g_id, snowflake u_id) { + this->guild_id = g_id; + this->user_id = u_id; + j->get_to(*this); + return *this; +} + +void from_json(const nlohmann::json& j, guild_member& gm) { + gm.nickname = StringNotNull(&j, "nick"); + gm.joined_at = TimestampNotNull(&j, "joined_at"); + gm.premium_since = TimestampNotNull(&j, "premium_since"); + + gm.roles.clear(); + if (j.contains("roles") && !j.at("roles").is_null()) { + for (auto& role : j.at("roles")) { + gm.roles.push_back(std::stoull(role.get())); + } + } + + gm.flags |= BoolNotNull(&j, "deaf") ? gm_deaf : 0; + gm.flags |= BoolNotNull(&j, "mute") ? gm_mute : 0; + gm.flags |= BoolNotNull(&j, "pending") ? gm_pending : 0; +} + +std::string guild_member::build_json() const { + json j; + if (!this->nickname.empty()) + j["nick"] = this->nickname; + if (this->roles.size()) { + j["roles"] = {}; + for (auto & role : roles) { + j["roles"].push_back(std::to_string(role)); + } + } + if (is_muted()) { + j["muted"] = true; + } + if (is_deaf()) { + j["deaf"] = true; + } + return j.dump(); +} + +bool guild_member::is_deaf() const { + return flags & dpp::gm_deaf; +} + +bool guild_member::is_muted() const { + return flags & dpp::gm_mute; +} + +bool guild_member::is_pending() const { + return flags & dpp::gm_pending; +} + +bool guild::is_large() const { + return this->flags & g_large; +} + +bool guild::is_unavailable() const { + return this->flags & g_unavailable; +} + +bool guild::widget_enabled() const { + return this->flags & g_widget_enabled; +} + +bool guild::has_invite_splash() const { + return this->flags & g_invite_splash; +} + +bool guild::has_vip_regions() const { + return this->flags & g_vip_regions; +} + +bool guild::has_vanity_url() const { + return this->flags & g_vanity_url; +} + +bool guild::is_verified() const { + return this->flags & g_verified; +} + +bool guild::is_partnered() const { + return this->flags & g_partnered; +} + +bool guild::is_community() const { + return this->flags & g_community; +} + +bool guild::has_commerce() const { + return this->flags & g_commerce; +} + +bool guild::has_news() const { + return this->flags & g_news; +} + +bool guild::is_discoverable() const { + return this->flags & g_discoverable; +} + +bool guild::is_featureable() const { + return this->flags & g_featureable; +} + +bool guild::has_animated_icon() const { + return this->flags & g_animated_icon; +} + +bool guild::has_banner() const { + return this->flags & g_banner; +} + +bool guild::is_welcome_screen_enabled() const { + return this->flags & g_welcome_screen_enabled; +} + +bool guild::has_member_verification_gate() const { + return this->flags & g_member_verification_gate; +} + +bool guild::is_preview_enabled() const { + return this->flags & g_preview_enabled; +} + + bool guild::has_animated_icon_hash() const { + return this->flags & g_has_animated_icon; + } + +std::string guild::build_json(bool with_id) const { + json j; + if (with_id) { + j["id"] = std::to_string(id); + } + if (!name.empty()) { + j["name"] = name; + } + j["widget_enabled"] = widget_enabled(); + if (afk_channel_id) { + j["afk_channel_id"] = afk_channel_id; + } + if (afk_channel_id) { + j["afk_timeout"] = afk_timeout; + } + if (widget_enabled()) { + j["widget_channel_id"] = widget_channel_id; + } + j["default_message_notifications"] = default_message_notifications; + j["explicit_content_filter"] = explicit_content_filter; + j["mfa_level"] = mfa_level; + if (system_channel_id) { + j["system_channel_id"] = system_channel_id; + } + if (rules_channel_id) { + j["rules_channel_id"] = rules_channel_id; + } + if (!vanity_url_code.empty()) { + j["vanity_url_code"] = vanity_url_code; + } + if (!description.empty()) { + j["description"] = description; + } + return j.dump(); +} + +void guild::rehash_members() { + members_container n; + n.reserve(members.size()); + for (auto t = members.begin(); t != members.end(); ++t) { + n.insert(*t); + } + members = n; +} + + +guild& guild::fill_from_json(discord_client* shard, nlohmann::json* d) { + /* NOTE: This can be called by GUILD_UPDATE and also GUILD_CREATE. + * GUILD_UPDATE sends a partial guild object, so we use Set*NotNull functions + * for a lot of the values under the assumption they may sometimes be missing. + */ + this->id = SnowflakeNotNull(d, "id"); + if (d->find("unavailable") == d->end() || (*d)["unavailable"].get() == false) { + /* Clear unavailable flag if set */ + if (this->flags & dpp::g_unavailable) { + this->flags -= dpp::g_unavailable; + } + SetStringNotNull(d, "name", this->name); + /* Special case for guild icon to allow for animated icons. + * Animated icons start with a_ on the name, so we use this to set a flag + * in the flags field and then just store the iconhash separately. + */ + std::string _icon = StringNotNull(d, "icon"); + if (!_icon.empty()) { + if (_icon.length() > 2 && _icon.substr(0, 2) == "a_") { + _icon = _icon.substr(2, _icon.length()); + this->flags |= g_has_animated_icon; + } + this->icon = _icon; + } + std::string _dsplash = StringNotNull(d, "discovery_splash"); + if (!_dsplash.empty()) { + this->discovery_splash = _dsplash; + } + SetSnowflakeNotNull(d, "owner_id", this->owner_id); + if (!(*d)["region"].is_null()) { + auto r = regionmap.find((*d)["region"].get()); + if (r != regionmap.end()) { + this->voice_region = r->second; + } + } + this->flags |= BoolNotNull(d, "large") ? dpp::g_large : 0; + this->flags |= BoolNotNull(d, "widget_enabled") ? dpp::g_widget_enabled : 0; + + for (auto & feature : (*d)["features"]) { + auto f = featuremap.find(feature.get()); + if (f != featuremap.end()) { + this->flags |= f->second; + } + } + uint8_t scf = Int8NotNull(d, "system_channel_flags"); + if (scf & 1) { + this->flags |= dpp::g_no_join_notifications; + } + if (scf & 2) { + this->flags |= dpp::g_no_boost_notifications; + } + + SetSnowflakeNotNull(d, "afk_channel_id", this->afk_channel_id); + SetInt8NotNull(d, "afk_timeout", this->afk_timeout); + SetSnowflakeNotNull(d, "widget_channel_id", this->widget_channel_id); + SetInt8NotNull(d, "verification_level", this->verification_level); + SetInt8NotNull(d, "default_message_notifications", this->default_message_notifications); + SetInt8NotNull(d, "explicit_content_filter", this->explicit_content_filter); + SetInt8NotNull(d, "mfa_level", this->mfa_level); + SetSnowflakeNotNull(d, "application_id", this->application_id); + SetSnowflakeNotNull(d, "system_channel_id", this->system_channel_id); + SetSnowflakeNotNull(d, "rules_channel_id", this->rules_channel_id); + SetInt32NotNull(d, "member_count", this->member_count); + SetStringNotNull(d, "vanity_url_code", this->vanity_url_code); + SetStringNotNull(d, "description", this->description); + if (d->find("voice_states") != d->end()) { + this->voice_members.clear(); + for (auto & vm : (*d)["voice_states"]) { + voicestate vs; + vs.fill_from_json(&vm); + vs.shard = shard; + vs.guild_id = this->id; + this->voice_members[vs.user_id] = vs; + } + } + + std::string _banner = StringNotNull(d, "banner"); + if (!_banner.empty()) { + this->banner = _banner; + } + SetInt8NotNull(d, "premium_tier", this->premium_tier); + SetInt16NotNull(d, "premium_subscription_count", this->premium_subscription_count); + SetSnowflakeNotNull(d, "public_updates_channel_id", this->public_updates_channel_id); + SetInt16NotNull(d, "max_video_channel_users", this->max_video_channel_users); + } else { + this->flags |= dpp::g_unavailable; + } + return *this; +} + +guild_widget::guild_widget() : enabled(false), channel_id(0) +{ +} + +guild_widget& guild_widget::fill_from_json(nlohmann::json* j) { + enabled = BoolNotNull(j, "enabled"); + channel_id = SnowflakeNotNull(j, "channel_id"); + return *this; +} + +std::string guild_widget::build_json() const { + return json({{"channel_id", channel_id}, {"enabled", enabled}}).dump(); +} + + +uint64_t guild::base_permissions(const user* member) const +{ + if (owner_id == member->id) + return ~0; + + role* everyone = dpp::find_role(id); + auto mi = members.find(member->id); + if (mi == members.end()) + return 0; + guild_member gm = mi->second; + + uint64_t permissions = everyone->permissions; + + for (auto& rid : gm.roles) { + role* r = dpp::find_role(rid); + permissions |= r->permissions; + } + + if (permissions & p_administrator) + return ~0; + + return permissions; +} + +uint64_t guild::permission_overwrites(const uint64_t base_permissions, const user* member, const channel* channel) const +{ + if (base_permissions & p_administrator) + return ~0; + + int64_t permissions = base_permissions; + for (auto it = channel->permission_overwrites.begin(); it != channel->permission_overwrites.end(); ++it) { + if (it->id == id && it->type == ot_role) { + permissions &= ~it->deny; + permissions |= it->allow; + break; + } + } + + auto mi = members.find(member->id); + if (mi == members.end()) + return 0; + guild_member gm = mi->second; + uint64_t allow = 0; + uint64_t deny = 0; + + for (auto& rid : gm.roles) { + + /* Skip \@everyone, calculated above */ + if (rid == id) + continue; + + for (auto it = channel->permission_overwrites.begin(); it != channel->permission_overwrites.end(); ++it) { + if ((rid == it->id && it->type == ot_role) || (member->id == it->id && it->type == ot_member)) { + allow |= it->allow; + deny |= it->deny; + break; + } + } + } + + permissions &= ~deny; + permissions |= allow; + + return permissions; +} + +bool guild::connect_member_voice(snowflake user_id) { + for (auto & c : channels) { + channel* ch = dpp::find_channel(c); + if (!ch || (!ch->is_voice_channel() && !ch->is_stage_channel())) { + continue; + } + auto vcmembers = ch->get_voice_members(); + auto vsi = vcmembers.find(user_id); + if (vsi != vcmembers.end()) { + if (vsi->second.shard) { + vsi->second.shard->connect_voice(this->id, vsi->second.channel_id); + return true; + } + } + } + return false; +} + + + +}; diff --git a/vendor/DPP/src/dpp/httplib.cpp b/vendor/DPP/src/dpp/httplib.cpp new file mode 100644 index 00000000..938412db --- /dev/null +++ b/vendor/DPP/src/dpp/httplib.cpp @@ -0,0 +1,6193 @@ +#include +#include +#include +#define CPPHTTPLIB_OPENSSL_SUPPORT +#include + +namespace httplib { + +/* + * Implementation + */ + +namespace detail { + +bool is_hex(char c, int &v) { + if (0x20 <= c && isdigit(c)) { + v = c - '0'; + return true; + } else if ('A' <= c && c <= 'F') { + v = c - 'A' + 10; + return true; + } else if ('a' <= c && c <= 'f') { + v = c - 'a' + 10; + return true; + } + return false; +} + +bool from_hex_to_i(const std::string &s, size_t i, size_t cnt, + int &val) { + if (i >= s.size()) { return false; } + + val = 0; + for (; cnt; i++, cnt--) { + if (!s[i]) { return false; } + int v = 0; + if (is_hex(s[i], v)) { + val = val * 16 + v; + } else { + return false; + } + } + return true; +} + +std::string from_i_to_hex(size_t n) { + const char *charset = "0123456789abcdef"; + std::string ret; + do { + ret = charset[n & 15] + ret; + n >>= 4; + } while (n > 0); + return ret; +} + +size_t to_utf8(int code, char *buff) { + if (code < 0x0080) { + buff[0] = (code & 0x7F); + return 1; + } else if (code < 0x0800) { + buff[0] = static_cast(0xC0 | ((code >> 6) & 0x1F)); + buff[1] = static_cast(0x80 | (code & 0x3F)); + return 2; + } else if (code < 0xD800) { + buff[0] = static_cast(0xE0 | ((code >> 12) & 0xF)); + buff[1] = static_cast(0x80 | ((code >> 6) & 0x3F)); + buff[2] = static_cast(0x80 | (code & 0x3F)); + return 3; + } else if (code < 0xE000) { // D800 - DFFF is invalid... + return 0; + } else if (code < 0x10000) { + buff[0] = static_cast(0xE0 | ((code >> 12) & 0xF)); + buff[1] = static_cast(0x80 | ((code >> 6) & 0x3F)); + buff[2] = static_cast(0x80 | (code & 0x3F)); + return 3; + } else if (code < 0x110000) { + buff[0] = static_cast(0xF0 | ((code >> 18) & 0x7)); + buff[1] = static_cast(0x80 | ((code >> 12) & 0x3F)); + buff[2] = static_cast(0x80 | ((code >> 6) & 0x3F)); + buff[3] = static_cast(0x80 | (code & 0x3F)); + return 4; + } + + // NOTREACHED + return 0; +} + +// NOTE: This code came up with the following stackoverflow post: +// https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c +std::string base64_encode(const std::string &in) { + static const auto lookup = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + + std::string out; + out.reserve(in.size()); + + int val = 0; + int valb = -6; + + for (auto c : in) { + val = (val << 8) + static_cast(c); + valb += 8; + while (valb >= 0) { + out.push_back(lookup[(val >> valb) & 0x3F]); + valb -= 6; + } + } + + if (valb > -6) { out.push_back(lookup[((val << 8) >> (valb + 8)) & 0x3F]); } + + while (out.size() % 4) { + out.push_back('='); + } + + return out; +} + +bool is_file(const std::string &path) { + struct stat st; + return stat(path.c_str(), &st) >= 0 && S_ISREG(st.st_mode); +} + +bool is_dir(const std::string &path) { + struct stat st; + return stat(path.c_str(), &st) >= 0 && S_ISDIR(st.st_mode); +} + +bool is_valid_path(const std::string &path) { + size_t level = 0; + size_t i = 0; + + // Skip slash + while (i < path.size() && path[i] == '/') { + i++; + } + + while (i < path.size()) { + // Read component + auto beg = i; + while (i < path.size() && path[i] != '/') { + i++; + } + + auto len = i - beg; + assert(len > 0); + + if (!path.compare(beg, len, ".")) { + ; + } else if (!path.compare(beg, len, "..")) { + if (level == 0) { return false; } + level--; + } else { + level++; + } + + // Skip slash + while (i < path.size() && path[i] == '/') { + i++; + } + } + + return true; +} + +std::string encode_query_param(const std::string &value) { + std::ostringstream escaped; + escaped.fill('0'); + escaped << std::hex; + + for (auto c : value) { + if (std::isalnum(static_cast(c)) || c == '-' || c == '_' || + c == '.' || c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' || + c == ')') { + escaped << c; + } else { + escaped << std::uppercase; + escaped << '%' << std::setw(2) + << static_cast(static_cast(c)); + escaped << std::nouppercase; + } + } + + return escaped.str(); +} + +std::string encode_url(const std::string &s) { + std::string result; + result.reserve(s.size()); + + for (size_t i = 0; s[i]; i++) { + switch (s[i]) { + case ' ': result += "%20"; break; + case '+': result += "%2B"; break; + case '\r': result += "%0D"; break; + case '\n': result += "%0A"; break; + case '\'': result += "%27"; break; + case ',': result += "%2C"; break; + // case ':': result += "%3A"; break; // ok? probably... + case ';': result += "%3B"; break; + default: + auto c = static_cast(s[i]); + if (c >= 0x80) { + result += '%'; + char hex[4]; + auto len = snprintf(hex, sizeof(hex) - 1, "%02X", c); + assert(len == 2); + result.append(hex, static_cast(len)); + } else { + result += s[i]; + } + break; + } + } + + return result; +} + +std::string decode_url(const std::string &s, + bool convert_plus_to_space) { + std::string result; + + for (size_t i = 0; i < s.size(); i++) { + if (s[i] == '%' && i + 1 < s.size()) { + if (s[i + 1] == 'u') { + int val = 0; + if (from_hex_to_i(s, i + 2, 4, val)) { + // 4 digits Unicode codes + char buff[4]; + size_t len = to_utf8(val, buff); + if (len > 0) { result.append(buff, len); } + i += 5; // 'u0000' + } else { + result += s[i]; + } + } else { + int val = 0; + if (from_hex_to_i(s, i + 1, 2, val)) { + // 2 digits hex codes + result += static_cast(val); + i += 2; // '00' + } else { + result += s[i]; + } + } + } else if (convert_plus_to_space && s[i] == '+') { + result += ' '; + } else { + result += s[i]; + } + } + + return result; +} + +void read_file(const std::string &path, std::string &out) { + std::ifstream fs(path, std::ios_base::binary); + fs.seekg(0, std::ios_base::end); + auto size = fs.tellg(); + fs.seekg(0); + out.resize(static_cast(size)); + fs.read(&out[0], static_cast(size)); +} + +std::string file_extension(const std::string &path) { + std::smatch m; + static auto re = std::regex("\\.([a-zA-Z0-9]+)$"); + if (std::regex_search(path, m, re)) { return m[1].str(); } + return std::string(); +} + +bool is_space_or_tab(char c) { return c == ' ' || c == '\t'; } + +std::pair trim(const char *b, const char *e, size_t left, + size_t right) { + while (b + left < e && is_space_or_tab(b[left])) { + left++; + } + while (right > 0 && is_space_or_tab(b[right - 1])) { + right--; + } + return std::make_pair(left, right); +} + +std::string trim_copy(const std::string &s) { + auto r = trim(s.data(), s.data() + s.size(), 0, s.size()); + return s.substr(r.first, r.second - r.first); +} + +template void split(const char *b, const char *e, char d, Fn fn) { + size_t i = 0; + size_t beg = 0; + + while (e ? (b + i < e) : (b[i] != '\0')) { + if (b[i] == d) { + auto r = trim(b, e, beg, i); + if (r.first < r.second) { fn(&b[r.first], &b[r.second]); } + beg = i + 1; + } + i++; + } + + if (i) { + auto r = trim(b, e, beg, i); + if (r.first < r.second) { fn(&b[r.first], &b[r.second]); } + } +} + +// NOTE: until the read size reaches `fixed_buffer_size`, use `fixed_buffer` +// to store data. The call can set memory on stack for performance. +class stream_line_reader { +public: + stream_line_reader(Stream &strm, char *fixed_buffer, size_t fixed_buffer_size) + : strm_(strm), fixed_buffer_(fixed_buffer), + fixed_buffer_size_(fixed_buffer_size) {} + + const char *ptr() const { + if (glowable_buffer_.empty()) { + return fixed_buffer_; + } else { + return glowable_buffer_.data(); + } + } + + size_t size() const { + if (glowable_buffer_.empty()) { + return fixed_buffer_used_size_; + } else { + return glowable_buffer_.size(); + } + } + + bool end_with_crlf() const { + auto end = ptr() + size(); + return size() >= 2 && end[-2] == '\r' && end[-1] == '\n'; + } + + bool getline() { + fixed_buffer_used_size_ = 0; + glowable_buffer_.clear(); + + for (size_t i = 0;; i++) { + char byte; + auto n = strm_.read(&byte, 1); + + if (n < 0) { + return false; + } else if (n == 0) { + if (i == 0) { + return false; + } else { + break; + } + } + + append(byte); + + if (byte == '\n') { break; } + } + + return true; + } + +private: + void append(char c) { + if (fixed_buffer_used_size_ < fixed_buffer_size_ - 1) { + fixed_buffer_[fixed_buffer_used_size_++] = c; + fixed_buffer_[fixed_buffer_used_size_] = '\0'; + } else { + if (glowable_buffer_.empty()) { + assert(fixed_buffer_[fixed_buffer_used_size_] == '\0'); + glowable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_); + } + glowable_buffer_ += c; + } + } + + Stream &strm_; + char *fixed_buffer_; + const size_t fixed_buffer_size_; + size_t fixed_buffer_used_size_ = 0; + std::string glowable_buffer_; +}; + +int close_socket(socket_t sock) { +#ifdef _WIN32 + if (sock >= 0 && sock < FD_SETSIZE) { + return closesocket(sock); + } +#else + return close(sock); +#endif +} + +template ssize_t handle_EINTR(T fn) { + ssize_t res = false; + while (true) { + res = fn(); + if (res < 0 && errno == EINTR) { continue; } + break; + } + return res; +} + +ssize_t select_read(socket_t sock, time_t sec, time_t usec) { +#ifdef CPPHTTPLIB_USE_POLL + struct pollfd pfd_read; + pfd_read.fd = sock; + pfd_read.events = POLLIN; + + auto timeout = static_cast(sec * 1000 + usec / 1000); + + return handle_EINTR([&]() { return poll(&pfd_read, 1, timeout); }); +#else +#ifndef _WIN32 + if (sock >= FD_SETSIZE) { return 1; } +#endif + + fd_set fds; + FD_ZERO(&fds); + FD_SET(sock, &fds); + + timeval tv; + tv.tv_sec = static_cast(sec); + tv.tv_usec = static_cast(usec); + + return handle_EINTR([&]() { + return select(static_cast(sock + 1), &fds, nullptr, nullptr, &tv); + }); +#endif +} + +ssize_t select_write(socket_t sock, time_t sec, time_t usec) { +#ifdef CPPHTTPLIB_USE_POLL + struct pollfd pfd_read; + pfd_read.fd = sock; + pfd_read.events = POLLOUT; + + auto timeout = static_cast(sec * 1000 + usec / 1000); + + return handle_EINTR([&]() { return poll(&pfd_read, 1, timeout); }); +#else +#ifndef _WIN32 + if (sock >= FD_SETSIZE) { return 1; } +#endif + + fd_set fds; + FD_ZERO(&fds); + FD_SET(sock, &fds); + + timeval tv; + tv.tv_sec = static_cast(sec); + tv.tv_usec = static_cast(usec); + + return handle_EINTR([&]() { + return select(static_cast(sock + 1), nullptr, &fds, nullptr, &tv); + }); +#endif +} + +bool wait_until_socket_is_ready(socket_t sock, time_t sec, time_t usec) { +#ifdef CPPHTTPLIB_USE_POLL + struct pollfd pfd_read; + pfd_read.fd = sock; + pfd_read.events = POLLIN | POLLOUT; + + auto timeout = static_cast(sec * 1000 + usec / 1000); + + auto poll_res = handle_EINTR([&]() { return poll(&pfd_read, 1, timeout); }); + + if (poll_res > 0 && pfd_read.revents & (POLLIN | POLLOUT)) { + int error = 0; + socklen_t len = sizeof(error); + auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR, + reinterpret_cast(&error), &len); + return res >= 0 && !error; + } + return false; +#else +#ifndef _WIN32 + if (sock >= FD_SETSIZE) { return false; } +#endif + + fd_set fdsr; + FD_ZERO(&fdsr); + FD_SET(sock, &fdsr); + + auto fdsw = fdsr; + auto fdse = fdsr; + + timeval tv; + tv.tv_sec = static_cast(sec); + tv.tv_usec = static_cast(usec); + + auto ret = handle_EINTR([&]() { + return select(static_cast(sock + 1), &fdsr, &fdsw, &fdse, &tv); + }); + + if (ret > 0 && (FD_ISSET(sock, &fdsr) || FD_ISSET(sock, &fdsw))) { + int error = 0; + socklen_t len = sizeof(error); + return getsockopt(sock, SOL_SOCKET, SO_ERROR, + reinterpret_cast(&error), &len) >= 0 && + !error; + } + return false; +#endif +} + +class SocketStream : public Stream { +public: + SocketStream(socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec, + time_t write_timeout_sec, time_t write_timeout_usec); + ~SocketStream() override; + + bool is_readable() const override; + bool is_writable() const override; + ssize_t read(char *ptr, size_t size) override; + ssize_t write(const char *ptr, size_t size) override; + void get_remote_ip_and_port(std::string &ip, int &port) const override; + socket_t socket() const override; + +private: + socket_t sock_; + time_t read_timeout_sec_; + time_t read_timeout_usec_; + time_t write_timeout_sec_; + time_t write_timeout_usec_; +}; + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT +class SSLSocketStream : public Stream { +public: + SSLSocketStream(socket_t sock, SSL *ssl, time_t read_timeout_sec, + time_t read_timeout_usec, time_t write_timeout_sec, + time_t write_timeout_usec); + ~SSLSocketStream() override; + + bool is_readable() const override; + bool is_writable() const override; + ssize_t read(char *ptr, size_t size) override; + ssize_t write(const char *ptr, size_t size) override; + void get_remote_ip_and_port(std::string &ip, int &port) const override; + socket_t socket() const override; + +private: + socket_t sock_; + SSL *ssl_; + time_t read_timeout_sec_; + time_t read_timeout_usec_; + time_t write_timeout_sec_; + time_t write_timeout_usec_; +}; +#endif + +class BufferStream : public Stream { +public: + BufferStream() = default; + ~BufferStream() override = default; + + bool is_readable() const override; + bool is_writable() const override; + ssize_t read(char *ptr, size_t size) override; + ssize_t write(const char *ptr, size_t size) override; + void get_remote_ip_and_port(std::string &ip, int &port) const override; + socket_t socket() const override; + + const std::string &get_buffer() const; + +private: + std::string buffer; + size_t position = 0; +}; + +bool keep_alive(socket_t sock, time_t keep_alive_timeout_sec) { + using namespace std::chrono; + auto start = steady_clock::now(); + while (true) { + auto val = select_read(sock, 0, 10000); + if (val < 0) { + return false; + } else if (val == 0) { + auto current = steady_clock::now(); + auto duration = duration_cast(current - start); + auto timeout = keep_alive_timeout_sec * 1000; + if (duration.count() > timeout) { return false; } + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } else { + return true; + } + } +} + +template +bool +process_server_socket_core(socket_t sock, size_t keep_alive_max_count, + time_t keep_alive_timeout_sec, T callback) { + assert(keep_alive_max_count > 0); + auto ret = false; + auto count = keep_alive_max_count; + while (count > 0 && keep_alive(sock, keep_alive_timeout_sec)) { + auto close_connection = count == 1; + auto connection_closed = false; + ret = callback(close_connection, connection_closed); + if (!ret || connection_closed) { break; } + count--; + } + return ret; +} + +template +bool +process_server_socket(socket_t sock, size_t keep_alive_max_count, + time_t keep_alive_timeout_sec, time_t read_timeout_sec, + time_t read_timeout_usec, time_t write_timeout_sec, + time_t write_timeout_usec, T callback) { + return process_server_socket_core( + sock, keep_alive_max_count, keep_alive_timeout_sec, + [&](bool close_connection, bool &connection_closed) { + SocketStream strm(sock, read_timeout_sec, read_timeout_usec, + write_timeout_sec, write_timeout_usec); + return callback(strm, close_connection, connection_closed); + }); +} + +template +bool process_client_socket(socket_t sock, time_t read_timeout_sec, + time_t read_timeout_usec, + time_t write_timeout_sec, + time_t write_timeout_usec, T callback) { + SocketStream strm(sock, read_timeout_sec, read_timeout_usec, + write_timeout_sec, write_timeout_usec); + return callback(strm); +} + +int shutdown_socket(socket_t sock) { +#ifdef _WIN32 + return shutdown(sock, SD_BOTH); +#else + return shutdown(sock, SHUT_RDWR); +#endif +} + +template +socket_t create_socket(const char *host, int port, int address_family, + int socket_flags, bool tcp_nodelay, + SocketOptions socket_options, + BindOrConnect bind_or_connect) { + // Get address info + struct addrinfo hints; + struct addrinfo *result; + + memset(&hints, 0, sizeof(struct addrinfo)); + hints.ai_family = address_family; + hints.ai_socktype = SOCK_STREAM; + hints.ai_flags = socket_flags; + hints.ai_protocol = 0; + + auto service = std::to_string(port); + + if (getaddrinfo(host, service.c_str(), &hints, &result)) { +#ifdef __linux__ + res_init(); +#endif + return INVALID_SOCKET; + } + + for (auto rp = result; rp; rp = rp->ai_next) { + // Create a socket +#ifdef _WIN32 + auto sock = + WSASocketW(rp->ai_family, rp->ai_socktype, rp->ai_protocol, nullptr, 0, + WSA_FLAG_NO_HANDLE_INHERIT | WSA_FLAG_OVERLAPPED); + /** + * Since the WSA_FLAG_NO_HANDLE_INHERIT is only supported on Windows 7 SP1 + * and above the socket creation fails on older Windows Systems. + * + * Let's try to create a socket the old way in this case. + * + * Reference: + * https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasocketa + * + * WSA_FLAG_NO_HANDLE_INHERIT: + * This flag is supported on Windows 7 with SP1, Windows Server 2008 R2 with + * SP1, and later + * + */ + if (sock == INVALID_SOCKET) { + sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); + } +#else + auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); +#endif + if (sock == INVALID_SOCKET) { continue; } + +#ifndef _WIN32 + if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1) { continue; } +#endif + + if (tcp_nodelay) { + int yes = 1; + setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast(&yes), + sizeof(yes)); + } + + if (socket_options) { socket_options(sock); } + + if (rp->ai_family == AF_INET6) { + int no = 0; + setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, reinterpret_cast(&no), + sizeof(no)); + } + + // bind or connect + if (bind_or_connect(sock, *rp)) { + freeaddrinfo(result); + return sock; + } + + close_socket(sock); + } + + freeaddrinfo(result); + return INVALID_SOCKET; +} + +void set_nonblocking(socket_t sock, bool nonblocking) { +#ifdef _WIN32 + auto flags = nonblocking ? 1UL : 0UL; + ioctlsocket(sock, FIONBIO, &flags); +#else + auto flags = fcntl(sock, F_GETFL, 0); + fcntl(sock, F_SETFL, + nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK))); +#endif +} + +bool is_connection_error() { +#ifdef _WIN32 + return WSAGetLastError() != WSAEWOULDBLOCK; +#else + return errno != EINPROGRESS; +#endif +} + +bool bind_ip_address(socket_t sock, const char *host) { + struct addrinfo hints; + struct addrinfo *result; + + memset(&hints, 0, sizeof(struct addrinfo)); + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_STREAM; + hints.ai_protocol = 0; + + if (getaddrinfo(host, "0", &hints, &result)) { return false; } + + auto ret = false; + for (auto rp = result; rp; rp = rp->ai_next) { + const auto &ai = *rp; + if (!::bind(sock, ai.ai_addr, static_cast(ai.ai_addrlen))) { + ret = true; + break; + } + } + + freeaddrinfo(result); + return ret; +} + +#if !defined _WIN32 && !defined ANDROID +#define USE_IF2IP +#endif + +#ifdef USE_IF2IP +std::string if2ip(const std::string &ifn) { + struct ifaddrs *ifap; + getifaddrs(&ifap); + for (auto ifa = ifap; ifa; ifa = ifa->ifa_next) { + if (ifa->ifa_addr && ifn == ifa->ifa_name) { + if (ifa->ifa_addr->sa_family == AF_INET) { + auto sa = reinterpret_cast(ifa->ifa_addr); + char buf[INET_ADDRSTRLEN]; + if (inet_ntop(AF_INET, &sa->sin_addr, buf, INET_ADDRSTRLEN)) { + freeifaddrs(ifap); + return std::string(buf, INET_ADDRSTRLEN); + } + } + } + } + freeifaddrs(ifap); + return std::string(); +} +#endif + +socket_t create_client_socket( + const char *host, int port, int address_family, bool tcp_nodelay, + SocketOptions socket_options, time_t connection_timeout_sec, + time_t connection_timeout_usec, time_t read_timeout_sec, + time_t read_timeout_usec, time_t write_timeout_sec, + time_t write_timeout_usec, const std::string &intf, Error &error) { + auto sock = create_socket( + host, port, address_family, 0, tcp_nodelay, std::move(socket_options), + [&](socket_t sock, struct addrinfo &ai) -> bool { + if (!intf.empty()) { +#ifdef USE_IF2IP + auto ip = if2ip(intf); + if (ip.empty()) { ip = intf; } + if (!bind_ip_address(sock, ip.c_str())) { + error = Error::BindIPAddress; + return false; + } +#endif + } + + set_nonblocking(sock, true); + + auto ret = + ::connect(sock, ai.ai_addr, static_cast(ai.ai_addrlen)); + + if (ret < 0) { + if (is_connection_error() || + !wait_until_socket_is_ready(sock, connection_timeout_sec, + connection_timeout_usec)) { + error = Error::Connection; + return false; + } + } + + set_nonblocking(sock, false); + + { + timeval tv; + tv.tv_sec = static_cast(read_timeout_sec); + tv.tv_usec = static_cast(read_timeout_usec); + setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv)); + } + { + timeval tv; + tv.tv_sec = static_cast(write_timeout_sec); + tv.tv_usec = static_cast(write_timeout_usec); + setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (char *)&tv, sizeof(tv)); + } + + error = Error::Success; + return true; + }); + + if (sock != INVALID_SOCKET) { + error = Error::Success; + } else { + if (error == Error::Success) { error = Error::Connection; } + } + + return sock; +} + +void get_remote_ip_and_port(const struct sockaddr_storage &addr, + socklen_t addr_len, std::string &ip, + int &port) { + if (addr.ss_family == AF_INET) { + port = ntohs(reinterpret_cast(&addr)->sin_port); + } else if (addr.ss_family == AF_INET6) { + port = + ntohs(reinterpret_cast(&addr)->sin6_port); + } + + std::array ipstr{}; + if (!getnameinfo(reinterpret_cast(&addr), addr_len, + ipstr.data(), static_cast(ipstr.size()), nullptr, + 0, NI_NUMERICHOST)) { + ip = ipstr.data(); + } +} + +void get_remote_ip_and_port(socket_t sock, std::string &ip, int &port) { + struct sockaddr_storage addr; + socklen_t addr_len = sizeof(addr); + + if (!getpeername(sock, reinterpret_cast(&addr), + &addr_len)) { + get_remote_ip_and_port(addr, addr_len, ip, port); + } +} + +constexpr unsigned int str2tag_core(const char *s, size_t l, + unsigned int h) { + return (l == 0) ? h + : str2tag_core(s + 1, l - 1, + (h * 33) ^ static_cast(*s)); +} + +unsigned int str2tag(const std::string &s) { + return str2tag_core(s.data(), s.size(), 0); +} + +namespace udl { + +constexpr unsigned int operator"" _(const char *s, size_t l) { + return str2tag_core(s, l, 0); +} + +} // namespace udl + +const char * +find_content_type(const std::string &path, + const std::map &user_data) { + auto ext = file_extension(path); + + auto it = user_data.find(ext); + if (it != user_data.end()) { return it->second.c_str(); } + + using udl::operator""_; + + switch (str2tag(ext)) { + default: return nullptr; + case "css"_: return "text/css"; + case "csv"_: return "text/csv"; + case "txt"_: return "text/plain"; + case "vtt"_: return "text/vtt"; + case "htm"_: + case "html"_: return "text/html"; + + case "apng"_: return "image/apng"; + case "avif"_: return "image/avif"; + case "bmp"_: return "image/bmp"; + case "gif"_: return "image/gif"; + case "png"_: return "image/png"; + case "svg"_: return "image/svg+xml"; + case "webp"_: return "image/webp"; + case "ico"_: return "image/x-icon"; + case "tif"_: return "image/tiff"; + case "tiff"_: return "image/tiff"; + case "jpg"_: + case "jpeg"_: return "image/jpeg"; + + case "mp4"_: return "video/mp4"; + case "mpeg"_: return "video/mpeg"; + case "webm"_: return "video/webm"; + + case "mp3"_: return "audio/mp3"; + case "mpga"_: return "audio/mpeg"; + case "weba"_: return "audio/webm"; + case "wav"_: return "audio/wave"; + + case "otf"_: return "font/otf"; + case "ttf"_: return "font/ttf"; + case "woff"_: return "font/woff"; + case "woff2"_: return "font/woff2"; + + case "7z"_: return "application/x-7z-compressed"; + case "atom"_: return "application/atom+xml"; + case "pdf"_: return "application/pdf"; + case "js"_: + case "mjs"_: return "application/javascript"; + case "json"_: return "application/json"; + case "rss"_: return "application/rss+xml"; + case "tar"_: return "application/x-tar"; + case "xht"_: + case "xhtml"_: return "application/xhtml+xml"; + case "xslt"_: return "application/xslt+xml"; + case "xml"_: return "application/xml"; + case "gz"_: return "application/gzip"; + case "zip"_: return "application/zip"; + case "wasm"_: return "application/wasm"; + } +} + +const char *status_message(int status) { + switch (status) { + case 100: return "Continue"; + case 101: return "Switching Protocol"; + case 102: return "Processing"; + case 103: return "Early Hints"; + case 200: return "OK"; + case 201: return "Created"; + case 202: return "Accepted"; + case 203: return "Non-Authoritative Information"; + case 204: return "No Content"; + case 205: return "Reset Content"; + case 206: return "Partial Content"; + case 207: return "Multi-Status"; + case 208: return "Already Reported"; + case 226: return "IM Used"; + case 300: return "Multiple Choice"; + case 301: return "Moved Permanently"; + case 302: return "Found"; + case 303: return "See Other"; + case 304: return "Not Modified"; + case 305: return "Use Proxy"; + case 306: return "unused"; + case 307: return "Temporary Redirect"; + case 308: return "Permanent Redirect"; + case 400: return "Bad Request"; + case 401: return "Unauthorized"; + case 402: return "Payment Required"; + case 403: return "Forbidden"; + case 404: return "Not Found"; + case 405: return "Method Not Allowed"; + case 406: return "Not Acceptable"; + case 407: return "Proxy Authentication Required"; + case 408: return "Request Timeout"; + case 409: return "Conflict"; + case 410: return "Gone"; + case 411: return "Length Required"; + case 412: return "Precondition Failed"; + case 413: return "Payload Too Large"; + case 414: return "URI Too Long"; + case 415: return "Unsupported Media Type"; + case 416: return "Range Not Satisfiable"; + case 417: return "Expectation Failed"; + case 418: return "I'm a teapot"; + case 421: return "Misdirected Request"; + case 422: return "Unprocessable Entity"; + case 423: return "Locked"; + case 424: return "Failed Dependency"; + case 425: return "Too Early"; + case 426: return "Upgrade Required"; + case 428: return "Precondition Required"; + case 429: return "Too Many Requests"; + case 431: return "Request Header Fields Too Large"; + case 451: return "Unavailable For Legal Reasons"; + case 501: return "Not Implemented"; + case 502: return "Bad Gateway"; + case 503: return "Service Unavailable"; + case 504: return "Gateway Timeout"; + case 505: return "HTTP Version Not Supported"; + case 506: return "Variant Also Negotiates"; + case 507: return "Insufficient Storage"; + case 508: return "Loop Detected"; + case 510: return "Not Extended"; + case 511: return "Network Authentication Required"; + + default: + case 500: return "Internal Server Error"; + } +} + +bool can_compress_content_type(const std::string &content_type) { + return (!content_type.find("text/") && content_type != "text/event-stream") || + content_type == "image/svg+xml" || + content_type == "application/javascript" || + content_type == "application/json" || + content_type == "application/xml" || + content_type == "application/xhtml+xml"; +} + +enum class EncodingType { None = 0, Gzip, Brotli }; + +EncodingType encoding_type(const Request &req, const Response &res) { + auto ret = + detail::can_compress_content_type(res.get_header_value("Content-Type")); + if (!ret) { return EncodingType::None; } + + const auto &s = req.get_header_value("Accept-Encoding"); + (void)(s); + +#ifdef CPPHTTPLIB_BROTLI_SUPPORT + // TODO: 'Accept-Encoding' has br, not br;q=0 + ret = s.find("br") != std::string::npos; + if (ret) { return EncodingType::Brotli; } +#endif + +#ifdef CPPHTTPLIB_ZLIB_SUPPORT + // TODO: 'Accept-Encoding' has gzip, not gzip;q=0 + ret = s.find("gzip") != std::string::npos; + if (ret) { return EncodingType::Gzip; } +#endif + + return EncodingType::None; +} + +class compressor { +public: + virtual ~compressor(){}; + + typedef std::function Callback; + virtual bool compress(const char *data, size_t data_length, bool last, + Callback callback) = 0; +}; + +class decompressor { +public: + virtual ~decompressor() {} + + virtual bool is_valid() const = 0; + + typedef std::function Callback; + virtual bool decompress(const char *data, size_t data_length, + Callback callback) = 0; +}; + +class nocompressor : public compressor { +public: + ~nocompressor(){}; + + bool compress(const char *data, size_t data_length, bool /*last*/, + Callback callback) override { + if (!data_length) { return true; } + return callback(data, data_length); + } +}; + +#ifdef CPPHTTPLIB_ZLIB_SUPPORT +class gzip_compressor : public compressor { +public: + gzip_compressor() { + std::memset(&strm_, 0, sizeof(strm_)); + strm_.zalloc = Z_NULL; + strm_.zfree = Z_NULL; + strm_.opaque = Z_NULL; + + is_valid_ = deflateInit2(&strm_, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8, + Z_DEFAULT_STRATEGY) == Z_OK; + } + + ~gzip_compressor() { deflateEnd(&strm_); } + + bool compress(const char *data, size_t data_length, bool last, + Callback callback) override { + assert(is_valid_); + + auto flush = last ? Z_FINISH : Z_NO_FLUSH; + + strm_.avail_in = static_cast(data_length); + strm_.next_in = const_cast(reinterpret_cast(data)); + + int ret = Z_OK; + + std::array buff{}; + do { + strm_.avail_out = buff.size(); + strm_.next_out = reinterpret_cast(buff.data()); + + ret = deflate(&strm_, flush); + if (ret == Z_STREAM_ERROR) { return false; } + + if (!callback(buff.data(), buff.size() - strm_.avail_out)) { + return false; + } + } while (strm_.avail_out == 0); + + assert((last && ret == Z_STREAM_END) || (!last && ret == Z_OK)); + assert(strm_.avail_in == 0); + return true; + } + +private: + bool is_valid_ = false; + z_stream strm_; +}; + +class gzip_decompressor : public decompressor { +public: + gzip_decompressor() { + std::memset(&strm_, 0, sizeof(strm_)); + strm_.zalloc = Z_NULL; + strm_.zfree = Z_NULL; + strm_.opaque = Z_NULL; + + // 15 is the value of wbits, which should be at the maximum possible value + // to ensure that any gzip stream can be decoded. The offset of 32 specifies + // that the stream type should be automatically detected either gzip or + // deflate. + is_valid_ = inflateInit2(&strm_, 32 + 15) == Z_OK; + } + + ~gzip_decompressor() { inflateEnd(&strm_); } + + bool is_valid() const override { return is_valid_; } + + bool decompress(const char *data, size_t data_length, + Callback callback) override { + assert(is_valid_); + + int ret = Z_OK; + + strm_.avail_in = static_cast(data_length); + strm_.next_in = const_cast(reinterpret_cast(data)); + + std::array buff{}; + while (strm_.avail_in > 0) { + strm_.avail_out = buff.size(); + strm_.next_out = reinterpret_cast(buff.data()); + + ret = inflate(&strm_, Z_NO_FLUSH); + assert(ret != Z_STREAM_ERROR); + switch (ret) { + case Z_NEED_DICT: + case Z_DATA_ERROR: + case Z_MEM_ERROR: inflateEnd(&strm_); return false; + } + + if (!callback(buff.data(), buff.size() - strm_.avail_out)) { + return false; + } + } + + return ret == Z_OK || ret == Z_STREAM_END; + } + +private: + bool is_valid_ = false; + z_stream strm_; +}; +#endif + +#ifdef CPPHTTPLIB_BROTLI_SUPPORT +class brotli_compressor : public compressor { +public: + brotli_compressor() { + state_ = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr); + } + + ~brotli_compressor() { BrotliEncoderDestroyInstance(state_); } + + bool compress(const char *data, size_t data_length, bool last, + Callback callback) override { + std::array buff{}; + + auto operation = last ? BROTLI_OPERATION_FINISH : BROTLI_OPERATION_PROCESS; + auto available_in = data_length; + auto next_in = reinterpret_cast(data); + + for (;;) { + if (last) { + if (BrotliEncoderIsFinished(state_)) { break; } + } else { + if (!available_in) { break; } + } + + auto available_out = buff.size(); + auto next_out = buff.data(); + + if (!BrotliEncoderCompressStream(state_, operation, &available_in, + &next_in, &available_out, &next_out, + nullptr)) { + return false; + } + + auto output_bytes = buff.size() - available_out; + if (output_bytes) { + callback(reinterpret_cast(buff.data()), output_bytes); + } + } + + return true; + } + +private: + BrotliEncoderState *state_ = nullptr; +}; + +class brotli_decompressor : public decompressor { +public: + brotli_decompressor() { + decoder_s = BrotliDecoderCreateInstance(0, 0, 0); + decoder_r = decoder_s ? BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT + : BROTLI_DECODER_RESULT_ERROR; + } + + ~brotli_decompressor() { + if (decoder_s) { BrotliDecoderDestroyInstance(decoder_s); } + } + + bool is_valid() const override { return decoder_s; } + + bool decompress(const char *data, size_t data_length, + Callback callback) override { + if (decoder_r == BROTLI_DECODER_RESULT_SUCCESS || + decoder_r == BROTLI_DECODER_RESULT_ERROR) { + return 0; + } + + const uint8_t *next_in = (const uint8_t *)data; + size_t avail_in = data_length; + size_t total_out; + + decoder_r = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT; + + std::array buff{}; + while (decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) { + char *next_out = buff.data(); + size_t avail_out = buff.size(); + + decoder_r = BrotliDecoderDecompressStream( + decoder_s, &avail_in, &next_in, &avail_out, + reinterpret_cast(&next_out), &total_out); + + if (decoder_r == BROTLI_DECODER_RESULT_ERROR) { return false; } + + if (!callback(buff.data(), buff.size() - avail_out)) { return false; } + } + + return decoder_r == BROTLI_DECODER_RESULT_SUCCESS || + decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT; + } + +private: + BrotliDecoderResult decoder_r; + BrotliDecoderState *decoder_s = nullptr; +}; +#endif + +bool has_header(const Headers &headers, const char *key) { + return headers.find(key) != headers.end(); +} + +const char *get_header_value(const Headers &headers, const char *key, + size_t id = 0, const char *def = nullptr) { + auto rng = headers.equal_range(key); + auto it = rng.first; + std::advance(it, static_cast(id)); + if (it != rng.second) { return it->second.c_str(); } + return def; +} + +template +T get_header_value(const Headers & /*headers*/, const char * /*key*/, + size_t /*id*/ = 0, uint64_t /*def*/ = 0) {} + +template <> +uint64_t get_header_value(const Headers &headers, + const char *key, size_t id, + uint64_t def) { + auto rng = headers.equal_range(key); + auto it = rng.first; + std::advance(it, static_cast(id)); + if (it != rng.second) { + return std::strtoull(it->second.data(), nullptr, 10); + } + return def; +} + +template +bool parse_header(const char *beg, const char *end, T fn) { + // Skip trailing spaces and tabs. + while (beg < end && is_space_or_tab(end[-1])) { + end--; + } + + auto p = beg; + while (p < end && *p != ':') { + p++; + } + + if (p == end) { return false; } + + auto key_end = p; + + if (*p++ != ':') { return false; } + + while (p < end && is_space_or_tab(*p)) { + p++; + } + + if (p < end) { + fn(std::string(beg, key_end), decode_url(std::string(p, end), false)); + return true; + } + + return false; +} + +bool read_headers(Stream &strm, Headers &headers) { + const auto bufsiz = 2048; + char buf[bufsiz]; + stream_line_reader line_reader(strm, buf, bufsiz); + + for (;;) { + if (!line_reader.getline()) { return false; } + + // Check if the line ends with CRLF. + if (line_reader.end_with_crlf()) { + // Blank line indicates end of headers. + if (line_reader.size() == 2) { break; } + } else { + continue; // Skip invalid line. + } + + // Exclude CRLF + auto end = line_reader.ptr() + line_reader.size() - 2; + + parse_header(line_reader.ptr(), end, + [&](std::string &&key, std::string &&val) { + headers.emplace(std::move(key), std::move(val)); + }); + } + + return true; +} + +bool read_content_with_length(Stream &strm, uint64_t len, + Progress progress, + ContentReceiverWithProgress out) { + char buf[CPPHTTPLIB_RECV_BUFSIZ]; + + uint64_t r = 0; + while (r < len) { + auto read_len = static_cast(len - r); + auto n = strm.read(buf, (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ)); + if (n <= 0) { return false; } + + if (!out(buf, static_cast(n), r, len)) { return false; } + r += static_cast(n); + + if (progress) { + if (!progress(r, len)) { return false; } + } + } + + return true; +} + +void skip_content_with_length(Stream &strm, uint64_t len) { + char buf[CPPHTTPLIB_RECV_BUFSIZ]; + uint64_t r = 0; + while (r < len) { + auto read_len = static_cast(len - r); + auto n = strm.read(buf, (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ)); + if (n <= 0) { return; } + r += static_cast(n); + } +} + +bool read_content_without_length(Stream &strm, + ContentReceiverWithProgress out) { + char buf[CPPHTTPLIB_RECV_BUFSIZ]; + uint64_t r = 0; + for (;;) { + auto n = strm.read(buf, CPPHTTPLIB_RECV_BUFSIZ); + if (n < 0) { + return false; + } else if (n == 0) { + return true; + } + + if (!out(buf, static_cast(n), r, 0)) { return false; } + r += static_cast(n); + } + + return true; +} + +bool read_content_chunked(Stream &strm, + ContentReceiverWithProgress out) { + const auto bufsiz = 16; + char buf[bufsiz]; + + stream_line_reader line_reader(strm, buf, bufsiz); + + if (!line_reader.getline()) { return false; } + + unsigned long chunk_len; + while (true) { + char *end_ptr; + + chunk_len = std::strtoul(line_reader.ptr(), &end_ptr, 16); + + if (end_ptr == line_reader.ptr()) { return false; } + if (chunk_len == ULONG_MAX) { return false; } + + if (chunk_len == 0) { break; } + + if (!read_content_with_length(strm, chunk_len, nullptr, out)) { + return false; + } + + if (!line_reader.getline()) { return false; } + + if (strcmp(line_reader.ptr(), "\r\n")) { break; } + + if (!line_reader.getline()) { return false; } + } + + if (chunk_len == 0) { + // Reader terminator after chunks + if (!line_reader.getline() || strcmp(line_reader.ptr(), "\r\n")) + return false; + } + + return true; +} + +bool is_chunked_transfer_encoding(const Headers &headers) { + return !strcasecmp(get_header_value(headers, "Transfer-Encoding", 0, ""), + "chunked"); +} + +template +bool prepare_content_receiver(T &x, int &status, + ContentReceiverWithProgress receiver, + bool decompress, U callback) { + if (decompress) { + std::string encoding = x.get_header_value("Content-Encoding"); + std::unique_ptr decompressor; + + if (encoding.find("gzip") != std::string::npos || + encoding.find("deflate") != std::string::npos) { +#ifdef CPPHTTPLIB_ZLIB_SUPPORT + decompressor = detail::make_unique(); +#else + status = 415; + return false; +#endif + } else if (encoding.find("br") != std::string::npos) { +#ifdef CPPHTTPLIB_BROTLI_SUPPORT + decompressor = detail::make_unique(); +#else + status = 415; + return false; +#endif + } + + if (decompressor) { + if (decompressor->is_valid()) { + ContentReceiverWithProgress out = [&](const char *buf, size_t n, + uint64_t off, uint64_t len) { + return decompressor->decompress(buf, n, + [&](const char *buf, size_t n) { + return receiver(buf, n, off, len); + }); + }; + return callback(std::move(out)); + } else { + status = 500; + return false; + } + } + } + + ContentReceiverWithProgress out = [&](const char *buf, size_t n, uint64_t off, + uint64_t len) { + return receiver(buf, n, off, len); + }; + return callback(std::move(out)); +} + +template +bool read_content(Stream &strm, T &x, size_t payload_max_length, int &status, + Progress progress, ContentReceiverWithProgress receiver, + bool decompress) { + return prepare_content_receiver( + x, status, std::move(receiver), decompress, + [&](const ContentReceiverWithProgress &out) { + auto ret = true; + auto exceed_payload_max_length = false; + + if (is_chunked_transfer_encoding(x.headers)) { + ret = read_content_chunked(strm, out); + } else if (!has_header(x.headers, "Content-Length")) { + ret = read_content_without_length(strm, out); + } else { + auto len = get_header_value(x.headers, "Content-Length"); + if (len > payload_max_length) { + exceed_payload_max_length = true; + skip_content_with_length(strm, len); + ret = false; + } else if (len > 0) { + ret = read_content_with_length(strm, len, std::move(progress), out); + } + } + + if (!ret) { status = exceed_payload_max_length ? 413 : 400; } + return ret; + }); +} + +ssize_t write_headers(Stream &strm, const Headers &headers) { + ssize_t write_len = 0; + for (const auto &x : headers) { + auto len = + strm.write_format("%s: %s\r\n", x.first.c_str(), x.second.c_str()); + if (len < 0) { return len; } + write_len += len; + } + auto len = strm.write("\r\n"); + if (len < 0) { return len; } + write_len += len; + return write_len; +} + +bool write_data(Stream &strm, const char *d, size_t l) { + size_t offset = 0; + while (offset < l) { + auto length = strm.write(d + offset, l - offset); + if (length < 0) { return false; } + offset += static_cast(length); + } + return true; +} + +template +bool write_content(Stream &strm, const ContentProvider &content_provider, + size_t offset, size_t length, T is_shutting_down, + Error &error) { + size_t end_offset = offset + length; + auto ok = true; + DataSink data_sink; + + data_sink.write = [&](const char *d, size_t l) -> bool { + if (ok) { + if (write_data(strm, d, l)) { + offset += l; + } else { + ok = false; + } + } + return ok; + }; + + data_sink.is_writable = [&](void) { return ok && strm.is_writable(); }; + + while (offset < end_offset && !is_shutting_down()) { + if (!content_provider(offset, end_offset - offset, data_sink)) { + error = Error::Canceled; + return false; + } + if (!ok) { + error = Error::Write; + return false; + } + } + + error = Error::Success; + return true; +} + +template +bool write_content(Stream &strm, const ContentProvider &content_provider, + size_t offset, size_t length, + const T &is_shutting_down) { + auto error = Error::Success; + return write_content(strm, content_provider, offset, length, is_shutting_down, + error); +} + +template +bool +write_content_without_length(Stream &strm, + const ContentProvider &content_provider, + const T &is_shutting_down) { + size_t offset = 0; + auto data_available = true; + auto ok = true; + DataSink data_sink; + + data_sink.write = [&](const char *d, size_t l) -> bool { + if (ok) { + offset += l; + if (!write_data(strm, d, l)) { ok = false; } + } + return ok; + }; + + data_sink.done = [&](void) { data_available = false; }; + + data_sink.is_writable = [&](void) { return ok && strm.is_writable(); }; + + while (data_available && !is_shutting_down()) { + if (!content_provider(offset, 0, data_sink)) { return false; } + if (!ok) { return false; } + } + return true; +} + +template +bool +write_content_chunked(Stream &strm, const ContentProvider &content_provider, + const T &is_shutting_down, U &compressor, Error &error) { + size_t offset = 0; + auto data_available = true; + auto ok = true; + DataSink data_sink; + + data_sink.write = [&](const char *d, size_t l) -> bool { + if (ok) { + data_available = l > 0; + offset += l; + + std::string payload; + if (compressor.compress(d, l, false, + [&](const char *data, size_t data_len) { + payload.append(data, data_len); + return true; + })) { + if (!payload.empty()) { + // Emit chunked response header and footer for each chunk + auto chunk = + from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n"; + if (!write_data(strm, chunk.data(), chunk.size())) { + ok = false; + } + } + } else { + ok = false; + } + } + return ok; + }; + + data_sink.done = [&](void) { + if (!ok) { return; } + + data_available = false; + + std::string payload; + if (!compressor.compress(nullptr, 0, true, + [&](const char *data, size_t data_len) { + payload.append(data, data_len); + return true; + })) { + ok = false; + return; + } + + if (!payload.empty()) { + // Emit chunked response header and footer for each chunk + auto chunk = from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n"; + if (!write_data(strm, chunk.data(), chunk.size())) { + ok = false; + return; + } + } + + static const std::string done_marker("0\r\n\r\n"); + if (!write_data(strm, done_marker.data(), done_marker.size())) { + ok = false; + } + }; + + data_sink.is_writable = [&](void) { return ok && strm.is_writable(); }; + + while (data_available && !is_shutting_down()) { + if (!content_provider(offset, 0, data_sink)) { + error = Error::Canceled; + return false; + } + if (!ok) { + error = Error::Write; + return false; + } + } + + error = Error::Success; + return true; +} + +template +bool write_content_chunked(Stream &strm, + const ContentProvider &content_provider, + const T &is_shutting_down, U &compressor) { + auto error = Error::Success; + return write_content_chunked(strm, content_provider, is_shutting_down, + compressor, error); +} + +template +bool redirect(T &cli, Request &req, Response &res, + const std::string &path, const std::string &location, + Error &error) { + Request new_req = req; + new_req.path = path; + new_req.redirect_count_ -= 1; + + if (res.status == 303 && (req.method != "GET" && req.method != "HEAD")) { + new_req.method = "GET"; + new_req.body.clear(); + new_req.headers.clear(); + } + + Response new_res; + + auto ret = cli.send(new_req, new_res, error); + if (ret) { + req = new_req; + res = new_res; + res.location = location; + } + return ret; +} + +std::string params_to_query_str(const Params ¶ms) { + std::string query; + + for (auto it = params.begin(); it != params.end(); ++it) { + if (it != params.begin()) { query += "&"; } + query += it->first; + query += "="; + query += encode_query_param(it->second); + } + return query; +} + +std::string append_query_params(const char *path, const Params ¶ms) { + std::string path_with_query = path; + const static std::regex re("[^?]+\\?.*"); + auto delm = std::regex_match(path, re) ? '&' : '?'; + path_with_query += delm + params_to_query_str(params); + return path_with_query; +} + +void parse_query_text(const std::string &s, Params ¶ms) { + std::set cache; + split(s.data(), s.data() + s.size(), '&', [&](const char *b, const char *e) { + std::string kv(b, e); + if (cache.find(kv) != cache.end()) { return; } + cache.insert(kv); + + std::string key; + std::string val; + split(b, e, '=', [&](const char *b2, const char *e2) { + if (key.empty()) { + key.assign(b2, e2); + } else { + val.assign(b2, e2); + } + }); + + if (!key.empty()) { + params.emplace(decode_url(key, true), decode_url(val, true)); + } + }); +} + +bool parse_multipart_boundary(const std::string &content_type, + std::string &boundary) { + auto pos = content_type.find("boundary="); + if (pos == std::string::npos) { return false; } + boundary = content_type.substr(pos + 9); + if (boundary.length() >= 2 && boundary.front() == '"' && + boundary.back() == '"') { + boundary = boundary.substr(1, boundary.size() - 2); + } + return !boundary.empty(); +} + +bool parse_range_header(const std::string &s, Ranges &ranges) try { + static auto re_first_range = std::regex(R"(bytes=(\d*-\d*(?:,\s*\d*-\d*)*))"); + std::smatch m; + if (std::regex_match(s, m, re_first_range)) { + auto pos = static_cast(m.position(1)); + auto len = static_cast(m.length(1)); + bool all_valid_ranges = true; + split(&s[pos], &s[pos + len], ',', [&](const char *b, const char *e) { + if (!all_valid_ranges) return; + static auto re_another_range = std::regex(R"(\s*(\d*)-(\d*))"); + std::cmatch cm; + if (std::regex_match(b, e, cm, re_another_range)) { + ssize_t first = -1; + if (!cm.str(1).empty()) { + first = static_cast(std::stoll(cm.str(1))); + } + + ssize_t last = -1; + if (!cm.str(2).empty()) { + last = static_cast(std::stoll(cm.str(2))); + } + + if (first != -1 && last != -1 && first > last) { + all_valid_ranges = false; + return; + } + ranges.emplace_back(std::make_pair(first, last)); + } + }); + return all_valid_ranges; + } + return false; +} catch (...) { return false; } + +class MultipartFormDataParser { +public: + MultipartFormDataParser() = default; + + void set_boundary(std::string &&boundary) { boundary_ = boundary; } + + bool is_valid() const { return is_valid_; } + + bool parse(const char *buf, size_t n, const ContentReceiver &content_callback, + const MultipartContentHeader &header_callback) { + + static const std::regex re_content_disposition( + "^Content-Disposition:\\s*form-data;\\s*name=\"(.*?)\"(?:;\\s*filename=" + "\"(.*?)\")?\\s*$", + std::regex_constants::icase); + static const std::string dash_ = "--"; + static const std::string crlf_ = "\r\n"; + + buf_.append(buf, n); // TODO: performance improvement + + while (!buf_.empty()) { + switch (state_) { + case 0: { // Initial boundary + auto pattern = dash_ + boundary_ + crlf_; + if (pattern.size() > buf_.size()) { return true; } + auto pos = buf_.find(pattern); + if (pos != 0) { return false; } + buf_.erase(0, pattern.size()); + off_ += pattern.size(); + state_ = 1; + break; + } + case 1: { // New entry + clear_file_info(); + state_ = 2; + break; + } + case 2: { // Headers + auto pos = buf_.find(crlf_); + while (pos != std::string::npos) { + // Empty line + if (pos == 0) { + if (!header_callback(file_)) { + is_valid_ = false; + return false; + } + buf_.erase(0, crlf_.size()); + off_ += crlf_.size(); + state_ = 3; + break; + } + + static const std::string header_name = "content-type:"; + const auto header = buf_.substr(0, pos); + if (start_with_case_ignore(header, header_name)) { + file_.content_type = trim_copy(header.substr(header_name.size())); + } else { + std::smatch m; + if (std::regex_match(header, m, re_content_disposition)) { + file_.name = m[1]; + file_.filename = m[2]; + } + } + + buf_.erase(0, pos + crlf_.size()); + off_ += pos + crlf_.size(); + pos = buf_.find(crlf_); + } + if (state_ != 3) { return true; } + break; + } + case 3: { // Body + { + auto pattern = crlf_ + dash_; + if (pattern.size() > buf_.size()) { return true; } + + auto pos = find_string(buf_, pattern); + + if (!content_callback(buf_.data(), pos)) { + is_valid_ = false; + return false; + } + + off_ += pos; + buf_.erase(0, pos); + } + { + auto pattern = crlf_ + dash_ + boundary_; + if (pattern.size() > buf_.size()) { return true; } + + auto pos = buf_.find(pattern); + if (pos != std::string::npos) { + if (!content_callback(buf_.data(), pos)) { + is_valid_ = false; + return false; + } + + off_ += pos + pattern.size(); + buf_.erase(0, pos + pattern.size()); + state_ = 4; + } else { + if (!content_callback(buf_.data(), pattern.size())) { + is_valid_ = false; + return false; + } + + off_ += pattern.size(); + buf_.erase(0, pattern.size()); + } + } + break; + } + case 4: { // Boundary + if (crlf_.size() > buf_.size()) { return true; } + if (buf_.compare(0, crlf_.size(), crlf_) == 0) { + buf_.erase(0, crlf_.size()); + off_ += crlf_.size(); + state_ = 1; + } else { + auto pattern = dash_ + crlf_; + if (pattern.size() > buf_.size()) { return true; } + if (buf_.compare(0, pattern.size(), pattern) == 0) { + buf_.erase(0, pattern.size()); + off_ += pattern.size(); + is_valid_ = true; + state_ = 5; + } else { + return true; + } + } + break; + } + case 5: { // Done + is_valid_ = false; + return false; + } + } + } + + return true; + } + +private: + void clear_file_info() { + file_.name.clear(); + file_.filename.clear(); + file_.content_type.clear(); + } + + bool start_with_case_ignore(const std::string &a, + const std::string &b) const { + if (a.size() < b.size()) { return false; } + for (size_t i = 0; i < b.size(); i++) { + if (::tolower(a[i]) != ::tolower(b[i])) { return false; } + } + return true; + } + + bool start_with(const std::string &a, size_t off, + const std::string &b) const { + if (a.size() - off < b.size()) { return false; } + for (size_t i = 0; i < b.size(); i++) { + if (a[i + off] != b[i]) { return false; } + } + return true; + } + + size_t find_string(const std::string &s, const std::string &pattern) const { + auto c = pattern.front(); + + size_t off = 0; + while (off < s.size()) { + auto pos = s.find(c, off); + if (pos == std::string::npos) { return s.size(); } + + auto rem = s.size() - pos; + if (pattern.size() > rem) { return pos; } + + if (start_with(s, pos, pattern)) { return pos; } + + off = pos + 1; + } + + return s.size(); + } + + std::string boundary_; + + std::string buf_; + size_t state_ = 0; + bool is_valid_ = false; + size_t off_ = 0; + MultipartFormData file_; +}; + +std::string to_lower(const char *beg, const char *end) { + std::string out; + auto it = beg; + while (it != end) { + out += static_cast(::tolower(*it)); + it++; + } + return out; +} + +std::string make_multipart_data_boundary() { + static const char data[] = + "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; + + // std::random_device might actually be deterministic on some + // platforms, but due to lack of support in the c++ standard library, + // doing better requires either some ugly hacks or breaking portability. + std::random_device seed_gen; + // Request 128 bits of entropy for initialization + std::seed_seq seed_sequence{seed_gen(), seed_gen(), seed_gen(), seed_gen()}; + std::mt19937 engine(seed_sequence); + + std::string result = "--cpp-httplib-multipart-data-"; + + for (auto i = 0; i < 16; i++) { + result += data[engine() % (sizeof(data) - 1)]; + } + + return result; +} + +std::pair +get_range_offset_and_length(const Request &req, size_t content_length, + size_t index) { + auto r = req.ranges[index]; + + if (r.first == -1 && r.second == -1) { + return std::make_pair(0, content_length); + } + + auto slen = static_cast(content_length); + + if (r.first == -1) { + r.first = (std::max)(static_cast(0), slen - r.second); + r.second = slen - 1; + } + + if (r.second == -1) { r.second = slen - 1; } + return std::make_pair(r.first, static_cast(r.second - r.first) + 1); +} + +std::string make_content_range_header_field(size_t offset, size_t length, + size_t content_length) { + std::string field = "bytes "; + field += std::to_string(offset); + field += "-"; + field += std::to_string(offset + length - 1); + field += "/"; + field += std::to_string(content_length); + return field; +} + +template +bool process_multipart_ranges_data(const Request &req, Response &res, + const std::string &boundary, + const std::string &content_type, + SToken stoken, CToken ctoken, + Content content) { + for (size_t i = 0; i < req.ranges.size(); i++) { + ctoken("--"); + stoken(boundary); + ctoken("\r\n"); + if (!content_type.empty()) { + ctoken("Content-Type: "); + stoken(content_type); + ctoken("\r\n"); + } + + auto offsets = get_range_offset_and_length(req, res.body.size(), i); + auto offset = offsets.first; + auto length = offsets.second; + + ctoken("Content-Range: "); + stoken(make_content_range_header_field(offset, length, res.body.size())); + ctoken("\r\n"); + ctoken("\r\n"); + if (!content(offset, length)) { return false; } + ctoken("\r\n"); + } + + ctoken("--"); + stoken(boundary); + ctoken("--\r\n"); + + return true; +} + +bool make_multipart_ranges_data(const Request &req, Response &res, + const std::string &boundary, + const std::string &content_type, + std::string &data) { + return process_multipart_ranges_data( + req, res, boundary, content_type, + [&](const std::string &token) { data += token; }, + [&](const char *token) { data += token; }, + [&](size_t offset, size_t length) { + if (offset < res.body.size()) { + data += res.body.substr(offset, length); + return true; + } + return false; + }); +} + +size_t +get_multipart_ranges_data_length(const Request &req, Response &res, + const std::string &boundary, + const std::string &content_type) { + size_t data_length = 0; + + process_multipart_ranges_data( + req, res, boundary, content_type, + [&](const std::string &token) { data_length += token.size(); }, + [&](const char *token) { data_length += strlen(token); }, + [&](size_t /*offset*/, size_t length) { + data_length += length; + return true; + }); + + return data_length; +} + +template +bool write_multipart_ranges_data(Stream &strm, const Request &req, + Response &res, + const std::string &boundary, + const std::string &content_type, + const T &is_shutting_down) { + return process_multipart_ranges_data( + req, res, boundary, content_type, + [&](const std::string &token) { strm.write(token); }, + [&](const char *token) { strm.write(token); }, + [&](size_t offset, size_t length) { + return write_content(strm, res.content_provider_, offset, length, + is_shutting_down); + }); +} + +std::pair +get_range_offset_and_length(const Request &req, const Response &res, + size_t index) { + auto r = req.ranges[index]; + + if (r.second == -1) { + r.second = static_cast(res.content_length_) - 1; + } + + return std::make_pair(r.first, r.second - r.first + 1); +} + +bool expect_content(const Request &req) { + if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH" || + req.method == "PRI" || req.method == "DELETE") { + return true; + } + // TODO: check if Content-Length is set + return false; +} + +bool has_crlf(const char *s) { + auto p = s; + while (*p) { + if (*p == '\r' || *p == '\n') { return true; } + p++; + } + return false; +} + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT +template +std::string message_digest(const std::string &s, Init init, + Update update, Final final, + size_t digest_length) { + using namespace std; + + std::vector md(digest_length, 0); + CTX ctx; + init(&ctx); + update(&ctx, s.data(), s.size()); + final(md.data(), &ctx); + + stringstream ss; + for (auto c : md) { + ss << setfill('0') << setw(2) << hex << (unsigned int)c; + } + return ss.str(); +} + +std::string MD5(const std::string &s) { + return message_digest(s, MD5_Init, MD5_Update, MD5_Final, + MD5_DIGEST_LENGTH); +} + +std::string SHA_256(const std::string &s) { + return message_digest(s, SHA256_Init, SHA256_Update, SHA256_Final, + SHA256_DIGEST_LENGTH); +} + +std::string SHA_512(const std::string &s) { + return message_digest(s, SHA512_Init, SHA512_Update, SHA512_Final, + SHA512_DIGEST_LENGTH); +} +#endif + +#ifdef _WIN32 +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT +// NOTE: This code came up with the following stackoverflow post: +// https://stackoverflow.com/questions/9507184/can-openssl-on-windows-use-the-system-certificate-store +bool load_system_certs_on_windows(X509_STORE *store) { + auto hStore = CertOpenSystemStoreW((HCRYPTPROV_LEGACY)NULL, L"ROOT"); + + if (!hStore) { return false; } + + PCCERT_CONTEXT pContext = NULL; + while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) != + nullptr) { + auto encoded_cert = + static_cast(pContext->pbCertEncoded); + + auto x509 = d2i_X509(NULL, &encoded_cert, pContext->cbCertEncoded); + if (x509) { + X509_STORE_add_cert(store, x509); + X509_free(x509); + } + } + + CertFreeCertificateContext(pContext); + CertCloseStore(hStore, 0); + + return true; +} +#endif + +class WSInit { +public: + WSInit() { + WSADATA wsaData; + WSAStartup(0x0002, &wsaData); + } + + ~WSInit() { WSACleanup(); } +}; + +static WSInit wsinit_; +#endif + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT +std::pair make_digest_authentication_header( + const Request &req, const std::map &auth, + size_t cnonce_count, const std::string &cnonce, const std::string &username, + const std::string &password, bool is_proxy = false) { + using namespace std; + + string nc; + { + stringstream ss; + ss << setfill('0') << setw(8) << hex << cnonce_count; + nc = ss.str(); + } + + auto qop = auth.at("qop"); + if (qop.find("auth-int") != std::string::npos) { + qop = "auth-int"; + } else { + qop = "auth"; + } + + std::string algo = "MD5"; + if (auth.find("algorithm") != auth.end()) { algo = auth.at("algorithm"); } + + string response; + { + auto H = algo == "SHA-256" ? detail::SHA_256 + : algo == "SHA-512" ? detail::SHA_512 + : detail::MD5; + + auto A1 = username + ":" + auth.at("realm") + ":" + password; + + auto A2 = req.method + ":" + req.path; + if (qop == "auth-int") { A2 += ":" + H(req.body); } + + response = H(H(A1) + ":" + auth.at("nonce") + ":" + nc + ":" + cnonce + + ":" + qop + ":" + H(A2)); + } + + auto field = "Digest username=\"" + username + "\", realm=\"" + + auth.at("realm") + "\", nonce=\"" + auth.at("nonce") + + "\", uri=\"" + req.path + "\", algorithm=" + algo + + ", qop=" + qop + ", nc=\"" + nc + "\", cnonce=\"" + cnonce + + "\", response=\"" + response + "\""; + + auto key = is_proxy ? "Proxy-Authorization" : "Authorization"; + return std::make_pair(key, field); +} +#endif + +bool parse_www_authenticate(const Response &res, + std::map &auth, + bool is_proxy) { + auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate"; + if (res.has_header(auth_key)) { + static auto re = std::regex(R"~((?:(?:,\s*)?(.+?)=(?:"(.*?)"|([^,]*))))~"); + auto s = res.get_header_value(auth_key); + auto pos = s.find(' '); + if (pos != std::string::npos) { + auto type = s.substr(0, pos); + if (type == "Basic") { + return false; + } else if (type == "Digest") { + s = s.substr(pos + 1); + auto beg = std::sregex_iterator(s.begin(), s.end(), re); + for (auto i = beg; i != std::sregex_iterator(); ++i) { + auto m = *i; + auto key = s.substr(static_cast(m.position(1)), + static_cast(m.length(1))); + auto val = m.length(2) > 0 + ? s.substr(static_cast(m.position(2)), + static_cast(m.length(2))) + : s.substr(static_cast(m.position(3)), + static_cast(m.length(3))); + auth[key] = val; + } + return true; + } + } + } + return false; +} + +// https://stackoverflow.com/questions/440133/how-do-i-create-a-random-alpha-numeric-string-in-c/440240#answer-440240 +std::string random_string(size_t length) { + auto randchar = []() -> char { + const char charset[] = "0123456789" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz"; + const size_t max_index = (sizeof(charset) - 1); + return charset[static_cast(std::rand()) % max_index]; + }; + std::string str(length, 0); + std::generate_n(str.begin(), length, randchar); + return str; +} + +class ContentProviderAdapter { +public: + explicit ContentProviderAdapter( + ContentProviderWithoutLength &&content_provider) + : content_provider_(content_provider) {} + + bool operator()(size_t offset, size_t, DataSink &sink) { + return content_provider_(offset, sink); + } + +private: + ContentProviderWithoutLength content_provider_; +}; + +template +void duration_to_sec_and_usec(const T &duration, U callback) { + auto sec = std::chrono::duration_cast(duration).count(); + auto usec = std::chrono::duration_cast( + duration - std::chrono::seconds(sec)) + .count(); + callback(sec, usec); +} + +} // namespace detail + +// Header utilities +std::pair make_range_header(Ranges ranges) { + std::string field = "bytes="; + auto i = 0; + for (auto r : ranges) { + if (i != 0) { field += ", "; } + if (r.first != -1) { field += std::to_string(r.first); } + field += '-'; + if (r.second != -1) { field += std::to_string(r.second); } + i++; + } + return std::make_pair("Range", std::move(field)); +} + +std::pair +make_basic_authentication_header(const std::string &username, + const std::string &password, + bool is_proxy = false) { + auto field = "Basic " + detail::base64_encode(username + ":" + password); + auto key = is_proxy ? "Proxy-Authorization" : "Authorization"; + return std::make_pair(key, std::move(field)); +} + +std::pair +make_bearer_token_authentication_header(const std::string &token, + bool is_proxy = false) { + auto field = "Bearer " + token; + auto key = is_proxy ? "Proxy-Authorization" : "Authorization"; + return std::make_pair(key, std::move(field)); +} + +// Request implementation +bool Request::has_header(const char *key) const { + return detail::has_header(headers, key); +} + +std::string Request::get_header_value(const char *key, size_t id) const { + return detail::get_header_value(headers, key, id, ""); +} + +template +T Request::get_header_value(const char *key, size_t id) const { + return detail::get_header_value(headers, key, id, 0); +} + +size_t Request::get_header_value_count(const char *key) const { + auto r = headers.equal_range(key); + return static_cast(std::distance(r.first, r.second)); +} + +void Request::set_header(const char *key, const char *val) { + if (!detail::has_crlf(key) && !detail::has_crlf(val)) { + headers.emplace(key, val); + } +} + +void Request::set_header(const char *key, const std::string &val) { + if (!detail::has_crlf(key) && !detail::has_crlf(val.c_str())) { + headers.emplace(key, val); + } +} + +bool Request::has_param(const char *key) const { + return params.find(key) != params.end(); +} + +std::string Request::get_param_value(const char *key, size_t id) const { + auto rng = params.equal_range(key); + auto it = rng.first; + std::advance(it, static_cast(id)); + if (it != rng.second) { return it->second; } + return std::string(); +} + +size_t Request::get_param_value_count(const char *key) const { + auto r = params.equal_range(key); + return static_cast(std::distance(r.first, r.second)); +} + +bool Request::is_multipart_form_data() const { + const auto &content_type = get_header_value("Content-Type"); + return !content_type.find("multipart/form-data"); +} + +bool Request::has_file(const char *key) const { + return files.find(key) != files.end(); +} + +MultipartFormData Request::get_file_value(const char *key) const { + auto it = files.find(key); + if (it != files.end()) { return it->second; } + return MultipartFormData(); +} + +// Response implementation +bool Response::has_header(const char *key) const { + return headers.find(key) != headers.end(); +} + +std::string Response::get_header_value(const char *key, + size_t id) const { + return detail::get_header_value(headers, key, id, ""); +} + +template +T Response::get_header_value(const char *key, size_t id) const { + return detail::get_header_value(headers, key, id, 0); +} + +size_t Response::get_header_value_count(const char *key) const { + auto r = headers.equal_range(key); + return static_cast(std::distance(r.first, r.second)); +} + +void Response::set_header(const char *key, const char *val) { + if (!detail::has_crlf(key) && !detail::has_crlf(val)) { + headers.emplace(key, val); + } +} + +void Response::set_header(const char *key, const std::string &val) { + if (!detail::has_crlf(key) && !detail::has_crlf(val.c_str())) { + headers.emplace(key, val); + } +} + +void Response::set_redirect(const char *url, int stat) { + if (!detail::has_crlf(url)) { + set_header("Location", url); + if (300 <= stat && stat < 400) { + this->status = stat; + } else { + this->status = 302; + } + } +} + +void Response::set_redirect(const std::string &url, int stat) { + set_redirect(url.c_str(), stat); +} + +void Response::set_content(const char *s, size_t n, + const char *content_type) { + body.assign(s, n); + + auto rng = headers.equal_range("Content-Type"); + headers.erase(rng.first, rng.second); + set_header("Content-Type", content_type); +} + +void Response::set_content(const std::string &s, + const char *content_type) { + set_content(s.data(), s.size(), content_type); +} + +void +Response::set_content_provider(size_t in_length, const char *content_type, + ContentProvider provider, + const std::function &resource_releaser) { + assert(in_length > 0); + set_header("Content-Type", content_type); + content_length_ = in_length; + content_provider_ = std::move(provider); + content_provider_resource_releaser_ = resource_releaser; + is_chunked_content_provider_ = false; +} + +void +Response::set_content_provider(const char *content_type, + ContentProviderWithoutLength provider, + const std::function &resource_releaser) { + set_header("Content-Type", content_type); + content_length_ = 0; + content_provider_ = detail::ContentProviderAdapter(std::move(provider)); + content_provider_resource_releaser_ = resource_releaser; + is_chunked_content_provider_ = false; +} + +void Response::set_chunked_content_provider( + const char *content_type, ContentProviderWithoutLength provider, + const std::function &resource_releaser) { + set_header("Content-Type", content_type); + content_length_ = 0; + content_provider_ = detail::ContentProviderAdapter(std::move(provider)); + content_provider_resource_releaser_ = resource_releaser; + is_chunked_content_provider_ = true; +} + +// Result implementation +bool Result::has_request_header(const char *key) const { + return request_headers_.find(key) != request_headers_.end(); +} + +std::string Result::get_request_header_value(const char *key, + size_t id) const { + return detail::get_header_value(request_headers_, key, id, ""); +} + +template +T Result::get_request_header_value(const char *key, size_t id) const { + return detail::get_header_value(request_headers_, key, id, 0); +} + +size_t Result::get_request_header_value_count(const char *key) const { + auto r = request_headers_.equal_range(key); + return static_cast(std::distance(r.first, r.second)); +} + +// Stream implementation +ssize_t Stream::write(const char *ptr) { + return write(ptr, strlen(ptr)); +} + +ssize_t Stream::write(const std::string &s) { + return write(s.data(), s.size()); +} + +template +ssize_t Stream::write_format(const char *fmt, const Args &...args) { + const auto bufsiz = 2048; + std::array buf; + +#if defined(_MSC_VER) && _MSC_VER < 1900 + auto sn = _snprintf_s(buf.data(), bufsiz - 1, buf.size() - 1, fmt, args...); +#else + auto sn = snprintf(buf.data(), buf.size() - 1, fmt, args...); +#endif + if (sn <= 0) { return sn; } + + auto n = static_cast(sn); + + if (n >= buf.size() - 1) { + std::vector glowable_buf(buf.size()); + + while (n >= glowable_buf.size() - 1) { + glowable_buf.resize(glowable_buf.size() * 2); +#if defined(_MSC_VER) && _MSC_VER < 1900 + n = static_cast(_snprintf_s(&glowable_buf[0], glowable_buf.size(), + glowable_buf.size() - 1, fmt, + args...)); +#else + n = static_cast( + snprintf(&glowable_buf[0], glowable_buf.size() - 1, fmt, args...)); +#endif + } + return write(&glowable_buf[0], n); + } else { + return write(buf.data(), n); + } +} + +namespace detail { + +// Socket stream implementation +SocketStream::SocketStream(socket_t sock, time_t read_timeout_sec, + time_t read_timeout_usec, + time_t write_timeout_sec, + time_t write_timeout_usec) + : sock_(sock), read_timeout_sec_(read_timeout_sec), + read_timeout_usec_(read_timeout_usec), + write_timeout_sec_(write_timeout_sec), + write_timeout_usec_(write_timeout_usec) {} + +SocketStream::~SocketStream() {} + +bool SocketStream::is_readable() const { + return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0; +} + +bool SocketStream::is_writable() const { + return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0; +} + +ssize_t SocketStream::read(char *ptr, size_t size) { + if (!is_readable()) { return -1; } + +#ifdef _WIN32 + if (size > static_cast((std::numeric_limits::max)())) { + return -1; + } + return recv(sock_, ptr, static_cast(size), CPPHTTPLIB_RECV_FLAGS); +#else + return handle_EINTR( + [&]() { return recv(sock_, ptr, size, CPPHTTPLIB_RECV_FLAGS); }); +#endif +} + +ssize_t SocketStream::write(const char *ptr, size_t size) { + if (!is_writable()) { return -1; } + +#ifdef _WIN32 + if (size > static_cast((std::numeric_limits::max)())) { + return -1; + } + return send(sock_, ptr, static_cast(size), CPPHTTPLIB_SEND_FLAGS); +#else + return handle_EINTR( + [&]() { return send(sock_, ptr, size, CPPHTTPLIB_SEND_FLAGS); }); +#endif +} + +void SocketStream::get_remote_ip_and_port(std::string &ip, + int &port) const { + return detail::get_remote_ip_and_port(sock_, ip, port); +} + +socket_t SocketStream::socket() const { return sock_; } + +// Buffer stream implementation +bool BufferStream::is_readable() const { return true; } + +bool BufferStream::is_writable() const { return true; } + +ssize_t BufferStream::read(char *ptr, size_t size) { +#if defined(_MSC_VER) && _MSC_VER <= 1900 + auto len_read = buffer._Copy_s(ptr, size, size, position); +#else + auto len_read = buffer.copy(ptr, size, position); +#endif + position += static_cast(len_read); + return static_cast(len_read); +} + +ssize_t BufferStream::write(const char *ptr, size_t size) { + buffer.append(ptr, size); + return static_cast(size); +} + +void BufferStream::get_remote_ip_and_port(std::string & /*ip*/, + int & /*port*/) const {} + +socket_t BufferStream::socket() const { return 0; } + +const std::string &BufferStream::get_buffer() const { return buffer; } + +} // namespace detail + +// HTTP server implementation +Server::Server() + : new_task_queue( + [] { return new ThreadPool(CPPHTTPLIB_THREAD_POOL_COUNT); }), + svr_sock_(INVALID_SOCKET), is_running_(false) { +#ifndef _WIN32 + signal(SIGPIPE, SIG_IGN); +#endif +} + +Server::~Server() {} + +Server &Server::Get(const char *pattern, Handler handler) { + return Get(pattern, strlen(pattern), handler); +} + +Server &Server::Get(const char *pattern, size_t pattern_len, + Handler handler) { + get_handlers_.push_back( + std::make_pair(std::regex(pattern, pattern_len), std::move(handler))); + return *this; +} + +Server &Server::Post(const char *pattern, Handler handler) { + return Post(pattern, strlen(pattern), handler); +} + +Server &Server::Post(const char *pattern, size_t pattern_len, + Handler handler) { + post_handlers_.push_back( + std::make_pair(std::regex(pattern, pattern_len), std::move(handler))); + return *this; +} + +Server &Server::Post(const char *pattern, + HandlerWithContentReader handler) { + return Post(pattern, strlen(pattern), handler); +} + +Server &Server::Post(const char *pattern, size_t pattern_len, + HandlerWithContentReader handler) { + post_handlers_for_content_reader_.push_back( + std::make_pair(std::regex(pattern, pattern_len), std::move(handler))); + return *this; +} + +Server &Server::Put(const char *pattern, Handler handler) { + return Put(pattern, strlen(pattern), handler); +} + +Server &Server::Put(const char *pattern, size_t pattern_len, + Handler handler) { + put_handlers_.push_back( + std::make_pair(std::regex(pattern, pattern_len), std::move(handler))); + return *this; +} + +Server &Server::Put(const char *pattern, + HandlerWithContentReader handler) { + return Put(pattern, strlen(pattern), handler); +} + +Server &Server::Put(const char *pattern, size_t pattern_len, + HandlerWithContentReader handler) { + put_handlers_for_content_reader_.push_back( + std::make_pair(std::regex(pattern, pattern_len), std::move(handler))); + return *this; +} + +Server &Server::Patch(const char *pattern, Handler handler) { + return Patch(pattern, strlen(pattern), handler); +} + +Server &Server::Patch(const char *pattern, size_t pattern_len, + Handler handler) { + patch_handlers_.push_back( + std::make_pair(std::regex(pattern, pattern_len), std::move(handler))); + return *this; +} + +Server &Server::Patch(const char *pattern, + HandlerWithContentReader handler) { + return Patch(pattern, strlen(pattern), handler); +} + +Server &Server::Patch(const char *pattern, size_t pattern_len, + HandlerWithContentReader handler) { + patch_handlers_for_content_reader_.push_back( + std::make_pair(std::regex(pattern, pattern_len), std::move(handler))); + return *this; +} + +Server &Server::Delete(const char *pattern, Handler handler) { + return Delete(pattern, strlen(pattern), handler); +} + +Server &Server::Delete(const char *pattern, size_t pattern_len, + Handler handler) { + delete_handlers_.push_back( + std::make_pair(std::regex(pattern, pattern_len), std::move(handler))); + return *this; +} + +Server &Server::Delete(const char *pattern, + HandlerWithContentReader handler) { + return Delete(pattern, strlen(pattern), handler); +} + +Server &Server::Delete(const char *pattern, size_t pattern_len, + HandlerWithContentReader handler) { + delete_handlers_for_content_reader_.push_back( + std::make_pair(std::regex(pattern, pattern_len), std::move(handler))); + return *this; +} + +Server &Server::Options(const char *pattern, Handler handler) { + return Options(pattern, strlen(pattern), handler); +} + +Server &Server::Options(const char *pattern, size_t pattern_len, + Handler handler) { + options_handlers_.push_back( + std::make_pair(std::regex(pattern, pattern_len), std::move(handler))); + return *this; +} + +bool Server::set_base_dir(const char *dir, const char *mount_point) { + return set_mount_point(mount_point, dir); +} + +bool Server::set_mount_point(const char *mount_point, const char *dir, + Headers headers) { + if (detail::is_dir(dir)) { + std::string mnt = mount_point ? mount_point : "/"; + if (!mnt.empty() && mnt[0] == '/') { + base_dirs_.push_back({mnt, dir, std::move(headers)}); + return true; + } + } + return false; +} + +bool Server::remove_mount_point(const char *mount_point) { + for (auto it = base_dirs_.begin(); it != base_dirs_.end(); ++it) { + if (it->mount_point == mount_point) { + base_dirs_.erase(it); + return true; + } + } + return false; +} + +Server & +Server::set_file_extension_and_mimetype_mapping(const char *ext, + const char *mime) { + file_extension_and_mimetype_map_[ext] = mime; + return *this; +} + +Server &Server::set_file_request_handler(Handler handler) { + file_request_handler_ = std::move(handler); + return *this; +} + +Server &Server::set_error_handler(HandlerWithResponse handler) { + error_handler_ = std::move(handler); + return *this; +} + +Server &Server::set_error_handler(Handler handler) { + error_handler_ = [handler](const Request &req, Response &res) { + handler(req, res); + return HandlerResponse::Handled; + }; + return *this; +} + +Server &Server::set_exception_handler(ExceptionHandler handler) { + exception_handler_ = std::move(handler); + return *this; +} + +Server &Server::set_pre_routing_handler(HandlerWithResponse handler) { + pre_routing_handler_ = std::move(handler); + return *this; +} + +Server &Server::set_post_routing_handler(Handler handler) { + post_routing_handler_ = std::move(handler); + return *this; +} + +Server &Server::set_logger(Logger logger) { + logger_ = std::move(logger); + return *this; +} + +Server & +Server::set_expect_100_continue_handler(Expect100ContinueHandler handler) { + expect_100_continue_handler_ = std::move(handler); + + return *this; +} + +Server &Server::set_address_family(int family) { + address_family_ = family; + return *this; +} + +Server &Server::set_tcp_nodelay(bool on) { + tcp_nodelay_ = on; + return *this; +} + +Server &Server::set_socket_options(SocketOptions socket_options) { + socket_options_ = std::move(socket_options); + return *this; +} + +Server &Server::set_keep_alive_max_count(size_t count) { + keep_alive_max_count_ = count; + return *this; +} + +Server &Server::set_keep_alive_timeout(time_t sec) { + keep_alive_timeout_sec_ = sec; + return *this; +} + +Server &Server::set_read_timeout(time_t sec, time_t usec) { + read_timeout_sec_ = sec; + read_timeout_usec_ = usec; + return *this; +} + +template +Server & +Server::set_read_timeout(const std::chrono::duration &duration) { + detail::duration_to_sec_and_usec( + duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); }); + return *this; +} + +Server &Server::set_write_timeout(time_t sec, time_t usec) { + write_timeout_sec_ = sec; + write_timeout_usec_ = usec; + return *this; +} + +template +Server & +Server::set_write_timeout(const std::chrono::duration &duration) { + detail::duration_to_sec_and_usec( + duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); }); + return *this; +} + +Server &Server::set_idle_interval(time_t sec, time_t usec) { + idle_interval_sec_ = sec; + idle_interval_usec_ = usec; + return *this; +} + +template +Server & +Server::set_idle_interval(const std::chrono::duration &duration) { + detail::duration_to_sec_and_usec( + duration, [&](time_t sec, time_t usec) { set_idle_interval(sec, usec); }); + return *this; +} + +Server &Server::set_payload_max_length(size_t length) { + payload_max_length_ = length; + return *this; +} + +bool Server::bind_to_port(const char *host, int port, int socket_flags) { + if (bind_internal(host, port, socket_flags) < 0) return false; + return true; +} +int Server::bind_to_any_port(const char *host, int socket_flags) { + return bind_internal(host, 0, socket_flags); +} + +bool Server::listen_after_bind() { return listen_internal(); } + +bool Server::listen(const char *host, int port, int socket_flags) { + return bind_to_port(host, port, socket_flags) && listen_internal(); +} + +bool Server::is_running() const { return is_running_; } + +void Server::stop() { + if (is_running_) { + assert(svr_sock_ != INVALID_SOCKET); + std::atomic sock(svr_sock_.exchange(INVALID_SOCKET)); + detail::shutdown_socket(sock); + detail::close_socket(sock); + } +} + +bool Server::parse_request_line(const char *s, Request &req) { + const static std::regex re( + "(GET|HEAD|POST|PUT|DELETE|CONNECT|OPTIONS|TRACE|PATCH|PRI) " + "(([^? ]+)(?:\\?([^ ]*?))?) (HTTP/1\\.[01])\r\n"); + + std::cmatch m; + if (std::regex_match(s, m, re)) { + req.version = std::string(m[5]); + req.method = std::string(m[1]); + req.target = std::string(m[2]); + req.path = detail::decode_url(m[3], false); + + // Parse query text + auto len = std::distance(m[4].first, m[4].second); + if (len > 0) { detail::parse_query_text(m[4], req.params); } + + return true; + } + + return false; +} + +bool Server::write_response(Stream &strm, bool close_connection, + const Request &req, Response &res) { + return write_response_core(strm, close_connection, req, res, false); +} + +bool Server::write_response_with_content(Stream &strm, + bool close_connection, + const Request &req, + Response &res) { + return write_response_core(strm, close_connection, req, res, true); +} + +bool Server::write_response_core(Stream &strm, bool close_connection, + const Request &req, Response &res, + bool need_apply_ranges) { + assert(res.status != -1); + + if (400 <= res.status && error_handler_ && + error_handler_(req, res) == HandlerResponse::Handled) { + need_apply_ranges = true; + } + + std::string content_type; + std::string boundary; + if (need_apply_ranges) { apply_ranges(req, res, content_type, boundary); } + + // Prepare additional headers + if (close_connection || req.get_header_value("Connection") == "close") { + res.set_header("Connection", "close"); + } else { + std::stringstream ss; + ss << "timeout=" << keep_alive_timeout_sec_ + << ", max=" << keep_alive_max_count_; + res.set_header("Keep-Alive", ss.str()); + } + + if (!res.has_header("Content-Type") && + (!res.body.empty() || res.content_length_ > 0 || res.content_provider_)) { + res.set_header("Content-Type", "text/plain"); + } + + if (!res.has_header("Content-Length") && res.body.empty() && + !res.content_length_ && !res.content_provider_) { + res.set_header("Content-Length", "0"); + } + + if (!res.has_header("Accept-Ranges") && req.method == "HEAD") { + res.set_header("Accept-Ranges", "bytes"); + } + + if (post_routing_handler_) { post_routing_handler_(req, res); } + + // Response line and headers + { + detail::BufferStream bstrm; + + if (!bstrm.write_format("HTTP/1.1 %d %s\r\n", res.status, + detail::status_message(res.status))) { + return false; + } + + if (!detail::write_headers(bstrm, res.headers)) { return false; } + + // Flush buffer + auto &data = bstrm.get_buffer(); + strm.write(data.data(), data.size()); + } + + // Body + auto ret = true; + if (req.method != "HEAD") { + if (!res.body.empty()) { + if (!strm.write(res.body)) { ret = false; } + } else if (res.content_provider_) { + if (!write_content_with_provider(strm, req, res, boundary, + content_type)) { + ret = false; + } + } + } + + // Log + if (logger_) { logger_(req, res); } + + return ret; +} + +bool +Server::write_content_with_provider(Stream &strm, const Request &req, + Response &res, const std::string &boundary, + const std::string &content_type) { + auto is_shutting_down = [this]() { + return this->svr_sock_ == INVALID_SOCKET; + }; + + if (res.content_length_ > 0) { + if (req.ranges.empty()) { + return detail::write_content(strm, res.content_provider_, 0, + res.content_length_, is_shutting_down); + } else if (req.ranges.size() == 1) { + auto offsets = + detail::get_range_offset_and_length(req, res.content_length_, 0); + auto offset = offsets.first; + auto length = offsets.second; + return detail::write_content(strm, res.content_provider_, offset, length, + is_shutting_down); + } else { + return detail::write_multipart_ranges_data( + strm, req, res, boundary, content_type, is_shutting_down); + } + } else { + if (res.is_chunked_content_provider_) { + auto type = detail::encoding_type(req, res); + + std::unique_ptr compressor; + if (type == detail::EncodingType::Gzip) { +#ifdef CPPHTTPLIB_ZLIB_SUPPORT + compressor = detail::make_unique(); +#endif + } else if (type == detail::EncodingType::Brotli) { +#ifdef CPPHTTPLIB_BROTLI_SUPPORT + compressor = detail::make_unique(); +#endif + } else { + compressor = detail::make_unique(); + } + assert(compressor != nullptr); + + return detail::write_content_chunked(strm, res.content_provider_, + is_shutting_down, *compressor); + } else { + return detail::write_content_without_length(strm, res.content_provider_, + is_shutting_down); + } + } +} + +bool Server::read_content(Stream &strm, Request &req, Response &res) { + MultipartFormDataMap::iterator cur; + if (read_content_core( + strm, req, res, + // Regular + [&](const char *buf, size_t n) { + if (req.body.size() + n > req.body.max_size()) { return false; } + req.body.append(buf, n); + return true; + }, + // Multipart + [&](const MultipartFormData &file) { + cur = req.files.emplace(file.name, file); + return true; + }, + [&](const char *buf, size_t n) { + auto &content = cur->second.content; + if (content.size() + n > content.max_size()) { return false; } + content.append(buf, n); + return true; + })) { + const auto &content_type = req.get_header_value("Content-Type"); + if (!content_type.find("application/x-www-form-urlencoded")) { + detail::parse_query_text(req.body, req.params); + } + return true; + } + return false; +} + +bool Server::read_content_with_content_receiver( + Stream &strm, Request &req, Response &res, ContentReceiver receiver, + MultipartContentHeader multipart_header, + ContentReceiver multipart_receiver) { + return read_content_core(strm, req, res, std::move(receiver), + std::move(multipart_header), + std::move(multipart_receiver)); +} + +bool Server::read_content_core(Stream &strm, Request &req, Response &res, + ContentReceiver receiver, + MultipartContentHeader mulitpart_header, + ContentReceiver multipart_receiver) { + detail::MultipartFormDataParser multipart_form_data_parser; + ContentReceiverWithProgress out; + + if (req.is_multipart_form_data()) { + const auto &content_type = req.get_header_value("Content-Type"); + std::string boundary; + if (!detail::parse_multipart_boundary(content_type, boundary)) { + res.status = 400; + return false; + } + + multipart_form_data_parser.set_boundary(std::move(boundary)); + out = [&](const char *buf, size_t n, uint64_t /*off*/, uint64_t /*len*/) { + /* For debug + size_t pos = 0; + while (pos < n) { + auto read_size = std::min(1, n - pos); + auto ret = multipart_form_data_parser.parse( + buf + pos, read_size, multipart_receiver, mulitpart_header); + if (!ret) { return false; } + pos += read_size; + } + return true; + */ + return multipart_form_data_parser.parse(buf, n, multipart_receiver, + mulitpart_header); + }; + } else { + out = [receiver](const char *buf, size_t n, uint64_t /*off*/, + uint64_t /*len*/) { return receiver(buf, n); }; + } + + if (req.method == "DELETE" && !req.has_header("Content-Length")) { + return true; + } + + if (!detail::read_content(strm, req, payload_max_length_, res.status, nullptr, + out, true)) { + return false; + } + + if (req.is_multipart_form_data()) { + if (!multipart_form_data_parser.is_valid()) { + res.status = 400; + return false; + } + } + + return true; +} + +bool Server::handle_file_request(const Request &req, Response &res, + bool head) { + for (const auto &entry : base_dirs_) { + // Prefix match + if (!req.path.compare(0, entry.mount_point.size(), entry.mount_point)) { + std::string sub_path = "/" + req.path.substr(entry.mount_point.size()); + if (detail::is_valid_path(sub_path)) { + auto path = entry.base_dir + sub_path; + if (path.back() == '/') { path += "index.html"; } + + if (detail::is_file(path)) { + detail::read_file(path, res.body); + auto type = + detail::find_content_type(path, file_extension_and_mimetype_map_); + if (type) { res.set_header("Content-Type", type); } + for (const auto &kv : entry.headers) { + res.set_header(kv.first.c_str(), kv.second); + } + res.status = req.has_header("Range") ? 206 : 200; + if (!head && file_request_handler_) { + file_request_handler_(req, res); + } + return true; + } + } + } + } + return false; +} + +socket_t +Server::create_server_socket(const char *host, int port, int socket_flags, + SocketOptions socket_options) const { + return detail::create_socket( + host, port, address_family_, socket_flags, tcp_nodelay_, + std::move(socket_options), + [](socket_t sock, struct addrinfo &ai) -> bool { + if (::bind(sock, ai.ai_addr, static_cast(ai.ai_addrlen))) { + return false; + } + if (::listen(sock, 5)) { // Listen through 5 channels + return false; + } + return true; + }); +} + +int Server::bind_internal(const char *host, int port, int socket_flags) { + if (!is_valid()) { return -1; } + + svr_sock_ = create_server_socket(host, port, socket_flags, socket_options_); + if (svr_sock_ == INVALID_SOCKET) { return -1; } + + if (port == 0) { + struct sockaddr_storage addr; + socklen_t addr_len = sizeof(addr); + if (getsockname(svr_sock_, reinterpret_cast(&addr), + &addr_len) == -1) { + return -1; + } + if (addr.ss_family == AF_INET) { + return ntohs(reinterpret_cast(&addr)->sin_port); + } else if (addr.ss_family == AF_INET6) { + return ntohs(reinterpret_cast(&addr)->sin6_port); + } else { + return -1; + } + } else { + return port; + } +} + +bool Server::listen_internal() { + auto ret = true; + is_running_ = true; + + { + std::unique_ptr task_queue(new_task_queue()); + + while (svr_sock_ != INVALID_SOCKET) { +#ifndef _WIN32 + if (idle_interval_sec_ > 0 || idle_interval_usec_ > 0) { +#endif + auto val = detail::select_read(svr_sock_, idle_interval_sec_, + idle_interval_usec_); + if (val == 0) { // Timeout + task_queue->on_idle(); + continue; + } +#ifndef _WIN32 + } +#endif + socket_t sock = accept(svr_sock_, nullptr, nullptr); + + if (sock == INVALID_SOCKET) { + if (errno == EMFILE) { + // The per-process limit of open file descriptors has been reached. + // Try to accept new connections after a short sleep. + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + continue; + } + if (svr_sock_ != INVALID_SOCKET) { + detail::close_socket(svr_sock_); + ret = false; + } else { + ; // The server socket was closed by user. + } + break; + } + + { + timeval tv; + tv.tv_sec = static_cast(read_timeout_sec_); + tv.tv_usec = static_cast(read_timeout_usec_); + setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv)); + } + { + timeval tv; + tv.tv_sec = static_cast(write_timeout_sec_); + tv.tv_usec = static_cast(write_timeout_usec_); + setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (char *)&tv, sizeof(tv)); + } + +#if __cplusplus > 201703L + task_queue->enqueue([=, this]() { process_and_close_socket(sock); }); +#else + task_queue->enqueue([=]() { process_and_close_socket(sock); }); +#endif + } + + task_queue->shutdown(); + } + + is_running_ = false; + return ret; +} + +bool Server::routing(Request &req, Response &res, Stream &strm) { + if (pre_routing_handler_ && + pre_routing_handler_(req, res) == HandlerResponse::Handled) { + return true; + } + + // File handler + bool is_head_request = req.method == "HEAD"; + if ((req.method == "GET" || is_head_request) && + handle_file_request(req, res, is_head_request)) { + return true; + } + + if (detail::expect_content(req)) { + // Content reader handler + { + ContentReader reader( + [&](ContentReceiver receiver) { + return read_content_with_content_receiver( + strm, req, res, std::move(receiver), nullptr, nullptr); + }, + [&](MultipartContentHeader header, ContentReceiver receiver) { + return read_content_with_content_receiver(strm, req, res, nullptr, + std::move(header), + std::move(receiver)); + }); + + if (req.method == "POST") { + if (dispatch_request_for_content_reader( + req, res, std::move(reader), + post_handlers_for_content_reader_)) { + return true; + } + } else if (req.method == "PUT") { + if (dispatch_request_for_content_reader( + req, res, std::move(reader), + put_handlers_for_content_reader_)) { + return true; + } + } else if (req.method == "PATCH") { + if (dispatch_request_for_content_reader( + req, res, std::move(reader), + patch_handlers_for_content_reader_)) { + return true; + } + } else if (req.method == "DELETE") { + if (dispatch_request_for_content_reader( + req, res, std::move(reader), + delete_handlers_for_content_reader_)) { + return true; + } + } + } + + // Read content into `req.body` + if (!read_content(strm, req, res)) { return false; } + } + + // Regular handler + if (req.method == "GET" || req.method == "HEAD") { + return dispatch_request(req, res, get_handlers_); + } else if (req.method == "POST") { + return dispatch_request(req, res, post_handlers_); + } else if (req.method == "PUT") { + return dispatch_request(req, res, put_handlers_); + } else if (req.method == "DELETE") { + return dispatch_request(req, res, delete_handlers_); + } else if (req.method == "OPTIONS") { + return dispatch_request(req, res, options_handlers_); + } else if (req.method == "PATCH") { + return dispatch_request(req, res, patch_handlers_); + } + + res.status = 400; + return false; +} + +bool Server::dispatch_request(Request &req, Response &res, + const Handlers &handlers) { + for (const auto &x : handlers) { + const auto &pattern = x.first; + const auto &handler = x.second; + + if (std::regex_match(req.path, req.matches, pattern)) { + handler(req, res); + return true; + } + } + return false; +} + +void Server::apply_ranges(const Request &req, Response &res, + std::string &content_type, + std::string &boundary) { + if (req.ranges.size() > 1) { + boundary = detail::make_multipart_data_boundary(); + + auto it = res.headers.find("Content-Type"); + if (it != res.headers.end()) { + content_type = it->second; + res.headers.erase(it); + } + + res.headers.emplace("Content-Type", + "multipart/byteranges; boundary=" + boundary); + } + + auto type = detail::encoding_type(req, res); + + if (res.body.empty()) { + if (res.content_length_ > 0) { + size_t length = 0; + if (req.ranges.empty()) { + length = res.content_length_; + } else if (req.ranges.size() == 1) { + auto offsets = + detail::get_range_offset_and_length(req, res.content_length_, 0); + auto offset = offsets.first; + length = offsets.second; + auto content_range = detail::make_content_range_header_field( + offset, length, res.content_length_); + res.set_header("Content-Range", content_range); + } else { + length = detail::get_multipart_ranges_data_length(req, res, boundary, + content_type); + } + res.set_header("Content-Length", std::to_string(length)); + } else { + if (res.content_provider_) { + if (res.is_chunked_content_provider_) { + res.set_header("Transfer-Encoding", "chunked"); + if (type == detail::EncodingType::Gzip) { + res.set_header("Content-Encoding", "gzip"); + } else if (type == detail::EncodingType::Brotli) { + res.set_header("Content-Encoding", "br"); + } + } + } + } + } else { + if (req.ranges.empty()) { + ; + } else if (req.ranges.size() == 1) { + auto offsets = + detail::get_range_offset_and_length(req, res.body.size(), 0); + auto offset = offsets.first; + auto length = offsets.second; + auto content_range = detail::make_content_range_header_field( + offset, length, res.body.size()); + res.set_header("Content-Range", content_range); + if (offset < res.body.size()) { + res.body = res.body.substr(offset, length); + } else { + res.body.clear(); + res.status = 416; + } + } else { + std::string data; + if (detail::make_multipart_ranges_data(req, res, boundary, content_type, + data)) { + res.body.swap(data); + } else { + res.body.clear(); + res.status = 416; + } + } + + if (type != detail::EncodingType::None) { + std::unique_ptr compressor; + std::string content_encoding; + + if (type == detail::EncodingType::Gzip) { +#ifdef CPPHTTPLIB_ZLIB_SUPPORT + compressor = detail::make_unique(); + content_encoding = "gzip"; +#endif + } else if (type == detail::EncodingType::Brotli) { +#ifdef CPPHTTPLIB_BROTLI_SUPPORT + compressor = detail::make_unique(); + content_encoding = "br"; +#endif + } + + if (compressor) { + std::string compressed; + if (compressor->compress(res.body.data(), res.body.size(), true, + [&](const char *data, size_t data_len) { + compressed.append(data, data_len); + return true; + })) { + res.body.swap(compressed); + res.set_header("Content-Encoding", content_encoding); + } + } + } + + auto length = std::to_string(res.body.size()); + res.set_header("Content-Length", length); + } +} + +bool Server::dispatch_request_for_content_reader( + Request &req, Response &res, ContentReader content_reader, + const HandlersForContentReader &handlers) { + for (const auto &x : handlers) { + const auto &pattern = x.first; + const auto &handler = x.second; + + if (std::regex_match(req.path, req.matches, pattern)) { + handler(req, res, content_reader); + return true; + } + } + return false; +} + +bool +Server::process_request(Stream &strm, bool close_connection, + bool &connection_closed, + const std::function &setup_request) { + std::array buf{}; + + detail::stream_line_reader line_reader(strm, buf.data(), buf.size()); + + // Connection has been closed on client + if (!line_reader.getline()) { return false; } + + Request req; + Response res; + + res.version = "HTTP/1.1"; + +#ifdef _WIN32 + // TODO: Increase FD_SETSIZE statically (libzmq), dynamically (MySQL). +#else +#ifndef CPPHTTPLIB_USE_POLL + // Socket file descriptor exceeded FD_SETSIZE... + if (strm.socket() >= FD_SETSIZE) { + Headers dummy; + detail::read_headers(strm, dummy); + res.status = 500; + return write_response(strm, close_connection, req, res); + } +#endif +#endif + + // Check if the request URI doesn't exceed the limit + if (line_reader.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) { + Headers dummy; + detail::read_headers(strm, dummy); + res.status = 414; + return write_response(strm, close_connection, req, res); + } + + // Request line and headers + if (!parse_request_line(line_reader.ptr(), req) || + !detail::read_headers(strm, req.headers)) { + res.status = 400; + return write_response(strm, close_connection, req, res); + } + + if (req.get_header_value("Connection") == "close") { + connection_closed = true; + } + + if (req.version == "HTTP/1.0" && + req.get_header_value("Connection") != "Keep-Alive") { + connection_closed = true; + } + + strm.get_remote_ip_and_port(req.remote_addr, req.remote_port); + req.set_header("REMOTE_ADDR", req.remote_addr); + req.set_header("REMOTE_PORT", std::to_string(req.remote_port)); + + if (req.has_header("Range")) { + const auto &range_header_value = req.get_header_value("Range"); + if (!detail::parse_range_header(range_header_value, req.ranges)) { + res.status = 416; + return write_response(strm, close_connection, req, res); + } + } + + if (setup_request) { setup_request(req); } + + if (req.get_header_value("Expect") == "100-continue") { + auto status = 100; + if (expect_100_continue_handler_) { + status = expect_100_continue_handler_(req, res); + } + switch (status) { + case 100: + case 417: + strm.write_format("HTTP/1.1 %d %s\r\n\r\n", status, + detail::status_message(status)); + break; + default: return write_response(strm, close_connection, req, res); + } + } + + // Rounting + bool routed = false; + try { + routed = routing(req, res, strm); + } catch (std::exception &e) { + if (exception_handler_) { + exception_handler_(req, res, e); + routed = true; + } else { + res.status = 500; + res.set_header("EXCEPTION_WHAT", e.what()); + } + } catch (...) { + res.status = 500; + res.set_header("EXCEPTION_WHAT", "UNKNOWN"); + } + + if (routed) { + if (res.status == -1) { res.status = req.ranges.empty() ? 200 : 206; } + return write_response_with_content(strm, close_connection, req, res); + } else { + if (res.status == -1) { res.status = 404; } + return write_response(strm, close_connection, req, res); + } +} + +bool Server::is_valid() const { return true; } + +bool Server::process_and_close_socket(socket_t sock) { + auto ret = detail::process_server_socket( + sock, keep_alive_max_count_, keep_alive_timeout_sec_, read_timeout_sec_, + read_timeout_usec_, write_timeout_sec_, write_timeout_usec_, + [this](Stream &strm, bool close_connection, bool &connection_closed) { + return process_request(strm, close_connection, connection_closed, + nullptr); + }); + + detail::shutdown_socket(sock); + detail::close_socket(sock); + return ret; +} + +// HTTP client implementation +ClientImpl::ClientImpl(const std::string &host) + : ClientImpl(host, 80, std::string(), std::string()) {} + +ClientImpl::ClientImpl(const std::string &host, int port) + : ClientImpl(host, port, std::string(), std::string()) {} + +ClientImpl::ClientImpl(const std::string &host, int port, + const std::string &client_cert_path, + const std::string &client_key_path) + // : (Error::Success), host_(host), port_(port), + : host_(host), port_(port), + host_and_port_(host_ + ":" + std::to_string(port_)), + client_cert_path_(client_cert_path), client_key_path_(client_key_path) {} + +ClientImpl::~ClientImpl() { lock_socket_and_shutdown_and_close(); } + +bool ClientImpl::is_valid() const { return true; } + +void ClientImpl::copy_settings(const ClientImpl &rhs) { + client_cert_path_ = rhs.client_cert_path_; + client_key_path_ = rhs.client_key_path_; + connection_timeout_sec_ = rhs.connection_timeout_sec_; + read_timeout_sec_ = rhs.read_timeout_sec_; + read_timeout_usec_ = rhs.read_timeout_usec_; + write_timeout_sec_ = rhs.write_timeout_sec_; + write_timeout_usec_ = rhs.write_timeout_usec_; + basic_auth_username_ = rhs.basic_auth_username_; + basic_auth_password_ = rhs.basic_auth_password_; + bearer_token_auth_token_ = rhs.bearer_token_auth_token_; +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + digest_auth_username_ = rhs.digest_auth_username_; + digest_auth_password_ = rhs.digest_auth_password_; +#endif + keep_alive_ = rhs.keep_alive_; + follow_location_ = rhs.follow_location_; + tcp_nodelay_ = rhs.tcp_nodelay_; + socket_options_ = rhs.socket_options_; + compress_ = rhs.compress_; + decompress_ = rhs.decompress_; + interface_ = rhs.interface_; + proxy_host_ = rhs.proxy_host_; + proxy_port_ = rhs.proxy_port_; + proxy_basic_auth_username_ = rhs.proxy_basic_auth_username_; + proxy_basic_auth_password_ = rhs.proxy_basic_auth_password_; + proxy_bearer_token_auth_token_ = rhs.proxy_bearer_token_auth_token_; +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + proxy_digest_auth_username_ = rhs.proxy_digest_auth_username_; + proxy_digest_auth_password_ = rhs.proxy_digest_auth_password_; +#endif +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + server_certificate_verification_ = rhs.server_certificate_verification_; +#endif + logger_ = rhs.logger_; +} + +socket_t ClientImpl::create_client_socket(Error &error) const { + if (!proxy_host_.empty() && proxy_port_ != -1) { + return detail::create_client_socket( + proxy_host_.c_str(), proxy_port_, address_family_, tcp_nodelay_, + socket_options_, connection_timeout_sec_, connection_timeout_usec_, + read_timeout_sec_, read_timeout_usec_, write_timeout_sec_, + write_timeout_usec_, interface_, error); + } + return detail::create_client_socket( + host_.c_str(), port_, address_family_, tcp_nodelay_, socket_options_, + connection_timeout_sec_, connection_timeout_usec_, read_timeout_sec_, + read_timeout_usec_, write_timeout_sec_, write_timeout_usec_, interface_, + error); +} + +bool ClientImpl::create_and_connect_socket(Socket &socket, + Error &error) { + auto sock = create_client_socket(error); + if (sock == INVALID_SOCKET) { return false; } + socket.sock = sock; + return true; +} + +void ClientImpl::shutdown_ssl(Socket & /*socket*/, + bool /*shutdown_gracefully*/) { + // If there are any requests in flight from threads other than us, then it's + // a thread-unsafe race because individual ssl* objects are not thread-safe. + assert(socket_requests_in_flight_ == 0 || + socket_requests_are_from_thread_ == std::this_thread::get_id()); +} + +void ClientImpl::shutdown_socket(Socket &socket) { + if (socket.sock == INVALID_SOCKET) { return; } + detail::shutdown_socket(socket.sock); +} + +void ClientImpl::close_socket(Socket &socket) { + // If there are requests in flight in another thread, usually closing + // the socket will be fine and they will simply receive an error when + // using the closed socket, but it is still a bug since rarely the OS + // may reassign the socket id to be used for a new socket, and then + // suddenly they will be operating on a live socket that is different + // than the one they intended! + assert(socket_requests_in_flight_ == 0 || + socket_requests_are_from_thread_ == std::this_thread::get_id()); + + // It is also a bug if this happens while SSL is still active +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + assert(socket.ssl == nullptr); +#endif + if (socket.sock == INVALID_SOCKET) { return; } + detail::close_socket(socket.sock); + socket.sock = INVALID_SOCKET; +} + +void ClientImpl::lock_socket_and_shutdown_and_close() { + std::lock_guard guard(socket_mutex_); + shutdown_ssl(socket_, true); + shutdown_socket(socket_); + close_socket(socket_); +} + +bool ClientImpl::read_response_line(Stream &strm, const Request &req, + Response &res) { + std::array buf; + + detail::stream_line_reader line_reader(strm, buf.data(), buf.size()); + + if (!line_reader.getline()) { return false; } + + const static std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r\n"); + + std::cmatch m; + if (!std::regex_match(line_reader.ptr(), m, re)) { + return req.method == "CONNECT"; + } + res.version = std::string(m[1]); + res.status = std::stoi(std::string(m[2])); + res.reason = std::string(m[3]); + + // Ignore '100 Continue' + while (res.status == 100) { + if (!line_reader.getline()) { return false; } // CRLF + if (!line_reader.getline()) { return false; } // next response line + + if (!std::regex_match(line_reader.ptr(), m, re)) { return false; } + res.version = std::string(m[1]); + res.status = std::stoi(std::string(m[2])); + res.reason = std::string(m[3]); + } + + return true; +} + +bool ClientImpl::send(Request &req, Response &res, Error &error) { + std::lock_guard request_mutex_guard(request_mutex_); + + { + std::lock_guard guard(socket_mutex_); + // Set this to false immediately - if it ever gets set to true by the end of + // the request, we know another thread instructed us to close the socket. + socket_should_be_closed_when_request_is_done_ = false; + + auto is_alive = false; + if (socket_.is_open()) { + is_alive = detail::select_write(socket_.sock, 0, 0) > 0; + if (!is_alive) { + // Attempt to avoid sigpipe by shutting down nongracefully if it seems + // like the other side has already closed the connection Also, there + // cannot be any requests in flight from other threads since we locked + // request_mutex_, so safe to close everything immediately + const bool shutdown_gracefully = false; + shutdown_ssl(socket_, shutdown_gracefully); + shutdown_socket(socket_); + close_socket(socket_); + } + } + + if (!is_alive) { + if (!create_and_connect_socket(socket_, error)) { return false; } + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + // TODO: refactoring + if (is_ssl()) { + auto &scli = static_cast(*this); + if (!proxy_host_.empty() && proxy_port_ != -1) { + bool success = false; + if (!scli.connect_with_proxy(socket_, res, success, error)) { + return success; + } + } + + if (!scli.initialize_ssl(socket_, error)) { return false; } + } +#endif + } + + // Mark the current socket as being in use so that it cannot be closed by + // anyone else while this request is ongoing, even though we will be + // releasing the mutex. + if (socket_requests_in_flight_ > 1) { + assert(socket_requests_are_from_thread_ == std::this_thread::get_id()); + } + socket_requests_in_flight_ += 1; + socket_requests_are_from_thread_ = std::this_thread::get_id(); + } + + for (const auto &header : default_headers_) { + if (req.headers.find(header.first) == req.headers.end()) { + req.headers.insert(header); + } + } + + auto close_connection = !keep_alive_; + auto ret = process_socket(socket_, [&](Stream &strm) { + return handle_request(strm, req, res, close_connection, error); + }); + + // Briefly lock mutex in order to mark that a request is no longer ongoing + { + std::lock_guard guard(socket_mutex_); + socket_requests_in_flight_ -= 1; + if (socket_requests_in_flight_ <= 0) { + assert(socket_requests_in_flight_ == 0); + socket_requests_are_from_thread_ = std::thread::id(); + } + + if (socket_should_be_closed_when_request_is_done_ || close_connection || + !ret) { + shutdown_ssl(socket_, true); + shutdown_socket(socket_); + close_socket(socket_); + } + } + + if (!ret) { + if (error == Error::Success) { error = Error::Unknown; } + } + + return ret; +} + +Result ClientImpl::send(const Request &req) { + auto req2 = req; + return send_(std::move(req2)); +} + +Result ClientImpl::send_(Request &&req) { + auto res = detail::make_unique(); + auto error = Error::Success; + auto ret = send(req, *res, error); + return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers)}; +} + +bool ClientImpl::handle_request(Stream &strm, Request &req, + Response &res, bool close_connection, + Error &error) { + if (req.path.empty()) { + error = Error::Connection; + return false; + } + + auto req_save = req; + + bool ret; + + if (!is_ssl() && !proxy_host_.empty() && proxy_port_ != -1) { + auto req2 = req; + req2.path = "http://" + host_and_port_ + req.path; + ret = process_request(strm, req2, res, close_connection, error); + req = req2; + req.path = req_save.path; + } else { + ret = process_request(strm, req, res, close_connection, error); + } + + if (!ret) { return false; } + + if (300 < res.status && res.status < 400 && follow_location_) { + req = req_save; + ret = redirect(req, res, error); + } + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + if ((res.status == 401 || res.status == 407) && + req.authorization_count_ < 5) { + auto is_proxy = res.status == 407; + const auto &username = + is_proxy ? proxy_digest_auth_username_ : digest_auth_username_; + const auto &password = + is_proxy ? proxy_digest_auth_password_ : digest_auth_password_; + + if (!username.empty() && !password.empty()) { + std::map auth; + if (detail::parse_www_authenticate(res, auth, is_proxy)) { + Request new_req = req; + new_req.authorization_count_ += 1; + auto key = is_proxy ? "Proxy-Authorization" : "Authorization"; + new_req.headers.erase(key); + new_req.headers.insert(detail::make_digest_authentication_header( + req, auth, new_req.authorization_count_, detail::random_string(10), + username, password, is_proxy)); + + Response new_res; + + ret = send(new_req, new_res, error); + if (ret) { res = new_res; } + } + } + } +#endif + + return ret; +} + +bool ClientImpl::redirect(Request &req, Response &res, Error &error) { + if (req.redirect_count_ == 0) { + error = Error::ExceedRedirectCount; + return false; + } + + auto location = detail::decode_url(res.get_header_value("location"), true); + if (location.empty()) { return false; } + + const static std::regex re( + R"(^(?:(https?):)?(?://([^:/?#]*)(?::(\d+))?)?([^?#]*(?:\?[^#]*)?)(?:#.*)?)"); + + std::smatch m; + if (!std::regex_match(location, m, re)) { return false; } + + auto scheme = is_ssl() ? "https" : "http"; + + auto next_scheme = m[1].str(); + auto next_host = m[2].str(); + auto port_str = m[3].str(); + auto next_path = m[4].str(); + + auto next_port = port_; + if (!port_str.empty()) { + next_port = std::stoi(port_str); + } else if (!next_scheme.empty()) { + next_port = next_scheme == "https" ? 443 : 80; + } + + if (next_scheme.empty()) { next_scheme = scheme; } + if (next_host.empty()) { next_host = host_; } + if (next_path.empty()) { next_path = "/"; } + + if (next_scheme == scheme && next_host == host_ && next_port == port_) { + return detail::redirect(*this, req, res, next_path, location, error); + } else { + if (next_scheme == "https") { +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + SSLClient cli(next_host.c_str(), next_port); + cli.copy_settings(*this); + return detail::redirect(cli, req, res, next_path, location, error); +#else + return false; +#endif + } else { + ClientImpl cli(next_host.c_str(), next_port); + cli.copy_settings(*this); + return detail::redirect(cli, req, res, next_path, location, error); + } + } +} + +bool ClientImpl::write_content_with_provider(Stream &strm, + const Request &req, + Error &error) { + auto is_shutting_down = []() { return false; }; + + if (req.is_chunked_content_provider_) { + // TODO: Brotli suport + std::unique_ptr compressor; +#ifdef CPPHTTPLIB_ZLIB_SUPPORT + if (compress_) { + compressor = detail::make_unique(); + } else +#endif + { + compressor = detail::make_unique(); + } + + return detail::write_content_chunked(strm, req.content_provider_, + is_shutting_down, *compressor, error); + } else { + return detail::write_content(strm, req.content_provider_, 0, + req.content_length_, is_shutting_down, error); + } +} // namespace httplib + +bool ClientImpl::write_request(Stream &strm, Request &req, + bool close_connection, Error &error) { + // Prepare additional headers + if (close_connection) { req.headers.emplace("Connection", "close"); } + + if (!req.has_header("Host")) { + if (is_ssl()) { + if (port_ == 443) { + req.headers.emplace("Host", host_); + } else { + req.headers.emplace("Host", host_and_port_); + } + } else { + if (port_ == 80) { + req.headers.emplace("Host", host_); + } else { + req.headers.emplace("Host", host_and_port_); + } + } + } + + if (!req.has_header("Accept")) { req.headers.emplace("Accept", "*/*"); } + + if (!req.has_header("User-Agent")) { + req.headers.emplace("User-Agent", "cpp-httplib/0.7"); + } + + if (req.body.empty()) { + if (req.content_provider_) { + if (!req.is_chunked_content_provider_) { + auto length = std::to_string(req.content_length_); + req.headers.emplace("Content-Length", length); + } + } else { + if (req.method == "POST" || req.method == "PUT" || + req.method == "PATCH") { + req.headers.emplace("Content-Length", "0"); + } + } + } else { + if (!req.has_header("Content-Type")) { + req.headers.emplace("Content-Type", "text/plain"); + } + + if (!req.has_header("Content-Length")) { + auto length = std::to_string(req.body.size()); + req.headers.emplace("Content-Length", length); + } + } + + if (!basic_auth_password_.empty()) { + req.headers.insert(make_basic_authentication_header( + basic_auth_username_, basic_auth_password_, false)); + } + + if (!proxy_basic_auth_username_.empty() && + !proxy_basic_auth_password_.empty()) { + req.headers.insert(make_basic_authentication_header( + proxy_basic_auth_username_, proxy_basic_auth_password_, true)); + } + + if (!bearer_token_auth_token_.empty()) { + req.headers.insert(make_bearer_token_authentication_header( + bearer_token_auth_token_, false)); + } + + if (!proxy_bearer_token_auth_token_.empty()) { + req.headers.insert(make_bearer_token_authentication_header( + proxy_bearer_token_auth_token_, true)); + } + + // Request line and headers + { + detail::BufferStream bstrm; + + const auto &path = detail::encode_url(req.path); + bstrm.write_format("%s %s HTTP/1.1\r\n", req.method.c_str(), path.c_str()); + + detail::write_headers(bstrm, req.headers); + + // Flush buffer + auto &data = bstrm.get_buffer(); + if (!detail::write_data(strm, data.data(), data.size())) { + error = Error::Write; + return false; + } + } + + // Body + if (req.body.empty()) { + return write_content_with_provider(strm, req, error); + } else { + return detail::write_data(strm, req.body.data(), req.body.size()); + } + + return true; +} + +std::unique_ptr ClientImpl::send_with_content_provider( + Request &req, + // const char *method, const char *path, const Headers &headers, + const char *body, size_t content_length, ContentProvider content_provider, + ContentProviderWithoutLength content_provider_without_length, + const char *content_type, Error &error) { + + // Request req; + // req.method = method; + // req.headers = headers; + // req.path = path; + + if (content_type) { req.headers.emplace("Content-Type", content_type); } + +#ifdef CPPHTTPLIB_ZLIB_SUPPORT + if (compress_) { req.headers.emplace("Content-Encoding", "gzip"); } +#endif + +#ifdef CPPHTTPLIB_ZLIB_SUPPORT + if (compress_ && !content_provider_without_length) { + // TODO: Brotli support + detail::gzip_compressor compressor; + + if (content_provider) { + auto ok = true; + size_t offset = 0; + DataSink data_sink; + + data_sink.write = [&](const char *data, size_t data_len) -> bool { + if (ok) { + auto last = offset + data_len == content_length; + + auto ret = compressor.compress( + data, data_len, last, [&](const char *data, size_t data_len) { + req.body.append(data, data_len); + return true; + }); + + if (ret) { + offset += data_len; + } else { + ok = false; + } + } + return ok; + }; + + data_sink.is_writable = [&](void) { return ok && true; }; + + while (ok && offset < content_length) { + if (!content_provider(offset, content_length - offset, data_sink)) { + error = Error::Canceled; + return nullptr; + } + } + } else { + if (!compressor.compress(body, content_length, true, + [&](const char *data, size_t data_len) { + req.body.append(data, data_len); + return true; + })) { + error = Error::Compression; + return nullptr; + } + } + } else +#endif + { + if (content_provider) { + req.content_length_ = content_length; + req.content_provider_ = std::move(content_provider); + req.is_chunked_content_provider_ = false; + } else if (content_provider_without_length) { + req.content_length_ = 0; + req.content_provider_ = detail::ContentProviderAdapter( + std::move(content_provider_without_length)); + req.is_chunked_content_provider_ = true; + req.headers.emplace("Transfer-Encoding", "chunked"); + } else { + req.body.assign(body, content_length); + ; + } + } + + auto res = detail::make_unique(); + return send(req, *res, error) ? std::move(res) : nullptr; +} + +Result ClientImpl::send_with_content_provider( + const char *method, const char *path, const Headers &headers, + const char *body, size_t content_length, ContentProvider content_provider, + ContentProviderWithoutLength content_provider_without_length, + const char *content_type) { + Request req; + req.method = method; + req.headers = headers; + req.path = path; + + auto error = Error::Success; + + auto res = send_with_content_provider( + req, + // method, path, headers, + body, content_length, std::move(content_provider), + std::move(content_provider_without_length), content_type, error); + + return Result{std::move(res), error, std::move(req.headers)}; +} + +bool ClientImpl::process_request(Stream &strm, Request &req, + Response &res, bool close_connection, + Error &error) { + // Send request + if (!write_request(strm, req, close_connection, error)) { return false; } + + // Receive response and headers + if (!read_response_line(strm, req, res) || + !detail::read_headers(strm, res.headers)) { + error = Error::Read; + return false; + } + + // Body + if ((res.status != 204) && req.method != "HEAD" && req.method != "CONNECT") { + auto redirect = 300 < res.status && res.status < 400 && follow_location_; + + if (req.response_handler && !redirect) { + if (!req.response_handler(res)) { + error = Error::Canceled; + return false; + } + } + + auto out = + req.content_receiver + ? static_cast( + [&](const char *buf, size_t n, uint64_t off, uint64_t len) { + if (redirect) { return true; } + auto ret = req.content_receiver(buf, n, off, len); + if (!ret) { error = Error::Canceled; } + return ret; + }) + : static_cast( + [&](const char *buf, size_t n, uint64_t /*off*/, + uint64_t /*len*/) { + if (res.body.size() + n > res.body.max_size()) { + return false; + } + res.body.append(buf, n); + return true; + }); + + auto progress = [&](uint64_t current, uint64_t total) { + if (!req.progress || redirect) { return true; } + auto ret = req.progress(current, total); + if (!ret) { error = Error::Canceled; } + return ret; + }; + + int dummy_status; + if (!detail::read_content(strm, res, (std::numeric_limits::max)(), + dummy_status, std::move(progress), std::move(out), + decompress_)) { + if (error != Error::Canceled) { error = Error::Read; } + return false; + } + } + + if (res.get_header_value("Connection") == "close" || + (res.version == "HTTP/1.0" && res.reason != "Connection established")) { + // TODO this requires a not-entirely-obvious chain of calls to be correct + // for this to be safe. Maybe a code refactor (such as moving this out to + // the send function and getting rid of the recursiveness of the mutex) + // could make this more obvious. + + // This is safe to call because process_request is only called by + // handle_request which is only called by send, which locks the request + // mutex during the process. It would be a bug to call it from a different + // thread since it's a thread-safety issue to do these things to the socket + // if another thread is using the socket. + lock_socket_and_shutdown_and_close(); + } + + // Log + if (logger_) { logger_(req, res); } + + return true; +} + +bool +ClientImpl::process_socket(const Socket &socket, + std::function callback) { + return detail::process_client_socket( + socket.sock, read_timeout_sec_, read_timeout_usec_, write_timeout_sec_, + write_timeout_usec_, std::move(callback)); +} + +bool ClientImpl::is_ssl() const { return false; } + +Result ClientImpl::Get(const char *path) { + return Get(path, Headers(), Progress()); +} + +Result ClientImpl::Get(const char *path, Progress progress) { + return Get(path, Headers(), std::move(progress)); +} + +Result ClientImpl::Get(const char *path, const Headers &headers) { + return Get(path, headers, Progress()); +} + +Result ClientImpl::Get(const char *path, const Headers &headers, + Progress progress) { + Request req; + req.method = "GET"; + req.path = path; + req.headers = headers; + req.progress = std::move(progress); + + return send_(std::move(req)); +} + +Result ClientImpl::Get(const char *path, + ContentReceiver content_receiver) { + return Get(path, Headers(), nullptr, std::move(content_receiver), nullptr); +} + +Result ClientImpl::Get(const char *path, + ContentReceiver content_receiver, + Progress progress) { + return Get(path, Headers(), nullptr, std::move(content_receiver), + std::move(progress)); +} + +Result ClientImpl::Get(const char *path, const Headers &headers, + ContentReceiver content_receiver) { + return Get(path, headers, nullptr, std::move(content_receiver), nullptr); +} + +Result ClientImpl::Get(const char *path, const Headers &headers, + ContentReceiver content_receiver, + Progress progress) { + return Get(path, headers, nullptr, std::move(content_receiver), + std::move(progress)); +} + +Result ClientImpl::Get(const char *path, + ResponseHandler response_handler, + ContentReceiver content_receiver) { + return Get(path, Headers(), std::move(response_handler), + std::move(content_receiver), nullptr); +} + +Result ClientImpl::Get(const char *path, const Headers &headers, + ResponseHandler response_handler, + ContentReceiver content_receiver) { + return Get(path, headers, std::move(response_handler), + std::move(content_receiver), nullptr); +} + +Result ClientImpl::Get(const char *path, + ResponseHandler response_handler, + ContentReceiver content_receiver, + Progress progress) { + return Get(path, Headers(), std::move(response_handler), + std::move(content_receiver), std::move(progress)); +} + +Result ClientImpl::Get(const char *path, const Headers &headers, + ResponseHandler response_handler, + ContentReceiver content_receiver, + Progress progress) { + Request req; + req.method = "GET"; + req.path = path; + req.headers = headers; + req.response_handler = std::move(response_handler); + req.content_receiver = + [content_receiver](const char *data, size_t data_length, + uint64_t /*offset*/, uint64_t /*total_length*/) { + return content_receiver(data, data_length); + }; + req.progress = std::move(progress); + + return send_(std::move(req)); +} + +Result ClientImpl::Get(const char *path, const Params ¶ms, + const Headers &headers, Progress progress) { + if (params.empty()) { return Get(path, headers); } + + std::string path_with_query = detail::append_query_params(path, params); + return Get(path_with_query.c_str(), headers, progress); +} + +Result ClientImpl::Get(const char *path, const Params ¶ms, + const Headers &headers, + ContentReceiver content_receiver, + Progress progress) { + return Get(path, params, headers, nullptr, content_receiver, progress); +} + +Result ClientImpl::Get(const char *path, const Params ¶ms, + const Headers &headers, + ResponseHandler response_handler, + ContentReceiver content_receiver, + Progress progress) { + if (params.empty()) { + return Get(path, headers, response_handler, content_receiver, progress); + } + + std::string path_with_query = detail::append_query_params(path, params); + return Get(path_with_query.c_str(), headers, response_handler, + content_receiver, progress); +} + +Result ClientImpl::Head(const char *path) { + return Head(path, Headers()); +} + +Result ClientImpl::Head(const char *path, const Headers &headers) { + Request req; + req.method = "HEAD"; + req.headers = headers; + req.path = path; + + return send_(std::move(req)); +} + +Result ClientImpl::Post(const char *path) { + return Post(path, std::string(), nullptr); +} + +Result ClientImpl::Post(const char *path, const char *body, + size_t content_length, + const char *content_type) { + return Post(path, Headers(), body, content_length, content_type); +} + +Result ClientImpl::Post(const char *path, const Headers &headers, + const char *body, size_t content_length, + const char *content_type) { + return send_with_content_provider("POST", path, headers, body, content_length, + nullptr, nullptr, content_type); +} + +Result ClientImpl::Post(const char *path, const std::string &body, + const char *content_type) { + return Post(path, Headers(), body, content_type); +} + +Result ClientImpl::Post(const char *path, const Headers &headers, + const std::string &body, + const char *content_type) { + return send_with_content_provider("POST", path, headers, body.data(), + body.size(), nullptr, nullptr, + content_type); +} + +Result ClientImpl::Post(const char *path, const Params ¶ms) { + return Post(path, Headers(), params); +} + +Result ClientImpl::Post(const char *path, size_t content_length, + ContentProvider content_provider, + const char *content_type) { + return Post(path, Headers(), content_length, std::move(content_provider), + content_type); +} + +Result ClientImpl::Post(const char *path, + ContentProviderWithoutLength content_provider, + const char *content_type) { + return Post(path, Headers(), std::move(content_provider), content_type); +} + +Result ClientImpl::Post(const char *path, const Headers &headers, + size_t content_length, + ContentProvider content_provider, + const char *content_type) { + return send_with_content_provider("POST", path, headers, nullptr, + content_length, std::move(content_provider), + nullptr, content_type); +} + +Result ClientImpl::Post(const char *path, const Headers &headers, + ContentProviderWithoutLength content_provider, + const char *content_type) { + return send_with_content_provider("POST", path, headers, nullptr, 0, nullptr, + std::move(content_provider), content_type); +} + +Result ClientImpl::Post(const char *path, const Headers &headers, + const Params ¶ms) { + auto query = detail::params_to_query_str(params); + return Post(path, headers, query, "application/x-www-form-urlencoded"); +} + +Result ClientImpl::Post(const char *path, + const MultipartFormDataItems &items) { + return Post(path, Headers(), items); +} + +Result ClientImpl::Post(const char *path, const Headers &headers, + const MultipartFormDataItems &items) { + return Post(path, headers, items, detail::make_multipart_data_boundary()); +} +Result ClientImpl::Post(const char *path, const Headers &headers, + const MultipartFormDataItems &items, + const std::string &boundary) { + for (size_t i = 0; i < boundary.size(); i++) { + char c = boundary[i]; + if (!std::isalnum(c) && c != '-' && c != '_') { + return Result{nullptr, Error::UnsupportedMultipartBoundaryChars}; + } + } + + std::string body; + + for (const auto &item : items) { + body += "--" + boundary + "\r\n"; + body += "Content-Disposition: form-data; name=\"" + item.name + "\""; + if (!item.filename.empty()) { + body += "; filename=\"" + item.filename + "\""; + } + body += "\r\n"; + if (!item.content_type.empty()) { + body += "Content-Type: " + item.content_type + "\r\n"; + } + body += "\r\n"; + body += item.content + "\r\n"; + } + + body += "--" + boundary + "--\r\n"; + + std::string content_type = "multipart/form-data; boundary=" + boundary; + return Post(path, headers, body, content_type.c_str()); +} + +Result ClientImpl::Put(const char *path) { + return Put(path, std::string(), nullptr); +} + +Result ClientImpl::Put(const char *path, const char *body, + size_t content_length, const char *content_type) { + return Put(path, Headers(), body, content_length, content_type); +} + +Result ClientImpl::Put(const char *path, const Headers &headers, + const char *body, size_t content_length, + const char *content_type) { + return send_with_content_provider("PUT", path, headers, body, content_length, + nullptr, nullptr, content_type); +} + +Result ClientImpl::Put(const char *path, const std::string &body, + const char *content_type) { + return Put(path, Headers(), body, content_type); +} + +Result ClientImpl::Put(const char *path, const Headers &headers, + const std::string &body, + const char *content_type) { + return send_with_content_provider("PUT", path, headers, body.data(), + body.size(), nullptr, nullptr, + content_type); +} + +Result ClientImpl::Put(const char *path, size_t content_length, + ContentProvider content_provider, + const char *content_type) { + return Put(path, Headers(), content_length, std::move(content_provider), + content_type); +} + +Result ClientImpl::Put(const char *path, + ContentProviderWithoutLength content_provider, + const char *content_type) { + return Put(path, Headers(), std::move(content_provider), content_type); +} + +Result ClientImpl::Put(const char *path, const Headers &headers, + size_t content_length, + ContentProvider content_provider, + const char *content_type) { + return send_with_content_provider("PUT", path, headers, nullptr, + content_length, std::move(content_provider), + nullptr, content_type); +} + +Result ClientImpl::Put(const char *path, const Headers &headers, + ContentProviderWithoutLength content_provider, + const char *content_type) { + return send_with_content_provider("PUT", path, headers, nullptr, 0, nullptr, + std::move(content_provider), content_type); +} + +Result ClientImpl::Put(const char *path, const Params ¶ms) { + return Put(path, Headers(), params); +} + +Result ClientImpl::Put(const char *path, const Headers &headers, + const Params ¶ms) { + auto query = detail::params_to_query_str(params); + return Put(path, headers, query, "application/x-www-form-urlencoded"); +} + +Result ClientImpl::Patch(const char *path) { + return Patch(path, std::string(), nullptr); +} + +Result ClientImpl::Patch(const char *path, const char *body, + size_t content_length, + const char *content_type) { + return Patch(path, Headers(), body, content_length, content_type); +} + +Result ClientImpl::Patch(const char *path, const Headers &headers, + const char *body, size_t content_length, + const char *content_type) { + return send_with_content_provider("PATCH", path, headers, body, + content_length, nullptr, nullptr, + content_type); +} + +Result ClientImpl::Patch(const char *path, const std::string &body, + const char *content_type) { + return Patch(path, Headers(), body, content_type); +} + +Result ClientImpl::Patch(const char *path, const Headers &headers, + const std::string &body, + const char *content_type) { + return send_with_content_provider("PATCH", path, headers, body.data(), + body.size(), nullptr, nullptr, + content_type); +} + +Result ClientImpl::Patch(const char *path, size_t content_length, + ContentProvider content_provider, + const char *content_type) { + return Patch(path, Headers(), content_length, std::move(content_provider), + content_type); +} + +Result ClientImpl::Patch(const char *path, + ContentProviderWithoutLength content_provider, + const char *content_type) { + return Patch(path, Headers(), std::move(content_provider), content_type); +} + +Result ClientImpl::Patch(const char *path, const Headers &headers, + size_t content_length, + ContentProvider content_provider, + const char *content_type) { + return send_with_content_provider("PATCH", path, headers, nullptr, + content_length, std::move(content_provider), + nullptr, content_type); +} + +Result ClientImpl::Patch(const char *path, const Headers &headers, + ContentProviderWithoutLength content_provider, + const char *content_type) { + return send_with_content_provider("PATCH", path, headers, nullptr, 0, nullptr, + std::move(content_provider), content_type); +} + +Result ClientImpl::Delete(const char *path) { + return Delete(path, Headers(), std::string(), nullptr); +} + +Result ClientImpl::Delete(const char *path, const Headers &headers) { + return Delete(path, headers, std::string(), nullptr); +} + +Result ClientImpl::Delete(const char *path, const char *body, + size_t content_length, + const char *content_type) { + return Delete(path, Headers(), body, content_length, content_type); +} + +Result ClientImpl::Delete(const char *path, const Headers &headers, + const char *body, size_t content_length, + const char *content_type) { + Request req; + req.method = "DELETE"; + req.headers = headers; + req.path = path; + + if (content_type) { req.headers.emplace("Content-Type", content_type); } + req.body.assign(body, content_length); + + return send_(std::move(req)); +} + +Result ClientImpl::Delete(const char *path, const std::string &body, + const char *content_type) { + return Delete(path, Headers(), body.data(), body.size(), content_type); +} + +Result ClientImpl::Delete(const char *path, const Headers &headers, + const std::string &body, + const char *content_type) { + return Delete(path, headers, body.data(), body.size(), content_type); +} + +Result ClientImpl::Options(const char *path) { + return Options(path, Headers()); +} + +Result ClientImpl::Options(const char *path, const Headers &headers) { + Request req; + req.method = "OPTIONS"; + req.headers = headers; + req.path = path; + + return send_(std::move(req)); +} + +size_t ClientImpl::is_socket_open() const { + std::lock_guard guard(socket_mutex_); + return socket_.is_open(); +} + +void ClientImpl::stop() { + std::lock_guard guard(socket_mutex_); + + // If there is anything ongoing right now, the ONLY thread-safe thing we can + // do is to shutdown_socket, so that threads using this socket suddenly + // discover they can't read/write any more and error out. Everything else + // (closing the socket, shutting ssl down) is unsafe because these actions are + // not thread-safe. + if (socket_requests_in_flight_ > 0) { + shutdown_socket(socket_); + + // Aside from that, we set a flag for the socket to be closed when we're + // done. + socket_should_be_closed_when_request_is_done_ = true; + return; + } + + // Otherwise, sitll holding the mutex, we can shut everything down ourselves + shutdown_ssl(socket_, true); + shutdown_socket(socket_); + close_socket(socket_); +} + +void ClientImpl::set_connection_timeout(time_t sec, time_t usec) { + connection_timeout_sec_ = sec; + connection_timeout_usec_ = usec; +} + +template +void ClientImpl::set_connection_timeout( + const std::chrono::duration &duration) { + detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t usec) { + set_connection_timeout(sec, usec); + }); +} + +void ClientImpl::set_read_timeout(time_t sec, time_t usec) { + read_timeout_sec_ = sec; + read_timeout_usec_ = usec; +} + +template +void ClientImpl::set_read_timeout( + const std::chrono::duration &duration) { + detail::duration_to_sec_and_usec( + duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); }); +} + +void ClientImpl::set_write_timeout(time_t sec, time_t usec) { + write_timeout_sec_ = sec; + write_timeout_usec_ = usec; +} + +template +void ClientImpl::set_write_timeout( + const std::chrono::duration &duration) { + detail::duration_to_sec_and_usec( + duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); }); +} + +void ClientImpl::set_basic_auth(const char *username, + const char *password) { + basic_auth_username_ = username; + basic_auth_password_ = password; +} + +void ClientImpl::set_bearer_token_auth(const char *token) { + bearer_token_auth_token_ = token; +} + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT +void ClientImpl::set_digest_auth(const char *username, + const char *password) { + digest_auth_username_ = username; + digest_auth_password_ = password; +} +#endif + +void ClientImpl::set_keep_alive(bool on) { keep_alive_ = on; } + +void ClientImpl::set_follow_location(bool on) { follow_location_ = on; } + +void ClientImpl::set_default_headers(Headers headers) { + default_headers_ = std::move(headers); +} + +void ClientImpl::set_address_family(int family) { + address_family_ = family; +} + +void ClientImpl::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; } + +void ClientImpl::set_socket_options(SocketOptions socket_options) { + socket_options_ = std::move(socket_options); +} + +void ClientImpl::set_compress(bool on) { compress_ = on; } + +void ClientImpl::set_decompress(bool on) { decompress_ = on; } + +void ClientImpl::set_interface(const char *intf) { interface_ = intf; } + +void ClientImpl::set_proxy(const char *host, int port) { + proxy_host_ = host; + proxy_port_ = port; +} + +void ClientImpl::set_proxy_basic_auth(const char *username, + const char *password) { + proxy_basic_auth_username_ = username; + proxy_basic_auth_password_ = password; +} + +void ClientImpl::set_proxy_bearer_token_auth(const char *token) { + proxy_bearer_token_auth_token_ = token; +} + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT +void ClientImpl::set_proxy_digest_auth(const char *username, + const char *password) { + proxy_digest_auth_username_ = username; + proxy_digest_auth_password_ = password; +} +#endif + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT +void ClientImpl::enable_server_certificate_verification(bool enabled) { + server_certificate_verification_ = enabled; +} +#endif + +void ClientImpl::set_logger(Logger logger) { + logger_ = std::move(logger); +} + +/* + * SSL Implementation + */ +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT +namespace detail { + +template +SSL *ssl_new(socket_t sock, SSL_CTX *ctx, std::mutex &ctx_mutex, + U SSL_connect_or_accept, V setup) { + SSL *ssl = nullptr; + { + std::lock_guard guard(ctx_mutex); + ssl = SSL_new(ctx); + } + + if (ssl) { + set_nonblocking(sock, true); + auto bio = BIO_new_socket(static_cast(sock), BIO_NOCLOSE); + BIO_set_nbio(bio, 1); + SSL_set_bio(ssl, bio, bio); + + if (!setup(ssl) || SSL_connect_or_accept(ssl) != 1) { + SSL_shutdown(ssl); + { + std::lock_guard guard(ctx_mutex); + SSL_free(ssl); + } + set_nonblocking(sock, false); + return nullptr; + } + BIO_set_nbio(bio, 0); + set_nonblocking(sock, false); + } + + return ssl; +} + +void ssl_delete(std::mutex &ctx_mutex, SSL *ssl, + bool shutdown_gracefully) { + // sometimes we may want to skip this to try to avoid SIGPIPE if we know + // the remote has closed the network connection + // Note that it is not always possible to avoid SIGPIPE, this is merely a + // best-efforts. + if (shutdown_gracefully) { SSL_shutdown(ssl); } + + std::lock_guard guard(ctx_mutex); + SSL_free(ssl); +} + +template +bool ssl_connect_or_accept_nonblocking(socket_t sock, SSL *ssl, + U ssl_connect_or_accept, + time_t timeout_sec, + time_t timeout_usec) { + int res = 0; + while ((res = ssl_connect_or_accept(ssl)) != 1) { + auto err = SSL_get_error(ssl, res); + switch (err) { + case SSL_ERROR_WANT_READ: + if (select_read(sock, timeout_sec, timeout_usec) > 0) { continue; } + break; + case SSL_ERROR_WANT_WRITE: + if (select_write(sock, timeout_sec, timeout_usec) > 0) { continue; } + break; + default: break; + } + return false; + } + return true; +} + +template +bool +process_server_socket_ssl(SSL *ssl, socket_t sock, size_t keep_alive_max_count, + time_t keep_alive_timeout_sec, + time_t read_timeout_sec, time_t read_timeout_usec, + time_t write_timeout_sec, time_t write_timeout_usec, + T callback) { + return process_server_socket_core( + sock, keep_alive_max_count, keep_alive_timeout_sec, + [&](bool close_connection, bool &connection_closed) { + SSLSocketStream strm(sock, ssl, read_timeout_sec, read_timeout_usec, + write_timeout_sec, write_timeout_usec); + return callback(strm, close_connection, connection_closed); + }); +} + +template +bool +process_client_socket_ssl(SSL *ssl, socket_t sock, time_t read_timeout_sec, + time_t read_timeout_usec, time_t write_timeout_sec, + time_t write_timeout_usec, T callback) { + SSLSocketStream strm(sock, ssl, read_timeout_sec, read_timeout_usec, + write_timeout_sec, write_timeout_usec); + return callback(strm); +} + +#if OPENSSL_VERSION_NUMBER < 0x10100000L +static std::shared_ptr> openSSL_locks_; + +class SSLThreadLocks { +public: + SSLThreadLocks() { + openSSL_locks_ = + std::make_shared>(CRYPTO_num_locks()); + CRYPTO_set_locking_callback(locking_callback); + } + + ~SSLThreadLocks() { CRYPTO_set_locking_callback(nullptr); } + +private: + static void locking_callback(int mode, int type, const char * /*file*/, + int /*line*/) { + auto &lk = (*openSSL_locks_)[static_cast(type)]; + if (mode & CRYPTO_LOCK) { + lk.lock(); + } else { + lk.unlock(); + } + } +}; + +#endif + +class SSLInit { +public: + SSLInit() { +#if OPENSSL_VERSION_NUMBER < 0x1010001fL + SSL_load_error_strings(); + SSL_library_init(); +#else + OPENSSL_init_ssl( + OPENSSL_INIT_LOAD_SSL_STRINGS | OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL); +#endif + } + + ~SSLInit() { +#if OPENSSL_VERSION_NUMBER < 0x1010001fL + ERR_free_strings(); +#endif + } + +private: +#if OPENSSL_VERSION_NUMBER < 0x10100000L + SSLThreadLocks thread_init_; +#endif +}; + +// SSL socket stream implementation +SSLSocketStream::SSLSocketStream(socket_t sock, SSL *ssl, + time_t read_timeout_sec, + time_t read_timeout_usec, + time_t write_timeout_sec, + time_t write_timeout_usec) + : sock_(sock), ssl_(ssl), read_timeout_sec_(read_timeout_sec), + read_timeout_usec_(read_timeout_usec), + write_timeout_sec_(write_timeout_sec), + write_timeout_usec_(write_timeout_usec) { + SSL_clear_mode(ssl, SSL_MODE_AUTO_RETRY); +} + +SSLSocketStream::~SSLSocketStream() {} + +bool SSLSocketStream::is_readable() const { + return detail::select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0; +} + +bool SSLSocketStream::is_writable() const { + return detail::select_write(sock_, write_timeout_sec_, write_timeout_usec_) > + 0; +} + +ssize_t SSLSocketStream::read(char *ptr, size_t size) { + if (SSL_pending(ssl_) > 0) { + return SSL_read(ssl_, ptr, static_cast(size)); + } else if (is_readable()) { + auto ret = SSL_read(ssl_, ptr, static_cast(size)); + if (ret < 0) { + auto err = SSL_get_error(ssl_, ret); + while (err == SSL_ERROR_WANT_READ) { + if (SSL_pending(ssl_) > 0) { + return SSL_read(ssl_, ptr, static_cast(size)); + } else if (is_readable()) { + ret = SSL_read(ssl_, ptr, static_cast(size)); + if (ret >= 0) { return ret; } + err = SSL_get_error(ssl_, ret); + } else { + return -1; + } + } + } + return ret; + } + return -1; +} + +ssize_t SSLSocketStream::write(const char *ptr, size_t size) { + if (is_writable()) { return SSL_write(ssl_, ptr, static_cast(size)); } + return -1; +} + +void SSLSocketStream::get_remote_ip_and_port(std::string &ip, + int &port) const { + detail::get_remote_ip_and_port(sock_, ip, port); +} + +socket_t SSLSocketStream::socket() const { return sock_; } + +static SSLInit sslinit_; + +} // namespace detail + +// SSL HTTP server implementation +SSLServer::SSLServer(const char *cert_path, const char *private_key_path, + const char *client_ca_cert_file_path, + const char *client_ca_cert_dir_path) { + ctx_ = SSL_CTX_new(TLS_method()); + + if (ctx_) { + SSL_CTX_set_options(ctx_, + SSL_OP_ALL | SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | + SSL_OP_NO_COMPRESSION | + SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION); + + // auto ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1); + // SSL_CTX_set_tmp_ecdh(ctx_, ecdh); + // EC_KEY_free(ecdh); + + if (SSL_CTX_use_certificate_chain_file(ctx_, cert_path) != 1 || + SSL_CTX_use_PrivateKey_file(ctx_, private_key_path, SSL_FILETYPE_PEM) != + 1) { + SSL_CTX_free(ctx_); + ctx_ = nullptr; + } else if (client_ca_cert_file_path || client_ca_cert_dir_path) { + // if (client_ca_cert_file_path) { + // auto list = SSL_load_client_CA_file(client_ca_cert_file_path); + // SSL_CTX_set_client_CA_list(ctx_, list); + // } + + SSL_CTX_load_verify_locations(ctx_, client_ca_cert_file_path, + client_ca_cert_dir_path); + + SSL_CTX_set_verify( + ctx_, + SSL_VERIFY_PEER | + SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE, + nullptr); + } + } +} + +SSLServer::SSLServer(X509 *cert, EVP_PKEY *private_key, + X509_STORE *client_ca_cert_store) { + ctx_ = SSL_CTX_new(SSLv23_server_method()); + + if (ctx_) { + SSL_CTX_set_options(ctx_, + SSL_OP_ALL | SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | + SSL_OP_NO_COMPRESSION | + SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION); + + if (SSL_CTX_use_certificate(ctx_, cert) != 1 || + SSL_CTX_use_PrivateKey(ctx_, private_key) != 1) { + SSL_CTX_free(ctx_); + ctx_ = nullptr; + } else if (client_ca_cert_store) { + + SSL_CTX_set_cert_store(ctx_, client_ca_cert_store); + + SSL_CTX_set_verify( + ctx_, + SSL_VERIFY_PEER | + SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE, + nullptr); + } + } +} + +SSLServer::~SSLServer() { + if (ctx_) { SSL_CTX_free(ctx_); } +} + +bool SSLServer::is_valid() const { return ctx_; } + +bool SSLServer::process_and_close_socket(socket_t sock) { + auto ssl = detail::ssl_new( + sock, ctx_, ctx_mutex_, + [&](SSL *ssl) { + return detail::ssl_connect_or_accept_nonblocking( + sock, ssl, SSL_accept, read_timeout_sec_, read_timeout_usec_); + }, + [](SSL * /*ssl*/) { return true; }); + + bool ret = false; + if (ssl) { + ret = detail::process_server_socket_ssl( + ssl, sock, keep_alive_max_count_, keep_alive_timeout_sec_, + read_timeout_sec_, read_timeout_usec_, write_timeout_sec_, + write_timeout_usec_, + [this, ssl](Stream &strm, bool close_connection, + bool &connection_closed) { + return process_request(strm, close_connection, connection_closed, + [&](Request &req) { req.ssl = ssl; }); + }); + + // Shutdown gracefully if the result seemed successful, non-gracefully if + // the connection appeared to be closed. + const bool shutdown_gracefully = ret; + detail::ssl_delete(ctx_mutex_, ssl, shutdown_gracefully); + } + + detail::shutdown_socket(sock); + detail::close_socket(sock); + return ret; +} + +// SSL HTTP client implementation +SSLClient::SSLClient(const std::string &host) + : SSLClient(host, 443, std::string(), std::string()) {} + +SSLClient::SSLClient(const std::string &host, int port) + : SSLClient(host, port, std::string(), std::string()) {} + +SSLClient::SSLClient(const std::string &host, int port, + const std::string &client_cert_path, + const std::string &client_key_path) + : ClientImpl(host, port, client_cert_path, client_key_path) { + ctx_ = SSL_CTX_new(SSLv23_client_method()); + + detail::split(&host_[0], &host_[host_.size()], '.', + [&](const char *b, const char *e) { + host_components_.emplace_back(std::string(b, e)); + }); + if (!client_cert_path.empty() && !client_key_path.empty()) { + if (SSL_CTX_use_certificate_file(ctx_, client_cert_path.c_str(), + SSL_FILETYPE_PEM) != 1 || + SSL_CTX_use_PrivateKey_file(ctx_, client_key_path.c_str(), + SSL_FILETYPE_PEM) != 1) { + SSL_CTX_free(ctx_); + ctx_ = nullptr; + } + } +} + +SSLClient::SSLClient(const std::string &host, int port, + X509 *client_cert, EVP_PKEY *client_key) + : ClientImpl(host, port) { + ctx_ = SSL_CTX_new(SSLv23_client_method()); + + detail::split(&host_[0], &host_[host_.size()], '.', + [&](const char *b, const char *e) { + host_components_.emplace_back(std::string(b, e)); + }); + if (client_cert != nullptr && client_key != nullptr) { + if (SSL_CTX_use_certificate(ctx_, client_cert) != 1 || + SSL_CTX_use_PrivateKey(ctx_, client_key) != 1) { + SSL_CTX_free(ctx_); + ctx_ = nullptr; + } + } +} + +SSLClient::~SSLClient() { + if (ctx_) { SSL_CTX_free(ctx_); } + // Make sure to shut down SSL since shutdown_ssl will resolve to the + // base function rather than the derived function once we get to the + // base class destructor, and won't free the SSL (causing a leak). + SSLClient::shutdown_ssl(socket_, true); +} + +bool SSLClient::is_valid() const { return ctx_; } + +void SSLClient::set_ca_cert_path(const char *ca_cert_file_path, + const char *ca_cert_dir_path) { + if (ca_cert_file_path) { ca_cert_file_path_ = ca_cert_file_path; } + if (ca_cert_dir_path) { ca_cert_dir_path_ = ca_cert_dir_path; } +} + +void SSLClient::set_ca_cert_store(X509_STORE *ca_cert_store) { + if (ca_cert_store) { + if (ctx_) { + if (SSL_CTX_get_cert_store(ctx_) != ca_cert_store) { + // Free memory allocated for old cert and use new store `ca_cert_store` + SSL_CTX_set_cert_store(ctx_, ca_cert_store); + } + } else { + X509_STORE_free(ca_cert_store); + } + } +} + +long SSLClient::get_openssl_verify_result() const { + return verify_result_; +} + +SSL_CTX *SSLClient::ssl_context() const { return ctx_; } + +bool SSLClient::create_and_connect_socket(Socket &socket, Error &error) { + return is_valid() && ClientImpl::create_and_connect_socket(socket, error); +} + +// Assumes that socket_mutex_ is locked and that there are no requests in flight +bool SSLClient::connect_with_proxy(Socket &socket, Response &res, + bool &success, Error &error) { + success = true; + Response res2; + if (!detail::process_client_socket( + socket.sock, read_timeout_sec_, read_timeout_usec_, + write_timeout_sec_, write_timeout_usec_, [&](Stream &strm) { + Request req2; + req2.method = "CONNECT"; + req2.path = host_and_port_; + return process_request(strm, req2, res2, false, error); + })) { + // Thread-safe to close everything because we are assuming there are no + // requests in flight + shutdown_ssl(socket, true); + shutdown_socket(socket); + close_socket(socket); + success = false; + return false; + } + + if (res2.status == 407) { + if (!proxy_digest_auth_username_.empty() && + !proxy_digest_auth_password_.empty()) { + std::map auth; + if (detail::parse_www_authenticate(res2, auth, true)) { + Response res3; + if (!detail::process_client_socket( + socket.sock, read_timeout_sec_, read_timeout_usec_, + write_timeout_sec_, write_timeout_usec_, [&](Stream &strm) { + Request req3; + req3.method = "CONNECT"; + req3.path = host_and_port_; + req3.headers.insert(detail::make_digest_authentication_header( + req3, auth, 1, detail::random_string(10), + proxy_digest_auth_username_, proxy_digest_auth_password_, + true)); + return process_request(strm, req3, res3, false, error); + })) { + // Thread-safe to close everything because we are assuming there are + // no requests in flight + shutdown_ssl(socket, true); + shutdown_socket(socket); + close_socket(socket); + success = false; + return false; + } + } + } else { + res = res2; + return false; + } + } + + return true; +} + +bool SSLClient::load_certs() { + bool ret = true; + + std::call_once(initialize_cert_, [&]() { + std::lock_guard guard(ctx_mutex_); + if (!ca_cert_file_path_.empty()) { + if (!SSL_CTX_load_verify_locations(ctx_, ca_cert_file_path_.c_str(), + nullptr)) { + ret = false; + } + } else if (!ca_cert_dir_path_.empty()) { + if (!SSL_CTX_load_verify_locations(ctx_, nullptr, + ca_cert_dir_path_.c_str())) { + ret = false; + } + } else { +#ifdef _WIN32 + detail::load_system_certs_on_windows(SSL_CTX_get_cert_store(ctx_)); +#else + SSL_CTX_set_default_verify_paths(ctx_); +#endif + } + }); + + return ret; +} + +bool SSLClient::initialize_ssl(Socket &socket, Error &error) { + auto ssl = detail::ssl_new( + socket.sock, ctx_, ctx_mutex_, + [&](SSL *ssl) { + if (server_certificate_verification_) { + if (!load_certs()) { + error = Error::SSLLoadingCerts; + return false; + } + SSL_set_verify(ssl, SSL_VERIFY_NONE, nullptr); + } + + if (!detail::ssl_connect_or_accept_nonblocking( + socket.sock, ssl, SSL_connect, connection_timeout_sec_, + connection_timeout_usec_)) { + error = Error::SSLConnection; + return false; + } + + if (server_certificate_verification_) { + verify_result_ = SSL_get_verify_result(ssl); + + if (verify_result_ != X509_V_OK) { + error = Error::SSLServerVerification; + return false; + } + + auto server_cert = SSL_get_peer_certificate(ssl); + + if (server_cert == nullptr) { + error = Error::SSLServerVerification; + return false; + } + + if (!verify_host(server_cert)) { + X509_free(server_cert); + error = Error::SSLServerVerification; + return false; + } + X509_free(server_cert); + } + + return true; + }, + [&](SSL *ssl) { + SSL_set_tlsext_host_name(ssl, host_.c_str()); + return true; + }); + + if (ssl) { + socket.ssl = ssl; + return true; + } + + shutdown_socket(socket); + close_socket(socket); + return false; +} + +void SSLClient::shutdown_ssl(Socket &socket, bool shutdown_gracefully) { + if (socket.sock == INVALID_SOCKET) { + assert(socket.ssl == nullptr); + return; + } + if (socket.ssl) { + detail::ssl_delete(ctx_mutex_, socket.ssl, shutdown_gracefully); + socket.ssl = nullptr; + } + assert(socket.ssl == nullptr); +} + +bool +SSLClient::process_socket(const Socket &socket, + std::function callback) { + assert(socket.ssl); + return detail::process_client_socket_ssl( + socket.ssl, socket.sock, read_timeout_sec_, read_timeout_usec_, + write_timeout_sec_, write_timeout_usec_, std::move(callback)); +} + +bool SSLClient::is_ssl() const { return true; } + +bool SSLClient::verify_host(X509 *server_cert) const { + /* Quote from RFC2818 section 3.1 "Server Identity" + + If a subjectAltName extension of type dNSName is present, that MUST + be used as the identity. Otherwise, the (most specific) Common Name + field in the Subject field of the certificate MUST be used. Although + the use of the Common Name is existing practice, it is deprecated and + Certification Authorities are encouraged to use the dNSName instead. + + Matching is performed using the matching rules specified by + [RFC2459]. If more than one identity of a given type is present in + the certificate (e.g., more than one dNSName name, a match in any one + of the set is considered acceptable.) Names may contain the wildcard + character * which is considered to match any single domain name + component or component fragment. E.g., *.a.com matches foo.a.com but + not bar.foo.a.com. f*.com matches foo.com but not bar.com. + + In some cases, the URI is specified as an IP address rather than a + hostname. In this case, the iPAddress subjectAltName must be present + in the certificate and must exactly match the IP in the URI. + + */ + return verify_host_with_subject_alt_name(server_cert) || + verify_host_with_common_name(server_cert); +} + +bool +SSLClient::verify_host_with_subject_alt_name(X509 *server_cert) const { + auto ret = false; + + auto type = GEN_DNS; + + struct in6_addr addr6; + struct in_addr addr; + size_t addr_len = 0; + +#ifndef __MINGW32__ + if (inet_pton(AF_INET6, host_.c_str(), &addr6)) { + type = GEN_IPADD; + addr_len = sizeof(struct in6_addr); + } else if (inet_pton(AF_INET, host_.c_str(), &addr)) { + type = GEN_IPADD; + addr_len = sizeof(struct in_addr); + } +#endif + + auto alt_names = static_cast( + X509_get_ext_d2i(server_cert, NID_subject_alt_name, nullptr, nullptr)); + + if (alt_names) { + auto dsn_matched = false; + auto ip_mached = false; + + auto count = sk_GENERAL_NAME_num(alt_names); + + for (decltype(count) i = 0; i < count && !dsn_matched; i++) { + auto val = sk_GENERAL_NAME_value(alt_names, i); + if (val->type == type) { + auto name = (const char *)ASN1_STRING_get0_data(val->d.ia5); + auto name_len = (size_t)ASN1_STRING_length(val->d.ia5); + + switch (type) { + case GEN_DNS: dsn_matched = check_host_name(name, name_len); break; + + case GEN_IPADD: + if (!memcmp(&addr6, name, addr_len) || + !memcmp(&addr, name, addr_len)) { + ip_mached = true; + } + break; + } + } + } + + if (dsn_matched || ip_mached) { ret = true; } + } + + GENERAL_NAMES_free((STACK_OF(GENERAL_NAME) *)alt_names); + return ret; +} + +bool SSLClient::verify_host_with_common_name(X509 *server_cert) const { + const auto subject_name = X509_get_subject_name(server_cert); + + if (subject_name != nullptr) { + char name[BUFSIZ]; + auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName, + name, sizeof(name)); + + if (name_len != -1) { + return check_host_name(name, static_cast(name_len)); + } + } + + return false; +} + +bool SSLClient::check_host_name(const char *pattern, + size_t pattern_len) const { + if (host_.size() == pattern_len && host_ == pattern) { return true; } + + // Wildcard match + // https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/376484 + std::vector pattern_components; + detail::split(&pattern[0], &pattern[pattern_len], '.', + [&](const char *b, const char *e) { + pattern_components.emplace_back(std::string(b, e)); + }); + + if (host_components_.size() != pattern_components.size()) { return false; } + + auto itr = pattern_components.begin(); + for (const auto &h : host_components_) { + auto &p = *itr; + if (p != h && p != "*") { + auto partial_match = (p.size() > 0 && p[p.size() - 1] == '*' && + !p.compare(0, p.size() - 1, h)); + if (!partial_match) { return false; } + } + ++itr; + } + + return true; +} +#endif + +// Universal client implementation +Client::Client(const char *scheme_host_port) + : Client(scheme_host_port, std::string(), std::string()) {} + +Client::Client(const char *scheme_host_port, + const std::string &client_cert_path, + const std::string &client_key_path) { + const static std::regex re(R"(^(?:([a-z]+)://)?([^:/?#]+)(?::(\d+))?)"); + + std::cmatch m; + if (std::regex_match(scheme_host_port, m, re)) { + auto scheme = m[1].str(); + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + if (!scheme.empty() && (scheme != "http" && scheme != "https")) { +#else + if (!scheme.empty() && scheme != "http") { +#endif + std::string msg = "'" + scheme + "' scheme is not supported."; + throw std::invalid_argument(msg); + return; + } + + auto is_ssl = scheme == "https"; + + auto host = m[2].str(); + + auto port_str = m[3].str(); + auto port = !port_str.empty() ? std::stoi(port_str) : (is_ssl ? 443 : 80); + + if (is_ssl) { +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + cli_ = detail::make_unique(host.c_str(), port, + client_cert_path, client_key_path); + is_ssl_ = is_ssl; +#endif + } else { + cli_ = detail::make_unique(host.c_str(), port, + client_cert_path, client_key_path); + } + } else { + cli_ = detail::make_unique(scheme_host_port, 80, + client_cert_path, client_key_path); + } +} + +Client::Client(const std::string &host, int port) + : cli_(detail::make_unique(host, port)) {} + +Client::Client(const std::string &host, int port, + const std::string &client_cert_path, + const std::string &client_key_path) + : cli_(detail::make_unique(host, port, client_cert_path, + client_key_path)) {} + +Client::~Client() {} + +bool Client::is_valid() const { + return cli_ != nullptr && cli_->is_valid(); +} + +Result Client::Get(const char *path) { return cli_->Get(path); } +Result Client::Get(const char *path, const Headers &headers) { + return cli_->Get(path, headers); +} +Result Client::Get(const char *path, Progress progress) { + return cli_->Get(path, std::move(progress)); +} +Result Client::Get(const char *path, const Headers &headers, + Progress progress) { + return cli_->Get(path, headers, std::move(progress)); +} +Result Client::Get(const char *path, ContentReceiver content_receiver) { + return cli_->Get(path, std::move(content_receiver)); +} +Result Client::Get(const char *path, const Headers &headers, + ContentReceiver content_receiver) { + return cli_->Get(path, headers, std::move(content_receiver)); +} +Result Client::Get(const char *path, ContentReceiver content_receiver, + Progress progress) { + return cli_->Get(path, std::move(content_receiver), std::move(progress)); +} +Result Client::Get(const char *path, const Headers &headers, + ContentReceiver content_receiver, Progress progress) { + return cli_->Get(path, headers, std::move(content_receiver), + std::move(progress)); +} +Result Client::Get(const char *path, ResponseHandler response_handler, + ContentReceiver content_receiver) { + return cli_->Get(path, std::move(response_handler), + std::move(content_receiver)); +} +Result Client::Get(const char *path, const Headers &headers, + ResponseHandler response_handler, + ContentReceiver content_receiver) { + return cli_->Get(path, headers, std::move(response_handler), + std::move(content_receiver)); +} +Result Client::Get(const char *path, ResponseHandler response_handler, + ContentReceiver content_receiver, Progress progress) { + return cli_->Get(path, std::move(response_handler), + std::move(content_receiver), std::move(progress)); +} +Result Client::Get(const char *path, const Headers &headers, + ResponseHandler response_handler, + ContentReceiver content_receiver, Progress progress) { + return cli_->Get(path, headers, std::move(response_handler), + std::move(content_receiver), std::move(progress)); +} +Result Client::Get(const char *path, const Params ¶ms, + const Headers &headers, Progress progress) { + return cli_->Get(path, params, headers, progress); +} +Result Client::Get(const char *path, const Params ¶ms, + const Headers &headers, + ContentReceiver content_receiver, Progress progress) { + return cli_->Get(path, params, headers, content_receiver, progress); +} +Result Client::Get(const char *path, const Params ¶ms, + const Headers &headers, + ResponseHandler response_handler, + ContentReceiver content_receiver, Progress progress) { + return cli_->Get(path, params, headers, response_handler, content_receiver, + progress); +} + +Result Client::Head(const char *path) { return cli_->Head(path); } +Result Client::Head(const char *path, const Headers &headers) { + return cli_->Head(path, headers); +} + +Result Client::Post(const char *path) { return cli_->Post(path); } +Result Client::Post(const char *path, const char *body, + size_t content_length, const char *content_type) { + return cli_->Post(path, body, content_length, content_type); +} +Result Client::Post(const char *path, const Headers &headers, + const char *body, size_t content_length, + const char *content_type) { + return cli_->Post(path, headers, body, content_length, content_type); +} +Result Client::Post(const char *path, const std::string &body, + const char *content_type) { + return cli_->Post(path, body, content_type); +} +Result Client::Post(const char *path, const Headers &headers, + const std::string &body, const char *content_type) { + return cli_->Post(path, headers, body, content_type); +} +Result Client::Post(const char *path, size_t content_length, + ContentProvider content_provider, + const char *content_type) { + return cli_->Post(path, content_length, std::move(content_provider), + content_type); +} +Result Client::Post(const char *path, + ContentProviderWithoutLength content_provider, + const char *content_type) { + return cli_->Post(path, std::move(content_provider), content_type); +} +Result Client::Post(const char *path, const Headers &headers, + size_t content_length, + ContentProvider content_provider, + const char *content_type) { + return cli_->Post(path, headers, content_length, std::move(content_provider), + content_type); +} +Result Client::Post(const char *path, const Headers &headers, + ContentProviderWithoutLength content_provider, + const char *content_type) { + return cli_->Post(path, headers, std::move(content_provider), content_type); +} +Result Client::Post(const char *path, const Params ¶ms) { + return cli_->Post(path, params); +} +Result Client::Post(const char *path, const Headers &headers, + const Params ¶ms) { + return cli_->Post(path, headers, params); +} +Result Client::Post(const char *path, + const MultipartFormDataItems &items) { + return cli_->Post(path, items); +} +Result Client::Post(const char *path, const Headers &headers, + const MultipartFormDataItems &items) { + return cli_->Post(path, headers, items); +} +Result Client::Post(const char *path, const Headers &headers, + const MultipartFormDataItems &items, + const std::string &boundary) { + return cli_->Post(path, headers, items, boundary); +} +Result Client::Put(const char *path) { return cli_->Put(path); } +Result Client::Put(const char *path, const char *body, + size_t content_length, const char *content_type) { + return cli_->Put(path, body, content_length, content_type); +} +Result Client::Put(const char *path, const Headers &headers, + const char *body, size_t content_length, + const char *content_type) { + return cli_->Put(path, headers, body, content_length, content_type); +} +Result Client::Put(const char *path, const std::string &body, + const char *content_type) { + return cli_->Put(path, body, content_type); +} +Result Client::Put(const char *path, const Headers &headers, + const std::string &body, const char *content_type) { + return cli_->Put(path, headers, body, content_type); +} +Result Client::Put(const char *path, size_t content_length, + ContentProvider content_provider, + const char *content_type) { + return cli_->Put(path, content_length, std::move(content_provider), + content_type); +} +Result Client::Put(const char *path, + ContentProviderWithoutLength content_provider, + const char *content_type) { + return cli_->Put(path, std::move(content_provider), content_type); +} +Result Client::Put(const char *path, const Headers &headers, + size_t content_length, + ContentProvider content_provider, + const char *content_type) { + return cli_->Put(path, headers, content_length, std::move(content_provider), + content_type); +} +Result Client::Put(const char *path, const Headers &headers, + ContentProviderWithoutLength content_provider, + const char *content_type) { + return cli_->Put(path, headers, std::move(content_provider), content_type); +} +Result Client::Put(const char *path, const Params ¶ms) { + return cli_->Put(path, params); +} +Result Client::Put(const char *path, const Headers &headers, + const Params ¶ms) { + return cli_->Put(path, headers, params); +} +Result Client::Patch(const char *path) { return cli_->Patch(path); } +Result Client::Patch(const char *path, const char *body, + size_t content_length, const char *content_type) { + return cli_->Patch(path, body, content_length, content_type); +} +Result Client::Patch(const char *path, const Headers &headers, + const char *body, size_t content_length, + const char *content_type) { + return cli_->Patch(path, headers, body, content_length, content_type); +} +Result Client::Patch(const char *path, const std::string &body, + const char *content_type) { + return cli_->Patch(path, body, content_type); +} +Result Client::Patch(const char *path, const Headers &headers, + const std::string &body, const char *content_type) { + return cli_->Patch(path, headers, body, content_type); +} +Result Client::Patch(const char *path, size_t content_length, + ContentProvider content_provider, + const char *content_type) { + return cli_->Patch(path, content_length, std::move(content_provider), + content_type); +} +Result Client::Patch(const char *path, + ContentProviderWithoutLength content_provider, + const char *content_type) { + return cli_->Patch(path, std::move(content_provider), content_type); +} +Result Client::Patch(const char *path, const Headers &headers, + size_t content_length, + ContentProvider content_provider, + const char *content_type) { + return cli_->Patch(path, headers, content_length, std::move(content_provider), + content_type); +} +Result Client::Patch(const char *path, const Headers &headers, + ContentProviderWithoutLength content_provider, + const char *content_type) { + return cli_->Patch(path, headers, std::move(content_provider), content_type); +} +Result Client::Delete(const char *path) { return cli_->Delete(path); } +Result Client::Delete(const char *path, const Headers &headers) { + return cli_->Delete(path, headers); +} +Result Client::Delete(const char *path, const char *body, + size_t content_length, const char *content_type) { + return cli_->Delete(path, body, content_length, content_type); +} +Result Client::Delete(const char *path, const Headers &headers, + const char *body, size_t content_length, + const char *content_type) { + return cli_->Delete(path, headers, body, content_length, content_type); +} +Result Client::Delete(const char *path, const std::string &body, + const char *content_type) { + return cli_->Delete(path, body, content_type); +} +Result Client::Delete(const char *path, const Headers &headers, + const std::string &body, + const char *content_type) { + return cli_->Delete(path, headers, body, content_type); +} +Result Client::Options(const char *path) { return cli_->Options(path); } +Result Client::Options(const char *path, const Headers &headers) { + return cli_->Options(path, headers); +} + +bool Client::send(Request &req, Response &res, Error &error) { + return cli_->send(req, res, error); +} + +Result Client::send(const Request &req) { return cli_->send(req); } + +size_t Client::is_socket_open() const { return cli_->is_socket_open(); } + +void Client::stop() { cli_->stop(); } + +void Client::set_default_headers(Headers headers) { + cli_->set_default_headers(std::move(headers)); +} + +void Client::set_address_family(int family) { + cli_->set_address_family(family); +} + +void Client::set_tcp_nodelay(bool on) { cli_->set_tcp_nodelay(on); } + +void Client::set_socket_options(SocketOptions socket_options) { + cli_->set_socket_options(std::move(socket_options)); +} + +void Client::set_connection_timeout(time_t sec, time_t usec) { + cli_->set_connection_timeout(sec, usec); +} + +template +void Client::set_connection_timeout( + const std::chrono::duration &duration) { + cli_->set_connection_timeout(duration); +} + +void Client::set_read_timeout(time_t sec, time_t usec) { + cli_->set_read_timeout(sec, usec); +} + +template +void +Client::set_read_timeout(const std::chrono::duration &duration) { + cli_->set_read_timeout(duration); +} + +void Client::set_write_timeout(time_t sec, time_t usec) { + cli_->set_write_timeout(sec, usec); +} + +template +void +Client::set_write_timeout(const std::chrono::duration &duration) { + cli_->set_write_timeout(duration); +} + +void Client::set_basic_auth(const char *username, const char *password) { + cli_->set_basic_auth(username, password); +} +void Client::set_bearer_token_auth(const char *token) { + cli_->set_bearer_token_auth(token); +} +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT +void Client::set_digest_auth(const char *username, + const char *password) { + cli_->set_digest_auth(username, password); +} +#endif + +void Client::set_keep_alive(bool on) { cli_->set_keep_alive(on); } +void Client::set_follow_location(bool on) { + cli_->set_follow_location(on); +} + +void Client::set_compress(bool on) { cli_->set_compress(on); } + +void Client::set_decompress(bool on) { cli_->set_decompress(on); } + +void Client::set_interface(const char *intf) { + cli_->set_interface(intf); +} + +void Client::set_proxy(const char *host, int port) { + cli_->set_proxy(host, port); +} +void Client::set_proxy_basic_auth(const char *username, + const char *password) { + cli_->set_proxy_basic_auth(username, password); +} +void Client::set_proxy_bearer_token_auth(const char *token) { + cli_->set_proxy_bearer_token_auth(token); +} +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT +void Client::set_proxy_digest_auth(const char *username, + const char *password) { + cli_->set_proxy_digest_auth(username, password); +} +#endif + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT +void Client::enable_server_certificate_verification(bool enabled) { + cli_->enable_server_certificate_verification(enabled); +} +#endif + +void Client::set_logger(Logger logger) { cli_->set_logger(logger); } + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT +void Client::set_ca_cert_path(const char *ca_cert_file_path, + const char *ca_cert_dir_path) { + if (is_ssl_) { + static_cast(*cli_).set_ca_cert_path(ca_cert_file_path, + ca_cert_dir_path); + } +} + +void Client::set_ca_cert_store(X509_STORE *ca_cert_store) { + if (is_ssl_) { + static_cast(*cli_).set_ca_cert_store(ca_cert_store); + } +} + +long Client::get_openssl_verify_result() const { + if (is_ssl_) { + return static_cast(*cli_).get_openssl_verify_result(); + } + return -1; // NOTE: -1 doesn't match any of X509_V_ERR_??? +} + +SSL_CTX *Client::ssl_context() const { + if (is_ssl_) { return static_cast(*cli_).ssl_context(); } + return nullptr; +} +#endif + +} // namespace httplib diff --git a/vendor/DPP/src/dpp/integration.cpp b/vendor/DPP/src/dpp/integration.cpp new file mode 100644 index 00000000..dd5241d4 --- /dev/null +++ b/vendor/DPP/src/dpp/integration.cpp @@ -0,0 +1,120 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { + +integration::integration() : + managed(), + type(i_twitch), + role_id(0), + user_id(0), + expire_grace_period(0), + flags(0), + synced_at(0), + subscriber_count(0) +{ + app.id = 0; + app.bot = nullptr; +} + +integration::~integration() +{ +} + +integration& integration::fill_from_json(nlohmann::json* j) +{ + std::map type_map = { + { "", i_discord }, + { "youtube", i_youtube }, + { "twitch", i_twitch }, + { "discord", i_discord } + }; + this->id = SnowflakeNotNull(j, "id"); + this->name = StringNotNull(j, "name"); + this->type = type_map[StringNotNull(j, "type")]; + if (BoolNotNull(j, "enabled")) + this->flags |= if_enabled; + if (BoolNotNull(j, "syncing")) + this->flags |= if_syncing; + if (BoolNotNull(j, "enable_emoticons")) + this->flags |= if_emoticons; + if (BoolNotNull(j, "revoked")) + this->flags |= if_revoked; + if (Int8NotNull(j, "expire_behavior")) + this->flags |= if_expire_kick; + this->expire_grace_period = Int32NotNull(j, "expire_grace_period"); + if (j->find("user") != j->end()) { + auto t = (*j)["user"]; + this->user_id = SnowflakeNotNull(&t, "user_id"); + } + if (j->find("application") != j->end()) { + auto & t = (*j)["application"]; + this->app.id = SnowflakeNotNull(&t, "id"); + if (t.find("bot") != t.end()) { + auto & b = t["bot"]; + this->app.bot = dpp::find_user(SnowflakeNotNull(&b, "id")); + } + } + this->subscriber_count = Int32NotNull(j, "subscriber_count"); + + this->account_id = StringNotNull(&((*j)["account"]), "id"); + this->account_name = StringNotNull(&((*j)["account"]), "name"); + + return *this; +} + +std::string integration::build_json() const { + return json({ + { "expire_behavior", (flags & if_expire_kick) ? 1 : 0 }, + { "expire_grace_period", expire_grace_period }, + { "enable_emoticons", emoticons_enabled() } + }).dump(); +} + +bool integration::emoticons_enabled() const { + return flags & if_emoticons; +} + +bool integration::is_enabled() const { + return flags & if_enabled; +} + +bool integration::is_syncing() const { + return flags & if_syncing; +} + +bool integration::is_revoked() const { + return flags & if_revoked; +} + +bool integration::expiry_kicks_user() const { + return flags & if_expire_kick; +} + +}; diff --git a/vendor/DPP/src/dpp/invite.cpp b/vendor/DPP/src/dpp/invite.cpp new file mode 100644 index 00000000..725bef63 --- /dev/null +++ b/vendor/DPP/src/dpp/invite.cpp @@ -0,0 +1,70 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { + +invite::invite() : guild_id(0), channel_id(0), inviter_id(0), target_user_id(0), target_user_type(1), approximate_presence_count(0), approximate_member_count(0) +{ +} + +invite::~invite() { +} + + +invite& invite::fill_from_json(nlohmann::json* j) { + code = StringNotNull(j, "code"); + guild_id = (j->find("guild") != j->end()) ? SnowflakeNotNull(&((*j)["guild_id"]), "id") : 0; + channel_id = (j->find("channel") != j->end()) ? SnowflakeNotNull(&((*j)["channel"]), "id") : 0; + inviter_id = (j->find("inviter") != j->end()) ? SnowflakeNotNull(&((*j)["inviter"]), "id") : 0; + target_user_id = (j->find("target_user") != j->end()) ? SnowflakeNotNull(&((*j)["target_user"]), "id") : 0; + target_user_type = Int8NotNull(j, "target_user_type"); + approximate_presence_count = Int32NotNull(j, "approximate_presence_count"); + approximate_member_count = Int32NotNull(j, "approximate_member_count"); + max_age = Int32NotNull(j, "max_age"); + max_uses = Int32NotNull(j, "max_uses"); + temporary = BoolNotNull(j, "temporary"); + unique = BoolNotNull(j, "unique"); + return *this; +} + +std::string invite::build_json() const { + json j; + if (max_age > 0) + j["max_age"] = max_age; + if (max_uses > 0) + j["max_uses"] = max_uses; + if (target_user_id > 0) + j["target_user"] = target_user_id; + if (target_user_type > 0) + j["target_user_type"] = target_user_type; + if (temporary) + j["temporary"] = temporary; + if (unique) + j["unique"] = unique; + return j.dump(); +} + +}; diff --git a/vendor/DPP/src/dpp/managed.cpp b/vendor/DPP/src/dpp/managed.cpp new file mode 100644 index 00000000..7efac659 --- /dev/null +++ b/vendor/DPP/src/dpp/managed.cpp @@ -0,0 +1,29 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include + +namespace dpp { + +managed::managed(const snowflake nid) : id(nid) +{ +} + +}; diff --git a/vendor/DPP/src/dpp/message.cpp b/vendor/DPP/src/dpp/message.cpp new file mode 100644 index 00000000..aa0da318 --- /dev/null +++ b/vendor/DPP/src/dpp/message.cpp @@ -0,0 +1,996 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { + +component::component() : type(static_cast(1)), label(""), style(static_cast(1)), custom_id(""), disabled(false), min_values(-1), max_values(-1) +{ + emoji.animated = false; + emoji.id = 0; + emoji.name = ""; +} + + +component& component::fill_from_json(nlohmann::json* j) { + type = static_cast(Int8NotNull(j, "type")); + if (type == cot_action_row) { + components; + for (json sub_component : (*j)["components"]) { + dpp::component new_component; + new_component.fill_from_json(&sub_component); + components.push_back(new_component); + } + } else if (type == cot_button) { + label = StringNotNull(j, "label"); + style = static_cast(Int8NotNull(j, "style")); + custom_id = StringNotNull(j, "custom_id"); + disabled = BoolNotNull(j, "disabled"); + } else if (type == cot_selectmenu) { + label = ""; + custom_id = StringNotNull(j, "custom_id"); + disabled = BoolNotNull(j, "disabled"); + } + return *this; +} + +component& component::add_component(const component& c) +{ + set_type(cot_action_row); + components.push_back(c); + return *this; +} + +component& component::set_type(component_type ct) +{ + type = ct; + return *this; +} + +component& component::set_label(const std::string &l) +{ + if (type == cot_action_row) { + set_type(cot_button); + } + label = utility::utf8substr(l, 0, 80); + return *this; +} + +component& component::set_style(component_style cs) +{ + set_type(cot_button); + style = cs; + return *this; +} + +component& component::set_url(const std::string& u) +{ + set_type(cot_button); + set_style(cos_link); + url = utility::utf8substr(u, 0, 512); + return *this; +} + +component& component::set_id(const std::string &id) +{ + if (type == cot_action_row) { + set_type(cot_button); + } + custom_id = utility::utf8substr(id, 0, 100); + return *this; +} + +component& component::set_disabled(bool disable) +{ + if (type == cot_action_row) { + set_type(cot_button); + } + disabled = disable; + return *this; +} + +component& component::set_emoji(const std::string& name, dpp::snowflake id, bool animated) +{ + if (type == cot_action_row) { + set_type(cot_button); + } + this->emoji.id = id; + this->emoji.name = name; + this->emoji.animated = animated; + return *this; +} + +std::string component::build_json() const { + json j; + if (type == component_type::cot_action_row) { + j["type"] = 1; + json new_components; + for (component new_component : components) { + new_components.push_back(new_component.build_json()); + } + j["components"] = new_components; + } else if (type == component_type::cot_button) { + j["type"] = 2; + j["label"] = label; + j["style"] = int(style); + j["custom_id"] = custom_id; + j["disabled"] = disabled; + } else if (type == component_type::cot_selectmenu) { + j["type"] = 3; + j["custom_id"] = custom_id; + //j["disabled"] = disabled; + if (!placeholder.empty()) { + j["placeholder"] = placeholder; + } + if (min_values >= 0) { + j["min_values"] = min_values; + } + if (max_values >= 0) { + j["max_values"] = max_values; + } + j["options"] = json::array(); + for (auto opt : options) { + json o; + if (!opt.description.empty()) { + o["description"] = opt.description; + } + if (!opt.label.empty()) { + o["label"] = opt.label; + } + if (!opt.value.empty()) { + o["value"] = opt.value; + } + if (opt.is_default) { + o["default"] = true; + } + if (!opt.emoji.name.empty()) { + o["emoji"] = json::object(); + o["emoji"]["name"] = opt.emoji.name; + if (opt.emoji.id) { + o["emoji"]["id"] = std::to_string(opt.emoji.id); + } + } + j["options"].push_back(o); + } + } + return j.dump(); +} + +select_option::select_option() : is_default(false) { +} + +select_option::select_option(const std::string &_label, const std::string &_value, const std::string &_description) : is_default(false), label(_label), value(_value), description(_description) { +} + +select_option& select_option::set_label(const std::string &l) { + label = dpp::utility::utf8substr(l, 0, 100); + return *this; +} + +select_option& select_option::set_default(bool def) { + is_default = def; + return *this; +} + +select_option& select_option::set_value(const std::string &v) { + value = dpp::utility::utf8substr(v, 0, 100); + return *this; +} + +select_option& select_option::set_description(const std::string &d) { + description = dpp::utility::utf8substr(d, 0, 100); + return *this; +} + +select_option& select_option::set_emoji(const std::string &n, dpp::snowflake id, bool animated) { + emoji.name = n; + emoji.id = id; + emoji.animated = animated; + return *this; +} + +select_option& select_option::set_animated(bool anim) { + emoji.animated = anim; + return *this; +} + + +component& component::set_placeholder(const std::string &_placeholder) { + placeholder = dpp::utility::utf8substr(_placeholder, 0, 100); + return *this; +} + +component& component::set_min_values(uint32_t _min_values) { + min_values = _min_values; + return *this; +} + +component& component::set_max_values(uint32_t _max_values) { + max_values = _max_values; + return *this; +} + +component& component::add_select_option(const select_option &option) { + if (options.size() <= 25) { + options.push_back(option); + } + return *this; +} + +embed::~embed() { +} + +embed::embed() : timestamp(0), color(0) { +} + +message::message() : id(0), channel_id(0), guild_id(0), author(nullptr), sent(0), edited(0), flags(0), + type(mt_default), tts(false), mention_everyone(false), pinned(false), webhook_id(0) +{ + message_reference.channel_id = 0; + message_reference.guild_id = 0; + message_reference.message_id = 0; + message_reference.fail_if_not_exists = false; + interaction.id = 0; + interaction.type = interaction_type::it_ping; + interaction.usr.id = 0; + allowed_mentions.parse_users = false; + allowed_mentions.parse_everyone = false; + allowed_mentions.parse_roles = false; + /* The documentation for discord is INCORRECT. This defaults to true, and must be set to false. + * The default ctor reflects this. + */ + allowed_mentions.replied_user = true; + +} + +message& message::set_reference(snowflake _message_id, snowflake _guild_id, snowflake _channel_id, bool fail_if_not_exists) { + message_reference.channel_id = _channel_id; + message_reference.guild_id = _guild_id; + message_reference.message_id = _message_id; + message_reference.fail_if_not_exists = fail_if_not_exists; + return *this; +} + +message& message::set_allowed_mentions(bool _parse_users, bool _parse_roles, bool _parse_everyone, bool _replied_user, const std::vector &users, const std::vector &roles) { + allowed_mentions.parse_users = _parse_users; + allowed_mentions.parse_everyone = _parse_everyone; + allowed_mentions.parse_roles = _parse_roles; + allowed_mentions.replied_user = _replied_user; + allowed_mentions.users = users; + allowed_mentions.roles = roles; + return *this; +} + +message::message(snowflake _channel_id, const std::string &_content, message_type t) : message() { + channel_id = _channel_id; + content = utility::utf8substr(_content, 0, 2000); + type = t; +} + +message& message::add_component(const component& c) +{ + components.push_back(c); + return *this; +} + +message& message::add_embed(const embed& e) +{ + embeds.push_back(e); + return *this; +} + +message& message::set_flags(uint8_t f) +{ + flags = f; + return *this; +} + +message& message::set_type(message_type t) +{ + type = t; + return *this; +} + +message& message::set_filename(const std::string &fn) +{ + filename = fn; + return *this; +} + +message& message::set_file_content(const std::string &fc) +{ + filecontent = fc; + return *this; +} + +message& message::set_content(const std::string &c) +{ + content = utility::utf8substr(c, 0, 2000); + return *this; +} + +message::message(const std::string &_content, message_type t) : message() { + content = utility::utf8substr(_content, 0, 2000); + type = t; +} + +message::message(snowflake _channel_id, const embed& _embed) : message() { + channel_id = _channel_id; + embeds.push_back(_embed); +} + +embed::embed(json* j) : embed() { + title = StringNotNull(j, "title"); + type = StringNotNull(j, "type"); + description = StringNotNull(j, "description"); + url = StringNotNull(j, "url"); + timestamp = TimestampNotNull(j, "timestamp"); + color = Int32NotNull(j, "color"); + if (j->find("footer") != j->end()) { + dpp::embed_footer f; + json& fj = (*j)["footer"]; + f.text = StringNotNull(&fj, "text"); + f.icon_url = StringNotNull(&fj, "icon_url"); + f.proxy_url = StringNotNull(&fj, "proxy_url"); + footer = f; + } + std::vector type_list = { "image", "video", "thumbnail" }; + for (auto& s : type_list) { + if (j->find(s) != j->end()) { + embed_image curr; + json& fi = (*j)[s]; + curr.url = StringNotNull(&fi, "url"); + curr.height = StringNotNull(&fi, "height"); + curr.width = StringNotNull(&fi, "width"); + curr.proxy_url = StringNotNull(&fi, "proxy_url"); + if (s == "image") { + image = curr; + } else if (s == "video") { + video = curr; + } else if (s == "thumbnail") { + thumbnail = curr; + } + } + } + if (j->find("provider") != j->end()) { + json &p = (*j)["provider"]; + dpp::embed_provider pr; + pr.name = StringNotNull(&p, "name"); + pr.url = StringNotNull(&p, "url"); + provider = pr; + } + if (j->find("author") != j->end()) { + json &a = (*j)["author"]; + dpp::embed_author au; + au.name = StringNotNull(&a, "name"); + au.url = StringNotNull(&a, "url"); + au.icon_url = StringNotNull(&a, "icon_url"); + au.proxy_icon_url = StringNotNull(&a, "proxy_icon_url"); + author = au; + } + if (j->find("fields") != j->end()) { + json &fl = (*j)["fields"]; + for (auto & field : fl) { + embed_field f; + f.name = StringNotNull(&field, "name"); + f.value = StringNotNull(&field, "value"); + f.is_inline = BoolNotNull(&field, "inline"); + fields.push_back(f); + } + } +} + +embed& embed::add_field(const std::string& name, const std::string &value, bool is_inline) { + if (fields.size() < 25) { + embed_field f; + f.name = utility::utf8substr(name, 0, 256); + f.value = utility::utf8substr(value, 0, 1024); + f.is_inline = is_inline; + fields.push_back(f); + } + return *this; +} + +embed& embed::set_author(const embed_author& a) +{ + author = a; + return *this; +} + +embed& embed::set_author(const std::string& name, const std::string& url, const std::string& icon_url) { + dpp::embed_author a; + a.name = utility::utf8substr(name, 0, 256); + a.url = url; + a.icon_url = icon_url; + author = a; + return *this; +} + +embed& embed::set_footer(const embed_footer& f) { + footer = f; + return *this; +} + +embed& embed::set_provider(const std::string& name, const std::string& url) { + dpp::embed_provider p; + p.name = utility::utf8substr(name, 0, 256); + p.url = url; + provider = p; + return *this; +} + +embed& embed::set_image(const std::string& url) { + dpp::embed_image i; + i.url = url; + image = i; + return *this; +} + +embed& embed::set_video(const std::string& url) { + dpp::embed_image v; + v.url = url; + video = v; + return *this; +} + +embed& embed::set_thumbnail(const std::string& url) { + dpp::embed_image t; + t.url = url; + thumbnail = t; + return *this; +} + +embed& embed::set_title(const std::string &text) { + title = utility::utf8substr(text, 0, 256); + return *this; +} + +embed& embed::set_description(const std::string &text) { + description = utility::utf8substr(text, 0, 4096); + return *this; +} + +embed& embed::set_color(uint32_t col) { + // Mask off alpha, as discord doesn't use it + color = col & 0x00FFFFFF; + return *this; +} + +embed& embed::set_url(const std::string &u) { + url = u; + return *this; +} + +embed_footer& embed_footer::set_text(const std::string& t){ + text = t; + return *this; +} + +embed_footer& embed_footer::set_icon(const std::string& i){ + icon_url = i; + return *this; +} + +embed_footer& embed_footer::set_proxy(const std::string& p){ + proxy_url = p; + return *this; +} + +reaction::reaction() { + count = 0; + me = false; + emoji_id = 0; +} + +reaction::reaction(json* j) { + count = (*j)["count"]; + me = (*j)["me"]; + json emoji = (*j)["emoji"]; + emoji_id = SnowflakeNotNull(&emoji, "id"); + emoji_name = StringNotNull(&emoji, "name"); +} + +attachment::attachment() { + id = 0; + size = 0; + width = 0; + height = 0; +} + +attachment::attachment(json *j) : attachment() { + this->id = SnowflakeNotNull(j, "id"); + this->size = (*j)["size"]; + this->filename = (*j)["filename"]; + this->url = (*j)["url"]; + this->proxy_url = (*j)["proxy_url"]; + this->width = Int32NotNull(j, "width"); + this->height = Int32NotNull(j, "height"); + this->content_type = StringNotNull(j, "content_type"); +} + +std::string message::build_json(bool with_id, bool is_interaction_response) const { + /* This is the basics. once it works, expand on it. */ + json j({ + {"channel_id", channel_id}, + {"tts", tts}, + {"nonce", nonce}, + {"flags", flags}, + {"type", type} + }); + + if (with_id) { + j["id"] = std::to_string(id); + } + + if (!content.empty()) { + j["content"] = content; + } + + /* Populate message reference */ + if (message_reference.channel_id || message_reference.guild_id || message_reference.message_id) { + j["message_reference"] = json::object(); + if (message_reference.channel_id) { + j["message_reference"]["channel_id"] = std::to_string(message_reference.channel_id); + } + if (message_reference.guild_id) { + j["message_reference"]["guild_id"] = std::to_string(message_reference.guild_id); + } + if (message_reference.message_id) { + j["message_reference"]["message_id"] = std::to_string(message_reference.message_id); + } + j["message_reference"]["fail_if_not_exists"] = message_reference.fail_if_not_exists; + } + + j["allowed_mentions"] = json::object(); + j["allowed_mentions"]["parse"] = json::array(); + if (allowed_mentions.parse_everyone || allowed_mentions.parse_roles || allowed_mentions.parse_users || !allowed_mentions.replied_user || allowed_mentions.users.size() || allowed_mentions.roles.size()) { + if (allowed_mentions.parse_everyone) { + j["allowed_mentions"]["parse"].push_back("everyone"); + } + if (allowed_mentions.parse_roles) { + j["allowed_mentions"]["parse"].push_back("roles"); + } + if (allowed_mentions.parse_users) { + j["allowed_mentions"]["parse"].push_back("users"); + } + if (!allowed_mentions.replied_user) { + j["allowed_mentions"]["replied_user"] = false; + } + if (allowed_mentions.users.size()) { + j["allowed_mentions"]["users"] = json::array(); + for (auto& user : allowed_mentions.users) { + j["allowed_mentions"]["users"].push_back(std::to_string(user)); + } + } + if (allowed_mentions.roles.size()) { + j["allowed_mentions"]["roles"] = json::array(); + for (auto& role : allowed_mentions.roles) { + j["allowed_mentions"]["roles"].push_back(std::to_string(role)); + } + } + } + + + if (components.size()) { + j["components"] = json::array(); + } + for (auto & component : components) { + json n; + n["type"] = cot_action_row; + n["components"] = {}; + json sn; + for (auto & subcomponent : component.components) { + if (subcomponent.type == cot_button) { + sn["type"] = subcomponent.type; + sn["label"] = subcomponent.label; + sn["style"] = int(subcomponent.style); + if (subcomponent.type == cot_button && subcomponent.style != cos_link && !subcomponent.custom_id.empty()) { + /* Links cannot have a custom id */ + sn["custom_id"] = subcomponent.custom_id; + } + if (subcomponent.type == cot_button && subcomponent.style == cos_link && !subcomponent.url.empty()) { + sn["url"] = subcomponent.url; + } + sn["disabled"] = subcomponent.disabled; + + if (subcomponent.emoji.id || !subcomponent.emoji.name.empty()) { + sn["emoji"] = {}; + sn["emoji"]["animated"] = subcomponent.emoji.animated; + } + if (subcomponent.emoji.id) { + sn["emoji"]["id"] = std::to_string(subcomponent.emoji.id); + } + if (!subcomponent.emoji.name.empty()) { + sn["emoji"]["name"] = subcomponent.emoji.name; + } + } else if (subcomponent.type == cot_selectmenu) { + + sn["type"] = subcomponent.type; + sn["custom_id"] = subcomponent.custom_id; + //sn["disabled"] = subcomponent.disabled; + if (!subcomponent.placeholder.empty()) { + sn["placeholder"] = subcomponent.placeholder; + } + if (subcomponent.min_values >= 0) { + sn["min_values"] = subcomponent.min_values; + } + if (subcomponent.max_values >= 0) { + sn["max_values"] = subcomponent.max_values; + } + sn["options"] = json::array(); + for (auto opt : subcomponent.options) { + json o; + if (!opt.description.empty()) { + o["description"] = opt.description; + } + if (!opt.label.empty()) { + o["label"] = opt.label; + } + if (!opt.value.empty()) { + o["value"] = opt.value; + } + if (opt.is_default) { + o["default"] = true; + } + if (!opt.emoji.name.empty()) { + o["emoji"] = json::object(); + o["emoji"]["name"] = opt.emoji.name; + if (opt.emoji.id) { + o["emoji"]["id"] = std::to_string(opt.emoji.id); + } + if (opt.emoji.animated) { + o["emoji"]["animated"] = true; + } + } + sn["options"].push_back(o); + } + } + + n["components"].push_back(sn); + } + j["components"].push_back(n); + } + if (embeds.size()) { + j["embeds"] = json::array(); + + for (auto& embed : embeds) { + json e; + if (!embed.description.empty()) + e["description"] = embed.description; + if (!embed.title.empty()) + e["title"] = embed.title; + if (!embed.url.empty()) + e["url"] = embed.url; + e["color"] = embed.color; + if (embed.footer.has_value()) { + e["footer"]["text"] = embed.footer->text; + e["footer"]["icon_url"] = embed.footer->icon_url; + } + if (embed.image.has_value()) { + e["image"]["url"] = embed.image->url; + } + if (embed.thumbnail.has_value()) { + e["thumbnail"]["url"] = embed.thumbnail->url; + } + if (embed.author.has_value()) { + e["author"]["name"] = embed.author->name; + e["author"]["url"] = embed.author->url; + e["author"]["icon_url"] = embed.author->icon_url; + } + if (embed.fields.size()) { + e["fields"] = json(); + for (auto& field : embed.fields) { + json f({ {"name", field.name}, {"value", field.value}, {"inline", field.is_inline} }); + e["fields"].push_back(f); + } + } + if (embed.timestamp != 0) { + std::ostringstream ss; + struct tm t; + + #ifdef _WIN32 + gmtime_s(&t, &embed.timestamp); + #else + gmtime_r(&embed.timestamp, &t); + #endif + + ss << std::put_time(&t, "%FT%TZ"); + e["timestamp"] = ss.str(); + } + + j["embeds"].push_back(e); + } + } + return j.dump(); +} + +bool message::is_crossposted() const { + return flags & m_crossposted; +} + +bool message::is_crosspost() const { + return flags & m_is_crosspost; + +} + +bool message::supress_embeds() const { + return flags & m_supress_embeds; +} + +bool message::is_source_message_deleted() const { + return flags & m_source_message_deleted; +} + +bool message::is_urgent() const { + return flags & m_urgent; +} + +bool message::is_ephemeral() const { + return flags & m_ephemeral; +} + +bool message::is_loading() const { + return flags & m_loading; +} + +message::~message() { +} + + +message& message::fill_from_json(json* d, cache_policy_t cp) { + this->id = SnowflakeNotNull(d, "id"); + this->channel_id = SnowflakeNotNull(d, "channel_id"); + this->guild_id = SnowflakeNotNull(d, "guild_id"); + /* We didn't get a guild id. See if we can find one in the channel */ + if (guild_id == 0 && channel_id != 0) { + dpp::channel* c = dpp::find_channel(this->channel_id); + if (c) { + this->guild_id = c->guild_id; + } + } + this->flags = Int8NotNull(d, "flags"); + this->type = Int8NotNull(d, "type"); + this->author = nullptr; + user* authoruser = nullptr; + /* May be null, if its null cache it from the partial */ + if (d->find("author") != d->end()) { + json &j_author = (*d)["author"]; + if (cp.user_policy == dpp::cp_none) { + /* User caching off! Allocate a temp user to be deleted in destructor */ + authoruser = &self_author; + this->author = &self_author; + self_author.fill_from_json(&j_author); + } else { + /* User caching on - aggressive or lazy - create a cached user entry */ + authoruser = find_user(SnowflakeNotNull(&j_author, "id")); + if (!authoruser) { + /* User does not exist yet, cache the partial as a user record */ + authoruser = new user(); + authoruser->fill_from_json(&j_author); + get_user_cache()->store(authoruser); + } + this->author = authoruser; + } + } + if (d->find("interaction") != d->end()) { + json& inter = (*d)["interaction"]; + interaction.id = SnowflakeNotNull(&inter, "id"); + interaction.name = StringNotNull(&inter, "name"); + interaction.type = Int8NotNull(&inter, "type"); + if (inter.contains("user") && !inter["user"].is_null()) from_json(inter["user"], interaction.usr); + } + if (d->find("sticker_items") != d->end()) { + json &sub = (*d)["sticker_items"]; + for (auto & sticker_raw : sub) { + stickers.push_back(dpp::sticker().fill_from_json(&sticker_raw)); + } + } + if (d->find("mentions") != d->end()) { + json &sub = (*d)["mentions"]; + for (auto & m : sub) { + mentions.push_back(SnowflakeNotNull(&m, "id")); + } + } + if (d->find("mention_roles") != d->end()) { + json &sub = (*d)["mention_roles"]; + for (auto & m : sub) { + mention_roles.push_back(from_string(m, std::dec)); + } + } + if (d->find("mention_channels") != d->end()) { + json &sub = (*d)["mention_channels"]; + for (auto & m : sub) { + mention_channels.push_back(SnowflakeNotNull(&m, "id")); + } + } + /* Fill in member record, cache uncached ones */ + guild* g = find_guild(this->guild_id); + this->member = {}; + if (g && d->find("member") != d->end()) { + json& mi = (*d)["member"]; + snowflake uid = SnowflakeNotNull(&(mi["user"]), "id"); + if (!uid && authoruser) { + uid = authoruser->id; + } + if (cp.user_policy == dpp::cp_none) { + /* User caching off! Just fill in directly but dont store member to guild */ + this->member.fill_from_json(&mi, g->id, uid); + } else { + /* User caching on, lazy or aggressive - cache the member information */ + auto thismember = g->members.find(uid); + if (thismember == g->members.end()) { + if (uid != 0 && authoruser) { + guild_member gm; + gm.fill_from_json(&mi, g->id, uid); + g->members[authoruser->id] = gm; + this->member = gm; + } + } else { + /* Update roles etc */ + this->member = thismember->second; + if (authoruser) { + this->member.fill_from_json(&mi, g->id, authoruser->id); + g->members[authoruser->id] = this->member; + } + } + } + } + if (d->find("embeds") != d->end()) { + json & el = (*d)["embeds"]; + for (auto& e : el) { + this->embeds.push_back(embed(&e)); + } + } + this->content = StringNotNull(d, "content"); + this->sent = TimestampNotNull(d, "timestamp"); + this->edited = TimestampNotNull(d, "edited_timestamp"); + this->tts = BoolNotNull(d, "tts"); + this->mention_everyone = BoolNotNull(d, "mention_everyone"); + if (d->find("reactions") != d->end()) { + json & el = (*d)["reactions"]; + for (auto& e : el) { + this->reactions.push_back(reaction(&e)); + } + } + if (((*d)["nonce"]).is_string()) { + this->nonce = StringNotNull(d, "nonce"); + } else { + this->nonce = std::to_string(SnowflakeNotNull(d, "nonce")); + } + this->pinned = BoolNotNull(d, "pinned"); + this->webhook_id = SnowflakeNotNull(d, "webhook_id"); + for (auto& e : (*d)["attachments"]) { + this->attachments.push_back(attachment(&e)); + } + return *this; +} + +sticker::sticker() : id(0), pack_id(0), guild_id(0), type(st_standard), format_type(sf_png), available(true), sort_value(0) { +} + +sticker& sticker::fill_from_json(nlohmann::json* j) { + this->id = SnowflakeNotNull(j, "id"); + this->pack_id = SnowflakeNotNull(j, "pack_id"); + this->name = StringNotNull(j, "name"); + this->description = StringNotNull(j, "description"); + this->tags = StringNotNull(j, "tags"); + this->asset = StringNotNull(j, "asset"); + this->guild_id = SnowflakeNotNull(j, "guild_id"); + this->type = static_cast(Int8NotNull(j, "type")); + this->format_type = static_cast(Int8NotNull(j, "format_type")); + this->available = BoolNotNull(j, "available"); + this->sort_value = Int8NotNull(j, "sort_value"); + if (j->find("user") != j->end()) { + sticker_user.fill_from_json(&((*j)["user"])); + } + + return *this; +} + +std::string sticker::build_json(bool with_id) const { + json j; + + if (with_id) { + j["id"] = std::to_string(this->id); + } + j["pack_id"] = std::to_string(this->pack_id); + if (this->guild_id) { + j["guild_id"] = std::to_string(this->guild_id); + } + j["name"] = this->name; + j["description"] = this->description; + if (!this->tags.empty()) { + j["tags"] = this->tags; + } + if (!this->asset.empty()) { + j["asset"] = this->asset; + } + j["type"] = this->type; + j["format_type"] = this->format_type; + j["available"] = this->available; + j["sort_value"] = this->sort_value; + + return j.dump(); +} + +sticker_pack::sticker_pack() : id(0), sku_id(0), cover_sticker_id(0), banner_asset_id(0) { +} + +sticker_pack& sticker_pack::fill_from_json(nlohmann::json* j) { + this->id = SnowflakeNotNull(j, "id"); + this->sku_id = SnowflakeNotNull(j, "sku_id"); + this->cover_sticker_id = SnowflakeNotNull(j, "cover_sticker_id"); + this->banner_asset_id = SnowflakeNotNull(j, "banner_asset_id"); + this->name = StringNotNull(j, "name"); + this->description = StringNotNull(j, "description"); + if (j->find("stickers") != j->end()) { + json & sl = (*j)["stickers"]; + for (auto& s : sl) { + this->stickers[SnowflakeNotNull(&s, "id")] = sticker().fill_from_json(&s); + } + } + return *this; +} + +std::string sticker_pack::build_json(bool with_id) const { + json j; + if (with_id) { + j["id"] = std::to_string(this->id); + } + if (sku_id) { + j["sku_id"] = std::to_string(sku_id); + } + if (cover_sticker_id) { + j["cover_sticker_id"] = std::to_string(cover_sticker_id); + } + if (banner_asset_id) { + j["banner_asset_id"] = std::to_string(banner_asset_id); + } + j["name"] = name; + j["description"] = description; + j["stickers"] = json::array(); + for (auto& s : stickers) { + j["stickers"].push_back(json::parse(s.second.build_json(with_id))); + } + return j.dump(); +} + +sticker& sticker::set_filename(const std::string &fn) { + filename = fn; + return *this; +} + +sticker& sticker::set_file_content(const std::string &fc) { + filecontent = fc; + return *this; +} + + +}; diff --git a/vendor/DPP/src/dpp/presence.cpp b/vendor/DPP/src/dpp/presence.cpp new file mode 100644 index 00000000..23dce49b --- /dev/null +++ b/vendor/DPP/src/dpp/presence.cpp @@ -0,0 +1,211 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { + +activity::activity(const activity_type typ, const std::string& nam, const std::string& stat, const std::string& url_) : type(typ), name(nam), state(stat), url(url_) +{ +} + +presence::presence() : guild_id(0), user_id(0), flags(0) +{ +} + +presence::presence(presence_status status, activity_type type, const std::string& activity_description) { + dpp::activity a; + a.name = activity_description; + a.type = type; + activities.clear(); + activities.push_back(a); + flags &= PF_CLEAR_STATUS; + if (status == ps_online) + flags |= p_status_online; + else if (status == ps_idle) + flags |= p_status_idle; + else if (status == ps_dnd) + flags |= p_status_dnd; +} + +presence::presence(presence_status status, activity a) { + activities.clear(); + activities.push_back(std::move(a)); + flags &= PF_CLEAR_STATUS; + if (status == ps_online) + flags |= p_status_online; + else if (status == ps_idle) + flags |= p_status_idle; + else if (status == ps_dnd) + flags |= p_status_dnd; +} + +presence::~presence() { +} + +presence& presence::fill_from_json(nlohmann::json* j) { + guild_id = SnowflakeNotNull(j, "guild_id"); + user_id = SnowflakeNotNull(&((*j)["user"]), "id"); + + auto f = j->find("client_status"); + if (f != j->end()) { + + bool update_desktop = false, update_web = false, update_mobile = false; + std::string desktop, mobile, web; + + if (f->find("desktop") != f->end()) { + desktop = StringNotNull(&((*j)["client_status"]), "desktop"); + update_desktop = true; + } + if (f->find("mobile") != f->end()) { + mobile = StringNotNull(&((*j)["client_status"]), "mobile"); + update_mobile = true; + } + if (f->find("web") != f->end()) { + web = StringNotNull(&((*j)["client_status"]), "web"); + update_web = true; + } + + if (update_desktop) { + flags &= PF_CLEAR_DESKTOP; + if (desktop == "online") + flags |= p_desktop_online; + else if (desktop == "idle") + flags |= p_desktop_idle; + else if (desktop == "dnd") + flags |= p_desktop_dnd; + } + + if (update_mobile) { + flags &= PF_CLEAR_MOBILE; + if (mobile == "online") + flags |= p_mobile_online; + else if (mobile == "idle") + flags |= p_mobile_idle; + else if (mobile == "dnd") + flags |= p_mobile_dnd; + } + + if (update_web) { + flags &= PF_CLEAR_WEB; + if (web == "online") + flags |= p_web_online; + else if (web == "idle") + flags |= p_web_idle; + else if (web == "dnd") + flags |= p_web_dnd; + } + } + + if (j->find("status") != j->end()) { + flags &= PF_CLEAR_STATUS; + std::string main = StringNotNull(j, "status"); + if (main == "online") + flags |= p_status_online; + else if (main == "idle") + flags |= p_status_idle; + else if (main == "dnd") + flags |= p_status_dnd; + } + + + if (j->find("activities") != j->end()) { + activities.clear(); + for (auto & act : (*j)["activities"]) { + activity a; + a.name = StringNotNull(&act, "name"); + a.state = StringNotNull(&act, "state"); // if user + if (a.state.empty()) a.state = StringNotNull(&act, "details"); // if activity from bot, maybe? + a.type = (activity_type)Int8NotNull(&act, "type"); + a.url = StringNotNull(&act, "url"); + a.created_at = Int64NotNull(&act, "created_at"); + if (act.find("timestamps") != act.end()) { + a.start = Int64NotNull(&(act["timestamps"]), "start"); + a.end = Int64NotNull(&(act["timestamps"]), "end"); + } + a.application_id = SnowflakeNotNull(&act, "application_id"); + a.flags = Int8NotNull(&act, "flags"); + + activities.push_back(a); + } + } + + return *this; +} + +std::string presence::build_json() const { + std::map status_name_mapping = { + {ps_online, "online"}, + {ps_offline, "offline"}, + {ps_idle, "idle"}, + {ps_dnd, "dnd"} + }; + json j({ + + {"op", 3}, + {"d", + { + { "status", status_name_mapping[status()] }, + { "since", json::value_t::null }, + { "afk", false } + } + } + }); + if (activities.size()) { + for(const auto& i : activities){ + json j2({ + { "name", i.name }, + { "type", i.type } + }); + if (!i.url.empty()) j2["url"] = i.url; + if (!i.state.empty()) j2["details"] = i.state; // bot activity is details, not state + + j["d"]["activities"].push_back(j2); + } + /*j["d"]["game"] = json({ // use activities instead. + { "name", activities[0].name }, + { "type", activities[0].type } + });*/ + } + + return j.dump(); +} + +presence_status presence::desktop_status() const { + return (presence_status)((flags >> PF_SHIFT_DESKTOP) & PF_STATUS_MASK); +} + +presence_status presence::web_status() const { + return (presence_status)((flags >> PF_SHIFT_WEB) & PF_STATUS_MASK); +} + +presence_status presence::mobile_status() const { + return (presence_status)((flags >> PF_SHIFT_MOBILE) & PF_STATUS_MASK); +} + +presence_status presence::status() const { + return (presence_status)((flags >> PF_SHIFT_MAIN) & PF_STATUS_MASK); +} + +}; diff --git a/vendor/DPP/src/dpp/prune.cpp b/vendor/DPP/src/dpp/prune.cpp new file mode 100644 index 00000000..6799e0df --- /dev/null +++ b/vendor/DPP/src/dpp/prune.cpp @@ -0,0 +1,53 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include + +namespace dpp { + +using json = nlohmann::json; + +prune& prune::fill_from_json(nlohmann::json* j) { + days = Int32NotNull(j, "days"); + compute_prune_count = BoolNotNull(j, "compute_prune_count"); + if (j->find("include_roles") != j->end()) { + for (auto & r : (*j)["include_roles"]) { + include_roles.push_back(from_string(r.get(), std::dec)); + } + } + return *this; +} + +std::string prune::build_json(bool with_prune_count) const { + json j; + for (auto & r : include_roles) { + j["include_roles"].push_back(std::to_string(r)); + } + if (with_prune_count) { + j["compute_prune_count"] = compute_prune_count; + } + j["days"] = days; + return j.dump(); +} + +}; diff --git a/vendor/DPP/src/dpp/queues.cpp b/vendor/DPP/src/dpp/queues.cpp new file mode 100644 index 00000000..405f7781 --- /dev/null +++ b/vendor/DPP/src/dpp/queues.cpp @@ -0,0 +1,472 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include + +#ifdef _WIN32 +#include +#include +#include +#pragma comment(lib,"ws2_32") +#else +#include +#include +#include +#include +#endif + +#include +#include +#include +#include +#include +#include +#define CPPHTTPLIB_OPENSSL_SUPPORT +#include +#include +#include + +namespace dpp { + +http_request::http_request(const std::string &_endpoint, const std::string &_parameters, http_completion_event completion, const std::string &_postdata, http_method _method, const std::string &filename, const std::string &filecontent) : endpoint(_endpoint), parameters(_parameters), complete_handler(completion), postdata(_postdata), method(_method), completed(false), file_name(filename), file_content(filecontent) +{ +} + +http_request::~http_request() { +} + +void http_request::complete(const http_request_completion_t &c) { + /* Call completion handler only if the request has been completed */ + if (is_completed() && complete_handler) + complete_handler(c); +} + +/* Fill a http_request_completion_t from a HTTP result */ +void populate_result(const std::string &url, const cluster* owner, http_request_completion_t& rv, const httplib::Result &res) { + rv.status = res->status; + rv.body = res->body; + for (auto &v : res->headers) { + rv.headers[v.first] = v.second; + } + rv.ratelimit_limit = from_string(res->get_header_value("X-RateLimit-Limit"), std::dec); + rv.ratelimit_remaining = from_string(res->get_header_value("X-RateLimit-Remaining"), std::dec); + rv.ratelimit_reset_after = from_string(res->get_header_value("X-RateLimit-Reset-After"), std::dec); + rv.ratelimit_bucket = res->get_header_value("X-RateLimit-Bucket"); + rv.ratelimit_global = (res->get_header_value("X-RateLimit-Global") == "true"); + if (res->get_header_value("X-RateLimit-Retry-After") != "") { + rv.ratelimit_retry_after = from_string(res->get_header_value("X-RateLimit-Retry-After"), std::dec); + } + if (rv.status == 429) { + owner->log(ll_warning, fmt::format("Rate limited on endpoint {}, reset after {}s!", url, rv.ratelimit_retry_after ? rv.ratelimit_retry_after : rv.ratelimit_reset_after)); + } + if (url != "/api/v" DISCORD_API_VERSION "/gateway/bot") { // Squelch this particular api endpoint or it generates a warning the minute we boot a cluster + if (rv.ratelimit_global) { + owner->log(ll_warning, fmt::format("At global rate limit on endpoint {}, reset after {}s", url, rv.ratelimit_retry_after ? rv.ratelimit_retry_after : rv.ratelimit_reset_after)); + } else if (rv.ratelimit_remaining == 1) { + owner->log(ll_warning, fmt::format("Near endpoint {} rate limit, reset after {}s", url, rv.ratelimit_retry_after ? rv.ratelimit_retry_after : rv.ratelimit_reset_after)); + } + } +} + +/* Returns true if the request has been made */ +bool http_request::is_completed() +{ + return completed; +} + +/* Execute a HTTP request */ +http_request_completion_t http_request::Run(const cluster* owner) { + + http_request_completion_t rv; + + httplib::Client cli("https://discord.com"); + /* This is for a reason :( - Some systems have really out of date cert stores */ + cli.enable_server_certificate_verification(false); + cli.set_follow_location(true); + /* TODO: Once we have a version number header, use it here */ + httplib::Headers headers = { + {"Authorization", std::string("Bot ") + owner->token}, + {"User-Agent", "DiscordBot (https://github.com/brainboxdotcc/DPP, 0.0.1)"} + }; + cli.set_default_headers(headers); + + rv.ratelimit_limit = rv.ratelimit_remaining = rv.ratelimit_reset_after = rv.ratelimit_retry_after = 0; + rv.status = 0; + rv.ratelimit_global = false; + + std::string _url = endpoint; + if (!empty(parameters)) { + _url = endpoint + "/" +parameters; + } + + /* Because of the design of cpp-httplib we can't create a httplib::Result once and make this code + * shorter. We have to use "auto res = ...". This is because httplib::Result has no default constructor + * and needs to be passed a result and some other blackboxed rammel. + */ + switch (method) { + case m_get: { + if (auto res = cli.Get(_url.c_str())) { + populate_result(_url, owner, rv, res); + } else { + rv.error = (http_error)res.error(); + } + } + break; + case m_post: { + /* POST supports post data body */ + if (!file_name.empty() && !file_content.empty()) { + httplib::MultipartFormDataItems items = { + { "payload_json", postdata, "", "application/json" }, + { "file", file_content, file_name, "application/octet-stream" } + }; + if (auto res = cli.Post(_url.c_str(), items)) { + populate_result(_url, owner, rv, res); + } else { + rv.error = (http_error)res.error(); + } + } else { + if (auto res = cli.Post(_url.c_str(), postdata.c_str(), "application/json")) { + populate_result(_url, owner, rv, res); + } else { + rv.error = (http_error)res.error(); + } + } + } + break; + case m_patch: { + if (auto res = cli.Patch(_url.c_str(), postdata.c_str(), "application/json")) { + populate_result(_url, owner, rv, res); + } else { + rv.error = (http_error)res.error(); + } + } + break; + case m_put: { + /* PUT supports post data body */ + if (auto res = cli.Put(_url.c_str(), postdata.c_str(), "application/json")) { + populate_result(_url, owner, rv, res); + } else { + rv.error = (http_error)res.error(); + } + + } + break; + case m_delete: { + if (auto res = cli.Delete(_url.c_str())) { + populate_result(_url, owner, rv, res); + } else { + rv.error = (http_error)res.error(); + } + + } + break; + } + /* Set completion flag */ + completed = true; + return rv; +} + +request_queue::request_queue(const class cluster* owner) : creator(owner), terminating(false), globally_ratelimited(false), globally_limited_for(0) +{ + in_queue_listen_sock = socket(AF_INET, SOCK_STREAM, 0); + out_queue_listen_sock = socket(AF_INET, SOCK_STREAM, 0); + if (in_queue_listen_sock == -1 || out_queue_listen_sock == -1) { + throw dpp::exception("Can't initialise request queue sockets"); + } + + std::mt19937 generator(time(NULL)); + std::uniform_real_distribution distribution(8192, 32760); + + in_queue_port = distribution(generator); + out_queue_port = distribution(generator); + + struct sockaddr_in in_server, out_server; + in_server.sin_family = out_server.sin_family = AF_INET; + in_server.sin_addr.s_addr = out_server.sin_addr.s_addr = htonl(0x7f000001); /* Localhost */ + in_server.sin_port = htons(in_queue_port); + out_server.sin_port = htons(out_queue_port); + + if ((bind(in_queue_listen_sock, (struct sockaddr *)&in_server , sizeof(in_server)) < 0) || (bind(out_queue_listen_sock, (struct sockaddr *)&out_server , sizeof(out_server)) < 0)) { + throw dpp::exception("Can't bind request queue sockets"); + } + /* Backlog is only 1, because we only expect our own system to connect back to this once */ + listen(in_queue_listen_sock, 1); + listen(out_queue_listen_sock, 1); + + in_thread = new std::thread(&request_queue::in_loop, this); + out_thread = new std::thread(&request_queue::out_loop, this); + + std::this_thread::sleep_for(std::chrono::milliseconds(250)); + + in_queue_connect_sock = socket(AF_INET, SOCK_STREAM, 0); + out_queue_connect_sock = socket(AF_INET, SOCK_STREAM, 0); + if (in_queue_connect_sock == -1 || out_queue_connect_sock == -1) { + throw dpp::exception("Can't initialise request queue notifier sockets"); + } + + struct sockaddr_in in_client, out_client; + in_client.sin_addr.s_addr = out_client.sin_addr.s_addr = inet_addr("127.0.0.1"); + in_client.sin_family = out_client.sin_family = AF_INET; + in_client.sin_port = htons(in_queue_port); + out_client.sin_port = htons(out_queue_port); + + if ((connect(in_queue_connect_sock, (struct sockaddr *)&in_client, sizeof(in_client)) < 0) || (connect(out_queue_connect_sock, (struct sockaddr *)&out_client, sizeof(out_client)) < 0)) { + throw dpp::exception("Can't connect notifiers"); + } +} + +request_queue::~request_queue() +{ + terminating = true; + in_thread->join(); + out_thread->join(); + delete in_thread; + delete out_thread; +} + +void request_queue::in_loop() +{ + int c = sizeof(struct sockaddr_in); + fd_set readfds; + timeval ts; + char n; + struct sockaddr_in client; + int notifier = accept(in_queue_listen_sock, (struct sockaddr *)&client, (socklen_t*)&c); +#ifndef _WIN32 + close(in_queue_listen_sock); +#endif + while (!terminating) { + /* select for one second, waiting for new data */ + FD_ZERO(&readfds); + FD_SET(notifier, &readfds); + ts.tv_sec = 1; + ts.tv_usec = 0; + int r = select(FD_SETSIZE, &readfds, 0, 0, &ts); + time_t now = time(nullptr); + + if (r > 0 && FD_ISSET(notifier, &readfds)) { + + if (recv(notifier, &n, 1, 0) > 0) { + /* New request to be sent! */ + + if (!globally_ratelimited) { + + std::map> requests_in_copy; + { + /* Make a safe copy within a mutex */ + std::lock_guard lock(in_mutex); + requests_in_copy = requests_in; + } + + for (auto & bucket : requests_in_copy) { + for (auto req : bucket.second) { + + http_request_completion_t rv; + auto currbucket = buckets.find(bucket.first); + + if (currbucket != buckets.end()) { + /* Theres a bucket for this request. Check its status. If the bucket says to wait, + * skip all requests in this bucket till its ok. + */ + if (currbucket->second.remaining < 1) { + uint64_t wait = (currbucket->second.retry_after ? currbucket->second.retry_after : currbucket->second.reset_after); + if (time(NULL) > currbucket->second.timestamp + wait) { + /* Time has passed, we can process this bucket again. send its request. */ + rv = req->Run(creator); + } else { + /* Time not up yet, emit signal and wait */ + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + emit_in_queue_signal(); + break; + } + } else { + /* There's limit remaining, we can just run the request */ + rv = req->Run(creator); + } + } else { + /* No bucket for this endpoint yet. Just send it, and make one from its reply */ + rv = req->Run(creator); + } + + bucket_t newbucket; + newbucket.limit = rv.ratelimit_limit; + newbucket.remaining = rv.ratelimit_remaining; + newbucket.reset_after = rv.ratelimit_reset_after; + newbucket.retry_after = rv.ratelimit_retry_after; + newbucket.timestamp = time(NULL); + globally_ratelimited = rv.ratelimit_global; + if (globally_ratelimited) { + globally_limited_for = (newbucket.retry_after ? newbucket.retry_after : newbucket.reset_after); + } + buckets[req->endpoint] = newbucket; + + /* Make a new entry in the completion list and notify */ + { + std::lock_guard lock(out_mutex); + http_request_completion_t* hrc = new http_request_completion_t(); + *hrc = rv; + responses_out.push(std::make_pair(hrc, req)); + emit_out_queue_signal(); + } + } + } + + { + std::lock_guard lock(in_mutex); + bool again = false; + do { + again = false; + for (auto & bucket : requests_in) { + for (auto req = bucket.second.begin(); req != bucket.second.end(); ++req) { + if ((*req)->is_completed()) { + requests_in[bucket.first].erase(req); + again = true; + goto out; /* Only clean way out of a nested loop */ + } + } + } + out:; + } while (again); + } + + } else { + if (globally_limited_for > 0) { + std::this_thread::sleep_for(std::chrono::seconds(globally_limited_for)); + globally_limited_for = 0; + } + globally_ratelimited = false; + emit_in_queue_signal(); + } + } + } + } + close(notifier); +} + +void request_queue::out_loop() +{ + int c = sizeof(struct sockaddr_in); + fd_set readfds; + timeval ts; + char n; + struct sockaddr_in client; + SOCKET notifier = accept(out_queue_listen_sock, (struct sockaddr *)&client, (socklen_t*)&c); +#ifndef _WIN32 + close(out_queue_listen_sock); +#endif + while (!terminating) { + + /* select for one second, waiting for new data */ + FD_ZERO(&readfds); + FD_SET(notifier, &readfds); + ts.tv_sec = 1; + ts.tv_usec = 0; + int r = select(FD_SETSIZE, &readfds, 0, 0, &ts); + time_t now = time(nullptr); + + if (r > 0 && FD_ISSET(notifier, &readfds)) { + if (recv(notifier, &n, 1, 0) > 0) { + + /* A request has been completed! */ + std::pair queue_head = {}; + { + std::lock_guard lock(out_mutex); + if (responses_out.size()) { + queue_head = responses_out.front(); + responses_out.pop(); + } + } + + if (queue_head.first && queue_head.second) { + queue_head.second->complete(*queue_head.first); + } + + /* Queue deletions for 60 seconds from now */ + responses_to_delete.insert(std::make_pair(now + 60, queue_head)); + } + } + + /* Check for deletable items every second regardless of select status */ + while (responses_to_delete.size() && now >= responses_to_delete.begin()->first) { + delete responses_to_delete.begin()->second.first; + delete responses_to_delete.begin()->second.second; + responses_to_delete.erase(responses_to_delete.begin()); + } + } + shutdown(notifier, 2); + #ifdef _WIN32 + if (notifier >= 0 && notifier < FD_SETSIZE) { + closesocket(notifier); + } + #else + ::close(notifier); + #endif +} + + +/* These only need to send a byte to notify the other end of something to do. any byte will do. + */ +void request_queue::emit_in_queue_signal() +{ + send(in_queue_connect_sock, "X", 1, 0); +} + +void request_queue::emit_out_queue_signal() +{ + send(out_queue_connect_sock, "X", 1, 0); +} + +/* Post a http_request into the queue */ +void request_queue::post_request(http_request* req) +{ + std::lock_guard lock(in_mutex); + requests_in[req->endpoint].push_back(req); + emit_in_queue_signal(); +} + +std::string url_encode(const std::string &value) { + std::ostringstream escaped; + escaped.fill('0'); + escaped << std::hex; + + for (std::string::const_iterator i = value.begin(), n = value.end(); i != n; ++i) { + std::string::value_type c = (*i); + + // Keep alphanumeric and other accepted characters intact + if (isalnum((unsigned char)c) || c == '-' || c == '_' || c == '.' || c == '~') { + escaped << c; + continue; + } + + // Any other characters are percent-encoded + escaped << std::uppercase; + escaped << '%' << std::setw(2) << int((unsigned char) c); + escaped << std::nouppercase; + } + + return escaped.str(); +} + + +}; + diff --git a/vendor/DPP/src/dpp/role.cpp b/vendor/DPP/src/dpp/role.cpp new file mode 100644 index 00000000..71def202 --- /dev/null +++ b/vendor/DPP/src/dpp/role.cpp @@ -0,0 +1,238 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { + +role::role() : + managed(), + guild_id(0), + colour(0), + position(0), + permissions(0), + flags(0), + integration_id(0), + bot_id(0) +{ +} + +role::~role() +{ +} + +role& role::fill_from_json(snowflake _guild_id, nlohmann::json* j) +{ + this->guild_id = _guild_id; + this->name = StringNotNull(j, "name"); + this->id = SnowflakeNotNull(j, "id"); + this->colour = Int32NotNull(j, "color"); + this->position = Int8NotNull(j, "position"); + this->permissions = SnowflakeNotNull(j, "permissions"); + this->flags |= BoolNotNull(j, "hoist") ? dpp::r_hoist : 0; + this->flags |= BoolNotNull(j, "managed") ? dpp::r_managed : 0; + this->flags |= BoolNotNull(j, "mentionable") ? dpp::r_mentionable : 0; + if (j->find("tags") != j->end()) { + auto t = (*j)["tags"]; + this->flags |= BoolNotNull(&t, "premium_subscriber") ? dpp::r_premium_subscriber : 0; + this->bot_id = SnowflakeNotNull(&t, "bot_id"); + this->integration_id = SnowflakeNotNull(&t, "integration_id"); + } + return *this; +} + +std::string role::build_json(bool with_id) const { + json j; + + if (with_id) { + j["id"] = std::to_string(id); + } + if (colour) { + j["color"] = colour; + } + j["position"] = position; + j["permissions"] = permissions; + j["hoist"] = is_hoisted(); + j["mentionable"] = is_mentionable(); + + return j.dump(); +} + +bool role::is_hoisted() const { + return this->flags & dpp::r_hoist; +} + +bool role::is_mentionable() const { + return this->flags & dpp::r_mentionable; +} + +bool role::is_managed() const { + return this->flags & dpp::r_managed; +} + +bool role::has_create_instant_invite() const { + return ((this->permissions & p_administrator) | (this->permissions & p_create_instant_invite)); +} + +bool role::has_kick_members() const { + return ((this->permissions & p_administrator) | (this->permissions & p_kick_members)); +} + +bool role::has_ban_members() const { + return ((this->permissions & p_administrator) | (this->permissions & p_ban_members)); +} + +bool role::has_administrator() const { + return (this->permissions & p_administrator); +} + +bool role::has_manage_channels() const { + return ((this->permissions & p_administrator) | (this->permissions & p_manage_channels)); +} + +bool role::has_manage_guild() const { + return ((this->permissions & p_administrator) | (this->permissions & p_manage_guild)); +} + +bool role::has_add_reactions() const { + return ((this->permissions & p_administrator) | (this->permissions & p_add_reactions)); +} + +bool role::has_view_audit_log() const { + return ((this->permissions & p_administrator) | (this->permissions & p_view_audit_log)); +} + +bool role::has_priority_speaker() const { + return ((this->permissions & p_administrator) | (this->permissions & p_priority_speaker)); +} + +bool role::has_stream() const { + return ((this->permissions & p_administrator) | (this->permissions & p_stream)); +} + +bool role::has_view_channel() const { + return ((this->permissions & p_administrator) | (this->permissions & p_view_channel)); +} + +bool role::has_send_messages() const { + return ((this->permissions & p_administrator) | (this->permissions & p_send_messages)); +} + +bool role::has_send_tts_messages() const { + return ((this->permissions & p_administrator) | (this->permissions & p_send_tts_messages)); +} + +bool role::has_manage_messages() const { + return ((this->permissions & p_administrator) | (this->permissions & p_manage_messages)); +} + +bool role::has_embed_links() const { + return ((this->permissions & p_administrator) | (this->permissions & p_embed_links)); +} + +bool role::has_attach_files() const { + return ((this->permissions & p_administrator) | (this->permissions & p_attach_files)); +} + +bool role::has_read_message_history() const { + return ((this->permissions & p_administrator) | (this->permissions & p_read_message_history)); +} + +bool role::has_mention_everyone() const { + return ((this->permissions & p_administrator) | (this->permissions & p_mention_everyone)); +} + +bool role::has_use_external_emojis() const { + return ((this->permissions & p_administrator) | (this->permissions & p_use_external_emojis)); +} + +bool role::has_view_guild_insights() const { + return ((this->permissions & p_administrator) | (this->permissions & p_view_guild_insights)); +} + +bool role::has_connect() const { + return ((this->permissions & p_administrator) | (this->permissions & p_connect)); +} + +bool role::has_speak() const { + return ((this->permissions & p_administrator) | (this->permissions & p_speak)); +} + +bool role::has_mute_members() const { + return ((this->permissions & p_administrator) | (this->permissions & p_mute_members)); +} + +bool role::has_deafen_members() const { + return ((this->permissions & p_administrator) | (this->permissions & p_deafen_members)); +} + +bool role::has_move_members() const { + return ((this->permissions & p_administrator) | (this->permissions & p_move_members)); +} + +bool role::has_use_vad() const { + return ((this->permissions & p_administrator) | (this->permissions & p_use_vad)); +} + +bool role::has_change_nickname() const { + return ((this->permissions & p_administrator) | (this->permissions & p_change_nickname)); +} + +bool role::has_manage_nicknames() const { + return ((this->permissions & p_administrator) | (this->permissions & p_manage_nicknames)); +} + +bool role::has_manage_roles() const { + return ((this->permissions & p_administrator) | (this->permissions & p_manage_roles)); +} + +bool role::has_manage_webhooks() const { + return ((this->permissions & p_administrator) | (this->permissions & p_manage_webhooks)); +} + +bool role::has_manage_emojis() const { + return ((this->permissions & p_administrator) | (this->permissions & p_manage_emojis)); +} + +bool role::has_use_slash_commands() const { + return ((this->permissions & p_administrator) | (this->permissions & p_use_slash_commands)); +} + +bool role::has_request_to_speak() const { + return ((this->permissions & p_administrator) | (this->permissions & p_request_to_speak)); +} + +bool role::has_manage_threads() const { + return ((this->permissions & p_administrator) | (this->permissions & p_manage_threads)); +} + +bool role::has_use_public_threads() const { + return ((this->permissions & p_administrator) | (this->permissions & p_use_public_threads)); +} + +bool role::has_use_private_threads() const { + return ((this->permissions & p_administrator) | (this->permissions & p_use_private_threads)); +} +}; diff --git a/vendor/DPP/src/dpp/slashcommand.cpp b/vendor/DPP/src/dpp/slashcommand.cpp new file mode 100644 index 00000000..c63f2f29 --- /dev/null +++ b/vendor/DPP/src/dpp/slashcommand.cpp @@ -0,0 +1,332 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include + +namespace dpp { + +using json = nlohmann::json; + +slashcommand::slashcommand() : managed(), default_permission(true), type(ctxm_none) { +} + +slashcommand::~slashcommand() { +} + +slashcommand& slashcommand::fill_from_json(nlohmann::json* j) { + id = SnowflakeNotNull(j, "id"); + name = StringNotNull(j, "name"); + description = StringNotNull(j, "description"); + return *this; +} + +void to_json(json& j, const command_option_choice& choice) { + j["name"] = choice.name; + if (std::holds_alternative(choice.value)) { + j["value"] = std::get(choice.value); + } else if (std::holds_alternative(choice.value)) { + j["value"] = std::get(choice.value); + } else if (std::holds_alternative(choice.value)) { + j["value"] = std::to_string(std::get(choice.value)); + } else { + j["value"] = std::get(choice.value); + } +} + +void to_json(json& j, const command_option& opt) { + j["name"] = opt.name; + j["description"] = opt.description; + j["type"] = opt.type; + j["required"] = opt.required; + + if (opt.options.size()) { + j["options"] = json(); + + for (const auto& opt : opt.options) { + json jopt = opt; + j["options"].push_back(jopt); + } + } + + if (opt.choices.size()) { + j["choices"] = json(); + + for (const auto& choice : opt.choices) { + json jchoice = choice; + j["choices"].push_back(jchoice); + } + } +} + +void to_json(nlohmann::json& j, const command_permission& cp) { + j["id"] = std::to_string(cp.id); + j["type"] = cp.type; + j["permission"] = cp.permission; +} + +void to_json(nlohmann::json& j, const guild_command_permissions& gcp) { + j["id"] = std::to_string(gcp.id); + j["application_id"] = std::to_string(gcp.application_id); + j["guild_id"] = std::to_string(gcp.guild_id); + j["permissions"] = gcp.permissions; +} + +void to_json(json& j, const slashcommand& p) { + j["name"] = p.name; + + if (p.type != ctxm_user && p.type != ctxm_message) { + j["description"] = p.description; + } + + /* Only send this if set to something other than ctxm_none */ + if (p.type != ctxm_none) { + j["type"] = p.type; + } + + if (p.type != ctxm_user && p.type != ctxm_message) { + if (p.options.size()) { + j["options"] = json(); + + for (const auto& opt : p.options) { + json jopt = opt; + j["options"].push_back(jopt); + } + } + } + + if(p.permissions.size()) { + j["permissions"] = json(); + + for(const auto& perm : p.permissions) { + json jperm = perm; + j["permissions"].push_back(jperm); + } + } + + j["default_permission"] = p.default_permission; +} + +std::string slashcommand::build_json(bool with_id) const { + json j = *this; + + if (with_id) { + j["id"] = std::to_string(id); + } + + return j.dump(); +} + +slashcommand& slashcommand::set_type(slashcommand_contextmenu_type t) { + type = t; + return *this; +} + +slashcommand& slashcommand::set_name(const std::string &n) { + name = n; + return *this; +} + +slashcommand& slashcommand::set_description(const std::string &d) { + description = d; + return *this; +} + +slashcommand& slashcommand::set_application_id(snowflake i) { + application_id = i; + return *this; +} + +slashcommand& slashcommand::add_permission(const command_permission& p) { + this->permissions.push_back(p); + return *this; +} + +slashcommand& slashcommand::disable_default_permissions() { + this->default_permission = false; + return *this; +} + +command_option_choice::command_option_choice(const std::string &n, command_value v) : name(n), value(v) +{ +} + +command_option::command_option(command_option_type t, const std::string &n, const std::string &d, bool r) : + type(t), name(n), description(d), required(r) +{ +} + +command_option& command_option::add_choice(const command_option_choice &o) +{ + choices.push_back(o); + return *this; +} + +command_option& command_option::add_option(const command_option &o) +{ + options.push_back(o); + return *this; +} + +slashcommand& slashcommand::add_option(const command_option &o) +{ + options.push_back(o); + return *this; +} + +interaction& interaction::fill_from_json(nlohmann::json* j) { + j->get_to(*this); + return *this; +} + +std::string interaction::build_json(bool with_id) const { + return ""; +} + +void from_json(const nlohmann::json& j, command_data_option& cdo) { + cdo.name = StringNotNull(&j, "name"); + cdo.type = (command_option_type)Int8NotNull(&j, "type"); + + if (j.contains("options") && !j.at("options").is_null()) { + j.at("options").get_to(cdo.options); + } + + /* If there's a target ID, define it */ + if (j.contains("target_id") && !j.at("target_id").is_null()) { + cdo.target_id = (dpp::snowflake)SnowflakeNotNull(&j, "target_id"); + } + + if (j.contains("value") && !j.at("value").is_null()) { + switch (cdo.type) { + case co_boolean: + cdo.value = j.at("value").get(); + break; + case co_channel: + case co_role: + case co_user: + cdo.value = SnowflakeNotNull(&j, "value"); + break; + case co_integer: + cdo.value = j.at("value").get(); + break; + case co_string: + cdo.value = j.at("value").get(); + break; + case co_sub_command: + case co_sub_command_group: + /* Silences warning on clang, handled elsewhere */ + break; + } + } +} + +void from_json(const nlohmann::json& j, command_interaction& ci) { + ci.id = SnowflakeNotNull(&j, "id"); + ci.name = StringNotNull(&j, "name"); + + if (j.contains("options") && !j.at("options").is_null()) { + j.at("options").get_to(ci.options); + } +} + +void from_json(const nlohmann::json& j, component_interaction& bi) { + bi.component_type = Int8NotNull(&j, "component_type"); + bi.custom_id = StringNotNull(&j, "custom_id"); + if (bi.component_type == cotype_select && j.find("values") != j.end()) { + /* Get values */ + for (auto& entry : j["values"]) { + bi.values.push_back(entry.get()); + } + } +} + +void from_json(const nlohmann::json& j, interaction& i) { + i.id = SnowflakeNotNull(&j, "id"); + i.application_id = SnowflakeNotNull(&j, "application_id"); + i.channel_id = SnowflakeNotNull(&j, "channel_id"); + i.guild_id = SnowflakeNotNull(&j, "guild_id"); + + if (j.find("message") != j.end()) { + const json& m = j["message"]; + SetSnowflakeNotNull(&m, "id", i.message_id); + } + + + i.type = Int8NotNull(&j, "type"); + i.token = StringNotNull(&j, "token"); + i.version = Int8NotNull(&j, "version"); + + if (j.contains("member") && !j.at("member").is_null()) { + j.at("member").get_to(i.member); + if (j.at("member").contains("user") && !j.at("member").at("user").is_null()) { + j.at("member").at("user").get_to(i.usr); + } + } + + if (j.contains("data") && !j.at("data").is_null()) { + if (i.type == it_application_command) { + command_interaction ci; + j.at("data").get_to(ci); + i.data = ci; + } else if (i.type == it_component_button) { + component_interaction bi; + j.at("data").get_to(bi); + i.data = bi; + } + } +} + +interaction_response::interaction_response() { + msg = new message(); +} + +interaction_response::~interaction_response() { + delete msg; +} + +interaction_response::interaction_response(interaction_response_type t, const message& m) : interaction_response() { + type = t; + *msg = m; +} + +interaction_response& interaction_response::fill_from_json(nlohmann::json* j) { + type = (interaction_response_type)Int8NotNull(j, "type"); + if (j->find("data") != j->end()) { + msg->fill_from_json(&((*j)["data"])); + } + return *this; +} + +std::string interaction_response::build_json() const { + json j; + json msg_json = json::parse(msg->build_json(false, true)); + j["type"] = this->type; + auto cid = msg_json.find("channel_id"); + if (cid != msg_json.end()) { + msg_json.erase(cid); + } + j["data"] = msg_json; + return j.dump(); +} + +}; diff --git a/vendor/DPP/src/dpp/sslclient.cpp b/vendor/DPP/src/dpp/sslclient.cpp new file mode 100644 index 00000000..416ad035 --- /dev/null +++ b/vendor/DPP/src/dpp/sslclient.cpp @@ -0,0 +1,408 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include + +#ifdef _WIN32 +#include +#include +#include +#pragma comment(lib,"ws2_32") +#else +#include +#include +#include +#include +#include +#include +#endif + +#ifdef OPENSSL_SYS_WIN32 +#undef X509_NAME +#undef X509_EXTENSIONS +#undef X509_CERT_PAIR +#undef PKCS7_ISSUER_AND_SERIAL +#undef OCSP_REQUEST +#undef OCSP_RESPONSE +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace dpp { + +class opensslcontext { +public: + /** OpenSSL session */ + SSL* ssl; + + /** OpenSSL context */ + SSL_CTX* ctx; +}; + +/* You'd think that we would get better performance with a bigger buffer, but SSL frames are 16k each. + * SSL_read in non-blocking mode will only read 16k at a time. There's no point in a bigger buffer as + * it'd go unused. + */ +#define BUFSIZZ 1024 * 16 +const int ERROR_STATUS = -1; + +ssl_client::ssl_client(const std::string &_hostname, const std::string &_port) : last_tick(time(NULL)), hostname(_hostname), port(_port), bytes_in(0), bytes_out(0) +{ +#ifndef WIN32 + signal(SIGALRM, SIG_IGN); + signal(SIGHUP, SIG_IGN); + signal(SIGPIPE, SIG_IGN); + signal(SIGCHLD, SIG_IGN); + signal(SIGXFSZ, SIG_IGN); +#endif + ssl = new opensslcontext(); + Connect(); +} + +/* SSL Client constructor throws std::runtime_error if it can't connect to the host */ +void ssl_client::Connect() +{ + /* Initial connection is done in blocking mode. There is a timeout on it. */ + nonblocking = false; + const SSL_METHOD *method = TLS_client_method(); /* Create new client-method instance */ + + /* Create SSL context */ + ssl->ctx = SSL_CTX_new(method); + if (ssl->ctx == nullptr) + throw dpp::exception("Failed to create SSL client context!"); + + /* Create SSL session */ + ssl->ssl = SSL_new(ssl->ctx); + if (ssl->ssl == nullptr) + throw dpp::exception("SSL_new failed!"); + + /* Resolve hostname to IP */ + struct hostent *host; + if ((host = gethostbyname(hostname.c_str())) == nullptr) + throw dpp::exception(fmt::format("Couldn't resolve hostname '{}'", hostname)); + + struct addrinfo hints = {0}, *addrs; + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_STREAM; + hints.ai_protocol = IPPROTO_TCP; + + int status = getaddrinfo(hostname.c_str(), port.c_str(), &hints, &addrs); + if (status != 0) + throw dpp::exception(fmt::format("getaddrinfo (host={}, port={}): ", hostname, port, gai_strerror(status))); + + /* Attempt each address in turn, if there are multiple IP addresses on the hostname */ + int err; + for (struct addrinfo *addr = addrs; addr != nullptr; addr = addr->ai_next) { + sfd = socket(addrs->ai_family, addrs->ai_socktype, addrs->ai_protocol); + if (sfd == ERROR_STATUS) { + err = errno; + continue; + } else if (connect(sfd, addr->ai_addr, addr->ai_addrlen) == 0) { + break; + } + err = errno; + shutdown(sfd, 2); + #ifdef _WIN32 + if (sfd >= 0 && sfd < FD_SETSIZE) { + closesocket(sfd); + } + #else + ::close(sfd); + #endif + sfd = ERROR_STATUS; + } + freeaddrinfo(addrs); + + /* Check if none of the IPs yielded a valid connection */ + if (sfd == ERROR_STATUS) + throw dpp::exception(strerror(err)); + + /* We're good to go - hand the fd over to openssl */ + SSL_set_fd(ssl->ssl, sfd); + + status = SSL_connect(ssl->ssl); + if (status != 1) { + throw dpp::exception("SSL_connect error"); + } + + this->cipher = SSL_get_cipher(ssl->ssl); +} + +void ssl_client::write(const std::string &data) +{ + /* If we are in nonblocking mode, append to the buffer, + * otherwise just use SSL_write directly. The only time we + * use SSL_write directly is during connection before the + * ReadLoop is called, which allows for guaranteed simple + * lock-step delivery e.g. for HTTP header negotiation + */ + if (nonblocking) { + obuffer += data; + } else { + SSL_write(ssl->ssl, data.data(), data.length()); + } +} + +void ssl_client::one_second_timer() +{ +} + +std::string ssl_client::get_cipher() { + return cipher; +} + +void ssl_client::log(dpp::loglevel severity, const std::string &msg) const +{ +} + +void ssl_client::read_loop() +{ + /* The read loop is non-blocking using select(). This method + * cannot read while it is waiting for write, or write while it is + * waiting for read. This is a limitation of the openssl libraries, + * as SSL is sent and received in low level ~16k frames which must + * be synchronised and ordered correctly. Attempting to send while + * we need another frame or receive while we are due to send a frame + * would cause the protocol to break. + */ + int width; + int r = 0; + size_t ClientToServerLength = 0, ClientToServerOffset = 0; + bool read_blocked_on_write = false, write_blocked_on_read = false,read_blocked = false; + fd_set readfds, writefds, efds; + char ClientToServerBuffer[BUFSIZZ], ServerToClientBuffer[BUFSIZZ]; + + /* Make the socket nonblocking */ +#ifdef _WIN32 + u_long mode = 1; + int result = ioctlsocket(sfd, FIONBIO, &mode); + if (result != NO_ERROR) + throw dpp::exception("Can't switch socket to non-blocking mode!"); +#else + int ofcmode; + ofcmode = fcntl(sfd, F_GETFL, 0); + ofcmode |= O_NDELAY; + if (fcntl(sfd, F_SETFL, ofcmode)) { + throw dpp::exception("Can't switch socket to non-blocking mode!"); + } +#endif + nonblocking = true; + width = sfd + 1; + + try { + /* Loop until there is a socket error */ + while(true) { + + if (last_tick != time(NULL)) { + this->one_second_timer(); + last_tick = time(NULL); + } + + FD_ZERO(&readfds); + FD_ZERO(&writefds); + FD_ZERO(&efds); + + FD_SET(sfd,&readfds); + FD_SET(sfd,&efds); + if (custom_readable_fd && custom_readable_fd() >= 0) { + int cfd = custom_readable_fd(); + FD_SET(cfd, &readfds); + FD_SET(cfd, &efds); + } + if (custom_writeable_fd && custom_writeable_fd() >= 0) { + int cfd = custom_writeable_fd(); + FD_SET(cfd, &writefds); + } + + /* If we're waiting for a read on the socket don't try to write to the server */ + if (ClientToServerLength || obuffer.length() || read_blocked_on_write) { + FD_SET(sfd,&writefds); + } + + timeval ts; + ts.tv_sec = 0; + ts.tv_usec = 50000; + r = select(FD_SETSIZE, &readfds, &writefds, &efds, &ts); + if (r == 0) + continue; + + if (custom_writeable_fd && FD_ISSET(custom_writeable_fd(), &writefds)) { + custom_writeable_ready(); + } + if (custom_readable_fd && FD_ISSET(custom_readable_fd(), &readfds)) { + custom_readable_ready(); + } + if (custom_readable_fd && FD_ISSET(custom_readable_fd(), &efds)) { + } + + if (FD_ISSET(sfd, &efds)) { + this->log(dpp::ll_error, fmt::format("Error on SSL connection: {}", strerror(errno))); + return; + } + + /* Now check if there's data to read */ + if((FD_ISSET(sfd,&readfds) && !write_blocked_on_read) || (read_blocked_on_write && FD_ISSET(sfd,&writefds))) { + do { + read_blocked_on_write = false; + read_blocked = false; + + r = SSL_read(ssl->ssl,ServerToClientBuffer,BUFSIZZ); + + int e = SSL_get_error(ssl->ssl,r); + + switch (e) { + case SSL_ERROR_NONE: + /* Data received, add it to the buffer */ + buffer.append(ServerToClientBuffer, r); + this->handle_buffer(buffer); + bytes_in += r; + break; + case SSL_ERROR_ZERO_RETURN: + /* End of data */ + SSL_shutdown(ssl->ssl); + return; + break; + case SSL_ERROR_WANT_READ: + read_blocked = true; + break; + + /* We get a WANT_WRITE if we're trying to rehandshake and we block on a write during that rehandshake. + * We need to wait on the socket to be writeable but reinitiate the read when it is + */ + case SSL_ERROR_WANT_WRITE: + read_blocked_on_write = true; + break; + default: + return; + break; + } + + /* We need a check for read_blocked here because SSL_pending() doesn't work properly during the + * handshake. This check prevents a busy-wait loop around SSL_read() + */ + } while (SSL_pending(ssl->ssl) && !read_blocked); + } + + /* Check for input on the sendq */ + if (obuffer.length() && ClientToServerLength == 0) { + memcpy(&ClientToServerBuffer, obuffer.data(), obuffer.length() > BUFSIZZ ? BUFSIZZ : obuffer.length()); + ClientToServerLength = obuffer.length() > BUFSIZZ ? BUFSIZZ : obuffer.length(); + obuffer = obuffer.substr(ClientToServerLength, obuffer.length()); + ClientToServerOffset = 0; + } + + /* If the socket is writeable... */ + if ((FD_ISSET(sfd,&writefds) && ClientToServerLength) || (write_blocked_on_read && FD_ISSET(sfd,&readfds))) { + write_blocked_on_read = false; + /* Try to write */ + r = SSL_write(ssl->ssl, ClientToServerBuffer + ClientToServerOffset, ClientToServerLength); + + switch(SSL_get_error(ssl->ssl,r)) { + /* We wrote something */ + case SSL_ERROR_NONE: + ClientToServerLength -= r; + ClientToServerOffset += r; + bytes_out += r; + break; + + /* We would have blocked */ + case SSL_ERROR_WANT_WRITE: + break; + + /* We get a WANT_READ if we're trying to rehandshake and we block onwrite during the current connection. + * We need to wait on the socket to be readable but reinitiate our write when it is + */ + case SSL_ERROR_WANT_READ: + write_blocked_on_read = true; + break; + + /* Some other error */ + default: + return; + break; + } + } + } + } + catch (const std::exception &e) { + log(ll_warning, fmt::format("Read loop ended: {}", e.what())); + } +} + +uint64_t ssl_client::get_bytes_out() +{ + return bytes_out; +} + +uint64_t ssl_client::get_bytes_in() +{ + return bytes_in; +} + +bool ssl_client::handle_buffer(std::string &buffer) +{ + return true; +} + +void ssl_client::close() +{ + if (ssl->ssl) { + SSL_free(ssl->ssl); + ssl->ssl = nullptr; + } + shutdown(sfd, 2); + #ifdef _WIN32 + if (sfd >= 0 && sfd < FD_SETSIZE) { + closesocket(sfd); + } + #else + ::close(sfd); + #endif + if (ssl->ctx) { + SSL_CTX_free(ssl->ctx); + ssl->ctx = nullptr; + } + sfd = -1; + obuffer.clear(); + buffer.clear(); +} + +ssl_client::~ssl_client() +{ + this->close(); + delete ssl; +} + +}; \ No newline at end of file diff --git a/vendor/DPP/src/dpp/user.cpp b/vendor/DPP/src/dpp/user.cpp new file mode 100644 index 00000000..74c70bf6 --- /dev/null +++ b/vendor/DPP/src/dpp/user.cpp @@ -0,0 +1,183 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include + +using json = nlohmann::json; + +/* A mapping of discord's flag values to our bitmap (theyre different bit positions to fit other stuff in) */ +std::map usermap = { + { 1 << 0, dpp::u_discord_employee }, + { 1 << 1, dpp::u_partnered_owner }, + { 1 << 2, dpp::u_hypesquad_events }, + { 1 << 3, dpp::u_bughunter_1 }, + { 1 << 6, dpp::u_house_bravery }, + { 1 << 7, dpp::u_house_brilliance }, + { 1 << 8, dpp::u_house_balanace }, + { 1 << 9, dpp::u_early_supporter }, + { 1 << 10, dpp::u_team_user }, + { 1 << 14, dpp::u_bughunter_2 }, + { 1 << 16, dpp::u_verified_bot }, + { 1 << 17, dpp::u_verified_bot_dev }, + { 1 << 18, dpp::u_certified_moderator } +}; + +namespace dpp { + +user::user() : + managed(), + discriminator(0), + flags(0), + refcount(1) +{ +} + +user::~user() +{ +} + +std::string user::get_avatar_url() const { + /* XXX: Discord were supposed to change their CDN over to discord.com, they havent. + * At some point in the future this URL *will* change! + */ + return fmt::format("https://cdn.discordapp.com/avatars/{}/{}{}.{}", + this->id, + (has_animated_icon() ? "a_" : ""), + this->avatar.to_string(), + (has_animated_icon() ? "gif" : "png") + ); +} + +bool user::is_bot() const { + return this->flags & u_bot; +} + +bool user::is_system() const { + return this->flags & u_system; +} + +bool user::is_mfa_enabled() const { + return this->flags & u_mfa_enabled; +} + +bool user::is_verified() const { + return this->flags & u_verified; +} + +bool user::has_nitro_full() const { + return this->flags & u_nitro_full; +} + +bool user::has_nitro_classic() const { + return this->flags & u_nitro_classic; +} + +bool user::is_discord_employee() const { + return this->flags & u_discord_employee; +} + +bool user::is_partnered_owner() const { + return this->flags & u_partnered_owner; +} + +bool user::has_hypesquad_events() const { + return this->flags & u_hypesquad_events; +} + +bool user::is_bughunter_1() const { + return this->flags & u_bughunter_1; +} + +bool user::is_house_bravery() const { + return this->flags & u_house_bravery; +} + +bool user::is_house_brilliance() const { + return this->flags & u_house_brilliance; +} + +bool user::is_house_balanace() const { + return this->flags & u_house_balanace; +} + +bool user::is_early_supporter() const { + return this->flags & u_early_supporter; +} + +bool user::is_team_user() const { + return this->flags & u_team_user; +} + +bool user::is_bughunter_2() const { + return this->flags & u_bughunter_2; +} + +bool user::is_verified_bot() const { + return this->flags & u_verified_bot; +} + +bool user::is_verified_bot_dev() const { + return this->flags & u_verified_bot_dev; +} + +bool user::is_certified_moderator() const { + return this->flags & u_certified_moderator; +} + +bool user::has_animated_icon() const { + return this->flags & u_animated_icon; +} + +user& user::fill_from_json(json* j) { + j->get_to(*this); + return *this; +} + +void from_json(const nlohmann::json& j, user& u) { + u.id = SnowflakeNotNull(&j, "id"); + u.username = StringNotNull(&j, "username"); + + std::string av = StringNotNull(&j, "avatar"); + if (av.length() > 2 && av.substr(0, 2) == "a_") { + av = av.substr(2, av.length()); + u.flags |= u_animated_icon; + } + u.avatar = av; + + u.discriminator = SnowflakeNotNull(&j, "discriminator"); + + u.flags |= BoolNotNull(&j, "bot") ? dpp::u_bot : 0; + u.flags |= BoolNotNull(&j, "system") ? dpp::u_system : 0; + u.flags |= BoolNotNull(&j, "mfa_enabled") ? dpp::u_mfa_enabled : 0; + u.flags |= BoolNotNull(&j, "verified") ? dpp::u_verified : 0; + u.flags |= Int8NotNull(&j, "premium_type") == 1 ? dpp::u_nitro_classic : 0; + u.flags |= Int8NotNull(&j, "premium_type") == 2 ? dpp::u_nitro_full : 0; + uint32_t flags = Int32NotNull(&j, "flags"); + for (auto & flag : usermap) { + if (flags & flag.first) { + u.flags |= flag.second; + } + } +} + +}; diff --git a/vendor/DPP/src/dpp/utility.cpp b/vendor/DPP/src/dpp/utility.cpp new file mode 100644 index 00000000..dc49a123 --- /dev/null +++ b/vendor/DPP/src/dpp/utility.cpp @@ -0,0 +1,274 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace std::literals; + +namespace dpp { + + namespace utility { + + double time_f() + { + using namespace std::chrono; + auto tp = system_clock::now() + 0ns; + return tp.time_since_epoch().count() / 1000000000.0; + } + + bool has_voice() { +#if HAVE_VOICE + return true; +#else + return false; +#endif + } + + std::string current_date_time() { +#ifdef _WIN32 + std::time_t curr_time = time(nullptr); + return std::ctime(&curr_time); +#else + auto t = std::time(nullptr); + struct tm timedata; + localtime_r(&t, &timedata); + std::stringstream s; + s << std::put_time(&timedata, "%Y-%m-%d %H:%M:%S"); + return s.str(); +#endif + } + + std::string loglevel(dpp::loglevel in) { + switch (in) { + case dpp::ll_trace: return "TRACE"; + case dpp::ll_debug: return "DEBUG"; + case dpp::ll_info: return "INFO"; + case dpp::ll_warning: return "WARN"; + case dpp::ll_error: return "ERROR"; + case dpp::ll_critical: return "CRIT"; + default: return "???"; + } + } + + uptime::uptime() : days(0), hours(0), mins(0), secs(0) { + } + + uptime::uptime(time_t diff) : uptime() { + days = (uint16_t)(diff / (3600 * 24)); + hours = (uint8_t)(diff % (3600 * 24) / 3600); + mins = (uint8_t)(diff % 3600 / 60); + secs = (uint8_t)(diff % 60); + } + + std::string uptime::to_string() { + if (hours == 0 && days == 0) { + return fmt::format("{:02d}:{:02d}", mins, secs); + } else { + return fmt::format("{}{:02d}:{:02d}:{:02d}", (days ? fmt::format("{} day{}, ", days, (days > 1 ? "s" : "")) : ""), hours, mins, secs); + } + } + + uint64_t uptime::to_secs() { + return secs + (mins * 60) + (hours * 60 * 60) + (days * 60 * 60 * 24); + } + + uint64_t uptime::to_msecs() { + return to_secs() * 1000; + } + + iconhash::iconhash() : first(0), second(0) { + } + + void iconhash::set(const std::string &hash) { + if (hash.empty()) { // Clear values if empty hash + first = second = 0; + return; + } + if (hash.length() != 32) + throw std::length_error("iconhash must be exactly 32 characters in length"); + this->first = from_string(hash.substr(0, 16), std::hex); + this->second = from_string(hash.substr(16, 16), std::hex); + } + + iconhash::iconhash(const std::string &hash) { + set(hash); + } + + iconhash& iconhash::operator=(const std::string &assignment) { + set(assignment); + return *this; + } + + std::string iconhash::to_string() const { + if (first == 0 && second == 0) + return ""; + else + return fmt::format("{:016x}{:016x}", this->first, this->second); + } + + void debug_dump(uint8_t* data, size_t length) { + size_t addr = (size_t)data; + size_t extra = addr % 16; + if (extra != 0) { + addr -= extra; + std::cout << fmt::format("[{:016X}] : ", addr); + } + for (size_t n = 0; n < extra; ++n) { + std::cout << "-- "; + } + for (uint8_t* ptr = data; ptr < data + length; ++ptr) { + if (((size_t)ptr % 16) == 0) { + std::cout << fmt::format("\n[{:016X}] : ", (size_t)ptr); + } + std::cout << fmt::format("{:02X} ", *ptr); + } + std::cout << "\n"; + } + + std::string bytes(uint64_t c) { + if (c > 1099511627776) { // 1TB + return fmt::format("{:.2f}T", (c / 1099511627776.0)); + } else if (c > 1073741824) { // 1GB + return fmt::format("{:.2f}G", (c / 1073741824.0)); + } else if (c > 1048576) { // 1MB + return fmt::format("{:.2f}M", (c / 1048576.0)); + } else if (c > 1024) { // 1KB + return fmt::format("{:.2f}K", (c / 1024.0)); + } else { // Bytes + return std::to_string(c); + } + } + + void exec(const std::string& cmd, std::vector parameters, cmd_result_t callback) { +#ifndef _WIN32 + auto t = std::thread([cmd, parameters, callback]() { + std::array buffer; + std::vector my_parameters = parameters; + std::string result; + std::stringstream cmd_and_parameters; + cmd_and_parameters << cmd; + for (auto & parameter : my_parameters) { + cmd_and_parameters << " " << std::quoted(parameter); + } + /* Capture stderr */ + cmd_and_parameters << " 2>&1"; + std::unique_ptr pipe(popen(cmd_and_parameters.str().c_str(), "r"), pclose); + if (!pipe) { + return ""; + } + while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) { + result += buffer.data(); + } + if (callback) { + callback(result); + } + return ""; + }); + t.detach(); +#endif + } + + size_t utf8len(const std::string &str) + { + size_t i = 0, iBefore = 0, count = 0; + const char* s = str.c_str(); + if (*s == 0) + return 0; + + while (s[i] > 0) { + ascii: + i++; + } + + count += i - iBefore; + + while (s[i]) { + if (s[i] > 0) { + iBefore = i; + goto ascii; + } else { + switch (0xF0 & s[i]) { + case 0xE0: + i += 3; + break; + case 0xF0: + i += 4; + break; + default: + i += 2; + break; + } + } + + count++; + } + + return count; + } + + std::string utf8substr(const std::string& str, std::string::size_type start, std::string::size_type leng) + { + if (leng == 0) { + return ""; + } + if (start == 0 && leng >= utf8len(str)) { + return str; + } + std::string::size_type i, ix, q, min = std::string::npos, max = std::string::npos; + for (q = 0, i = 0, ix = str.length(); i < ix; i++, q++) + { + if (q == start) + min = i; + if (q <= start + leng || leng == std::string::npos) + max = i; + + unsigned char c = (unsigned char)str[i]; + if (c < 0x80) + i += 0; + else if ((c & 0xE0) == 0xC0) + i += 1; + else if ((c & 0xF0) == 0xE0) + i += 2; + else if ((c & 0xF8) == 0xF0) + i += 3; + else + return ""; //invalid utf8 + } + if (q <= start + leng || leng == std::string::npos) + max = i; + if (min == std::string::npos || max == std::string::npos) + return ""; + + return str.substr(min, max); + } + }; + +}; diff --git a/vendor/DPP/src/dpp/voiceregion.cpp b/vendor/DPP/src/dpp/voiceregion.cpp new file mode 100644 index 00000000..19bdd352 --- /dev/null +++ b/vendor/DPP/src/dpp/voiceregion.cpp @@ -0,0 +1,80 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include + +namespace dpp { + +using json = nlohmann::json; + +voiceregion::voiceregion() : flags(0) +{ +} + +voiceregion::~voiceregion() { +} + +voiceregion& voiceregion::fill_from_json(nlohmann::json* j) { + id = StringNotNull(j, "id"); + name = StringNotNull(j, "id"); + if (BoolNotNull(j, "optimal")) + flags |= v_optimal; + if (BoolNotNull(j, "deprecated")) + flags |= v_deprecated; + if (BoolNotNull(j, "custom")) + flags |= v_custom; + if (BoolNotNull(j, "vip")) + flags |= v_vip; + return *this; +} + +std::string voiceregion::build_json() const { + return json({ + { "id", id }, + { "name", name }, + { "optimal", is_optimal() }, + { "deprecated", is_deprecated() }, + { "custom", is_custom() }, + { "vip", is_vip() } + }).dump(); +} + +bool voiceregion::is_optimal() const { + return flags & v_optimal; +} + +bool voiceregion::is_deprecated() const { + return flags & v_deprecated; +} + +bool voiceregion::is_custom() const { + return flags & v_custom; +} + +bool voiceregion::is_vip() const { + return flags & v_vip; +} + + +}; + diff --git a/vendor/DPP/src/dpp/voicestate.cpp b/vendor/DPP/src/dpp/voicestate.cpp new file mode 100644 index 00000000..ddb31593 --- /dev/null +++ b/vendor/DPP/src/dpp/voicestate.cpp @@ -0,0 +1,91 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { + +voicestate::voicestate() : shard(nullptr), guild_id(0), channel_id(0), user_id(0) +{ +} + +voicestate::~voicestate() { +} + +voicestate& voicestate::fill_from_json(nlohmann::json* j) { + guild_id = SnowflakeNotNull(j, "guild_id"); + channel_id = SnowflakeNotNull(j, "channel_id"); + user_id = SnowflakeNotNull(j, "user_id"); + session_id = StringNotNull(j, "session_id"); + flags = 0; + if (BoolNotNull(j, "deaf")) + flags |= vs_deaf; + if (BoolNotNull(j, "mute")) + flags |= vs_mute; + if (BoolNotNull(j, "self_mute")) + flags |= vs_self_mute; + if (BoolNotNull(j, "self_deaf")) + flags |= vs_self_deaf; + if (BoolNotNull(j, "self_stream")) + flags |= vs_self_stream; + if (BoolNotNull(j, "self_video")) + flags |= vs_self_video; + if (BoolNotNull(j, "supress")) + flags |= vs_supress; + return *this; +} + +bool voicestate::is_deaf() const { + return flags & vs_deaf; +} + +bool voicestate::is_mute() const { + return flags & vs_mute; +} + +bool voicestate::is_self_mute() const { + return flags & vs_self_mute; +} + +bool voicestate::is_self_deaf() const { + return flags & vs_self_deaf; +} + +bool voicestate::self_stream() const { + return flags & vs_self_stream; +} + +bool voicestate::self_video() const { + return flags & vs_self_video; +} + +bool voicestate::is_supressed() const { + return flags & vs_supress; +} + +std::string voicestate::build_json() const { + return json({}).dump(); +} + +}; diff --git a/vendor/DPP/src/dpp/webhook.cpp b/vendor/DPP/src/dpp/webhook.cpp new file mode 100644 index 00000000..8d8ae88c --- /dev/null +++ b/vendor/DPP/src/dpp/webhook.cpp @@ -0,0 +1,97 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include + +namespace dpp { + +using json = nlohmann::json; + +webhook::webhook() : managed(), type(w_incoming), guild_id(0), channel_id(0), user_id(0), application_id(0), image_data(nullptr) +{ +} + +webhook::~webhook() { + if (image_data) { + delete image_data; + } +} + +webhook& webhook::fill_from_json(nlohmann::json* j) { + id = SnowflakeNotNull(j, "id"); + type = Int8NotNull(j, "type"); + channel_id = SnowflakeNotNull(j, "channel_id"); + guild_id = SnowflakeNotNull(j, "guild_id"); + if (j->find("user") != j->end()) { + json & user = (*j)["user"]; + user_id = SnowflakeNotNull(&user, "id"); + } + name = StringNotNull(j, "name"); + avatar = StringNotNull(j, "name"); + token = StringNotNull(j, "token"); + application_id = SnowflakeNotNull(j, "application_id"); + + return *this; +} + +std::string webhook::build_json(bool with_id) const { + json j; + if (with_id) { + j["id"] = std::to_string(id); + } + j["name"] = name; + j["type"] = type; + if (channel_id) + j["channel_id"] = channel_id; + if (guild_id) + j["guild_id"] = guild_id; + if (!name.empty()) + j["name"] = name; + if (image_data) + j["avatar"] = *image_data; + if (application_id) + j["application_id"] = application_id; + return j.dump(); +} + +webhook& webhook::load_image(const std::string &image_blob, image_type type) { + static std::map mimetypes = { + { i_gif, "image/gif" }, + { i_jpg, "image/jpeg" }, + { i_png, "image/png" } + }; + if (image_blob.size() > MAX_EMOJI_SIZE) { + throw dpp::exception("Webhook icon file exceeds discord limit of 256 kilobytes"); + } + if (image_data) { + /* If there's already image data defined, free the old data, to prevent a memory leak */ + delete image_data; + } + image_data = new std::string("data:" + mimetypes[type] + ";base64," + base64_encode((unsigned char const*)image_blob.data(), image_blob.length())); + + return *this; +} + +}; + diff --git a/vendor/DPP/src/dpp/wsclient.cpp b/vendor/DPP/src/dpp/wsclient.cpp new file mode 100644 index 00000000..21d72ac1 --- /dev/null +++ b/vendor/DPP/src/dpp/wsclient.cpp @@ -0,0 +1,325 @@ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#include +#include +#include +#include +#include + +namespace dpp { + +const unsigned char WS_MASKBIT = (1 << 7); +const unsigned char WS_FINBIT = (1 << 7); +const unsigned char WS_PAYLOAD_LENGTH_MAGIC_LARGE = 126; +const unsigned char WS_PAYLOAD_LENGTH_MAGIC_HUGE = 127; +const size_t WS_MAX_PAYLOAD_LENGTH_SMALL = 125; +const size_t WS_MAX_PAYLOAD_LENGTH_LARGE = 65535; +const size_t MAXHEADERSIZE = sizeof(uint64_t) + 2; + +websocket_client::websocket_client(const std::string &hostname, const std::string &port, const std::string &urlpath) + : ssl_client(hostname, port), + state(HTTP_HEADERS), + key(fmt::format("{:16x}", time(nullptr))), + path(urlpath) +{ +} + +void websocket_client::Connect() +{ + state = HTTP_HEADERS; + /* Send headers synchronously */ + this->write( + fmt::format( + + "GET {} HTTP/1.1\r\n" + "Host: {}\r\n" + "pragma: no-cache\r\n" + "User-Agent: DPP/0.1\r\n" + "Upgrade: WebSocket\r\n" + "Connection: Upgrade\r\n" + "Sec-WebSocket-Key: {}\r\n" + "Sec-WebSocket-Version: 13\r\n\r\n", + + this->path, this->hostname, this->key + ) + ); +} + +websocket_client::~websocket_client() +{ +} + +bool websocket_client::HandleFrame(const std::string &buffer) +{ + /* This is a stub for classes that derive the websocket client */ + return true; +} + +size_t websocket_client::FillHeader(unsigned char* outbuf, size_t sendlength, ws_opcode opcode) +{ + size_t pos = 0; + outbuf[pos++] = WS_FINBIT | opcode; + + if (sendlength <= WS_MAX_PAYLOAD_LENGTH_SMALL) + { + outbuf[pos++] = sendlength; + } + else if (sendlength <= WS_MAX_PAYLOAD_LENGTH_LARGE) + { + outbuf[pos++] = WS_PAYLOAD_LENGTH_MAGIC_LARGE; + outbuf[pos++] = (sendlength >> 8) & 0xff; + outbuf[pos++] = sendlength & 0xff; + } + else + { + outbuf[pos++] = WS_PAYLOAD_LENGTH_MAGIC_HUGE; + const uint64_t len = sendlength; + for (int i = sizeof(uint64_t)-1; i >= 0; i--) + outbuf[pos++] = ((len >> i*8) & 0xff); + } + + /* Masking - We don't care about masking, but discord insists on it. We send a mask of 0x00000000 because + * any value XOR 0 is itself, meaning we dont have to waste time and effort on this crap. + */ + outbuf[1] |= WS_MASKBIT; + outbuf[pos++] = 0; + outbuf[pos++] = 0; + outbuf[pos++] = 0; + outbuf[pos++] = 0; + + return pos; +} + + +void websocket_client::write(const std::string &data) +{ + if (state == HTTP_HEADERS) { + /* Simple write */ + ssl_client::write(data); + } else { + unsigned char out[MAXHEADERSIZE]; + size_t s = this->FillHeader(out, data.length(), OP_TEXT); + std::string header((const char*)out, s); + ssl_client::write(header); + ssl_client::write(data); + } +} + +std::vector tokenize(std::string const &in, const char* sep = "\r\n") { + std::string::size_type b = 0; + std::vector result; + + while ((b = in.find_first_not_of(sep, b)) != std::string::npos) { + auto e = in.find(sep, b); + result.push_back(in.substr(b, e-b)); + b = e; + } + return result; +} + +bool websocket_client::handle_buffer(std::string &buffer) +{ + switch (state) { + case HTTP_HEADERS: + if (buffer.find("\r\n\r\n") != std::string::npos) { + /* Got all headers, proceed to new state */ + + /* Get headers string */ + std::string headers = buffer.substr(0, buffer.find("\r\n\r\n")); + + /* Modify buffer, remove headers section */ + buffer.erase(0, buffer.find("\r\n\r\n") + 4); + + /* Process headers into map */ + std::vector h = tokenize(headers); + if (h.size()) { + std::string status_line = h[0]; + h.erase(h.begin()); + /* HTTP/1.1 101 Switching Protocols */ + std::vector status = tokenize(status_line, " "); + if (status.size() >= 3 && status[1] == "101") { + for(auto &hd : h) { + std::string::size_type sep = hd.find(": "); + if (sep != std::string::npos) { + std::string key = hd.substr(0, sep); + std::string value = hd.substr(sep + 2, hd.length()); + HTTPHeaders[key] = value; + } + } + + state = CONNECTED; + } else { + return false; + } + } + } + break; + case CONNECTED: + /* Process packets until we can't */ + while (this->parseheader(buffer)); + break; + } + return true; +} + +ws_state websocket_client::GetState() +{ + return this->state; +} + +bool websocket_client::parseheader(std::string &data) +{ + if (data.size() < 4) { + /* Not enough data to form a frame yet */ + return false; + } else { + unsigned char opcode = data[0]; + switch (opcode & ~WS_FINBIT) + { + case OP_CONTINUATION: + case OP_TEXT: + case OP_BINARY: + case OP_PING: + case OP_PONG: + { + std::string payload; + + unsigned char len1 = data[1]; + unsigned int payloadstartoffset = 2; + + if (len1 & WS_MASKBIT) { + len1 &= ~WS_MASKBIT; + payloadstartoffset += 2; + /* We don't handle masked data, because discord doesnt send it */ + return true; + } + + /* 6 bit ("small") length frame */ + uint64_t len = len1; + + if (len1 == WS_PAYLOAD_LENGTH_MAGIC_LARGE) { + /* 24 bit ("large") length frame */ + if (data.length() < 8) { + /* We don't have a complete header yet */ + return false; + } + + unsigned char len2 = (unsigned char)data[2]; + unsigned char len3 = (unsigned char)data[3]; + len = (len2 << 8) | len3; + + payloadstartoffset += 2; + } else if (len1 == WS_PAYLOAD_LENGTH_MAGIC_HUGE) { + /* 64 bit ("huge") length frame */ + if (data.length() < 10) { + /* We don't have a complete header yet */ + return false; + } + len = 0; + for (int v = 2, shift = 56; v < 10; ++v, shift -= 8) { + unsigned char l = (unsigned char)data[v]; + len |= (uint64_t)(l & 0xff) << shift; + } + payloadstartoffset += 8; + } + + if (data.length() < payloadstartoffset + len) { + /* We don't have a complete frame yet */ + return false; + } + + /* Copy from buffer into string */ + const std::string::iterator endit = data.begin() + payloadstartoffset + len; + for (std::string::const_iterator i = data.begin() + payloadstartoffset; i != endit; ++i) { + const unsigned char c = (unsigned char)*i; + payload.push_back(c); + } + + /* Remove this frame from the input buffer */ + data.erase(data.begin(), endit); + + if ((opcode & ~WS_FINBIT) == OP_PING || (opcode & ~WS_FINBIT) == OP_PONG) { + HandlePingPong((opcode & ~WS_FINBIT) == OP_PING, payload); + } else { + /* Pass this frame to the deriving class */ + this->HandleFrame(payload); + } + return true; + } + break; + + case OP_CLOSE: + { + uint16_t error = data[2] & 0xff; + error <<= 8; + error |= (data[3] & 0xff); + this->Error(error); + return false; + } + break; + + default: + { + this->Error(0); + return false; + } + break; + } + } + return false; +} + +void websocket_client::one_second_timer() +{ + if (((time(NULL) % 20) == 0) && (state == CONNECTED)) { + /* For sending pings, we send with payload */ + unsigned char out[MAXHEADERSIZE]; + std::string payload = "keepalive"; + size_t s = this->FillHeader(out, payload.length(), OP_PING); + std::string header((const char*)out, s); + ssl_client::write(header); + ssl_client::write(payload); + } +} + +void websocket_client::HandlePingPong(bool ping, const std::string &payload) +{ + unsigned char out[MAXHEADERSIZE]; + if (ping) { + /* For receving pings we echo back their payload with the type OP_PONG */ + size_t s = this->FillHeader(out, payload.length(), OP_PONG); + std::string header((const char*)out, s); + ssl_client::write(header); + ssl_client::write(payload); + } +} + +void websocket_client::Error(uint32_t errorcode) +{ +} + +void websocket_client::close() +{ + this->state = HTTP_HEADERS; + ssl_client::close(); +} + +}; \ No newline at end of file