1
0
mirror of https://github.com/VCMP-SqMod/SqMod.git synced 2025-06-16 07:07:13 +02:00

Major plugin refactor and cleanup.

Switched to POCO library for unified platform/library interface.
Deprecated the external module API. It was creating more problems than solving.
Removed most built-in libraries in favor of system libraries for easier maintenance.
Cleaned and secured code with help from static analyzers.
This commit is contained in:
Sandu Liviu Catalin
2021-01-30 08:51:39 +02:00
parent e0e34b4030
commit 4a6bfc086c
6219 changed files with 1209835 additions and 454916 deletions

View File

@ -1,19 +1,22 @@
// ------------------------------------------------------------------------------------------------
#include "Library/CURL.hpp"
// ------------------------------------------------------------------------------------------------
#include <sqratConst.h>
// ------------------------------------------------------------------------------------------------
namespace SqMod {
// ------------------------------------------------------------------------------------------------
SQMODE_DECL_TYPENAME(SqCpSslOptions, _SC("SqCprSslOptions"))
SQMODE_DECL_TYPENAME(SqCpError, _SC("SqCpError"))
SQMODE_DECL_TYPENAME(SqCpCookies, _SC("SqCprCookies"))
SQMODE_DECL_TYPENAME(SqCpHeader, _SC("SqCprHeader"))
SQMODE_DECL_TYPENAME(SqCpResponse, _SC("SqCprResponse"))
SQMODE_DECL_TYPENAME(SqCpParameters, _SC("SqCprParameters"))
SQMODE_DECL_TYPENAME(SqCpPayload, _SC("SqCprPayload"))
SQMODE_DECL_TYPENAME(SqCpProxies, _SC("SqCprProxies"))
SQMODE_DECL_TYPENAME(SqCpSession, _SC("SqCprSession"))
SQMOD_DECL_TYPENAME(SqCpSslOptions, _SC("SqCprSslOptions"))
SQMOD_DECL_TYPENAME(SqCpError, _SC("SqCpError"))
SQMOD_DECL_TYPENAME(SqCpCookies, _SC("SqCprCookies"))
SQMOD_DECL_TYPENAME(SqCpHeader, _SC("SqCprHeader"))
SQMOD_DECL_TYPENAME(SqCpResponse, _SC("SqCprResponse"))
SQMOD_DECL_TYPENAME(SqCpParameters, _SC("SqCprParameters"))
SQMOD_DECL_TYPENAME(SqCpPayload, _SC("SqCprPayload"))
SQMOD_DECL_TYPENAME(SqCpProxies, _SC("SqCprProxies"))
SQMOD_DECL_TYPENAME(SqCpSession, _SC("SqCprSession"))
// ------------------------------------------------------------------------------------------------
static const EnumElement g_ErrorCodes[] = {

View File

@ -1,7 +1,7 @@
#pragma once
// ------------------------------------------------------------------------------------------------
#include "Base/Shared.hpp"
#include "Core/Common.hpp"
// ------------------------------------------------------------------------------------------------
#include <cpr/cpr.h>
@ -48,7 +48,7 @@ struct CpSslOptions : public cpr::SslOptions
/* --------------------------------------------------------------------------------------------
* Retrieve cpr::SslOptions::cert_file value.
*/
const std::string & GetCertFile() const { return Base::cert_file; }
SQMOD_NODISCARD const std::string & GetCertFile() const { return Base::cert_file; }
/* --------------------------------------------------------------------------------------------
* Assign cpr::SslOptions::cert_file and cpr::SslOptions::cert_type values.
@ -80,7 +80,7 @@ struct CpSslOptions : public cpr::SslOptions
/* --------------------------------------------------------------------------------------------
* Retrieve cpr::SslOptions::cert_type value.
*/
const std::string & GetCertType() const { return Base::cert_type; }
SQMOD_NODISCARD const std::string & GetCertType() const { return Base::cert_type; }
/* --------------------------------------------------------------------------------------------
* Assign cpr::SslOptions::cert_type values.
@ -90,7 +90,7 @@ struct CpSslOptions : public cpr::SslOptions
/* --------------------------------------------------------------------------------------------
* Retrieve cpr::SslOptions::key_file value.
*/
const std::string & GetKeyFile() const { return Base::key_file; }
SQMOD_NODISCARD const std::string & GetKeyFile() const { return Base::key_file; }
/* --------------------------------------------------------------------------------------------
* Assign cpr::SslOptions::cert_file, cpr::SslOptions::key_pass and cpr::SslOptions::cert_type values.
@ -126,7 +126,7 @@ struct CpSslOptions : public cpr::SslOptions
/* --------------------------------------------------------------------------------------------
* Retrieve cpr::SslOptions::key_type value.
*/
const std::string & GetKeyType() const { return Base::key_type; }
SQMOD_NODISCARD const std::string & GetKeyType() const { return Base::key_type; }
/* --------------------------------------------------------------------------------------------
* Assign cpr::SslOptions::key_type values.
@ -136,7 +136,7 @@ struct CpSslOptions : public cpr::SslOptions
/* --------------------------------------------------------------------------------------------
* Retrieve cpr::SslOptions::key_pass value.
*/
const std::string & GetKeyPass() const { return Base::key_pass; }
SQMOD_NODISCARD const std::string & GetKeyPass() const { return Base::key_pass; }
/* --------------------------------------------------------------------------------------------
* Assign cpr::SslOptions::key_pass values.
@ -147,36 +147,36 @@ struct CpSslOptions : public cpr::SslOptions
/* --------------------------------------------------------------------------------------------
* Retrieve cpr::SslOptions::enable_alpn value.
*/
bool GetALPN() const { return Base::enable_alpn; }
SQMOD_NODISCARD bool GetALPN() const { return Base::enable_alpn; }
/* --------------------------------------------------------------------------------------------
* Modify cpr::SslOptions::enable_alpn value.
*/
void SetALPN(bool value) { Base::enable_alpn = value; }
#else
void GetALPN() const { STHROWF("Unsupported"); }
void SetALPN(bool) { STHROWF("Unsupported"); }
void GetALPN() const { STHROWF("Unsupported"); } // NOLINT(readability-convert-member-functions-to-static)
void SetALPN(bool) { STHROWF("Unsupported"); } // NOLINT(readability-convert-member-functions-to-static)
#endif // SUPPORT_ALPN
#if SUPPORT_NPN
/* --------------------------------------------------------------------------------------------
* Retrieve cpr::SslOptions::enable_npn value.
*/
bool GetNPM() const { return Base::enable_npn; }
SQMOD_NODISCARD bool GetNPM() const { return Base::enable_npn; }
/* --------------------------------------------------------------------------------------------
* Modify cpr::SslOptions::enable_npn value.
*/
void SetNPM(bool value) { Base::enable_npn = value; }
#else
void GetNPM() const { STHROWF("Unsupported"); }
void SetNPM(bool) { STHROWF("Unsupported"); }
void GetNPM() const { STHROWF("Unsupported"); } // NOLINT(readability-convert-member-functions-to-static)
void SetNPM(bool) { STHROWF("Unsupported"); } // NOLINT(readability-convert-member-functions-to-static)
#endif // SUPPORT_NPN
/* --------------------------------------------------------------------------------------------
* Retrieve cpr::SslOptions::verify_host value.
*/
bool GetVerifyHost() const { return Base::verify_host; }
SQMOD_NODISCARD bool GetVerifyHost() const { return Base::verify_host; }
/* --------------------------------------------------------------------------------------------
* Modify cpr::SslOptions::verify_host value.
@ -186,7 +186,7 @@ struct CpSslOptions : public cpr::SslOptions
/* --------------------------------------------------------------------------------------------
* Retrieve cpr::SslOptions::verify_peer value.
*/
bool GetVerifyPeer() const { return Base::verify_peer; }
SQMOD_NODISCARD bool GetVerifyPeer() const { return Base::verify_peer; }
/* --------------------------------------------------------------------------------------------
* Modify cpr::SslOptions::verify_peer value.
@ -196,7 +196,7 @@ struct CpSslOptions : public cpr::SslOptions
/* --------------------------------------------------------------------------------------------
* Retrieve cpr::SslOptions::verify_status value.
*/
bool GetVerifyStatus() const { return Base::verify_status; }
SQMOD_NODISCARD bool GetVerifyStatus() const { return Base::verify_status; }
/* --------------------------------------------------------------------------------------------
* Modify cpr::SslOptions::verify_status value.
@ -206,21 +206,21 @@ struct CpSslOptions : public cpr::SslOptions
/* --------------------------------------------------------------------------------------------
* Retrieve cpr::SslOptions::ssl_version value.
*/
int GetSslVersion() const { return Base::ssl_version; }
SQMOD_NODISCARD int GetSslVersion() const { return Base::ssl_version; }
#if SUPPORT_MAX_TLS_VERSION
/* --------------------------------------------------------------------------------------------
* Retrieve cpr::SslOptions::max_version value.
*/
int GetMaxVersion() const { return Base::max_version; }
SQMOD_NODISCARD int GetMaxVersion() const { return Base::max_version; }
#else
void GetMaxVersion() const { STHROWF("Unsupported"); }
void GetMaxVersion() const { STHROWF("Unsupported"); } // NOLINT(readability-convert-member-functions-to-static)
#endif // SUPPORT_MAX_TLS_VERSION
/* --------------------------------------------------------------------------------------------
* Retrieve cpr::SslOptions::ca_info value.
*/
const std::string & GetCaInfo() const { return Base::ca_info; }
SQMOD_NODISCARD const std::string & GetCaInfo() const { return Base::ca_info; }
/* --------------------------------------------------------------------------------------------
* Assign cpr::SslOptions::ca_info values.
@ -230,7 +230,7 @@ struct CpSslOptions : public cpr::SslOptions
/* --------------------------------------------------------------------------------------------
* Retrieve cpr::SslOptions::ca_path value.
*/
const std::string & GetCaPath() const { return Base::ca_path; }
SQMOD_NODISCARD const std::string & GetCaPath() const { return Base::ca_path; }
/* --------------------------------------------------------------------------------------------
* Assign cpr::SslOptions::ca_path values.
@ -240,7 +240,7 @@ struct CpSslOptions : public cpr::SslOptions
/* --------------------------------------------------------------------------------------------
* Retrieve cpr::SslOptions::crl_file value.
*/
const std::string & GetCrlFile() const { return Base::crl_file; }
SQMOD_NODISCARD const std::string & GetCrlFile() const { return Base::crl_file; }
/* --------------------------------------------------------------------------------------------
* Assign cpr::SslOptions::crl_file values.
@ -250,7 +250,7 @@ struct CpSslOptions : public cpr::SslOptions
/* --------------------------------------------------------------------------------------------
* Retrieve cpr::SslOptions::ciphers value.
*/
const std::string & GetCiphers() const { return Base::ciphers; }
SQMOD_NODISCARD const std::string & GetCiphers() const { return Base::ciphers; }
/* --------------------------------------------------------------------------------------------
* Assign cpr::SslOptions::ciphers values.
@ -261,30 +261,30 @@ struct CpSslOptions : public cpr::SslOptions
/* --------------------------------------------------------------------------------------------
* Retrieve cpr::SslOptions::tls13_ciphers value.
*/
const std::string & GetTLS13Ciphers() const { return Base::tls13_ciphers; }
SQMOD_NODISCARD const std::string & GetTLS13Ciphers() const { return Base::tls13_ciphers; }
/* --------------------------------------------------------------------------------------------
* Assign cpr::SslOptions::tls13_ciphers values.
*/
void SetTLS13Ciphers(StackStrF & cph) { tls13_ciphers.assign(cph.mPtr, cph.GetSize()); }
#else
void GetTLS13Ciphers() const { STHROWF("Unsupported"); }
void SetTLS13Ciphers(StackStrF &) const { STHROWF("Unsupported"); }
void GetTLS13Ciphers() const { STHROWF("Unsupported"); } // NOLINT(readability-convert-member-functions-to-static)
void SetTLS13Ciphers(StackStrF &) const { STHROWF("Unsupported"); } // NOLINT(readability-convert-member-functions-to-static)
#endif // SUPPORT_TLSv13_CIPHERS
#if SUPPORT_SESSIONID_CACHE
/* --------------------------------------------------------------------------------------------
* Retrieve cpr::SslOptions::session_id_cache value.
*/
bool GetSessionIdCache() const { return Base::session_id_cache; }
SQMOD_NODISCARD bool GetSessionIdCache() const { return Base::session_id_cache; }
/* --------------------------------------------------------------------------------------------
* Modify cpr::SslOptions::session_id_cache value.
*/
void SetSessionIdCache(bool value) { Base::session_id_cache = value; }
#else
void GetSessionIdCache() const { STHROWF("Unsupported"); }
void SetSessionIdCache(bool) const { STHROWF("Unsupported"); }
void GetSessionIdCache() const { STHROWF("Unsupported"); } // NOLINT(readability-convert-member-functions-to-static)
void SetSessionIdCache(bool) const { STHROWF("Unsupported"); } // NOLINT(readability-convert-member-functions-to-static)
#endif // SUPPORT_SESSIONID_CACHE
/* --------------------------------------------------------------------------------------------
@ -298,7 +298,7 @@ struct CpSslOptions : public cpr::SslOptions
*/
void SetSSLv2() { ssl_version = CURL_SSLVERSION_SSLv2; }
#else
void SetSSLv2() const { STHROWF("Unsupported"); }
void SetSSLv2() const { STHROWF("Unsupported"); } // NOLINT(readability-convert-member-functions-to-static)
#endif
/* --------------------------------------------------------------------------------------------
* Modify cpr::SslOptions::ssl_version value.
@ -306,7 +306,7 @@ struct CpSslOptions : public cpr::SslOptions
#if SUPPORT_SSLv3
void SetSSLv3() { ssl_version = CURL_SSLVERSION_SSLv3; }
#else
void SetSSLv3() const { STHROWF("Unsupported"); }
void SetSSLv3() const { STHROWF("Unsupported"); } // NOLINT(readability-convert-member-functions-to-static)
#endif
/* --------------------------------------------------------------------------------------------
@ -315,7 +315,7 @@ struct CpSslOptions : public cpr::SslOptions
#if SUPPORT_TLSv1_0
void SetTLSv1_0() { ssl_version = CURL_SSLVERSION_TLSv1_0; }
#else
void SetTLSv1_0() const { STHROWF("Unsupported"); }
void SetTLSv1_0() const { STHROWF("Unsupported"); } // NOLINT(readability-convert-member-functions-to-static)
#endif
/* --------------------------------------------------------------------------------------------
@ -324,7 +324,7 @@ struct CpSslOptions : public cpr::SslOptions
#if SUPPORT_TLSv1_1
void SetTLSv1_1() { ssl_version = CURL_SSLVERSION_TLSv1_1; }
#else
void SetTLSv1_1() const { STHROWF("Unsupported"); }
void SetTLSv1_1() const { STHROWF("Unsupported"); } // NOLINT(readability-convert-member-functions-to-static)
#endif
/* --------------------------------------------------------------------------------------------
@ -333,7 +333,7 @@ struct CpSslOptions : public cpr::SslOptions
#if SUPPORT_TLSv1_2
void SetTLSv1_2() { ssl_version = CURL_SSLVERSION_TLSv1_2; }
#else
void SetTLSv1_2() const { STHROWF("Unsupported"); }
void SetTLSv1_2() const { STHROWF("Unsupported"); } // NOLINT(readability-convert-member-functions-to-static)
#endif
/* --------------------------------------------------------------------------------------------
@ -342,7 +342,7 @@ struct CpSslOptions : public cpr::SslOptions
#if SUPPORT_TLSv1_3
void SetTLSv1_3() { ssl_version = CURL_SSLVERSION_TLSv1_3; }
#else
void SetTLSv1_3() const { STHROWF("Unsupported"); }
void SetTLSv1_3() const { STHROWF("Unsupported"); } // NOLINT(readability-convert-member-functions-to-static)
#endif
/* --------------------------------------------------------------------------------------------
@ -351,7 +351,7 @@ struct CpSslOptions : public cpr::SslOptions
#if SUPPORT_MAX_TLS_VERSION
void SetMaxTLSVersion() { max_version = CURL_SSLVERSION_DEFAULT; }
#else
void SetMaxTLSVersion() const { STHROWF("Unsupported"); }
void SetMaxTLSVersion() const { STHROWF("Unsupported"); } // NOLINT(readability-convert-member-functions-to-static)
#endif
/* --------------------------------------------------------------------------------------------
@ -360,7 +360,7 @@ struct CpSslOptions : public cpr::SslOptions
#if SUPPORT_MAX_TLSv1_0
void SetMaxTLSv1_0() { max_version = CURL_SSLVERSION_MAX_TLSv1_0; }
#else
void SetMaxTLSv1_0() const { STHROWF("Unsupported"); }
void SetMaxTLSv1_0() const { STHROWF("Unsupported"); } // NOLINT(readability-convert-member-functions-to-static)
#endif
/* --------------------------------------------------------------------------------------------
@ -369,7 +369,7 @@ struct CpSslOptions : public cpr::SslOptions
#if SUPPORT_MAX_TLSv1_1
void SetMaxTLSv1_1() { max_version = CURL_SSLVERSION_MAX_TLSv1_1; }
#else
void SetMaxTLSv1_1() const { STHROWF("Unsupported"); }
void SetMaxTLSv1_1() const { STHROWF("Unsupported"); } // NOLINT(readability-convert-member-functions-to-static)
#endif
/* --------------------------------------------------------------------------------------------
@ -378,7 +378,7 @@ struct CpSslOptions : public cpr::SslOptions
#if SUPPORT_MAX_TLSv1_2
void SetMaxTLSv1_2() { max_version = CURL_SSLVERSION_MAX_TLSv1_2; }
#else
void SetMaxTLSv1_2() const { STHROWF("Unsupported"); }
void SetMaxTLSv1_2() const { STHROWF("Unsupported"); } // NOLINT(readability-convert-member-functions-to-static)
#endif
/* --------------------------------------------------------------------------------------------
@ -387,7 +387,7 @@ struct CpSslOptions : public cpr::SslOptions
#if SUPPORT_MAX_TLSv1_3
void SetMaxTLSv1_3() { max_version = CURL_SSLVERSION_MAX_TLSv1_3; }
#else
void SetMaxTLSv1_3() const { STHROWF("Unsupported"); }
void SetMaxTLSv1_3() const { STHROWF("Unsupported"); } // NOLINT(readability-convert-member-functions-to-static)
#endif
};
@ -448,7 +448,7 @@ struct CpError : public cpr::Error
/* --------------------------------------------------------------------------------------------
* Retrieve cpr::Error::code.
*/
SQInteger GetCode() const
SQMOD_NODISCARD SQInteger GetCode() const
{
return static_cast< SQInteger >(cpr::Error::code);
}
@ -464,7 +464,7 @@ struct CpError : public cpr::Error
/* --------------------------------------------------------------------------------------------
* Retrieve cpr::Error::text.
*/
const std::string & GetMessage() const
SQMOD_NODISCARD const std::string & GetMessage() const
{
return cpr::Error::message;
}
@ -532,7 +532,7 @@ struct CpCookies : public cpr::Cookies
/* --------------------------------------------------------------------------------------------
* Retrieve the number of values.
*/
SQInteger Size() const
SQMOD_NODISCARD SQInteger Size() const
{
return static_cast< SQInteger >(cpr::Cookies::map_.size());
}
@ -540,7 +540,7 @@ struct CpCookies : public cpr::Cookies
/* --------------------------------------------------------------------------------------------
* Check if no value is stored.
*/
bool Empty() const
SQMOD_NODISCARD bool Empty() const
{
return cpr::Cookies::map_.empty();
}
@ -556,7 +556,7 @@ struct CpCookies : public cpr::Cookies
/* --------------------------------------------------------------------------------------------
* Retrieve the number of matching values.
*/
SQInteger Count(StackStrF & key) const
SQMOD_NODISCARD SQInteger Count(StackStrF & key) const
{
return static_cast< SQInteger >(cpr::Cookies::map_.count(key.ToStr()));
}
@ -581,7 +581,7 @@ struct CpCookies : public cpr::Cookies
/* --------------------------------------------------------------------------------------------
* Check if value exists.
*/
bool Has(StackStrF & key) const
SQMOD_NODISCARD bool Has(StackStrF & key) const
{
return cpr::Cookies::map_.find(key.ToStr()) != cpr::Cookies::map_.end();
}
@ -589,7 +589,7 @@ struct CpCookies : public cpr::Cookies
/* --------------------------------------------------------------------------------------------
* Retrieve value.
*/
std::string & Get(StackStrF & key)
SQMOD_NODISCARD std::string & Get(StackStrF & key)
{
auto itr = cpr::Cookies::map_.find(key.ToStr());
// Does it exist?
@ -654,7 +654,7 @@ struct CpHeader
/* --------------------------------------------------------------------------------------------
* Copy constructor.
*/
explicit CpHeader(const cpr::Header & e) : mMap(e) { }
explicit CpHeader(const cpr::Header & e) : mMap(e) { } // NOLINT(modernize-pass-by-value)
/* --------------------------------------------------------------------------------------------
* Move constructor.
@ -699,7 +699,7 @@ struct CpHeader
/* --------------------------------------------------------------------------------------------
* Retrieve the number of values.
*/
SQInteger Size() const
SQMOD_NODISCARD SQInteger Size() const
{
return static_cast< SQInteger >(mMap.size());
}
@ -707,7 +707,7 @@ struct CpHeader
/* --------------------------------------------------------------------------------------------
* Check if no value is stored.
*/
bool Empty() const
SQMOD_NODISCARD bool Empty() const
{
return mMap.empty();
}
@ -723,7 +723,7 @@ struct CpHeader
/* --------------------------------------------------------------------------------------------
* Retrieve the number of matching values.
*/
SQInteger Count(StackStrF & key) const
SQMOD_NODISCARD SQInteger Count(StackStrF & key) const
{
return static_cast< SQInteger >(mMap.count(key.ToStr()));
}
@ -748,7 +748,7 @@ struct CpHeader
/* --------------------------------------------------------------------------------------------
* Check if value exists.
*/
bool Has(StackStrF & key) const
SQMOD_NODISCARD bool Has(StackStrF & key) const
{
return mMap.find(key.ToStr()) != mMap.end();
}
@ -756,7 +756,7 @@ struct CpHeader
/* --------------------------------------------------------------------------------------------
* Retrieve value.
*/
std::string & Get(StackStrF & key)
SQMOD_NODISCARD std::string & Get(StackStrF & key)
{
auto itr = mMap.find(key.ToStr());
// Does it exist?
@ -852,7 +852,7 @@ struct CpResponse : public cpr::Response
/* --------------------------------------------------------------------------------------------
* Retrieve certificate information.
*/
Array GetCertInfoArray()
SQMOD_NODISCARD Array GetCertInfoArray()
{
if (!cpr::Response::curl_)
{
@ -874,7 +874,7 @@ struct CpResponse : public cpr::Response
/* --------------------------------------------------------------------------------------------
* Retrieve cpr::Response::status_code.
*/
SQInteger GetStatusCode() const
SQMOD_NODISCARD SQInteger GetStatusCode() const
{
return cpr::Response::status_code;
}
@ -890,7 +890,7 @@ struct CpResponse : public cpr::Response
/* --------------------------------------------------------------------------------------------
* Retrieve cpr::Response::text.
*/
const std::string & GetText() const
SQMOD_NODISCARD const std::string & GetText() const
{
return cpr::Response::text;
}
@ -906,7 +906,7 @@ struct CpResponse : public cpr::Response
/* --------------------------------------------------------------------------------------------
* Steal values from cpr::Response::header.
*/
CpHeader StealHeader()
SQMOD_NODISCARD CpHeader StealHeader()
{
return CpHeader(std::move(cpr::Response::header));
}
@ -914,7 +914,7 @@ struct CpResponse : public cpr::Response
/* --------------------------------------------------------------------------------------------
* Retrieve cpr::Response::header.
*/
CpHeader GetHeader() const
SQMOD_NODISCARD CpHeader GetHeader() const
{
return CpHeader(cpr::Response::header);
}
@ -938,7 +938,7 @@ struct CpResponse : public cpr::Response
/* --------------------------------------------------------------------------------------------
* Retrieve cpr::Response::url.
*/
const std::string & GetURL() const
SQMOD_NODISCARD const std::string & GetURL() const
{
return cpr::Response::url.str();
}
@ -954,7 +954,7 @@ struct CpResponse : public cpr::Response
/* --------------------------------------------------------------------------------------------
* Steal values from cpr::Response::cookies.
*/
CpCookies StealCookies()
SQMOD_NODISCARD CpCookies StealCookies()
{
return CpCookies(std::move(cpr::Response::cookies));
}
@ -962,7 +962,7 @@ struct CpResponse : public cpr::Response
/* --------------------------------------------------------------------------------------------
* Retrieve cpr::Response::cookies.
*/
CpCookies GetCookies() const
SQMOD_NODISCARD CpCookies GetCookies() const
{
return CpCookies(cpr::Response::cookies);
}
@ -986,7 +986,7 @@ struct CpResponse : public cpr::Response
/* --------------------------------------------------------------------------------------------
* Retrieve cpr::Response::url.
*/
CpError GetError() const
SQMOD_NODISCARD CpError GetError() const
{
return CpError(cpr::Response::error);
}
@ -1002,7 +1002,7 @@ struct CpResponse : public cpr::Response
/* --------------------------------------------------------------------------------------------
* Retrieve cpr::Response::raw_header.
*/
const std::string & GetRawHeader() const
SQMOD_NODISCARD const std::string & GetRawHeader() const
{
return cpr::Response::raw_header;
}
@ -1018,7 +1018,7 @@ struct CpResponse : public cpr::Response
/* --------------------------------------------------------------------------------------------
* Retrieve cpr::Response::status_line.
*/
const std::string & GetStatusLine() const
SQMOD_NODISCARD const std::string & GetStatusLine() const
{
return cpr::Response::status_line;
}
@ -1034,7 +1034,7 @@ struct CpResponse : public cpr::Response
/* --------------------------------------------------------------------------------------------
* Retrieve cpr::Response::reason.
*/
const std::string & GetReason() const
SQMOD_NODISCARD const std::string & GetReason() const
{
return cpr::Response::reason;
}
@ -1050,7 +1050,7 @@ struct CpResponse : public cpr::Response
/* --------------------------------------------------------------------------------------------
* Retrieve cpr::Response::uploaded_bytes.
*/
SQInteger GetUploadedBytes() const
SQMOD_NODISCARD SQInteger GetUploadedBytes() const
{
return static_cast< SQInteger >(cpr::Response::uploaded_bytes); // possible precision loss!
}
@ -1066,7 +1066,7 @@ struct CpResponse : public cpr::Response
/* --------------------------------------------------------------------------------------------
* Retrieve cpr::Response::downloaded_bytes.
*/
SQInteger GetDownloadedBytes() const
SQMOD_NODISCARD SQInteger GetDownloadedBytes() const
{
return static_cast< SQInteger >(cpr::Response::downloaded_bytes); // possible precision loss!
}
@ -1082,7 +1082,7 @@ struct CpResponse : public cpr::Response
/* --------------------------------------------------------------------------------------------
* Retrieve cpr::Response::redirect_count.
*/
SQInteger GetRedirectCount() const
SQMOD_NODISCARD SQInteger GetRedirectCount() const
{
return cpr::Response::redirect_count;
}
@ -1145,7 +1145,7 @@ struct CpParameters : public cpr::Parameters
/* --------------------------------------------------------------------------------------------
* Retrieve the number of values.
*/
SQInteger Size() const
SQMOD_NODISCARD SQInteger Size() const
{
return static_cast< SQInteger >(cpr::Parameters::containerList_.size());
}
@ -1153,7 +1153,7 @@ struct CpParameters : public cpr::Parameters
/* --------------------------------------------------------------------------------------------
* Check if no value is stored.
*/
bool Empty() const
SQMOD_NODISCARD bool Empty() const
{
return cpr::Parameters::containerList_.empty();
}
@ -1316,7 +1316,7 @@ struct CpPayload : public cpr::Payload
/* --------------------------------------------------------------------------------------------
* Retrieve the number of values.
*/
SQInteger Size() const
SQMOD_NODISCARD SQInteger Size() const
{
return static_cast< SQInteger >(cpr::Payload::containerList_.size());
}
@ -1324,7 +1324,7 @@ struct CpPayload : public cpr::Payload
/* --------------------------------------------------------------------------------------------
* Check if no value is stored.
*/
bool Empty() const
SQMOD_NODISCARD bool Empty() const
{
return cpr::Payload::containerList_.empty();
}
@ -1340,7 +1340,7 @@ struct CpPayload : public cpr::Payload
/* --------------------------------------------------------------------------------------------
* Retrieve the number of matching values.
*/
SQInteger Count(StackStrF & key) const
SQMOD_NODISCARD SQInteger Count(StackStrF & key) const
{
return static_cast< SQInteger >(std::count_if(
cpr::Payload::containerList_.begin(), cpr::Payload::containerList_.end(),
@ -1364,7 +1364,7 @@ struct CpPayload : public cpr::Payload
/* --------------------------------------------------------------------------------------------
* Check if value exists.
*/
bool Has(StackStrF & key) const
SQMOD_NODISCARD bool Has(StackStrF & key) const
{
return std::find_if(
cpr::Payload::containerList_.begin(), cpr::Payload::containerList_.end(),
@ -1375,7 +1375,7 @@ struct CpPayload : public cpr::Payload
/* --------------------------------------------------------------------------------------------
* Retrieve value.
*/
std::string & Get(StackStrF & key)
SQMOD_NODISCARD std::string & Get(StackStrF & key)
{
auto itr = std::find_if(
cpr::Payload::containerList_.begin(), cpr::Payload::containerList_.end(),
@ -1495,7 +1495,7 @@ struct CpProxies : public cpr::Proxies
/* --------------------------------------------------------------------------------------------
* Retrieve the number of values.
*/
SQInteger Size() const
SQMOD_NODISCARD SQInteger Size() const
{
return static_cast< SQInteger >(cpr::Proxies::hosts_.size());
}
@ -1503,7 +1503,7 @@ struct CpProxies : public cpr::Proxies
/* --------------------------------------------------------------------------------------------
* Check if no value is stored.
*/
bool Empty() const
SQMOD_NODISCARD bool Empty() const
{
return cpr::Proxies::hosts_.empty();
}
@ -1519,7 +1519,7 @@ struct CpProxies : public cpr::Proxies
/* --------------------------------------------------------------------------------------------
* Retrieve the number of matching values.
*/
SQInteger Count(StackStrF & key) const
SQMOD_NODISCARD SQInteger Count(StackStrF & key) const
{
return static_cast< SQInteger >(cpr::Proxies::hosts_.count(key.ToStr()));
}
@ -1544,7 +1544,7 @@ struct CpProxies : public cpr::Proxies
/* --------------------------------------------------------------------------------------------
* Check if value exists.
*/
bool Has(StackStrF & key) const
SQMOD_NODISCARD bool Has(StackStrF & key) const
{
return cpr::Proxies::hosts_.find(key.ToStr()) != cpr::Proxies::hosts_.end();
}
@ -1552,7 +1552,7 @@ struct CpProxies : public cpr::Proxies
/* --------------------------------------------------------------------------------------------
* Retrieve value.
*/
std::string & Get(StackStrF & key)
SQMOD_NODISCARD std::string & Get(StackStrF & key)
{
auto itr = cpr::Proxies::hosts_.find(key.ToStr());
// Does it exist?

View File

@ -1,12 +1,10 @@
// ------------------------------------------------------------------------------------------------
#include "Library/Chrono.hpp"
#include "Library/Chrono/Date.hpp"
#include "Library/Chrono/Datetime.hpp"
#include "Library/Chrono/Time.hpp"
#include "Library/Chrono/Timer.hpp"
#include "Library/Chrono/Timestamp.hpp"
#include "Library/Numeric/LongInt.hpp"
#include "Base/Shared.hpp"
#include "Library/Numeric/Long.hpp"
#include "Core/Utility.hpp"
// ------------------------------------------------------------------------------------------------
#ifdef SQMOD_OS_WINDOWS
@ -33,7 +31,7 @@ extern void Register_ChronoTimer(HSQUIRRELVM vm, Table & cns);
extern void Register_ChronoTimestamp(HSQUIRRELVM vm, Table & cns);
// ------------------------------------------------------------------------------------------------
const Uint8 Chrono::MonthLengths[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
const uint8_t Chrono::MonthLengths[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
// ------------------------------------------------------------------------------------------------
#ifdef SQMOD_OS_WINDOWS
@ -49,7 +47,7 @@ inline LARGE_INTEGER GetFrequency()
}
// ------------------------------------------------------------------------------------------------
Int64 Chrono::GetCurrentSysTime()
int64_t Chrono::GetCurrentSysTime()
{
// Force the following code to run on first core
// (see http://msdn.microsoft.com/en-us/library/windows/desktop/ms644904(v=vs.85).aspx)
@ -68,54 +66,54 @@ Int64 Chrono::GetCurrentSysTime()
SetThreadAffinityMask(current_thread, previous_mask);
// Return the current time as microseconds
return Int64(1000000LL * time.QuadPart / frequency.QuadPart);
return int64_t(1000000LL * time.QuadPart / frequency.QuadPart);
}
// ------------------------------------------------------------------------------------------------
Int64 Chrono::GetEpochTimeMicro()
int64_t Chrono::GetEpochTimeMicro()
{
FILETIME ft;
GetSystemTimeAsFileTime(&ft);
// Extract the nanoseconds from the resulted timestamp
Uint64 time = ft.dwHighDateTime;
uint64_t time = ft.dwHighDateTime;
time <<= 32;
time |= ft.dwLowDateTime;
time /= 10;
time -= 11644473600000000ULL;
// Return the resulted timestamp
return Int64(time);
return int64_t(time);
}
// ------------------------------------------------------------------------------------------------
#ifndef _SQ64
Int64 GetTickCount64()
int64_t GetTickCount64()
{
return static_cast< Int64 >(GetTickCount()); // Fall-back to 32 bit?
return static_cast< int64_t >(GetTickCount()); // Fall-back to 32 bit?
}
#endif // _SQ64
#else
// ------------------------------------------------------------------------------------------------
Int64 Chrono::GetCurrentSysTime()
int64_t Chrono::GetCurrentSysTime()
{
// POSIX implementation
timespec time;
clock_gettime(CLOCK_MONOTONIC, &time);
return Int64(Uint64(time.tv_sec) * 1000000 + time.tv_nsec / 1000);
return int64_t(uint64_t(time.tv_sec) * 1000000 + time.tv_nsec / 1000);
}
// ------------------------------------------------------------------------------------------------
Int64 Chrono::GetEpochTimeMicro()
int64_t Chrono::GetEpochTimeMicro()
{
// POSIX implementation
timespec time;
clock_gettime(CLOCK_REALTIME, &time);
return Int64(Uint64(time.tv_sec) * 1000000 + time.tv_nsec / 1000);
return int64_t(uint64_t(time.tv_sec) * 1000000 + time.tv_nsec / 1000);
}
// ------------------------------------------------------------------------------------------------
Uint32 GetTickCount()
uint32_t GetTickCount()
{
// POSIX implementation
struct timespec time;
@ -127,7 +125,7 @@ Uint32 GetTickCount()
}
// ------------------------------------------------------------------------------------------------
Int64 GetTickCount64()
int64_t GetTickCount64()
{
struct timespec time;
if (clock_gettime(CLOCK_MONOTONIC, &time))
@ -140,21 +138,16 @@ Int64 GetTickCount64()
#endif // SQMOD_OS_WINDOWS
// ------------------------------------------------------------------------------------------------
Int64 Chrono::GetEpochTimeMilli()
int64_t Chrono::GetEpochTimeMilli()
{
return (GetEpochTimeMicro() / 1000L);
}
// ------------------------------------------------------------------------------------------------
bool Chrono::ValidDate(Uint16 year, Uint8 month, Uint8 day)
bool Chrono::ValidDate(uint16_t year, uint8_t month, uint8_t day)
{
// Is this a valid date?
if (year == 0 || month == 0 || day == 0)
{
return false;
}
// Is the month within range?
else if (month > 12)
// Is this a valid date? & Is the month within range?
if (year == 0 || month == 0 || day == 0 || month > 12)
{
return false;
}
@ -163,7 +156,7 @@ bool Chrono::ValidDate(Uint16 year, Uint8 month, Uint8 day)
}
// ------------------------------------------------------------------------------------------------
Uint8 Chrono::DaysInMonth(Uint16 year, Uint8 month)
uint8_t Chrono::DaysInMonth(uint16_t year, uint8_t month)
{
// Is the specified month within range?
if (month > 12)
@ -171,7 +164,7 @@ Uint8 Chrono::DaysInMonth(Uint16 year, Uint8 month)
STHROWF("Month value is out of range: %u > 12", month);
}
// Obtain the days in this month
Uint8 days = *(MonthLengths + month);
uint8_t days = *(MonthLengths + month);
// Should we account for January?
if (month == 2 && IsLeapYear(year))
{
@ -182,12 +175,12 @@ Uint8 Chrono::DaysInMonth(Uint16 year, Uint8 month)
}
// ------------------------------------------------------------------------------------------------
Uint16 Chrono::DayOfYear(Uint16 year, Uint8 month, Uint8 day)
uint16_t Chrono::DayOfYear(uint16_t year, uint8_t month, uint8_t day)
{
// Start with 0 days
Uint16 doy = 0;
uint16_t doy = 0;
// Cumulate the days in months
for (Uint8 m = 1; m < month; ++month)
for (uint8_t m = 1; m < month; ++month)
{
doy += DaysInMonth(year, m);
}
@ -198,15 +191,15 @@ Uint16 Chrono::DayOfYear(Uint16 year, Uint8 month, Uint8 day)
}
// ------------------------------------------------------------------------------------------------
Date Chrono::ReverseDayOfyear(Uint16 year, Uint16 doy)
Date Chrono::ReverseDayOfYear(uint16_t year, uint16_t doy)
{
// The resulted month
Uint8 month = 1;
uint8_t month = 1;
// Calculate the months till the specified day of year
for (; month < 12; ++month)
{
// Get the number of days in the current month
Uint32 days = DaysInMonth(year, month);
uint32_t days = DaysInMonth(year, month);
// Can this month fit in the remaining days?
if (days >= doy)
{
@ -220,7 +213,7 @@ Date Chrono::ReverseDayOfyear(Uint16 year, Uint16 doy)
}
// ------------------------------------------------------------------------------------------------
Int64 Chrono::DateRangeToSeconds(Uint16 _year, Uint8 _month, Uint8 _day, Uint16 year_, Uint8 month_, Uint8 day_)
int64_t Chrono::DateRangeToSeconds(uint16_t _year, uint8_t _month, uint8_t _day, uint16_t year_, uint8_t month_, uint8_t day_)
{
// Are we within the same year?
if (_year == year_)
@ -235,7 +228,7 @@ Int64 Chrono::DateRangeToSeconds(Uint16 _year, Uint8 _month, Uint8 _day, Uint16
std::swap(_day, day_);
}
// Calculate the remaining days from the first year
Int64 num = DaysInYear(_year) - DayOfYear(_year, _month, _day);
int64_t num = DaysInYear(_year) - DayOfYear(_year, _month, _day);
// Calculate the days withing the years range
while (++_year < year_)
{
@ -301,7 +294,7 @@ void Register_Chrono(HSQUIRRELVM vm)
.Func(_SC("DaysInYear"), &Chrono::DaysInYear)
.Func(_SC("DaysInMonth"), &Chrono::DaysInMonth)
.Func(_SC("DayOfYear"), &Chrono::DayOfYear)
.Func(_SC("ReverseDayOfyear"), &Chrono::ReverseDayOfyear);
.Func(_SC("ReverseDayOfYear"), &Chrono::ReverseDayOfYear);
RootTable(vm).Bind(_SC("SqChrono"), cns);
}

View File

@ -1,7 +1,7 @@
#pragma once
// ------------------------------------------------------------------------------------------------
#include "SqBase.hpp"
#include "Core/Common.hpp"
// ------------------------------------------------------------------------------------------------
namespace SqMod {
@ -21,7 +21,7 @@ class Chrono
public:
// ------------------------------------------------------------------------------------------------
static const Uint8 MonthLengths[12];
static const uint8_t MonthLengths[12];
/* --------------------------------------------------------------------------------------------
* Default constructor. (disabled)
@ -56,27 +56,27 @@ public:
/* --------------------------------------------------------------------------------------------
* Retrieve the current time as microseconds.
*/
static Int64 GetCurrentSysTime();
static int64_t GetCurrentSysTime();
/* --------------------------------------------------------------------------------------------
* Retrieve the epoch time as microseconds.
*/
static Int64 GetEpochTimeMicro();
static int64_t GetEpochTimeMicro();
/* --------------------------------------------------------------------------------------------
* Retrieve the epoch time as milliseconds.
*/
static Int64 GetEpochTimeMilli();
static int64_t GetEpochTimeMilli();
/* --------------------------------------------------------------------------------------------
* See whether the specified date is valid.
*/
static bool ValidDate(Uint16 year, Uint8 month, Uint8 day);
static bool ValidDate(uint16_t year, uint8_t month, uint8_t day);
/* --------------------------------------------------------------------------------------------
* See whether the specified year is a leap year.
*/
static bool IsLeapYear(Uint16 year)
static bool IsLeapYear(uint16_t year)
{
return !(year % 400) || (!(year % 4) && (year % 100));
}
@ -84,7 +84,7 @@ public:
/* --------------------------------------------------------------------------------------------
* retrieve the number of days in the specified year.
*/
static Uint16 DaysInYear(Uint16 year)
static uint16_t DaysInYear(uint16_t year)
{
return IsLeapYear(year) ? 366 : 365;
}
@ -92,22 +92,22 @@ public:
/* --------------------------------------------------------------------------------------------
* Retrieve the number of days in the specified month.
*/
static Uint8 DaysInMonth(Uint16 year, Uint8 month);
static uint8_t DaysInMonth(uint16_t year, uint8_t month);
/* --------------------------------------------------------------------------------------------
* Retrieve the number/position of the specified day in the specified year and month.
*/
static Uint16 DayOfYear(Uint16 year, Uint8 month, Uint8 day);
static uint16_t DayOfYear(uint16_t year, uint8_t month, uint8_t day);
/* --------------------------------------------------------------------------------------------
* Convert just the year and day of year to full date.
*/
static Date ReverseDayOfyear(Uint16 year, Uint16 doy);
static Date ReverseDayOfYear(uint16_t year, uint16_t doy);
/* --------------------------------------------------------------------------------------------
* Calculate the number of days in the specified date range.
*/
static Int64 DateRangeToSeconds(Uint16 _year, Uint8 _month, Uint8 _day, Uint16 year_, Uint8 month_, Uint8 day_);
static int64_t DateRangeToSeconds(uint16_t _year, uint8_t _month, uint8_t _day, uint16_t year_, uint8_t month_, uint8_t day_);
};
} // Namespace:: SqMod

View File

@ -1,28 +1,26 @@
// ------------------------------------------------------------------------------------------------
#include "Library/Chrono/Date.hpp"
#include "Library/Chrono/Time.hpp"
#include "Library/Chrono/Datetime.hpp"
#include "Library/Chrono/Timestamp.hpp"
#include "Base/Shared.hpp"
#include "Core/Utility.hpp"
// ------------------------------------------------------------------------------------------------
namespace SqMod {
// ------------------------------------------------------------------------------------------------
SQMODE_DECL_TYPENAME(Typename, _SC("SqDate"))
SQMOD_DECL_TYPENAME(Typename, _SC("SqDate"))
// ------------------------------------------------------------------------------------------------
SQChar Date::Delimiter = '-';
// ------------------------------------------------------------------------------------------------
Int32 Date::Compare(const Date & o) const
int32_t Date::Compare(const Date & o) const
{
if (m_Year < o.m_Year)
{
{ // NOLINT(bugprone-branch-clone)
return -1;
}
else if (m_Year > o.m_Year)
{
{ // NOLINT(bugprone-branch-clone)
return 1;
}
else if (m_Month < o.m_Month)
@ -71,13 +69,13 @@ Date Date::operator / (const Date & o) const
}
// ------------------------------------------------------------------------------------------------
CSStr Date::ToString() const
String Date::ToString() const
{
return ToStrF("%04u%c%02u%c%02u", m_Year, m_Delimiter, m_Month, m_Delimiter, m_Day);
return fmt::format("{:04}{}{:02}{}{:02}", m_Year, m_Delimiter, m_Month, m_Delimiter, m_Day);
}
// ------------------------------------------------------------------------------------------------
void Date::Set(Uint16 year, Uint8 month, Uint8 day)
void Date::Set(uint16_t year, uint8_t month, uint8_t day)
{
if (!Chrono::ValidDate(year, month, day))
{
@ -90,7 +88,7 @@ void Date::Set(Uint16 year, Uint8 month, Uint8 day)
}
// ------------------------------------------------------------------------------------------------
void Date::SetStr(CSStr str)
void Date::SetStr(const SQChar * str)
{
// The format specifications that will be used to scan the string
static SQChar fs[] = _SC(" %u - %u - %u ");
@ -108,21 +106,21 @@ void Date::SetStr(CSStr str)
fs[4] = m_Delimiter;
fs[9] = m_Delimiter;
// The sscanf function requires at least 32 bit integers
Uint32 year = 0, month = 0, day = 0;
uint32_t year = 0, month = 0, day = 0;
// Attempt to extract the component values from the specified string
sscanf(str, fs, &year, &month, &day);
// Clamp the extracted values to the boundaries of associated type and assign them
Set(ClampL< Uint32, Uint8 >(year),
ClampL< Uint32, Uint8 >(month),
ClampL< Uint32, Uint8 >(day)
Set(ClampL< uint32_t, uint8_t >(year),
ClampL< uint32_t, uint8_t >(month),
ClampL< uint32_t, uint8_t >(day)
);
}
// ------------------------------------------------------------------------------------------------
void Date::SetDayOfYear(Uint16 doy)
void Date::SetDayOfYear(uint16_t doy)
{
// Reverse the given day of year to a full date
Date d = Chrono::ReverseDayOfyear(m_Year, doy);
Date d = Chrono::ReverseDayOfYear(m_Year, doy);
// Set the obtained month
SetMonth(d.m_Month);
// Set the obtained day
@ -130,7 +128,7 @@ void Date::SetDayOfYear(Uint16 doy)
}
// ------------------------------------------------------------------------------------------------
void Date::SetYear(Uint16 year)
void Date::SetYear(uint16_t year)
{
// Make sure the year is valid
if (!year)
@ -148,7 +146,7 @@ void Date::SetYear(Uint16 year)
}
// ------------------------------------------------------------------------------------------------
void Date::SetMonth(Uint8 month)
void Date::SetMonth(uint8_t month)
{
// Make sure the month is valid
if (month == 0 || month > 12)
@ -165,10 +163,10 @@ void Date::SetMonth(Uint8 month)
}
// ------------------------------------------------------------------------------------------------
void Date::SetDay(Uint8 day)
void Date::SetDay(uint8_t day)
{
// Grab the amount of days in the current month
const Uint8 dim = Chrono::DaysInMonth(m_Year, m_Month);
const uint8_t dim = Chrono::DaysInMonth(m_Year, m_Month);
// Make sure the day is valid
if (day == 0)
{
@ -183,26 +181,26 @@ void Date::SetDay(Uint8 day)
}
// ------------------------------------------------------------------------------------------------
Date & Date::AddYears(Int32 years)
Date & Date::AddYears(int32_t years)
{
// Do we have a valid amount of years?
if (years)
{
// Add the specified amount of years
SetYear(ConvTo< Uint16 >::From(static_cast< Int32 >(m_Year) + years));
SetYear(ConvTo< uint16_t >::From(static_cast< int32_t >(m_Year) + years));
}
// Allow chaining operations
return *this;
}
// ------------------------------------------------------------------------------------------------
Date & Date::AddMonths(Int32 months)
Date & Date::AddMonths(int32_t months)
{
// Do we have a valid amount of months?
if (months)
{
// Extract the number of years
Int32 years = static_cast< Int32 >(months / 12);
auto years = static_cast< int32_t >(months / 12);
// Extract the number of months
months = (months % 12) + m_Month;
// Do we have extra months?
@ -223,47 +221,47 @@ Date & Date::AddMonths(Int32 months)
// Are there any years to add?
if (years)
{
SetYear(ConvTo< Uint16 >::From(static_cast< Int32 >(m_Year) + years));
SetYear(ConvTo< uint16_t >::From(static_cast< int32_t >(m_Year) + years));
}
// Add the months
SetMonth(months);
SetMonth(static_cast< uint8_t >(months));
}
// Allow chaining operations
return *this;
}
// ------------------------------------------------------------------------------------------------
Date & Date::AddDays(Int32 days)
Date & Date::AddDays(int32_t days)
{
// Do we have a valid amount of days?
if (days)
{
// Whether the number of days is positive or negative
const Int32 dir = days > 0 ? 1 : -1;
const int32_t dir = days > 0 ? 1 : -1;
// Grab current year
Int32 year = m_Year;
int32_t year = m_Year;
// Calculate the days in the current year
Int32 diy = Chrono::DaysInYear(year);
int32_t diy = Chrono::DaysInYear(static_cast< uint16_t >(year));
// Calculate the day of year
Int32 doy = GetDayOfYear() + days;
int32_t doy = GetDayOfYear() + days;
// Calculate the resulting years
while (doy > diy || doy < 0)
{
doy -= diy * dir;
year += dir;
diy = Chrono::DaysInYear(year);
diy = Chrono::DaysInYear(static_cast< uint16_t >(year));
}
// Set the obtained year
SetYear(year);
SetYear(static_cast< uint16_t >(year));
// Set the obtained day of year
SetDayOfYear(doy);
SetDayOfYear(static_cast< uint16_t >(doy));
}
// Allow chaining operations
return *this;
}
// ------------------------------------------------------------------------------------------------
Date Date::AndYears(Int32 years)
Date Date::AndYears(int32_t years)
{
// Do we have a valid amount of years?
if (!years)
@ -273,13 +271,13 @@ Date Date::AndYears(Int32 years)
// Replicate the current date
Date d(*this);
// Add the specified amount of years
d.SetYear(ConvTo< Uint16 >::From(static_cast< Int32 >(m_Year) + years));
d.SetYear(ConvTo< uint16_t >::From(static_cast< int32_t >(m_Year) + years));
// Return the resulted date
return d;
}
// ------------------------------------------------------------------------------------------------
Date Date::AndMonths(Int32 months)
Date Date::AndMonths(int32_t months)
{
// Do we have a valid amount of months?
if (!months)
@ -287,7 +285,7 @@ Date Date::AndMonths(Int32 months)
return Date(*this); // Return the date as is
}
// Extract the number of years
Int32 years = static_cast< Int32 >(months / 12);
auto years = static_cast< int32_t >(months / 12);
// Extract the number of months
months = (months % 12) + m_Month;
// Do we have extra months?
@ -310,16 +308,16 @@ Date Date::AndMonths(Int32 months)
// Are there any years to add?
if (years)
{
d.SetYear(ConvTo< Uint16 >::From(static_cast< Int32 >(m_Year) + years));
d.SetYear(ConvTo< uint16_t >::From(static_cast< int32_t >(m_Year) + years));
}
// Add the months
d.SetMonth(months);
d.SetMonth(static_cast< uint8_t >(months));
// Return the resulted date
return d;
}
// ------------------------------------------------------------------------------------------------
Date Date::AndDays(Int32 days)
Date Date::AndDays(int32_t days)
{
// Do we have a valid amount of days?
if (!days)
@ -327,26 +325,26 @@ Date Date::AndDays(Int32 days)
return Date(*this); // Return the date as is
}
// Whether the number of days is positive or negative
const Int32 dir = days > 0 ? 1 : -1;
const int32_t dir = days > 0 ? 1 : -1;
// Grab current year
Int32 year = m_Year;
int32_t year = m_Year;
// Calculate the days in the current year
Int32 diy = Chrono::DaysInYear(year);
int32_t diy = Chrono::DaysInYear(static_cast< uint16_t >(year));
// Calculate the day of year
Int32 doy = GetDayOfYear() + days;
int32_t doy = GetDayOfYear() + days;
// Calculate the resulting years
while (doy > diy || doy < 0)
{
doy -= diy * dir;
year += dir;
diy = Chrono::DaysInYear(year);
diy = Chrono::DaysInYear(static_cast< uint16_t >(year));
}
// Replicate the current date
Date d(*this);
// Set the obtained year
d.SetYear(year);
d.SetYear(static_cast< uint16_t >(year));
// Set the obtained day of year
d.SetDayOfYear(doy);
d.SetDayOfYear(static_cast< uint16_t >(doy));
// Return the resulted date
return d;
}
@ -355,14 +353,14 @@ Date Date::AndDays(Int32 days)
Timestamp Date::GetTimestamp() const
{
// Calculate the current day of the year
Int32 days = Chrono::DayOfYear(m_Year, m_Month, m_Day);
int32_t days = Chrono::DayOfYear(m_Year, m_Month, m_Day);
// Calculate all days till the current year
for (Int32 year = 0; year < m_Year; --year)
for (int32_t year = 0; year < m_Year; --year)
{
days += Chrono::DaysInYear(year);
days += Chrono::DaysInYear(static_cast< uint16_t >(year));
}
// Return the resulted timestamp
return Timestamp(static_cast< Int64 >(days * 86400000000LL));
return Timestamp(static_cast< int64_t >(days * 86400000000LL));
}
// ================================================================================================
@ -372,9 +370,9 @@ void Register_ChronoDate(HSQUIRRELVM vm, Table & /*cns*/)
Class< Date >(vm, Typename::Str)
// Constructors
.Ctor()
.Ctor< Uint16 >()
.Ctor< Uint16, Uint8 >()
.Ctor< Uint16, Uint8, Uint8 >()
.Ctor< uint16_t >()
.Ctor< uint16_t, uint8_t >()
.Ctor< uint16_t, uint8_t, uint8_t >()
// Static Properties
.SetStaticValue(_SC("GlobalDelimiter"), &Date::Delimiter)
// Core Meta-methods
@ -405,9 +403,9 @@ void Register_ChronoDate(HSQUIRRELVM vm, Table & /*cns*/)
.Func(_SC("AndMonths"), &Date::AndMonths)
.Func(_SC("AndDays"), &Date::AndDays)
// Overloaded Methods
.Overload< void (Date::*)(Uint16) >(_SC("Set"), &Date::Set)
.Overload< void (Date::*)(Uint16, Uint8) >(_SC("Set"), &Date::Set)
.Overload< void (Date::*)(Uint16, Uint8, Uint8) >(_SC("Set"), &Date::Set)
.Overload< void (Date::*)(uint16_t) >(_SC("Set"), &Date::Set)
.Overload< void (Date::*)(uint16_t, uint8_t) >(_SC("Set"), &Date::Set)
.Overload< void (Date::*)(uint16_t, uint8_t, uint8_t) >(_SC("Set"), &Date::Set)
);
}

View File

@ -19,9 +19,9 @@ public:
private:
// ------------------------------------------------------------------------------------------------
Uint16 m_Year; // Year
Uint8 m_Month; // Month
Uint8 m_Day; // Day
uint16_t m_Year{}; // Year
uint8_t m_Month{}; // Month
uint8_t m_Day{}; // Day
// ------------------------------------------------------------------------------------------------
SQChar m_Delimiter; // Component delimiter when generating strings.
@ -31,7 +31,7 @@ protected:
/* ------------------------------------------------------------------------------------------------
* Compare the values of two instances.
*/
Int32 Compare(const Date & o) const;
SQMOD_NODISCARD int32_t Compare(const Date & o) const;
public:
@ -48,27 +48,27 @@ public:
}
/* ------------------------------------------------------------------------------------------------
* Speciffic year constructor.
* Specific year constructor.
*/
Date(Uint16 year)
explicit Date(uint16_t year)
: m_Delimiter(Delimiter)
{
Set(year, 1, 1);
}
/* ------------------------------------------------------------------------------------------------
* Speciffic year and month constructor.
* Specific year and month constructor.
*/
Date(Uint16 year, Uint8 month)
Date(uint16_t year, uint8_t month)
: m_Delimiter(Delimiter)
{
Set(year, month, 1);
}
/* ------------------------------------------------------------------------------------------------
* Speciffic date constructor.
* Specific date constructor.
*/
Date(Uint16 year, Uint8 month, Uint8 day)
Date(uint16_t year, uint8_t month, uint8_t day)
: m_Delimiter(Delimiter)
{
Set(year, month, day);
@ -77,7 +77,7 @@ public:
/* ------------------------------------------------------------------------------------------------
* String constructor.
*/
Date(CSStr str)
explicit Date(const SQChar * str)
: m_Delimiter(Delimiter)
{
SetStr(str);
@ -179,7 +179,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Used by the script engine to compare two instances of this type.
*/
Int32 Cmp(const Date & o) const
SQMOD_NODISCARD int32_t Cmp(const Date & o) const
{
return Compare(o);
}
@ -187,12 +187,12 @@ public:
/* --------------------------------------------------------------------------------------------
* Used by the script engine to convert an instance of this type to a string.
*/
CSStr ToString() const;
SQMOD_NODISCARD String ToString() const;
/* ------------------------------------------------------------------------------------------------
* Assign the specified values.
*/
void Set(Uint16 year)
void Set(uint16_t year)
{
Set(year, m_Month, m_Day);
}
@ -200,7 +200,7 @@ public:
/* ------------------------------------------------------------------------------------------------
* Assign the specified values.
*/
void Set(Uint16 year, Uint8 month)
void Set(uint16_t year, uint8_t month)
{
Set(year, month, m_Day);
}
@ -208,12 +208,12 @@ public:
/* ------------------------------------------------------------------------------------------------
* Assign the specified values.
*/
void Set(Uint16 year, Uint8 month, Uint8 day);
void Set(uint16_t year, uint8_t month, uint8_t day);
/* ------------------------------------------------------------------------------------------------
* Retrieve the local delimiter character.
*/
SQChar GetDelimiter() const
SQMOD_NODISCARD SQChar GetDelimiter() const
{
return m_Delimiter;
}
@ -229,7 +229,7 @@ public:
/* ------------------------------------------------------------------------------------------------
* Retrieve the values as a string.
*/
CSStr GetStr() const
SQMOD_NODISCARD String GetStr() const
{
return ToString();
}
@ -237,12 +237,12 @@ public:
/* ------------------------------------------------------------------------------------------------
* Extract the values from a string.
*/
void SetStr(CSStr str);
void SetStr(const SQChar * str);
/* ------------------------------------------------------------------------------------------------
* Retrieve the day component.
*/
Uint16 GetDayOfYear() const
SQMOD_NODISCARD uint16_t GetDayOfYear() const
{
return Chrono::DayOfYear(m_Year, m_Month, m_Day);
}
@ -250,12 +250,12 @@ public:
/* ------------------------------------------------------------------------------------------------
* Modify the day component.
*/
void SetDayOfYear(Uint16 doy);
void SetDayOfYear(uint16_t doy);
/* ------------------------------------------------------------------------------------------------
* Retrieve the year component.
*/
Uint16 GetYear() const
SQMOD_NODISCARD uint16_t GetYear() const
{
return m_Year;
}
@ -263,12 +263,12 @@ public:
/* ------------------------------------------------------------------------------------------------
* Modify the year component.
*/
void SetYear(Uint16 year);
void SetYear(uint16_t year);
/* ------------------------------------------------------------------------------------------------
* Retrieve the month component.
*/
Uint8 GetMonth() const
SQMOD_NODISCARD uint8_t GetMonth() const
{
return m_Month;
}
@ -276,12 +276,12 @@ public:
/* ------------------------------------------------------------------------------------------------
* Modify the month component.
*/
void SetMonth(Uint8 month);
void SetMonth(uint8_t month);
/* ------------------------------------------------------------------------------------------------
* Retrieve the day component.
*/
Uint8 GetDay() const
SQMOD_NODISCARD uint8_t GetDay() const
{
return m_Day;
}
@ -289,42 +289,42 @@ public:
/* ------------------------------------------------------------------------------------------------
* Modify the day component.
*/
void SetDay(Uint8 day);
void SetDay(uint8_t day);
/* ------------------------------------------------------------------------------------------------
* Add the specified amount of years to the current date.
*/
Date & AddYears(Int32 years);
Date & AddYears(int32_t years);
/* ------------------------------------------------------------------------------------------------
* Add the specified amount of months to the current date.
*/
Date & AddMonths(Int32 months);
Date & AddMonths(int32_t months);
/* ------------------------------------------------------------------------------------------------
* Add the specified amount of days to the current date.
*/
Date & AddDays(Int32 days);
Date & AddDays(int32_t days);
/* ------------------------------------------------------------------------------------------------
* Add the specified amount of years to obtain a new date.
*/
Date AndYears(Int32 years);
SQMOD_NODISCARD Date AndYears(int32_t years);
/* ------------------------------------------------------------------------------------------------
* Add the specified amount of months to obtain a new date.
*/
Date AndMonths(Int32 months);
SQMOD_NODISCARD Date AndMonths(int32_t months);
/* ------------------------------------------------------------------------------------------------
* Add the specified amount of days to obtain a new date.
*/
Date AndDays(Int32 days);
SQMOD_NODISCARD Date AndDays(int32_t days);
/* ------------------------------------------------------------------------------------------------
* See whether the associated year is a leap year.
*/
bool IsThisLeapYear() const
SQMOD_NODISCARD bool IsThisLeapYear() const
{
return Chrono::IsLeapYear(m_Year);
}
@ -332,7 +332,7 @@ public:
/* ------------------------------------------------------------------------------------------------
* Retrieve the number of days in the associated year.
*/
Uint16 GetYearDays() const
SQMOD_NODISCARD uint16_t GetYearDays() const
{
return Chrono::DaysInYear(m_Year);
}
@ -340,7 +340,7 @@ public:
/* ------------------------------------------------------------------------------------------------
* Retrieve the number of days in the associated month.
*/
Uint8 GetMonthDays() const
SQMOD_NODISCARD uint8_t GetMonthDays() const
{
return Chrono::DaysInMonth(m_Year, m_Month);
}
@ -348,7 +348,7 @@ public:
/* ------------------------------------------------------------------------------------------------
* Convert this date instance to a time-stamp.
*/
Timestamp GetTimestamp() const;
SQMOD_NODISCARD Timestamp GetTimestamp() const;
};
} // Namespace:: SqMod

View File

@ -3,13 +3,13 @@
#include "Library/Chrono/Date.hpp"
#include "Library/Chrono/Time.hpp"
#include "Library/Chrono/Timestamp.hpp"
#include "Base/Shared.hpp"
#include "Core/Utility.hpp"
// ------------------------------------------------------------------------------------------------
namespace SqMod {
// ------------------------------------------------------------------------------------------------
SQMODE_DECL_TYPENAME(Typename, _SC("SqDatetime"))
SQMOD_DECL_TYPENAME(Typename, _SC("SqDatetime"))
// ------------------------------------------------------------------------------------------------
SQChar Datetime::Delimiter = ' ';
@ -17,14 +17,14 @@ SQChar Datetime::DateDelim = '-';
SQChar Datetime::TimeDelim = ':';
// ------------------------------------------------------------------------------------------------
Int32 Datetime::Compare(const Datetime & o) const
int32_t Datetime::Compare(const Datetime & o) const
{
if (m_Year < o.m_Year)
{
{ // NOLINT(bugprone-branch-clone)
return -1;
}
else if (m_Year > o.m_Year)
{
{ // NOLINT(bugprone-branch-clone)
return 1;
}
else if (m_Month < o.m_Month)
@ -107,9 +107,9 @@ Datetime Datetime::operator / (const Datetime & o) const
}
// ------------------------------------------------------------------------------------------------
CSStr Datetime::ToString() const
String Datetime::ToString() const
{
return ToStrF("%04u%c%02u%c%02u%c%02u%c%02u%c%02u%c%u"
return fmt::format("{:04}{}{:02}{}{:02}{}{:02}{}{:02}{}{:02}{}{}"
, m_Year, m_DateDelim, m_Month, m_DateDelim, m_Day
, m_Delimiter
, m_Hour, m_TimeDelim, m_Minute, m_TimeDelim, m_Second , m_TimeDelim, m_Millisecond
@ -117,7 +117,7 @@ CSStr Datetime::ToString() const
}
// ------------------------------------------------------------------------------------------------
void Datetime::Set(Uint16 year, Uint8 month, Uint8 day, Uint8 hour, Uint8 minute, Uint8 second, Uint16 millisecond)
void Datetime::Set(uint16_t year, uint8_t month, uint8_t day, uint8_t hour, uint8_t minute, uint8_t second, uint16_t millisecond)
{
// Validate the specified date
if (!Chrono::ValidDate(year, month, day))
@ -159,7 +159,7 @@ void Datetime::Set(Uint16 year, Uint8 month, Uint8 day, Uint8 hour, Uint8 minute
}
// ------------------------------------------------------------------------------------------------
void Datetime::SetStr(CSStr str)
void Datetime::SetStr(const SQChar * str)
{
// The format specifications that will be used to scan the string
static SQChar fs[] = _SC(" %u - %u - %u %u : %u : %u : %u ");
@ -185,25 +185,25 @@ void Datetime::SetStr(CSStr str)
fs[24] = m_TimeDelim;
fs[29] = m_TimeDelim;
// The sscanf function requires at least 32 bit integers
Uint32 year = 0, month = 0, day = 0, hour = 0, minute = 0, second = 0, milli = 0;
uint32_t year = 0, month = 0, day = 0, hour = 0, minute = 0, second = 0, milli = 0;
// Attempt to extract the component values from the specified string
sscanf(str, fs, &year, &month, &day, &hour, &minute, &second, &milli);
// Clamp the extracted values to the boundaries of associated type and assign them
Set(ClampL< Uint32, Uint8 >(year),
ClampL< Uint32, Uint8 >(month),
ClampL< Uint32, Uint8 >(day),
ClampL< Uint32, Uint8 >(hour),
ClampL< Uint32, Uint8 >(minute),
ClampL< Uint32, Uint8 >(second),
ClampL< Uint32, Uint16 >(milli)
Set(ClampL< uint32_t, uint8_t >(year),
ClampL< uint32_t, uint8_t >(month),
ClampL< uint32_t, uint8_t >(day),
ClampL< uint32_t, uint8_t >(hour),
ClampL< uint32_t, uint8_t >(minute),
ClampL< uint32_t, uint8_t >(second),
ClampL< uint32_t, uint16_t >(milli)
);
}
// ------------------------------------------------------------------------------------------------
void Datetime::SetDayOfYear(Uint16 doy)
void Datetime::SetDayOfYear(uint16_t doy)
{
// Reverse the given day of year to a full date
Date d = Chrono::ReverseDayOfyear(m_Year, doy);
Date d = Chrono::ReverseDayOfYear(m_Year, doy);
// Set the obtained month
SetMonth(d.GetMonth());
// Set the obtained day
@ -211,7 +211,7 @@ void Datetime::SetDayOfYear(Uint16 doy)
}
// ------------------------------------------------------------------------------------------------
void Datetime::SetYear(Uint16 year)
void Datetime::SetYear(uint16_t year)
{
// Make sure the year is valid
if (!year)
@ -229,7 +229,7 @@ void Datetime::SetYear(Uint16 year)
}
// ------------------------------------------------------------------------------------------------
void Datetime::SetMonth(Uint8 month)
void Datetime::SetMonth(uint8_t month)
{
// Make sure the month is valid
if (month == 0 || month > 12)
@ -246,10 +246,10 @@ void Datetime::SetMonth(Uint8 month)
}
// ------------------------------------------------------------------------------------------------
void Datetime::SetDay(Uint8 day)
void Datetime::SetDay(uint8_t day)
{
// Grab the amount of days in the current month
const Uint8 dim = Chrono::DaysInMonth(m_Year, m_Month);
const uint8_t dim = Chrono::DaysInMonth(m_Year, m_Month);
// Make sure the day is valid
if (day == 0)
{
@ -264,7 +264,7 @@ void Datetime::SetDay(Uint8 day)
}
// ------------------------------------------------------------------------------------------------
void Datetime::SetHour(Uint8 hour)
void Datetime::SetHour(uint8_t hour)
{
// Is the specified hour within range?
if (hour >= 24)
@ -276,7 +276,7 @@ void Datetime::SetHour(Uint8 hour)
}
// ------------------------------------------------------------------------------------------------
void Datetime::SetMinute(Uint8 minute)
void Datetime::SetMinute(uint8_t minute)
{
// Is the specified minute within range?
if (minute >= 60)
@ -288,7 +288,7 @@ void Datetime::SetMinute(Uint8 minute)
}
// ------------------------------------------------------------------------------------------------
void Datetime::SetSecond(Uint8 second)
void Datetime::SetSecond(uint8_t second)
{
// Is the specified second within range?
if (second >= 60)
@ -300,7 +300,7 @@ void Datetime::SetSecond(Uint8 second)
}
// ------------------------------------------------------------------------------------------------
void Datetime::SetMillisecond(Uint16 millisecond)
void Datetime::SetMillisecond(uint16_t millisecond)
{
// Is the specified millisecond within range?
if (millisecond >= 1000)
@ -312,26 +312,26 @@ void Datetime::SetMillisecond(Uint16 millisecond)
}
// ------------------------------------------------------------------------------------------------
Datetime & Datetime::AddYears(Int32 years)
Datetime & Datetime::AddYears(int32_t years)
{
// Do we have a valid amount of years?
if (years)
{
// Add the specified amount of years
SetYear(ConvTo< Uint16 >::From(static_cast< Int32 >(m_Year) + years));
SetYear(ConvTo< uint16_t >::From(static_cast< int32_t >(m_Year) + years));
}
// Allow chaining operations
return *this;
}
// ------------------------------------------------------------------------------------------------
Datetime & Datetime::AddMonths(Int32 months)
Datetime & Datetime::AddMonths(int32_t months)
{
// Do we have a valid amount of months?
if (months)
{
// Extract the number of years
Int32 years = static_cast< Int32 >(months / 12);
auto years = static_cast< int32_t >(months / 12);
// Extract the number of months
months = (months % 12) + m_Month;
// Do we have extra months?
@ -352,53 +352,53 @@ Datetime & Datetime::AddMonths(Int32 months)
// Are there any years to add?
if (years)
{
SetYear(ConvTo< Uint16 >::From(static_cast< Int32 >(m_Year) + years));
SetYear(ConvTo< uint16_t >::From(static_cast< int32_t >(m_Year) + years));
}
// Add the months
SetMonth(months);
SetMonth(static_cast< uint8_t >(months));
}
// Allow chaining operations
return *this;
}
// ------------------------------------------------------------------------------------------------
Datetime & Datetime::AddDays(Int32 days)
Datetime & Datetime::AddDays(int32_t days)
{
// Do we have a valid amount of days?
if (days)
{
// Whether the number of days is positive or negative
const Int32 dir = days > 0 ? 1 : -1;
const int32_t dir = days > 0 ? 1 : -1;
// Grab current year
Int32 year = m_Year;
int32_t year = m_Year;
// Calculate the days in the current year
Int32 diy = Chrono::DaysInYear(year);
int32_t diy = Chrono::DaysInYear(static_cast< uint16_t >(year));
// Calculate the day of year
Int32 doy = GetDayOfYear() + days;
int32_t doy = GetDayOfYear() + days;
// Calculate the resulting years
while (doy > diy || doy < 0)
{
doy -= diy * dir;
year += dir;
diy = Chrono::DaysInYear(year);
diy = Chrono::DaysInYear(static_cast< uint16_t >(year));
}
// Set the obtained year
SetYear(year);
SetYear(static_cast< uint16_t >(year));
// Set the obtained day of year
SetDayOfYear(doy);
SetDayOfYear(static_cast< uint16_t >(doy));
}
// Allow chaining operations
return *this;
}
// ------------------------------------------------------------------------------------------------
Datetime & Datetime::AddHours(Int32 hours)
Datetime & Datetime::AddHours(int32_t hours)
{
// Did we even add any hours?
if (hours)
{
// Extract the number of days
Int32 days = static_cast< Int32 >(hours / 24);
auto days = static_cast< int32_t >(hours / 24);
// Extract the number of hours
m_Hour += (hours % 24);
// Are the hours overlapping with the next day?
@ -420,13 +420,13 @@ Datetime & Datetime::AddHours(Int32 hours)
}
// ------------------------------------------------------------------------------------------------
Datetime & Datetime::AddMinutes(Int32 minutes)
Datetime & Datetime::AddMinutes(int32_t minutes)
{
// Did we even add any minutes?
if (minutes)
{
// Extract the number of hours
Int32 hours = static_cast< Int32 >(minutes / 60);
auto hours = static_cast< int32_t >(minutes / 60);
// Extract the number of minutes
m_Minute += (minutes % 60);
// Are the minutes overlapping with the next hour?
@ -448,13 +448,13 @@ Datetime & Datetime::AddMinutes(Int32 minutes)
}
// ------------------------------------------------------------------------------------------------
Datetime & Datetime::AddSeconds(Int32 seconds)
Datetime & Datetime::AddSeconds(int32_t seconds)
{
// Did we even add any seconds?
if (seconds)
{
// Extract the number of minutes
Int32 minutes = static_cast< Int32 >(seconds / 60);
auto minutes = static_cast< int32_t >(seconds / 60);
// Extract the number of seconds
m_Second += (seconds % 60);
// Are the seconds overlapping with the next minute?
@ -476,13 +476,13 @@ Datetime & Datetime::AddSeconds(Int32 seconds)
}
// ------------------------------------------------------------------------------------------------
Datetime & Datetime::AddMilliseconds(Int32 milliseconds)
Datetime & Datetime::AddMilliseconds(int32_t milliseconds)
{
// Did we even add any milliseconds?
if (milliseconds)
{
// Extract the number of seconds
Int32 seconds = static_cast< Int32 >(milliseconds / 1000);
auto seconds = static_cast< int32_t >(milliseconds / 1000);
// Extract the number of milliseconds
m_Millisecond += (milliseconds / 1000);
// Are the milliseconds overlapping with the next second?
@ -504,7 +504,7 @@ Datetime & Datetime::AddMilliseconds(Int32 milliseconds)
}
// ------------------------------------------------------------------------------------------------
Datetime Datetime::AndYears(Int32 years)
Datetime Datetime::AndYears(int32_t years)
{
// Do we have a valid amount of years?
if (!years)
@ -514,13 +514,13 @@ Datetime Datetime::AndYears(Int32 years)
// Replicate the current date
Datetime dt(*this);
// Add the specified amount of years
dt.SetYear(ConvTo< Uint16 >::From(static_cast< Int32 >(m_Year) + years));
dt.SetYear(ConvTo< uint16_t >::From(static_cast< int32_t >(m_Year) + years));
// Return the resulted date
return dt;
}
// ------------------------------------------------------------------------------------------------
Datetime Datetime::AndMonths(Int32 months)
Datetime Datetime::AndMonths(int32_t months)
{
// Do we have a valid amount of months?
if (!months)
@ -528,7 +528,7 @@ Datetime Datetime::AndMonths(Int32 months)
return Datetime(*this); // Return the date-time as is
}
// Extract the number of years
Int32 years = static_cast< Int32 >(months / 12);
auto years = static_cast< int32_t >(months / 12);
// Extract the number of months
months = (months % 12) + m_Month;
// Do we have extra months?
@ -551,16 +551,16 @@ Datetime Datetime::AndMonths(Int32 months)
// Are there any years to add?
if (years)
{
dt.SetYear(ConvTo< Uint16 >::From(static_cast< Int32 >(m_Year) + years));
dt.SetYear(ConvTo< uint16_t >::From(static_cast< int32_t >(m_Year) + years));
}
// Add the months
dt.SetMonth(months);
dt.SetMonth(static_cast< uint8_t >(months));
// Return the resulted date
return dt;
}
// ------------------------------------------------------------------------------------------------
Datetime Datetime::AndDays(Int32 days)
Datetime Datetime::AndDays(int32_t days)
{
// Do we have a valid amount of days?
if (!days)
@ -568,32 +568,32 @@ Datetime Datetime::AndDays(Int32 days)
return Datetime(*this); // Return the date-time as is
}
// Whether the number of days is positive or negative
const Int32 dir = days > 0 ? 1 : -1;
const int32_t dir = days > 0 ? 1 : -1;
// Grab current year
Int32 year = m_Year;
int32_t year = m_Year;
// Calculate the days in the current year
Int32 diy = Chrono::DaysInYear(year);
int32_t diy = Chrono::DaysInYear(static_cast< uint16_t >(year));
// Calculate the day of year
Int32 doy = GetDayOfYear() + days;
int32_t doy = GetDayOfYear() + days;
// Calculate the resulting years
while (doy > diy || doy < 0)
{
doy -= diy * dir;
year += dir;
diy = Chrono::DaysInYear(year);
diy = Chrono::DaysInYear(static_cast< uint16_t >(year));
}
// Replicate the current date
Datetime dt(*this);
// Set the obtained year
dt.SetYear(year);
dt.SetYear(static_cast< uint16_t >(year));
// Set the obtained day of year
dt.SetDayOfYear(doy);
dt.SetDayOfYear(static_cast< uint16_t >(doy));
// Return the resulted date
return dt;
}
// ------------------------------------------------------------------------------------------------
Datetime Datetime::AndHours(Int32 hours)
Datetime Datetime::AndHours(int32_t hours)
{
// Did we even add any hours?
if (!hours)
@ -601,7 +601,7 @@ Datetime Datetime::AndHours(Int32 hours)
return Datetime(*this); // Return the date-time as is
}
// Extract the number of days
Int32 days = static_cast< Int32 >(hours / 24);
auto days = static_cast< int32_t >(hours / 24);
// Extract the number of hours
hours = m_Hour + (hours % 24);
// Are the hours overlapping with the next day?
@ -617,13 +617,13 @@ Datetime Datetime::AndHours(Int32 hours)
dt.AddDays(days);
}
// Assign the resulted hours
dt.m_Hour = (hours % 24);
dt.m_Hour = static_cast< uint8_t >(hours % 24);
// Return the result
return dt;
}
// ------------------------------------------------------------------------------------------------
Datetime Datetime::AndMinutes(Int32 minutes)
Datetime Datetime::AndMinutes(int32_t minutes)
{
// Did we even added any minutes?
if (!minutes)
@ -631,7 +631,7 @@ Datetime Datetime::AndMinutes(Int32 minutes)
return Datetime(*this); // Return the date-time as is
}
// Extract the number of hours
Int32 hours = static_cast< Int32 >(minutes / 60);
auto hours = static_cast< int32_t >(minutes / 60);
// Extract the number of minutes
minutes = m_Minute + (minutes % 60);
// Are the minutes overlapping with the next hour?
@ -647,13 +647,13 @@ Datetime Datetime::AndMinutes(Int32 minutes)
dt.AddHours(hours);
}
// Assign the resulted minutes
dt.m_Minute = (minutes % 60);
dt.m_Minute = static_cast< uint8_t >(minutes % 60);
// Return the result
return dt;
}
// ------------------------------------------------------------------------------------------------
Datetime Datetime::AndSeconds(Int32 seconds)
Datetime Datetime::AndSeconds(int32_t seconds)
{
// Did we even added any seconds?
if (!seconds)
@ -661,7 +661,7 @@ Datetime Datetime::AndSeconds(Int32 seconds)
return Datetime(*this); // Return the date-time as is
}
// Extract the number of minutes
Int32 minutes = static_cast< Int32 >(seconds / 60);
auto minutes = static_cast< int32_t >(seconds / 60);
// Extract the number of seconds
seconds = m_Second + (seconds % 60);
// Are the seconds overlapping with the next minute?
@ -677,13 +677,13 @@ Datetime Datetime::AndSeconds(Int32 seconds)
dt.AddMinutes(minutes);
}
// Assign the resulted seconds
dt.m_Second = (seconds % 60);
dt.m_Second = static_cast< uint8_t >(seconds % 60);
// Return the result
return dt;
}
// ------------------------------------------------------------------------------------------------
Datetime Datetime::AndMilliseconds(Int32 milliseconds)
Datetime Datetime::AndMilliseconds(int32_t milliseconds)
{
// Did we even added any milliseconds?
if (!milliseconds)
@ -691,7 +691,7 @@ Datetime Datetime::AndMilliseconds(Int32 milliseconds)
return Datetime(*this); // Return the date-time as is
}
// Extract the number of seconds
Int32 seconds = static_cast< Int32 >(milliseconds / 1000);
auto seconds = static_cast< int32_t >(milliseconds / 1000);
// Extract the number of milliseconds
milliseconds = m_Millisecond + (milliseconds % 1000);
// Are the milliseconds overlapping with the next second?
@ -707,7 +707,7 @@ Datetime Datetime::AndMilliseconds(Int32 milliseconds)
dt.AddSeconds(seconds);
}
// Assign the resulted milliseconds
dt.m_Millisecond = (milliseconds % 1000);
dt.m_Millisecond = static_cast< uint16_t >(milliseconds % 1000);
// Return the result
return dt;
}
@ -728,19 +728,19 @@ Time Datetime::GetTime() const
Timestamp Datetime::GetTimestamp() const
{
// Calculate the current day of the year
Int32 days = Chrono::DayOfYear(m_Year, m_Month, m_Day);
int32_t days = Chrono::DayOfYear(m_Year, m_Month, m_Day);
// Calculate all days till the current year
for (Int32 year = 0; year < m_Year; --year)
for (int32_t year = 0; year < m_Year; --year)
{
days += Chrono::DaysInYear(year);
days += Chrono::DaysInYear(static_cast< uint16_t >(year));
}
// Calculate the microseconds in the resulted days
Int64 ms = static_cast< Int64 >(days * 86400000000LL);
auto ms = static_cast< int64_t >(days * 86400000000LL);
// Calculate the microseconds in the current time
ms += static_cast< Int64 >(m_Hour * 3600000000LL);
ms += static_cast< Int64 >(m_Minute * 60000000L);
ms += static_cast< Int64 >(m_Second * 1000000L);
ms += static_cast< Int64 >(m_Millisecond * 1000L);
ms += static_cast< int64_t >(m_Hour * 3600000000LL);
ms += static_cast< int64_t >(m_Minute * 60000000L);
ms += static_cast< int64_t >(m_Second * 1000000L);
ms += static_cast< int64_t >(m_Millisecond * 1000L);
// Return the resulted timestamp
return Timestamp(ms);
}
@ -752,13 +752,13 @@ void Register_ChronoDatetime(HSQUIRRELVM vm, Table & /*cns*/)
Class< Datetime >(vm, Typename::Str)
// Constructors
.Ctor()
.Ctor< Uint16 >()
.Ctor< Uint16, Uint8 >()
.Ctor< Uint16, Uint8, Uint8 >()
.Ctor< Uint16, Uint8, Uint8, Uint8 >()
.Ctor< Uint16, Uint8, Uint8, Uint8, Uint8 >()
.Ctor< Uint16, Uint8, Uint8, Uint8, Uint8, Uint8 >()
.Ctor< Uint16, Uint8, Uint8, Uint8, Uint8, Uint8, Uint16 >()
.Ctor< uint16_t >()
.Ctor< uint16_t, uint8_t >()
.Ctor< uint16_t, uint8_t, uint8_t >()
.Ctor< uint16_t, uint8_t, uint8_t, uint8_t >()
.Ctor< uint16_t, uint8_t, uint8_t, uint8_t, uint8_t >()
.Ctor< uint16_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t >()
.Ctor< uint16_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint16_t >()
// Static Properties
.SetStaticValue(_SC("GlobalDelimiter"), &Datetime::Delimiter)
.SetStaticValue(_SC("GlobalDateDelim"), &Datetime::DateDelim)
@ -809,13 +809,13 @@ void Register_ChronoDatetime(HSQUIRRELVM vm, Table & /*cns*/)
.Func(_SC("AndMillis"), &Datetime::AndMilliseconds)
.Func(_SC("AndMilliseconds"), &Datetime::AndMilliseconds)
// Overloaded Methods
.Overload< void (Datetime::*)(Uint16) >(_SC("Set"), &Datetime::Set)
.Overload< void (Datetime::*)(Uint16, Uint8) >(_SC("Set"), &Datetime::Set)
.Overload< void (Datetime::*)(Uint16, Uint8, Uint8) >(_SC("Set"), &Datetime::Set)
.Overload< void (Datetime::*)(Uint16, Uint8, Uint8, Uint8) >(_SC("Set"), &Datetime::Set)
.Overload< void (Datetime::*)(Uint16, Uint8, Uint8, Uint8, Uint8) >(_SC("Set"), &Datetime::Set)
.Overload< void (Datetime::*)(Uint16, Uint8, Uint8, Uint8, Uint8, Uint8) >(_SC("Set"), &Datetime::Set)
.Overload< void (Datetime::*)(Uint16, Uint8, Uint8, Uint8, Uint8, Uint8, Uint16) >(_SC("Set"), &Datetime::Set)
.Overload< void (Datetime::*)(uint16_t) >(_SC("Set"), &Datetime::Set)
.Overload< void (Datetime::*)(uint16_t, uint8_t) >(_SC("Set"), &Datetime::Set)
.Overload< void (Datetime::*)(uint16_t, uint8_t, uint8_t) >(_SC("Set"), &Datetime::Set)
.Overload< void (Datetime::*)(uint16_t, uint8_t, uint8_t, uint8_t) >(_SC("Set"), &Datetime::Set)
.Overload< void (Datetime::*)(uint16_t, uint8_t, uint8_t, uint8_t, uint8_t) >(_SC("Set"), &Datetime::Set)
.Overload< void (Datetime::*)(uint16_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t) >(_SC("Set"), &Datetime::Set)
.Overload< void (Datetime::*)(uint16_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint16_t) >(_SC("Set"), &Datetime::Set)
);
}

View File

@ -21,15 +21,15 @@ public:
private:
// ------------------------------------------------------------------------------------------------
Uint16 m_Year; // Year
Uint8 m_Month; // Month
Uint8 m_Day; // Day
uint16_t m_Year{}; // Year
uint8_t m_Month{}; // Month
uint8_t m_Day{}; // Day
// ------------------------------------------------------------------------------------------------
Uint8 m_Hour; // Hour
Uint8 m_Minute; // Minute
Uint8 m_Second; // Second
Uint16 m_Millisecond; // Millisecond
uint8_t m_Hour{}; // Hour
uint8_t m_Minute{}; // Minute
uint8_t m_Second{}; // Second
uint16_t m_Millisecond{}; // Millisecond
// ------------------------------------------------------------------------------------------------
SQChar m_Delimiter; // Date and time delimiter when generating strings.
@ -41,7 +41,7 @@ protected:
/* ------------------------------------------------------------------------------------------------
* Compare the values of two instances.
*/
Int32 Compare(const Datetime & o) const;
SQMOD_NODISCARD int32_t Compare(const Datetime & o) const;
public:
@ -64,9 +64,9 @@ public:
}
/* ------------------------------------------------------------------------------------------------
* Speciffic year constructor.
* Specific year constructor.
*/
Datetime(Uint16 year)
explicit Datetime(uint16_t year)
: m_Delimiter(Delimiter)
, m_DateDelim(DateDelim)
, m_TimeDelim(TimeDelim)
@ -75,9 +75,9 @@ public:
}
/* ------------------------------------------------------------------------------------------------
* Speciffic year and month constructor.
* Specific year and month constructor.
*/
Datetime(Uint16 year, Uint8 month)
Datetime(uint16_t year, uint8_t month)
: m_Delimiter(Delimiter)
, m_DateDelim(DateDelim)
, m_TimeDelim(TimeDelim)
@ -86,9 +86,9 @@ public:
}
/* ------------------------------------------------------------------------------------------------
* Speciffic date constructor.
* Specific date constructor.
*/
Datetime(Uint16 year, Uint8 month, Uint8 day)
Datetime(uint16_t year, uint8_t month, uint8_t day)
: m_Delimiter(Delimiter)
, m_DateDelim(DateDelim)
, m_TimeDelim(TimeDelim)
@ -97,9 +97,9 @@ public:
}
/* ------------------------------------------------------------------------------------------------
* Speciffic date and hour constructor.
* Specific date and hour constructor.
*/
Datetime(Uint16 year, Uint8 month, Uint8 day, Uint8 hour)
Datetime(uint16_t year, uint8_t month, uint8_t day, uint8_t hour)
: m_Delimiter(Delimiter)
, m_DateDelim(DateDelim)
, m_TimeDelim(TimeDelim)
@ -108,9 +108,9 @@ public:
}
/* ------------------------------------------------------------------------------------------------
* Speciffic date, hour and minute constructor.
* Specific date, hour and minute constructor.
*/
Datetime(Uint16 year, Uint8 month, Uint8 day, Uint8 hour, Uint8 minute)
Datetime(uint16_t year, uint8_t month, uint8_t day, uint8_t hour, uint8_t minute)
: m_Delimiter(Delimiter)
, m_DateDelim(DateDelim)
, m_TimeDelim(TimeDelim)
@ -119,9 +119,9 @@ public:
}
/* ------------------------------------------------------------------------------------------------
* Speciffic date and time constructor.
* Specific date and time constructor.
*/
Datetime(Uint16 year, Uint8 month, Uint8 day, Uint8 hour, Uint8 minute, Uint8 second)
Datetime(uint16_t year, uint8_t month, uint8_t day, uint8_t hour, uint8_t minute, uint8_t second)
: m_Delimiter(Delimiter)
, m_DateDelim(DateDelim)
, m_TimeDelim(TimeDelim)
@ -130,9 +130,9 @@ public:
}
/* ------------------------------------------------------------------------------------------------
* Speciffic date and precise time constructor.
* Specific date and precise time constructor.
*/
Datetime(Uint16 year, Uint8 month, Uint8 day, Uint8 hour, Uint8 minute, Uint8 second, Uint16 millisecond)
Datetime(uint16_t year, uint8_t month, uint8_t day, uint8_t hour, uint8_t minute, uint8_t second, uint16_t millisecond)
: m_Delimiter(Delimiter)
, m_DateDelim(DateDelim)
, m_TimeDelim(TimeDelim)
@ -236,7 +236,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Used by the script engine to compare two instances of this type.
*/
Int32 Cmp(const Datetime & o) const
SQMOD_NODISCARD int32_t Cmp(const Datetime & o) const
{
return Compare(o);
}
@ -244,12 +244,12 @@ public:
/* --------------------------------------------------------------------------------------------
* Used by the script engine to convert an instance of this type to a string.
*/
CSStr ToString() const;
SQMOD_NODISCARD String ToString() const;
/* ------------------------------------------------------------------------------------------------
* Assign the specified values.
*/
void Set(Uint16 year)
void Set(uint16_t year)
{
Set(year, m_Month, m_Day, m_Hour, m_Minute, m_Second, m_Millisecond);
}
@ -257,7 +257,7 @@ public:
/* ------------------------------------------------------------------------------------------------
* Assign the specified values.
*/
void Set(Uint16 year, Uint8 month)
void Set(uint16_t year, uint8_t month)
{
Set(year, month, m_Day, m_Hour, m_Minute, m_Second, m_Millisecond);
}
@ -265,7 +265,7 @@ public:
/* ------------------------------------------------------------------------------------------------
* Assign the specified values.
*/
void Set(Uint16 year, Uint8 month, Uint8 day)
void Set(uint16_t year, uint8_t month, uint8_t day)
{
Set(year, month, day, m_Hour, m_Minute, m_Second, m_Millisecond);
}
@ -273,7 +273,7 @@ public:
/* ------------------------------------------------------------------------------------------------
* Assign the specified values.
*/
void Set(Uint16 year, Uint8 month, Uint8 day, Uint8 hour)
void Set(uint16_t year, uint8_t month, uint8_t day, uint8_t hour)
{
Set(year, month, day, hour, m_Minute, m_Second, m_Millisecond);
}
@ -281,7 +281,7 @@ public:
/* ------------------------------------------------------------------------------------------------
* Assign the specified values.
*/
void Set(Uint16 year, Uint8 month, Uint8 day, Uint8 hour, Uint8 minute)
void Set(uint16_t year, uint8_t month, uint8_t day, uint8_t hour, uint8_t minute)
{
Set(year, month, day, hour, minute, m_Second, m_Millisecond);
}
@ -289,7 +289,7 @@ public:
/* ------------------------------------------------------------------------------------------------
* Assign the specified values.
*/
void Set(Uint16 year, Uint8 month, Uint8 day, Uint8 hour, Uint8 minute, Uint8 second)
void Set(uint16_t year, uint8_t month, uint8_t day, uint8_t hour, uint8_t minute, uint8_t second)
{
Set(year, month, day, hour, minute, second, m_Millisecond);
}
@ -297,12 +297,12 @@ public:
/* ------------------------------------------------------------------------------------------------
* Assign the specified values.
*/
void Set(Uint16 year, Uint8 month, Uint8 day, Uint8 hour, Uint8 minute, Uint8 second, Uint16 millisecond);
void Set(uint16_t year, uint8_t month, uint8_t day, uint8_t hour, uint8_t minute, uint8_t second, uint16_t millisecond);
/* ------------------------------------------------------------------------------------------------
* Retrieve the local delimiter character.
*/
SQChar GetDelimiter() const
SQMOD_NODISCARD SQChar GetDelimiter() const
{
return m_Delimiter;
}
@ -318,7 +318,7 @@ public:
/* ------------------------------------------------------------------------------------------------
* Retrieve the local date delimiter character.
*/
SQChar GetDateDelim() const
SQMOD_NODISCARD SQChar GetDateDelim() const
{
return m_DateDelim;
}
@ -334,7 +334,7 @@ public:
/* ------------------------------------------------------------------------------------------------
* Retrieve the local time delimiter character.
*/
SQChar GetTimeDelim() const
SQMOD_NODISCARD SQChar GetTimeDelim() const
{
return m_TimeDelim;
}
@ -350,7 +350,7 @@ public:
/* ------------------------------------------------------------------------------------------------
* Retrieve the values as a string.
*/
CSStr GetStr() const
SQMOD_NODISCARD String GetStr() const
{
return ToString();
}
@ -358,12 +358,12 @@ public:
/* ------------------------------------------------------------------------------------------------
* Extract the values from a string.
*/
void SetStr(CSStr str);
void SetStr(const SQChar * str);
/* ------------------------------------------------------------------------------------------------
* Retrieve the day component.
*/
Uint16 GetDayOfYear() const
SQMOD_NODISCARD uint16_t GetDayOfYear() const
{
return Chrono::DayOfYear(m_Year, m_Month, m_Day);
}
@ -371,12 +371,12 @@ public:
/* ------------------------------------------------------------------------------------------------
* Modify the day component.
*/
void SetDayOfYear(Uint16 doy);
void SetDayOfYear(uint16_t doy);
/* ------------------------------------------------------------------------------------------------
* Retrieve the year component.
*/
Uint16 GetYear() const
SQMOD_NODISCARD uint16_t GetYear() const
{
return m_Year;
}
@ -384,12 +384,12 @@ public:
/* ------------------------------------------------------------------------------------------------
* Modify the year component.
*/
void SetYear(Uint16 year);
void SetYear(uint16_t year);
/* ------------------------------------------------------------------------------------------------
* Retrieve the month component.
*/
Uint8 GetMonth() const
SQMOD_NODISCARD uint8_t GetMonth() const
{
return m_Month;
}
@ -397,12 +397,12 @@ public:
/* ------------------------------------------------------------------------------------------------
* Modify the month component.
*/
void SetMonth(Uint8 month);
void SetMonth(uint8_t month);
/* ------------------------------------------------------------------------------------------------
* Retrieve the day component.
*/
Uint8 GetDay() const
SQMOD_NODISCARD uint8_t GetDay() const
{
return m_Day;
}
@ -410,12 +410,12 @@ public:
/* ------------------------------------------------------------------------------------------------
* Modify the day component.
*/
void SetDay(Uint8 day);
void SetDay(uint8_t day);
/* ------------------------------------------------------------------------------------------------
* Retrieve the hour component.
*/
Uint8 GetHour() const
SQMOD_NODISCARD uint8_t GetHour() const
{
return m_Hour;
}
@ -423,12 +423,12 @@ public:
/* ------------------------------------------------------------------------------------------------
* Modify the hour component.
*/
void SetHour(Uint8 hour);
void SetHour(uint8_t hour);
/* ------------------------------------------------------------------------------------------------
* Retrieve the minute component.
*/
Uint8 GetMinute() const
SQMOD_NODISCARD uint8_t GetMinute() const
{
return m_Minute;
}
@ -436,12 +436,12 @@ public:
/* ------------------------------------------------------------------------------------------------
* Modify the minute component.
*/
void SetMinute(Uint8 minute);
void SetMinute(uint8_t minute);
/* ------------------------------------------------------------------------------------------------
* Retrieve the second component.
*/
Uint8 GetSecond() const
SQMOD_NODISCARD uint8_t GetSecond() const
{
return m_Second;
}
@ -449,12 +449,12 @@ public:
/* ------------------------------------------------------------------------------------------------
* Modify the second component.
*/
void SetSecond(Uint8 second);
void SetSecond(uint8_t second);
/* ------------------------------------------------------------------------------------------------
* Retrieve the millisecond component.
*/
Uint16 GetMillisecond() const
SQMOD_NODISCARD uint16_t GetMillisecond() const
{
return m_Millisecond;
}
@ -462,82 +462,82 @@ public:
/* ------------------------------------------------------------------------------------------------
* Modify the millisecond component.
*/
void SetMillisecond(Uint16 millisecond);
void SetMillisecond(uint16_t millisecond);
/* ------------------------------------------------------------------------------------------------
* Add the specified amount of years to the current date.
*/
Datetime & AddYears(Int32 years);
Datetime & AddYears(int32_t years);
/* ------------------------------------------------------------------------------------------------
* Add the specified amount of months to the current date.
*/
Datetime & AddMonths(Int32 months);
Datetime & AddMonths(int32_t months);
/* ------------------------------------------------------------------------------------------------
* Add the specified amount of days to the current date.
*/
Datetime & AddDays(Int32 days);
Datetime & AddDays(int32_t days);
/* ------------------------------------------------------------------------------------------------
* Add the specified amount of hours to the current time.
*/
Datetime & AddHours(Int32 hours);
Datetime & AddHours(int32_t hours);
/* ------------------------------------------------------------------------------------------------
* Add the specified amount of minutes to the current time.
*/
Datetime & AddMinutes(Int32 minutes);
Datetime & AddMinutes(int32_t minutes);
/* ------------------------------------------------------------------------------------------------
* Add the specified amount of seconds to the current time.
*/
Datetime & AddSeconds(Int32 seconds);
Datetime & AddSeconds(int32_t seconds);
/* ------------------------------------------------------------------------------------------------
* Add the specified amount of milliseconds to the current time.
*/
Datetime & AddMilliseconds(Int32 milliseconds);
Datetime & AddMilliseconds(int32_t milliseconds);
/* ------------------------------------------------------------------------------------------------
* Add the specified amount of years to obtain a new date.
*/
Datetime AndYears(Int32 years);
SQMOD_NODISCARD Datetime AndYears(int32_t years);
/* ------------------------------------------------------------------------------------------------
* Add the specified amount of months to obtain a new date.
*/
Datetime AndMonths(Int32 months);
SQMOD_NODISCARD Datetime AndMonths(int32_t months);
/* ------------------------------------------------------------------------------------------------
* Add the specified amount of days to obtain a new date.
*/
Datetime AndDays(Int32 days);
SQMOD_NODISCARD Datetime AndDays(int32_t days);
/* ------------------------------------------------------------------------------------------------
* Add the specified amount of hours to obtain a new time.
*/
Datetime AndHours(Int32 hours);
SQMOD_NODISCARD Datetime AndHours(int32_t hours);
/* ------------------------------------------------------------------------------------------------
* Add the specified amount of minutes to obtain a new time.
*/
Datetime AndMinutes(Int32 minutes);
SQMOD_NODISCARD Datetime AndMinutes(int32_t minutes);
/* ------------------------------------------------------------------------------------------------
* Add the specified amount of seconds to obtain a new time.
*/
Datetime AndSeconds(Int32 seconds);
SQMOD_NODISCARD Datetime AndSeconds(int32_t seconds);
/* ------------------------------------------------------------------------------------------------
* Add the specified amount of milliseconds to obtain a new time.
*/
Datetime AndMilliseconds(Int32 milliseconds);
SQMOD_NODISCARD Datetime AndMilliseconds(int32_t milliseconds);
/* ------------------------------------------------------------------------------------------------
* See whether the associated year is a leap year.
*/
bool IsThisLeapYear() const
SQMOD_NODISCARD bool IsThisLeapYear() const
{
return Chrono::IsLeapYear(m_Year);
}
@ -545,7 +545,7 @@ public:
/* ------------------------------------------------------------------------------------------------
* Retrieve the number of days in the associated year.
*/
Uint16 GetYearDays() const
SQMOD_NODISCARD uint16_t GetYearDays() const
{
return Chrono::DaysInYear(m_Year);
}
@ -553,7 +553,7 @@ public:
/* ------------------------------------------------------------------------------------------------
* Retrieve the number of days in the associated month.
*/
Uint8 GetMonthDays() const
SQMOD_NODISCARD uint8_t GetMonthDays() const
{
return Chrono::DaysInMonth(m_Year, m_Month);
}
@ -561,17 +561,17 @@ public:
/* ------------------------------------------------------------------------------------------------
* Retrieve the date from this date-time instance.
*/
Date GetDate() const;
SQMOD_NODISCARD Date GetDate() const;
/* ------------------------------------------------------------------------------------------------
* Retrieve the time from this date-time instance.
*/
Time GetTime() const;
SQMOD_NODISCARD Time GetTime() const;
/* ------------------------------------------------------------------------------------------------
* Convert this date-time instance to a time-stamp.
*/
Timestamp GetTimestamp() const;
SQMOD_NODISCARD Timestamp GetTimestamp() const;
};
} // Namespace:: SqMod

View File

@ -1,28 +1,26 @@
// ------------------------------------------------------------------------------------------------
#include "Library/Chrono/Time.hpp"
#include "Library/Chrono/Date.hpp"
#include "Library/Chrono/Datetime.hpp"
#include "Library/Chrono/Timestamp.hpp"
#include "Base/Shared.hpp"
#include "Core/Utility.hpp"
// ------------------------------------------------------------------------------------------------
namespace SqMod {
// ------------------------------------------------------------------------------------------------
SQMODE_DECL_TYPENAME(Typename, _SC("SqTime"))
SQMOD_DECL_TYPENAME(Typename, _SC("SqTime"))
// ------------------------------------------------------------------------------------------------
SQChar Time::Delimiter = ':';
// ------------------------------------------------------------------------------------------------
Int32 Time::Compare(const Time & o) const
int32_t Time::Compare(const Time & o) const
{
if (m_Hour < o.m_Hour)
{
{ // NOLINT(bugprone-branch-clone)
return -1;
}
else if (m_Hour > o.m_Hour)
{
{ // NOLINT(bugprone-branch-clone)
return 1;
}
else if (m_Minute < o.m_Minute)
@ -80,9 +78,9 @@ Time Time::operator / (const Time & o) const
}
// ------------------------------------------------------------------------------------------------
CSStr Time::ToString() const
String Time::ToString() const
{
return ToStrF("%02u%c%02u%c%02u%c%u",
return fmt::format("{:02}{}{:02}{}{:02}{}{}",
m_Hour, m_Delimiter,
m_Minute, m_Delimiter,
m_Second, m_Delimiter,
@ -90,7 +88,7 @@ CSStr Time::ToString() const
}
// ------------------------------------------------------------------------------------------------
void Time::Set(Uint8 hour, Uint8 minute, Uint8 second, Uint16 millisecond)
void Time::Set(uint8_t hour, uint8_t minute, uint8_t second, uint16_t millisecond)
{
// Is the specified hour within range?
if (hour >= 24)
@ -120,7 +118,7 @@ void Time::Set(Uint8 hour, Uint8 minute, Uint8 second, Uint16 millisecond)
}
// ------------------------------------------------------------------------------------------------
void Time::SetStr(CSStr str)
void Time::SetStr(const SQChar * str)
{
// The format specifications that will be used to scan the string
static SQChar fs[] = _SC(" %u : %u : %u : %u ");
@ -140,19 +138,19 @@ void Time::SetStr(CSStr str)
fs[9] = m_Delimiter;
fs[14] = m_Delimiter;
// The sscanf function requires at least 32 bit integers
Uint32 hour = 0, minute = 0, second = 0, milli = 0;
uint32_t hour = 0, minute = 0, second = 0, milli = 0;
// Attempt to extract the component values from the specified string
sscanf(str, fs, &hour, &minute, &second, &milli);
// Clamp the extracted values to the boundaries of associated type and assign them
Set(ClampL< Uint32, Uint8 >(hour),
ClampL< Uint32, Uint8 >(minute),
ClampL< Uint32, Uint8 >(second),
ClampL< Uint32, Uint16 >(milli)
Set(ClampL< uint32_t, uint8_t >(hour),
ClampL< uint32_t, uint8_t >(minute),
ClampL< uint32_t, uint8_t >(second),
ClampL< uint32_t, uint16_t >(milli)
);
}
// ------------------------------------------------------------------------------------------------
void Time::SetHour(Uint8 hour)
void Time::SetHour(uint8_t hour)
{
// Is the specified hour within range?
if (hour >= 24)
@ -164,7 +162,7 @@ void Time::SetHour(Uint8 hour)
}
// ------------------------------------------------------------------------------------------------
void Time::SetMinute(Uint8 minute)
void Time::SetMinute(uint8_t minute)
{
// Is the specified minute within range?
if (minute >= 60)
@ -176,7 +174,7 @@ void Time::SetMinute(Uint8 minute)
}
// ------------------------------------------------------------------------------------------------
void Time::SetSecond(Uint8 second)
void Time::SetSecond(uint8_t second)
{
// Is the specified second within range?
if (second >= 60)
@ -188,7 +186,7 @@ void Time::SetSecond(Uint8 second)
}
// ------------------------------------------------------------------------------------------------
void Time::SetMillisecond(Uint16 millisecond)
void Time::SetMillisecond(uint16_t millisecond)
{
// Is the specified millisecond within range?
if (millisecond >= 1000)
@ -200,7 +198,7 @@ void Time::SetMillisecond(Uint16 millisecond)
}
// ------------------------------------------------------------------------------------------------
Time & Time::AddHours(Int32 hours)
Time & Time::AddHours(int32_t hours)
{
// Did we even add any hours?
if (hours)
@ -215,13 +213,13 @@ Time & Time::AddHours(Int32 hours)
}
// ------------------------------------------------------------------------------------------------
Time & Time::AddMinutes(Int32 minutes)
Time & Time::AddMinutes(int32_t minutes)
{
// Did we even add any minutes?
if (minutes)
{
// Extract the number of hours
Int32 hours = static_cast< Int32 >(minutes / 60);
auto hours = static_cast< int32_t >(minutes / 60);
// Extract the number of minutes
m_Minute += (minutes % 60);
// Are the minutes overlapping with the next hour?
@ -243,13 +241,13 @@ Time & Time::AddMinutes(Int32 minutes)
}
// ------------------------------------------------------------------------------------------------
Time & Time::AddSeconds(Int32 seconds)
Time & Time::AddSeconds(int32_t seconds)
{
// Did we even add any seconds?
if (seconds)
{
// Extract the number of minutes
Int32 minutes = static_cast< Int32 >(seconds / 60);
auto minutes = static_cast< int32_t >(seconds / 60);
// Extract the number of seconds
m_Second += (seconds % 60);
// Are the seconds overlapping with the next minute?
@ -271,13 +269,13 @@ Time & Time::AddSeconds(Int32 seconds)
}
// ------------------------------------------------------------------------------------------------
Time & Time::AddMilliseconds(Int32 milliseconds)
Time & Time::AddMilliseconds(int32_t milliseconds)
{
// Did we even add any milliseconds?
if (milliseconds)
{
// Extract the number of seconds
Int32 seconds = static_cast< Int32 >(milliseconds / 1000);
auto seconds = static_cast< int32_t >(milliseconds / 1000);
// Extract the number of milliseconds
m_Millisecond += (milliseconds / 1000);
// Are the milliseconds overlapping with the next second?
@ -299,19 +297,19 @@ Time & Time::AddMilliseconds(Int32 milliseconds)
}
// ------------------------------------------------------------------------------------------------
Time Time::AndHours(Int32 hours)
Time Time::AndHours(int32_t hours)
{
// Did we even add any hours?
if (hours)
{
return Time((m_Hour + (hours % 24)) % 24, m_Minute, m_Second, m_Millisecond);
return Time(static_cast< uint8_t >((m_Hour + (hours % 24)) % 24), m_Minute, m_Second, m_Millisecond);
}
// Return the time as is
return Time(*this);
}
// ------------------------------------------------------------------------------------------------
Time Time::AndMinutes(Int32 minutes)
Time Time::AndMinutes(int32_t minutes)
{
// Did we even added any minutes?
if (!minutes)
@ -319,7 +317,7 @@ Time Time::AndMinutes(Int32 minutes)
return Time(*this); // Return the time as is
}
// Extract the number of hours
Int32 hours = static_cast< Int32 >(minutes / 60);
auto hours = static_cast< int32_t >(minutes / 60);
// Extract the number of minutes
minutes = m_Minute + (minutes % 60);
// Are the minutes overlapping with the next hour?
@ -335,13 +333,13 @@ Time Time::AndMinutes(Int32 minutes)
t.AddHours(hours);
}
// Assign the resulted minutes
t.m_Minute = (minutes % 60);
t.m_Minute = static_cast< uint8_t >(minutes % 60);
// Return the result
return t;
}
// ------------------------------------------------------------------------------------------------
Time Time::AndSeconds(Int32 seconds)
Time Time::AndSeconds(int32_t seconds)
{
// Did we even added any seconds?
if (!seconds)
@ -349,7 +347,7 @@ Time Time::AndSeconds(Int32 seconds)
return Time(*this); // Return the time as is
}
// Extract the number of minutes
Int32 minutes = static_cast< Int32 >(seconds / 60);
auto minutes = static_cast< int32_t >(seconds / 60);
// Extract the number of seconds
seconds = m_Second + (seconds % 60);
// Are the seconds overlapping with the next minute?
@ -365,13 +363,13 @@ Time Time::AndSeconds(Int32 seconds)
t.AddMinutes(minutes);
}
// Assign the resulted seconds
t.m_Second = (seconds % 60);
t.m_Second = static_cast< uint8_t >(seconds % 60);
// Return the result
return t;
}
// ------------------------------------------------------------------------------------------------
Time Time::AndMilliseconds(Int32 milliseconds)
Time Time::AndMilliseconds(int32_t milliseconds)
{
// Did we even added any milliseconds?
if (!milliseconds)
@ -379,7 +377,7 @@ Time Time::AndMilliseconds(Int32 milliseconds)
return Time(*this); // Return the time as is
}
// Extract the number of seconds
Int32 seconds = static_cast< Int32 >(milliseconds / 1000);
auto seconds = static_cast< int32_t >(milliseconds / 1000);
// Extract the number of milliseconds
milliseconds = m_Millisecond + (milliseconds % 1000);
// Are the milliseconds overlapping with the next second?
@ -395,7 +393,7 @@ Time Time::AndMilliseconds(Int32 milliseconds)
t.AddSeconds(seconds);
}
// Assign the resulted milliseconds
t.m_Millisecond = (milliseconds % 1000);
t.m_Millisecond = static_cast< uint16_t >(milliseconds % 1000);
// Return the result
return t;
}
@ -404,10 +402,10 @@ Time Time::AndMilliseconds(Int32 milliseconds)
Timestamp Time::GetTimestamp() const
{
// Calculate the microseconds in the current time
Int64 ms = static_cast< Int64 >(m_Hour * 3600000000LL);
ms += static_cast< Int64 >(m_Minute * 60000000L);
ms += static_cast< Int64 >(m_Second * 1000000L);
ms += static_cast< Int64 >(m_Millisecond * 1000L);
auto ms = static_cast< int64_t >(m_Hour * 3600000000LL);
ms += static_cast< int64_t >(m_Minute * 60000000L);
ms += static_cast< int64_t >(m_Second * 1000000L);
ms += static_cast< int64_t >(m_Millisecond * 1000L);
// Return the resulted timestamp
return Timestamp(ms);
}
@ -419,10 +417,10 @@ void Register_ChronoTime(HSQUIRRELVM vm, Table & /*cns*/)
Class< Time >(vm, Typename::Str)
// Constructors
.Ctor()
.Ctor< Uint8 >()
.Ctor< Uint8, Uint8 >()
.Ctor< Uint8, Uint8, Uint8 >()
.Ctor< Uint8, Uint8, Uint8, Uint16 >()
.Ctor< uint8_t >()
.Ctor< uint8_t, uint8_t >()
.Ctor< uint8_t, uint8_t, uint8_t >()
.Ctor< uint8_t, uint8_t, uint8_t, uint16_t >()
// Static Properties
.SetStaticValue(_SC("GlobalDelimiter"), &Time::Delimiter)
// Core Meta-methods
@ -454,10 +452,10 @@ void Register_ChronoTime(HSQUIRRELVM vm, Table & /*cns*/)
.Func(_SC("AndMillis"), &Time::AndMilliseconds)
.Func(_SC("AndMilliseconds"), &Time::AndMilliseconds)
// Overloaded Methods
.Overload< void (Time::*)(Uint8) >(_SC("Set"), &Time::Set)
.Overload< void (Time::*)(Uint8, Uint8) >(_SC("Set"), &Time::Set)
.Overload< void (Time::*)(Uint8, Uint8, Uint8) >(_SC("Set"), &Time::Set)
.Overload< void (Time::*)(Uint8, Uint8, Uint8, Uint16) >(_SC("Set"), &Time::Set)
.Overload< void (Time::*)(uint8_t) >(_SC("Set"), &Time::Set)
.Overload< void (Time::*)(uint8_t, uint8_t) >(_SC("Set"), &Time::Set)
.Overload< void (Time::*)(uint8_t, uint8_t, uint8_t) >(_SC("Set"), &Time::Set)
.Overload< void (Time::*)(uint8_t, uint8_t, uint8_t, uint16_t) >(_SC("Set"), &Time::Set)
);
}

View File

@ -21,15 +21,15 @@ protected:
/* ------------------------------------------------------------------------------------------------
* Compare the values of two instances.
*/
Int32 Compare(const Time & o) const;
SQMOD_NODISCARD int32_t Compare(const Time & o) const;
private:
// ------------------------------------------------------------------------------------------------
Uint8 m_Hour; // Hour
Uint8 m_Minute; // Minute
Uint8 m_Second; // Second
Uint16 m_Millisecond; // Millisecond
uint8_t m_Hour{}; // Hour
uint8_t m_Minute{}; // Minute
uint8_t m_Second{}; // Second
uint16_t m_Millisecond{}; // Millisecond
// ------------------------------------------------------------------------------------------------
SQChar m_Delimiter; // Component delimiter when generating strings.
@ -52,7 +52,7 @@ public:
/* ------------------------------------------------------------------------------------------------
* Base constructor.
*/
Time(Uint8 hour)
explicit Time(uint8_t hour)
: m_Delimiter(Delimiter)
{
Set(hour, 0, 0, 0);
@ -61,7 +61,7 @@ public:
/* ------------------------------------------------------------------------------------------------
* Base constructor.
*/
Time(Uint8 hour, Uint8 minute)
Time(uint8_t hour, uint8_t minute)
: m_Delimiter(Delimiter)
{
Set(hour, minute, 0, 0);
@ -70,7 +70,7 @@ public:
/* ------------------------------------------------------------------------------------------------
* Base constructor.
*/
Time(Uint8 hour, Uint8 minute, Uint8 second)
Time(uint8_t hour, uint8_t minute, uint8_t second)
: m_Delimiter(Delimiter)
{
Set(hour, minute, second, 0);
@ -79,7 +79,7 @@ public:
/* ------------------------------------------------------------------------------------------------
* Base constructor.
*/
Time(Uint8 hour, Uint8 minute, Uint8 second, Uint16 millisecond)
Time(uint8_t hour, uint8_t minute, uint8_t second, uint16_t millisecond)
: m_Delimiter(Delimiter)
{
Set(hour, minute, second, millisecond);
@ -88,7 +88,7 @@ public:
/* ------------------------------------------------------------------------------------------------
* String constructor.
*/
Time(CSStr str)
explicit Time(const SQChar * str)
: m_Delimiter(Delimiter)
{
SetStr(str);
@ -190,7 +190,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Used by the script engine to compare two instances of this type.
*/
Int32 Cmp(const Time & o) const
SQMOD_NODISCARD int32_t Cmp(const Time & o) const
{
return Compare(o);
}
@ -198,12 +198,12 @@ public:
/* --------------------------------------------------------------------------------------------
* Used by the script engine to convert an instance of this type to a string.
*/
CSStr ToString() const;
SQMOD_NODISCARD String ToString() const;
/* ------------------------------------------------------------------------------------------------
* Assign the specified values.
*/
void Set(Uint8 hour)
void Set(uint8_t hour)
{
Set(hour, m_Minute, m_Second, m_Millisecond);
}
@ -211,7 +211,7 @@ public:
/* ------------------------------------------------------------------------------------------------
* Assign the specified values.
*/
void Set(Uint8 hour, Uint8 minute)
void Set(uint8_t hour, uint8_t minute)
{
Set(hour, minute, m_Second, m_Millisecond);
}
@ -219,7 +219,7 @@ public:
/* ------------------------------------------------------------------------------------------------
* Assign the specified values.
*/
void Set(Uint8 hour, Uint8 minute, Uint8 second)
void Set(uint8_t hour, uint8_t minute, uint8_t second)
{
Set(hour, minute, second, m_Millisecond);
}
@ -227,12 +227,12 @@ public:
/* ------------------------------------------------------------------------------------------------
* Assign the specified values.
*/
void Set(Uint8 hour, Uint8 minute, Uint8 second, Uint16 millisecond);
void Set(uint8_t hour, uint8_t minute, uint8_t second, uint16_t millisecond);
/* ------------------------------------------------------------------------------------------------
* Retrieve the local delimiter character.
*/
SQChar GetDelimiter() const
SQMOD_NODISCARD SQChar GetDelimiter() const
{
return m_Delimiter;
}
@ -248,7 +248,7 @@ public:
/* ------------------------------------------------------------------------------------------------
* Retrieve the values as a string.
*/
CSStr GetStr() const
SQMOD_NODISCARD String GetStr() const
{
return ToString();
}
@ -256,12 +256,12 @@ public:
/* ------------------------------------------------------------------------------------------------
* Extract the values from a string.
*/
void SetStr(CSStr str);
void SetStr(const SQChar * str);
/* ------------------------------------------------------------------------------------------------
* Retrieve the hour component.
*/
Uint8 GetHour() const
SQMOD_NODISCARD uint8_t GetHour() const
{
return m_Hour;
}
@ -269,12 +269,12 @@ public:
/* ------------------------------------------------------------------------------------------------
* Modify the hour component.
*/
void SetHour(Uint8 hour);
void SetHour(uint8_t hour);
/* ------------------------------------------------------------------------------------------------
* Retrieve the minute component.
*/
Uint8 GetMinute() const
SQMOD_NODISCARD uint8_t GetMinute() const
{
return m_Minute;
}
@ -282,12 +282,12 @@ public:
/* ------------------------------------------------------------------------------------------------
* Modify the minute component.
*/
void SetMinute(Uint8 minute);
void SetMinute(uint8_t minute);
/* ------------------------------------------------------------------------------------------------
* Retrieve the second component.
*/
Uint8 GetSecond() const
SQMOD_NODISCARD uint8_t GetSecond() const
{
return m_Second;
}
@ -295,12 +295,12 @@ public:
/* ------------------------------------------------------------------------------------------------
* Modify the second component.
*/
void SetSecond(Uint8 second);
void SetSecond(uint8_t second);
/* ------------------------------------------------------------------------------------------------
* Retrieve the millisecond component.
*/
Uint16 GetMillisecond() const
SQMOD_NODISCARD uint16_t GetMillisecond() const
{
return m_Millisecond;
}
@ -308,52 +308,52 @@ public:
/* ------------------------------------------------------------------------------------------------
* Modify the millisecond component.
*/
void SetMillisecond(Uint16 millisecond);
void SetMillisecond(uint16_t millisecond);
/* ------------------------------------------------------------------------------------------------
* Add the specified amount of hours to the current time.
*/
Time & AddHours(Int32 hours);
Time & AddHours(int32_t hours);
/* ------------------------------------------------------------------------------------------------
* Add the specified amount of minutes to the current time.
*/
Time & AddMinutes(Int32 minutes);
Time & AddMinutes(int32_t minutes);
/* ------------------------------------------------------------------------------------------------
* Add the specified amount of seconds to the current time.
*/
Time & AddSeconds(Int32 seconds);
Time & AddSeconds(int32_t seconds);
/* ------------------------------------------------------------------------------------------------
* Add the specified amount of milliseconds to the current time.
*/
Time & AddMilliseconds(Int32 milliseconds);
Time & AddMilliseconds(int32_t milliseconds);
/* ------------------------------------------------------------------------------------------------
* Add the specified amount of hours to obtain a new time.
*/
Time AndHours(Int32 hours);
SQMOD_NODISCARD Time AndHours(int32_t hours);
/* ------------------------------------------------------------------------------------------------
* Add the specified amount of minutes to obtain a new time.
*/
Time AndMinutes(Int32 minutes);
SQMOD_NODISCARD Time AndMinutes(int32_t minutes);
/* ------------------------------------------------------------------------------------------------
* Add the specified amount of seconds to obtain a new time.
*/
Time AndSeconds(Int32 seconds);
SQMOD_NODISCARD Time AndSeconds(int32_t seconds);
/* ------------------------------------------------------------------------------------------------
* Add the specified amount of milliseconds to obtain a new time.
*/
Time AndMilliseconds(Int32 milliseconds);
SQMOD_NODISCARD Time AndMilliseconds(int32_t milliseconds);
/* ------------------------------------------------------------------------------------------------
* Convert this time instance to a time-stamp.
*/
Timestamp GetTimestamp() const;
SQMOD_NODISCARD Timestamp GetTimestamp() const;
};
} // Namespace:: SqMod

View File

@ -1,13 +1,12 @@
// ------------------------------------------------------------------------------------------------
#include "Library/Chrono/Timer.hpp"
#include "Library/Chrono/Timestamp.hpp"
#include "Base/Shared.hpp"
// ------------------------------------------------------------------------------------------------
namespace SqMod {
// ------------------------------------------------------------------------------------------------
SQMODE_DECL_TYPENAME(Typename, _SC("SqTimer"))
SQMOD_DECL_TYPENAME(Typename, _SC("SqTimer"))
// ------------------------------------------------------------------------------------------------
Timer::Timer()
@ -17,7 +16,7 @@ Timer::Timer()
}
// ------------------------------------------------------------------------------------------------
Int32 Timer::Cmp(const Timer & o) const
int32_t Timer::Cmp(const Timer & o) const
{
if (m_Timestamp == o.m_Timestamp)
return 0;
@ -28,9 +27,9 @@ Int32 Timer::Cmp(const Timer & o) const
}
// ------------------------------------------------------------------------------------------------
CSStr Timer::ToString() const
String Timer::ToString() const
{
return ToStrF("%lld", m_Timestamp);
return fmt::format("{}", m_Timestamp);
}
// ------------------------------------------------------------------------------------------------
@ -42,15 +41,15 @@ void Timer::Reset()
// ------------------------------------------------------------------------------------------------
Timestamp Timer::Restart()
{
const Int64 now = Chrono::GetCurrentSysTime(), elapsed = now - m_Timestamp;
const int64_t now = Chrono::GetCurrentSysTime(), elapsed = now - m_Timestamp;
m_Timestamp = now;
return Timestamp(elapsed);
}
// ------------------------------------------------------------------------------------------------
Int64 Timer::RestartRaw()
int64_t Timer::RestartRaw()
{
const Int64 now = Chrono::GetCurrentSysTime(), elapsed = now - m_Timestamp;
const int64_t now = Chrono::GetCurrentSysTime(), elapsed = now - m_Timestamp;
m_Timestamp = now;
return elapsed;
}
@ -62,7 +61,7 @@ Timestamp Timer::GetElapsedTime() const
}
// ------------------------------------------------------------------------------------------------
Int64 Timer::GetElapsedTimeRaw() const
int64_t Timer::GetElapsedTimeRaw() const
{
return (Chrono::GetCurrentSysTime() - m_Timestamp);
}

View File

@ -14,7 +14,7 @@ class Timer
/* --------------------------------------------------------------------------------------------
*
*/
Timer(Int64 t)
explicit Timer(int64_t t)
: m_Timestamp(t)
{
/* ... */
@ -30,19 +30,12 @@ public:
/* --------------------------------------------------------------------------------------------
*
*/
Timer(const Timer & o)
: m_Timestamp(o.m_Timestamp)
{
/* ... */
}
Timer(const Timer & o) = default;
/* --------------------------------------------------------------------------------------------
*
*/
~Timer()
{
/* ... */
}
~Timer() = default;
/* --------------------------------------------------------------------------------------------
*
@ -56,12 +49,12 @@ public:
/* --------------------------------------------------------------------------------------------
* ...
*/
Int32 Cmp(const Timer & b) const;
SQMOD_NODISCARD int32_t Cmp(const Timer & b) const;
/* --------------------------------------------------------------------------------------------
* ...
*/
CSStr ToString() const;
SQMOD_NODISCARD String ToString() const;
/* --------------------------------------------------------------------------------------------
*
@ -76,22 +69,22 @@ public:
/* --------------------------------------------------------------------------------------------
*
*/
Int64 RestartRaw();
int64_t RestartRaw();
/* --------------------------------------------------------------------------------------------
*
*/
Timestamp GetElapsedTime() const;
SQMOD_NODISCARD Timestamp GetElapsedTime() const;
/* --------------------------------------------------------------------------------------------
*
*/
Int64 GetElapsedTimeRaw() const;
SQMOD_NODISCARD int64_t GetElapsedTimeRaw() const;
private:
// --------------------------------------------------------------------------------------------
Int64 m_Timestamp;
int64_t m_Timestamp;
};
} // Namespace:: SqMod

View File

@ -2,15 +2,13 @@
#include "Library/Chrono/Timestamp.hpp"
#include "Library/Chrono/Timer.hpp"
#include "Library/Chrono/Date.hpp"
#include "Library/Chrono/Time.hpp"
#include "Library/Chrono/Datetime.hpp"
#include "Library/Numeric/LongInt.hpp"
#include "Library/Numeric/Long.hpp"
// ------------------------------------------------------------------------------------------------
namespace SqMod {
// ------------------------------------------------------------------------------------------------
SQMODE_DECL_TYPENAME(Typename, _SC("SqTimestamp"))
SQMOD_DECL_TYPENAME(Typename, _SC("SqTimestamp"))
// ------------------------------------------------------------------------------------------------
Timestamp::Timestamp(const SLongInt & t)
@ -20,7 +18,7 @@ Timestamp::Timestamp(const SLongInt & t)
}
// ------------------------------------------------------------------------------------------------
Int32 Timestamp::Cmp(const Timestamp & o) const
int32_t Timestamp::Cmp(const Timestamp & o) const
{
if (m_Timestamp == o.m_Timestamp)
{
@ -37,9 +35,9 @@ Int32 Timestamp::Cmp(const Timestamp & o) const
}
// ------------------------------------------------------------------------------------------------
CSStr Timestamp::ToString() const
String Timestamp::ToString() const
{
return ToStrF("%lld", m_Timestamp);
return fmt::format("{}", m_Timestamp);
}
// ------------------------------------------------------------------------------------------------
@ -55,9 +53,9 @@ SLongInt Timestamp::GetMicroseconds() const
}
// ------------------------------------------------------------------------------------------------
void Timestamp::SetMicroseconds(const SLongInt & ammount)
void Timestamp::SetMicroseconds(const SLongInt & amount)
{
m_Timestamp = ammount.GetNum();
m_Timestamp = amount.GetNum();
}
// ------------------------------------------------------------------------------------------------
@ -67,9 +65,9 @@ SLongInt Timestamp::GetMilliseconds() const
}
// ------------------------------------------------------------------------------------------------
void Timestamp::SetMilliseconds(const SLongInt & ammount)
void Timestamp::SetMilliseconds(const SLongInt & amount)
{
m_Timestamp = (ammount.GetNum() * 1000L);
m_Timestamp = (amount.GetNum() * 1000L);
}
// ------------------------------------------------------------------------------------------------
@ -79,51 +77,51 @@ static Timestamp SqGetEpochTimeNow()
}
// ------------------------------------------------------------------------------------------------
static Timestamp SqGetMicrosecondsRaw(Int64 ammount)
static Timestamp SqGetMicrosecondsRaw(int64_t amount)
{
return Timestamp(ammount);
return Timestamp(amount);
}
// ------------------------------------------------------------------------------------------------
static Timestamp SqGetMicroseconds(const SLongInt & ammount)
static Timestamp SqGetMicroseconds(const SLongInt & amount)
{
return Timestamp(ammount);
return Timestamp(amount);
}
// ------------------------------------------------------------------------------------------------
static Timestamp SqGetMilliseconds(SQInteger ammount)
static Timestamp SqGetMilliseconds(SQInteger amount)
{
return Timestamp(Int64(Int64(ammount) * 1000L));
return Timestamp(int64_t(int64_t(amount) * 1000L));
}
// ------------------------------------------------------------------------------------------------
static Timestamp SqGetSeconds(SQFloat ammount)
static Timestamp SqGetSeconds(SQFloat amount)
{
return Timestamp(Int64(Float64(ammount) * 1000000L));
return Timestamp(int64_t(double(amount) * 1000000L));
}
// ------------------------------------------------------------------------------------------------
static Timestamp SqGetMinutes(SQFloat ammount)
static Timestamp SqGetMinutes(SQFloat amount)
{
return Timestamp(Int64((Float64(ammount) * 60000000L)));
return Timestamp(int64_t((double(amount) * 60000000L)));
}
// ------------------------------------------------------------------------------------------------
static Timestamp SqGetHours(SQFloat ammount)
static Timestamp SqGetHours(SQFloat amount)
{
return Timestamp(Int64(Float64(ammount) * 3600000000LL));
return Timestamp(int64_t(double(amount) * 3600000000LL));
}
// ------------------------------------------------------------------------------------------------
static Timestamp SqGetDays(SQFloat ammount)
static Timestamp SqGetDays(SQFloat amount)
{
return Timestamp(Int64(Float64(ammount) * 86400000000LL));
return Timestamp(int64_t(double(amount) * 86400000000LL));
}
// ------------------------------------------------------------------------------------------------
static Timestamp SqGetYears(SQFloat ammount)
static Timestamp SqGetYears(SQFloat amount)
{
return Timestamp(Int64(Float64(ammount) * 31557600000000LL));
return Timestamp(int64_t(double(amount) * 31557600000000LL));
}
// ================================================================================================
@ -174,7 +172,6 @@ void Register_ChronoTimestamp(HSQUIRRELVM vm, Table & /*cns*/)
.StaticFunc(_SC("GetDays"), &SqGetDays)
.StaticFunc(_SC("GetYears"), &SqGetYears)
);
;
}
} // Namespace:: SqMod

View File

@ -31,7 +31,7 @@ public:
/* --------------------------------------------------------------------------------------------
*
*/
Timestamp(Int64 t)
explicit Timestamp(int64_t t)
: m_Timestamp(t)
{
/* ... */
@ -45,19 +45,12 @@ public:
/* --------------------------------------------------------------------------------------------
*
*/
Timestamp(const Timestamp & o)
: m_Timestamp(o.m_Timestamp)
{
/* ... */
}
Timestamp(const Timestamp & o) = default;
/* --------------------------------------------------------------------------------------------
*
*/
~Timestamp()
{
/* ... */
}
~Timestamp() = default;
/* --------------------------------------------------------------------------------------------
*
@ -103,12 +96,12 @@ public:
/* --------------------------------------------------------------------------------------------
* ...
*/
Int32 Cmp(const Timestamp & b) const;
SQMOD_NODISCARD int32_t Cmp(const Timestamp & b) const;
/* --------------------------------------------------------------------------------------------
* ...
*/
CSStr ToString() const;
SQMOD_NODISCARD String ToString() const;
/* --------------------------------------------------------------------------------------------
* ...
@ -118,7 +111,7 @@ public:
/* --------------------------------------------------------------------------------------------
*
*/
Int64 GetNum() const
SQMOD_NODISCARD int64_t GetNum() const
{
return m_Timestamp;
}
@ -126,17 +119,17 @@ public:
/* --------------------------------------------------------------------------------------------
*
*/
SLongInt GetMicroseconds() const;
SQMOD_NODISCARD SLongInt GetMicroseconds() const;
/* --------------------------------------------------------------------------------------------
*
*/
void SetMicroseconds(const SLongInt & ammount);
void SetMicroseconds(const SLongInt & amount);
/* --------------------------------------------------------------------------------------------
*
*/
SQInteger GetMicrosecondsRaw() const
SQMOD_NODISCARD SQInteger GetMicrosecondsRaw() const
{
return SQInteger(m_Timestamp);
}
@ -144,25 +137,25 @@ public:
/* --------------------------------------------------------------------------------------------
*
*/
void SetMicrosecondsRaw(SQInteger ammount)
void SetMicrosecondsRaw(SQInteger amount)
{
m_Timestamp = ammount;
m_Timestamp = amount;
}
/* --------------------------------------------------------------------------------------------
*
*/
SLongInt GetMilliseconds() const;
SQMOD_NODISCARD SLongInt GetMilliseconds() const;
/* --------------------------------------------------------------------------------------------
*
*/
void SetMilliseconds(const SLongInt & ammount);
void SetMilliseconds(const SLongInt & amount);
/* --------------------------------------------------------------------------------------------
*
*/
SQInteger GetMillisecondsRaw() const
SQMOD_NODISCARD SQInteger GetMillisecondsRaw() const
{
return SQInteger(m_Timestamp / 1000L);
}
@ -170,31 +163,31 @@ public:
/* --------------------------------------------------------------------------------------------
*
*/
void SetMillisecondsRaw(SQInteger ammount)
void SetMillisecondsRaw(SQInteger amount)
{
m_Timestamp = Int64(Int64(ammount) * 1000L);
m_Timestamp = int64_t(int64_t(amount) * 1000L);
}
/* --------------------------------------------------------------------------------------------
*
*/
SQFloat GetSecondsF() const
SQMOD_NODISCARD SQFloat GetSecondsF() const
{
return SQFloat(m_Timestamp / 1000000L);
return static_cast< SQFloat >(static_cast< int64_t >(m_Timestamp / 1000000LL));
}
/* --------------------------------------------------------------------------------------------
*
*/
void SetSecondsF(SQFloat ammount)
void SetSecondsF(SQFloat amount)
{
m_Timestamp = Int64(Float64(ammount) * 1000000L);
m_Timestamp = int64_t(double(amount) * 1000000L);
}
/* --------------------------------------------------------------------------------------------
*
*/
SQInteger GetSecondsI() const
SQMOD_NODISCARD SQInteger GetSecondsI() const
{
return SQInteger(m_Timestamp / 1000000L);
}
@ -202,31 +195,31 @@ public:
/* --------------------------------------------------------------------------------------------
*
*/
void SetSecondsI(SQInteger ammount)
void SetSecondsI(SQInteger amount)
{
m_Timestamp = Int64(Int64(ammount) * 1000000L);
m_Timestamp = int64_t(int64_t(amount) * 1000000L);
}
/* --------------------------------------------------------------------------------------------
*
*/
SQFloat GetMinutesF() const
SQMOD_NODISCARD SQFloat GetMinutesF() const
{
return SQFloat(m_Timestamp / 60000000.0f);
return SQFloat(m_Timestamp / 60000000.0);
}
/* --------------------------------------------------------------------------------------------
*
*/
void SetMinutesF(SQFloat ammount)
void SetMinutesF(SQFloat amount)
{
m_Timestamp = Int64(Float64(ammount) * 60000000L);
m_Timestamp = int64_t(double(amount) * 60000000L);
}
/* --------------------------------------------------------------------------------------------
*
*/
SQInteger GetMinutesI() const
SQMOD_NODISCARD SQInteger GetMinutesI() const
{
return SQInteger(m_Timestamp / 60000000L);
}
@ -234,31 +227,31 @@ public:
/* --------------------------------------------------------------------------------------------
*
*/
void SetMinutesI(SQInteger ammount)
void SetMinutesI(SQInteger amount)
{
m_Timestamp = Int64(Int64(ammount) * 60000000L);
m_Timestamp = int64_t(int64_t(amount) * 60000000L);
}
/* --------------------------------------------------------------------------------------------
*
*/
SQFloat GetHoursF() const
SQMOD_NODISCARD SQFloat GetHoursF() const
{
return SQFloat(m_Timestamp / 3600000000.0d);
return SQFloat(m_Timestamp / 3600000000.0);
}
/* --------------------------------------------------------------------------------------------
*
*/
void SetHoursF(SQFloat ammount)
void SetHoursF(SQFloat amount)
{
m_Timestamp = Int64(Float64(ammount) * 3600000000LL);
m_Timestamp = int64_t(double(amount) * 3600000000LL);
}
/* --------------------------------------------------------------------------------------------
*
*/
SQInteger GetHoursI() const
SQMOD_NODISCARD SQInteger GetHoursI() const
{
return SQInteger(m_Timestamp / 3600000000LL);
}
@ -266,31 +259,31 @@ public:
/* --------------------------------------------------------------------------------------------
*
*/
void SetHoursI(SQInteger ammount)
void SetHoursI(SQInteger amount)
{
m_Timestamp = Int64(Float64(ammount) * 3600000000LL);
m_Timestamp = int64_t(double(amount) * 3600000000LL);
}
/* --------------------------------------------------------------------------------------------
*
*/
SQFloat GetDaysF() const
SQMOD_NODISCARD SQFloat GetDaysF() const
{
return SQFloat(m_Timestamp / 86400000000.0d);
return SQFloat(m_Timestamp / 86400000000.0);
}
/* --------------------------------------------------------------------------------------------
*
*/
void SetDaysF(SQFloat ammount)
void SetDaysF(SQFloat amount)
{
m_Timestamp = Int64(Float64(ammount) * 86400000000LL);
m_Timestamp = int64_t(double(amount) * 86400000000LL);
}
/* --------------------------------------------------------------------------------------------
*
*/
SQInteger GetDaysI() const
SQMOD_NODISCARD SQInteger GetDaysI() const
{
return SQInteger(m_Timestamp / 86400000000LL);
}
@ -298,31 +291,31 @@ public:
/* --------------------------------------------------------------------------------------------
*
*/
void SetDaysI(SQInteger ammount)
void SetDaysI(SQInteger amount)
{
m_Timestamp = Int64(Float64(ammount) * 86400000000LL);
m_Timestamp = int64_t(double(amount) * 86400000000LL);
}
/* --------------------------------------------------------------------------------------------
*
*/
SQFloat GetYearsF() const
SQMOD_NODISCARD SQFloat GetYearsF() const
{
return SQFloat(m_Timestamp / 31557600000000.0d);
return SQFloat(m_Timestamp / 31557600000000.0);
}
/* --------------------------------------------------------------------------------------------
*
*/
void SetYearsF(SQFloat ammount)
void SetYearsF(SQFloat amount)
{
m_Timestamp = Int64(Float64(ammount) * 31557600000000LL);
m_Timestamp = int64_t(double(amount) * 31557600000000LL);
}
/* --------------------------------------------------------------------------------------------
*
*/
SQInteger GetYearsI() const
SQMOD_NODISCARD SQInteger GetYearsI() const
{
return SQInteger(m_Timestamp / 31557600000000LL);
}
@ -330,15 +323,15 @@ public:
/* --------------------------------------------------------------------------------------------
*
*/
void SetYearsI(SQInteger ammount)
void SetYearsI(SQInteger amount)
{
m_Timestamp = Int64(Float64(ammount) * 31557600000000LL);
m_Timestamp = int64_t(double(amount) * 31557600000000LL);
}
private:
// --------------------------------------------------------------------------------------------
Int64 m_Timestamp;
int64_t m_Timestamp;
};
} // Namespace:: SqMod

View File

@ -1,23 +1,13 @@
// ------------------------------------------------------------------------------------------------
#include "Library/Crypt.hpp"
#include "Base/Shared.hpp"
// ------------------------------------------------------------------------------------------------
#include <cstdlib>
#include <cstring>
// ------------------------------------------------------------------------------------------------
namespace SqMod {
// ------------------------------------------------------------------------------------------------
extern void Register_Hash(HSQUIRRELVM vm);
extern void Register_AES(HSQUIRRELVM vm);
// ================================================================================================
void Register_Crypt(HSQUIRRELVM vm)
{
Register_Hash(vm);
Register_AES(vm);
}
} // Namespace:: SqMod

View File

@ -1,11 +1,9 @@
#pragma once
// ------------------------------------------------------------------------------------------------
#include "SqBase.hpp"
#include "Core/Common.hpp"
// ------------------------------------------------------------------------------------------------
namespace SqMod {
} // Namespace:: SqMod

View File

@ -1,155 +0,0 @@
// ------------------------------------------------------------------------------------------------
#include "Library/Crypt/AES.hpp"
#include "Base/Shared.hpp"
// ------------------------------------------------------------------------------------------------
#include <cstdlib>
#include <cstring>
// ------------------------------------------------------------------------------------------------
namespace SqMod {
// ------------------------------------------------------------------------------------------------
SQMODE_DECL_TYPENAME(Typename, _SC("SqAES256"))
// ------------------------------------------------------------------------------------------------
AES256::AES256()
: m_Context(), m_Buffer()
{
aes256_done(&m_Context);
}
// ------------------------------------------------------------------------------------------------
AES256::AES256(CSStr key)
: m_Context(), m_Buffer()
{
Init(key);
}
// ------------------------------------------------------------------------------------------------
Int32 AES256::Cmp(const AES256 & o) const
{
return std::memcmp(m_Buffer, o.m_Buffer, sizeof(m_Buffer));
}
// ------------------------------------------------------------------------------------------------
CSStr AES256::ToString() const
{
return ToStrF("%s", m_Buffer);
}
// ------------------------------------------------------------------------------------------------
CSStr AES256::GetKey() const
{
return reinterpret_cast< CSStr >(m_Buffer);
}
// ------------------------------------------------------------------------------------------------
bool AES256::Init(CSStr key)
{
// Clear current key, if any
aes256_done(&m_Context);
// Is the specified key empty?
if (!key || *key == '\0')
{
return false; // Leave the context with an empty key
}
// Obtain the specified key size
const Uint32 size = (std::strlen(key) * sizeof(SQChar));
// See if the key size is accepted
if (size > sizeof(m_Buffer))
{
STHROWF("The specified key is out of bounds: %u > %u", size, sizeof(m_Buffer));
}
// Initialize the key buffer to 0
std::memset(m_Buffer, 0, sizeof(m_Buffer));
// Copy the key into the key buffer
std::memcpy(m_Buffer, key, size);
// Initialize the context with the specified key
aes256_init(&m_Context, m_Buffer);
// This context was successfully initialized
return true;
}
// ------------------------------------------------------------------------------------------------
void AES256::Done()
{
aes256_done(&m_Context);
}
// ------------------------------------------------------------------------------------------------
String AES256::Encrypt(CSStr data)
{
// Is there any data to encrypt?
if (!data || *data == 0)
{
return String();
}
// Copy the data into an editable string
String str(data);
// Make sure that we have a size with a multiple of 16
if ((str.size() % 16) != 0)
{
str.resize(str.size() - (str.size() % 16) + 16);
}
// Encrypt in chunks of 16 characters
for (Uint32 n = 0; n < str.size(); n += 16)
{
aes256_encrypt_ecb(&m_Context, reinterpret_cast< Uint8 * >(&str[n]));
}
// Return ownership of the encrypted string
return str;
}
// ------------------------------------------------------------------------------------------------
String AES256::Decrypt(CSStr data)
{
// Is there any data to decrypt?
if (!data || *data == 0)
{
return String();
}
// Copy the data into an editable string
String str(data);
// Make sure that we have a size with a multiple of 16
if ((str.size() % 16) != 0)
{
str.resize(str.size() - (str.size() % 16) + 16);
}
// Decrypt inc chunks of 16 characters
for (Uint32 n = 0; n < str.size(); n += 16)
{
aes256_decrypt_ecb(&m_Context, reinterpret_cast< Uint8 * >(&str[n]));
}
// Remove null characters in case the string was not a multiple of 16 when encrypted
while (!str.empty() && str.back() == 0)
{
str.pop_back();
}
// Return ownership of the encrypted string
return str;
}
// ================================================================================================
void Register_AES(HSQUIRRELVM vm)
{
RootTable(vm).Bind(Typename::Str,
Class< AES256 >(vm, Typename::Str)
// Constructors
.Ctor()
.Ctor< CSStr >()
// Meta-methods
.SquirrelFunc(_SC("_typename"), &Typename::Fn)
.Func(_SC("_tostring"), &AES256::ToString)
.Func(_SC("cmp"), &AES256::Cmp)
/* Properties */
.Prop(_SC("Key"), &AES256::GetKey)
/* Functions */
.Func(_SC("Init"), &AES256::Init)
.Func(_SC("Done"), &AES256::Done)
.Func(_SC("Encrypt"), &AES256::Encrypt)
.Func(_SC("Decrypt"), &AES256::Decrypt)
);
}
} // Namespace:: SqMod

View File

@ -1,102 +0,0 @@
#pragma once
// ------------------------------------------------------------------------------------------------
#include "SqBase.hpp"
// ------------------------------------------------------------------------------------------------
#include <aes256.h>
// ------------------------------------------------------------------------------------------------
namespace SqMod {
/* ------------------------------------------------------------------------------------------------
* Simple wrapper around a the AES encryption context.
*/
class AES256
{
public:
/* --------------------------------------------------------------------------------------------
* Default constructor.
*/
AES256();
/* --------------------------------------------------------------------------------------------
* Construct with an explicit key.
*/
AES256(CSStr key);
/* --------------------------------------------------------------------------------------------
* Copy constructor.
*/
AES256(const AES256 & o) = default;
/* --------------------------------------------------------------------------------------------
* Move constructor.
*/
AES256(AES256 && o) = default;
/* --------------------------------------------------------------------------------------------
* Destructor.
*/
~AES256() = default;
/* --------------------------------------------------------------------------------------------
* Copy assignment operator.
*/
AES256 & operator = (const AES256 & o) = default;
/* --------------------------------------------------------------------------------------------
* Move assignment operator.
*/
AES256 & operator = (AES256 && o) = default;
/* --------------------------------------------------------------------------------------------
* Used by the script engine to compare two instances of this type.
*/
Int32 Cmp(const AES256 & o) const;
/* --------------------------------------------------------------------------------------------
* Used by the script engine to convert an instance of this type to a string.
*/
CSStr ToString() const;
/* --------------------------------------------------------------------------------------------
* Retrieve the associated key.
*/
CSStr GetKey() const;
/* --------------------------------------------------------------------------------------------
* Initialize the context key.
*/
bool Init(CSStr key);
/* --------------------------------------------------------------------------------------------
* Reset the associated context.
*/
void Done();
/* --------------------------------------------------------------------------------------------
* Encrypt the specified string.
*/
String Encrypt(CSStr data);
/* --------------------------------------------------------------------------------------------
* Decrypt the specified string.
*/
String Decrypt(CSStr data);
private:
/* --------------------------------------------------------------------------------------------
* The managed encryption context.
*/
aes256_context m_Context;
/* --------------------------------------------------------------------------------------------
* The key used to encrypt data.
*/
Uint8 m_Buffer[32]{0};
};
} // Namespace:: SqMod

View File

@ -1,192 +0,0 @@
// ------------------------------------------------------------------------------------------------
#include "Library/Crypt/Hash.hpp"
#include "Base/Shared.hpp"
// ------------------------------------------------------------------------------------------------
#include <crc32.h>
#include <keccak.h>
#include <md5.h>
#include <sha1.h>
#include <sha256.h>
#include <sha3.h>
#include <b64.h>
#include <whirlpool.h>
// ------------------------------------------------------------------------------------------------
#include <cstdlib>
#include <cstring>
// ------------------------------------------------------------------------------------------------
namespace SqMod {
/* ------------------------------------------------------------------------------------------------
* Utility to avoid creating encoder instances for each call.
*/
template < class T > struct BaseHash
{
static T Algo;
};
// ------------------------------------------------------------------------------------------------
template < class T > T BaseHash< T >::Algo;
/* ------------------------------------------------------------------------------------------------
* Hash the specified value or the result of a formatted string.
*/
template < class T > static SQInteger HashF(HSQUIRRELVM vm)
{
// Attempt to retrieve the value from the stack as a string
StackStrF val(vm, 2);
// Have we failed to retrieve the string?
if (SQ_FAILED(val.Proc(true)))
{
return val.mRes; // Propagate the error!
}
// Forward the call to the actual implementation and store the string
String str(BaseHash< T >::Algo(val.mPtr));
// Push the string on the stack
sq_pushstring(vm, str.data(), str.size());
// At this point we have a valid string on the stack
return 1;
}
/* ------------------------------------------------------------------------------------------------
* Hash the specified value or the result of a formatted string with whirlpool algorithm.
*/
static SQInteger WhirlpoolF(HSQUIRRELVM vm)
{
// Attempt to retrieve the value from the stack as a string
StackStrF val(vm, 2);
// Have we failed to retrieve the string?
if (SQ_FAILED(val.Proc(true)))
{
return val.mRes; // Propagate the error!
}
// Prepare a whirlpool hashing context
whirlpool_ctx ctx;
// Initialize the hashing context
rhash_whirlpool_init(&ctx);
// Update the context with the given string
rhash_whirlpool_update(&ctx, reinterpret_cast< const unsigned char * >(val.mPtr),
val.mLen < 0 ? 0 : static_cast< size_t >(val.mLen));
// Reserve space for the result in binary form
unsigned char raw_hash[whirlpool_block_size];
// Finalize hashing and obtain the result
rhash_whirlpool_final(&ctx, raw_hash);
// Reserve space for the hexadecimal string
char hex_hash[whirlpool_block_size * 2];
// Convert from binary form to hex string
for (int i = 0, p = 0; i < whirlpool_block_size; ++i)
{
static const char dec2hex[16+1] = "0123456789abcdef";
hex_hash[p++] = dec2hex[(raw_hash[i] >> 4) & 15];
hex_hash[p++] = dec2hex[ raw_hash[i] & 15];
}
// Push the string on the stack
sq_pushstring(vm, hex_hash, whirlpool_block_size * 2);
// At this point we have a valid string on the stack
return 1;
}
/* ------------------------------------------------------------------------------------------------
* Encode the specified value or the result of a formatted string with base64 algorithm.
*/
static SQInteger EncodeBase64F(HSQUIRRELVM vm)
{
// Attempt to retrieve the value from the stack as a string
StackStrF val(vm, 2);
// Have we failed to retrieve the string?
if (SQ_FAILED(val.Proc(true)))
{
return val.mRes; // Propagate the error!
}
// Size of the encoded string
size_t enclen = 0;
// Attempt to encode the resulted string
char * result = b64_encode_ex(reinterpret_cast< const unsigned char * >(val.mPtr),
val.mLen < 0 ? 0 : static_cast< size_t >(val.mLen), &enclen);
// Did we fail to allocate memory for it?
if (!result)
{
return sq_throwerror(vm, _SC("Unable to allocate memory for output"));
}
// Push the string on the stack
sq_pushstring(vm, result, ConvTo< SQInteger >::From(enclen));
// At this point we have a valid string on the stack
return 1;
}
/* ------------------------------------------------------------------------------------------------
* Decode the specified value or the result of a formatted string with base64 algorithm.
*/
static SQInteger DecodeBase64F(HSQUIRRELVM vm)
{
// Attempt to retrieve the value from the stack as a string
StackStrF val(vm, 2);
// Have we failed to retrieve the string?
if (SQ_FAILED(val.Proc(true)))
{
return val.mRes; // Propagate the error!
}
// Size of the decoded string
size_t declen = 0;
// Attempt to decode the resulted string
unsigned char * result = b64_decode_ex(val.mPtr, val.mLen < 0 ? 0 : static_cast< size_t >(val.mLen), &declen);
// Did we fail to allocate memory for it?
if (!result)
{
return sq_throwerror(vm, _SC("Unable to allocate memory for output"));
}
// Push the string on the stack
sq_pushstring(vm, reinterpret_cast< CSStr >(result), ConvTo< SQInteger >::From(declen));
// At this point we have a valid string on the stack
return 1;
}
// ================================================================================================
template < class T > static void RegisterWrapper(Table & hashns, CCStr cname)
{
typedef HashWrapper< T > Hash;
hashns.Bind(cname,
Class< Hash >(hashns.GetVM(), cname)
// Constructors
.Ctor()
// Meta-methods
.Func(_SC("_tostring"), &Hash::ToString)
// Properties
.Prop(_SC("Hash"), &Hash::GetHash)
// Functions
.Func(_SC("Reset"), &Hash::Reset)
.Func(_SC("Compute"), &Hash::Compute)
.Func(_SC("GetHash"), &Hash::GetHash)
.Func(_SC("Add"), &Hash::AddStr)
.Func(_SC("AddStr"), &Hash::AddStr)
);
}
// ================================================================================================
void Register_Hash(HSQUIRRELVM vm)
{
Table hashns(vm);
RegisterWrapper< CRC32 >(hashns, _SC("CRC32"));
RegisterWrapper< Keccak >(hashns, _SC("Keccak"));
RegisterWrapper< MD5 >(hashns, _SC("MD5"));
RegisterWrapper< SHA1 >(hashns, _SC("SHA1"));
RegisterWrapper< SHA256 >(hashns, _SC("SHA256"));
RegisterWrapper< SHA3 >(hashns, _SC("SHA3"));
hashns.SquirrelFunc(_SC("GetCRC32"), &HashF< CRC32 >);
hashns.SquirrelFunc(_SC("GetKeccak"), &HashF< Keccak >);
hashns.SquirrelFunc(_SC("GetMD5"), &HashF< MD5 >);
hashns.SquirrelFunc(_SC("GetSHA1"), &HashF< SHA1 >);
hashns.SquirrelFunc(_SC("GetSHA256"), &HashF< SHA256 >);
hashns.SquirrelFunc(_SC("GetSHA3"), &HashF< SHA3 >);
hashns.SquirrelFunc(_SC("GetWhirlpool"), &WhirlpoolF);
hashns.SquirrelFunc(_SC("EncodeBase64"), &EncodeBase64F);
hashns.SquirrelFunc(_SC("DecodeBase64"), &DecodeBase64F);
RootTable(vm).Bind(_SC("SqHash"), hashns);
}
} // Namespace:: SqMod

View File

@ -1,99 +0,0 @@
#pragma once
// ------------------------------------------------------------------------------------------------
#include "SqBase.hpp"
// ------------------------------------------------------------------------------------------------
namespace SqMod {
/* ------------------------------------------------------------------------------------------------
* Simple class to maintain the state of an encoder.
*/
template < class T > class HashWrapper
{
public:
/* --------------------------------------------------------------------------------------------
* Default constructor.
*/
HashWrapper()
: m_Encoder()
{
/* ... */
}
/* --------------------------------------------------------------------------------------------
* Copy operator.
*/
HashWrapper(const HashWrapper & o)
: m_Encoder(o.m_Encoder)
{
/* ... */
}
/* --------------------------------------------------------------------------------------------
* Destructor.
*/
~HashWrapper()
{
/* ... */
}
/* --------------------------------------------------------------------------------------------
* Copy assignment operator.
*/
HashWrapper & operator = (const HashWrapper & o)
{
m_Encoder = o.m_Encoder;
return *this;
}
/* --------------------------------------------------------------------------------------------
* Used by the script engine to convert an instance of this type to a string.
*/
String ToString()
{
return m_Encoder.getHash();
}
/* --------------------------------------------------------------------------------------------
* Reset the encoder state.
*/
void Reset()
{
m_Encoder.reset();
}
/* --------------------------------------------------------------------------------------------
* Compute the hash of the specified string.
*/
String Compute(const String & str)
{
return m_Encoder(str);
}
/* --------------------------------------------------------------------------------------------
* Retrieve the hash value of the data hashed so far.
*/
String GetHash()
{
return m_Encoder.getHash();
}
/* --------------------------------------------------------------------------------------------
* Add a string value to be hashed.
*/
void AddStr(const String & str)
{
m_Encoder.add(str.data(), str.length() * sizeof(String::value_type));
}
private:
/* --------------------------------------------------------------------------------------------
* The managed encoder state.
*/
T m_Encoder;
};
} // Namespace:: SqMod

View File

@ -5,11 +5,13 @@
namespace SqMod {
// ------------------------------------------------------------------------------------------------
extern void Register_Buffer(HSQUIRRELVM vm);
extern void Register_INI(HSQUIRRELVM vm);
// ================================================================================================
void Register_IO(HSQUIRRELVM vm)
{
Register_Buffer(vm);
Register_INI(vm);
}

View File

@ -1,7 +1,7 @@
#pragma once
// ------------------------------------------------------------------------------------------------
#include "Base/Shared.hpp"
#include "Core/Common.hpp"
// ------------------------------------------------------------------------------------------------
namespace SqMod {

View File

@ -1,25 +1,20 @@
// ------------------------------------------------------------------------------------------------
#include "Library/Utils/Buffer.hpp"
#include "Library/Numeric/LongInt.hpp"
#include "Library/IO/Buffer.hpp"
#include "Library/Numeric/Long.hpp"
#include "Base/AABB.hpp"
#include "Base/Circle.hpp"
#include "Base/Color3.hpp"
#include "Base/Color4.hpp"
#include "Base/Quaternion.hpp"
#include "Base/Sphere.hpp"
#include "Base/Vector2.hpp"
#include "Base/Vector2i.hpp"
#include "Base/Vector3.hpp"
#include "Base/Vector4.hpp"
// ------------------------------------------------------------------------------------------------
#include <cstring>
// ------------------------------------------------------------------------------------------------
namespace SqMod {
// ------------------------------------------------------------------------------------------------
SQMODE_DECL_TYPENAME(Typename, _SC("SqBuffer"))
SQMOD_DECL_TYPENAME(Typename, _SC("SqBuffer"))
// ------------------------------------------------------------------------------------------------
void SqBuffer::WriteInt64(const SLongInt & val)
@ -27,7 +22,7 @@ void SqBuffer::WriteInt64(const SLongInt & val)
// Validate the managed buffer reference
Validate();
// Perform the requested operation
m_Buffer->Push< Int64 >(val.GetNum());
m_Buffer->Push< int64_t >(val.GetNum());
}
// ------------------------------------------------------------------------------------------------
@ -36,7 +31,7 @@ void SqBuffer::WriteUint64(const ULongInt & val)
// Validate the managed buffer reference
Validate();
// Perform the requested operation
m_Buffer->Push< Uint64 >(val.GetNum());
m_Buffer->Push< uint64_t >(val.GetNum());
}
// ------------------------------------------------------------------------------------------------
@ -72,11 +67,11 @@ SQInteger SqBuffer::WriteClientString(StackStrF & val)
STHROWF("String too large");
}
// Calculate the string length
Uint16 length = ConvTo< Uint16 >::From(val.mLen);
uint16_t length = ConvTo< uint16_t >::From(val.mLen);
// Change the size endianness to big endian
Uint16 size = ((length >> 8) & 0xFF) | ((length & 0xFF) << 8);
auto size = static_cast< uint16_t >(((length >> 8) & 0xFF) | ((length & 0xFF) << 8));
// Write the size and then the string contents
m_Buffer->Push< Uint16 >(size);
m_Buffer->Push< uint16_t >(size);
m_Buffer->AppendS(val.mPtr, length);
// Return the length of the written string
return val.mLen;
@ -178,9 +173,9 @@ SLongInt SqBuffer::ReadInt64()
// Validate the managed buffer reference
ValidateDeeper();
// Read one element from the buffer
const Int64 value = m_Buffer->Cursor< Int64 >();
const int64_t value = m_Buffer->Cursor< int64_t >();
// Advance the buffer cursor
m_Buffer->Advance< Int64 >(1);
m_Buffer->Advance< int64_t >(1);
// Return the requested information
return SLongInt(value);
}
@ -191,9 +186,9 @@ ULongInt SqBuffer::ReadUint64()
// Validate the managed buffer reference
ValidateDeeper();
// Read one element from the buffer
const Uint64 value = m_Buffer->Cursor< Uint64 >();
const uint64_t value = m_Buffer->Cursor< uint64_t >();
// Advance the buffer cursor
m_Buffer->Advance< Uint64 >(1);
m_Buffer->Advance< uint64_t >(1);
// Return the requested information
return ULongInt(value);
}
@ -209,7 +204,7 @@ LightObj SqBuffer::ReadRawString(SQInteger length)
if (length < 0)
{
// Grab the buffer range to search for
CCStr ptr = &m_Buffer->Cursor(), itr = ptr, end = m_Buffer->End();
const char * ptr = &m_Buffer->Cursor(), * itr = ptr, * end = m_Buffer->End();
// Attempt to look for a string terminator
while (itr != end && *itr != '\0')
{
@ -244,17 +239,17 @@ LightObj SqBuffer::ReadClientString()
// Validate the managed buffer reference
ValidateDeeper();
// Read one element from the buffer
Uint16 length = m_Buffer->Cursor< Uint16 >();
uint16_t length = m_Buffer->Cursor< uint16_t >();
// Convert the length to little endian
length = ((length >> 8) & 0xFF) | ((length & 0xFF) << 8);
length = static_cast< uint16_t >(((length >> 8) & 0xFF) | ((length & 0xFF) << 8));
// Validate the obtained length
if ((m_Buffer->Position() + sizeof(Uint16) + length) > m_Buffer->Capacity())
if ((m_Buffer->Position() + sizeof(uint16_t) + length) > m_Buffer->Capacity())
{
STHROWF("String of size (%u) starting at (%u) is out of buffer capacity (%u)",
length, m_Buffer->Position() + sizeof(Uint16), m_Buffer->Capacity());
length, m_Buffer->Position() + sizeof(uint16_t), m_Buffer->Capacity());
}
// Advance the buffer to the actual string
m_Buffer->Advance< Uint16 >(1);
m_Buffer->Advance< uint16_t >(1);
// Remember the current stack size
const StackGuard sg;
// Attempt to create the string as an object

View File

@ -1,8 +1,8 @@
#pragma once
// ------------------------------------------------------------------------------------------------
#include "Base/Shared.hpp"
#include "Base/Buffer.hpp"
#include "Core/Buffer.hpp"
#include "Core/Utility.hpp"
// ------------------------------------------------------------------------------------------------
namespace SqMod {
@ -39,11 +39,6 @@ public:
public:
/* --------------------------------------------------------------------------------------------
* Create a memory buffer with the requested size.
*/
static Object Create(SzType n);
/* --------------------------------------------------------------------------------------------
* Default constructor.
*/
@ -56,7 +51,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Allocate constructor.
*/
SqBuffer(SQInteger n)
explicit SqBuffer(SQInteger n)
: m_Buffer(new Buffer(ConvTo< SzType >::From(n)))
{
/* ... */
@ -92,7 +87,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Reference constructor.
*/
SqBuffer(const SRef & ref)
explicit SqBuffer(const SRef & ref) // NOLINT(modernize-pass-by-value)
: m_Buffer(ref)
{
/* ... */
@ -101,7 +96,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Buffer constructor.
*/
SqBuffer(const Buffer & b)
explicit SqBuffer(const Buffer & b)
: m_Buffer(new Buffer(b))
{
/* ... */
@ -110,7 +105,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Buffer constructor.
*/
SqBuffer(Buffer && b)
explicit SqBuffer(Buffer && b)
: m_Buffer(new Buffer(std::move(b)))
{
/* ... */
@ -144,7 +139,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Retrieve a reference to the managed memory buffer.
*/
const SRef & GetRef() const
SQMOD_NODISCARD const SRef & GetRef() const
{
return m_Buffer;
}
@ -181,7 +176,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Retrieve a certain element type at the specified position.
*/
Value Get(SQInteger n) const
SQMOD_NODISCARD Value Get(SQInteger n) const
{
// Validate the managed buffer reference
Validate();
@ -203,7 +198,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Retrieve the element at the front of the buffer.
*/
Value GetFront() const
SQMOD_NODISCARD Value GetFront() const
{
// Validate the managed buffer reference
Validate();
@ -225,7 +220,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Retrieve the element after the first element in the buffer.
*/
Value GetNext() const
SQMOD_NODISCARD Value GetNext() const
{
// Validate the managed buffer reference
Validate();
@ -247,7 +242,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Retrieve the element at the back of the buffer.
*/
Value GetBack() const
SQMOD_NODISCARD Value GetBack() const
{
// Validate the managed buffer reference
Validate();
@ -269,7 +264,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Retrieve the element before the last element in the buffer.
*/
Value GetPrev() const
SQMOD_NODISCARD Value GetPrev() const
{
// Validate the managed buffer reference
Validate();
@ -335,7 +330,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Retrieve the element at the cursor position.
*/
Value GetCursor() const
SQMOD_NODISCARD Value GetCursor() const
{
// Validate the managed buffer reference
Validate();
@ -357,7 +352,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Retrieve the element before the cursor position.
*/
Value GetBefore() const
SQMOD_NODISCARD Value GetBefore() const
{
// Validate the managed buffer reference
Validate();
@ -379,7 +374,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Retrieve the element after the cursor position.
*/
Value GetAfter() const
SQMOD_NODISCARD Value GetAfter() const
{
// Validate the managed buffer reference
Validate();
@ -401,7 +396,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Retrieve maximum elements it can hold for a certain type.
*/
SzType GetMax() const
SQMOD_NODISCARD SzType GetMax() const // NOLINT(readability-convert-member-functions-to-static)
{
return Buffer::Max();
}
@ -409,7 +404,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Retrieve the current buffer capacity in element count.
*/
SzType GetSize() const
SQMOD_NODISCARD SzType GetSize() const
{
// Validate the managed buffer reference
Validate();
@ -420,7 +415,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Retrieve the current buffer capacity in byte count.
*/
SzType GetCapacity() const
SQMOD_NODISCARD SzType GetCapacity() const
{
// Validate the managed buffer reference
Validate();
@ -431,7 +426,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Retrieve the current position of the cursor in the buffer.
*/
SzType GetPosition() const
SQMOD_NODISCARD SzType GetPosition() const
{
// Validate the managed buffer reference
Validate();
@ -442,7 +437,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Retrieve the amount of unused buffer after the edit cursor.
*/
SzType GetRemaining() const
SQMOD_NODISCARD SzType GetRemaining() const
{
// Validate the managed buffer reference
Validate();
@ -490,7 +485,7 @@ public:
// Validate the managed buffer reference
Validate();
// Perform the requested operation
m_Buffer->Push< Int8 >(ConvTo< Int8 >::From(val));
m_Buffer->Push< int8_t >(ConvTo< int8_t >::From(val));
}
/* --------------------------------------------------------------------------------------------
@ -501,7 +496,7 @@ public:
// Validate the managed buffer reference
Validate();
// Perform the requested operation
m_Buffer->Push< Uint8 >(ConvTo< Uint8 >::From(val));
m_Buffer->Push< uint8_t >(ConvTo< uint8_t >::From(val));
}
/* --------------------------------------------------------------------------------------------
@ -512,7 +507,7 @@ public:
// Validate the managed buffer reference
Validate();
// Perform the requested operation
m_Buffer->Push< Int16 >(ConvTo< Int16 >::From(val));
m_Buffer->Push< int16_t >(ConvTo< int16_t >::From(val));
}
/* --------------------------------------------------------------------------------------------
@ -523,7 +518,7 @@ public:
// Validate the managed buffer reference
Validate();
// Perform the requested operation
m_Buffer->Push< Uint16 >(ConvTo< Uint16 >::From(val));
m_Buffer->Push< uint16_t >(ConvTo< uint16_t >::From(val));
}
/* --------------------------------------------------------------------------------------------
@ -534,7 +529,7 @@ public:
// Validate the managed buffer reference
Validate();
// Perform the requested operation
m_Buffer->Push< Int32 >(ConvTo< Int32 >::From(val));
m_Buffer->Push< int32_t >(ConvTo< int32_t >::From(val));
}
/* --------------------------------------------------------------------------------------------
@ -545,7 +540,7 @@ public:
// Validate the managed buffer reference
Validate();
// Perform the requested operation
m_Buffer->Push< Uint32 >(ConvTo< Uint32 >::From(val));
m_Buffer->Push< uint32_t >(ConvTo< uint32_t >::From(val));
}
/* --------------------------------------------------------------------------------------------
@ -566,7 +561,7 @@ public:
// Validate the managed buffer reference
Validate();
// Perform the requested operation
m_Buffer->Push< Float32 >(ConvTo< Float32 >::From(val));
m_Buffer->Push< float >(ConvTo< float >::From(val));
}
/* --------------------------------------------------------------------------------------------
@ -577,7 +572,7 @@ public:
// Validate the managed buffer reference
Validate();
// Perform the requested operation
m_Buffer->Push< Float64 >(ConvTo< Float64 >::From(val));
m_Buffer->Push< double >(ConvTo< double >::From(val));
}
/* --------------------------------------------------------------------------------------------
@ -648,9 +643,9 @@ public:
// Validate the managed buffer reference
ValidateDeeper();
// Read one element from the buffer
const Int8 value = m_Buffer->Cursor< Int8 >();
const int8_t value = m_Buffer->Cursor< int8_t >();
// Advance the buffer cursor
m_Buffer->Advance< Int8 >(1);
m_Buffer->Advance< int8_t >(1);
// Return the requested information
return ConvTo< SQInteger >::From(value);
}
@ -663,9 +658,9 @@ public:
// Validate the managed buffer reference
ValidateDeeper();
// Read one element from the buffer
const Uint8 value = m_Buffer->Cursor< Uint8 >();
const uint8_t value = m_Buffer->Cursor< uint8_t >();
// Advance the buffer cursor
m_Buffer->Advance< Uint8 >(1);
m_Buffer->Advance< uint8_t >(1);
// Return the requested information
return ConvTo< SQInteger >::From(value);
}
@ -678,9 +673,9 @@ public:
// Validate the managed buffer reference
ValidateDeeper();
// Read one element from the buffer
const Int16 value = m_Buffer->Cursor< Int16 >();
const int16_t value = m_Buffer->Cursor< int16_t >();
// Advance the buffer cursor
m_Buffer->Advance< Int16 >(1);
m_Buffer->Advance< int16_t >(1);
// Return the requested information
return ConvTo< SQInteger >::From(value);
}
@ -693,9 +688,9 @@ public:
// Validate the managed buffer reference
ValidateDeeper();
// Read one element from the buffer
const Uint16 value = m_Buffer->Cursor< Uint16 >();
const uint16_t value = m_Buffer->Cursor< uint16_t >();
// Advance the buffer cursor
m_Buffer->Advance< Uint16 >(1);
m_Buffer->Advance< uint16_t >(1);
// Return the requested information
return ConvTo< SQInteger >::From(value);
}
@ -708,9 +703,9 @@ public:
// Validate the managed buffer reference
ValidateDeeper();
// Read one element from the buffer
const Int32 value = m_Buffer->Cursor< Int32 >();
const int32_t value = m_Buffer->Cursor< int32_t >();
// Advance the buffer cursor
m_Buffer->Advance< Int32 >(1);
m_Buffer->Advance< int32_t >(1);
// Return the requested information
return ConvTo< SQInteger >::From(value);
}
@ -723,9 +718,9 @@ public:
// Validate the managed buffer reference
ValidateDeeper();
// Read one element from the buffer
const Uint32 value = m_Buffer->Cursor< Uint32 >();
const uint32_t value = m_Buffer->Cursor< uint32_t >();
// Advance the buffer cursor
m_Buffer->Advance< Uint32 >(1);
m_Buffer->Advance< uint32_t >(1);
// Return the requested information
return ConvTo< SQInteger >::From(value);
}
@ -748,9 +743,9 @@ public:
// Validate the managed buffer reference
ValidateDeeper();
// Read one element from the buffer
const Float32 value = m_Buffer->Cursor< Float32 >();
const float value = m_Buffer->Cursor< float >();
// Advance the buffer cursor
m_Buffer->Advance< Float32 >(1);
m_Buffer->Advance< float >(1);
// Return the requested information
return ConvTo< SQFloat >::From(value);
}
@ -763,9 +758,9 @@ public:
// Validate the managed buffer reference
ValidateDeeper();
// Read one element from the buffer
const Float64 value = m_Buffer->Cursor< Float64 >();
const double value = m_Buffer->Cursor< double >();
// Advance the buffer cursor
m_Buffer->Advance< Float64 >(1);
m_Buffer->Advance< double >(1);
// Return the requested information
return ConvTo< SQFloat >::From(value);
}

View File

@ -2,15 +2,15 @@
#include "Library/IO/INI.hpp"
// ------------------------------------------------------------------------------------------------
#include <cerrno>
#include <sqratConst.h>
// ------------------------------------------------------------------------------------------------
namespace SqMod {
// ------------------------------------------------------------------------------------------------
SQMODE_DECL_TYPENAME(ResultTypename, _SC("SqIniResult"))
SQMODE_DECL_TYPENAME(EntriesTypename, _SC("SqIniEntries"))
SQMODE_DECL_TYPENAME(DocumentTypename, _SC("SqIniDocument"))
SQMOD_DECL_TYPENAME(ResultTypename, _SC("SqIniResult"))
SQMOD_DECL_TYPENAME(EntriesTypename, _SC("SqIniEntries"))
SQMOD_DECL_TYPENAME(DocumentTypename, _SC("SqIniDocument"))
// ------------------------------------------------------------------------------------------------
void IniResult::Check() const
@ -30,7 +30,7 @@ void IniResult::Check() const
case SI_OK:
case SI_UPDATED:
case SI_INSERTED:
break; /* These are not error messahes. */
break; /* These are not error messages. */
default:
STHROWF("Unable to %s for some unforeseen reason", m_Action.c_str());
}
@ -47,7 +47,7 @@ void IniDocumentRef::Validate() const
}
// ------------------------------------------------------------------------------------------------
Int32 IniEntries::Cmp(const IniEntries & o) const
int32_t IniEntries::Cmp(const IniEntries & o) const
{
if (m_Elem == o.m_Elem)
{
@ -84,7 +84,7 @@ void IniEntries::Prev()
}
// ------------------------------------------------------------------------------------------------
void IniEntries::Advance(Int32 n)
void IniEntries::Advance(int32_t n)
{
// Are there any other elements ahead?
if (m_List.empty() || m_Elem == m_List.end())
@ -99,7 +99,7 @@ void IniEntries::Advance(Int32 n)
}
// ------------------------------------------------------------------------------------------------
void IniEntries::Retreat(Int32 n)
void IniEntries::Retreat(int32_t n)
{
// Are there any other elements behind?
if (m_List.empty() || m_Elem == m_List.begin())
@ -114,7 +114,7 @@ void IniEntries::Retreat(Int32 n)
}
// ------------------------------------------------------------------------------------------------
CSStr IniEntries::GetItem() const
const SQChar * IniEntries::GetItem() const
{
// is the current element valid?
if (m_List.empty() || m_Elem == m_List.end())
@ -126,7 +126,7 @@ CSStr IniEntries::GetItem() const
}
// ------------------------------------------------------------------------------------------------
CSStr IniEntries::GetComment() const
const SQChar * IniEntries::GetComment() const
{
// is the current element valid?
if (m_List.empty() || m_Elem == m_List.end())
@ -138,7 +138,7 @@ CSStr IniEntries::GetComment() const
}
// ------------------------------------------------------------------------------------------------
Int32 IniEntries::GetOrder() const
int32_t IniEntries::GetOrder() const
{
// is the current element valid?
if (m_List.empty() || m_Elem == m_List.end())
@ -150,7 +150,7 @@ Int32 IniEntries::GetOrder() const
}
// ------------------------------------------------------------------------------------------------
Int32 IniDocument::Cmp(const IniDocument & o) const
int32_t IniDocument::Cmp(const IniDocument & o) const
{
if (m_Doc == o.m_Doc)
{
@ -167,7 +167,7 @@ Int32 IniDocument::Cmp(const IniDocument & o) const
}
// ------------------------------------------------------------------------------------------------
IniResult IniDocument::LoadFile(CSStr filepath)
IniResult IniDocument::LoadFile(const SQChar * filepath)
{
// Validate the handle
m_Doc.Validate();
@ -176,7 +176,7 @@ IniResult IniDocument::LoadFile(CSStr filepath)
}
// ------------------------------------------------------------------------------------------------
IniResult IniDocument::LoadData(CSStr source, Int32 size)
IniResult IniDocument::LoadData(const SQChar * source, int32_t size)
{
// Validate the handle
m_Doc.Validate();
@ -185,7 +185,7 @@ IniResult IniDocument::LoadData(CSStr source, Int32 size)
}
// ------------------------------------------------------------------------------------------------
IniResult IniDocument::SaveFile(CSStr filepath, bool signature)
IniResult IniDocument::SaveFile(const SQChar * filepath, bool signature)
{
// Validate the handle
m_Doc.Validate();
@ -227,7 +227,7 @@ IniEntries IniDocument::GetAllSections() const
}
// ------------------------------------------------------------------------------------------------
IniEntries IniDocument::GetAllKeys(CSStr section) const
IniEntries IniDocument::GetAllKeys(const SQChar * section) const
{
// Validate the handle
m_Doc.Validate();
@ -240,7 +240,7 @@ IniEntries IniDocument::GetAllKeys(CSStr section) const
}
// ------------------------------------------------------------------------------------------------
IniEntries IniDocument::GetAllValues(CSStr section, CSStr key) const
IniEntries IniDocument::GetAllValues(const SQChar * section, const SQChar * key) const
{
// Validate the handle
m_Doc.Validate();
@ -253,7 +253,7 @@ IniEntries IniDocument::GetAllValues(CSStr section, CSStr key) const
}
// ------------------------------------------------------------------------------------------------
Int32 IniDocument::GetSectionSize(CSStr section) const
int32_t IniDocument::GetSectionSize(const SQChar * section) const
{
// Validate the handle
m_Doc.Validate();
@ -262,11 +262,11 @@ Int32 IniDocument::GetSectionSize(CSStr section) const
}
// ------------------------------------------------------------------------------------------------
bool IniDocument::HasMultipleKeys(CSStr section, CSStr key) const
bool IniDocument::HasMultipleKeys(const SQChar * section, const SQChar * key) const
{
// Validate the handle
m_Doc.Validate();
// Where to retrive whether the key has multiple instances
// Where to retrieve whether the key has multiple instances
bool multiple = false;
// Attempt to query the information
if (m_Doc->GetValue(section, key, nullptr, &multiple) == nullptr)
@ -278,7 +278,7 @@ bool IniDocument::HasMultipleKeys(CSStr section, CSStr key) const
}
// ------------------------------------------------------------------------------------------------
CCStr IniDocument::GetValue(CSStr section, CSStr key, CSStr def) const
const char * IniDocument::GetValue(const SQChar * section, const SQChar * key, const SQChar * def) const
{
// Validate the handle
m_Doc.Validate();
@ -287,16 +287,16 @@ CCStr IniDocument::GetValue(CSStr section, CSStr key, CSStr def) const
}
// ------------------------------------------------------------------------------------------------
SQInteger IniDocument::GetInteger(CSStr section, CSStr key, SQInteger def) const
SQInteger IniDocument::GetInteger(const SQChar * section, const SQChar * key, SQInteger def) const
{
// Validate the handle
m_Doc.Validate();
// Attempt to query the information and return it
return static_cast< SQInteger >(m_Doc->GetLongValue(section, key, def, nullptr));
return static_cast< SQInteger >(m_Doc->GetLongValue(section, key, static_cast< long >(def), nullptr));
}
// ------------------------------------------------------------------------------------------------
SQFloat IniDocument::GetFloat(CSStr section, CSStr key, SQFloat def) const
SQFloat IniDocument::GetFloat(const SQChar * section, const SQChar * key, SQFloat def) const
{
// Validate the handle
m_Doc.Validate();
@ -305,7 +305,7 @@ SQFloat IniDocument::GetFloat(CSStr section, CSStr key, SQFloat def) const
}
// ------------------------------------------------------------------------------------------------
bool IniDocument::GetBoolean(CSStr section, CSStr key, bool def) const
bool IniDocument::GetBoolean(const SQChar * section, const SQChar * key, bool def) const
{
// Validate the handle
m_Doc.Validate();
@ -314,7 +314,7 @@ bool IniDocument::GetBoolean(CSStr section, CSStr key, bool def) const
}
// ------------------------------------------------------------------------------------------------
IniResult IniDocument::SetValue(CSStr section, CSStr key, CSStr value, bool force, CSStr comment)
IniResult IniDocument::SetValue(const SQChar * section, const SQChar * key, const SQChar * value, bool force, const SQChar * comment)
{
// Validate the handle
m_Doc.Validate();
@ -323,16 +323,16 @@ IniResult IniDocument::SetValue(CSStr section, CSStr key, CSStr value, bool forc
}
// ------------------------------------------------------------------------------------------------
IniResult IniDocument::SetInteger(CSStr section, CSStr key, SQInteger value, bool hex, bool force, CSStr comment)
IniResult IniDocument::SetInteger(const SQChar * section, const SQChar * key, SQInteger value, bool hex, bool force, const SQChar * comment)
{
// Validate the handle
m_Doc.Validate();
// Attempt to apply the specified information and return the result
return IniResult("set INI integer", m_Doc->SetLongValue(section, key, value, comment, hex, force));
return IniResult("set INI integer", m_Doc->SetLongValue(section, key, static_cast< long >(value), comment, hex, force));
}
// ------------------------------------------------------------------------------------------------
IniResult IniDocument::SetFloat(CSStr section, CSStr key, SQFloat value, bool force, CSStr comment)
IniResult IniDocument::SetFloat(const SQChar * section, const SQChar * key, SQFloat value, bool force, const SQChar * comment)
{
// Validate the handle
m_Doc.Validate();
@ -341,7 +341,7 @@ IniResult IniDocument::SetFloat(CSStr section, CSStr key, SQFloat value, bool fo
}
// ------------------------------------------------------------------------------------------------
IniResult IniDocument::SetBoolean(CSStr section, CSStr key, bool value, bool force, CSStr comment)
IniResult IniDocument::SetBoolean(const SQChar * section, const SQChar * key, bool value, bool force, const SQChar * comment)
{
// Validate the handle
m_Doc.Validate();
@ -350,7 +350,7 @@ IniResult IniDocument::SetBoolean(CSStr section, CSStr key, bool value, bool for
}
// ------------------------------------------------------------------------------------------------
bool IniDocument::DeleteValue(CSStr section, CSStr key, CSStr value, bool empty)
bool IniDocument::DeleteValue(const SQChar * section, const SQChar * key, const SQChar * value, bool empty)
{
// Validate the handle
m_Doc.Validate();
@ -367,7 +367,7 @@ void Register_INI(HSQUIRRELVM vm)
Class< IniResult >(vm, ResultTypename::Str)
// Constructors
.Ctor()
.Ctor< CSStr, SQInteger >()
.Ctor< const SQChar *, SQInteger >()
.Ctor< const IniResult & >()
// Core Meta-methods
.SquirrelFunc(_SC("_typename"), &ResultTypename::Fn)
@ -431,10 +431,10 @@ void Register_INI(HSQUIRRELVM vm)
// Member Methods
.Func(_SC("Reset"), &IniDocument::Reset)
.Func(_SC("LoadFile"), &IniDocument::LoadFile)
.Overload< IniResult (IniDocument::*)(CSStr) >(_SC("LoadString"), &IniDocument::LoadData)
.Overload< IniResult (IniDocument::*)(CSStr, Int32) >(_SC("LoadString"), &IniDocument::LoadData)
.Overload< IniResult (IniDocument::*)(CSStr) >(_SC("SaveFile"), &IniDocument::SaveFile)
.Overload< IniResult (IniDocument::*)(CSStr, bool) >(_SC("SaveFile"), &IniDocument::SaveFile)
.Overload< IniResult (IniDocument::*)(const SQChar *) >(_SC("LoadString"), &IniDocument::LoadData)
.Overload< IniResult (IniDocument::*)(const SQChar *, int32_t) >(_SC("LoadString"), &IniDocument::LoadData)
.Overload< IniResult (IniDocument::*)(const SQChar *) >(_SC("SaveFile"), &IniDocument::SaveFile)
.Overload< IniResult (IniDocument::*)(const SQChar *, bool) >(_SC("SaveFile"), &IniDocument::SaveFile)
.Func(_SC("SaveData"), &IniDocument::SaveData)
.Func(_SC("GetSections"), &IniDocument::GetAllSections)
.Func(_SC("GetKeys"), &IniDocument::GetAllKeys)
@ -445,34 +445,34 @@ void Register_INI(HSQUIRRELVM vm)
.Func(_SC("GetInteger"), &IniDocument::GetInteger)
.Func(_SC("GetFloat"), &IniDocument::GetFloat)
.Func(_SC("GetBoolean"), &IniDocument::GetBoolean)
.Overload< IniResult (IniDocument::*)(CSStr, CSStr, CSStr) >(_SC("SetValue"), &IniDocument::SetValue)
.Overload< IniResult (IniDocument::*)(CSStr, CSStr, CSStr, bool) >(_SC("SetValue"), &IniDocument::SetValue)
.Overload< IniResult (IniDocument::*)(CSStr, CSStr, CSStr, bool, CSStr) >(_SC("SetValue"), &IniDocument::SetValue)
.Overload< IniResult (IniDocument::*)(CSStr, CSStr, SQInteger) >(_SC("SetInteger"), &IniDocument::SetInteger)
.Overload< IniResult (IniDocument::*)(CSStr, CSStr, SQInteger, bool) >(_SC("SetInteger"), &IniDocument::SetInteger)
.Overload< IniResult (IniDocument::*)(CSStr, CSStr, SQInteger, bool, bool) >(_SC("SetInteger"), &IniDocument::SetInteger)
.Overload< IniResult (IniDocument::*)(CSStr, CSStr, SQInteger, bool, bool, CSStr) >(_SC("SetInteger"), &IniDocument::SetInteger)
.Overload< IniResult (IniDocument::*)(CSStr, CSStr, SQFloat) >(_SC("SetFloat"), &IniDocument::SetFloat)
.Overload< IniResult (IniDocument::*)(CSStr, CSStr, SQFloat, bool) >(_SC("SetFloat"), &IniDocument::SetFloat)
.Overload< IniResult (IniDocument::*)(CSStr, CSStr, SQFloat, bool, CSStr) >(_SC("SetFloat"), &IniDocument::SetFloat)
.Overload< IniResult (IniDocument::*)(CSStr, CSStr, bool) >(_SC("SetBoolean"), &IniDocument::SetBoolean)
.Overload< IniResult (IniDocument::*)(CSStr, CSStr, bool, bool) >(_SC("SetBoolean"), &IniDocument::SetBoolean)
.Overload< IniResult (IniDocument::*)(CSStr, CSStr, bool, bool, CSStr) >(_SC("SetBoolean"), &IniDocument::SetBoolean)
.Overload< bool (IniDocument::*)(CSStr) >(_SC("DeleteValue"), &IniDocument::DeleteValue)
.Overload< bool (IniDocument::*)(CSStr, CSStr) >(_SC("DeleteValue"), &IniDocument::DeleteValue)
.Overload< bool (IniDocument::*)(CSStr, CSStr, CSStr) >(_SC("DeleteValue"), &IniDocument::DeleteValue)
.Overload< bool (IniDocument::*)(CSStr, CSStr, CSStr, bool) >(_SC("DeleteValue"), &IniDocument::DeleteValue)
.Overload< IniResult (IniDocument::*)(const SQChar *, const SQChar *, const SQChar *) >(_SC("SetValue"), &IniDocument::SetValue)
.Overload< IniResult (IniDocument::*)(const SQChar *, const SQChar *, const SQChar *, bool) >(_SC("SetValue"), &IniDocument::SetValue)
.Overload< IniResult (IniDocument::*)(const SQChar *, const SQChar *, const SQChar *, bool, const SQChar *) >(_SC("SetValue"), &IniDocument::SetValue)
.Overload< IniResult (IniDocument::*)(const SQChar *, const SQChar *, SQInteger) >(_SC("SetInteger"), &IniDocument::SetInteger)
.Overload< IniResult (IniDocument::*)(const SQChar *, const SQChar *, SQInteger, bool) >(_SC("SetInteger"), &IniDocument::SetInteger)
.Overload< IniResult (IniDocument::*)(const SQChar *, const SQChar *, SQInteger, bool, bool) >(_SC("SetInteger"), &IniDocument::SetInteger)
.Overload< IniResult (IniDocument::*)(const SQChar *, const SQChar *, SQInteger, bool, bool, const SQChar *) >(_SC("SetInteger"), &IniDocument::SetInteger)
.Overload< IniResult (IniDocument::*)(const SQChar *, const SQChar *, SQFloat) >(_SC("SetFloat"), &IniDocument::SetFloat)
.Overload< IniResult (IniDocument::*)(const SQChar *, const SQChar *, SQFloat, bool) >(_SC("SetFloat"), &IniDocument::SetFloat)
.Overload< IniResult (IniDocument::*)(const SQChar *, const SQChar *, SQFloat, bool, const SQChar *) >(_SC("SetFloat"), &IniDocument::SetFloat)
.Overload< IniResult (IniDocument::*)(const SQChar *, const SQChar *, bool) >(_SC("SetBoolean"), &IniDocument::SetBoolean)
.Overload< IniResult (IniDocument::*)(const SQChar *, const SQChar *, bool, bool) >(_SC("SetBoolean"), &IniDocument::SetBoolean)
.Overload< IniResult (IniDocument::*)(const SQChar *, const SQChar *, bool, bool, const SQChar *) >(_SC("SetBoolean"), &IniDocument::SetBoolean)
.Overload< bool (IniDocument::*)(const SQChar *) >(_SC("DeleteValue"), &IniDocument::DeleteValue)
.Overload< bool (IniDocument::*)(const SQChar *, const SQChar *) >(_SC("DeleteValue"), &IniDocument::DeleteValue)
.Overload< bool (IniDocument::*)(const SQChar *, const SQChar *, const SQChar *) >(_SC("DeleteValue"), &IniDocument::DeleteValue)
.Overload< bool (IniDocument::*)(const SQChar *, const SQChar *, const SQChar *, bool) >(_SC("DeleteValue"), &IniDocument::DeleteValue)
);
RootTable(vm).Bind(_SC("SqIni"), inins);
ConstTable(vm).Enum(_SC("SqIniError"), Enumeration(vm)
.Const(_SC("Ok"), Int32(SI_OK))
.Const(_SC("Updated"), Int32(SI_UPDATED))
.Const(_SC("Inserted"), Int32(SI_INSERTED))
.Const(_SC("Fail"), Int32(SI_FAIL))
.Const(_SC("NoMem"), Int32(SI_NOMEM))
.Const(_SC("File"), Int32(SI_FILE))
.Const(_SC("Ok"), int32_t(SI_OK))
.Const(_SC("Updated"), int32_t(SI_UPDATED))
.Const(_SC("Inserted"), int32_t(SI_INSERTED))
.Const(_SC("Fail"), int32_t(SI_FAIL))
.Const(_SC("NoMem"), int32_t(SI_NOMEM))
.Const(_SC("File"), int32_t(SI_FILE))
);
}

View File

@ -1,7 +1,7 @@
#pragma once
// ------------------------------------------------------------------------------------------------
#include "Base/Shared.hpp"
#include "Core/Common.hpp"
// ------------------------------------------------------------------------------------------------
#include <SimpleIni.h>
@ -34,7 +34,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Construct with no specific result.
*/
explicit IniResult(CSStr action)
explicit IniResult(const SQChar * action)
: m_Action(!action ? _SC("") : action), m_Result(SI_OK)
{
/* ... */
@ -52,7 +52,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Construct with specific action and result.
*/
IniResult(CSStr action, SQInteger result)
IniResult(const SQChar * action, SQInteger result)
: m_Action(!action ? _SC("") : action), m_Result(result)
{
/* ... */
@ -61,30 +61,17 @@ public:
/* --------------------------------------------------------------------------------------------
* Copy constructor.
*/
IniResult(const IniResult & o)
: m_Action(o.m_Action), m_Result(o.m_Result)
{
/* ... */
}
IniResult(const IniResult & o) = default;
/* --------------------------------------------------------------------------------------------
* Destructor.
*/
~IniResult()
{
/* ... */
}
~IniResult() = default;
/* --------------------------------------------------------------------------------------------
* Copy assignment operator.
*/
IniResult & operator = (const IniResult & o)
{
m_Action = o.m_Action;
m_Result = o.m_Result;
return *this;
}
IniResult & operator = (const IniResult & o) = default;
/* --------------------------------------------------------------------------------------------
* Perform an equality comparison between two results.
@ -105,7 +92,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Implicit conversion to boolean for use in boolean operations.
*/
operator bool () const
operator bool () const // NOLINT(google-explicit-constructor)
{
return (m_Result >= 0);
}
@ -113,7 +100,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Used by the script engine to compare two instances of this type.
*/
Int32 Cmp(const IniResult & o) const
SQMOD_NODISCARD int32_t Cmp(const IniResult & o) const
{
if (m_Result == o.m_Result)
{
@ -132,7 +119,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Used by the script engine to convert an instance of this type to a string.
*/
CSStr ToString() const
SQMOD_NODISCARD const SQChar * ToString() const
{
return m_Action.c_str();
}
@ -140,7 +127,7 @@ public:
/* --------------------------------------------------------------------------------------------
* See whether this instance references a valid INI result.
*/
bool IsValid() const
SQMOD_NODISCARD bool IsValid() const
{
return (m_Result >= 0);
}
@ -148,7 +135,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Retrieve the associated action.
*/
CSStr GetAction() const
SQMOD_NODISCARD const SQChar * GetAction() const
{
return m_Action.c_str();
}
@ -156,7 +143,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Retrieve the resulted code.
*/
SQInteger GetResult() const
SQMOD_NODISCARD SQInteger GetResult() const
{
return m_Result;
}
@ -222,8 +209,8 @@ private:
{
delete m_Ptr;
delete m_Ref;
m_Ptr = NULL;
m_Ref = NULL;
m_Ptr = nullptr;
m_Ref = nullptr;
}
}
@ -242,7 +229,7 @@ public:
* Default constructor (null).
*/
IniDocumentRef()
: m_Ptr(NULL), m_Ref(NULL)
: m_Ptr(nullptr), m_Ref(nullptr)
{
/* ... */
}
@ -260,12 +247,12 @@ public:
/* --------------------------------------------------------------------------------------------
* Move constructor.
*/
IniDocumentRef(IniDocumentRef && o)
IniDocumentRef(IniDocumentRef && o) noexcept
: m_Ptr(o.m_Ptr), m_Ref(o.m_Ref)
{
o.m_Ptr = NULL;
o.m_Ref = NULL;
o.m_Ptr = nullptr;
o.m_Ref = nullptr;
}
/* --------------------------------------------------------------------------------------------
@ -279,7 +266,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Copy assignment operator.
*/
IniDocumentRef & operator = (const IniDocumentRef & o)
IniDocumentRef & operator = (const IniDocumentRef & o) noexcept // NOLINT(bugprone-unhandled-self-assignment)
{
if (m_Ptr != o.m_Ptr)
{
@ -294,14 +281,14 @@ public:
/* --------------------------------------------------------------------------------------------
* Move assignment operator.
*/
IniDocumentRef & operator = (IniDocumentRef && o)
IniDocumentRef & operator = (IniDocumentRef && o) noexcept
{
if (m_Ptr != o.m_Ptr)
{
m_Ptr = o.m_Ptr;
m_Ref = o.m_Ref;
o.m_Ptr = NULL;
o.m_Ref = NULL;
o.m_Ptr = nullptr;
o.m_Ref = nullptr;
}
return *this;
}
@ -325,7 +312,15 @@ public:
/* --------------------------------------------------------------------------------------------
* Implicit conversion to boolean for use in boolean operations.
*/
operator bool () const
operator bool () const // NOLINT(google-explicit-constructor)
{
return static_cast< bool >(m_Ptr);
}
/* --------------------------------------------------------------------------------------------
* Implicit conversion to the managed instance pointer.
*/
operator Pointer () // NOLINT(google-explicit-constructor)
{
return m_Ptr;
}
@ -333,15 +328,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Implicit conversion to the managed instance pointer.
*/
operator Pointer ()
{
return m_Ptr;
}
/* --------------------------------------------------------------------------------------------
* Implicit conversion to the managed instance pointer.
*/
operator ConstPtr () const
operator ConstPtr () const // NOLINT(google-explicit-constructor)
{
return m_Ptr;
}
@ -349,7 +336,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Implicit conversion to the managed instance reference.
*/
operator Reference ()
operator Reference () // NOLINT(google-explicit-constructor)
{
assert(m_Ptr);
return *m_Ptr;
@ -358,7 +345,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Implicit conversion to the managed instance reference.
*/
operator ConstRef () const
operator ConstRef () const // NOLINT(google-explicit-constructor)
{
assert(m_Ptr);
return *m_Ptr;
@ -385,7 +372,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Retrieve the number of active references to the managed instance.
*/
Counter Count() const
SQMOD_NODISCARD Counter Count() const
{
return (m_Ptr && m_Ref) ? (*m_Ref) : 0;
}
@ -410,7 +397,7 @@ protected:
/* --------------------------------------------------------------------------------------------
* Default constructor.
*/
IniEntries(const IniDocumentRef & ini, Container & list)
IniEntries(const IniDocumentRef & ini, Container & list) // NOLINT(modernize-pass-by-value)
: m_Doc(ini), m_List(), m_Elem()
{
m_List.swap(list);
@ -447,10 +434,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Destructor.
*/
~IniEntries()
{
/* ... */
}
~IniEntries() = default;
/* --------------------------------------------------------------------------------------------
* Copy assignment operator.
@ -466,12 +450,12 @@ public:
/* --------------------------------------------------------------------------------------------
* Used by the script engine to compare two instances of this type.
*/
Int32 Cmp(const IniEntries & o) const;
SQMOD_NODISCARD int32_t Cmp(const IniEntries & o) const;
/* --------------------------------------------------------------------------------------------
* Used by the script engine to convert an instance of this type to a string.
*/
CSStr ToString() const
SQMOD_NODISCARD const SQChar * ToString() const
{
return GetItem();
}
@ -479,7 +463,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Return whether the current element is valid and can be accessed.
*/
bool IsValid() const
SQMOD_NODISCARD bool IsValid() const
{
return !(m_List.empty() || m_Elem == m_List.end());
}
@ -487,7 +471,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Return whether the entry list is empty.
*/
bool IsEmpty() const
SQMOD_NODISCARD bool IsEmpty() const
{
return m_List.empty();
}
@ -495,7 +479,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Return the number of active references to this document instance.
*/
Uint32 GetRefCount() const
SQMOD_NODISCARD uint32_t GetRefCount() const
{
return m_Doc.Count();
}
@ -503,9 +487,9 @@ public:
/* --------------------------------------------------------------------------------------------
* Return the total entries in the list.
*/
Int32 GetSize() const
SQMOD_NODISCARD int32_t GetSize() const
{
return static_cast< Int32 >(m_List.size());
return static_cast< int32_t >(m_List.size());
}
/* --------------------------------------------------------------------------------------------
@ -536,12 +520,12 @@ public:
/* --------------------------------------------------------------------------------------------
* Advance a certain number of elements.
*/
void Advance(Int32 n);
void Advance(int32_t n);
/* --------------------------------------------------------------------------------------------
* Retreat a certain number of elements.
*/
void Retreat(Int32 n);
void Retreat(int32_t n);
/* --------------------------------------------------------------------------------------------
* Sort the entries using the default options.
@ -579,17 +563,17 @@ public:
/* --------------------------------------------------------------------------------------------
* Retrieve the string value of the current element item.
*/
CSStr GetItem() const;
SQMOD_NODISCARD const SQChar * GetItem() const;
/* --------------------------------------------------------------------------------------------
* Retrieve the string value of the current element comment.
*/
CSStr GetComment() const;
SQMOD_NODISCARD const SQChar * GetComment() const;
/* --------------------------------------------------------------------------------------------
* Retrieve the order of the current element.
*/
Int32 GetOrder() const;
SQMOD_NODISCARD int32_t GetOrder() const;
};
/* ------------------------------------------------------------------------------------------------
@ -602,16 +586,6 @@ protected:
// --------------------------------------------------------------------------------------------
typedef IniDocumentRef::Type::TNamesDepend Container;
/* --------------------------------------------------------------------------------------------
* Copy constructor. (disabled)
*/
IniDocument(const IniDocument & o);
/* --------------------------------------------------------------------------------------------
* Copy assignment operator. (disabled)
*/
IniDocument & operator = (const IniDocument & o);
private:
// ---------------------------------------------------------------------------------------------
@ -631,7 +605,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Explicit constructor.
*/
IniDocument(bool utf8)
explicit IniDocument(bool utf8)
: m_Doc(utf8, false, true)
{
/* ... */
@ -655,23 +629,30 @@ public:
/* ... */
}
/* --------------------------------------------------------------------------------------------
* Copy constructor. (disabled)
*/
IniDocument(const IniDocument & o) = delete;
/* --------------------------------------------------------------------------------------------
* Destructor.
*/
~IniDocument()
{
/* ... */
}
~IniDocument() = default;
/* --------------------------------------------------------------------------------------------
* Copy assignment operator. (disabled)
*/
IniDocument & operator = (const IniDocument & o) = delete;
/* --------------------------------------------------------------------------------------------
* Used by the script engine to compare two instances of this type.
*/
Int32 Cmp(const IniDocument & o) const;
SQMOD_NODISCARD int32_t Cmp(const IniDocument & o) const;
/* --------------------------------------------------------------------------------------------
* Used by the script engine to convert an instance of this type to a string.
*/
CSStr ToString() const
SQMOD_NODISCARD const SQChar * ToString() const // NOLINT(readability-convert-member-functions-to-static)
{
return _SC("");
}
@ -679,7 +660,7 @@ public:
/* --------------------------------------------------------------------------------------------
* See whether this instance references a valid INI document.
*/
bool IsValid() const
SQMOD_NODISCARD bool IsValid() const
{
return m_Doc;
}
@ -687,7 +668,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Return the number of active references to this document instance.
*/
Uint32 GetRefCount() const
SQMOD_NODISCARD uint32_t GetRefCount() const
{
return m_Doc.Count();
}
@ -695,7 +676,7 @@ public:
/* --------------------------------------------------------------------------------------------
* See whether any data has been loaded into this document.
*/
bool IsEmpty() const
SQMOD_NODISCARD bool IsEmpty() const
{
return m_Doc->IsEmpty();
}
@ -711,7 +692,7 @@ public:
/* --------------------------------------------------------------------------------------------
* See whether the INI data is treated as unicode.
*/
bool GetUnicode() const
SQMOD_NODISCARD bool GetUnicode() const
{
return m_Doc->IsUnicode();
}
@ -727,7 +708,7 @@ public:
/* --------------------------------------------------------------------------------------------
* See whether multiple identical keys be permitted in the file.
*/
bool GetMultiKey() const
SQMOD_NODISCARD bool GetMultiKey() const
{
return m_Doc->IsMultiKey();
}
@ -743,7 +724,7 @@ public:
/* --------------------------------------------------------------------------------------------
* See whether data values are permitted to span multiple lines in the file.
*/
bool GetMultiLine() const
SQMOD_NODISCARD bool GetMultiLine() const
{
return m_Doc->IsMultiLine();
}
@ -759,7 +740,7 @@ public:
/* --------------------------------------------------------------------------------------------
* See whether spaces are added around the equals sign when writing key/value pairs out.
*/
bool GetSpaces() const
SQMOD_NODISCARD bool GetSpaces() const
{
return m_Doc->UsingSpaces();
}
@ -775,12 +756,12 @@ public:
/* --------------------------------------------------------------------------------------------
* Load an INI file from disk into memory.
*/
IniResult LoadFile(CSStr filepath);
IniResult LoadFile(const SQChar * filepath);
/* --------------------------------------------------------------------------------------------
* Load INI file data direct from a string. (LoadString collides with the windows api)
*/
IniResult LoadData(CSStr source)
IniResult LoadData(const SQChar * source)
{
return LoadData(source, -1);
}
@ -788,12 +769,12 @@ public:
/* --------------------------------------------------------------------------------------------
* Load INI file data direct from a string. (LoadString collides with the windows api)
*/
IniResult LoadData(CSStr source, Int32 size);
IniResult LoadData(const SQChar * source, int32_t size);
/* --------------------------------------------------------------------------------------------
* Save an INI file from memory to disk.
*/
IniResult SaveFile(CSStr filepath)
IniResult SaveFile(const SQChar * filepath)
{
return SaveFile(filepath, true);
}
@ -801,7 +782,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Save an INI file from memory to disk.
*/
IniResult SaveFile(CSStr filepath, bool signature);
IniResult SaveFile(const SQChar * filepath, bool signature);
/* --------------------------------------------------------------------------------------------
* Save the INI data to a string.
@ -811,52 +792,52 @@ public:
/* --------------------------------------------------------------------------------------------
* Retrieve all section names.
*/
IniEntries GetAllSections() const;
SQMOD_NODISCARD IniEntries GetAllSections() const;
/* --------------------------------------------------------------------------------------------
* Retrieve all unique key names in a section.
*/
IniEntries GetAllKeys(CSStr section) const;
SQMOD_NODISCARD IniEntries GetAllKeys(const SQChar * section) const;
/* --------------------------------------------------------------------------------------------
* Retrieve all values for a specific key.
*/
IniEntries GetAllValues(CSStr section, CSStr key) const;
SQMOD_NODISCARD IniEntries GetAllValues(const SQChar * section, const SQChar * key) const;
/* --------------------------------------------------------------------------------------------
* Query the number of keys in a specific section.
*/
Int32 GetSectionSize(CSStr section) const;
SQMOD_NODISCARD int32_t GetSectionSize(const SQChar * section) const;
/* --------------------------------------------------------------------------------------------
* See whether a certain key has multiple instances.
*/
bool HasMultipleKeys(CSStr section, CSStr key) const;
SQMOD_NODISCARD bool HasMultipleKeys(const SQChar * section, const SQChar * key) const;
/* --------------------------------------------------------------------------------------------
* Retrieve the value for a specific key.
*/
CCStr GetValue(CSStr section, CSStr key, CSStr def) const;
SQMOD_NODISCARD const char * GetValue(const SQChar * section, const SQChar * key, const SQChar * def) const;
/* --------------------------------------------------------------------------------------------
* Retrieve a numeric value for a specific key.
*/
SQInteger GetInteger(CSStr section, CSStr key, SQInteger def) const;
SQMOD_NODISCARD SQInteger GetInteger(const SQChar * section, const SQChar * key, SQInteger def) const;
/* --------------------------------------------------------------------------------------------
* Retrieve a numeric value for a specific key.
*/
SQFloat GetFloat(CSStr section, CSStr key, SQFloat def) const;
SQMOD_NODISCARD SQFloat GetFloat(const SQChar * section, const SQChar * key, SQFloat def) const;
/* --------------------------------------------------------------------------------------------
* Retrieve a boolean value for a specific key.
*/
bool GetBoolean(CSStr section, CSStr key, bool def) const;
SQMOD_NODISCARD bool GetBoolean(const SQChar * section, const SQChar * key, bool def) const;
/* --------------------------------------------------------------------------------------------
* Add or update a section or value.
*/
IniResult SetValue(CSStr section, CSStr key, CSStr value)
IniResult SetValue(const SQChar * section, const SQChar * key, const SQChar * value)
{
return SetValue(section, key, value, false, nullptr);
}
@ -864,7 +845,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Add or update a section or value.
*/
IniResult SetValue(CSStr section, CSStr key, CSStr value, bool force)
IniResult SetValue(const SQChar * section, const SQChar * key, const SQChar * value, bool force)
{
return SetValue(section, key, value, force, nullptr);
}
@ -872,12 +853,12 @@ public:
/* --------------------------------------------------------------------------------------------
* Add or update a section or value.
*/
IniResult SetValue(CSStr section, CSStr key, CSStr value, bool force, CSStr comment);
IniResult SetValue(const SQChar * section, const SQChar * key, const SQChar * value, bool force, const SQChar * comment);
/* --------------------------------------------------------------------------------------------
* Add or update a numeric value.
*/
IniResult SetInteger(CSStr section, CSStr key, SQInteger value)
IniResult SetInteger(const SQChar * section, const SQChar * key, SQInteger value)
{
return SetInteger(section, key, value, false, false, nullptr);
}
@ -885,7 +866,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Add or update a numeric value.
*/
IniResult SetInteger(CSStr section, CSStr key, SQInteger value, bool hex)
IniResult SetInteger(const SQChar * section, const SQChar * key, SQInteger value, bool hex)
{
return SetInteger(section, key, value, hex, false, nullptr);
}
@ -893,7 +874,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Add or update a numeric value.
*/
IniResult SetInteger(CSStr section, CSStr key, SQInteger value, bool hex, bool force)
IniResult SetInteger(const SQChar * section, const SQChar * key, SQInteger value, bool hex, bool force)
{
return SetInteger(section, key, value, hex, force, nullptr);
}
@ -901,12 +882,12 @@ public:
/* --------------------------------------------------------------------------------------------
* Add or update a numeric value.
*/
IniResult SetInteger(CSStr section, CSStr key, SQInteger value, bool hex, bool force, CSStr comment);
IniResult SetInteger(const SQChar * section, const SQChar * key, SQInteger value, bool hex, bool force, const SQChar * comment);
/* --------------------------------------------------------------------------------------------
* Add or update a double value.
*/
IniResult SetFloat(CSStr section, CSStr key, SQFloat value)
IniResult SetFloat(const SQChar * section, const SQChar * key, SQFloat value)
{
return SetFloat(section, key, value, false, nullptr);
}
@ -914,7 +895,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Add or update a double value.
*/
IniResult SetFloat(CSStr section, CSStr key, SQFloat value, bool force)
IniResult SetFloat(const SQChar * section, const SQChar * key, SQFloat value, bool force)
{
return SetFloat(section, key, value, force, nullptr);
}
@ -922,12 +903,12 @@ public:
/* --------------------------------------------------------------------------------------------
* Add or update a double value.
*/
IniResult SetFloat(CSStr section, CSStr key, SQFloat value, bool force, CSStr comment);
IniResult SetFloat(const SQChar * section, const SQChar * key, SQFloat value, bool force, const SQChar * comment);
/* --------------------------------------------------------------------------------------------
* Add or update a double value.
*/
IniResult SetBoolean(CSStr section, CSStr key, bool value)
IniResult SetBoolean(const SQChar * section, const SQChar * key, bool value)
{
return SetBoolean(section, key, value, false, nullptr);
}
@ -935,7 +916,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Add or update a double value.
*/
IniResult SetBoolean(CSStr section, CSStr key, bool value, bool force)
IniResult SetBoolean(const SQChar * section, const SQChar * key, bool value, bool force)
{
return SetBoolean(section, key, value, force, nullptr);
}
@ -943,12 +924,12 @@ public:
/* --------------------------------------------------------------------------------------------
* Add or update a boolean value.
*/
IniResult SetBoolean(CSStr section, CSStr key, bool value, bool force, CSStr comment);
IniResult SetBoolean(const SQChar * section, const SQChar * key, bool value, bool force, const SQChar * comment);
/* --------------------------------------------------------------------------------------------
* Delete an entire section, or a key from a section.
*/
bool DeleteValue(CSStr section)
bool DeleteValue(const SQChar * section)
{
return DeleteValue(section, nullptr, nullptr, false);
}
@ -956,7 +937,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Delete an entire section, or a key from a section.
*/
bool DeleteValue(CSStr section, CSStr key)
bool DeleteValue(const SQChar * section, const SQChar * key)
{
return DeleteValue(section, key, nullptr, false);
}
@ -964,7 +945,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Delete an entire section, or a key from a section.
*/
bool DeleteValue(CSStr section, CSStr key, CSStr value)
bool DeleteValue(const SQChar * section, const SQChar * key, const SQChar * value)
{
return DeleteValue(section, key, value, false);
}
@ -972,7 +953,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Delete an entire section, or a key from a section.
*/
bool DeleteValue(CSStr section, CSStr key, CSStr value, bool empty);
bool DeleteValue(const SQChar * section, const SQChar * key, const SQChar * value, bool empty);
};
} // Namespace:: SqMod

View File

View File

View File

View File

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,11 +1,9 @@
#pragma once
// ------------------------------------------------------------------------------------------------
#include "SqBase.hpp"
#include "Core/Common.hpp"
// ------------------------------------------------------------------------------------------------
namespace SqMod {
} // Namespace:: SqMod

View File

@ -1,44 +1,42 @@
// ------------------------------------------------------------------------------------------------
#include "Library/Numeric/LongInt.hpp"
#include "Library/Numeric/Long.hpp"
#include "Library/Numeric/Random.hpp"
#include "Base/Shared.hpp"
#include "Base/DynArg.hpp"
// ------------------------------------------------------------------------------------------------
#include <cstdio>
#include <cerrno>
#include <cstdlib>
// ------------------------------------------------------------------------------------------------
namespace SqMod {
// ------------------------------------------------------------------------------------------------
SQMODE_DECL_TYPENAME(TypenameS, _SC("SLongInt"))
SQMODE_DECL_TYPENAME(TypenameU, _SC("ULongInt"))
SQMOD_DECL_TYPENAME(TypenameS, _SC("SLongInt"))
SQMOD_DECL_TYPENAME(TypenameU, _SC("ULongInt"))
// ------------------------------------------------------------------------------------------------
LongInt< Int64 >::LongInt(CSStr text)
LongInt< int64_t >::LongInt(const SQChar * text)
: m_Data(0), m_Text()
{
m_Data = std::strtoll(text, nullptr, 10);
}
// ------------------------------------------------------------------------------------------------
LongInt< Int64 >::LongInt(CSStr text, Uint32 base)
LongInt< int64_t >::LongInt(const SQChar * text, uint32_t base)
: m_Data(0), m_Text()
{
m_Data = std::strtoll(text, nullptr, base);
}
// ------------------------------------------------------------------------------------------------
LongInt< Int64 > & LongInt< Int64 >::operator = (CSStr text)
LongInt< int64_t > & LongInt< int64_t >::operator = (const SQChar * text)
{
m_Data = std::strtoll(text, nullptr, 10);
return *this;
}
// ------------------------------------------------------------------------------------------------
CSStr LongInt< Int64 >::ToString()
const SQChar * LongInt< int64_t >::ToString()
{
if (std::snprintf(m_Text, sizeof(m_Text), "%llu", m_Data) < 0)
{
@ -49,46 +47,46 @@ CSStr LongInt< Int64 >::ToString()
}
// ------------------------------------------------------------------------------------------------
void LongInt< Int64 >::Random()
void LongInt< int64_t >::Random()
{
m_Data = GetRandomInt64();
}
// ------------------------------------------------------------------------------------------------
void LongInt< Int64 >::Random(Type n)
void LongInt< int64_t >::Random(Type n)
{
m_Data = GetRandomInt64(n);
}
// ------------------------------------------------------------------------------------------------
void LongInt< Int64 >::Random(Type m, Type n)
void LongInt< int64_t >::Random(Type m, Type n)
{
m_Data = GetRandomInt64(m, n);
}
// ------------------------------------------------------------------------------------------------
LongInt< Uint64 >::LongInt(CSStr text)
LongInt< uint64_t >::LongInt(const SQChar * text)
: m_Data(0), m_Text()
{
m_Data = std::strtoull(text, nullptr, 10);
}
// ------------------------------------------------------------------------------------------------
LongInt< Uint64 >::LongInt(CSStr text, Uint32 base)
LongInt< uint64_t >::LongInt(const SQChar * text, uint32_t base)
: m_Data(0), m_Text()
{
m_Data = std::strtoull(text, nullptr, base);
}
// ------------------------------------------------------------------------------------------------
LongInt< Uint64 > & LongInt< Uint64 >::operator = (CSStr text)
LongInt< uint64_t > & LongInt< uint64_t >::operator = (const SQChar * text)
{
m_Data = std::strtoull(text, nullptr, 10);
return *this;
}
// ------------------------------------------------------------------------------------------------
CSStr LongInt< Uint64 >::ToString()
const SQChar * LongInt< uint64_t >::ToString()
{
if (std::snprintf(m_Text, sizeof(m_Text), "%llu", m_Data) < 0)
{
@ -99,25 +97,25 @@ CSStr LongInt< Uint64 >::ToString()
}
// ------------------------------------------------------------------------------------------------
void LongInt< Uint64 >::Random()
void LongInt< uint64_t >::Random()
{
m_Data = GetRandomUint64();
}
// ------------------------------------------------------------------------------------------------
void LongInt< Uint64 >::Random(Type n)
void LongInt< uint64_t >::Random(Type n)
{
m_Data = GetRandomUint64(n);
}
// ------------------------------------------------------------------------------------------------
void LongInt< Uint64 >::Random(Type m, Type n)
void LongInt< uint64_t >::Random(Type m, Type n)
{
m_Data = GetRandomUint64(m, n);
}
// ------------------------------------------------------------------------------------------------
Int64 PopStackSLong(HSQUIRRELVM vm, SQInteger idx)
int64_t PopStackSLong(HSQUIRRELVM vm, SQInteger idx)
{
// Identify which type must be extracted
switch (sq_gettype(vm, idx))
@ -126,23 +124,23 @@ Int64 PopStackSLong(HSQUIRRELVM vm, SQInteger idx)
{
SQInteger val;
sq_getinteger(vm, idx, &val);
return static_cast< Int64 >(val);
} break;
return static_cast< int64_t >(val);
}
case OT_FLOAT:
{
SQFloat val;
sq_getfloat(vm, idx, &val);
return ConvTo< Int64 >::From(val);
} break;
return ConvTo< int64_t >::From(val);
}
case OT_BOOL:
{
SQBool val;
sq_getbool(vm, idx, &val);
return static_cast< Int64 >(val);
} break;
return static_cast< int64_t >(val);
}
case OT_STRING:
{
CSStr val = nullptr;
const SQChar * val = nullptr;
// Attempt to retrieve and convert the string
if (SQ_SUCCEEDED(sq_getstring(vm, idx, &val)) && val != nullptr && *val != '\0')
{
@ -154,8 +152,8 @@ Int64 PopStackSLong(HSQUIRRELVM vm, SQInteger idx)
case OT_CLASS:
case OT_USERDATA:
{
return static_cast< Int64 >(sq_getsize(vm, idx));
} break;
return static_cast< int64_t >(sq_getsize(vm, idx));
}
case OT_INSTANCE:
{
// Attempt to treat the value as a signed long instance
@ -170,15 +168,15 @@ Int64 PopStackSLong(HSQUIRRELVM vm, SQInteger idx)
// Attempt to treat the value as a unsigned long instance
try
{
return ConvTo< Int64 >::From(Var< const ULongInt & >(vm, idx).value.GetNum());
return ConvTo< int64_t >::From(Var< const ULongInt & >(vm, idx).value.GetNum());
}
catch (...)
{
// Just ignore it...
}
// Attempt to get the size of the instance as a fall back
return static_cast< Int64 >(sq_getsize(vm, idx));
} break;
return static_cast< int64_t >(sq_getsize(vm, idx));
}
default: break;
}
// Default to 0
@ -186,7 +184,7 @@ Int64 PopStackSLong(HSQUIRRELVM vm, SQInteger idx)
}
// ------------------------------------------------------------------------------------------------
Uint64 PopStackULong(HSQUIRRELVM vm, SQInteger idx)
uint64_t PopStackULong(HSQUIRRELVM vm, SQInteger idx)
{
// Identify which type must be extracted
switch (sq_gettype(vm, idx))
@ -195,23 +193,23 @@ Uint64 PopStackULong(HSQUIRRELVM vm, SQInteger idx)
{
SQInteger val;
sq_getinteger(vm, idx, &val);
return ConvTo< Uint64 >::From(val);
} break;
return ConvTo< uint64_t >::From(val);
}
case OT_FLOAT:
{
SQFloat val;
sq_getfloat(vm, idx, &val);
return ConvTo< Uint64 >::From(val);
} break;
return ConvTo< uint64_t >::From(val);
}
case OT_BOOL:
{
SQBool val;
sq_getbool(vm, idx, &val);
return ConvTo< Uint64 >::From(val);
} break;
return ConvTo< uint64_t >::From(val);
}
case OT_STRING:
{
CSStr val = nullptr;
const SQChar * val = nullptr;
// Attempt to retrieve and convert the string
if (SQ_SUCCEEDED(sq_getstring(vm, idx, &val)) && val != nullptr && *val != '\0')
{
@ -223,14 +221,14 @@ Uint64 PopStackULong(HSQUIRRELVM vm, SQInteger idx)
case OT_CLASS:
case OT_USERDATA:
{
return ConvTo< Uint64 >::From(sq_getsize(vm, idx));
} break;
return ConvTo< uint64_t >::From(sq_getsize(vm, idx));
}
case OT_INSTANCE:
{
// Attempt to treat the value as a signed long instance
try
{
return ConvTo< Uint64 >::From(Var< const SLongInt & >(vm, idx).value.GetNum());
return ConvTo< uint64_t >::From(Var< const SLongInt & >(vm, idx).value.GetNum());
}
catch (...)
{
@ -246,8 +244,8 @@ Uint64 PopStackULong(HSQUIRRELVM vm, SQInteger idx)
// Just ignore it...
}
// Attempt to get the size of the instance as a fall back
return ConvTo< Uint64 >::From(sq_getsize(vm, idx));
} break;
return ConvTo< uint64_t >::From(sq_getsize(vm, idx));
}
default: break;
}
// Default to 0
@ -262,14 +260,14 @@ const SLongInt & GetSLongInt()
return l;
}
const SLongInt & GetSLongInt(Int64 n)
const SLongInt & GetSLongInt(int64_t n)
{
static SLongInt l;
l.SetNum(n);
return l;
}
const SLongInt & GetSLongInt(CSStr s)
const SLongInt & GetSLongInt(const SQChar * s)
{
static SLongInt l;
l = s;
@ -283,14 +281,14 @@ const ULongInt & GetULongInt()
return l;
}
const ULongInt & GetULongInt(Uint64 n)
const ULongInt & GetULongInt(uint64_t n)
{
static ULongInt l;
l.SetNum(n);
return l;
}
const ULongInt & GetULongInt(CSStr s)
const ULongInt & GetULongInt(const SQChar * s)
{
static ULongInt l;
l = s;
@ -305,12 +303,12 @@ void Register_LongInt(HSQUIRRELVM vm)
// Constructors
.Ctor()
.Ctor< SLongInt::Type >()
.template Ctor< CCStr, SQInteger >()
.template Ctor< const char *, SQInteger >()
// Properties
.Prop(_SC("Str"), &SLongInt::GetCStr, &SLongInt::SetStr)
.Prop(_SC("Num"), &SLongInt::GetSNum, &SLongInt::SetNum)
// Core Meta-methods
.SquirrelFunc(_SC("cmp"), &SqDynArgFwd< SqDynArgCmpFn< SLongInt >, SQInteger, SQFloat, bool, std::nullptr_t, CSStr, SLongInt, ULongInt >)
.SquirrelFunc(_SC("cmp"), &SqDynArgFwd< SqDynArgCmpFn< SLongInt >, SQInteger, SQFloat, bool, std::nullptr_t, const SQChar *, SLongInt, ULongInt >)
.SquirrelFunc(_SC("_typename"), &TypenameS::Fn)
.Func(_SC("_tostring"), &SLongInt::ToString)
// Core Functions
@ -320,11 +318,11 @@ void Register_LongInt(HSQUIRRELVM vm)
.Func(_SC("tobool"), &SLongInt::ToSqBool)
.Func(_SC("tochar"), &SLongInt::ToSqChar)
// Meta-methods
.SquirrelFunc(_SC("_add"), &SqDynArgFwd< SqDynArgAddFn< SLongInt >, SQInteger, SQFloat, bool, std::nullptr_t, CSStr, SLongInt, ULongInt >)
.SquirrelFunc(_SC("_sub"), &SqDynArgFwd< SqDynArgSubFn< SLongInt >, SQInteger, SQFloat, bool, std::nullptr_t, CSStr, SLongInt, ULongInt >)
.SquirrelFunc(_SC("_mul"), &SqDynArgFwd< SqDynArgMulFn< SLongInt >, SQInteger, SQFloat, bool, std::nullptr_t, CSStr, SLongInt, ULongInt >)
.SquirrelFunc(_SC("_div"), &SqDynArgFwd< SqDynArgDivFn< SLongInt >, SQInteger, SQFloat, bool, std::nullptr_t, CSStr, SLongInt, ULongInt >)
.SquirrelFunc(_SC("_modulo"), &SqDynArgFwd< SqDynArgModFn< SLongInt >, SQInteger, SQFloat, bool, std::nullptr_t, CSStr, SLongInt, ULongInt >)
.SquirrelFunc(_SC("_add"), &SqDynArgFwd< SqDynArgAddFn< SLongInt >, SQInteger, SQFloat, bool, std::nullptr_t, const SQChar *, SLongInt, ULongInt >)
.SquirrelFunc(_SC("_sub"), &SqDynArgFwd< SqDynArgSubFn< SLongInt >, SQInteger, SQFloat, bool, std::nullptr_t, const SQChar *, SLongInt, ULongInt >)
.SquirrelFunc(_SC("_mul"), &SqDynArgFwd< SqDynArgMulFn< SLongInt >, SQInteger, SQFloat, bool, std::nullptr_t, const SQChar *, SLongInt, ULongInt >)
.SquirrelFunc(_SC("_div"), &SqDynArgFwd< SqDynArgDivFn< SLongInt >, SQInteger, SQFloat, bool, std::nullptr_t, const SQChar *, SLongInt, ULongInt >)
.SquirrelFunc(_SC("_modulo"), &SqDynArgFwd< SqDynArgModFn< SLongInt >, SQInteger, SQFloat, bool, std::nullptr_t, const SQChar *, SLongInt, ULongInt >)
.Func< SLongInt (SLongInt::*)(void) const >(_SC("_unm"), &SLongInt::operator -)
// Functions
.Func(_SC("GetStr"), &SLongInt::GetCStr)
@ -342,12 +340,12 @@ void Register_LongInt(HSQUIRRELVM vm)
// Constructors
.Ctor()
.Ctor< ULongInt::Type >()
.Ctor< CCStr, SQInteger >()
.Ctor< const char *, SQInteger >()
// Properties
.Prop(_SC("Str"), &ULongInt::GetCStr, &ULongInt::SetStr)
.Prop(_SC("Num"), &ULongInt::GetSNum, &ULongInt::SetNum)
// Core Meta-methods
.SquirrelFunc(_SC("cmp"), &SqDynArgFwd< SqDynArgCmpFn< ULongInt >, SQInteger, SQFloat, bool, std::nullptr_t, CSStr, ULongInt, SLongInt >)
.SquirrelFunc(_SC("cmp"), &SqDynArgFwd< SqDynArgCmpFn< ULongInt >, SQInteger, SQFloat, bool, std::nullptr_t, const SQChar *, ULongInt, SLongInt >)
.SquirrelFunc(_SC("_typename"), &TypenameU::Fn)
.Func(_SC("_tostring"), &ULongInt::ToString)
// Core Functions
@ -357,11 +355,11 @@ void Register_LongInt(HSQUIRRELVM vm)
.Func(_SC("tobool"), &ULongInt::ToSqBool)
.Func(_SC("tochar"), &ULongInt::ToSqChar)
// Meta-methods
.SquirrelFunc(_SC("_add"), &SqDynArgFwd< SqDynArgAddFn< ULongInt >, SQInteger, SQFloat, bool, std::nullptr_t, CSStr, ULongInt, SLongInt >)
.SquirrelFunc(_SC("_sub"), &SqDynArgFwd< SqDynArgSubFn< ULongInt >, SQInteger, SQFloat, bool, std::nullptr_t, CSStr, ULongInt, SLongInt >)
.SquirrelFunc(_SC("_mul"), &SqDynArgFwd< SqDynArgMulFn< ULongInt >, SQInteger, SQFloat, bool, std::nullptr_t, CSStr, ULongInt, SLongInt >)
.SquirrelFunc(_SC("_div"), &SqDynArgFwd< SqDynArgDivFn< ULongInt >, SQInteger, SQFloat, bool, std::nullptr_t, CSStr, ULongInt, SLongInt >)
.SquirrelFunc(_SC("_modulo"), &SqDynArgFwd< SqDynArgModFn< ULongInt >, SQInteger, SQFloat, bool, std::nullptr_t, CSStr, ULongInt, SLongInt >)
.SquirrelFunc(_SC("_add"), &SqDynArgFwd< SqDynArgAddFn< ULongInt >, SQInteger, SQFloat, bool, std::nullptr_t, const SQChar *, ULongInt, SLongInt >)
.SquirrelFunc(_SC("_sub"), &SqDynArgFwd< SqDynArgSubFn< ULongInt >, SQInteger, SQFloat, bool, std::nullptr_t, const SQChar *, ULongInt, SLongInt >)
.SquirrelFunc(_SC("_mul"), &SqDynArgFwd< SqDynArgMulFn< ULongInt >, SQInteger, SQFloat, bool, std::nullptr_t, const SQChar *, ULongInt, SLongInt >)
.SquirrelFunc(_SC("_div"), &SqDynArgFwd< SqDynArgDivFn< ULongInt >, SQInteger, SQFloat, bool, std::nullptr_t, const SQChar *, ULongInt, SLongInt >)
.SquirrelFunc(_SC("_modulo"), &SqDynArgFwd< SqDynArgModFn< ULongInt >, SQInteger, SQFloat, bool, std::nullptr_t, const SQChar *, ULongInt, SLongInt >)
.Func< ULongInt (ULongInt::*)(void) const >(_SC("_unm"), &ULongInt::operator -)
// Functions
.Func(_SC("GetStr"), &ULongInt::GetCStr)

View File

@ -1,7 +1,7 @@
#pragma once
// ------------------------------------------------------------------------------------------------
#include "Base/Shared.hpp"
#include "Core/Utility.hpp"
// ------------------------------------------------------------------------------------------------
namespace SqMod {
@ -12,18 +12,18 @@ template < typename T > class LongInt;
/* ------------------------------------------------------------------------------------------------
* Specialization of the Long int class for signed integers.
*/
template <> class LongInt< Int64 >
template <> class LongInt< int64_t >
{
public:
// --------------------------------------------------------------------------------------------
typedef Int64 Type; // The specialized type.
typedef int64_t Type; // The specialized type.
private:
// --------------------------------------------------------------------------------------------
Type m_Data; // The assigned value.
SQChar m_Text[32]; // String representation of the value.
SQChar m_Text[24]; // String representation of the value.
public:
@ -48,12 +48,12 @@ public:
/* --------------------------------------------------------------------------------------------
* String encoded constructor.
*/
explicit LongInt(CSStr text);
explicit LongInt(const SQChar * text);
/* --------------------------------------------------------------------------------------------
* String encoded with explicit base constructor.
*/
LongInt(CSStr text, Uint32 base);
LongInt(const SQChar * text, uint32_t base);
/* --------------------------------------------------------------------------------------------
* Copy constructor.
@ -67,15 +67,12 @@ public:
/* --------------------------------------------------------------------------------------------
* Destructor.
*/
~LongInt()
{
/* ... */
}
~LongInt() = default;
/* --------------------------------------------------------------------------------------------
*
*/
LongInt & operator = (const LongInt< Type > & o)
LongInt & operator = (const LongInt< Type > & o) // NOLINT(bugprone-unhandled-self-assignment)
{
m_Data = o.m_Data;
return *this;
@ -93,7 +90,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Assignment operator.
*/
LongInt< Type > & operator = (CSStr text);
LongInt< Type > & operator = (const SQChar * text);
/* --------------------------------------------------------------------------------------------
* Equality comparison operator.
@ -146,13 +143,13 @@ public:
/* --------------------------------------------------------------------------------------------
* Implicit conversion to the specialized type.
*/
operator Type () const
operator Type () const // NOLINT(google-explicit-constructor)
{
return m_Data;
}
/* --------------------------------------------------------------------------------------------
* Adition operator.
* Addition operator.
*/
template < typename U > LongInt< Type > operator + (const LongInt< U > & o) const
{
@ -192,7 +189,7 @@ public:
}
/* --------------------------------------------------------------------------------------------
* Adition operator.
* Addition operator.
*/
LongInt< Type > operator + (SQInteger s) const
{
@ -232,7 +229,7 @@ public:
}
/* --------------------------------------------------------------------------------------------
* Adition operator.
* Addition operator.
*/
LongInt< Type > operator + (SQFloat s) const
{
@ -272,7 +269,7 @@ public:
}
/* --------------------------------------------------------------------------------------------
* Adition operator.
* Addition operator.
*/
LongInt< Type > operator + (bool s) const
{
@ -312,7 +309,7 @@ public:
}
/* --------------------------------------------------------------------------------------------
* Adition operator.
* Addition operator.
*/
LongInt< Type > operator + (std::nullptr_t) const
{
@ -352,9 +349,9 @@ public:
}
/* --------------------------------------------------------------------------------------------
* Adition operator.
* Addition operator.
*/
LongInt< Type > operator + (CSStr str) const
LongInt< Type > operator + (const SQChar * str) const
{
return LongInt< Type >(m_Data + ConvTo< Type >::From(str));
}
@ -362,7 +359,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Subtraction operator.
*/
LongInt< Type > operator - (CSStr str) const
LongInt< Type > operator - (const SQChar * str) const
{
return LongInt< Type >(m_Data - ConvTo< Type >::From(str));
}
@ -370,7 +367,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Multiplication operator.
*/
LongInt< Type > operator * (CSStr str) const
LongInt< Type > operator * (const SQChar * str) const
{
return LongInt< Type >(m_Data * ConvTo< Type >::From(str));
}
@ -378,7 +375,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Division operator.
*/
LongInt< Type > operator / (CSStr str) const
LongInt< Type > operator / (const SQChar * str) const
{
return LongInt< Type >(m_Data / ConvTo< Type >::From(str));
}
@ -386,13 +383,13 @@ public:
/* --------------------------------------------------------------------------------------------
* Modulus operator.
*/
LongInt< Type > operator % (CSStr str) const
LongInt< Type > operator % (const SQChar * str) const
{
return LongInt< Type >(m_Data % ConvTo< Type >::From(str));
}
/* --------------------------------------------------------------------------------------------
* Unarry minus operator.
* Unary minus operator.
*/
LongInt< Type > operator - () const
{
@ -402,7 +399,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Used by the script engine to compare two instances of this type.
*/
Int32 Cmp(const LongInt< Type > & o) const
SQMOD_NODISCARD int32_t Cmp(const LongInt< Type > & o) const
{
if (m_Data == o.m_Data)
{
@ -421,12 +418,12 @@ public:
/* --------------------------------------------------------------------------------------------
* Used by the script engine to compare an instance of this type with another one.
*/
Int32 Cmp(const LongInt< Uint64 > & o) const;
SQMOD_NODISCARD int32_t Cmp(const LongInt< uint64_t > & o) const;
/* --------------------------------------------------------------------------------------------
* Used by the script engine to compare an instance of this type with a scalar value.
*/
Int32 Cmp(SQInteger s) const
SQMOD_NODISCARD int32_t Cmp(SQInteger s) const
{
if (m_Data == static_cast< Type >(s))
{
@ -445,7 +442,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Used by the script engine to compare an instance of this type with a scalar value.
*/
Int32 Cmp(SQFloat s) const
SQMOD_NODISCARD int32_t Cmp(SQFloat s) const
{
if (m_Data == static_cast< Type >(s))
{
@ -464,7 +461,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Used by the script engine to compare an instance of this type with a scalar value.
*/
Int32 Cmp(bool s) const
SQMOD_NODISCARD int32_t Cmp(bool s) const
{
if (m_Data == static_cast< Type >(s))
{
@ -484,7 +481,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Used by the script engine to compare an instance of this type with a scalar value.
*/
Int32 Cmp(std::nullptr_t) const
SQMOD_NODISCARD int32_t Cmp(std::nullptr_t) const
{
if (m_Data == static_cast< Type >(0))
{
@ -503,7 +500,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Used by the script engine to compare an instance of this type with a scalar value.
*/
Int32 Cmp(CSStr str) const
SQMOD_NODISCARD int32_t Cmp(const SQChar * str) const
{
const Type v = ConvTo< Type >::From(str);
@ -524,7 +521,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Used by the script engine to convert an instance of this type to a string.
*/
CSStr ToString();
const SQChar * ToString();
/* --------------------------------------------------------------------------------------------
* Assign an integer value.
@ -537,7 +534,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Retrieve an the specialized value.
*/
Type GetNum() const
SQMOD_NODISCARD Type GetNum() const
{
return m_Data;
}
@ -545,7 +542,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Retrieve an a Squirrel integer value.
*/
SQInteger GetSNum() const
SQMOD_NODISCARD SQInteger GetSNum() const
{
return ClampL< Type, SQInteger >(m_Data);
}
@ -553,7 +550,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Assign a string value.
*/
void SetStr(CSStr text)
void SetStr(const SQChar * text)
{
*this = text;
}
@ -561,7 +558,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Retrieve a string value.
*/
CSStr GetCStr()
const SQChar * GetCStr()
{
return ToString();
}
@ -584,7 +581,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Attempt to convert the long integer to a squirrel integer.
*/
SQInteger ToSqInteger() const
SQMOD_NODISCARD SQInteger ToSqInteger() const
{
return ClampL< Type, SQInteger >(m_Data);
}
@ -592,15 +589,15 @@ public:
/* --------------------------------------------------------------------------------------------
* Attempt to convert the long integer to a squirrel float.
*/
SQFloat ToSqFloat() const
SQMOD_NODISCARD SQFloat ToSqFloat() const
{
return ClampL< Float64, SQFloat >(static_cast< Float64 >(m_Data));
return ClampL< double, SQFloat >(static_cast< double >(m_Data));
}
/* --------------------------------------------------------------------------------------------
* Attempt to convert the long integer to a squirrel string.
*/
CSStr ToSqString()
const SQChar * ToSqString()
{
return ToString();
}
@ -608,7 +605,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Attempt to convert the long integer to a squirrel boolean.
*/
bool ToSqBool() const
SQMOD_NODISCARD bool ToSqBool() const
{
return (m_Data > 0);
}
@ -616,7 +613,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Attempt to convert the long integer to a squirrel character.
*/
SQChar ToSqChar() const
SQMOD_NODISCARD SQChar ToSqChar() const
{
return ClampL< Type, SQChar >(m_Data);
}
@ -625,18 +622,18 @@ public:
/* ------------------------------------------------------------------------------------------------
* Specialization of the Long int class for unsigned integers.
*/
template <> class LongInt< Uint64 >
template <> class LongInt< uint64_t >
{
public:
// --------------------------------------------------------------------------------------------
typedef Uint64 Type; // The specialized type.
typedef uint64_t Type; // The specialized type.
private:
// --------------------------------------------------------------------------------------------
Type m_Data; // The assigned value.
SQChar m_Text[32]; // String representation of the value.
SQChar m_Text[24]; // String representation of the value.
public:
@ -652,7 +649,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Explicit value constructor.
*/
LongInt(Type n)
explicit LongInt(Type n)
: m_Data(n), m_Text()
{
/* ... */
@ -661,12 +658,12 @@ public:
/* --------------------------------------------------------------------------------------------
* String encoded constructor.
*/
LongInt(CSStr text);
explicit LongInt(const SQChar * text);
/* --------------------------------------------------------------------------------------------
* String encoded with explicit base constructor.
*/
LongInt(CSStr text, Uint32 base);
LongInt(const SQChar * text, uint32_t base);
/* --------------------------------------------------------------------------------------------
* Copy constructor.
@ -680,15 +677,12 @@ public:
/* --------------------------------------------------------------------------------------------
* Destructor.
*/
~LongInt()
{
/* ... */
}
~LongInt() = default;
/* --------------------------------------------------------------------------------------------
* Copy assignment operator.
*/
LongInt & operator = (const LongInt< Type > & o)
LongInt & operator = (const LongInt< Type > & o) // NOLINT(bugprone-unhandled-self-assignment)
{
m_Data = o.m_Data;
return *this;
@ -706,7 +700,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Assignment operator.
*/
LongInt< Type > & operator = (CSStr text);
LongInt< Type > & operator = (const SQChar * text);
/* --------------------------------------------------------------------------------------------
* Equality comparison operator.
@ -759,13 +753,13 @@ public:
/* --------------------------------------------------------------------------------------------
* Implicit conversion to the specialized type.
*/
operator Type () const
operator Type () const // NOLINT(google-explicit-constructor)
{
return m_Data;
}
/* --------------------------------------------------------------------------------------------
* Adition operator.
* Addition operator.
*/
template < typename U > LongInt< Type > operator + (const LongInt< U > & o) const
{
@ -805,7 +799,7 @@ public:
}
/* --------------------------------------------------------------------------------------------
* Adition operator.
* Addition operator.
*/
LongInt< Type > operator + (SQInteger s) const
{
@ -845,7 +839,7 @@ public:
}
/* --------------------------------------------------------------------------------------------
* Adition operator.
* Addition operator.
*/
LongInt< Type > operator + (SQFloat s) const
{
@ -885,7 +879,7 @@ public:
}
/* --------------------------------------------------------------------------------------------
* Adition operator.
* Addition operator.
*/
LongInt< Type > operator + (bool s) const
{
@ -925,7 +919,7 @@ public:
}
/* --------------------------------------------------------------------------------------------
* Adition operator.
* Addition operator.
*/
LongInt< Type > operator + (std::nullptr_t) const
{
@ -965,9 +959,9 @@ public:
}
/* --------------------------------------------------------------------------------------------
* Adition operator.
* Addition operator.
*/
LongInt< Type > operator + (CSStr str) const
LongInt< Type > operator + (const SQChar * str) const
{
return LongInt< Type >(m_Data + ConvTo< Type >::From(str));
}
@ -975,7 +969,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Subtraction operator.
*/
LongInt< Type > operator - (CSStr str) const
LongInt< Type > operator - (const SQChar * str) const
{
return LongInt< Type >(m_Data - ConvTo< Type >::From(str));
}
@ -983,7 +977,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Multiplication operator.
*/
LongInt< Type > operator * (CSStr str) const
LongInt< Type > operator * (const SQChar * str) const
{
return LongInt< Type >(m_Data * ConvTo< Type >::From(str));
}
@ -991,7 +985,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Division operator.
*/
LongInt< Type > operator / (CSStr str) const
LongInt< Type > operator / (const SQChar * str) const
{
return LongInt< Type >(m_Data / ConvTo< Type >::From(str));
}
@ -999,13 +993,13 @@ public:
/* --------------------------------------------------------------------------------------------
* Modulus operator.
*/
LongInt< Type > operator % (CSStr str) const
LongInt< Type > operator % (const SQChar * str) const
{
return LongInt< Type >(m_Data % ConvTo< Type >::From(str));
}
/* --------------------------------------------------------------------------------------------
* Unarry minus operator.
* Unary minus operator.
*/
LongInt< Type > operator - () const
{
@ -1015,7 +1009,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Used by the script engine to compare two instances of this type.
*/
Int32 Cmp(const LongInt< Type > & o) const
SQMOD_NODISCARD int32_t Cmp(const LongInt< Type > & o) const
{
if (m_Data == o.m_Data)
{
@ -1034,7 +1028,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Used by the script engine to compare an instance of this type with another one.
*/
Int32 Cmp(const LongInt< Int64 > & o) const
SQMOD_NODISCARD int32_t Cmp(const LongInt< int64_t > & o) const
{
const Type v = ConvTo< Type >::From(o.GetNum());
@ -1055,7 +1049,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Used by the script engine to compare an instance of this type with a scalar value.
*/
Int32 Cmp(SQInteger s) const
SQMOD_NODISCARD int32_t Cmp(SQInteger s) const
{
if (m_Data == static_cast< Type >(s))
{
@ -1074,7 +1068,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Used by the script engine to compare an instance of this type with a scalar value.
*/
Int32 Cmp(SQFloat s) const
SQMOD_NODISCARD int32_t Cmp(SQFloat s) const
{
if (m_Data == static_cast< Type >(s))
{
@ -1093,7 +1087,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Used by the script engine to compare an instance of this type with a scalar value.
*/
Int32 Cmp(bool s) const
SQMOD_NODISCARD int32_t Cmp(bool s) const
{
if (m_Data == static_cast< Type >(s))
{
@ -1113,7 +1107,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Used by the script engine to compare an instance of this type with a scalar value.
*/
Int32 Cmp(std::nullptr_t) const
SQMOD_NODISCARD int32_t Cmp(std::nullptr_t) const
{
if (m_Data == static_cast< Type >(0))
{
@ -1132,7 +1126,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Used by the script engine to compare an instance of this type with a scalar value.
*/
Int32 Cmp(CSStr str) const
SQMOD_NODISCARD int32_t Cmp(const SQChar * str) const
{
const Type v = ConvTo< Type >::From(str);
@ -1153,7 +1147,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Used by the script engine to convert an instance of this type to a string.
*/
CSStr ToString();
const SQChar * ToString();
/* --------------------------------------------------------------------------------------------
* Assign an integer value.
@ -1166,7 +1160,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Retrieve an the specialized value.
*/
Type GetNum() const
SQMOD_NODISCARD Type GetNum() const
{
return m_Data;
}
@ -1174,7 +1168,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Retrieve an a Squirrel integer value.
*/
SQInteger GetSNum() const
SQMOD_NODISCARD SQInteger GetSNum() const
{
return (SQInteger)(m_Data);
}
@ -1182,7 +1176,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Assign a string value.
*/
void SetStr(CSStr text)
void SetStr(const SQChar * text)
{
*this = text;
}
@ -1190,7 +1184,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Retrieve a string value.
*/
CSStr GetCStr()
const SQChar * GetCStr()
{
return ToString();
}
@ -1213,7 +1207,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Attempt to convert the long integer to a squirrel integer.
*/
SQInteger ToSqInteger() const
SQMOD_NODISCARD SQInteger ToSqInteger() const
{
return ClampL< Type, SQInteger >(m_Data);
}
@ -1221,15 +1215,15 @@ public:
/* --------------------------------------------------------------------------------------------
* Attempt to convert the long integer to a squirrel float.
*/
SQFloat ToSqFloat() const
SQMOD_NODISCARD SQFloat ToSqFloat() const
{
return ClampL< Float64, SQFloat >(static_cast< Float64 >(m_Data));
return ClampL< double, SQFloat >(static_cast< double >(m_Data));
}
/* --------------------------------------------------------------------------------------------
* Attempt to convert the long integer to a squirrel string.
*/
CSStr ToSqString()
const SQChar * ToSqString()
{
return ToString();
}
@ -1237,7 +1231,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Attempt to convert the long integer to a squirrel boolean.
*/
bool ToSqBool() const
SQMOD_NODISCARD bool ToSqBool() const
{
return (m_Data > 0);
}
@ -1245,14 +1239,14 @@ public:
/* --------------------------------------------------------------------------------------------
* Attempt to convert the long integer to a squirrel character.
*/
SQChar ToSqChar() const
SQMOD_NODISCARD SQChar ToSqChar() const
{
return ClampL< Type, SQChar >(m_Data);
}
};
// ------------------------------------------------------------------------------------------------
inline Int32 LongInt< Int64 >::Cmp(const LongInt< Uint64 > & o) const
inline int32_t LongInt< int64_t >::Cmp(const LongInt< uint64_t > & o) const
{
const Type v = ConvTo< Type >::From(o.GetNum());
@ -1271,27 +1265,27 @@ inline Int32 LongInt< Int64 >::Cmp(const LongInt< Uint64 > & o) const
}
// ------------------------------------------------------------------------------------------------
typedef LongInt< Int64 > SLongInt;
typedef LongInt< Uint64 > ULongInt;
typedef LongInt< int64_t > SLongInt;
typedef LongInt< uint64_t > ULongInt;
/* ------------------------------------------------------------------------------------------------
* Attempt to pop the value at the specified index on the stack as a signed long integer.
*/
Int64 PopStackSLong(HSQUIRRELVM vm, SQInteger idx);
int64_t PopStackSLong(HSQUIRRELVM vm, SQInteger idx);
/* ------------------------------------------------------------------------------------------------
* Attempt to pop the value at the specified index on the stack as an unsigned long integer.
*/
Uint64 PopStackULong(HSQUIRRELVM vm, SQInteger idx);
uint64_t PopStackULong(HSQUIRRELVM vm, SQInteger idx);
/* ------------------------------------------------------------------------------------------------
* Get a persistent LongInt instance with the given values.
*/
const SLongInt & GetSLongInt();
const SLongInt & GetSLongInt(Int64 n);
const SLongInt & GetSLongInt(CSStr s);
const SLongInt & GetSLongInt(int64_t n);
const SLongInt & GetSLongInt(const SQChar * s);
const ULongInt & GetULongInt();
const ULongInt & GetULongInt(Uint64 n);
const ULongInt & GetULongInt(CSStr s);
const ULongInt & GetULongInt(uint64_t n);
const ULongInt & GetULongInt(const SQChar * s);
} // Namespace:: SqMod

View File

@ -1,7 +1,6 @@
// ------------------------------------------------------------------------------------------------
#include "Library/Numeric/Math.hpp"
#include "Library/Numeric/LongInt.hpp"
#include "Base/Shared.hpp"
#include "Library/Numeric/Long.hpp"
// ------------------------------------------------------------------------------------------------
#include <cmath>
@ -61,12 +60,12 @@ static SQInteger SqRemainder(HSQUIRRELVM vm)
}
// Are we both arguments floats?
if ((sq_gettype(vm, 2) == OT_FLOAT) && sq_gettype(vm, 3) == OT_FLOAT)
{
{ // NOLINT(bugprone-branch-clone)
sq_pushfloat(vm, std::remainder(PopStackFloat(vm, 2), PopStackFloat(vm, 3)));
}
// Are we both arguments integers?
else if ((sq_gettype(vm, 2) == OT_INTEGER) && sq_gettype(vm, 3) == OT_INTEGER)
{
{ // NOLINT(bugprone-branch-clone)
sq_pushinteger(vm, std::remainder(PopStackInteger(vm, 2), PopStackInteger(vm, 3)));
}
// Is the first argument float?
@ -79,7 +78,7 @@ static SQInteger SqRemainder(HSQUIRRELVM vm)
{
sq_pushinteger(vm, std::remainder(PopStackInteger(vm, 2), PopStackInteger(vm, 3)));
}
// Default to both arhuments as float so we don't loos precision from the float one
// Default to both arguments as float so we don't loos precision from the float one
else
{
sq_pushfloat(vm, std::remainder(PopStackFloat(vm, 2), PopStackFloat(vm, 3)));
@ -189,10 +188,6 @@ static SQInteger SqNanL(HSQUIRRELVM vm)
{
Var< SLongInt * >::push(vm, new SLongInt(std::nanl(val.mPtr)));
}
catch (const Sqrat::Exception & e)
{
return sq_throwerror(vm, e.what());
}
catch (const std::exception & e)
{
return sq_throwerror(vm, e.what());
@ -694,10 +689,6 @@ static SQInteger SqRoundL(HSQUIRRELVM vm)
Var< SLongInt * >::push(vm, new SLongInt(std::llround(PopStackInteger(vm, 2))));
}
}
catch (const Sqrat::Exception & e)
{
return sq_throwerror(vm, e.what());
}
catch (const std::exception & e)
{
return sq_throwerror(vm, e.what());
@ -733,7 +724,7 @@ static SQInteger SqFrexp(HSQUIRRELVM vm)
return sq_throwerror(vm, "Wrong number of arguments");
}
// Where the exponent is retrieved
Int32 expv = 0;
int32_t expv = 0;
// Fetch the arguments from the stack and perform the requested operation
const SQFloat sigv = std::frexp(PopStackFloat(vm, 2), &expv);
// Create a new table on the stack
@ -1075,9 +1066,9 @@ static SQInteger SqDigits1(HSQUIRRELVM vm)
return sq_throwerror(vm, "Wrong number of arguments");
}
// Fetch the integer value from the stack
Int64 n = std::llabs(PopStackSLong(vm, 2));
int64_t n = std::llabs(PopStackSLong(vm, 2));
// Start with 0 digits
Uint8 d = 0;
uint8_t d = 0;
// Identify the number of digits
while (n != 0)
{
@ -1099,9 +1090,9 @@ static SQInteger SqDigits0(HSQUIRRELVM vm)
return sq_throwerror(vm, "Wrong number of arguments");
}
// Fetch the integer value from the stack
Int64 n = std::llabs(PopStackSLong(vm, 2));
int64_t n = std::llabs(PopStackSLong(vm, 2));
// Start with 0 digits
Uint8 d = 0;
uint8_t d = 0;
// Identify the number of digits
do
{
@ -1115,14 +1106,14 @@ static SQInteger SqDigits0(HSQUIRRELVM vm)
}
// ------------------------------------------------------------------------------------------------
SQFloat SqIToF(Int64 sigv, Int64 expv, Int32 padn, bool negf)
SQFloat SqIToF(int64_t sigv, int64_t expv, int32_t padn, bool negf)
{
// The number of characters to add before the exponent
static CharT padb[64];
CharT padb[64];
// Make sure the pad number is positive
padn = ClampMin(padn, 0);
// Is the number of pad characters out of range?
if (static_cast< Uint32 >(padn) >= sizeof(padb))
if (static_cast< uint32_t >(padn) >= sizeof(padb))
{
STHROWF("Pad characters out of range: %d >= %d", padn, sizeof(padb));
}
@ -1130,23 +1121,23 @@ SQFloat SqIToF(Int64 sigv, Int64 expv, Int32 padn, bool negf)
std::memset(padb, '0', padn);
// Add the null terminator
padb[padn] = '\0';
// The obtained string containing the floating point
CSStr fstr = nullptr;
// Generate the floating point value
// Now transform the resulted string to a floating point value
if (negf)
{
fstr = ToStrF("-%lld.%s%lld", sigv, padb, expv);
#ifdef SQUSEDOUBLE
return std::strtod(fmt::format("-{}.{}{}", sigv, padb, expv).c_str(), nullptr);
#else
return std::strtof(fmt::format("-{}.{}{}", sigv, padb, expv).c_str(), nullptr);
#endif // SQUSEDOUBLE
}
else
{
fstr = ToStrF("%lld.%s%lld", sigv, padb, expv);
}
// Now transform the resulted string to a floating point value
#ifdef SQUSEDOUBLE
return std::strtod(fstr, nullptr);
return std::strtod(fmt::format("{}.{}{}", sigv, padb, expv).c_str(), nullptr);
#else
return std::strtof(fstr, nullptr);
return std::strtof(fmt::format("{}.{}{}", sigv, padb, expv).c_str(), nullptr);
#endif // SQUSEDOUBLE
}
}
// ================================================================================================

View File

@ -1,11 +1,9 @@
#pragma once
// ------------------------------------------------------------------------------------------------
#include "SqBase.hpp"
#include "Core/Common.hpp"
// ------------------------------------------------------------------------------------------------
namespace SqMod {
} // Namespace:: SqMod

View File

@ -1,13 +1,12 @@
// ------------------------------------------------------------------------------------------------
#include "Library/Numeric/Random.hpp"
#include "Base/Shared.hpp"
#include "Base/Buffer.hpp"
#include "Core/Common.hpp"
#include "Core/Buffer.hpp"
// ------------------------------------------------------------------------------------------------
#include <ctime>
#include <memory>
#include <random>
#include <cstdlib>
// ------------------------------------------------------------------------------------------------
#ifdef SQMOD_OS_WINDOWS
@ -21,52 +20,52 @@
namespace SqMod {
// ------------------------------------------------------------------------------------------------
static std::unique_ptr< std::mt19937 > RG32_MT19937 =
std::unique_ptr< std::mt19937 >(new std::mt19937(GenerateSeed()));
static std::unique_ptr< std::mt19937 > RG32_MT19937 = // NOLINT(cert-err58-cpp)
std::make_unique< std::mt19937 >(GenerateSeed());
static std::unique_ptr< std::mt19937_64 > RG64_MT19937 =
std::unique_ptr< std::mt19937_64 >(new std::mt19937_64(GenerateSeed()));
static std::unique_ptr< std::mt19937_64 > RG64_MT19937 = // NOLINT(cert-err58-cpp)
std::make_unique< std::mt19937_64 >(GenerateSeed());
// ------------------------------------------------------------------------------------------------
static std::uniform_int_distribution< Int8 > Int8_Dist(std::numeric_limits< Int8 >::min(),
std::numeric_limits< Int8 >::max());
static std::uniform_int_distribution< Uint8 > Uint8_Dist(std::numeric_limits< Uint8 >::min(),
std::numeric_limits< Uint8 >::max());
static std::uniform_int_distribution< int8_t > Int8_Dist(std::numeric_limits< int8_t >::min(), // NOLINT(cert-err58-cpp)
std::numeric_limits< int8_t >::max());
static std::uniform_int_distribution< uint8_t > uint8_t_Dist(std::numeric_limits< uint8_t >::min(), // NOLINT(cert-err58-cpp)
std::numeric_limits< uint8_t >::max());
static std::uniform_int_distribution< Int16 > Int16_Dist(std::numeric_limits< Int16 >::min(),
std::numeric_limits< Int16 >::max());
static std::uniform_int_distribution< Uint16 > Uint16_Dist(std::numeric_limits< Uint16 >::min(),
std::numeric_limits< Uint16 >::max());
static std::uniform_int_distribution< int16_t > Int16_Dist(std::numeric_limits< int16_t >::min(), // NOLINT(cert-err58-cpp)
std::numeric_limits< int16_t >::max());
static std::uniform_int_distribution< uint16_t > Uint16_Dist(std::numeric_limits< uint16_t >::min(), // NOLINT(cert-err58-cpp)
std::numeric_limits< uint16_t >::max());
static std::uniform_int_distribution< Int32 > Int32_Dist(std::numeric_limits< Int32 >::min(),
std::numeric_limits< Int32 >::max());
static std::uniform_int_distribution< Uint32 > Uint32_Dist(std::numeric_limits< Uint32 >::min(),
std::numeric_limits< Uint32 >::max());
static std::uniform_int_distribution< int32_t > Int32_Dist(std::numeric_limits< int32_t >::min(), // NOLINT(cert-err58-cpp)
std::numeric_limits< int32_t >::max());
static std::uniform_int_distribution< uint32_t > Uint32_Dist(std::numeric_limits< uint32_t >::min(), // NOLINT(cert-err58-cpp)
std::numeric_limits< uint32_t >::max());
static std::uniform_int_distribution< Int64 > Int64_Dist(std::numeric_limits< Int64 >::min(),
std::numeric_limits< Int64 >::max());
static std::uniform_int_distribution< Uint64 > Uint64_Dist(std::numeric_limits< Uint64 >::min(),
std::numeric_limits< Uint64 >::max());
static std::uniform_int_distribution< int64_t > Int64_Dist(std::numeric_limits< int64_t >::min(), // NOLINT(cert-err58-cpp)
std::numeric_limits< int64_t >::max());
static std::uniform_int_distribution< uint64_t > Uint64_Dist(std::numeric_limits< uint64_t >::min(), // NOLINT(cert-err58-cpp)
std::numeric_limits< uint64_t >::max());
static std::uniform_real_distribution<Float32> Float32_Dist(std::numeric_limits< Float32 >::min(),
std::numeric_limits< Float32 >::max());
static std::uniform_real_distribution<Float64> Float64_Dist(std::numeric_limits< Float64 >::min(),
std::numeric_limits< Float64 >::max());
static std::uniform_real_distribution<float> Float32_Dist(std::numeric_limits< float >::min(), // NOLINT(cert-err58-cpp)
std::numeric_limits< float >::max());
static std::uniform_real_distribution<double> Float64_Dist(std::numeric_limits< double >::min(), // NOLINT(cert-err58-cpp)
std::numeric_limits< double >::max());
// ------------------------------------------------------------------------------------------------
static std::uniform_int_distribution< String::value_type >
String_Dist(std::numeric_limits< String::value_type >::min(),
String_Dist(std::numeric_limits< String::value_type >::min(), // NOLINT(cert-err58-cpp)
std::numeric_limits< String::value_type >::max());
// ------------------------------------------------------------------------------------------------
SizeT GenerateSeed()
uint32_t GenerateSeed()
{
Ulong a = clock();
Ulong b = time(NULL);
unsigned long a = clock();
unsigned long b = time(nullptr);
#ifdef SQMOD_OS_WINDOWS
Ulong c = _getpid();
unsigned long c = _getpid();
#else
Ulong c = getpid();
unsigned long c = getpid();
#endif
// Mangle
a=a-b; a=a-c; a=a^(c >> 13);
@ -83,9 +82,9 @@ SizeT GenerateSeed()
}
// ------------------------------------------------------------------------------------------------
SizeT GenerateSeed2()
size_t GenerateSeed2()
{
struct {
struct { // NOLINT(cppcoreguidelines-pro-type-member-init)
std::clock_t c;
std::time_t t;
#ifdef SQMOD_OS_WINDOWS
@ -108,199 +107,199 @@ SizeT GenerateSeed2()
// ------------------------------------------------------------------------------------------------
void ReseedRandom()
{
RG32_MT19937.reset(new std::mt19937(GenerateSeed()));
RG64_MT19937.reset(new std::mt19937_64(GenerateSeed()));
RG32_MT19937 = std::make_unique<std::mt19937>(GenerateSeed());
RG64_MT19937 = std::make_unique<std::mt19937_64>(GenerateSeed());
}
void ReseedRandom(Uint32 n)
void ReseedRandom(uint32_t n)
{
RG32_MT19937.reset(new std::mt19937(n));
RG64_MT19937.reset(new std::mt19937_64(n));
RG32_MT19937 = std::make_unique<std::mt19937>(n);
RG64_MT19937 = std::make_unique<std::mt19937_64>(n);
}
// ------------------------------------------------------------------------------------------------
void ReseedRandom32()
{
RG32_MT19937.reset(new std::mt19937(GenerateSeed()));
RG32_MT19937 = std::make_unique<std::mt19937>(GenerateSeed());
}
void ReseedRandom32(Uint32 n)
void ReseedRandom32(uint32_t n)
{
RG32_MT19937.reset(new std::mt19937(n));
RG32_MT19937 = std::make_unique<std::mt19937>(n);
}
// ------------------------------------------------------------------------------------------------
void ReseedRandom64()
{
RG64_MT19937.reset(new std::mt19937_64(GenerateSeed()));
RG64_MT19937 = std::make_unique<std::mt19937_64>(GenerateSeed());
}
void ReseedRandom64(Uint32 n)
void ReseedRandom64(uint32_t n)
{
RG64_MT19937.reset(new std::mt19937_64(n));
RG64_MT19937 = std::make_unique<std::mt19937_64>(n);
}
// ------------------------------------------------------------------------------------------------
Int8 GetRandomInt8()
int8_t GetRandomInt8()
{
return Int8_Dist(*RG32_MT19937);
}
Int8 GetRandomInt8(Int8 n)
int8_t GetRandomInt8(int8_t n)
{
return std::uniform_int_distribution< Int8 >(0, n)(*RG32_MT19937);
return std::uniform_int_distribution< int8_t >(0, n)(*RG32_MT19937);
}
Int8 GetRandomInt8(Int8 m, Int8 n)
int8_t GetRandomInt8(int8_t m, int8_t n)
{
return std::uniform_int_distribution< Int8 >(m, n)(*RG32_MT19937);
return std::uniform_int_distribution< int8_t >(m, n)(*RG32_MT19937);
}
// ------------------------------------------------------------------------------------------------
Uint8 GetRandomUint8()
uint8_t GetRandomUint8()
{
return Uint8_Dist(*RG32_MT19937);
return uint8_t_Dist(*RG32_MT19937);
}
Uint8 GetRandomUint8(Uint8 n)
uint8_t GetRandomUint8(uint8_t n)
{
return std::uniform_int_distribution< Uint8 >(0, n)(*RG32_MT19937);
return std::uniform_int_distribution< uint8_t >(0, n)(*RG32_MT19937);
}
Uint8 GetRandomUint8(Uint8 m, Uint8 n)
uint8_t GetRandomUint8(uint8_t m, uint8_t n)
{
return std::uniform_int_distribution< Uint8 >(m, n)(*RG32_MT19937);
return std::uniform_int_distribution< uint8_t >(m, n)(*RG32_MT19937);
}
// ------------------------------------------------------------------------------------------------
Int16 GetRandomInt16()
int16_t GetRandomInt16()
{
return Int16_Dist(*RG32_MT19937);
}
Int16 GetRandomInt16(Int16 n)
int16_t GetRandomInt16(int16_t n)
{
return std::uniform_int_distribution< Int16 >(0, n)(*RG32_MT19937);
return std::uniform_int_distribution< int16_t >(0, n)(*RG32_MT19937);
}
Int16 GetRandomInt16(Int16 m, Int16 n)
int16_t GetRandomInt16(int16_t m, int16_t n)
{
return std::uniform_int_distribution< Int16 >(m, n)(*RG32_MT19937);
return std::uniform_int_distribution< int16_t >(m, n)(*RG32_MT19937);
}
// ------------------------------------------------------------------------------------------------
Uint16 GetRandomUint16()
uint16_t GetRandomUint16()
{
return Uint16_Dist(*RG32_MT19937);
}
Uint16 GetRandomUint16(Uint16 n)
uint16_t GetRandomUint16(uint16_t n)
{
return std::uniform_int_distribution< Uint16 >(0, n)(*RG32_MT19937);
return std::uniform_int_distribution< uint16_t >(0, n)(*RG32_MT19937);
}
Uint16 GetRandomUint16(Uint16 m, Uint16 n)
uint16_t GetRandomUint16(uint16_t m, uint16_t n)
{
return std::uniform_int_distribution< Uint16 >(m, n)(*RG32_MT19937);
return std::uniform_int_distribution< uint16_t >(m, n)(*RG32_MT19937);
}
// ------------------------------------------------------------------------------------------------
Int32 GetRandomInt32()
int32_t GetRandomInt32()
{
return Int32_Dist(*RG32_MT19937);
}
Int32 GetRandomInt32(Int32 n)
int32_t GetRandomInt32(int32_t n)
{
return std::uniform_int_distribution< Int32 >(0, n)(*RG32_MT19937);
return std::uniform_int_distribution< int32_t >(0, n)(*RG32_MT19937);
}
Int32 GetRandomInt32(Int32 m, Int32 n)
int32_t GetRandomInt32(int32_t m, int32_t n)
{
return std::uniform_int_distribution< Int32 >(m, n)(*RG32_MT19937);
return std::uniform_int_distribution< int32_t >(m, n)(*RG32_MT19937);
}
// ------------------------------------------------------------------------------------------------
Uint32 GetRandomUint32()
uint32_t GetRandomUint32()
{
return Int32_Dist(*RG32_MT19937);
return Uint32_Dist(*RG32_MT19937);
}
Uint32 GetRandomUint32(Uint32 n)
uint32_t GetRandomUint32(uint32_t n)
{
return std::uniform_int_distribution< Int32 >(0, n)(*RG32_MT19937);
return std::uniform_int_distribution< uint32_t >(0, n)(*RG32_MT19937);
}
Uint32 GetRandomUint32(Uint32 m, Uint32 n)
uint32_t GetRandomUint32(uint32_t m, uint32_t n)
{
return std::uniform_int_distribution< Int32 >(m, n)(*RG32_MT19937);
return std::uniform_int_distribution< uint32_t >(m, n)(*RG32_MT19937);
}
// ------------------------------------------------------------------------------------------------
Int64 GetRandomInt64()
int64_t GetRandomInt64()
{
return Int64_Dist(*RG64_MT19937);
}
Int64 GetRandomInt64(Int64 n)
int64_t GetRandomInt64(int64_t n)
{
return std::uniform_int_distribution< Int64 >(0, n)(*RG64_MT19937);
return std::uniform_int_distribution< int64_t >(0, n)(*RG64_MT19937);
}
Int64 GetRandomInt64(Int64 m, Int64 n)
int64_t GetRandomInt64(int64_t m, int64_t n)
{
return std::uniform_int_distribution< Int64 >(m, n)(*RG64_MT19937);
return std::uniform_int_distribution< int64_t >(m, n)(*RG64_MT19937);
}
// ------------------------------------------------------------------------------------------------
Uint64 GetRandomUint64()
uint64_t GetRandomUint64()
{
return Uint64_Dist(*RG64_MT19937);
}
Uint64 GetRandomUint64(Uint64 n)
uint64_t GetRandomUint64(uint64_t n)
{
return std::uniform_int_distribution< Uint64 >(0, n)(*RG64_MT19937);
return std::uniform_int_distribution< uint64_t >(0, n)(*RG64_MT19937);
}
Uint64 GetRandomUint64(Uint64 m, Uint64 n)
uint64_t GetRandomUint64(uint64_t m, uint64_t n)
{
return std::uniform_int_distribution< Uint64 >(m, n)(*RG64_MT19937);
return std::uniform_int_distribution< uint64_t >(m, n)(*RG64_MT19937);
}
// ------------------------------------------------------------------------------------------------
Float32 GetRandomFloat32()
float GetRandomFloat32()
{
return Float32_Dist(*RG32_MT19937);
}
Float32 GetRandomFloat32(Float32 n)
float GetRandomFloat32(float n)
{
return std::uniform_real_distribution< Float32 >(0, n)(*RG32_MT19937);
return std::uniform_real_distribution< float >(0, n)(*RG32_MT19937);
}
Float32 GetRandomFloat32(Float32 m, Float32 n)
float GetRandomFloat32(float m, float n)
{
return std::uniform_real_distribution< Float32 >(m, n)(*RG32_MT19937);
return std::uniform_real_distribution< float >(m, n)(*RG32_MT19937);
}
// ------------------------------------------------------------------------------------------------
Float64 GetRandomFloat64()
double GetRandomFloat64()
{
return Float64_Dist(*RG64_MT19937);
}
Float64 GetRandomFloat64(Float64 n)
double GetRandomFloat64(double n)
{
return std::uniform_real_distribution< Float64 >(0, n)(*RG64_MT19937);
return std::uniform_real_distribution< double >(0, n)(*RG64_MT19937);
}
Float64 GetRandomFloat64(Float64 m, Float64 n)
double GetRandomFloat64(double m, double n)
{
return std::uniform_real_distribution< Float64 >(m, n)(*RG64_MT19937);
return std::uniform_real_distribution< double >(m, n)(*RG64_MT19937);
}
// ------------------------------------------------------------------------------------------------
@ -353,7 +352,7 @@ bool GetRandomBool(SQFloat p)
}
// ------------------------------------------------------------------------------------------------
static String RandomString(Int32 len)
static String RandomString(int32_t len)
{
// Is there anything to generate?
if (len <= 0)
@ -367,7 +366,7 @@ static String RandomString(Int32 len)
}
// ------------------------------------------------------------------------------------------------
static String RandomString(Int32 len, SQChar n)
static String RandomString(int32_t len, SQChar n)
{
// Is there anything to generate?
if (len <= 0)
@ -381,7 +380,7 @@ static String RandomString(Int32 len, SQChar n)
}
// ------------------------------------------------------------------------------------------------
static String RandomString(Int32 len, SQChar m, SQChar n)
static String RandomString(int32_t len, SQChar m, SQChar n)
{
// Is there anything to generate?
if (len <= 0)
@ -401,11 +400,11 @@ void Register_Random(HSQUIRRELVM vm)
.Func(_SC("GenSeed"), &GenerateSeed)
.Func(_SC("GenSeed2"), &GenerateSeed2)
.Overload< void (*)(void) >(_SC("Reseed"), &ReseedRandom)
.Overload< void (*)(Uint32) >(_SC("Reseed"), &ReseedRandom)
.Overload< void (*)(uint32_t) >(_SC("Reseed"), &ReseedRandom)
.Overload< void (*)(void) >(_SC("Reseed32"), &ReseedRandom32)
.Overload< void (*)(Uint32) >(_SC("Reseed32"), &ReseedRandom32)
.Overload< void (*)(uint32_t) >(_SC("Reseed32"), &ReseedRandom32)
.Overload< void (*)(void) >(_SC("Reseed64"), &ReseedRandom64)
.Overload< void (*)(Uint32) >(_SC("Reseed64"), &ReseedRandom64)
.Overload< void (*)(uint32_t) >(_SC("Reseed64"), &ReseedRandom64)
#ifdef _SQ64
.Overload< SQInteger (*)(void) >(_SC("Integer"), &GetRandomInt64)
@ -427,9 +426,9 @@ void Register_Random(HSQUIRRELVM vm)
.Overload< SQFloat (*)(SQFloat, SQFloat) >(_SC("Float"), &GetRandomFloat32)
#endif // SQUSEDOUBLE
.Overload< String (*)(Int32) >(_SC("String"), &RandomString)
.Overload< String (*)(Int32, SQChar) >(_SC("String"), &RandomString)
.Overload< String (*)(Int32, SQChar, SQChar) >(_SC("String"), &RandomString)
.Overload< String (*)(int32_t) >(_SC("String"), &RandomString)
.Overload< String (*)(int32_t, SQChar) >(_SC("String"), &RandomString)
.Overload< String (*)(int32_t, SQChar, SQChar) >(_SC("String"), &RandomString)
.Overload< bool (*)(void) >(_SC("Bool"), &GetRandomBool)
.Overload< bool (*)(SQFloat) >(_SC("Bool"), &GetRandomBool)
);

View File

@ -9,61 +9,61 @@ namespace SqMod {
/* ------------------------------------------------------------------------------------------------
* Attempt to generate a moderately unique number to be used as a seed for random numbers.
*/
Uint32 GenerateSeed();
uint32_t GenerateSeed();
// ------------------------------------------------------------------------------------------------
void ReseedRandom();
void ReseedRandom(Uint32 n);
void ReseedRandom(uint32_t n);
// ------------------------------------------------------------------------------------------------
Int8 GetRandomInt8();
Int8 GetRandomInt8(Int8 n);
Int8 GetRandomInt8(Int8 m, Int8 n);
SQMOD_NODISCARD int8_t GetRandomInt8();
SQMOD_NODISCARD int8_t GetRandomInt8(int8_t n);
SQMOD_NODISCARD int8_t GetRandomInt8(int8_t m, int8_t n);
// ------------------------------------------------------------------------------------------------
Uint8 GetRandomUint8();
Uint8 GetRandomUint8(Uint8 n);
Uint8 GetRandomUint8(Uint8 m, Uint8 n);
SQMOD_NODISCARD uint8_t GetRandomUint8();
SQMOD_NODISCARD uint8_t GetRandomUint8(uint8_t n);
SQMOD_NODISCARD uint8_t GetRandomUint8(uint8_t m, uint8_t n);
// ------------------------------------------------------------------------------------------------
Int16 GetRandomInt16();
Int16 GetRandomInt16(Int16 n);
Int16 GetRandomInt16(Int16 m, Int16 n);
SQMOD_NODISCARD int16_t GetRandomInt16();
SQMOD_NODISCARD int16_t GetRandomInt16(int16_t n);
SQMOD_NODISCARD int16_t GetRandomInt16(int16_t m, int16_t n);
// ------------------------------------------------------------------------------------------------
Uint16 GetRandomUint16();
Uint16 GetRandomUint16(Uint16 n);
Uint16 GetRandomUint16(Uint16 m, Uint16 n);
SQMOD_NODISCARD uint16_t GetRandomUint16();
SQMOD_NODISCARD uint16_t GetRandomUint16(uint16_t n);
SQMOD_NODISCARD uint16_t GetRandomUint16(uint16_t m, uint16_t n);
// ------------------------------------------------------------------------------------------------
Int32 GetRandomInt32();
Int32 GetRandomInt32(Int32 n);
Int32 GetRandomInt32(Int32 m, Int32 n);
SQMOD_NODISCARD int32_t GetRandomInt32();
SQMOD_NODISCARD int32_t GetRandomInt32(int32_t n);
SQMOD_NODISCARD int32_t GetRandomInt32(int32_t m, int32_t n);
// ------------------------------------------------------------------------------------------------
Uint32 GetRandomUint32();
Uint32 GetRandomUint32(Uint32 n);
Uint32 GetRandomUint32(Uint32 m, Uint32 n);
SQMOD_NODISCARD uint32_t GetRandomUint32();
SQMOD_NODISCARD uint32_t GetRandomUint32(uint32_t n);
SQMOD_NODISCARD uint32_t GetRandomUint32(uint32_t m, uint32_t n);
// ------------------------------------------------------------------------------------------------
Int64 GetRandomInt64();
Int64 GetRandomInt64(Int64 n);
Int64 GetRandomInt64(Int64 m, Int64 n);
SQMOD_NODISCARD int64_t GetRandomInt64();
SQMOD_NODISCARD int64_t GetRandomInt64(int64_t n);
SQMOD_NODISCARD int64_t GetRandomInt64(int64_t m, int64_t n);
// ------------------------------------------------------------------------------------------------
Uint64 GetRandomUint64();
Uint64 GetRandomUint64(Uint64 n);
Uint64 GetRandomUint64(Uint64 m, Uint64 n);
SQMOD_NODISCARD uint64_t GetRandomUint64();
SQMOD_NODISCARD uint64_t GetRandomUint64(uint64_t n);
SQMOD_NODISCARD uint64_t GetRandomUint64(uint64_t m, uint64_t n);
// ------------------------------------------------------------------------------------------------
Float32 GetRandomFloat32();
Float32 GetRandomFloat32(Float32 n);
Float32 GetRandomFloat32(Float32 m, Float32 n);
SQMOD_NODISCARD float GetRandomFloat32();
SQMOD_NODISCARD float GetRandomFloat32(float n);
SQMOD_NODISCARD float GetRandomFloat32(float m, float n);
// ------------------------------------------------------------------------------------------------
Float64 GetRandomFloat64();
Float64 GetRandomFloat64(Float64 n);
Float64 GetRandomFloat64(Float64 m, Float64 n);
SQMOD_NODISCARD double GetRandomFloat64();
SQMOD_NODISCARD double GetRandomFloat64(double n);
SQMOD_NODISCARD double GetRandomFloat64(double m, double n);
// ------------------------------------------------------------------------------------------------
void GetRandomString(String & str, String::size_type len);
@ -71,85 +71,85 @@ void GetRandomString(String & str, String::size_type len, String::value_type n);
void GetRandomString(String & str, String::size_type len, String::value_type m, String::value_type n);
// ------------------------------------------------------------------------------------------------
bool GetRandomBool();
SQMOD_NODISCARD bool GetRandomBool();
// ------------------------------------------------------------------------------------------------
template <typename T> struct RandomVal
{ /* ... */ };
// ------------------------------------------------------------------------------------------------
template <> struct RandomVal< Int8 >
template <> struct RandomVal< int8_t >
{
static inline Int8 Get() { return GetRandomInt8(); }
static inline Int8 Get(Int8 n) { return GetRandomInt8(n); }
static inline Int8 Get(Int8 m, Int8 n) { return GetRandomInt8(m, n); }
static inline int8_t Get() { return GetRandomInt8(); }
static inline int8_t Get(int8_t n) { return GetRandomInt8(n); }
static inline int8_t Get(int8_t m, int8_t n) { return GetRandomInt8(m, n); }
};
template <> struct RandomVal< Uint8 >
template <> struct RandomVal< uint8_t >
{
static inline Uint8 Get() { return GetRandomUint8(); }
static inline Uint8 Get(Uint8 n) { return GetRandomUint8(n); }
static inline Uint8 Get(Uint8 m, Uint8 n) { return GetRandomUint8(m, n); }
static inline uint8_t Get() { return GetRandomUint8(); }
static inline uint8_t Get(uint8_t n) { return GetRandomUint8(n); }
static inline uint8_t Get(uint8_t m, uint8_t n) { return GetRandomUint8(m, n); }
};
// ------------------------------------------------------------------------------------------------
template <> struct RandomVal< Int16 >
template <> struct RandomVal< int16_t >
{
static inline Int16 Get() { return GetRandomInt16(); }
static inline Int16 Get(Int16 n) { return GetRandomInt16(n); }
static inline Int16 Get(Int16 m, Int16 n) { return GetRandomInt16(m, n); }
static inline int16_t Get() { return GetRandomInt16(); }
static inline int16_t Get(int16_t n) { return GetRandomInt16(n); }
static inline int16_t Get(int16_t m, int16_t n) { return GetRandomInt16(m, n); }
};
template <> struct RandomVal< Uint16 >
template <> struct RandomVal< uint16_t >
{
static inline Uint16 Get() { return GetRandomUint16(); }
static inline Uint16 Get(Uint16 n) { return GetRandomUint16(n); }
static inline Uint16 Get(Uint16 m, Uint16 n) { return GetRandomUint16(m, n); }
static inline uint16_t Get() { return GetRandomUint16(); }
static inline uint16_t Get(uint16_t n) { return GetRandomUint16(n); }
static inline uint16_t Get(uint16_t m, uint16_t n) { return GetRandomUint16(m, n); }
};
// ------------------------------------------------------------------------------------------------
template <> struct RandomVal< Int32 >
template <> struct RandomVal< int32_t >
{
static inline Int32 Get() { return GetRandomInt32(); }
static inline Int32 Get(Int32 n) { return GetRandomInt32(n); }
static inline Int32 Get(Int32 m, Int32 n) { return GetRandomInt32(m, n); }
static inline int32_t Get() { return GetRandomInt32(); }
static inline int32_t Get(int32_t n) { return GetRandomInt32(n); }
static inline int32_t Get(int32_t m, int32_t n) { return GetRandomInt32(m, n); }
};
template <> struct RandomVal< Uint32 >
template <> struct RandomVal< uint32_t >
{
static inline Uint32 Get() { return GetRandomUint32(); }
static inline Uint32 Get(Uint32 n) { return GetRandomUint32(n); }
static inline Uint32 Get(Uint32 m, Uint32 n) { return GetRandomUint32(m, n); }
static inline uint32_t Get() { return GetRandomUint32(); }
static inline uint32_t Get(uint32_t n) { return GetRandomUint32(n); }
static inline uint32_t Get(uint32_t m, uint32_t n) { return GetRandomUint32(m, n); }
};
// ------------------------------------------------------------------------------------------------
template <> struct RandomVal< Int64 >
template <> struct RandomVal< int64_t >
{
static inline Int64 Get() { return GetRandomInt64(); }
static inline Int64 Get(Int64 n) { return GetRandomInt64(n); }
static inline Int64 Get(Int64 m, Int64 n) { return GetRandomInt64(m, n); }
static inline int64_t Get() { return GetRandomInt64(); }
static inline int64_t Get(int64_t n) { return GetRandomInt64(n); }
static inline int64_t Get(int64_t m, int64_t n) { return GetRandomInt64(m, n); }
};
template <> struct RandomVal< Uint64 >
template <> struct RandomVal< uint64_t >
{
static inline Uint64 Get() { return GetRandomUint64(); }
static inline Uint64 Get(Uint64 n) { return GetRandomUint64(n); }
static inline Uint64 Get(Uint64 m, Uint64 n) { return GetRandomUint64(m, n); }
static inline uint64_t Get() { return GetRandomUint64(); }
static inline uint64_t Get(uint64_t n) { return GetRandomUint64(n); }
static inline uint64_t Get(uint64_t m, uint64_t n) { return GetRandomUint64(m, n); }
};
// ------------------------------------------------------------------------------------------------
template <> struct RandomVal< Float32 >
template <> struct RandomVal< float >
{
static inline Float32 Get() { return GetRandomFloat32(); }
static inline Float32 Get(Float32 n) { return GetRandomFloat32(n); }
static inline Float32 Get(Float32 m, Float32 n) { return GetRandomFloat32(m, n); }
static inline float Get() { return GetRandomFloat32(); }
static inline float Get(float n) { return GetRandomFloat32(n); }
static inline float Get(float m, float n) { return GetRandomFloat32(m, n); }
};
template <> struct RandomVal< Float64 >
template <> struct RandomVal< double >
{
static inline Float64 Get() { return GetRandomFloat64(); }
static inline Float64 Get(Float64 n) { return GetRandomFloat64(n); }
static inline Float64 Get(Float64 m, Float64 n) { return GetRandomFloat64(m, n); }
static inline double Get() { return GetRandomFloat64(); }
static inline double Get(double n) { return GetRandomFloat64(n); }
static inline double Get(double m, double n) { return GetRandomFloat64(m, n); }
};
// ------------------------------------------------------------------------------------------------

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,184 +0,0 @@
// ------------------------------------------------------------------------------------------------
#include "Library/Socket.hpp"
#include "Misc/Signal.hpp"
// ------------------------------------------------------------------------------------------------
namespace SqMod {
// ------------------------------------------------------------------------------------------------
SQMODE_DECL_TYPENAME(SimpleSocketTypename, _SC("SimpleSocket"))
SQMODE_DECL_TYPENAME(PassiveSocketTypename, _SC("PassiveSocket"))
SQMODE_DECL_TYPENAME(ActiveSocketTypename, _SC("ActiveSocket"))
// ------------------------------------------------------------------------------------------------
#if defined(_DEBUG) || defined(SQMOD_EXCEPTLOC)
void SimpleSocket::Validate(CCStr file, Int32 line) const
{
if (!m_Socket)
{
SqThrowF("Invalid socket reference =>[%s:%d]", file, line);
}
}
#else
void SimpleSocket::Validate() const
{
if (!m_Socket)
{
SqThrowF("Invalid socket reference");
}
}
#endif // _DEBUG
// ------------------------------------------------------------------------------------------------
LightObj PassiveSocket::Accept()
{
SQMOD_VALIDATE(*this);
// Forward the request and store the returned instance
CActiveSocket * socket = Get()->Accept();
// Was there a socket returned?
if (socket)
{
// Return an object with the new socket instance
return LightObj(SqTypeIdentity< ActiveSocket >{}, SqVM(), socket);
}
// Return a null object
return LightObj{};
}
// ================================================================================================
void Register_Socket(HSQUIRRELVM vm)
{
Table skns(vm);
skns.Bind(_SC("Simple"),
Class< SimpleSocket, NoConstructor< SimpleSocket > >(vm, SimpleSocketTypename::Str)
// Properties
.Prop(_SC("Tag"), &SimpleSocket::GetTag, &SimpleSocket::SetTag)
.Prop(_SC("Data"), &SimpleSocket::GetData, &SimpleSocket::SetData)
.Prop(_SC("IsValid"), &SimpleSocket::IsSocketValid)
.Prop(_SC("ErrorDescription"), &SimpleSocket::DescribeError)
.Prop(_SC("NonBlocking"), &SimpleSocket::IsNonBlocking)
.Prop(_SC("InternalData"), &SimpleSocket::GetInternalData)
.Prop(_SC("BytesReceived"), &SimpleSocket::GetBytesReceived)
.Prop(_SC("BytesSent"), &SimpleSocket::GetBytesSent)
.Prop(_SC("ConnectTimeoutSec"), &SimpleSocket::GetConnectTimeoutSec)
.Prop(_SC("ConnectTimeoutUSec"), &SimpleSocket::GetConnectTimeoutUSec)
.Prop(_SC("ReceiveTimeoutSec"), &SimpleSocket::GetReceiveTimeoutSec)
.Prop(_SC("ReceiveTimeoutUSec"), &SimpleSocket::GetReceiveTimeoutUSec)
.Prop(_SC("Multicast"), &SimpleSocket::GetMulticast, &SimpleSocket::SetMulticast)
.Prop(_SC("SendTimeoutSec"), &SimpleSocket::GetSendTimeoutSec)
.Prop(_SC("SendTimeoutUSec"), &SimpleSocket::GetSendTimeoutUSec)
.Prop(_SC("SocketError"), &SimpleSocket::GetSocketError)
.Prop(_SC("TotalTimeMs"), &SimpleSocket::GetTotalTimeMs)
.Prop(_SC("TotalTimeUsec"), &SimpleSocket::GetTotalTimeUsec)
.Prop(_SC("SocketDSCP"), &SimpleSocket::GetSocketDSCP, &SimpleSocket::SetSocketDSCP)
.Prop(_SC("SocketType"), &SimpleSocket::GetSocketType)
.Prop(_SC("ClientAddr"), &SimpleSocket::GetClientAddr)
.Prop(_SC("ClientPort"), &SimpleSocket::GetClientPort)
.Prop(_SC("ServerAddr"), &SimpleSocket::GetServerAddr)
.Prop(_SC("ServerPort"), &SimpleSocket::GetServerPort)
.Prop(_SC("ReceiveWindowSize"), &SimpleSocket::GetReceiveWindowSize, &SimpleSocket::SetReceiveWindowSize)
.Prop(_SC("SendWindowSize"), &SimpleSocket::GetSendWindowSize, &SimpleSocket::SetSendWindowSize)
// Meta-methods
.SquirrelFunc(_SC("_typename"), &SimpleSocketTypename::Fn)
// Member Methods
.FmtFunc(_SC("SetTag"), &SimpleSocket::ApplyTag)
.Func(_SC("Initialize"), &SimpleSocket::Initialize)
.Func(_SC("Close"), &SimpleSocket::Close)
.Func(_SC("Shutdown"), &SimpleSocket::Shutdown)
.Func(_SC("Select"), &SimpleSocket::Select)
.Func(_SC("SelectEx"), &SimpleSocket::SelectEx)
.Func(_SC("TranslateSocketError"), &SimpleSocket::TranslateSocketError)
.Func(_SC("DescribeError"), &SimpleSocket::DescribeError)
.Func(_SC("Receive"), &SimpleSocket::Receive)
.Func(_SC("ReceiveInto"), &SimpleSocket::ReceiveInto)
.Func(_SC("Send"), &SimpleSocket::Send)
.Func(_SC("SendFile"), &SimpleSocket::SendFile)
.Func(_SC("SetBlocking"), &SimpleSocket::SetBlocking)
.Func(_SC("SetNonBlocking"), &SimpleSocket::SetNonBlocking)
.Func(_SC("SetOptionLinger"), &SimpleSocket::SetOptionLinger)
.Func(_SC("SetOptionReuseAddr"), &SimpleSocket::SetOptionReuseAddr)
.Func(_SC("SetConnectTimeout"), &SimpleSocket::SetConnectTimeout)
.Func(_SC("SetReceiveTimeout"), &SimpleSocket::SetReceiveTimeout)
.Func(_SC("SetMulticast"), &SimpleSocket::SetMulticastEx)
.FmtFunc(_SC("BindInterface"), &SimpleSocket::BindInterface)
.Func(_SC("SetSendTimeout"), &SimpleSocket::SetSendTimeout)
.Func(_SC("SetSocketDSCP"), &SimpleSocket::SetSocketDSCPEx)
.Func(_SC("SetReceiveWindowSize"), &SimpleSocket::SetReceiveWindowSize)
.Func(_SC("SetSendWindowSize"), &SimpleSocket::SetSendWindowSize)
.Func(_SC("DisableNagleAlgoritm"), &SimpleSocket::DisableNagleAlgoritm)
.Func(_SC("EnableNagleAlgoritm"), &SimpleSocket::EnableNagleAlgoritm)
// Static Member Methods
.StaticFunc(_SC("DescribeErrorCode"), &SimpleSocket::DescribeErrorCode)
);
skns.Bind(_SC("Passive"),
DerivedClass< PassiveSocket, SimpleSocket, NoCopy< PassiveSocket > >(vm, PassiveSocketTypename::Str)
// Constructors
.Ctor()
.Ctor< SQInteger >()
// Meta-methods
.SquirrelFunc(_SC("_typename"), &PassiveSocketTypename::Fn)
.Func(_SC("_tostring"), &PassiveSocket::ToString)
// Member Methods
.Func(_SC("Accept"), &PassiveSocket::Accept)
.Func(_SC("BindMulticast"), &PassiveSocket::BindMulticast)
.FmtFunc(_SC("Listen"), &PassiveSocket::Listen)
.FmtFunc(_SC("ListenEx"), &PassiveSocket::ListenEx)
.FmtFunc(_SC("SendStr"), &PassiveSocket::SendStr)
);
skns.Bind(_SC("Active"),
DerivedClass< ActiveSocket, SimpleSocket, NoCopy< ActiveSocket > >(vm, ActiveSocketTypename::Str)
// Constructors
.Ctor()
.Ctor< SQInteger >()
// Meta-methods
.SquirrelFunc(_SC("_typename"), &ActiveSocketTypename::Fn)
.Func(_SC("_tostring"), &ActiveSocket::ToString)
// Member Methods
.Func(_SC("Open"), &ActiveSocket::Open)
.FmtFunc(_SC("SendStr"), &ActiveSocket::SendStr)
);
RootTable(vm).Bind(_SC("SqSocket"), skns);
ConstTable(vm).Enum(_SC("SqSocketType"), Enumeration(vm)
.Const(_SC("Invalid"), static_cast< SQInteger >(CSimpleSocket::SocketTypeInvalid))
.Const(_SC("TCP"), static_cast< SQInteger >(CSimpleSocket::SocketTypeTcp))
.Const(_SC("UDP"), static_cast< SQInteger >(CSimpleSocket::SocketTypeUdp))
.Const(_SC("TCP6"), static_cast< SQInteger >(CSimpleSocket::SocketTypeTcp6))
.Const(_SC("UDP6"), static_cast< SQInteger >(CSimpleSocket::SocketTypeUdp6))
.Const(_SC("Raw"), static_cast< SQInteger >(CSimpleSocket::SocketTypeRaw))
);
ConstTable(vm).Enum(_SC("SqSocketError"), Enumeration(vm)
.Const(_SC("Error"), static_cast< SQInteger >(CSimpleSocket::SocketError))
.Const(_SC("Success"), static_cast< SQInteger >(CSimpleSocket::SocketSuccess))
.Const(_SC("InvalidSocket"), static_cast< SQInteger >(CSimpleSocket::SocketInvalidSocket))
.Const(_SC("InvalidAddress"), static_cast< SQInteger >(CSimpleSocket::SocketInvalidAddress))
.Const(_SC("InvalidPort"), static_cast< SQInteger >(CSimpleSocket::SocketInvalidPort))
.Const(_SC("ConnectionRefused"), static_cast< SQInteger >(CSimpleSocket::SocketConnectionRefused))
.Const(_SC("Timedout"), static_cast< SQInteger >(CSimpleSocket::SocketTimedout))
.Const(_SC("Ewouldblock"), static_cast< SQInteger >(CSimpleSocket::SocketEwouldblock))
.Const(_SC("Notconnected"), static_cast< SQInteger >(CSimpleSocket::SocketNotconnected))
.Const(_SC("Einprogress"), static_cast< SQInteger >(CSimpleSocket::SocketEinprogress))
.Const(_SC("Interrupted"), static_cast< SQInteger >(CSimpleSocket::SocketInterrupted))
.Const(_SC("ConnectionAborted"), static_cast< SQInteger >(CSimpleSocket::SocketConnectionAborted))
.Const(_SC("ProtocolError"), static_cast< SQInteger >(CSimpleSocket::SocketProtocolError))
.Const(_SC("FirewallError"), static_cast< SQInteger >(CSimpleSocket::SocketFirewallError))
.Const(_SC("InvalidSocketBuffer"), static_cast< SQInteger >(CSimpleSocket::SocketInvalidSocketBuffer))
.Const(_SC("ConnectionReset"), static_cast< SQInteger >(CSimpleSocket::SocketConnectionReset))
.Const(_SC("AddressInUse"), static_cast< SQInteger >(CSimpleSocket::SocketAddressInUse))
.Const(_SC("InvalidPointer"), static_cast< SQInteger >(CSimpleSocket::SocketInvalidPointer))
.Const(_SC("Eunknown"), static_cast< SQInteger >(CSimpleSocket::SocketEunknown))
);
ConstTable(vm).Enum(_SC("SqSocketShutdownMode"), Enumeration(vm)
.Const(_SC("Receives"), static_cast< SQInteger >(CSimpleSocket::Receives))
.Const(_SC("Sends"), static_cast< SQInteger >(CSimpleSocket::Sends))
.Const(_SC("Both"), static_cast< SQInteger >(CSimpleSocket::Both))
);
}
} // Namespace:: SqMod

View File

@ -1,755 +0,0 @@
#pragma once
// ------------------------------------------------------------------------------------------------
#include "Base/Shared.hpp"
#include "Library/Utils/Buffer.hpp"
#include "Library/Numeric/LongInt.hpp"
// ------------------------------------------------------------------------------------------------
#include <PassiveSocket.h>
#include <ActiveSocket.h>
// ------------------------------------------------------------------------------------------------
namespace SqMod {
/* ------------------------------------------------------------------------------------------------
* Handle validation.
*/
#if defined(_DEBUG) || defined(SQMOD_EXCEPTLOC)
#define SQMOD_VALIDATE(x) (x).Validate(__FILE__, __LINE__)
#else
#define SQMOD_VALIDATE(x) (x).Validate()
#endif // _DEBUG
// ------------------------------------------------------------------------------------------------
using CSimpleSocketPtr = SharedPtr< CSimpleSocket >;
using CSimpleSocketRef = WeakPtr< CSimpleSocket >;
/* ------------------------------------------------------------------------------------------------
* Provides a platform independent class to for socket development. This class is designed
* to abstract socket communication development in a platform independent manner.
*/
class SimpleSocket
{
protected:
/* --------------------------------------------------------------------------------------------
* The managed socket instance.
*/
CSimpleSocket * m_Socket;
/* --------------------------------------------------------------------------------------------
* User tag associated with this instance.
*/
String m_Tag;
/* --------------------------------------------------------------------------------------------
* User data associated with this instance.
*/
LightObj m_Data;
/* --------------------------------------------------------------------------------------------
* Default constructor. Initializes everything to null.
*/
SimpleSocket()
: m_Socket(nullptr)
{
}
/* --------------------------------------------------------------------------------------------
* Explicit constructor. Initializes with the given socket instance.
*/
explicit SimpleSocket(CSimpleSocket * socket)
: m_Socket(socket)
{
if (!socket)
{
STHROWF("Invalid socket instance.");
}
}
/* --------------------------------------------------------------------------------------------
* Destructor constructor.
*/
virtual ~SimpleSocket()
{
// Close the socket
if (m_Socket && m_Socket->IsSocketValid())
{
m_Socket->Close();
}
// Delete the managed socket (`delete` checks for NULL)
delete m_Socket;
}
/* --------------------------------------------------------------------------------------------
* Validate the managed connection handle and throw an error if invalid.
*/
#if defined(_DEBUG) || defined(SQMOD_EXCEPTLOC)
void Validate(CCStr file, Int32 line) const;
#else
void Validate() const;
#endif // _DEBUG
public:
/* --------------------------------------------------------------------------------------------
* Copy constructor (disabled).
*/
SimpleSocket(const SimpleSocket &) = delete;
/* --------------------------------------------------------------------------------------------
* Move constructor (disabled).
*/
SimpleSocket(SimpleSocket &&) = delete;
/* --------------------------------------------------------------------------------------------
* Copy assignment operator (disabled).
*/
SimpleSocket & operator = (const SimpleSocket &) = delete;
/* --------------------------------------------------------------------------------------------
* Move assignment operator (disabled).
*/
SimpleSocket & operator = (SimpleSocket &&) = delete;
/* --------------------------------------------------------------------------------------------
* Retrieve the associated user tag.
*/
const String & GetTag() const
{
return m_Tag;
}
/* --------------------------------------------------------------------------------------------
* Modify the associated user tag.
*/
void SetTag(StackStrF & tag)
{
if (tag.mLen > 0)
{
m_Tag.assign(tag.mPtr, static_cast< size_t >(tag.mLen));
}
else
{
m_Tag.clear();
}
}
/* --------------------------------------------------------------------------------------------
* Modify the associated user tag.
*/
SimpleSocket & ApplyTag(StackStrF & tag)
{
SetTag(tag);
return *this;
}
/* --------------------------------------------------------------------------------------------
* Retrieve the associated user data.
*/
LightObj & GetData()
{
return m_Data;
}
/* --------------------------------------------------------------------------------------------
* Modify the associated user data.
*/
void SetData(LightObj & data)
{
m_Data = data;
}
/* --------------------------------------------------------------------------------------------
* Initialize instance of CSocket. This method MUST be called before an object can be used.
*/
bool Initialize()
{
SQMOD_VALIDATE(*this);
return m_Socket->Initialize();
}
/* --------------------------------------------------------------------------------------------
* Close the managed socket.
*/
bool Close()
{
SQMOD_VALIDATE(*this);
return m_Socket->Close();
}
/* --------------------------------------------------------------------------------------------
* Shutdown the managed socket with various send and receive operations.
*/
bool Shutdown(SQInteger mode)
{
SQMOD_VALIDATE(*this);
return m_Socket->Shutdown(static_cast< CSimpleSocket::CShutdownMode >(mode));
}
/* --------------------------------------------------------------------------------------------
* Examine the socket descriptor sets currently owned by the instance of the socket class
* (the readfds, writefds, and errorfds parameters) to see whether some of their descriptors
* are ready for reading, are ready for writing, or have an exceptional condition pending, respectively.
* Block until an event happens on the specified file descriptors.
*/
bool Select()
{
SQMOD_VALIDATE(*this);
return m_Socket->Select();
}
/* --------------------------------------------------------------------------------------------
* Examine the socket descriptor sets currently owned by the instance of the socket class
* (the readfds, writefds, and errorfds parameters) to see whether some of their descriptors
* are ready for reading, are ready for writing, or have an exceptional condition pending, respectively.
*/
bool SelectEx(SQInteger timeout_sec, SQInteger timeout_usec)
{
SQMOD_VALIDATE(*this);
return m_Socket->Select(static_cast< Int32 >(timeout_sec), static_cast< Int32 >(timeout_usec));
}
/* --------------------------------------------------------------------------------------------
* Does the current instance of the socket object contain a valid socket descriptor.
*/
bool IsSocketValid()
{
SQMOD_VALIDATE(*this);
return m_Socket->IsSocketValid();
}
/* --------------------------------------------------------------------------------------------
* Provides a standard error code for cross platform development by mapping the
* operating system error to an error defined by the CSocket class.
*/
void TranslateSocketError()
{
SQMOD_VALIDATE(*this);
m_Socket->TranslateSocketError();
}
/* --------------------------------------------------------------------------------------------
* Returns a human-readable description of the given error code or the last error code of a socket.
*/
LightObj DescribeError()
{
SQMOD_VALIDATE(*this);
return LightObj(m_Socket->DescribeError(), -1);
}
/* --------------------------------------------------------------------------------------------
* Returns a human-readable description of the given error code or the last error code of a socket.
*/
static LightObj DescribeErrorCode(SQInteger err)
{
return LightObj(CSimpleSocket::DescribeError(static_cast< CSimpleSocket::CSocketError >(err)), -1);
}
/* --------------------------------------------------------------------------------------------
* Attempts to receive a block of data on an established connection. Buffer cursor is not affected!
* This is potentially broken because by the time a job is processed, another one could have override internal buffer.
*/
SQInteger Receive(Buffer::SzType max_bytes)
{
SQMOD_VALIDATE(*this);
// Now the call can be forwarded
return m_Socket->Receive(max_bytes, nullptr);
}
/* --------------------------------------------------------------------------------------------
* Attempts to receive a block of data on an established connection. Buffer cursor is not affected!
*/
SQInteger ReceiveInto(Buffer::SzType max_bytes, SqBuffer & out)
{
SQMOD_VALIDATE(*this);
// Make sure there is enough space in the buffer
if (max_bytes > out.GetRef()->Capacity())
{
out.GetRef()->Adjust(max_bytes); // We don't keep old data!
}
// Now the call can be forwarded
return m_Socket->Receive(max_bytes, out.GetRef()->Get< Uint8 >());
}
/* --------------------------------------------------------------------------------------------
* Attempts to send a block of data on an established connection.. Buffer cursor is not affected!
*/
SQInteger Send(SqBuffer & in, Buffer::SzType bytes_to_send)
{
SQMOD_VALIDATE(*this);
// Make sure there is enough data in the buffer
if (bytes_to_send > in.GetRef()->Capacity())
{
STHROWF("Not enough data in the buffer");
}
// Now the call can be forwarded
return m_Socket->Send(in.GetRef()->Get< Uint8 >(), bytes_to_send);
}
/* --------------------------------------------------------------------------------------------
* Copies data between one file descriptor and another.
*/
SQInteger SendFile(Int32 out_fd, Int32 in_fd, SLongInt & offset, Int32 count)
{
SQMOD_VALIDATE(*this);
// Create a native offset
off_t native_offset = ConvTo< off_t >::From(offset.GetNum());
// Forward the call and save the result
auto r = m_Socket->SendFile(out_fd, in_fd, &native_offset, count);
// Translate the native offset back to the wrapper
offset.SetNum(native_offset);
// Return back the result
return r;
}
/* --------------------------------------------------------------------------------------------
* Returns blocking/non-blocking state of socket.
*/
bool IsNonBlocking()
{
SQMOD_VALIDATE(*this);
return m_Socket->IsNonblocking();
}
/* --------------------------------------------------------------------------------------------
* Set the socket to blocking.
*/
bool SetBlocking()
{
SQMOD_VALIDATE(*this);
return m_Socket->SetBlocking();
}
/* --------------------------------------------------------------------------------------------
* Set the socket as non-blocking.
*/
bool SetNonBlocking()
{
SQMOD_VALIDATE(*this);
return m_Socket->SetNonblocking();
}
/* --------------------------------------------------------------------------------------------
* Returns a copy of the internal buffer used to receive data. Very ineffective. Use carefully.
*/
SqBuffer GetInternalData()
{
SQMOD_VALIDATE(*this);
return SqBuffer(reinterpret_cast< Buffer::ConstPtr >(m_Socket->GetData()),
static_cast< Buffer::SzType >(m_Socket->GetBytesReceived()), 0);
}
/* --------------------------------------------------------------------------------------------
* Returns the number of bytes received on the last call to SimpleSocket::Receive().
*/
SQInteger GetBytesReceived()
{
SQMOD_VALIDATE(*this);
return m_Socket->GetBytesReceived();
}
/* --------------------------------------------------------------------------------------------
* Returns the number of bytes sent on the last call to SimpleSocket::Send().
*/
SQInteger GetBytesSent()
{
SQMOD_VALIDATE(*this);
return m_Socket->GetBytesSent();
}
/* --------------------------------------------------------------------------------------------
* Controls the actions taken when CSimpleSocket::Close is executed on a socket object that has unsent data.
*/
bool SetOptionLinger(bool toggle, SQInteger time)
{
SQMOD_VALIDATE(*this);
return m_Socket->SetOptionLinger(toggle, ConvTo< Uint16 >::From(time));
}
/* --------------------------------------------------------------------------------------------
* Tells the kernel that even if this port is busy (in the TIME_WAIT state), go ahead and reuse it anyway.
*/
bool SetOptionReuseAddr()
{
SQMOD_VALIDATE(*this);
return m_Socket->SetOptionReuseAddr();
}
/* --------------------------------------------------------------------------------------------
* Gets the timeout value that specifies the maximum number of seconds a call to
* SimpleSocket::Open waits until it completes.
*/
SQInteger GetConnectTimeoutSec()
{
SQMOD_VALIDATE(*this);
return m_Socket->GetConnectTimeoutSec();
}
/* --------------------------------------------------------------------------------------------
* Gets the timeout value that specifies the maximum number of microseconds a call to
* SimpleSocket::Open waits until it completes.
*/
SQInteger GetConnectTimeoutUSec()
{
SQMOD_VALIDATE(*this);
return m_Socket->GetConnectTimeoutUSec();
}
/* --------------------------------------------------------------------------------------------
* Sets the timeout value that specifies the maximum amount of time a call to
* SimpleSocket::Receive waits until it completes.
*/
void SetConnectTimeout(Int32 timeout_sec, Int32 timeout_usec)
{
SQMOD_VALIDATE(*this);
m_Socket->SetConnectTimeout(timeout_sec, timeout_usec);
}
/* --------------------------------------------------------------------------------------------
* Gets the timeout value that specifies the maximum number of seconds a a call to
* SimpleSocket::Receive waits until it completes.
*/
SQInteger GetReceiveTimeoutSec()
{
SQMOD_VALIDATE(*this);
return m_Socket->GetReceiveTimeoutSec();
}
/* --------------------------------------------------------------------------------------------
* Gets the timeout value that specifies the maximum number of microseconds a call to
* SimpleSocket::Receive waits until it completes.
*/
SQInteger GetReceiveTimeoutUSec()
{
SQMOD_VALIDATE(*this);
return m_Socket->GetReceiveTimeoutUSec();
}
/* --------------------------------------------------------------------------------------------
* Sets the timeout value that specifies the maximum amount of time a call to
* SimpleSocket::Receive waits until it completes.
*/
bool SetReceiveTimeout(Int32 timeout_sec, Int32 timeout_usec)
{
SQMOD_VALIDATE(*this);
return m_Socket->SetReceiveTimeout(timeout_sec, timeout_usec);
}
/* --------------------------------------------------------------------------------------------
* Enable/disable multi-cast for a socket. This options is only valid for socket descriptors
* of type SimpleSocket::SocketTypeUdp.
*/
void SetMulticast(bool toggle)
{
SQMOD_VALIDATE(*this);
if (!m_Socket->SetMulticast(toggle, 1)) STHROWF("Unable to set multi-cast on socket.");
}
/* --------------------------------------------------------------------------------------------
* Enable/disable multi-cast for a socket. This options is only valid for socket descriptors
* of type SimpleSocket::SocketTypeUdp.
*/
bool SetMulticastEx(bool toggle, Uint8 multicast_ttl)
{
SQMOD_VALIDATE(*this);
return m_Socket->SetMulticast(toggle, multicast_ttl);
}
/* --------------------------------------------------------------------------------------------
* Return true if socket is multi-cast or false is socket is uni-cast.
*/
bool GetMulticast()
{
SQMOD_VALIDATE(*this);
return m_Socket->GetMulticast();
}
/* --------------------------------------------------------------------------------------------
* Bind socket to a specific interface when using multi-cast.
*/
bool BindInterface(StackStrF & intrf)
{
SQMOD_VALIDATE(*this);
return m_Socket->BindInterface(intrf.mPtr);
}
/* --------------------------------------------------------------------------------------------
* Gets the timeout value that specifies the maximum number of seconds a a call to
* SimpleSocket::Send waits until it completes.
*/
SQInteger GetSendTimeoutSec()
{
SQMOD_VALIDATE(*this);
return m_Socket->GetSendTimeoutSec();
}
/* --------------------------------------------------------------------------------------------
* Gets the timeout value that specifies the maximum number of microseconds a call to
* SimpleSocket::Send waits until it completes.
*/
SQInteger GetSendTimeoutUSec()
{
SQMOD_VALIDATE(*this);
return m_Socket->GetSendTimeoutUSec();
}
/* --------------------------------------------------------------------------------------------
* Gets the timeout value that specifies the maximum amount of time a call to
* SimpleSocket::Send waits until it completes.
*/
bool SetSendTimeout(Int32 timeout_sec, Int32 timeout_usec)
{
SQMOD_VALIDATE(*this);
return m_Socket->SetSendTimeout(timeout_sec, timeout_usec);
}
/* --------------------------------------------------------------------------------------------
* Returns the last error that occured for the instace of the SimpleSocket instance.
* This method should be called immediately to retrieve the error code for the failing mehtod call.
*/
SQInteger GetSocketError()
{
SQMOD_VALIDATE(*this);
return static_cast< SQInteger >(m_Socket->GetSocketError());
}
/* --------------------------------------------------------------------------------------------
* Get the total time the of the last operation in milliseconds.
*/
SQInteger GetTotalTimeMs()
{
SQMOD_VALIDATE(*this);
return static_cast< SQInteger >(m_Socket->GetTotalTimeMs());
}
/* --------------------------------------------------------------------------------------------
* Get the total time the of the last operation in microseconds.
*/
SQInteger GetTotalTimeUsec()
{
SQMOD_VALIDATE(*this);
return static_cast< SQInteger >(m_Socket->GetTotalTimeUsec());
}
/* --------------------------------------------------------------------------------------------
* Return Differentiated Services Code Point (DSCP) value currently set on the socket object.
*/
Int32 GetSocketDSCP()
{
SQMOD_VALIDATE(*this);
return m_Socket->GetSocketDscp();
}
/* --------------------------------------------------------------------------------------------
* Set Differentiated Services Code Point (DSCP) for socket object.
*/
void SetSocketDSCP(Int32 dscp)
{
SQMOD_VALIDATE(*this);
if (!m_Socket->SetSocketDscp(dscp)) STHROWF("Unable to set DSCP on socket.");
}
/* --------------------------------------------------------------------------------------------
* Set Differentiated Services Code Point (DSCP) for socket object.
*/
bool SetSocketDSCPEx(Int32 dscp)
{
SQMOD_VALIDATE(*this);
return m_Socket->SetSocketDscp(dscp);
}
/* --------------------------------------------------------------------------------------------
* Return socket type.
*/
SQInteger GetSocketType()
{
SQMOD_VALIDATE(*this);
return static_cast< SQInteger >(m_Socket->GetSocketType());
}
/* --------------------------------------------------------------------------------------------
* Returns clients Internet host address as a string in standard numbers-and-dots notation.
*/
LightObj GetClientAddr()
{
SQMOD_VALIDATE(*this);
return LightObj(m_Socket->GetClientAddr(), -1);
}
/* --------------------------------------------------------------------------------------------
* Returns the port number on which the client is connected.
*/
SQInteger GetClientPort()
{
SQMOD_VALIDATE(*this);
return m_Socket->GetClientPort();
}
/* --------------------------------------------------------------------------------------------
* Returns server Internet host address as a string in standard numbers-and-dots notation.
*/
LightObj GetServerAddr()
{
SQMOD_VALIDATE(*this);
return LightObj(m_Socket->GetServerAddr(), -1);
}
/* --------------------------------------------------------------------------------------------
* Returns the port number on which the server is connected.
*/
SQInteger GetServerPort()
{
SQMOD_VALIDATE(*this);
return m_Socket->GetServerPort();
}
/* --------------------------------------------------------------------------------------------
* Get the TCP receive buffer window size for the current socket object.
*/
SQInteger GetReceiveWindowSize()
{
SQMOD_VALIDATE(*this);
return static_cast< SQInteger >(m_Socket->GetReceiveWindowSize());
}
/* --------------------------------------------------------------------------------------------
* Get the TCP send buffer window size for the current socket object.
*/
SQInteger GetSendWindowSize()
{
SQMOD_VALIDATE(*this);
return static_cast< SQInteger >(m_Socket->GetSendWindowSize());
}
/* --------------------------------------------------------------------------------------------
* Set the TCP receive buffer window size for the current socket object.
*/
SQInteger SetReceiveWindowSize(SQInteger window_size)
{
SQMOD_VALIDATE(*this);
return static_cast< SQInteger >(m_Socket->SetReceiveWindowSize(ConvTo< Uint32 >::From(window_size)));
}
/* --------------------------------------------------------------------------------------------
* Set the TCP send buffer window size for the current socket object.
*/
SQInteger SetSendWindowSize(SQInteger window_size)
{
SQMOD_VALIDATE(*this);
return static_cast< SQInteger >(m_Socket->SetSendWindowSize(ConvTo< Uint32 >::From(window_size)));
}
/* --------------------------------------------------------------------------------------------
* Disable the Nagle algorithm (Set TCP_NODELAY to true)
*/
bool DisableNagleAlgoritm()
{
SQMOD_VALIDATE(*this);
return m_Socket->DisableNagleAlgoritm();
}
/* --------------------------------------------------------------------------------------------
* Enable the Nagle algorithm (Set TCP_NODELAY to false)
*/
bool EnableNagleAlgoritm()
{
SQMOD_VALIDATE(*this);
return m_Socket->EnableNagleAlgoritm();
}
};
/* ------------------------------------------------------------------------------------------------
* Provides a platform independent class to create a passive socket. A passive socket is used to
* create a "listening" socket. This type of object would be used when an application needs to
* wait for inbound connections.
*/
class PassiveSocket : public SimpleSocket
{
public:
/* --------------------------------------------------------------------------------------------
* Default constructor. Defaults to creating a TCP socket.
*/
PassiveSocket()
: PassiveSocket(CSimpleSocket::SocketTypeTcp)
{
}
/* --------------------------------------------------------------------------------------------
* Explicit constructor. Creates a socket of the specified type.
*/
explicit PassiveSocket(SQInteger type)
: SimpleSocket(new CPassiveSocket(static_cast< CSimpleSocket::CSocketType >(type)))
{
}
/* --------------------------------------------------------------------------------------------
* Explicit constructor. Creates a socket with the specified instance.
*/
explicit PassiveSocket(CPassiveSocket * socket)
: SimpleSocket(socket)
{
}
/* --------------------------------------------------------------------------------------------
* Retrieve the managed socket to the type that we expect.
*/
CPassiveSocket * Get()
{
return dynamic_cast< CPassiveSocket * >(m_Socket);
}
/* --------------------------------------------------------------------------------------------
* Retrieve the managed socket to the type that we expect.
*/
const CPassiveSocket * Get() const
{
return dynamic_cast< CPassiveSocket * >(m_Socket);
}
/* --------------------------------------------------------------------------------------------
* Return a string representation of this instance.
*/
LightObj ToString()
{
return m_Socket ? LightObj{} : GetServerAddr();
}
/* --------------------------------------------------------------------------------------------
* Extracts the first connection request on the queue of pending connections and creates a newly connected socket.
*/
LightObj Accept();
/* --------------------------------------------------------------------------------------------
* Bind to a multi-cast group on a specified interface, multi-cast group, and port.
*/
bool BindMulticast(StackStrF & intrf, StackStrF & group, Uint16 port)
{
SQMOD_VALIDATE(*this);
return Get()->BindMulticast(intrf.mPtr, group.mPtr, port);
}
/* --------------------------------------------------------------------------------------------
* Create a listening socket at local IP address 'x.x.x.x' or 'localhost' if addr is NULL on port port.
*/
bool Listen(Uint16 port, StackStrF & addr)
{
SQMOD_VALIDATE(*this);
return Get()->Listen(addr.mPtr, port);
}
/* --------------------------------------------------------------------------------------------
* Create a listening socket at local IP address 'x.x.x.x' or 'localhost' if addr is NULL on port port.
*/
bool ListenEx(Uint16 port, Int32 connection_backlog, StackStrF & addr)
{
SQMOD_VALIDATE(*this);
return Get()->Listen(addr.mPtr, port, connection_backlog);
}
/* --------------------------------------------------------------------------------------------
* Attempts to send a string on an established connection.
*/
Int32 SendStr(StackStrF & str)
{
SQMOD_VALIDATE(*this);
return Get()->Send(reinterpret_cast< const uint8_t * >(str.mPtr),
static_cast< size_t >(str.mLen) * (sizeof(SQChar) / sizeof(uint8_t)));
}
};
/* ------------------------------------------------------------------------------------------------
* Provides a platform independent class to create an active socket. An active socket is used to
* create a socket which connects to a server. This type of object would be used when
* an application needs to send/receive data from a server.
*/
class ActiveSocket : public SimpleSocket
{
friend class PassiveSocket;
public:
/* --------------------------------------------------------------------------------------------
* Default constructor. Defaults to creating a TCP socket.
*/
ActiveSocket()
: ActiveSocket(CSimpleSocket::SocketTypeTcp)
{
}
/* --------------------------------------------------------------------------------------------
* Explicit constructor. Creates a socket of the specified type.
*/
explicit ActiveSocket(SQInteger type)
: SimpleSocket(new CActiveSocket(static_cast< CSimpleSocket::CSocketType >(type)))
{
}
/* --------------------------------------------------------------------------------------------
* Explicit constructor. Creates a socket with the specified instance.
*/
explicit ActiveSocket(CActiveSocket * socket)
: SimpleSocket(socket)
{
}
/* --------------------------------------------------------------------------------------------
* Retrieve the managed socket to the type that we expect.
*/
CActiveSocket * Get()
{
return dynamic_cast< CActiveSocket * >(m_Socket);
}
/* --------------------------------------------------------------------------------------------
* Retrieve the managed socket to the type that we expect.
*/
const CActiveSocket * Get() const
{
return dynamic_cast< CActiveSocket * >(m_Socket);
}
/* --------------------------------------------------------------------------------------------
* Return a string representation of this instance.
*/
LightObj ToString()
{
return m_Socket ? LightObj{} : GetClientAddr();
}
/* --------------------------------------------------------------------------------------------
* Establish a connection to the address specified by addr.
*/
bool Open(Uint16 port, StackStrF & addr)
{
SQMOD_VALIDATE(*this);
return Get()->Open(addr.mPtr, port);
}
/* --------------------------------------------------------------------------------------------
* Attempts to send a string on an established connection.
*/
Int32 SendStr(StackStrF & str)
{
SQMOD_VALIDATE(*this);
return Get()->Send(reinterpret_cast< const uint8_t * >(str.mPtr),
static_cast< size_t >(str.mLen) * (sizeof(SQChar) / sizeof(uint8_t)));
}
};
} // Namespace:: SqMod

View File

@ -1,11 +1,10 @@
// ------------------------------------------------------------------------------------------------
#include "Library/String.hpp"
#include "Base/Shared.hpp"
#include "Base/Buffer.hpp"
#include "Core/Utility.hpp"
#include "Core/Buffer.hpp"
// ------------------------------------------------------------------------------------------------
#include <cctype>
#include <cstdio>
#include <cstdlib>
#include <cstring>
@ -16,7 +15,7 @@
namespace SqMod {
// ------------------------------------------------------------------------------------------------
static LightObj SqLeftStr(SQChar f, Uint32 w, StackStrF & s)
static LightObj SqLeftStr(SQChar f, uint32_t w, StackStrF & s)
{
// Is the specified width valid?
if (!w)
@ -46,7 +45,7 @@ static LightObj SqLeftStr(SQChar f, Uint32 w, StackStrF & s)
}
// ------------------------------------------------------------------------------------------------
static LightObj SqLeftOffsetStr(SQChar f, Uint32 w, Uint32 o, StackStrF & s)
static LightObj SqLeftOffsetStr(SQChar f, uint32_t w, uint32_t o, StackStrF & s)
{
// Is the specified width valid?
if (!w)
@ -68,7 +67,7 @@ static LightObj SqLeftOffsetStr(SQChar f, Uint32 w, Uint32 o, StackStrF & s)
else
{
// Calculate the string length
const Uint32 n = ConvTo< Uint32 >::From(s.mLen);
const uint32_t n = ConvTo< uint32_t >::From(s.mLen);
// Insert the fill character first
std::memset(b.Data(), f, w);
// Overwrite with the specified string
@ -90,7 +89,7 @@ static LightObj SqLeftOffsetStr(SQChar f, Uint32 w, Uint32 o, StackStrF & s)
}
// ------------------------------------------------------------------------------------------------
static LightObj SqRightStr(SQChar f, Uint32 w, StackStrF & s)
static LightObj SqRightStr(SQChar f, uint32_t w, StackStrF & s)
{
// Is the specified width valid?
if (!w)
@ -107,7 +106,7 @@ static LightObj SqRightStr(SQChar f, Uint32 w, StackStrF & s)
else
{
// Calculate the string length
const Uint32 n = ConvTo< Uint32 >::From(s.mLen);
const uint32_t n = ConvTo< uint32_t >::From(s.mLen);
// Insert the fill character first
std::memset(b.Data(), f, w);
// Overwrite with the specified string
@ -129,7 +128,7 @@ static LightObj SqRightStr(SQChar f, Uint32 w, StackStrF & s)
}
// ------------------------------------------------------------------------------------------------
static LightObj SqRightOffsetStr(SQChar f, Uint32 w, Uint32 o, StackStrF & s)
static LightObj SqRightOffsetStr(SQChar f, uint32_t w, uint32_t o, StackStrF & s)
{
// Is the specified width valid?
if (!w)
@ -151,7 +150,7 @@ static LightObj SqRightOffsetStr(SQChar f, Uint32 w, Uint32 o, StackStrF & s)
else
{
// Calculate the string length
const Uint32 n = ConvTo< Uint32 >::From(s.mLen);
const uint32_t n = ConvTo< uint32_t >::From(s.mLen);
// Insert the fill character first
std::memset(b.Data(), f, w);
// Overwrite with the specified string
@ -173,7 +172,7 @@ static LightObj SqRightOffsetStr(SQChar f, Uint32 w, Uint32 o, StackStrF & s)
}
// ------------------------------------------------------------------------------------------------
static LightObj SqCenterStr(SQChar f, Uint32 w, StackStrF & s)
static LightObj SqCenterStr(SQChar f, uint32_t w, StackStrF & s)
{
// Is the specified width valid?
if (!w)
@ -190,7 +189,7 @@ static LightObj SqCenterStr(SQChar f, Uint32 w, StackStrF & s)
else
{
// Calculate the insert position
const Int32 p = ((w/2) - (s.mLen/2));
const int32_t p = ((w/2) - (s.mLen/2));
// Insert only the fill character first
std::memset(b.Data(), f, w);
// Overwrite with the specified string
@ -205,7 +204,7 @@ static LightObj SqCenterStr(SQChar f, Uint32 w, StackStrF & s)
}
// ------------------------------------------------------------------------------------------------
static Buffer StrJustAlphaNumImpl(CSStr str, Uint32 len)
static Buffer StrJustAlphaNumImpl(const SQChar * str, uint32_t len)
{
// See if we actually have something to search for
if(!len)
@ -215,9 +214,9 @@ static Buffer StrJustAlphaNumImpl(CSStr str, Uint32 len)
// Obtain a temporary buffer
Buffer b(len + 1); // + null terminator
// Resulted string size
Uint32 n = 0;
uint32_t n = 0;
// Currently processed character
SQChar c = 0;
SQChar c;
// Process characters
while ((c = *(str++)) != '\0')
{
@ -237,7 +236,7 @@ static Buffer StrJustAlphaNumImpl(CSStr str, Uint32 len)
}
// ------------------------------------------------------------------------------------------------
Buffer StrJustAlphaNumB(CSStr str)
Buffer StrJustAlphaNumB(const SQChar * str)
{
// See if we actually have something to search for
if(!str || *str == '\0')
@ -249,7 +248,7 @@ Buffer StrJustAlphaNumB(CSStr str)
}
// ------------------------------------------------------------------------------------------------
CSStr StrJustAlphaNum(CSStr str)
const SQChar * StrJustAlphaNum(const SQChar * str)
{
// See if we actually have something to search for
if(!str || *str == '\0')
@ -273,7 +272,7 @@ static LightObj SqJustAlphaNum(StackStrF & s)
}
// ------------------------------------------------------------------------------------------------
static Buffer StrToLowercaseImpl(CSStr str, Uint32 len)
static Buffer StrToLowercaseImpl(const SQChar * str, uint32_t len)
{
// See if we actually have something to search for
if(!len)
@ -283,7 +282,7 @@ static Buffer StrToLowercaseImpl(CSStr str, Uint32 len)
// Obtain a temporary buffer
Buffer b(len + 1); // + null terminator
// Resulted string size
Uint32 n = 0;
uint32_t n = 0;
// Process characters
while (*str != '\0')
{
@ -299,7 +298,7 @@ static Buffer StrToLowercaseImpl(CSStr str, Uint32 len)
}
// ------------------------------------------------------------------------------------------------
Buffer StrToLowercaseB(CSStr str)
Buffer StrToLowercaseB(const SQChar * str)
{
// See if we actually have something to search for
if(!str || *str == '\0')
@ -311,7 +310,7 @@ Buffer StrToLowercaseB(CSStr str)
}
// ------------------------------------------------------------------------------------------------
CSStr StrToLowercase(CSStr str)
const SQChar * StrToLowercase(const SQChar * str)
{
// See if we actually have something to search for
if(!str || *str == '\0')
@ -335,7 +334,7 @@ static LightObj SqToLowercase(StackStrF & s)
}
// ------------------------------------------------------------------------------------------------
static Buffer StrToUppercaseImpl(CSStr str, Uint32 len)
static Buffer StrToUppercaseImpl(const SQChar * str, uint32_t len)
{
// See if we actually have something to search for
if(!len)
@ -345,7 +344,7 @@ static Buffer StrToUppercaseImpl(CSStr str, Uint32 len)
// Obtain a temporary buffer
Buffer b(len + 1); // + null terminator
// Resulted string size
Uint32 n = 0;
uint32_t n = 0;
// Process characters
while (*str != '\0')
{
@ -361,7 +360,7 @@ static Buffer StrToUppercaseImpl(CSStr str, Uint32 len)
}
// ------------------------------------------------------------------------------------------------
Buffer StrToUppercaseB(CSStr str)
Buffer StrToUppercaseB(const SQChar * str)
{
// See if we actually have something to search for
if(!str || *str == '\0')
@ -373,7 +372,7 @@ Buffer StrToUppercaseB(CSStr str)
}
// ------------------------------------------------------------------------------------------------
CSStr StrToUppercase(CSStr str)
const SQChar * StrToUppercase(const SQChar * str)
{
// See if we actually have something to search for
if(!str || *str == '\0')
@ -409,7 +408,7 @@ template < int (*Fn)(int) > static bool SqAllChars(StackStrF & s)
return true;
}
// Start iterating characters and find the first that doesn't match
for (CSStr itr = s.mPtr; *itr != '\0'; ++itr)
for (const SQChar * itr = s.mPtr; *itr != '\0'; ++itr)
{
// Call the predicate with the current character
if (Fn(*itr) == 0)
@ -430,7 +429,7 @@ template < int (*Fn)(int), bool Neg > static LightObj SqFirstChar(StackStrF & s)
if (s.mLen)
{
// Start iterating characters and find the first that doesn't match
for (CSStr itr = s.mPtr; *itr != '\0'; ++itr)
for (const SQChar * itr = s.mPtr; *itr != '\0'; ++itr)
{
// Call the predicate with the current character
if ((Fn(*itr) == 0) == Neg)
@ -458,7 +457,7 @@ template < int (*Fn)(int), bool Neg > static LightObj SqLastChar(StackStrF & s)
if (s.mLen)
{
// Start iterating characters and find the first that doesn't match
for (CSStr itr = (s.mPtr + s.mLen) - 1; itr >= s.mPtr; --itr)
for (const SQChar * itr = (s.mPtr + s.mLen) - 1; itr >= s.mPtr; --itr)
{
// Call the predicate with the current character
if ((Fn(*itr) == 0) == Neg)
@ -507,10 +506,10 @@ static SQInteger SplitWhereCharImpl(HSQUIRRELVM vm, int(*fn)(int), bool neg)
}
// Remember the position of the last found match
CSStr last = val.mPtr;
const SQChar * last = val.mPtr;
// Start iterating characters and slice where a match is found
for (CSStr itr = val.mPtr; *itr != '\0'; ++itr)
for (const SQChar * itr = val.mPtr; *itr != '\0'; ++itr)
{
// Call the predicate with the current character
if ((fn(*itr) == 0) == neg)
@ -577,7 +576,7 @@ template < int (*Fn)(int) > static bool IsCharOfType(int c)
}
// ------------------------------------------------------------------------------------------------
static bool OnlyDelimiter(CSStr str, SQChar chr)
static bool OnlyDelimiter(const SQChar * str, SQChar chr)
{
while (*str != '\0')
{
@ -595,7 +594,7 @@ static bool OnlyDelimiter(CSStr str, SQChar chr)
// ------------------------------------------------------------------------------------------------
static SQInteger SqStrExplode(HSQUIRRELVM vm)
{
const Int32 top = sq_gettop(vm);
const int32_t top = sq_gettop(vm);
// Was the delimiter character specified?
if (top <= 1)
{
@ -619,15 +618,15 @@ static SQInteger SqStrExplode(HSQUIRRELVM vm)
return val.mRes; // Propagate the error!
}
// The delimiter character and boolean empty
SQChar delim = 0;
bool empty = 0;
SQChar delim;
bool empty;
// Attempt to retrieve the remaining arguments from the stack
try
{
delim = Var< SQChar >(vm, 2).value;
empty = Var< bool >(vm, 3).value;
}
catch (const Sqrat::Exception & e)
catch (const std::exception & e)
{
return sq_throwerror(vm, e.what());
}
@ -636,7 +635,7 @@ static SQInteger SqStrExplode(HSQUIRRELVM vm)
return sq_throwerror(vm, _SC("Unable to retrieve arguments"));
}
// Grab the string value to a shorter name
CSStr str = val.mPtr;
const SQChar * str = val.mPtr;
// Create an empty array on the stack
sq_newarray(vm, 0);
// See if we actually have something to explode
@ -646,9 +645,9 @@ static SQInteger SqStrExplode(HSQUIRRELVM vm)
return 1;
}
// Don't modify the specified string pointer
CSStr itr = str, last = str;
const SQChar * itr = str, * last = str;
// The number of delimiter occurrences
Uint32 num = 0;
uint32_t num = 0;
// Pre-count how many delimiters of this type exist
while (*itr != '\0')
{
@ -755,10 +754,10 @@ static SQInteger SqStrExplode(HSQUIRRELVM vm)
}
// ------------------------------------------------------------------------------------------------
static CSStr StrImplode(SQChar chr, Array & arr)
static const SQChar * StrImplode(SQChar chr, Array & arr)
{
// Determine array size
const Int32 length = static_cast< Int32 >(arr.Length());
const auto length = static_cast< int32_t >(arr.Length());
// Is there anything to implode?
if (length <= 0)
{
@ -789,18 +788,18 @@ static CSStr StrImplode(SQChar chr, Array & arr)
}
// ------------------------------------------------------------------------------------------------
static CSStr FromArray(Array & arr)
static const SQChar * FromArray(Array & arr)
{
// Determine array size
const Int32 length = ConvTo< Int32 >::From(arr.Length());
const int32_t length = ConvTo< int32_t >::From(arr.Length());
// Obtain a temporary buffer
Buffer b(length * sizeof(Int32));
Buffer b(length * sizeof(int32_t));
// Get array elements as integers
arr.GetArray< Int32 >(b.Get< Int32 >(), length);
arr.GetArray< int32_t >(b.Get< int32_t >(), length);
// Overwrite integers with characters
for (Int32 n = 0; n < length; ++n)
for (int32_t n = 0; n < length; ++n)
{
b.At(n) = ConvTo< SQChar >::From(b.At< Int32 >(n * sizeof(Int32)));
b.At(n) = ConvTo< SQChar >::From(b.At< int32_t >(n * sizeof(int32_t)));
}
// Terminate the resulted string
b.At(length) = '\0';
@ -839,7 +838,7 @@ static String StrCharacterSwap(SQInteger a, SQInteger b, StackStrF & val)
}
// Turn it into a string that we can edit
String str(val.mPtr, val.mLen);
// Replace all occurences of the specified character
// Replace all occurrences of the specified character
std::replace(str.begin(), str.end(),
static_cast< String::value_type >(a), static_cast< String::value_type >(b));
// Return the new string

View File

@ -1,7 +1,7 @@
#pragma once
// ------------------------------------------------------------------------------------------------
#include "SqBase.hpp"
#include "Core/Common.hpp"
// ------------------------------------------------------------------------------------------------
namespace SqMod {
@ -9,19 +9,19 @@ namespace SqMod {
/* ------------------------------------------------------------------------------------------------
* Get a new string with only the alpha numeric characters from the specified string.
*/
CSStr StrJustAlphaNum(CSStr str);
Buffer StrJustAlphaNumB(CSStr str);
SQMOD_NODISCARD const SQChar * StrJustAlphaNum(const SQChar * str);
SQMOD_NODISCARD Buffer StrJustAlphaNumB(const SQChar * str);
/* ------------------------------------------------------------------------------------------------
* Convert the specified string to lowercase.
*/
CSStr StrToLowercase(CSStr str);
Buffer StrToLowercaseB(CSStr str);
SQMOD_NODISCARD const SQChar * StrToLowercase(const SQChar * str);
SQMOD_NODISCARD Buffer StrToLowercaseB(const SQChar * str);
/* ------------------------------------------------------------------------------------------------
* Convert the specified string to uppercase.
*/
CSStr StrToUppercase(CSStr str);
Buffer StrToUppercaseB(CSStr str);
SQMOD_NODISCARD const SQChar * StrToUppercase(const SQChar * str);
SQMOD_NODISCARD Buffer StrToUppercaseB(const SQChar * str);
} // Namespace:: SqMod

View File

@ -1,13 +1,9 @@
// ------------------------------------------------------------------------------------------------
#include "Library/System.hpp"
#include "Base/Shared.hpp"
#include "Base/Buffer.hpp"
#include "Core/Buffer.hpp"
// ------------------------------------------------------------------------------------------------
#include <cstdio>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
// ------------------------------------------------------------------------------------------------
@ -34,18 +30,18 @@ static SQInteger SqSysExec(HSQUIRRELVM vm)
// Attempt to open the specified process
FILE * pipe = popen(val.mPtr, "r");
// The process return status
Int32 status = -1;
int32_t status;
// Did we fail to open the process?
if (!pipe)
{
return sq_throwerror(vm, ToStrF("Unable to open process [%s]", val.mPtr));
return sq_throwerrorf(vm, "Unable to open process [%s]", val.mPtr);
}
// Attempt to read process output
try
{
while (!std::feof(pipe))
{
if (std::fgets(buffer, 128, pipe) != NULL)
if (std::fgets(buffer, 128, pipe) != nullptr)
{
b.AppendS(buffer);
}
@ -56,12 +52,12 @@ static SQInteger SqSysExec(HSQUIRRELVM vm)
// Close the process
status = pclose(pipe);
// Now throw the error
return sq_throwerror(vm, ToStrF("Unable read process output [%d]", status));
return sq_throwerrorf(vm, "Unable read process output [%d]", status);
}
// Close the process and obtain the exit status
status = pclose(pipe);
// Remember the top of the stack
const Int32 top = sq_gettop(vm);
const int32_t top = sq_gettop(vm);
// Create a new table on the stack
sq_newtable(vm);
// Push the element name

View File

@ -1,11 +1,9 @@
#pragma once
// ------------------------------------------------------------------------------------------------
#include "Base/Shared.hpp"
#include "Core/Common.hpp"
// ------------------------------------------------------------------------------------------------
namespace SqMod {
} // Namespace:: SqMod

View File

@ -5,8 +5,8 @@
namespace SqMod {
// ------------------------------------------------------------------------------------------------
SQMODE_DECL_TYPENAME(TypenameD, _SC("SqSysDir"))
SQMODE_DECL_TYPENAME(TypenameF, _SC("SqSysFile"))
SQMOD_DECL_TYPENAME(TypenameD, _SC("SqSysDir"))
SQMOD_DECL_TYPENAME(TypenameF, _SC("SqSysFile"))
// ------------------------------------------------------------------------------------------------
LightObj SysDir::ReadFile() const
@ -68,7 +68,7 @@ LightObj SysDir::ReadFileAt(SQInteger i) const
// The file handle where it will be opened
tinydir_file * handle = ptr->GetOrMake();
// Attempt to read the current file
if (tinydir_readfile_n(mHandle.get(), handle, i) == -1)
if (tinydir_readfile_n(mHandle.get(), handle, static_cast< size_t >(i)) == -1)
{
STHROWF("Failed to read file at index (" PRINT_INT_FMT ")", i);
}

View File

@ -1,9 +1,10 @@
#pragma once
// ------------------------------------------------------------------------------------------------
#include "Base/Shared.hpp"
#include "Core/Common.hpp"
// ------------------------------------------------------------------------------------------------
#include <cwchar>
#include <memory>
// ------------------------------------------------------------------------------------------------
@ -22,7 +23,7 @@ typedef std::unique_ptr< tinydir_file > TinyFile;
class SysDir
{
// --------------------------------------------------------------------------------------------
TinyDir mHandle; /* Handle to the managed directory. */
TinyDir mHandle{}; /* Handle to the managed directory. */
public:
@ -40,7 +41,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Make sure a valid handle is being managed before attempting to use it.
*/
void Validate(CSStr action) const
void Validate(const SQChar * action) const
{
if (!mHandle)
{
@ -51,16 +52,11 @@ public:
/* --------------------------------------------------------------------------------------------
* Defaults to a null handle.
*/
SysDir()
: mHandle()
{
/*...*/
}
SysDir() = default;
/* --------------------------------------------------------------------------------------------
* Opens the directory at the specified path.
*/
SysDir(StackStrF & path)
explicit SysDir(StackStrF & path)
: SysDir(false, path)
{
/*...*/
@ -100,11 +96,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Move constructor.
*/
SysDir(SysDir && o)
: mHandle(std::forward< TinyDir >(o.mHandle))
{
/*...*/
}
SysDir(SysDir && o) noexcept = default;
/* --------------------------------------------------------------------------------------------
* Destructor.
@ -126,7 +118,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Move assignment operator.
*/
SysDir & operator = (SysDir && o)
SysDir & operator = (SysDir && o) noexcept
{
// Avoid self assignment
if (this != &o)
@ -145,7 +137,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Retrieve the raw managed handle.
*/
tinydir_dir * Get() const
SQMOD_NODISCARD tinydir_dir * Get() const
{
return mHandle.get();
}
@ -153,7 +145,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Retrieve the raw managed handle and make one if it doesn't exist already.
*/
tinydir_dir * GetOrMake()
SQMOD_NODISCARD tinydir_dir * GetOrMake()
{
// Do we have a handle already?
if (!mHandle)
@ -167,7 +159,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Take ownership of the managed handle.
*/
tinydir_dir * Release()
SQMOD_NODISCARD tinydir_dir * Release()
{
return mHandle.release();
}
@ -183,17 +175,21 @@ public:
/* --------------------------------------------------------------------------------------------
* Used by the script engine to convert an instance of this type to a string.
*/
CSStr ToString() const
SQMOD_NODISCARD String ToString() const
{
return mHandle ? mHandle->path : _SC("");
#if defined(UNICODE) || defined(_UNICODE)
return mHandle ? String(mHandle->path, mHandle->path + std::wcslen(mHandle->path)) : _SC("");
#else
return mHandle ? String(mHandle->path) : String();
#endif
}
/* --------------------------------------------------------------------------------------------
* Check for the presence of a handle.
*/
bool IsValid() const
SQMOD_NODISCARD bool IsValid() const
{
return !!mHandle;
return static_cast< bool >(mHandle);
}
/* --------------------------------------------------------------------------------------------
@ -215,7 +211,11 @@ public:
// If we just allocated one, we initialize it (win, either way)
tinydir_close(mHandle.get());
// Attempt to open the specified directory
#if defined(UNICODE) || defined(_UNICODE)
if (tinydir_open(mHandle.get(), std::wstring(path.mPtr, path.mPtr + path.GetSize()).c_str()) == -1)
#else
if (tinydir_open(mHandle.get(), path.mPtr) == -1)
#endif
{
// Don't keep a bad handle
mHandle.reset();
@ -243,7 +243,11 @@ public:
// If we just allocated one, we initialize it (win, either way)
tinydir_close(mHandle.get());
// Attempt to open the specified directory
#if defined(UNICODE) || defined(_UNICODE)
if (tinydir_open_sorted(mHandle.get(), std::wstring(path.mPtr, path.mPtr + path.GetSize()).c_str()) == -1)
#else
if (tinydir_open_sorted(mHandle.get(), path.mPtr) == -1)
#endif
{
// Don't keep a bad handle
mHandle.reset();
@ -324,17 +328,21 @@ public:
/* --------------------------------------------------------------------------------------------
* Retrieve the opened path.
*/
CSStr GetPath() const
SQMOD_NODISCARD String GetPath() const
{
Validate("obtain path");
// Return the requested information
return mHandle->path;
#if defined(UNICODE) || defined(_UNICODE)
return String(mHandle->path, mHandle->path + std::wcslen(mHandle->path));
#else
return String(mHandle->path);
#endif
}
/* --------------------------------------------------------------------------------------------
* See if there's a next element in the opened directory.
*/
bool HasNext() const
SQMOD_NODISCARD bool HasNext() const
{
Validate("check for next");
// Return the requested information
@ -344,7 +352,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Retrieve the number of files in the opened directory (only when opened in sorted mode).
*/
SQInteger FileCount() const
SQMOD_NODISCARD SQInteger FileCount() const
{
Validate("obtain file count");
// Return the requested information
@ -354,11 +362,11 @@ public:
/* --------------------------------------------------------------------------------------------
* Open current file from the specified directory.
*/
LightObj ReadFile() const;
SQMOD_NODISCARD LightObj ReadFile() const;
/* --------------------------------------------------------------------------------------------
* Open current file from the specified directory.
*/
LightObj ReadFileAt(SQInteger i) const;
SQMOD_NODISCARD LightObj ReadFileAt(SQInteger i) const;
};
/* ------------------------------------------------------------------------------------------------
@ -367,7 +375,7 @@ public:
class SysFile
{
// --------------------------------------------------------------------------------------------
TinyFile mHandle; /* Handle to the managed file. */
TinyFile mHandle{}; /* Handle to the managed file. */
public:
/* --------------------------------------------------------------------------------------------
@ -384,7 +392,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Make sure a valid handle is being managed before attempting to use it.
*/
void Validate(CSStr action) const
void Validate(const SQChar * action) const
{
if (!mHandle)
{
@ -395,16 +403,12 @@ public:
/* --------------------------------------------------------------------------------------------
* Defaults to a null handle.
*/
SysFile()
: mHandle()
{
/*...*/
}
SysFile() = default;
/* --------------------------------------------------------------------------------------------
* Opens the file at the specified path.
*/
SysFile(StackStrF & path)
explicit SysFile(StackStrF & path)
: SysFile()
{
Open(path);
@ -418,11 +422,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Move constructor.
*/
SysFile(SysFile && o)
: mHandle(std::forward< TinyFile >(o.mHandle))
{
/*...*/
}
SysFile(SysFile && o) noexcept = default;
/* --------------------------------------------------------------------------------------------
* Copy assignment operator (disabled).
@ -432,7 +432,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Move assignment operator.
*/
SysFile & operator = (SysFile && o)
SysFile & operator = (SysFile && o) noexcept
{
// Avoid self assignment
if (this != &o)
@ -446,7 +446,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Retrieve the raw managed handle.
*/
tinydir_file * Get() const
SQMOD_NODISCARD tinydir_file * Get() const
{
return mHandle.get();
}
@ -454,7 +454,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Retrieve the raw managed handle and make one if it doesn't exist already.
*/
tinydir_file * GetOrMake()
SQMOD_NODISCARD tinydir_file * GetOrMake()
{
// Do we have a handle already?
if (!mHandle)
@ -468,7 +468,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Take ownership of the managed handle.
*/
tinydir_file * Release()
SQMOD_NODISCARD tinydir_file * Release()
{
return mHandle.release();
}
@ -484,17 +484,21 @@ public:
/* --------------------------------------------------------------------------------------------
* Used by the script engine to convert an instance of this type to a string.
*/
CSStr ToString() const
SQMOD_NODISCARD String ToString() const
{
return mHandle ? mHandle->path : _SC("");
#if defined(UNICODE) || defined(_UNICODE)
return mHandle ? String(mHandle->path, mHandle->path + std::wcslen(mHandle->path)) : _SC("");
#else
return mHandle ? String(mHandle->path) : String();
#endif
}
/* --------------------------------------------------------------------------------------------
* Check for the presence of a handle.
*/
bool IsValid() const
SQMOD_NODISCARD bool IsValid() const
{
return !!mHandle;
return static_cast< bool >(mHandle);
}
/* --------------------------------------------------------------------------------------------
@ -512,7 +516,11 @@ public:
// Discard current error number
errno = 0;
// Attempt to open the specified file
#if defined(UNICODE) || defined(_UNICODE)
if (tinydir_file_open(mHandle.get(), std::wstring(path.mPtr, path.mPtr + path.GetSize()).c_str()) == -1)
#else
if (tinydir_file_open(mHandle.get(), path.mPtr) == -1)
#endif
{
// Don't keep a bad handle
mHandle.reset();
@ -531,7 +539,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Check if the opened element is a directory.
*/
bool IsDir() const
SQMOD_NODISCARD bool IsDir() const
{
Validate("check type");
// Return the requested information
@ -541,7 +549,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Check if the opened element is a regular file.
*/
bool IsReg() const
SQMOD_NODISCARD bool IsReg() const
{
Validate("check type");
// Return the requested information
@ -551,31 +559,43 @@ public:
/* --------------------------------------------------------------------------------------------
* Retrieve the path of the opened file.
*/
CSStr GetPath() const
SQMOD_NODISCARD String GetPath() const
{
Validate("retrieve path");
// Return the requested information
return mHandle->path;
#if defined(UNICODE) || defined(_UNICODE)
return String(mHandle->path, mHandle->path + std::wcslen(mHandle->path));
#else
return String(mHandle->path);
#endif
}
/* --------------------------------------------------------------------------------------------
* Retrieve the name of the opened file.
*/
CSStr GetName() const
SQMOD_NODISCARD String GetName() const
{
Validate("retrieve name");
// Return the requested information
return mHandle->name;
#if defined(UNICODE) || defined(_UNICODE)
return String(mHandle->name, mHandle->name + std::wcslen(mHandle->name));
#else
return String(mHandle->name);
#endif
}
/* --------------------------------------------------------------------------------------------
* Retrieve the extension of the opened file.
*/
CSStr GetExtension() const
SQMOD_NODISCARD String GetExtension() const
{
Validate("retrieve extension");
// Return the requested information
return mHandle->extension != nullptr ? mHandle->extension : _SC("");
#if defined(UNICODE) || defined(_UNICODE)
return String(mHandle->extension, mHandle->extension + std::wcslen(mHandle->extension));
#else
return String(mHandle->name);
#endif
}
};

View File

@ -1,11 +1,9 @@
// ------------------------------------------------------------------------------------------------
#include "Library/System/Environment.hpp"
#include "Library/System/Env.hpp"
// ------------------------------------------------------------------------------------------------
#include <cctype>
#include <cstdlib>
#include <cstring>
#include <utility>
// ------------------------------------------------------------------------------------------------
#ifdef SQMOD_OS_WINDOWS
@ -35,7 +33,7 @@ namespace SqMod {
#endif // SQMOD_OS_WINDOWS
// ------------------------------------------------------------------------------------------------
void SysEnv::Get(Buffer & b, CCStr name, CCStr fallback)
void SysEnv::Get(Buffer & b, const char * name, const char * fallback)
{
// Make sure the requested variable name is valid
if (name && *name != 0)
@ -67,7 +65,7 @@ void SysEnv::Get(Buffer & b, CCStr name, CCStr fallback)
b.Advance(len);
#else
// Retrieve the pointer to the variable contents
CSStr val = getenv(name);
const SQChar * val = getenv(name);
// If the returned pointer is null then the variable doesn't exist
if (!val)
{
@ -86,7 +84,7 @@ void SysEnv::Get(Buffer & b, CCStr name, CCStr fallback)
}
// ------------------------------------------------------------------------------------------------
bool SysEnv::Has(CCStr name)
bool SysEnv::Has(const char * name)
{
#ifdef SQMOD_OS_WINDOWS
return (GetEnvironmentVariableA(name, nullptr, 0) > 0);
@ -106,7 +104,7 @@ bool SysEnv::Has(const String & name)
}
// ------------------------------------------------------------------------------------------------
Buffer SysEnv::Get(CCStr name, CCStr fallback)
Buffer SysEnv::Get(const char * name, const char * fallback)
{
// Allocate a moderately sized buffer
Buffer b(128);
@ -117,7 +115,7 @@ Buffer SysEnv::Get(CCStr name, CCStr fallback)
}
// ------------------------------------------------------------------------------------------------
bool SysEnv::Set(CCStr name, CCStr value)
bool SysEnv::Set(const char * name, const char * value)
{
#ifdef SQMOD_OS_WINDOWS
// Set the specified environment variable and return the result
@ -255,7 +253,7 @@ String SysEnv::OSVersion()
// Obtain a temporary buffer capable of holding the version string
Buffer b(128);
// The amount of data written to the buffer
Uint32 sz = 0;
uint32_t sz;
// Generate the version string with the received information
if (vi.szCSDVersion[0])
{
@ -347,7 +345,7 @@ String SysEnv::NodeName()
}
// ------------------------------------------------------------------------------------------------
Uint32 SysEnv::ProcessorCount()
uint32_t SysEnv::ProcessorCount()
{
#ifdef SQMOD_OS_WINDOWS
// Prepare the structure in which the system information is retrieved
@ -358,9 +356,9 @@ Uint32 SysEnv::ProcessorCount()
return si.dwNumberOfProcessors;
#elif defined(_SC_NPROCESSORS_ONLN)
// Attempt to obtain the number of processors available on the system
const Int32 count = sysconf(_SC_NPROCESSORS_ONLN);
const int32_t count = sysconf(_SC_NPROCESSORS_ONLN);
// Validate the result and return the appropriate value
return (count < 0) ? 1 : static_cast< Uint32 >(count);
return (count < 0) ? 1 : static_cast< uint32_t >(count);
#else
// Obviously at least one processor should be available
return 1;
@ -385,7 +383,7 @@ void SysEnv::TerminatePath(Buffer & b)
}
// ------------------------------------------------------------------------------------------------
void SysEnv::ExpandVars(Buffer & b, CCStr pos, CCStr end)
void SysEnv::ExpandVars(Buffer & b, const char * pos, const char * end)
{
// Let's have a string to store the extracted variable name and value
String var;
@ -398,7 +396,7 @@ void SysEnv::ExpandVars(Buffer & b, CCStr pos, CCStr end)
// Clear previous name, if any
var.clear();
// Where the name of the variable starts and where it ends
CCStr start = ++pos, stop = pos;
const char * start = ++pos, * stop = pos;
// Is this variable name enclosed within curly braces?
if (*start == '{')
{
@ -463,7 +461,7 @@ void SysEnv::ExpandVars(Buffer & b, CCStr pos, CCStr end)
}
// ------------------------------------------------------------------------------------------------
void SysEnv::ExpandPath(Buffer & b, CCStr pos, CCStr end)
void SysEnv::ExpandPath(Buffer & b, const char * pos, const char * end)
{
// Does the path even contain something to be expanded?
if (pos == end || *pos == '\0')
@ -492,7 +490,7 @@ void SysEnv::ExpandPath(Buffer & b, CCStr pos, CCStr end)
}
// ------------------------------------------------------------------------------------------------
void SysEnv::ExpandVars(Buffer & b, CCStr str)
void SysEnv::ExpandVars(Buffer & b, const char * str)
{
// Do we have anything to expand?
if (!str || *str == '\0')
@ -506,7 +504,7 @@ void SysEnv::ExpandVars(Buffer & b, CCStr str)
return;
}
// Calculate the size of the specified string
const Uint32 len = strlen(str);
const auto len = static_cast< uint32_t >(strlen(str));
// Forward the call to the internal function
ExpandVars(b, str, str + len);
}
@ -530,7 +528,7 @@ void SysEnv::ExpandVars(Buffer & b, const String & str)
}
// ------------------------------------------------------------------------------------------------
Buffer SysEnv::ExpandVars(CCStr str)
Buffer SysEnv::ExpandVars(const char * str)
{
// Do we have anything to expand?
if (!str || *str == '\0')
@ -538,7 +536,7 @@ Buffer SysEnv::ExpandVars(CCStr str)
return Buffer(); // Nothing to expand!
}
// Calculate the size of the specified string
const Uint32 len = strlen(str);
const auto len = static_cast< uint32_t >(strlen(str));
// Allocate a moderately sized buffer
Buffer b(len + 128);
// Forward the call to the internal function
@ -556,7 +554,7 @@ Buffer SysEnv::ExpandVars(const String & str)
return Buffer(); // Nothing to expand!
}
// Allocate a moderately sized buffer
Buffer b(str.size() + 128);
Buffer b(static_cast< uint32_t >(str.size() + 128));
// Forward the call to the internal function
ExpandVars(b, str.c_str(), str.c_str() + str.size());
// Return ownership of the buffer
@ -564,7 +562,7 @@ Buffer SysEnv::ExpandVars(const String & str)
}
// ------------------------------------------------------------------------------------------------
void SysEnv::ExpandPath(Buffer & b, CCStr path)
void SysEnv::ExpandPath(Buffer & b, const char * path)
{
// Do we have anything to expand?
if (!path || *path == '\0')
@ -578,7 +576,7 @@ void SysEnv::ExpandPath(Buffer & b, CCStr path)
return;
}
// Calculate the size of the specified string
const Uint32 len = strlen(path);
const auto len = static_cast< uint32_t >(strlen(path));
// Forward the call to the internal function
ExpandPath(b, path, path + len);
}
@ -602,7 +600,7 @@ void SysEnv::ExpandPath(Buffer & b, const String & path)
}
// ------------------------------------------------------------------------------------------------
Buffer SysEnv::ExpandPath(CCStr path)
Buffer SysEnv::ExpandPath(const char * path)
{
// Do we have anything to expand?
if (!path || *path == '\0')
@ -610,7 +608,7 @@ Buffer SysEnv::ExpandPath(CCStr path)
return Buffer(); // Nothing to expand!
}
// Calculate the size of the specified string
const Uint32 len = strlen(path);
const auto len = static_cast< uint32_t >(strlen(path));
// Allocate buffer capable of storing a full path
Buffer b(SQMOD_MAX_PATH);
// Forward the call to the internal function
@ -699,7 +697,7 @@ void SysEnv::HomeDir(Buffer & b)
if (SUCCEEDED(SHGetFolderPathA(nullptr, CSIDL_PROFILE, nullptr, 0, &b.Cursor())))
{
// Move the edit cursor to the end of the appended data
b.Advance(strlen(&b.Cursor()));
b.Advance(static_cast< uint32_t >(strlen(&b.Cursor())));
}
// Try the secondary method of retrieving the home directory
else if (Has("USERPROFILE"))
@ -821,9 +819,9 @@ void SysEnv::DataHomeDir(Buffer & b)
HomeDir(b);
// Use the home directory and append the ".local/share" sub folder
b.AppendS(".config/share");
#endif // SQMOD_OS_WINDOWS
// Make sure that the path is properly terminated
TerminatePath(b);
#endif // SQMOD_OS_WINDOWS
}
// ------------------------------------------------------------------------------------------------
@ -914,7 +912,7 @@ void SysEnv::TempDir(Buffer & b)
// Acquire a new buffer with a more appropriate capacity this time
b.Grow(len - b.Remaining() + 2);
// Attempt to retrieve the temporary directory one more time
len = GetTempPathA(b.Remaining(), &b.Cursor());
/*len = */GetTempPathA(b.Remaining(), &b.Cursor());
// ^ On failure the null terminator is included in the length
}
// Convert the acquired path to its long form
@ -1084,37 +1082,37 @@ Buffer SysEnv::NullDir()
}
// ------------------------------------------------------------------------------------------------
static bool SqEnv_Has(CCStr name)
static bool SqEnv_Has(const char * name)
{
return SysEnv::Has(name);
}
// ------------------------------------------------------------------------------------------------
static Object SqEnv_Get(CCStr name)
static Object SqEnv_Get(const char * name)
{
return BufferToStrObj(SysEnv::Get(name, nullptr));
}
// ------------------------------------------------------------------------------------------------
static Object SqEnv_GetOr(CCStr name, CCStr fallback)
static Object SqEnv_GetOr(const char * name, const char * fallback)
{
return BufferToStrObj(SysEnv::Get(name, fallback));
}
// ------------------------------------------------------------------------------------------------
static void SqEnv_Set(CCStr name, CCStr value)
static void SqEnv_Set(const char * name, const char * value)
{
SysEnv::Set(name, value);
}
// ------------------------------------------------------------------------------------------------
static Object SqEnv_ExpandVars(CCStr str)
static Object SqEnv_ExpandVars(const char * str)
{
return BufferToStrObj(SysEnv::ExpandVars(str));
}
// ------------------------------------------------------------------------------------------------
static Object SqEnv_ExpandPath(CCStr path)
static Object SqEnv_ExpandPath(const char * path)
{
return BufferToStrObj(SysEnv::ExpandPath(path));
}

View File

@ -1,8 +1,8 @@
#pragma once
// ------------------------------------------------------------------------------------------------
#include "Base/Shared.hpp"
#include "Base/Buffer.hpp"
#include "Core/Common.hpp"
#include "Core/Buffer.hpp"
// ------------------------------------------------------------------------------------------------
namespace SqMod {
@ -47,7 +47,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Returns true if an environment variable with the given name is defined.
*/
static bool Has(CCStr name);
static bool Has(const char * name);
/* --------------------------------------------------------------------------------------------
* Returns true if an environment variable with the given name is defined.
@ -58,12 +58,12 @@ public:
* Returns the value of the environment variable with the given name.
* If the environment variable is undefined, returns fallback value instead.
*/
static void Get(Buffer & b, CCStr name, CCStr fallback);
static void Get(Buffer & b, const char * name, const char * fallback);
/* --------------------------------------------------------------------------------------------
* Returns the value of the environment variable with the given name.
*/
static Buffer Get(CCStr name)
static Buffer Get(const char * name)
{
return Get(name, nullptr);
}
@ -80,13 +80,13 @@ public:
* Returns the value of the environment variable with the given name.
* If the environment variable is undefined, returns fallback value instead.
*/
static Buffer Get(CCStr name, CCStr fallback);
static Buffer Get(const char * name, const char * fallback);
/* --------------------------------------------------------------------------------------------
* Returns the value of the environment variable with the given name.
* If the environment variable is undefined, returns fallback value instead.
*/
static Buffer Get(CCStr name, const String & fallback)
static Buffer Get(const char * name, const String & fallback)
{
return Get(name, fallback.c_str());
}
@ -95,7 +95,7 @@ public:
* Returns the value of the environment variable with the given name.
* If the environment variable is undefined, returns fallback value instead.
*/
static Buffer Get(const String & name, CCStr fallback)
static Buffer Get(const String & name, const char * fallback)
{
return Get(name.c_str(), fallback);
}
@ -112,7 +112,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Sets the environment variable with the given name to the given value.
*/
static bool Set(CCStr name, CCStr value);
static bool Set(const char * name, const char * value);
/* --------------------------------------------------------------------------------------------
* Sets the environment variable with the given name to the given value.
@ -148,7 +148,7 @@ public:
* Returns the number of processors installed in the system. If the number of processors
* cannot be determined, returns 1.
*/
static Uint32 ProcessorCount();
static uint32_t ProcessorCount();
protected:
@ -160,19 +160,19 @@ protected:
/* --------------------------------------------------------------------------------------------
* Expands all environment variables contained in the string.
*/
static void ExpandVars(Buffer & b, CCStr pos, CCStr end);
static void ExpandVars(Buffer & b, const char * pos, const char * end);
/* --------------------------------------------------------------------------------------------
* Expands all environment variables contained in the path. Uses the Unix variable style.
*/
static void ExpandPath(Buffer & b, CCStr pos, CCStr end);
static void ExpandPath(Buffer & b, const char * pos, const char * end);
public:
/* --------------------------------------------------------------------------------------------
* Expands all environment variables contained in the string.
*/
static void ExpandVars(Buffer & b, CCStr str);
static void ExpandVars(Buffer & b, const char * str);
/* --------------------------------------------------------------------------------------------
* Expands all environment variables contained in the string.
@ -182,7 +182,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Expands all environment variables contained in the string.
*/
static Buffer ExpandVars(CCStr str);
static Buffer ExpandVars(const char * str);
/* --------------------------------------------------------------------------------------------
* Expands all environment variables contained in the string.
@ -192,7 +192,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Expands all environment variables contained in the path. Uses the Unix variable style.
*/
static void ExpandPath(Buffer & b, CCStr path);
static void ExpandPath(Buffer & b, const char * path);
/* --------------------------------------------------------------------------------------------
* Expands all environment variables contained in the path. Uses the Unix variable style.
@ -202,7 +202,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Expands all environment variables contained in the path. Uses the Unix variable style.
*/
static Buffer ExpandPath(CCStr path);
static Buffer ExpandPath(const char * path);
/* --------------------------------------------------------------------------------------------
* Expands all environment variables contained in the path. Uses the Unix variable style.

View File

@ -1,13 +1,13 @@
// ------------------------------------------------------------------------------------------------
#include "Library/System/Path.hpp"
#include "Library/System/Environment.hpp"
#include "Library/System/Env.hpp"
// ------------------------------------------------------------------------------------------------
#include <cctype>
#include <cstdlib>
#include <cstring>
#include <limits>
#include <utility>
// ------------------------------------------------------------------------------------------------
#include <sqratConst.h>
// ------------------------------------------------------------------------------------------------
#ifdef SQMOD_OS_WINDOWS
@ -34,10 +34,10 @@ namespace SqMod {
#endif // SQMOD_OS_WINDOWS
// ------------------------------------------------------------------------------------------------
SQMODE_DECL_TYPENAME(Typename, _SC("SqSysPath"))
SQMOD_DECL_TYPENAME(Typename, _SC("SqSysPath"))
// ------------------------------------------------------------------------------------------------
Buffer GetRealFilePath(CSStr path)
Buffer GetRealFilePath(const SQChar * path)
{
// Make sure the specified path is valid
if (!path || *path == '\0')
@ -49,14 +49,14 @@ Buffer GetRealFilePath(CSStr path)
#ifdef SQMOD_OS_WINDOWS
// Attempt to obtain the full path to the file
DWORD ret = ::GetFullPathName(path, b.Size< PChar >(), b.Get< PChar >(), nullptr);
DWORD ret = ::GetFullPathNameA(path, b.Size< char >(), b.Get< char >(), nullptr);
// Should we allocate a bigger buffer?
if (ret > b.Size< PChar >())
{
// Grab a bigger buffer
b.Adjust(ret);
// Grab the path again
ret = GetFullPathName(path, b.Size< PChar >(), b.Get< PChar >(), nullptr);
ret = GetFullPathNameA(path, b.Size< char >(), b.Get< char >(), nullptr);
}
// Did we fail to obtain a path?
if (ret == 0 && ::GetLastError() != 0)
@ -100,7 +100,7 @@ SysPath::SysPath(bool absolute)
}
// ------------------------------------------------------------------------------------------------
SysPath::SysPath(CSStr path)
SysPath::SysPath(const SQChar * path)
: m_Dirs()
, m_Name()
, m_Drive(0)
@ -110,7 +110,7 @@ SysPath::SysPath(CSStr path)
}
// ------------------------------------------------------------------------------------------------
SysPath::SysPath(CSStr path, Int32 style)
SysPath::SysPath(const SQChar * path, int32_t style)
: m_Dirs()
, m_Name()
, m_Drive(0)
@ -120,7 +120,7 @@ SysPath::SysPath(CSStr path, Int32 style)
}
// ------------------------------------------------------------------------------------------------
SysPath::SysPath(CSStr path, Style style)
SysPath::SysPath(const SQChar * path, Style style)
: m_Dirs()
, m_Name()
, m_Drive(0)
@ -130,7 +130,7 @@ SysPath::SysPath(CSStr path, Style style)
}
// ------------------------------------------------------------------------------------------------
SysPath::SysPath(const Buffer & path, Int32 size)
SysPath::SysPath(const Buffer & path, int32_t size)
: m_Dirs()
, m_Name()
, m_Drive(0)
@ -140,7 +140,7 @@ SysPath::SysPath(const Buffer & path, Int32 size)
}
// ------------------------------------------------------------------------------------------------
SysPath::SysPath(const Buffer & path, Style style, Int32 size)
SysPath::SysPath(const Buffer & path, Style style, int32_t size)
: m_Dirs()
, m_Name()
, m_Drive(0)
@ -170,7 +170,7 @@ SysPath::SysPath(const String & path, Style style)
}
// ------------------------------------------------------------------------------------------------
SysPath::SysPath(const SysPath & parent, CSStr name)
SysPath::SysPath(const SysPath & parent, const SQChar * name)
: m_Dirs(parent.m_Dirs)
, m_Name(name ? name : "")
, m_Drive(parent.m_Drive)
@ -180,7 +180,7 @@ SysPath::SysPath(const SysPath & parent, CSStr name)
}
// ------------------------------------------------------------------------------------------------
SysPath::SysPath(const SysPath & parent, const String & name)
SysPath::SysPath(const SysPath & parent, const String & name) // NOLINT(modernize-pass-by-value)
: m_Dirs(parent.m_Dirs)
, m_Name(name)
, m_Drive(parent.m_Drive)
@ -201,63 +201,7 @@ SysPath::SysPath(const SysPath & parent, const SysPath & relative)
}
// ------------------------------------------------------------------------------------------------
SysPath::SysPath(const SysPath & o)
: m_Dirs(o.m_Dirs)
, m_Name(o.m_Name)
, m_Drive(o.m_Drive)
, m_Absolute(o.m_Absolute)
{
/* ... */
}
// ------------------------------------------------------------------------------------------------
SysPath::SysPath(SysPath && o)
: m_Dirs(std::move(o.m_Dirs))
, m_Name(std::move(o.m_Name))
, m_Drive(o.m_Drive)
, m_Absolute(o.m_Absolute)
{
/* ... */
}
// ------------------------------------------------------------------------------------------------
SysPath::~SysPath()
{
/* ... */
}
// ------------------------------------------------------------------------------------------------
SysPath & SysPath::operator = (const SysPath & o)
{
// Prevent self assignment
if (this != &o)
{
m_Dirs = o.m_Dirs;
m_Name = o.m_Name;
m_Drive = o.m_Drive;
m_Absolute = o.m_Absolute;
}
return *this;
}
// ------------------------------------------------------------------------------------------------
SysPath & SysPath::operator = (SysPath && o)
{
// Prevent self assignment
if (this != &o)
{
m_Dirs = std::move(o.m_Dirs);
m_Name = std::move(o.m_Name);
m_Drive = o.m_Drive;
m_Absolute = o.m_Absolute;
}
return *this;
}
// ------------------------------------------------------------------------------------------------
SysPath & SysPath::operator = (CSStr path)
SysPath & SysPath::operator = (const SQChar * path)
{
Assign(path);
return *this;
@ -290,7 +234,7 @@ SysPath::operator bool () const
}
// ------------------------------------------------------------------------------------------------
const String & SysPath::operator [] (Uint32 n) const
const String & SysPath::operator [] (uint32_t n) const
{
// Is this within the bounds of the directory list?
if (n < m_Dirs.size())
@ -305,7 +249,7 @@ const String & SysPath::operator [] (Uint32 n) const
}
// ------------------------------------------------------------------------------------------------
Int32 SysPath::Cmp(const SysPath & o) const
int32_t SysPath::Cmp(const SysPath & o) const
{
if (*this == o)
return 0;
@ -340,7 +284,7 @@ void SysPath::Clear()
}
// ------------------------------------------------------------------------------------------------
SysPath & SysPath::Assign(CSStr path)
SysPath & SysPath::Assign(const SQChar * path)
{
// Is the specified path valid?
if (!path || *path == '\0')
@ -361,13 +305,13 @@ SysPath & SysPath::Assign(CSStr path)
}
// ------------------------------------------------------------------------------------------------
SysPath & SysPath::Assign(CSStr path, Int32 style)
SysPath & SysPath::Assign(const SQChar * path, int32_t style)
{
return Assign(path, static_cast< Style >(style));
}
// ------------------------------------------------------------------------------------------------
SysPath & SysPath::Assign(CSStr path, Style style)
SysPath & SysPath::Assign(const SQChar * path, Style style)
{
// Is the specified path valid?
if (!path || *path == '\0')
@ -383,7 +327,7 @@ SysPath & SysPath::Assign(CSStr path, Style style)
case Style::Unix:
ParseUnix(path, path + strlen(path));
break;
case Style::Windows:
case Style::Windows: // NOLINT(bugprone-branch-clone)
ParseWindows(path, path + strlen(path));
break;
case Style::Native:
@ -399,8 +343,6 @@ SysPath & SysPath::Assign(CSStr path, Style style)
case Style::Dynamic:
ParseDynamic(path, path + strlen(path));
break;
default:
STHROWF("Unknown system path style");
}
}
// Allow chaining
@ -408,7 +350,7 @@ SysPath & SysPath::Assign(CSStr path, Style style)
}
// ------------------------------------------------------------------------------------------------
SysPath & SysPath::Assign(const Buffer & path, Int32 size)
SysPath & SysPath::Assign(const Buffer & path, int32_t size)
{
// Is the specified path valid?
if (!path)
@ -424,7 +366,7 @@ SysPath & SysPath::Assign(const Buffer & path, Int32 size)
ParseUnix(path.Data(), &path.Cursor());
#endif // SQMOD_OS_WINDOWS
}
else if (static_cast< Uint32 >(size) < path.Capacity())
else if (static_cast< uint32_t >(size) < path.Capacity())
{
#ifdef SQMOD_OS_WINDOWS
ParseWindows(path.Data(), path.Data() + size);
@ -441,7 +383,7 @@ SysPath & SysPath::Assign(const Buffer & path, Int32 size)
}
// ------------------------------------------------------------------------------------------------
SysPath & SysPath::Assign(const Buffer & path, Style style, Int32 size)
SysPath & SysPath::Assign(const Buffer & path, Style style, int32_t size)
{
// Is the specified path valid?
if (!path)
@ -457,7 +399,7 @@ SysPath & SysPath::Assign(const Buffer & path, Style style, Int32 size)
case Style::Unix:
ParseUnix(path.Data(), &path.Cursor());
break;
case Style::Windows:
case Style::Windows: // NOLINT(bugprone-branch-clone)
ParseWindows(path.Data(), &path.Cursor());
break;
case Style::Native:
@ -473,11 +415,9 @@ SysPath & SysPath::Assign(const Buffer & path, Style style, Int32 size)
case Style::Dynamic:
ParseDynamic(path.Data(), &path.Cursor());
break;
default:
STHROWF("Unknown system path style");
}
}
else if (static_cast< Uint32 >(size) < path.Capacity())
else if (static_cast< uint32_t >(size) < path.Capacity())
{
// Identify which style was requested
switch (style)
@ -485,7 +425,7 @@ SysPath & SysPath::Assign(const Buffer & path, Style style, Int32 size)
case Style::Unix:
ParseUnix(path.Data(), path.Data() + size);
break;
case Style::Windows:
case Style::Windows: // NOLINT(bugprone-branch-clone)
ParseWindows(path.Data(), path.Data() + size);
break;
case Style::Native:
@ -501,8 +441,6 @@ SysPath & SysPath::Assign(const Buffer & path, Style style, Int32 size)
case Style::Dynamic:
ParseDynamic(path.Data(), path.Data() + size);
break;
default:
STHROWF("Unknown system path style");
}
}
else
@ -551,7 +489,7 @@ SysPath & SysPath::Assign(const String & path, Style style)
case Style::Unix:
ParseUnix(path.data(), path.data() + path.size());
break;
case Style::Windows:
case Style::Windows: // NOLINT(bugprone-branch-clone)
ParseWindows(path.data(), path.data() + path.size());
break;
case Style::Native:
@ -567,8 +505,6 @@ SysPath & SysPath::Assign(const String & path, Style style)
case Style::Dynamic:
ParseDynamic(path.data(), path.data() + path.size());
break;
default:
STHROWF("Unknown system path style");
}
}
// Allow chaining
@ -576,7 +512,7 @@ SysPath & SysPath::Assign(const String & path, Style style)
}
// ------------------------------------------------------------------------------------------------
SysPath & SysPath::Assign(const SysPath & parent, CSStr name)
SysPath & SysPath::Assign(const SysPath & parent, const SQChar * name)
{
// Copy the parent values
*this = parent;
@ -627,7 +563,7 @@ SysPath & SysPath::Assign(SysPath && path)
}
// ------------------------------------------------------------------------------------------------
SysPath & SysPath::AssignDir(CSStr path)
SysPath & SysPath::AssignDir(const SQChar * path)
{
// Assign the specified path
Assign(path);
@ -636,7 +572,7 @@ SysPath & SysPath::AssignDir(CSStr path)
}
// ------------------------------------------------------------------------------------------------
SysPath & SysPath::AssignDir(CSStr path, Int32 style)
SysPath & SysPath::AssignDir(const SQChar * path, int32_t style)
{
// Assign the specified path
Assign(path, style);
@ -645,7 +581,7 @@ SysPath & SysPath::AssignDir(CSStr path, Int32 style)
}
// ------------------------------------------------------------------------------------------------
SysPath & SysPath::AssignDir(CSStr path, Style style)
SysPath & SysPath::AssignDir(const SQChar * path, Style style)
{
// Assign the specified path
Assign(path, style);
@ -654,7 +590,7 @@ SysPath & SysPath::AssignDir(CSStr path, Style style)
}
// ------------------------------------------------------------------------------------------------
SysPath & SysPath::AssignDir(const Buffer & path, Int32 size)
SysPath & SysPath::AssignDir(const Buffer & path, int32_t size)
{
// Assign the specified path
Assign(path, size);
@ -663,7 +599,7 @@ SysPath & SysPath::AssignDir(const Buffer & path, Int32 size)
}
// ------------------------------------------------------------------------------------------------
SysPath & SysPath::AssignDir(const Buffer & path, Style style, Int32 size)
SysPath & SysPath::AssignDir(const Buffer & path, Style style, int32_t size)
{
// Assign the specified path
Assign(path, style, size);
@ -718,13 +654,13 @@ Buffer SysPath::ToBuffer(Style style) const
}
// ------------------------------------------------------------------------------------------------
Object SysPath::ToStr(Int32 style) const
Object SysPath::ToStr(int32_t style) const
{
return BufferToStrObj(ToBuffer(static_cast< Style >(style)));
}
// ------------------------------------------------------------------------------------------------
void SysPath::FromString(CSStr path)
void SysPath::FromString(const SQChar * path)
{
Assign(path);
}
@ -776,7 +712,7 @@ SysPath & SysPath::MakeParent()
else
{
// Are we already referencing a parent?
if (m_Dirs.back().compare("..") == 0)
if (m_Dirs.back().compare("..") == 0) // NOLINT(readability-string-compare)
{
// Then reference the parent of that parent
m_Dirs.emplace_back("..");
@ -885,31 +821,31 @@ SysPath & SysPath::Append(SysPath && path)
}
// ------------------------------------------------------------------------------------------------
SysPath & SysPath::Append(CSStr path)
SysPath & SysPath::Append(const SQChar * path)
{
return Append(SysPath(path));
}
// ------------------------------------------------------------------------------------------------
SysPath & SysPath::Append(CSStr path, Int32 style)
SysPath & SysPath::Append(const SQChar * path, int32_t style)
{
return Append(SysPath(path, style));
}
// ------------------------------------------------------------------------------------------------
SysPath & SysPath::Append(CSStr path, Style style)
SysPath & SysPath::Append(const SQChar * path, Style style)
{
return Append(SysPath(path, style));
}
// ------------------------------------------------------------------------------------------------
SysPath & SysPath::Append(const Buffer & path, Int32 size)
SysPath & SysPath::Append(const Buffer & path, int32_t size)
{
return Append(SysPath(path, size));
}
// ------------------------------------------------------------------------------------------------
SysPath & SysPath::Append(const Buffer & path, Style style, Int32 size)
SysPath & SysPath::Append(const Buffer & path, Style style, int32_t size)
{
return Append(SysPath(path, style, size));
}
@ -927,7 +863,7 @@ SysPath & SysPath::Append(const String & path, Style style)
}
// ------------------------------------------------------------------------------------------------
const String & SysPath::Directory(Uint32 n) const
const String & SysPath::Directory(uint32_t n) const
{
// Is this within the bounds of the directory list?
if (n < m_Dirs.size())
@ -942,7 +878,7 @@ const String & SysPath::Directory(Uint32 n) const
}
// ------------------------------------------------------------------------------------------------
SysPath & SysPath::Push(CSStr dir)
SysPath & SysPath::Push(const SQChar * dir)
{
// Is the specified directory valid?
if (dir && *dir != 0)
@ -957,7 +893,7 @@ SysPath & SysPath::Push(CSStr dir)
SysPath & SysPath::Push(const String & dir)
{
// Is the specified directory valid?
if (!dir.empty() && dir.compare(".") != 0)
if (!dir.empty() && dir.compare(".") != 0) // NOLINT(readability-string-compare)
{
Push(String(dir));
}
@ -969,13 +905,13 @@ SysPath & SysPath::Push(const String & dir)
SysPath & SysPath::Push(String && dir)
{
// Is the specified directory valid?
if (!dir.empty() && dir.compare(".") != 0)
if (!dir.empty() && dir.compare(".") != 0) // NOLINT(readability-string-compare)
{
// Does it refer to a parent directory?
if (dir.compare("..") == 0)
if (dir.compare("..") == 0) // NOLINT(readability-string-compare)
{
// Is our last directory already a reference to a parent?
if (!m_Dirs.empty() && m_Dirs.back().compare("..") != 0)
if (!m_Dirs.empty() && m_Dirs.back().compare("..") != 0) // NOLINT(readability-string-compare)
{
m_Dirs.pop_back();
}
@ -1022,7 +958,7 @@ SysPath & SysPath::PopFront()
}
// ------------------------------------------------------------------------------------------------
SysPath & SysPath::SetFilename(CSStr name)
SysPath & SysPath::SetFilename(const SQChar * name)
{
// Is the file name even valid?
if (name)
@ -1052,7 +988,7 @@ SysPath & SysPath::SetFilename(String && name)
}
// ------------------------------------------------------------------------------------------------
SysPath & SysPath::SetBasename(CSStr name)
SysPath & SysPath::SetBasename(const SQChar * name)
{
// Is the file name even valid?
if (name)
@ -1128,7 +1064,7 @@ String SysPath::GetBasename() const
}
// ------------------------------------------------------------------------------------------------
SysPath & SysPath::SetExtension(CSStr ext)
SysPath & SysPath::SetExtension(const SQChar * ext)
{
// Attempt to find the last dot in the file name
const String::size_type pos = m_Name.rfind('.');
@ -1185,7 +1121,7 @@ String SysPath::GetExtension() const
}
// ------------------------------------------------------------------------------------------------
CSStr SysPath::GetExtensionC() const
const SQChar * SysPath::GetExtensionC() const
{
// Attempt to find the last dot in the file name
const String::size_type pos = m_Name.rfind('.');
@ -1234,7 +1170,7 @@ SysPath & SysPath::Resolve(const SysPath & path)
}
// ------------------------------------------------------------------------------------------------
void SysPath::ParseUnix(CSStr pos, CSStr end)
void SysPath::ParseUnix(const SQChar * pos, const SQChar * end)
{
// Clear previous path information
Clear();
@ -1271,7 +1207,7 @@ void SysPath::ParseUnix(CSStr pos, CSStr end)
}
}
// Make another iterator to slice directory names in one go
CSStr itr = pos;
const SQChar * itr = pos;
// Extract the remaining directories from the specified path
while (itr != end)
{
@ -1299,7 +1235,7 @@ void SysPath::ParseUnix(CSStr pos, CSStr end)
}
// ------------------------------------------------------------------------------------------------
void SysPath::ParseWindows(CSStr pos, CSStr end)
void SysPath::ParseWindows(const SQChar * pos, const SQChar * end)
{
// Clear previous path information
Clear();
@ -1354,7 +1290,7 @@ void SysPath::ParseWindows(CSStr pos, CSStr end)
return;
}
// Make another iterator to slice directory names in one go
CSStr itr = pos;
const SQChar * itr = pos;
// Extract the remaining directories from the specified path
while (itr != end)
{
@ -1382,7 +1318,7 @@ void SysPath::ParseWindows(CSStr pos, CSStr end)
}
// ------------------------------------------------------------------------------------------------
void SysPath::ParseDynamic(CSStr pos, CSStr end)
void SysPath::ParseDynamic(const SQChar * pos, const SQChar * end)
{
// Clear previous path information
Clear();
@ -1443,7 +1379,7 @@ void SysPath::ParseDynamic(CSStr pos, CSStr end)
}
#endif // SQMOD_OS_WINDOWS
// Make another iterator to slice directory names in one go
CSStr itr = pos;
const SQChar * itr = pos;
// Extract the remaining directories from the specified path
while (itr != end)
{
@ -1471,14 +1407,14 @@ void SysPath::ParseDynamic(CSStr pos, CSStr end)
}
// ------------------------------------------------------------------------------------------------
void SysPath::ParseGuess(CSStr pos, CSStr end)
void SysPath::ParseGuess(const SQChar * pos, const SQChar * end)
{
// Scan for forward slash
const bool has_fwslash = (strchr(pos, '/') != NULL);
const bool has_bwslash = (strchr(pos, '\\') != NULL);
const bool has_fwslash = (strchr(pos, '/') != nullptr);
const bool has_bwslash = (strchr(pos, '\\') != nullptr);
// Does it contain both forward and backward slashes?
if (has_fwslash && has_bwslash)
{
{ // NOLINT(bugprone-branch-clone)
ParseDynamic(pos, end);
}
// Does it contain the forward slash?
@ -1488,7 +1424,7 @@ void SysPath::ParseGuess(CSStr pos, CSStr end)
}
// Does it contain the backward slash?
else if (has_bwslash)
{
{ // NOLINT(bugprone-branch-clone)
ParseWindows(pos, end);
}
// Does it contain a drive letter?
@ -1518,14 +1454,14 @@ Buffer SysPath::BuildUnix() const
for (const auto & dir : m_Dirs)
{
// Append the name
b.AppendS(dir.c_str(), dir.size());
b.AppendS(dir.c_str(), static_cast< uint32_t >(dir.size()));
// Separate from next
b.Push('/');
}
// Is there a file name to add?
if (!m_Name.empty())
{
b.AppendS(m_Name.c_str(), m_Name.size());
b.AppendS(m_Name.c_str(), static_cast< uint32_t >(m_Name.size()));
}
// Make sure the string is null terminated
b.Cursor() = '\0';
@ -1558,14 +1494,14 @@ Buffer SysPath::BuildWindows() const
for (const auto & dir : m_Dirs)
{
// Append the name
b.AppendS(dir.c_str(), dir.size());
b.AppendS(dir.c_str(), static_cast< uint32_t >(dir.size()));
// Separate from next
b.Push('\\');
}
// Is there a file name to add?
if (!m_Name.empty())
{
b.AppendS(m_Name.c_str(), m_Name.size());
b.AppendS(m_Name.c_str(), static_cast< uint32_t >(m_Name.size()));
}
// Make sure the string is null terminated
b.Cursor() = '\0';
@ -1574,19 +1510,19 @@ Buffer SysPath::BuildWindows() const
}
// ------------------------------------------------------------------------------------------------
SysPath SysPath::ForDirectory(CSStr path)
SysPath SysPath::ForDirectory(const SQChar * path)
{
return SysPath(path).MakeDirectory();
}
// ------------------------------------------------------------------------------------------------
SysPath SysPath::ForDirectory(CSStr path, Int32 style)
SysPath SysPath::ForDirectory(const SQChar * path, int32_t style)
{
return SysPath(path, style).MakeDirectory();
}
// ------------------------------------------------------------------------------------------------
SysPath SysPath::ForDirectory(CSStr path, Style style)
SysPath SysPath::ForDirectory(const SQChar * path, Style style)
{
return SysPath(path, style).MakeDirectory();
}
@ -1604,7 +1540,7 @@ SysPath SysPath::ForDirectory(const String & path, Style style)
}
// ------------------------------------------------------------------------------------------------
SysPath SysPath::Expand(CSStr path)
SysPath SysPath::Expand(const SQChar * path)
{
return SysPath(SysEnv::ExpandPath(path));
}
@ -1670,43 +1606,43 @@ SysPath SysPath::Null()
}
// ------------------------------------------------------------------------------------------------
SysPath SysPath::Real(CSStr path)
SysPath SysPath::Real(const SQChar * path)
{
return SysPath(GetRealFilePath(path));
}
// ------------------------------------------------------------------------------------------------
SysPath SysPath::With(const SysPath & parent, CSStr name)
SysPath SysPath::With(const SysPath & parent, const SQChar * name)
{
return SysPath(parent, name);
}
// ------------------------------------------------------------------------------------------------
SysPath SysPath::MakeUnix(CSStr path)
SysPath SysPath::MakeUnix(const SQChar * path)
{
return SysPath(path, Style::Unix);
}
// ------------------------------------------------------------------------------------------------
SysPath SysPath::MakeWindows(CSStr path)
SysPath SysPath::MakeWindows(const SQChar * path)
{
return SysPath(path, Style::Windows);
}
// ------------------------------------------------------------------------------------------------
SysPath SysPath::MakeNative(CSStr path)
SysPath SysPath::MakeNative(const SQChar * path)
{
return SysPath(path, Style::Native);
}
// ------------------------------------------------------------------------------------------------
SysPath SysPath::MakeGuess(CSStr path)
SysPath SysPath::MakeGuess(const SQChar * path)
{
return SysPath(path, Style::Guess);
}
// ------------------------------------------------------------------------------------------------
SysPath SysPath::MakeDynamic(CSStr path)
SysPath SysPath::MakeDynamic(const SQChar * path)
{
return SysPath(path, Style::Dynamic);
}
@ -1725,8 +1661,8 @@ String SysPath::NormalizePath(SQInteger s, StackStrF & val)
return String();
}
// Turn it into a string that we can edit
String str(val.mPtr, val.mLen);
// Replace all occurences of the specified character
String str(val.mPtr, static_cast< size_t >(val.mLen));
// Replace all occurrences of the specified character
for (String::reference c : str)
{
if (c == '/' || c == '\\')
@ -1744,8 +1680,8 @@ void Register_SysPath(HSQUIRRELVM vm)
Class< SysPath >(vm, Typename::Str)
// Constructors
.Ctor()
.Ctor< CSStr >()
.Ctor< CSStr, Int32 >()
.Ctor< const SQChar * >()
.Ctor< const SQChar *, int32_t >()
// Meta-methods
.SquirrelFunc(_SC("_typename"), &Typename::Fn)
.Func(_SC("_tostring"), &SysPath::ToString)
@ -1779,29 +1715,29 @@ void Register_SysPath(HSQUIRRELVM vm)
.Func(_SC("MakeParent"), &SysPath::MakeParent)
.Func(_SC("Dir"), &SysPath::Directory)
.Func(_SC("Directory"), &SysPath::Directory)
.Func< SysPath & (SysPath::*)(CSStr) >(_SC("Push"), &SysPath::Push)
.Func< SysPath & (SysPath::*)(const SQChar *) >(_SC("Push"), &SysPath::Push)
.Func(_SC("PopBack"), &SysPath::PopBack)
.Func(_SC("PopFront"), &SysPath::PopFront)
.Func< SysPath & (SysPath::*)(CSStr) >(_SC("SetFilename"), &SysPath::SetFilename)
.Func< SysPath & (SysPath::*)(const SQChar *) >(_SC("SetFilename"), &SysPath::SetFilename)
.Func(_SC("GetFilename"), &SysPath::GetFilename)
.Func< SysPath & (SysPath::*)(CSStr) >(_SC("SetBasename"), &SysPath::SetBasename)
.Func< SysPath & (SysPath::*)(const SQChar *) >(_SC("SetBasename"), &SysPath::SetBasename)
.Func(_SC("GetBasename"), &SysPath::GetBasename)
.Func< SysPath & (SysPath::*)(CSStr) >(_SC("SetExtension"), &SysPath::SetExtension)
.Func< SysPath & (SysPath::*)(const SQChar *) >(_SC("SetExtension"), &SysPath::SetExtension)
.Func(_SC("GetExtension"), &SysPath::GetExtension)
.Func(_SC("Resolve"), &SysPath::Resolve)
// Member Overloads
.Overload< SysPath & (SysPath::*)(CSStr) >(_SC("Assign"), &SysPath::Assign)
.Overload< SysPath & (SysPath::*)(CSStr, Int32) >(_SC("Assign"), &SysPath::Assign)
.Overload< SysPath & (SysPath::*)(CSStr) >(_SC("AssignDir"), &SysPath::AssignDir)
.Overload< SysPath & (SysPath::*)(CSStr, Int32) >(_SC("AssignDir"), &SysPath::AssignDir)
.Overload< SysPath & (SysPath::*)(CSStr) >(_SC("Append"), &SysPath::Append)
.Overload< SysPath & (SysPath::*)(CSStr, Int32) >(_SC("Append"), &SysPath::Append)
.Overload< SysPath & (SysPath::*)(const SQChar *) >(_SC("Assign"), &SysPath::Assign)
.Overload< SysPath & (SysPath::*)(const SQChar *, int32_t) >(_SC("Assign"), &SysPath::Assign)
.Overload< SysPath & (SysPath::*)(const SQChar *) >(_SC("AssignDir"), &SysPath::AssignDir)
.Overload< SysPath & (SysPath::*)(const SQChar *, int32_t) >(_SC("AssignDir"), &SysPath::AssignDir)
.Overload< SysPath & (SysPath::*)(const SQChar *) >(_SC("Append"), &SysPath::Append)
.Overload< SysPath & (SysPath::*)(const SQChar *, int32_t) >(_SC("Append"), &SysPath::Append)
.Overload< SysPath & (SysPath::*)(void) >(_SC("MakeAbsolute"), &SysPath::MakeAbsolute)
.Overload< SysPath & (SysPath::*)(const SysPath &) >(_SC("MakeAbsolute"), &SysPath::MakeAbsolute)
// Static Functions
.StaticFunc(_SC("Separator"), &SysPath::Separator)
.StaticFunc(_SC("PathSeparator"), &SysPath::PathSeparator)
.StaticFunc< SysPath (*)(CSStr) >(_SC("Expand"), &SysPath::Expand)
.StaticFunc< SysPath (*)(const SQChar *) >(_SC("Expand"), &SysPath::Expand)
.StaticFunc(_SC("Home"), &SysPath::Home)
.StaticFunc(_SC("ConfigHome"), &SysPath::ConfigHome)
.StaticFunc(_SC("DataHome"), &SysPath::DataHome)
@ -1822,18 +1758,18 @@ void Register_SysPath(HSQUIRRELVM vm)
.StaticFunc(_SC("Dynamic"), &SysPath::MakeDynamic)
.StaticFmtFunc(_SC("Normalize"), &SysPath::NormalizePath)
// Static Overloads
.StaticOverload< SysPath (*)(CSStr) >(_SC("ForDir"), &SysPath::ForDirectory)
.StaticOverload< SysPath (*)(CSStr, Int32) >(_SC("ForDir"), &SysPath::ForDirectory)
.StaticOverload< SysPath (*)(CSStr) >(_SC("ForDirectory"), &SysPath::ForDirectory)
.StaticOverload< SysPath (*)(CSStr, Int32) >(_SC("ForDirectory"), &SysPath::ForDirectory)
.StaticOverload< SysPath (*)(const SQChar *) >(_SC("ForDir"), &SysPath::ForDirectory)
.StaticOverload< SysPath (*)(const SQChar *, int32_t) >(_SC("ForDir"), &SysPath::ForDirectory)
.StaticOverload< SysPath (*)(const SQChar *) >(_SC("ForDirectory"), &SysPath::ForDirectory)
.StaticOverload< SysPath (*)(const SQChar *, int32_t) >(_SC("ForDirectory"), &SysPath::ForDirectory)
);
ConstTable(vm).Enum(_SC("SqSysPathStyle"), Enumeration(vm)
.Const(_SC("Unix"), static_cast< Int32 >(SysPath::Style::Unix))
.Const(_SC("Windows"), static_cast< Int32 >(SysPath::Style::Windows))
.Const(_SC("Native"), static_cast< Int32 >(SysPath::Style::Native))
.Const(_SC("Guess"), static_cast< Int32 >(SysPath::Style::Guess))
.Const(_SC("Dynamic"), static_cast< Int32 >(SysPath::Style::Dynamic))
.Const(_SC("Unix"), static_cast< int32_t >(SysPath::Style::Unix))
.Const(_SC("Windows"), static_cast< int32_t >(SysPath::Style::Windows))
.Const(_SC("Native"), static_cast< int32_t >(SysPath::Style::Native))
.Const(_SC("Guess"), static_cast< int32_t >(SysPath::Style::Guess))
.Const(_SC("Dynamic"), static_cast< int32_t >(SysPath::Style::Dynamic))
);
}

View File

@ -1,7 +1,7 @@
#pragma once
// ------------------------------------------------------------------------------------------------
#include "Base/Shared.hpp"
#include "Core/Common.hpp"
// ------------------------------------------------------------------------------------------------
#include <vector>
@ -12,7 +12,7 @@ namespace SqMod {
/* ------------------------------------------------------------------------------------------------
* Retrieve the full path of file.
*/
Buffer GetRealFilePath(CSStr path);
Buffer GetRealFilePath(const SQChar * path);
/* ------------------------------------------------------------------------------------------------
* This class represents filesystem paths in a platform-independent manner.
@ -44,37 +44,37 @@ public:
/* --------------------------------------------------------------------------------------------
* Creates an empty absolute or relative path.
*/
SysPath(bool absolute);
explicit SysPath(bool absolute);
/* --------------------------------------------------------------------------------------------
* Creates a path in native format from a string.
*/
SysPath(CSStr path);
explicit SysPath(const SQChar * path);
/* --------------------------------------------------------------------------------------------
* Creates a path from a string.
*/
SysPath(CSStr path, Int32 style);
SysPath(const SQChar * path, int32_t style);
/* --------------------------------------------------------------------------------------------
* Creates a path from a string.
*/
SysPath(CSStr path, Style style);
SysPath(const SQChar * path, Style style);
/* --------------------------------------------------------------------------------------------
* Creates a path in native format from a string.
*/
SysPath(const Buffer & path, Int32 size = -1);
explicit SysPath(const Buffer & path, int32_t size = -1);
/* --------------------------------------------------------------------------------------------
* Creates a path from a string.
*/
SysPath(const Buffer & path, Style style, Int32 size = -1);
SysPath(const Buffer & path, Style style, int32_t size = -1);
/* --------------------------------------------------------------------------------------------
* Creates a path in native format from a string.
*/
SysPath(const String & path);
explicit SysPath(const String & path);
/* --------------------------------------------------------------------------------------------
* Creates a path from a string.
@ -85,7 +85,7 @@ public:
* Creates a path from a parent path and a file name. The parent path is expected to reference
* a directory.
*/
SysPath(const SysPath & parent, CSStr name);
SysPath(const SysPath & parent, const SQChar * name);
/* --------------------------------------------------------------------------------------------
* Creates a path from a parent path and a file name. The parent path is expected to reference
@ -102,32 +102,32 @@ public:
/* --------------------------------------------------------------------------------------------
* Copy constructor.
*/
SysPath(const SysPath & o);
SysPath(const SysPath & o) = default;
/* --------------------------------------------------------------------------------------------
* Move constructor.
*/
SysPath(SysPath && o);
SysPath(SysPath && o) noexcept = default;
/* --------------------------------------------------------------------------------------------
* Destructor.
*/
~SysPath();
~SysPath() = default;
/* --------------------------------------------------------------------------------------------
* Copy assignment operator.
*/
SysPath & operator = (const SysPath & o);
SysPath & operator = (const SysPath & o) = default;
/* --------------------------------------------------------------------------------------------
* Move assignment operator.
*/
SysPath & operator = (SysPath && o);
SysPath & operator = (SysPath && o) noexcept = default;
/* --------------------------------------------------------------------------------------------
* Assigns a string containing a path in native format.
*/
SysPath & operator = (CSStr path);
SysPath & operator = (const SQChar * path);
/* --------------------------------------------------------------------------------------------
* Assigns a string containing a path in native format.
@ -147,22 +147,22 @@ public:
/* --------------------------------------------------------------------------------------------
* Implicit conversion to boolean operator.
*/
operator bool () const;
operator bool () const; // NOLINT(google-explicit-constructor)
/* --------------------------------------------------------------------------------------------
* Returns the n'th directory in the directory list. If n == depth(), returns the file name.
*/
const String & operator [] (Uint32 n) const;
const String & operator [] (uint32_t n) const;
/* --------------------------------------------------------------------------------------------
* Used by the script engine to compare two instances of this type.
*/
Int32 Cmp(const SysPath & o) const;
SQMOD_NODISCARD int32_t Cmp(const SysPath & o) const;
/* --------------------------------------------------------------------------------------------
* Used by the script engine to convert an instance of this type to a string.
*/
Object ToString() const;
SQMOD_NODISCARD Object ToString() const;
/* --------------------------------------------------------------------------------------------
* Swaps the path with another one.
@ -177,27 +177,27 @@ public:
/* --------------------------------------------------------------------------------------------
* Assigns a string containing a path in native format.
*/
SysPath & Assign(CSStr path);
SysPath & Assign(const SQChar * path);
/* --------------------------------------------------------------------------------------------
* Assigns a string containing a path.
*/
SysPath & Assign(CSStr path, Int32 style);
SysPath & Assign(const SQChar * path, int32_t style);
/* --------------------------------------------------------------------------------------------
* Assigns a string containing a path.
*/
SysPath & Assign(CSStr path, Style style);
SysPath & Assign(const SQChar * path, Style style);
/* --------------------------------------------------------------------------------------------
* Assigns a string containing a path in native format.
*/
SysPath & Assign(const Buffer & path, Int32 size = -1);
SysPath & Assign(const Buffer & path, int32_t size = -1);
/* --------------------------------------------------------------------------------------------
* Assigns a string containing a path.
*/
SysPath & Assign(const Buffer & path, Style style, Int32 size = -1);
SysPath & Assign(const Buffer & path, Style style, int32_t size = -1);
/* --------------------------------------------------------------------------------------------
* Assigns a string containing a path in native format.
@ -213,7 +213,7 @@ public:
* Creates a path from a parent path and a file name. The parent path is expected to reference
* a directory.
*/
SysPath & Assign(const SysPath & parent, CSStr name);
SysPath & Assign(const SysPath & parent, const SQChar * name);
/* --------------------------------------------------------------------------------------------
* Creates a path from a parent path and a file name. The parent path is expected to reference
@ -240,27 +240,27 @@ public:
/* --------------------------------------------------------------------------------------------
* The resulting path always refers to a directory and the filename part is empty.
*/
SysPath & AssignDir(CSStr path);
SysPath & AssignDir(const SQChar * path);
/* --------------------------------------------------------------------------------------------
* The resulting path always refers to a directory and the filename part is empty.
*/
SysPath & AssignDir(CSStr path, Int32 style);
SysPath & AssignDir(const SQChar * path, int32_t style);
/* --------------------------------------------------------------------------------------------
* The resulting path always refers to a directory and the filename part is empty.
*/
SysPath & AssignDir(CSStr path, Style style);
SysPath & AssignDir(const SQChar * path, Style style);
/* --------------------------------------------------------------------------------------------
* The resulting path always refers to a directory and the filename part is empty.
*/
SysPath & AssignDir(const Buffer & path, Int32 size = -1);
SysPath & AssignDir(const Buffer & path, int32_t size = -1);
/* --------------------------------------------------------------------------------------------
* The resulting path always refers to a directory and the filename part is empty.
*/
SysPath & AssignDir(const Buffer & path, Style style, Int32 size = -1);
SysPath & AssignDir(const Buffer & path, Style style, int32_t size = -1);
/* --------------------------------------------------------------------------------------------
* The resulting path always refers to a directory and the filename part is empty.
@ -275,27 +275,27 @@ public:
/* --------------------------------------------------------------------------------------------
* Returns a string containing the path in native format.
*/
Buffer ToBuffer() const;
SQMOD_NODISCARD Buffer ToBuffer() const;
/* --------------------------------------------------------------------------------------------
* Returns a string containing the path in the given format.
*/
Buffer ToBuffer(Style style) const;
SQMOD_NODISCARD Buffer ToBuffer(Style style) const;
/* --------------------------------------------------------------------------------------------
* Returns a string containing the path in the given format.
*/
Object ToStr(Int32 style) const;
SQMOD_NODISCARD Object ToStr(int32_t style) const;
/* --------------------------------------------------------------------------------------------
* Assigns a string containing a path.
*/
void FromString(CSStr path);
void FromString(const SQChar * path);
/* --------------------------------------------------------------------------------------------
* See whether the path is absolute.
*/
bool IsAbsolute() const
SQMOD_NODISCARD bool IsAbsolute() const
{
return m_Absolute;
}
@ -303,7 +303,7 @@ public:
/* --------------------------------------------------------------------------------------------
* See whether the path is relative.
*/
bool IsRelative() const
SQMOD_NODISCARD bool IsRelative() const
{
return !m_Absolute;
}
@ -311,7 +311,7 @@ public:
/* --------------------------------------------------------------------------------------------
* See whether the path references a directory.
*/
bool IsDirectory() const
SQMOD_NODISCARD bool IsDirectory() const
{
return m_Name.empty();
}
@ -319,7 +319,7 @@ public:
/* --------------------------------------------------------------------------------------------
* See whether the path references a file.
*/
bool IsFile() const
SQMOD_NODISCARD bool IsFile() const
{
return !m_Name.empty();
}
@ -327,7 +327,7 @@ public:
/* --------------------------------------------------------------------------------------------
* See whether the path Does not contain a drive, directories or file name.
*/
bool Empty() const
SQMOD_NODISCARD bool Empty() const
{
return (m_Dirs.empty() && m_Name.empty() && m_Drive == 0);
}
@ -376,27 +376,27 @@ public:
/* --------------------------------------------------------------------------------------------
* Parse the given string and append the resulted path.
*/
SysPath & Append(CSStr path);
SysPath & Append(const SQChar * path);
/* --------------------------------------------------------------------------------------------
* Parse the given string and append the resulted path.
*/
SysPath & Append(CSStr path, Int32 style);
SysPath & Append(const SQChar * path, int32_t style);
/* --------------------------------------------------------------------------------------------
* Parse the given string and append the resulted path.
*/
SysPath & Append(CSStr path, Style style);
SysPath & Append(const SQChar * path, Style style);
/* --------------------------------------------------------------------------------------------
* Parse the given string and append the resulted path.
*/
SysPath & Append(const Buffer & path, Int32 size = -1);
SysPath & Append(const Buffer & path, int32_t size = -1);
/* --------------------------------------------------------------------------------------------
* Parse the given string and append the resulted path.
*/
SysPath & Append(const Buffer & path, Style style, Int32 size = -1);
SysPath & Append(const Buffer & path, Style style, int32_t size = -1);
/* --------------------------------------------------------------------------------------------
* Parse the given string and append the resulted path.
@ -411,7 +411,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Returns the drive letter.
*/
CharT GetDrive() const
SQMOD_NODISCARD CharT GetDrive() const
{
return m_Drive;
}
@ -427,20 +427,20 @@ public:
/* --------------------------------------------------------------------------------------------
* Returns the number of directories in the directory list.
*/
Uint32 Depth() const
SQMOD_NODISCARD uint32_t Depth() const
{
return m_Dirs.size();
return static_cast< uint32_t >(m_Dirs.size());
}
/* --------------------------------------------------------------------------------------------
* Returns the n'th directory in the directory list. If n == depth(), returns the file name.
*/
const String & Directory(Uint32 n) const;
SQMOD_NODISCARD const String & Directory(uint32_t n) const;
/* --------------------------------------------------------------------------------------------
* Adds a directory to the directory list.
*/
SysPath & Push(CSStr dir);
SysPath & Push(const SQChar * dir);
/* --------------------------------------------------------------------------------------------
* Adds a directory to the directory list.
@ -465,7 +465,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Set the specified file name.
*/
SysPath & SetFilename(CSStr name);
SysPath & SetFilename(const SQChar * name);
/* --------------------------------------------------------------------------------------------
* Set the specified file name.
@ -480,7 +480,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Retrieves the file name.
*/
const String & GetFilename() const
SQMOD_NODISCARD const String & GetFilename() const
{
return m_Name;
}
@ -488,7 +488,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Set the specified file name.
*/
void SqSetFilename(CSStr name)
void SqSetFilename(const SQChar * name)
{
SetFilename(name);
}
@ -496,7 +496,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Sets the basename part of the file name and does not change the extension.
*/
SysPath & SetBasename(CSStr name);
SysPath & SetBasename(const SQChar * name);
/* --------------------------------------------------------------------------------------------
* Sets the basename part of the file name and does not change the extension.
@ -511,12 +511,12 @@ public:
/* --------------------------------------------------------------------------------------------
* Returns the basename (the file name without extension) of the path.
*/
String GetBasename() const;
SQMOD_NODISCARD String GetBasename() const;
/* --------------------------------------------------------------------------------------------
* Sets the basename part of the file name and does not change the extension.
*/
void SqSetBasename(CSStr name)
void SqSetBasename(const SQChar * name)
{
SetBasename(name);
}
@ -524,7 +524,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Sets the file name extension.
*/
SysPath & SetExtension(CSStr ext);
SysPath & SetExtension(const SQChar * ext);
/* --------------------------------------------------------------------------------------------
* Sets the file name extension.
@ -534,12 +534,12 @@ public:
/* --------------------------------------------------------------------------------------------
* Returns the file name extension.
*/
String GetExtension() const;
SQMOD_NODISCARD String GetExtension() const;
/* --------------------------------------------------------------------------------------------
* Sets the file name extension.
*/
void SqSetExtension(CSStr ext)
void SqSetExtension(const SQChar * ext)
{
SetExtension(ext);
}
@ -547,12 +547,12 @@ public:
/* --------------------------------------------------------------------------------------------
* Returns a pointer to the internal name string where the extension starts.
*/
CSStr GetExtensionC() const;
SQMOD_NODISCARD const SQChar * GetExtensionC() const;
/* --------------------------------------------------------------------------------------------
* Returns a path referring to the path's directory.
*/
SysPath Parent() const;
SQMOD_NODISCARD SysPath Parent() const;
/* --------------------------------------------------------------------------------------------
* Resolves the given path against the current one. If the given path is absolute, it replaces
@ -565,32 +565,32 @@ protected:
/* --------------------------------------------------------------------------------------------
* Parse a path using the unix standards.
*/
void ParseUnix(CSStr pos, CSStr end);
void ParseUnix(const SQChar * pos, const SQChar * end);
/* --------------------------------------------------------------------------------------------
* Parse a path using the windows standards.
*/
void ParseWindows(CSStr pos, CSStr end);
void ParseWindows(const SQChar * pos, const SQChar * end);
/* --------------------------------------------------------------------------------------------
* Parse a path and expect combined windows and unix styles.
*/
void ParseDynamic(CSStr pos, CSStr end);
void ParseDynamic(const SQChar * pos, const SQChar * end);
/* --------------------------------------------------------------------------------------------
* Parse a path and try to detect it's type automatically.
*/
void ParseGuess(CSStr pos, CSStr end);
void ParseGuess(const SQChar * pos, const SQChar * end);
/* --------------------------------------------------------------------------------------------
* Build a path string using the Unix conventions.
*/
Buffer BuildUnix() const;
SQMOD_NODISCARD Buffer BuildUnix() const;
/* --------------------------------------------------------------------------------------------
* Build a path string using the Windows conventions.
*/
Buffer BuildWindows() const;
SQMOD_NODISCARD Buffer BuildWindows() const;
private:
@ -629,17 +629,17 @@ public:
/* --------------------------------------------------------------------------------------------
* Creates a path referring to a directory.
*/
static SysPath ForDirectory(CSStr path);
static SysPath ForDirectory(const SQChar * path);
/* --------------------------------------------------------------------------------------------
* Creates a path referring to a directory.
*/
static SysPath ForDirectory(CSStr path, Int32 style);
static SysPath ForDirectory(const SQChar * path, int32_t style);
/* --------------------------------------------------------------------------------------------
* Creates a path referring to a directory.
*/
static SysPath ForDirectory(CSStr path, Style style);
static SysPath ForDirectory(const SQChar * path, Style style);
/* --------------------------------------------------------------------------------------------
* Creates a path referring to a directory.
@ -655,7 +655,7 @@ public:
* Expands all environment variables contained in the path. On Unix, a tilde as first character
* in the path is replaced with the path to user's home directory.
*/
static SysPath Expand(CSStr path);
static SysPath Expand(const SQChar * path);
/* --------------------------------------------------------------------------------------------
* Expands all environment variables contained in the path.
@ -701,7 +701,7 @@ public:
static SysPath Temp();
/* --------------------------------------------------------------------------------------------
* Returns the systemwide config directory.
* Returns the system-wide config directory.
*/
static SysPath Config();
@ -718,38 +718,38 @@ public:
/* --------------------------------------------------------------------------------------------
* Returns the real path to the specified file or directory.
*/
static SysPath Real(CSStr path);
static SysPath Real(const SQChar * path);
/* --------------------------------------------------------------------------------------------
* Creates a path from a parent path and a file name. The parent path is expected to reference
* a directory.
*/
static SysPath With(const SysPath & parent, CSStr name);
static SysPath With(const SysPath & parent, const SQChar * name);
/* --------------------------------------------------------------------------------------------
* Creates a path in unix format from a string.
*/
static SysPath MakeUnix(CSStr path);
static SysPath MakeUnix(const SQChar * path);
/* --------------------------------------------------------------------------------------------
* Creates a path in windows format from a string.
*/
static SysPath MakeWindows(CSStr path);
static SysPath MakeWindows(const SQChar * path);
/* --------------------------------------------------------------------------------------------
* Creates a path in native format from a string.
*/
static SysPath MakeNative(CSStr path);
static SysPath MakeNative(const SQChar * path);
/* --------------------------------------------------------------------------------------------
* Creates a path in and guess the format from a string.
*/
static SysPath MakeGuess(CSStr path);
static SysPath MakeGuess(const SQChar * path);
/* --------------------------------------------------------------------------------------------
* Creates a path in dynamic format from a string.
*/
static SysPath MakeDynamic(CSStr path);
static SysPath MakeDynamic(const SQChar * path);
/* --------------------------------------------------------------------------------------------
* Makes sure all separators from a path are the same.

View File

@ -3,14 +3,10 @@
// ------------------------------------------------------------------------------------------------
#include <cstdio>
#include <cstdlib>
// ------------------------------------------------------------------------------------------------
namespace SqMod {
// ------------------------------------------------------------------------------------------------
extern void Register_Buffer(HSQUIRRELVM vm);
/* ------------------------------------------------------------------------------------------------
* Probably not the best implementation but should cover all sorts of weird cases.
*/
@ -31,9 +27,9 @@ static SQInteger SqExtractIPv4(HSQUIRRELVM vm)
// Cleansed IP address buffer
SQChar address[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
// Counting variables used by loops
Uint32 i = 0, j = 0, k = 0;
uint32_t i = 0, j = 0, k = 0;
// Replicate the necessary characters from the resulted string
for (; (i < static_cast< Uint32 >(val.mLen)) && (j < 16) && (k < 4); ++i)
for (; (i < static_cast< uint32_t >(val.mLen)) && (j < 16) && (k < 4); ++i)
{
// Is this a digit?
if (std::isdigit(val.mPtr[i]) != 0)
@ -61,9 +57,9 @@ static SQInteger SqExtractIPv4(HSQUIRRELVM vm)
address[j++] = '.';
}
// Components of the IP address
Uint32 blocks[4] = {0, 0, 0, 0};
uint32_t blocks[4] = {0, 0, 0, 0};
// Attempt to extract the components of the IP address
std::sscanf(address, "%u.%u.%u.%u", &blocks[0], &blocks[1], &blocks[2], &blocks[3]);
std::sscanf(address, "%u.%u.%u.%u", &blocks[0], &blocks[1], &blocks[2], &blocks[3]); // NOLINT(cert-err34-c)
// Create a new array on the stack to hold the extracted components
sq_newarray(vm, 4);
// Push the elements into the array
@ -72,7 +68,7 @@ static SQInteger SqExtractIPv4(HSQUIRRELVM vm)
// Push the element index
sq_pushinteger(vm, i);
// Push the element value
sq_pushinteger(vm, Clamp(blocks[i], 0U, 255U));
sq_pushinteger(vm, std::clamp(blocks[i], 0U, 255U));
// Assign the element
const SQRESULT res = sq_set(vm, -3);
// See if the assignment failed
@ -91,8 +87,6 @@ void Register_Utils(HSQUIRRELVM vm)
RootTable(vm).Bind(_SC("SqUtils"), Table(vm)
.SquirrelFunc(_SC("ExtractIPv4"), &SqExtractIPv4)
);
Register_Buffer(vm);
}
} // Namespace:: SqMod

View File

@ -1,11 +1,9 @@
#pragma once
// ------------------------------------------------------------------------------------------------
#include "Base/Shared.hpp"
#include "Core/Common.hpp"
// ------------------------------------------------------------------------------------------------
namespace SqMod {
} // Namespace:: SqMod

View File

@ -1,26 +0,0 @@
// ------------------------------------------------------------------------------------------------
#include "Library/Web.hpp"
// ------------------------------------------------------------------------------------------------
namespace SqMod {
// ------------------------------------------------------------------------------------------------
struct CvInit {
#if defined(NO_SSL)
CvInit() { mg_init_library(MG_FEATURES_FILES|MG_FEATURES_IPV6|MG_FEATURES_WEBSOCKET|MG_FEATURES_CACHE|MG_FEATURES_HTTP2); }
#else
CvInit() { mg_init_library(MG_FEATURES_FILES|MG_FEATURES_SSL|MG_FEATURES_IPV6|MG_FEATURES_WEBSOCKET|MG_FEATURES_CACHE|MG_FEATURES_HTTP2); }
#endif
} g_CvInit;
// ================================================================================================
void Register_Web(HSQUIRRELVM vm)
{
Table wbns(vm);
RootTable(vm).Bind(_SC("SqWeb"), wbns);
}
} // Namespace:: SqMod

View File

@ -1,23 +0,0 @@
#pragma once
// ------------------------------------------------------------------------------------------------
#include "Base/Shared.hpp"
#include "Misc/Signal.hpp"
// ------------------------------------------------------------------------------------------------
#include <memory>
#include <vector>
#include <memory>
#include <thread>
#include <functional>
#include <algorithm>
// ------------------------------------------------------------------------------------------------
#include <civetweb.h>
// ------------------------------------------------------------------------------------------------
namespace SqMod {
} // Namespace:: SqMod

View File

@ -1,263 +0,0 @@
// ------------------------------------------------------------------------------------------------
#include "Library/Worker.hpp"
// ------------------------------------------------------------------------------------------------
namespace SqMod {
// ------------------------------------------------------------------------------------------------
SQMODE_DECL_TYPENAME(SqWorker, _SC("SqWorker"))
// ------------------------------------------------------------------------------------------------
Worker::Container Worker::sm_Workers{};
// ------------------------------------------------------------------------------------------------
Thread::Thread( Worker * worker)
: mWorker(worker)
, mObject(worker)
, mThread(&Worker::Start, worker)
{
}
// ------------------------------------------------------------------------------------------------
Thread::Thread(Thread && o) noexcept
: mWorker(o.mWorker)
, mObject(std::forward< LightObj >(o.mObject))
, mThread(std::forward< std::thread >(o.mThread))
{
o.mWorker = nullptr;
}
// ------------------------------------------------------------------------------------------------
Worker::Worker(SQInteger stack, String && str, size_t h)
: m_PendingJobs(4096), m_FinishedJobs(4096)
, m_Running()
, m_VM(nullptr)
, m_Mutex()
, m_Hash(h)
, m_Name(std::forward< String >(str))
, m_StackSize(stack)
{
}
// ------------------------------------------------------------------------------------------------
Worker::~Worker()
{
// Instruct the thread to stop whenever possible
Stop();
// Locate our self in the list
std::unique_ptr< Thread > & t = sm_Workers[m_Hash];
// Wait for the thread to finish
if (t->mThread.joinable())
{
t->mThread.join();
}
// Remove ourselves from the list
sm_Workers.erase(m_Hash);
}
// ------------------------------------------------------------------------------------------------
void Worker::Terminate()
{
// Attempt to stop workers
for (auto & t : sm_Workers)
{
// Tell the thread to stop as soon as it can
t.second->mWorker->Stop();
// Wait for it to stop
if (t.second->mThread.joinable())
{
t.second->mThread.join();
}
}
// Simply get rid of them
sm_Workers.clear();
}
// ------------------------------------------------------------------------------------------------
void Worker::Process(size_t jobs)
{
std::vector< Worker * > workers;
workers.reserve(sm_Workers.size());
for (auto & t : sm_Workers)
{
workers.push_back(t.second->mWorker);
}
for (auto & t : workers)
{
for (size_t n = 0; n < jobs; ++n)
{
std::unique_ptr< BaseJob > job;
// Try to get a job from the queue
if (t->m_FinishedJobs.try_dequeue(job))
{
// Allow the job to finish
job->Finish(t->m_VM, *t);
}
}
}
}
// ------------------------------------------------------------------------------------------------
LightObj Worker::Create(SQInteger stack, StackStrF & str)
{
HSQUIRRELVM vm = SqVM();
// Make sure there's a name
if (str.mLen <= 0)
{
STHROWF("Invalid or empty worker name");
}
// Extract the worker name
String name(str.mPtr, static_cast< size_t >(str.mLen));
// Create the name hash
size_t name_hash = std::hash< String >{}(name);
// Make sure this worker doesn't exist
if (sm_Workers.exists(name_hash))
{
STHROWF("Worker already exists");
}
// Attempt to create a routine instance
DeleteGuard< Worker > dg(new Worker(stack, std::move(name), name_hash));
ClassType< Worker >::PushInstance(vm, dg.Get());
Worker * worker = dg.Grab();
// Create the worker thread
std::unique_ptr< Thread > & th = sm_Workers.emplace_back(name_hash, new Thread{worker});
// Return the worker object
return th->mObject;
}
// ------------------------------------------------------------------------------------------------
void Worker::Start()
{
// Initialize
{
// Acquire exclusive access to this instance
std::lock_guard< std::mutex > lg(m_Mutex);
// This should never be the case but why not
if (m_VM)
{
STHROWF("Worker was already started.");
}
// Create the JS state
m_VM = sq_open(m_StackSize);
// Associate with this VM
sq_setforeignptr(m_VM, this);
// Tell the VM to use these functions to output user on error messages
sq_setprintfunc(m_VM, PrintFunc, ErrorFunc);
// Tell the VM to trigger this function on compile time errors
sq_setcompilererrorhandler(m_VM, CompilerErrorHandler);
// Push the runtime error handler on the stack and create a closure
sq_newclosure(m_VM, RuntimeErrorHandler, 0);
// Tell the VM to trigger this function on runtime errors
sq_seterrorhandler(m_VM);
// This is now running
m_Running.test_and_set();
}
// Process
while (m_Running.test_and_set())
{
// Acquire exclusive access to this instance
std::lock_guard< std::mutex > lg(m_Mutex);
// Do the actual processing
Work();
}
// Cleanup
{
// Acquire exclusive access to this instance
std::lock_guard< std::mutex > lg(m_Mutex);
// We're out of the process loop
sq_close(m_VM);
}
}
// ------------------------------------------------------------------------------------------------
void Worker::Work()
{
std::unique_ptr< BaseJob > job;
// Try to get a job from the queue
if (!m_PendingJobs.try_dequeue(job))
{
using namespace std::chrono_literals;
// Do not hammer the CPU if there are no jobs
std::this_thread::sleep_for(50ms);
}
else
{
// Do the job
job->Start(m_VM, *this);
// This job was finished
m_FinishedJobs.enqueue(std::move(job));
}
}
// ------------------------------------------------------------------------------------------------
void Worker::PrintFunc(HSQUIRRELVM /*vm*/, CSStr msg, ...)
{
// Initialize the variable argument list
va_list args;
va_start(args, msg);
// Forward the message to the logger
Logger::Get().SendFv(LOGL_USR, false, msg, args);
// Finalize the variable argument list
va_end(args);
}
// ------------------------------------------------------------------------------------------------
void Worker::ErrorFunc(HSQUIRRELVM vm, CSStr msg, ...)
{
// Initialize the variable argument list
va_list args;
va_start(args, msg);
// Tell the logger to display debugging information
Logger::Get().DebugFv(vm, msg, args);
// Finalize the variable argument list
va_end(args);
}
// ------------------------------------------------------------------------------------------------
SQInteger Worker::RuntimeErrorHandler(HSQUIRRELVM vm)
{
// Was there a value thrown?
if (sq_gettop(vm) < 1)
{
return SQ_OK; // No error to display!
}
// Attempt to generate the string value
StackStrF val(vm, 2);
// Have we failed to retrieve the string?
if (SQ_FAILED(val.Proc(false)))
{
Logger::Get().DebugF(vm, _SC("Unknown runtime error has occurred"));
}
else
{
Logger::Get().DebugF(vm, _SC("%s"), val.mPtr);
}
// We handled the error
return SQ_OK;
}
// ------------------------------------------------------------------------------------------------
void Worker::CompilerErrorHandler(HSQUIRRELVM /*vm*/, CSStr desc, CSStr src, SQInteger line, SQInteger column)
{
LogFtl("Message: %s\n[\n=>Location: %s\n=>Line: %" PRINT_INT_FMT "\n=>Column: %" PRINT_INT_FMT "\n]", desc, src, line, column);
}
// ------------------------------------------------------------------------------------------------
void TerminateWorkers()
{
Worker::Terminate();
}
// ================================================================================================
void Register_Worker(HSQUIRRELVM vm)
{
Table thns(vm);
thns.Bind(_SC("Worker"),
Class< Worker, NoConstructor< Worker > >(vm, SqWorker::Str)
// Meta-methods
.SquirrelFunc(_SC("_typename"), &SqWorker::Fn)
// Properties
.Prop(_SC("Name"), &Worker::GetName)
// Core Methods
.Func(_SC("Enqueue"), &Worker::Enqueue)
// Static Member Methods
);
thns.FmtFunc(_SC("Process"), &Worker::Process);
thns.FmtFunc(_SC("Create"), &Worker::Create);
RootTable(vm).Bind(_SC("SqThread"), thns);
}
} // Namespace:: SqMod

View File

@ -1,217 +0,0 @@
#pragma once
// ------------------------------------------------------------------------------------------------
#include "Base/Shared.hpp"
#include "Base/VecMap.hpp"
#include "Library/Worker/Job.hpp"
#include "Logger.hpp"
// ------------------------------------------------------------------------------------------------
#include <thread>
#include <mutex>
#include <atomic>
#include <vector>
#include <chrono>
#include <condition_variable>
// ------------------------------------------------------------------------------------------------
#include <concurrentqueue.h>
// ------------------------------------------------------------------------------------------------
namespace SqMod {
using namespace moodycamel;
// ------------------------------------------------------------------------------------------------
struct Worker;
/* ------------------------------------------------------------------------------------------------
* Thread.
*/
struct Thread
{
// --------------------------------------------------------------------------------------------
Worker * mWorker; // Worker pointer.
LightObj mObject; // Worker object.
std::thread mThread; // Worker thread.
/* --------------------------------------------------------------------------------------------
* Default constructor.
*/
Thread()
: mWorker(nullptr), mObject(), mThread()
{
}
/* --------------------------------------------------------------------------------------------
* Base constructor.
*/
Thread(Worker * worker);
/* --------------------------------------------------------------------------------------------
* Copy constructor (disabled).
*/
Thread(const Thread & o) = delete;
/* --------------------------------------------------------------------------------------------
* Move constructor (disabled).
*/
Thread(Thread && o) noexcept;
/* --------------------------------------------------------------------------------------------
* Destructor.
*/
~Thread()
{
End();
}
/* --------------------------------------------------------------------------------------------
* Copy assignment (disabled).
*/
Thread & operator = (const Thread & o) = delete;
/* --------------------------------------------------------------------------------------------
* Move assignment (disabled).
*/
Thread & operator = (Thread && o) = delete;
/* --------------------------------------------------------------------------------------------
*
*/
void End()
{
}
};
/* ------------------------------------------------------------------------------------------------
*
*/
struct Worker
{
/* --------------------------------------------------------------------------------------------
* Default constructor.
*/
Worker(SQInteger stack, String && str, size_t h);
/* --------------------------------------------------------------------------------------------
* Copy constructor (disabled).
*/
Worker(const Worker & o) = delete;
/* --------------------------------------------------------------------------------------------
* Move constructor (disabled).
*/
Worker(Worker && o) = delete;
/* --------------------------------------------------------------------------------------------
* Destructor.
*/
~Worker();
/* --------------------------------------------------------------------------------------------
* Copy assignment operator (disabled).
*/
Worker & operator = (const Worker & o) = delete;
/* --------------------------------------------------------------------------------------------
* Move assignment operator (disabled).
*/
Worker & operator = (Worker && o) = delete;
/* --------------------------------------------------------------------------------------------
*
*/
static void Terminate();
/* --------------------------------------------------------------------------------------------
*
*/
static void Process(size_t jobs);
/* --------------------------------------------------------------------------------------------
*
*/
static LightObj Create(SQInteger stack, StackStrF & str);
/* --------------------------------------------------------------------------------------------
* Invoke the actual process loop only if the worker was not requested to stop.
*/
void Start();
/* --------------------------------------------------------------------------------------------
* Stop the worker but do not remove from container.
*/
void Kill()
{
std::lock_guard< std::mutex > lg(m_Mutex);
}
/* --------------------------------------------------------------------------------------------
* Stop the worker and remove from container.
*/
void Stop()
{
m_Running.clear(); // Stop running as soon as you finish what you're doing
}
/* --------------------------------------------------------------------------------------------
* Retrieve the worker name.
*/
const String & GetName() const
{
return m_Name;
}
/* --------------------------------------------------------------------------------------------
*
*/
void Enqueue(JobWrapperBase & job)
{
m_PendingJobs.enqueue(job.Grab());
}
private:
/* --------------------------------------------------------------------------------------------
* Worker thread container.
*/
using Container = VecMap< size_t, std::unique_ptr< Thread > >;
/* --------------------------------------------------------------------------------------------
* List of active worker threads.
*/
static Container sm_Workers;
/* --------------------------------------------------------------------------------------------
*
*/
using Jobs = ConcurrentQueue< std::unique_ptr< BaseJob > >;
/* --------------------------------------------------------------------------------------------
* Pending job queue.
*/
Jobs m_PendingJobs;
/* --------------------------------------------------------------------------------------------
* Finished job queue.
*/
Jobs m_FinishedJobs;
/* --------------------------------------------------------------------------------------------
* Loop state.
*/
std::atomic_flag m_Running;
/* --------------------------------------------------------------------------------------------
* Script state.
*/
HSQUIRRELVM m_VM;
/* --------------------------------------------------------------------------------------------
* Instance mutex.
*/
std::mutex m_Mutex;
/* --------------------------------------------------------------------------------------------
* Cached name hash.
*/
size_t m_Hash;
/* --------------------------------------------------------------------------------------------
* Worker name string.
*/
String m_Name;
/* --------------------------------------------------------------------------------------------
* Cached name hash.
*/
SQInteger m_StackSize;
/* --------------------------------------------------------------------------------------------
* Take jobs from the queue and perform them.
*/
void Work();
/* --------------------------------------------------------------------------------------------
* Script output handlers.
*/
static void PrintFunc(HSQUIRRELVM vm, CSStr msg, ...);
static void ErrorFunc(HSQUIRRELVM vm, CSStr msg, ...);
/* --------------------------------------------------------------------------------------------
* Script error handlers.
*/
static SQInteger RuntimeErrorHandler(HSQUIRRELVM vm);
static void CompilerErrorHandler(HSQUIRRELVM vm, CSStr desc, CSStr src,
SQInteger line, SQInteger column);
};
} // Namespace:: SqMod

View File

@ -1,60 +0,0 @@
// ------------------------------------------------------------------------------------------------
#include "Library/Worker/Job.hpp"
// ------------------------------------------------------------------------------------------------
namespace SqMod {
// ------------------------------------------------------------------------------------------------
SQMODE_DECL_TYPENAME(SqBaseJob, _SC("SqBaseJob"))
SQMODE_DECL_TYPENAME(SqEvaluateJob, _SC("SqEvaluateJob"))
SQMODE_DECL_TYPENAME(SqExecuteJob, _SC("SqExecuteJob"))
// ================================================================================================
void Register_Job(HSQUIRRELVM vm)
{
Table jbns(vm);
{
using Type = JobWrapperBase;
jbns.Bind(_SC("Base"),
Class< Type, NoConstructor< Type > >(vm, SqBaseJob::Str)
// Meta-methods
.SquirrelFunc(_SC("_typename"), &SqBaseJob::Fn)
// Properties
.Prop(_SC("Callback"), &Type::GetCallback, &Type::SetCallback)
// Core Methods
.CbFunc(_SC("SetCallback"), &Type::SetCallback)
);
}
{
using Type = JobWrapper< EvaluateJob >;
jbns.Bind(_SC("Evaluate"),
DerivedClass< Type, JobWrapperBase, NoCopy< Type > >(vm, SqEvaluateJob::Str)
// Meta-methods
.SquirrelFunc(_SC("_typename"), &SqEvaluateJob::Fn)
// Properties
.Prop(_SC("Code"), &Type::GetCode, &Type::SetCode)
.Prop(_SC("Name"), &Type::GetName, &Type::SetName)
// Core Methods
.CbFunc(_SC("SetCode"), &Type::SetCode)
.FmtFunc(_SC("SetName"), &Type::ApplyName)
);
}
{
using Type = JobWrapper< ExecuteJob >;
jbns.Bind(_SC("Execute"),
DerivedClass< Type, JobWrapperBase, NoCopy< Type > >(vm, SqExecuteJob::Str)
// Meta-methods
.SquirrelFunc(_SC("_typename"), &SqExecuteJob::Fn)
);
}
RootTable(vm).Bind(_SC("SqJob"), jbns);
}
} // Namespace:: SqMod

View File

@ -1,293 +0,0 @@
#pragma once
// ------------------------------------------------------------------------------------------------
#include "Base/Shared.hpp"
#include "Library/Worker/Parameter.hpp"
// ------------------------------------------------------------------------------------------------
#include <memory>
// ------------------------------------------------------------------------------------------------
namespace SqMod {
/* ------------------------------------------------------------------------------------------------
* Handle validation.
*/
#if defined(_DEBUG) || defined(SQMOD_EXCEPTLOC)
#define SQMOD_VALIDATE(x) (x).Validate(__FILE__, __LINE__)
#else
#define SQMOD_VALIDATE(x) (x).Validate()
#endif // _DEBUG
// ------------------------------------------------------------------------------------------------
struct Worker;
/* ------------------------------------------------------------------------------------------------
* Used to represent a job that a worker must do, as well as a reply from the worker with the result.
*/
struct BaseJob
{
// --------------------------------------------------------------------------------------------
Function mCallback; // Function to call once completed.
/* --------------------------------------------------------------------------------------------
* Default constructor.
*/
BaseJob()
: mCallback()
{
}
/* --------------------------------------------------------------------------------------------
* Copy constructor (disabled).
*/
BaseJob(const BaseJob & o) = delete;
/* --------------------------------------------------------------------------------------------
* Move constructor (disabled).
*/
BaseJob(BaseJob && o) noexcept = delete;
/* --------------------------------------------------------------------------------------------
* Destructor.
*/
virtual ~BaseJob() = default;
/* --------------------------------------------------------------------------------------------
* Copy assignment operator (disabled).
*/
BaseJob & operator = (const BaseJob & o) = delete;
/* --------------------------------------------------------------------------------------------
* Move assignment operator (disabled).
*/
BaseJob & operator = (BaseJob && o) = delete;
/* --------------------------------------------------------------------------------------------
* Create a new job that will replace the specified job.
*/
virtual BaseJob * New(BaseJob & job) = 0;
/* --------------------------------------------------------------------------------------------
* Invoked inside a worker to perform the job.
*/
virtual bool Start(HSQUIRRELVM vm, Worker & worker) = 0;
/* --------------------------------------------------------------------------------------------
* Invoked inside a worker to perform the job.
*/
virtual void Finish(HSQUIRRELVM vm, Worker & worker)
{
// Do we have a callback?
if (!mCallback.IsNull())
{
mCallback.Execute();
}
}
};
/* ------------------------------------------------------------------------------------------------
* Tell the worker to evaluate a piece of code.
*/
struct EvaluateJob : public BaseJob
{
// --------------------------------------------------------------------------------------------
String mCode; // The code to evaluate.
String mName; // How to refer to this code in errors.
/* --------------------------------------------------------------------------------------------
* Default constructor.
*/
EvaluateJob()
: BaseJob(), mCode(), mName()
{
}
/* --------------------------------------------------------------------------------------------
* Destructor.
*/
virtual ~EvaluateJob() override = default;
/* --------------------------------------------------------------------------------------------
* Create a new job that will replace the specified job.
*/
BaseJob * New(BaseJob & job) override
{
return new EvaluateJob();
}
/* --------------------------------------------------------------------------------------------
*
*/
bool Start(HSQUIRRELVM vm, Worker & worker) override
{
SQRESULT r = sq_compilebuffer(vm, mCode.data(), mCode.size(), mName.data(), SQTrue);
// See if the code could be compiled
if (SQ_FAILED(r))
{
return false; // Job failed
}
// Backup the stack top
SQInteger top = sq_gettop(vm);
// Push the root table as environment
sq_pushroottable(vm);
// Attempt to invoke the compiled code
r = sq_call(vm, 1, SQFalse, SQTrue);
// Restore the stack top
sq_settop(vm, top);
// See if the code could be evaluated
if (SQ_FAILED(r))
{
return false; // Job failed
}
// Job completed
return true;
}
};
/* ------------------------------------------------------------------------------------------------
* Tell the worker to execute the code from a file.
*/
struct ExecuteJob : public BaseJob
{
// --------------------------------------------------------------------------------------------
String mFile; // The file to evaluate.
/* --------------------------------------------------------------------------------------------
* Default constructor.
*/
ExecuteJob()
: BaseJob()
{
}
/* --------------------------------------------------------------------------------------------
* Destructor.
*/
virtual ~ExecuteJob() override = default;
/* --------------------------------------------------------------------------------------------
* Create a new job that will replace the specified job.
*/
BaseJob * New(BaseJob & job) override
{
return new ExecuteJob();
}
/* --------------------------------------------------------------------------------------------
*
*/
bool Start(HSQUIRRELVM vm, Worker & worker) override
{
return true;
}
};
/* ------------------------------------------------------------------------------------------------
* Used internally to wrap a job and expose it to the script.
*/
struct JobWrapperBase
{
/* --------------------------------------------------------------------------------------------
* Copy constructor (disabled).
*/
JobWrapperBase(const JobWrapperBase & o) = delete;
/* --------------------------------------------------------------------------------------------
* Move constructor (disabled).
*/
JobWrapperBase(JobWrapperBase && o) noexcept = delete;
/* --------------------------------------------------------------------------------------------
* Destructor.
*/
~JobWrapperBase()
{
// There should always be an instance
delete m_Inst;
m_Inst = nullptr;
}
/* --------------------------------------------------------------------------------------------
* Copy assignment operator (disabled).
*/
JobWrapperBase & operator = (const JobWrapperBase & o) = delete;
/* --------------------------------------------------------------------------------------------
* Move assignment operator (disabled).
*/
JobWrapperBase & operator = (JobWrapperBase && o) = delete;
/* --------------------------------------------------------------------------------------------
* Retrieve a raw pointer to the managed instance.
*/
BaseJob * Get() const
{
return m_Inst;
}
/* --------------------------------------------------------------------------------------------
* Retrieve a managed pointer managed instance and yield ownership.
*/
std::unique_ptr< BaseJob > Grab()
{
std::unique_ptr< BaseJob > ptr(m_Inst);
m_Inst = ptr->New(*m_Inst);
return ptr;
}
/* --------------------------------------------------------------------------------------------
*
*/
void SetCallback(Function & cb)
{
m_Inst->mCallback = std::move(cb);
}
/* --------------------------------------------------------------------------------------------
*
*/
const Function & GetCallback() const
{
return m_Inst->mCallback;
}
protected:
/* --------------------------------------------------------------------------------------------
* Instance of the wrapped job.
*/
BaseJob * m_Inst;
/* --------------------------------------------------------------------------------------------
* Default constructor.
*/
JobWrapperBase(BaseJob * job) noexcept
: m_Inst(job)
{
}
};
/* ------------------------------------------------------------------------------------------------
* Used internally to wrap a job and expose it to the script.
*/
template < class T > struct JobWrapper : public JobWrapperBase
{
/* --------------------------------------------------------------------------------------------
* Default constructor.
*/
JobWrapper()
: JobWrapperBase(new T)
{
}
/* --------------------------------------------------------------------------------------------
*
*/
void SetCode(StackStrF & str)
{
static_cast< T * >(m_Inst)->mCode.assign(str.mPtr, static_cast< size_t >(str.mLen));
}
/* --------------------------------------------------------------------------------------------
*
*/
const String & GetCode() const
{
return static_cast< T * >(m_Inst)->mCode;
}
/* --------------------------------------------------------------------------------------------
*
*/
void SetName(StackStrF & str)
{
static_cast< T * >(m_Inst)->mName.assign(str.mPtr, static_cast< size_t >(str.mLen));
}
/* --------------------------------------------------------------------------------------------
*
*/
JobWrapper< T > & ApplyName(StackStrF & str)
{
SetName(str);
return *this;
}
/* --------------------------------------------------------------------------------------------
*
*/
const String & GetName() const
{
return static_cast< T * >(m_Inst)->mName;
}
};
} // Namespace:: SqMod

View File

@ -1,208 +0,0 @@
// ------------------------------------------------------------------------------------------------
#include "Library/Worker/Parameter.hpp"
// ------------------------------------------------------------------------------------------------
namespace SqMod {
// ------------------------------------------------------------------------------------------------
Parameter::Parameter(CCStr str)
: Parameter()
{
// Make sure there's a string
if (str)
{
mSize = static_cast< uint32_t >(std::strlen(str));
mString = new SQChar[mSize+1];
std::strcpy(mString, str);
}
// Even an empty string should still be marked as a string
mType = T_STRING;
}
// ------------------------------------------------------------------------------------------------
Parameter::Parameter(CCStr str, size_t len)
: Parameter()
{
// Make sure there's a string
if (str && len)
{
mSize = ConvTo< uint32_t >::From(len);
mString = new SQChar[mSize+1];
std::strncpy(mString, str, mSize);
mString[mSize] = '\0'; // Null terminator
}
// Even an empty string should still be marked as a string
mType = T_STRING;
}
// ------------------------------------------------------------------------------------------------
Parameter::Parameter(ArrayType && v)
: mType(T_ARRAY), mSize(static_cast< uint32_t >(v.size()))
, mArray(new ArrayType(std::forward< ArrayType >(v)))
{
}
// ------------------------------------------------------------------------------------------------
Parameter::Parameter(const ArrayType & v)
: mType(T_ARRAY), mSize(static_cast< uint32_t >(v.size()))
, mArray(new ArrayType(v))
{
}
// ------------------------------------------------------------------------------------------------
Parameter::Parameter(TableType && v)
: mType(T_ARRAY), mSize(static_cast< uint32_t >(v.size()))
, mTable(new TableType(std::forward< TableType >(v)))
{
}
// ------------------------------------------------------------------------------------------------
Parameter::Parameter(const TableType & v)
: mType(T_ARRAY), mSize(static_cast< uint32_t >(v.size()))
, mTable(new TableType(v))
{
}
// ------------------------------------------------------------------------------------------------
Parameter::Parameter(const Parameter & o)
: mType(o.mType), mSize(o.mSize), mData(o.mData)
{
// Identify the type to be copied
switch (mType)
{
// Fundamental types can be copied bit-wise (which we did)
case T_NULL:
case T_INT:
case T_BOOL:
case T_FLOAT: break;
case T_STRING:
if (mSize)
{
mString = new SQChar[mSize];
std::strncpy(mString, o.mString, mSize);
mString[mSize] = '\0'; // Null terminator
}
else
{
mString = nullptr; // Empty string?
}
break;
case T_ARRAY:
mArray = o.mArray ? new ArrayType(*o.mArray) : nullptr;
break;
case T_TABLE:
mTable = o.mTable ? new TableType(*o.mTable) : nullptr;
break;
// How did we get here?
default: break;
}
}
// ------------------------------------------------------------------------------------------------
Parameter::Parameter(Parameter && o)
: mType(o.mType), mSize(o.mSize), mData(o.mData)
{
o.Discard(); // Take ownership
}
// ------------------------------------------------------------------------------------------------
bool Parameter::operator == (const Parameter & o) const noexcept
{
// If they're not the same type then there's no point in comparing
if (mType != o.mType)
{
return false;
}
// Identify which type to compare
switch (mType)
{
// Null is same regardless
case T_NULL: return true;
// Boolean is stored as integer
case T_INT:
case T_BOOL: return (mInt == o.mInt);
// Take into account precision errors
case T_FLOAT: return EpsEq(mFloat, o.mFloat);
case T_STRING:
// Only perform a comparison if there's actually a string to compare
if (mSize && mSize == o.mSize)
{
return std::strncmp(mString, o.mString, mSize) == 0;
}
else
{
return false; // If they're not the same size then they can't be the same
}
// For table or arrays we only test if they're the same rather then each value individually
case T_ARRAY: return (mArray == o.mArray);
case T_TABLE: return (mTable == o.mTable);
// How did we get here?
default: return false;
}
}
// ------------------------------------------------------------------------------------------------
void Parameter::Assign(const Parameter & o)
{
// Avoid self assignment
if (this == &o) return;
/* We could probably optimize this by reusing current container memory.
* But chances are we would complicate code for the simpler case.
* And the simpler case is likely to be the more common scenario.
*/
// Discard current information
Clear();
// The size and type are copied bit-wise
mType = o.mType;
mSize = o.mSize;
// Identify the type to be copied
switch (mType)
{
// Fundamental types can be copied bit-wise
case T_NULL:
case T_INT:
case T_BOOL:
case T_FLOAT:
mData = o.mData;
break;
// Strings require memory to be allocated
case T_STRING:
if (mSize)
{
mString = new SQChar[mSize];
std::strncpy(mString, o.mString, mSize);
mString[mSize] = '\0'; // Null terminator
}
else
{
mString = nullptr; // Empty string?
}
break;
case T_ARRAY:
mArray = o.mArray ? new ArrayType(*o.mArray) : nullptr;
break;
case T_TABLE:
mTable = o.mTable ? new TableType(*o.mTable) : nullptr;
break;
// How did we get here?
default: break;
}
}
// ------------------------------------------------------------------------------------------------
void Parameter::Assign(Parameter && o)
{
// Avoid self assignment
if (this == &o) return;
// Discard current information
Clear();
// We don't care about the type since we take ownership
mType = o.mType;
mSize = o.mSize;
mData = o.mData;
// Take ownership
o.Discard();
}
// ------------------------------------------------------------------------------------------------
void Parameter::Clear()
{
switch (mType)
{
case T_STRING: delete[] mString; break;
case T_ARRAY: delete mArray; break;
case T_TABLE: delete mTable; break;
default: break;
}
}
} // Namespace:: SqMod

View File

@ -1,247 +0,0 @@
#pragma once
// ------------------------------------------------------------------------------------------------
#include "Base/Shared.hpp"
#include "Base/VecMap.hpp"
// ------------------------------------------------------------------------------------------------
namespace SqMod {
/* ------------------------------------------------------------------------------------------------
* Used to transmit values between workers in a language agnostic way.
*/
struct Parameter
{
enum
{
T_NULL=0, // Null/undefined type.
T_INT, // Integer type.
T_BOOL, // Boolean type.
T_FLOAT, // Floating point type.
T_STRING, // String type.
T_ARRAY, // Array type.
T_TABLE // Table type.
};
// --------------------------------------------------------------------------------------------
using ArrayType = std::vector< Parameter >; // Parameter array.
using TableType = VecMap< Parameter, Parameter >; // Parameter table.
// --------------------------------------------------------------------------------------------
uint32_t mType; // Type of value stored in the parameter.
uint32_t mSize; // Container size. Mostly used for the string because there's space from padding.
/* --------------------------------------------------------------------------------------------
*
*/
union {
int64_t mInt; // Parameter value represented as integer.
uint64_t mData; // Parameter value represented as raw bits.
double mFloat; // Parameter value represented as floating point.
CStr mString; // Parameter value represented as string pointer.
ArrayType * mArray; // Parameter value represented as array pointer.
TableType * mTable; // Parameter value represented as table pointer.
};
/* --------------------------------------------------------------------------------------------
* Default constructor (null).
*/
Parameter() noexcept
: Parameter(nullptr)
{
}
/* --------------------------------------------------------------------------------------------
* Null constructor.
*/
explicit Parameter(std::nullptr_t)
: mType(T_NULL), mSize(0), mData(0ull)
{
}
/* --------------------------------------------------------------------------------------------
* Integer constructor.
*/
explicit Parameter(int8_t v)
: mType(T_INT), mSize(sizeof(v)), mInt(v)
{
}
/* --------------------------------------------------------------------------------------------
* Integer constructor.
*/
explicit Parameter(uint8_t v)
: mType(T_INT), mSize(sizeof(v)), mInt(v)
{
}
/* --------------------------------------------------------------------------------------------
* Integer constructor.
*/
explicit Parameter(int16_t v)
: mType(T_INT), mSize(sizeof(v)), mInt(v)
{
}
/* --------------------------------------------------------------------------------------------
* Integer constructor.
*/
explicit Parameter(uint16_t v)
: mType(T_INT), mSize(sizeof(v)), mInt(v)
{
}
/* --------------------------------------------------------------------------------------------
* Integer constructor.
*/
explicit Parameter(int32_t v)
: mType(T_INT), mSize(sizeof(v)), mInt(v)
{
}
/* --------------------------------------------------------------------------------------------
* Integer constructor.
*/
explicit Parameter(uint32_t v)
: mType(T_INT), mSize(sizeof(v)), mInt(v)
{
}
/* --------------------------------------------------------------------------------------------
* Integer constructor.
*/
explicit Parameter(int64_t v)
: mType(T_INT), mSize(sizeof(v)), mInt(v)
{
}
/* --------------------------------------------------------------------------------------------
* Integer constructor.
*/
explicit Parameter(uint64_t v)
: mType(T_INT), mSize(sizeof(v)), mInt(static_cast< int64_t >(v))
{
}
/* --------------------------------------------------------------------------------------------
* Boolean constructor.
*/
explicit Parameter(bool SQ_UNUSED_ARG(v)) //static analyzer shat the bed
: mType(T_BOOL), mSize(1), mInt(v ? 1 : 0)
{
}
/* --------------------------------------------------------------------------------------------
* Floating point constructor.
*/
explicit Parameter(float v)
: mType(T_FLOAT), mSize(sizeof(v)), mFloat(v)
{
}
/* --------------------------------------------------------------------------------------------
* Floating point constructor.
*/
explicit Parameter(double v)
: mType(T_FLOAT), mSize(sizeof(v)), mFloat(v)
{
}
/* --------------------------------------------------------------------------------------------
* String constructor.
*/
explicit Parameter(CCStr str);
/* --------------------------------------------------------------------------------------------
* String constructor.
*/
explicit Parameter(CCStr str, size_t len);
/* --------------------------------------------------------------------------------------------
* Array constructor.
*/
explicit Parameter(ArrayType && v);
/* --------------------------------------------------------------------------------------------
* Array constructor.
*/
explicit Parameter(const ArrayType & v);
/* --------------------------------------------------------------------------------------------
* Table constructor.
*/
explicit Parameter(TableType && v);
/* --------------------------------------------------------------------------------------------
* Table constructor.
*/
explicit Parameter(const TableType & v);
/* --------------------------------------------------------------------------------------------
* Copy constructor.
*/
Parameter(const Parameter & o);
/* --------------------------------------------------------------------------------------------
* Move constructor.
*/
Parameter(Parameter && o);
/* --------------------------------------------------------------------------------------------
* Destructor.
*/
~Parameter()
{
Reset();
}
/* --------------------------------------------------------------------------------------------
* Copy assignment operator.
*/
Parameter & operator = (const Parameter & o)
{
Assign(o);
return *this;
}
/* --------------------------------------------------------------------------------------------
* Move assignment operator.
*/
Parameter & operator = (Parameter && o)
{
Assign(std::forward< Parameter >(o));
return *this;
}
/* --------------------------------------------------------------------------------------------
* Equality comparison operator.
*/
bool operator == (const Parameter & o) const noexcept;
/* --------------------------------------------------------------------------------------------
* Inequality comparison operator.
*/
bool operator != (const Parameter & o) const noexcept
{
return !(*this == o);
}
/* --------------------------------------------------------------------------------------------
* Discard any current information and set to null.
*/
void Reset()
{
Clear(nullptr);
}
/* --------------------------------------------------------------------------------------------
* Swap parameter contents.
*/
void Swap(Parameter & o) noexcept
{
std::swap(mType, o.mType);
std::swap(mSize, o.mSize);
std::swap(mData, o.mData);
}
/* --------------------------------------------------------------------------------------------
* Assign a copy of another parameter.
*/
void Assign(const Parameter & o);
/* --------------------------------------------------------------------------------------------
* Assign a ownership of another parameter.
*/
void Assign(Parameter && o);
private:
/* --------------------------------------------------------------------------------------------
* Discard any and all information without performing any release of memory.
*/
void Discard() noexcept
{
mType = T_NULL;
mSize = 0;
mData = 0ull;
}
/* --------------------------------------------------------------------------------------------
* Clear/release any stored value and reset to default. Does not set to null.
*/
void Clear();
/* --------------------------------------------------------------------------------------------
* Clear/release any stored value and reset to default. Specialization which sets to null.
*/
void Clear(std::nullptr_t)
{
Clear(); // Do a regular clear first
Discard(); // Now we can forget about it
}
};
} // Namespace:: SqMod

View File

@ -1,507 +0,0 @@
// ------------------------------------------------------------------------------------------------
#include "Library/XML.hpp"
// ------------------------------------------------------------------------------------------------
namespace SqMod {
// ------------------------------------------------------------------------------------------------
SQMODE_DECL_TYPENAME(XmlParseResultTypename, _SC("SqXmlParseResult"))
SQMODE_DECL_TYPENAME(XmlDocumentTypename, _SC("SqXmlDocument"))
SQMODE_DECL_TYPENAME(XmlNodeTypename, _SC("SqXmlNode"))
SQMODE_DECL_TYPENAME(XmlAttributeTypename, _SC("SqXmlAttribute"))
SQMODE_DECL_TYPENAME(XmlTextTypename, _SC("SqXmlText"))
// ------------------------------------------------------------------------------------------------
XmlNode XmlDocument::GetNode() const
{
// Validate the document handle
m_Doc.Validate();
// Return the requested information
return XmlNode(m_Doc, m_Doc->document_element());
}
// ------------------------------------------------------------------------------------------------
XmlAttribute XmlNode::GetFirstAttr() const
{
return XmlAttribute(m_Doc, m_Node.first_attribute());
}
// ------------------------------------------------------------------------------------------------
XmlAttribute XmlNode::GetLastAttr() const
{
return XmlAttribute(m_Doc, m_Node.last_attribute());
}
// ------------------------------------------------------------------------------------------------
XmlText XmlNode::GetText() const
{
return XmlText(m_Doc, m_Node.text());
}
// ------------------------------------------------------------------------------------------------
XmlAttribute XmlNode::GetAttribute(CSStr name) const
{
return XmlAttribute(m_Doc, m_Node.attribute(name));
}
// ------------------------------------------------------------------------------------------------
XmlAttribute XmlNode::AttributeFrom(CSStr name, XmlAttribute & attr) const
{
return XmlAttribute(m_Doc, m_Node.attribute(name, attr.m_Attr));
}
// ------------------------------------------------------------------------------------------------
XmlAttribute XmlNode::AppendAttr(CSStr name)
{
return XmlAttribute(m_Doc, m_Node.append_attribute(name));
}
// ------------------------------------------------------------------------------------------------
XmlAttribute XmlNode::PrependAttr(CSStr name)
{
return XmlAttribute(m_Doc, m_Node.prepend_attribute(name));
}
// ------------------------------------------------------------------------------------------------
XmlAttribute XmlNode::InsertAttrAfter(CSStr name, const XmlAttribute & attr)
{
return XmlAttribute(m_Doc, m_Node.insert_attribute_after(name, attr.m_Attr));
}
// ------------------------------------------------------------------------------------------------
XmlAttribute XmlNode::InsertAttrBefore(CSStr name, const XmlAttribute & attr)
{
return XmlAttribute(m_Doc, m_Node.insert_attribute_before(name, attr.m_Attr));
}
// ------------------------------------------------------------------------------------------------
XmlAttribute XmlNode::AppendAttrCopy(const XmlAttribute & proto)
{
return XmlAttribute(m_Doc, m_Node.append_copy(proto.m_Attr));
}
// ------------------------------------------------------------------------------------------------
XmlAttribute XmlNode::PrependAttrCopy(const XmlAttribute & proto)
{
return XmlAttribute(m_Doc, m_Node.prepend_copy(proto.m_Attr));
}
// ------------------------------------------------------------------------------------------------
XmlAttribute XmlNode::InsertAttrCopyAfter(const XmlAttribute & proto, const XmlAttribute & attr)
{
return XmlAttribute(m_Doc, m_Node.insert_copy_after(proto.m_Attr, attr.m_Attr));
}
// ------------------------------------------------------------------------------------------------
XmlAttribute XmlNode::InsertAttrCopyBefore(const XmlAttribute & proto, const XmlAttribute & attr)
{
return XmlAttribute(m_Doc, m_Node.insert_copy_before(proto.m_Attr, attr.m_Attr));
}
// ------------------------------------------------------------------------------------------------
bool XmlNode::RemoveAttrInst(const XmlAttribute & attr)
{
return m_Node.remove_attribute(attr.m_Attr);
}
// ------------------------------------------------------------------------------------------------
LightObj XmlAttribute::AsLong(const SLongInt & def) const
{
return LightObj(SqTypeIdentity< SLongInt >{}, SqVM(), m_Attr.as_llong(def.GetNum()));
}
// ------------------------------------------------------------------------------------------------
LightObj XmlAttribute::AsUlong(const ULongInt & def) const
{
return LightObj(SqTypeIdentity< ULongInt >{}, SqVM(), m_Attr.as_ullong(def.GetNum()));
}
// ------------------------------------------------------------------------------------------------
bool XmlAttribute::ApplyLong(const SLongInt & value)
{
return m_Attr.set_value(value.GetNum());
}
// ------------------------------------------------------------------------------------------------
bool XmlAttribute::ApplyUlong(const ULongInt & value)
{
return m_Attr.set_value(value.GetNum());
}
// ------------------------------------------------------------------------------------------------
LightObj XmlAttribute::GetLong() const
{
return LightObj(SqTypeIdentity< SLongInt >{}, SqVM(), m_Attr.as_llong());
}
// ------------------------------------------------------------------------------------------------
void XmlAttribute::SetLong(const SLongInt & value)
{
m_Attr = value.GetNum();
}
// ------------------------------------------------------------------------------------------------
LightObj XmlAttribute::GetUlong() const
{
return LightObj(SqTypeIdentity< ULongInt >{}, SqVM(), m_Attr.as_ullong());
}
// ------------------------------------------------------------------------------------------------
void XmlAttribute::SetUlong(const ULongInt & value)
{
m_Attr = value.GetNum();
}
// ------------------------------------------------------------------------------------------------
LightObj XmlText::AsLong(const SLongInt & def) const
{
return LightObj(SqTypeIdentity< SLongInt >{}, SqVM(), m_Text.as_llong(def.GetNum()));
}
// ------------------------------------------------------------------------------------------------
LightObj XmlText::AsUlong(const ULongInt & def) const
{
return LightObj(SqTypeIdentity< ULongInt >{}, SqVM(), m_Text.as_ullong(def.GetNum()));
}
// ------------------------------------------------------------------------------------------------
bool XmlText::ApplyLong(const SLongInt & value)
{
return m_Text.set(value.GetNum());
}
// ------------------------------------------------------------------------------------------------
bool XmlText::ApplyUlong(const ULongInt & value)
{
return m_Text.set(value.GetNum());
}
// ------------------------------------------------------------------------------------------------
LightObj XmlText::GetLong() const
{
return LightObj(SqTypeIdentity< SLongInt >{}, SqVM(), m_Text.as_llong());
}
// ------------------------------------------------------------------------------------------------
void XmlText::SetLong(const SLongInt & value)
{
m_Text = value.GetNum();
}
// ------------------------------------------------------------------------------------------------
LightObj XmlText::GetUlong() const
{
return LightObj(SqTypeIdentity< SLongInt >{}, SqVM(), m_Text.as_ullong());
}
// ------------------------------------------------------------------------------------------------
void XmlText::SetUlong(const ULongInt & value)
{
m_Text = value.GetNum();
}
// ------------------------------------------------------------------------------------------------
XmlNode XmlText::GetData() const
{
return XmlNode(m_Doc, m_Text.data());
}
// ================================================================================================
void Register_XML(HSQUIRRELVM vm)
{
Table xmlns(vm);
xmlns.Bind(_SC("ParseResult"), Class< XmlParseResult >(vm, XmlParseResultTypename::Str)
// Constructors
.Ctor()
.Ctor< const XmlParseResult & >()
// Core Meta-methods
.Func(_SC("_cmp"), &XmlParseResult::Cmp)
.SquirrelFunc(_SC("_typename"), &XmlParseResultTypename::Fn)
.Func(_SC("_tostring"), &XmlParseResult::ToString)
// Properties
.Prop(_SC("Valid"), &XmlParseResult::IsValid)
.Prop(_SC("References"), &XmlParseResult::GetRefCount)
.Prop(_SC("Ok"), &XmlParseResult::IsOk)
.Prop(_SC("Status"), &XmlParseResult::GetStatus)
.Prop(_SC("Offset"), &XmlParseResult::GetOffset)
.Prop(_SC("Encoding"), &XmlParseResult::GetEncoding)
.Prop(_SC("Description"), &XmlParseResult::GetDescription)
// Member Methods
.Func(_SC("Check"), &XmlParseResult::Check)
);
xmlns.Bind(_SC("Attribute"), Class< XmlAttribute >(vm, XmlAttributeTypename::Str)
// Constructors
.Ctor()
.Ctor< const XmlAttribute & >()
// Core Meta-methods
.Func(_SC("_cmp"), &XmlAttribute::Cmp)
.SquirrelFunc(_SC("_typename"), &XmlAttributeTypename::Fn)
.Func(_SC("_tostring"), &XmlAttribute::ToString)
// Properties
.Prop(_SC("Valid"), &XmlAttribute::IsValid)
.Prop(_SC("References"), &XmlAttribute::GetRefCount)
.Prop(_SC("Empty"), &XmlAttribute::IsEmpty)
.Prop(_SC("Hash"), &XmlAttribute::GetHashValue)
.Prop(_SC("Name"), &XmlAttribute::GetName, &XmlAttribute::SetName)
.Prop(_SC("Value"), &XmlAttribute::GetValue, &XmlAttribute::SetValue)
.Prop(_SC("Int"), &XmlAttribute::GetInt, &XmlAttribute::SetInt)
.Prop(_SC("Uint"), &XmlAttribute::GetUint, &XmlAttribute::SetUint)
.Prop(_SC("Float"), &XmlAttribute::GetFloat, &XmlAttribute::SetFloat)
.Prop(_SC("Double"), &XmlAttribute::GetDouble, &XmlAttribute::SetDouble)
.Prop(_SC("Long"), &XmlAttribute::GetLong, &XmlAttribute::SetLong)
.Prop(_SC("Ulong"), &XmlAttribute::GetUlong, &XmlAttribute::SetUlong)
.Prop(_SC("Bool"), &XmlAttribute::GetBool, &XmlAttribute::SetBool)
.Prop(_SC("Next"), &XmlAttribute::NextAttribute)
.Prop(_SC("Prev"), &XmlAttribute::PrevAttribute)
// Member Methods
.Func(_SC("SetName"), &XmlAttribute::ApplyName)
.Func(_SC("SetValue"), &XmlAttribute::ApplyValue)
.Func(_SC("AsString"), &XmlAttribute::AsString)
.Func(_SC("AsInt"), &XmlAttribute::AsInt)
.Func(_SC("AsUint"), &XmlAttribute::AsUint)
.Func(_SC("AsFloat"), &XmlAttribute::AsFloat)
.Func(_SC("AsDouble"), &XmlAttribute::AsDouble)
.Func(_SC("AsLong"), &XmlAttribute::AsLong)
.Func(_SC("AsUlong"), &XmlAttribute::AsUlong)
.Func(_SC("AsBool"), &XmlAttribute::AsBool)
.Func(_SC("SetString"), &XmlAttribute::ApplyString)
.Func(_SC("SetInt"), &XmlAttribute::ApplyInt)
.Func(_SC("SetUint"), &XmlAttribute::ApplyUint)
.Func(_SC("SetFloat"), &XmlAttribute::ApplyFloat)
.Func(_SC("SetDouble"), &XmlAttribute::ApplyDouble)
.Func(_SC("SetLong"), &XmlAttribute::ApplyLong)
.Func(_SC("SetUlong"), &XmlAttribute::ApplyUlong)
.Func(_SC("SetBool"), &XmlAttribute::ApplyBool)
);
xmlns.Bind(_SC("Text"), Class< XmlText >(vm, XmlTextTypename::Str)
// Constructors
.Ctor()
.Ctor< const XmlText & >()
// Core Meta-methods
.Func(_SC("_cmp"), &XmlText::Cmp)
.SquirrelFunc(_SC("_typename"), &XmlTextTypename::Fn)
.Func(_SC("_tostring"), &XmlText::ToString)
// Properties
.Prop(_SC("Valid"), &XmlText::IsValid)
.Prop(_SC("References"), &XmlText::GetRefCount)
.Prop(_SC("Empty"), &XmlText::IsEmpty)
.Prop(_SC("Value"), &XmlText::GetValue)
.Prop(_SC("Int"), &XmlText::GetInt, &XmlText::SetInt)
.Prop(_SC("Uint"), &XmlText::GetUint, &XmlText::SetUint)
.Prop(_SC("Float"), &XmlText::GetFloat, &XmlText::SetFloat)
.Prop(_SC("Double"), &XmlText::GetDouble, &XmlText::SetDouble)
.Prop(_SC("Long"), &XmlText::GetLong, &XmlText::SetLong)
.Prop(_SC("Ulong"), &XmlText::GetUlong, &XmlText::SetUlong)
.Prop(_SC("Bool"), &XmlText::GetBool, &XmlText::SetBool)
.Prop(_SC("Data"), &XmlText::GetData)
// Member Methods
.Func(_SC("AsString"), &XmlText::AsString)
.Func(_SC("AsInt"), &XmlText::AsInt)
.Func(_SC("AsUint"), &XmlText::AsUint)
.Func(_SC("AsFloat"), &XmlText::AsFloat)
.Func(_SC("AsDouble"), &XmlText::AsDouble)
.Func(_SC("AsLong"), &XmlText::AsLong)
.Func(_SC("AsUlong"), &XmlText::AsUlong)
.Func(_SC("AsBool"), &XmlText::AsBool)
.Func(_SC("SetString"), &XmlText::ApplyString)
.Func(_SC("SetInt"), &XmlText::ApplyInt)
.Func(_SC("SetUint"), &XmlText::ApplyUint)
.Func(_SC("SetFloat"), &XmlText::ApplyFloat)
.Func(_SC("SetDouble"), &XmlText::ApplyDouble)
.Func(_SC("SetLong"), &XmlText::ApplyLong)
.Func(_SC("SetUlong"), &XmlText::ApplyUlong)
.Func(_SC("SetBool"), &XmlText::ApplyBool)
);
xmlns.Bind(_SC("Node"), Class< XmlNode >(vm, XmlNodeTypename::Str)
// Constructors
.Ctor()
.Ctor< const XmlNode & >()
// Core Meta-methods
.Func(_SC("_cmp"), &XmlNode::Cmp)
.SquirrelFunc(_SC("_typename"), &XmlNodeTypename::Fn)
.Func(_SC("_tostring"), &XmlNode::ToString)
// Properties
.Prop(_SC("Valid"), &XmlNode::IsValid)
.Prop(_SC("References"), &XmlNode::GetRefCount)
.Prop(_SC("Empty"), &XmlNode::IsEmpty)
.Prop(_SC("Hash"), &XmlNode::GetHashValue)
.Prop(_SC("OffsetDebug"), &XmlNode::GetOffsetDebug)
.Prop(_SC("Type"), &XmlNode::GetType)
.Prop(_SC("Name"), &XmlNode::GetName, &XmlNode::SetName)
.Prop(_SC("Value"), &XmlNode::GetValue, &XmlNode::SetValue)
.Prop(_SC("FirstAttr"), &XmlNode::GetFirstAttr)
.Prop(_SC("LastAttr"), &XmlNode::GetLastAttr)
.Prop(_SC("FirstChild"), &XmlNode::GetFirstChild)
.Prop(_SC("LastChild"), &XmlNode::GetLastChild)
.Prop(_SC("NextSibling"), &XmlNode::GetNextSibling)
.Prop(_SC("PrevSibling"), &XmlNode::GetPrevSibling)
.Prop(_SC("Parent"), &XmlNode::GetParent)
.Prop(_SC("Root"), &XmlNode::GetRoot)
.Prop(_SC("Text"), &XmlNode::GetText)
.Prop(_SC("ChildValue"), &XmlNode::GetChildValue)
// Member Methods
.Overload< XmlParseResult (XmlNode::*)(CSStr) >(_SC("AppendBuffer"), &XmlNode::AppendBuffer)
.Overload< XmlParseResult (XmlNode::*)(CSStr, Uint32) >(_SC("AppendBuffer"), &XmlNode::AppendBuffer)
.Overload< XmlParseResult (XmlNode::*)(CSStr, Uint32, Int32) >(_SC("AppendBuffer"), &XmlNode::AppendBuffer)
.Func(_SC("SetName"), &XmlNode::ApplyName)
.Func(_SC("SetValue"), &XmlNode::ApplyValue)
.Func(_SC("GetChild"), &XmlNode::Child)
.Func(_SC("GetAttr"), &XmlNode::GetAttribute)
.Func(_SC("GetAttribute"), &XmlNode::GetAttribute)
.Func(_SC("GetAttrFrom"), &XmlNode::AttributeFrom)
.Func(_SC("GetAttributeFrom"), &XmlNode::AttributeFrom)
.Func(_SC("GetNextSibling"), &XmlNode::NextSibling)
.Func(_SC("GetPrevSibling"), &XmlNode::PrevSibling)
.Func(_SC("GetChildValue"), &XmlNode::ChildValue)
.Func(_SC("AppendAttr"), &XmlNode::AppendAttr)
.Func(_SC("PrependAttr"), &XmlNode::PrependAttr)
.Func(_SC("InsertAttrAfter"), &XmlNode::InsertAttrAfter)
.Func(_SC("InsertAttrBefore"), &XmlNode::InsertAttrBefore)
.Func(_SC("AppendAttrCopy"), &XmlNode::AppendAttrCopy)
.Func(_SC("PrependAttrCopy"), &XmlNode::PrependAttrCopy)
.Func(_SC("InsertAttrCopyAfter"), &XmlNode::InsertAttrCopyAfter)
.Func(_SC("InsertAttrCopyBefore"), &XmlNode::InsertAttrCopyBefore)
.Func(_SC("AppendChild"), &XmlNode::AppendChild)
.Func(_SC("PrependChild"), &XmlNode::PrependChild)
.Func(_SC("AppendChildNode"), &XmlNode::AppendChildNode)
.Func(_SC("PrependChildNode"), &XmlNode::PrependChildNode)
.Func(_SC("AppendChildType"), &XmlNode::AppendChildType)
.Func(_SC("PrependChildType"), &XmlNode::PrependChildType)
.Func(_SC("InsertChildAfter"), &XmlNode::InsertChildAfter)
.Func(_SC("InsertChildBefore"), &XmlNode::InsertChildBefore)
.Func(_SC("InsertChildTypeAfter"), &XmlNode::InsertChildTypeAfter)
.Func(_SC("InsertChildTypeBefore"), &XmlNode::InsertChildTypeBefore)
.Func(_SC("AppendCopy"), &XmlNode::AppendCopy)
.Func(_SC("PrependCopy"), &XmlNode::PrependCopy)
.Func(_SC("InsertCopyAfter"), &XmlNode::InsertCopyAfter)
.Func(_SC("InsertCopyBefore"), &XmlNode::InsertCopyBefore)
.Func(_SC("AppendMove"), &XmlNode::AppendMove)
.Func(_SC("PrependMove"), &XmlNode::PrependMove)
.Func(_SC("InsertMoveAfter"), &XmlNode::InsertMoveAfter)
.Func(_SC("InsertMoveBefore"), &XmlNode::InsertMoveBefore)
.Func(_SC("RemoveAttr"), &XmlNode::RemoveAttr)
.Func(_SC("RemoveAttrInst"), &XmlNode::RemoveAttrInst)
.Func(_SC("RemoveChild"), &XmlNode::RemoveChild)
.Func(_SC("RemoveChildInst"), &XmlNode::RemoveChildInst)
.Overload< XmlNode (XmlNode::*)(CSStr, CSStr) const >(_SC("FindChildByAttr"), &XmlNode::FindChildByAttr)
.Overload< XmlNode (XmlNode::*)(CSStr, CSStr, CSStr) const >(_SC("FindChildByAttr"), &XmlNode::FindChildByAttr)
.Func(_SC("FindElemByPath"), &XmlNode::FindElemByPath)
);
xmlns.Bind(_SC("Document"), Class< XmlDocument, NoCopy< XmlDocument > >(vm, XmlDocumentTypename::Str)
// Constructors
.Ctor()
// Core Meta-methods
.Func(_SC("_cmp"), &XmlDocument::Cmp)
.SquirrelFunc(_SC("_typename"), &XmlDocumentTypename::Fn)
.Func(_SC("_tostring"), &XmlDocument::ToString)
// Properties
.Prop(_SC("Valid"), &XmlDocument::IsValid)
.Prop(_SC("References"), &XmlDocument::GetRefCount)
.Prop(_SC("Node"), &XmlDocument::GetNode)
// Member Methods
.Overload< void (XmlDocument::*)(void) > (_SC("Reset"), &XmlDocument::Reset)
.Overload < void (XmlDocument::*)(const XmlDocument &) >(_SC("Reset"), &XmlDocument::Reset)
.Overload< XmlParseResult (XmlDocument::*)(CSStr) >(_SC("LoadString"), &XmlDocument::LoadData)
.Overload< XmlParseResult (XmlDocument::*)(CSStr, Uint32) >(_SC("LoadString"), &XmlDocument::LoadData)
.Overload< XmlParseResult (XmlDocument::*)(CSStr) >(_SC("LoadFile"), &XmlDocument::LoadFile)
.Overload< XmlParseResult (XmlDocument::*)(CSStr, Uint32) >(_SC("LoadFile"), &XmlDocument::LoadFile)
.Overload< XmlParseResult (XmlDocument::*)(CSStr, Uint32, Int32) >(_SC("LoadFile"), &XmlDocument::LoadFile)
.Overload < void (XmlDocument::*)(CSStr) > (_SC("SaveFile"), &XmlDocument::SaveFile)
.Overload < void (XmlDocument::*)(CSStr, CSStr) > (_SC("SaveFile"), &XmlDocument::SaveFile)
.Overload < void (XmlDocument::*)(CSStr, CSStr, Uint32) > (_SC("SaveFile"), &XmlDocument::SaveFile)
.Overload < void (XmlDocument::*)(CSStr, CSStr, Uint32, Int32) > (_SC("SaveFile"), &XmlDocument::SaveFile)
);
RootTable(vm).Bind(_SC("SqXml"), xmlns);
ConstTable(vm).Enum(_SC("SqXmlNodeType"), Enumeration(vm)
.Const(_SC("Null"), static_cast< Int32 >(node_null))
.Const(_SC("XmlDocument"), static_cast< Int32 >(node_document))
.Const(_SC("Element"), static_cast< Int32 >(node_element))
.Const(_SC("PCData"), static_cast< Int32 >(node_pcdata))
.Const(_SC("CData"), static_cast< Int32 >(node_cdata))
.Const(_SC("Comment"), static_cast< Int32 >(node_comment))
.Const(_SC("Pi"), static_cast< Int32 >(node_pi))
.Const(_SC("Declaration"), static_cast< Int32 >(node_declaration))
.Const(_SC("Doctype"), static_cast< Int32 >(node_doctype))
);
ConstTable(vm).Enum(_SC("SqXmlParse"), Enumeration(vm)
.Const(_SC("Minimal"), static_cast< Int32 >(parse_minimal))
.Const(_SC("Default"), static_cast< Int32 >(parse_default))
.Const(_SC("Full"), static_cast< Int32 >(parse_full))
.Const(_SC("Pi"), static_cast< Int32 >(parse_pi))
.Const(_SC("Comments"), static_cast< Int32 >(parse_comments))
.Const(_SC("CData"), static_cast< Int32 >(parse_cdata))
.Const(_SC("WSPCData"), static_cast< Int32 >(parse_ws_pcdata))
.Const(_SC("Escapes"), static_cast< Int32 >(parse_escapes))
.Const(_SC("EOL"), static_cast< Int32 >(parse_eol))
.Const(_SC("WConvAttribute"), static_cast< Int32 >(parse_wconv_attribute))
.Const(_SC("WNormAttribute"), static_cast< Int32 >(parse_wnorm_attribute))
.Const(_SC("Declaration"), static_cast< Int32 >(parse_declaration))
.Const(_SC("Doctype"), static_cast< Int32 >(parse_doctype))
.Const(_SC("WSPCDataSingle"), static_cast< Int32 >(parse_ws_pcdata_single))
.Const(_SC("TrimPCData"), static_cast< Int32 >(parse_trim_pcdata))
.Const(_SC("Fragment"), static_cast< Int32 >(parse_fragment))
.Const(_SC("EmbedPCData"), static_cast< Int32 >(parse_embed_pcdata))
);
ConstTable(vm).Enum(_SC("SqXmlEncoding"), Enumeration(vm)
.Const(_SC("Auto"), static_cast< Int32 >(encoding_auto))
.Const(_SC("Utf8"), static_cast< Int32 >(encoding_utf8))
.Const(_SC("Utf16LE"), static_cast< Int32 >(encoding_utf16_le))
.Const(_SC("Utf16BE"), static_cast< Int32 >(encoding_utf16_be))
.Const(_SC("Utf16"), static_cast< Int32 >(encoding_utf16))
.Const(_SC("Utf32LE"), static_cast< Int32 >(encoding_utf32_le))
.Const(_SC("Utf32BE"), static_cast< Int32 >(encoding_utf32_be))
.Const(_SC("Utf32"), static_cast< Int32 >(encoding_utf32))
.Const(_SC("WChar"), static_cast< Int32 >(encoding_wchar))
.Const(_SC("Latin1"), static_cast< Int32 >(encoding_latin1))
);
ConstTable(vm).Enum(_SC("SqXmlFormat"), Enumeration(vm)
.Const(_SC("Indent"), static_cast< Int32 >(format_indent))
.Const(_SC("WriteBOM"), static_cast< Int32 >(format_write_bom))
.Const(_SC("Raw"), static_cast< Int32 >(format_raw))
.Const(_SC("NoDeclaration"), static_cast< Int32 >(format_no_declaration))
.Const(_SC("NoEscapes"), static_cast< Int32 >(format_no_escapes))
.Const(_SC("SaveFileText"), static_cast< Int32 >(format_save_file_text))
.Const(_SC("IndentAttributes"), static_cast< Int32 >(format_indent_attributes))
.Const(_SC("Default"), static_cast< Int32 >(format_default))
);
ConstTable(vm).Enum(_SC("SqXmlParseStatus"), Enumeration(vm)
.Const(_SC("Ok"), static_cast< Int32 >(status_ok))
.Const(_SC("FileNotFound"), static_cast< Int32 >(status_file_not_found))
.Const(_SC("IOError"), static_cast< Int32 >(status_io_error))
.Const(_SC("OutOfMemory"), static_cast< Int32 >(status_out_of_memory))
.Const(_SC("InternalError"), static_cast< Int32 >(status_internal_error))
.Const(_SC("UnrecognizedTag"), static_cast< Int32 >(status_unrecognized_tag))
.Const(_SC("BadPi"), static_cast< Int32 >(status_bad_pi))
.Const(_SC("BadComment"), static_cast< Int32 >(status_bad_comment))
.Const(_SC("BadCData"), static_cast< Int32 >(status_bad_cdata))
.Const(_SC("BadDoctype"), static_cast< Int32 >(status_bad_doctype))
.Const(_SC("BadPCData"), static_cast< Int32 >(status_bad_pcdata))
.Const(_SC("BadStartElement"), static_cast< Int32 >(status_bad_start_element))
.Const(_SC("BadAttribute"), static_cast< Int32 >(status_bad_attribute))
.Const(_SC("BadEndElement"), static_cast< Int32 >(status_bad_end_element))
.Const(_SC("EndElementMismatch"), static_cast< Int32 >(status_end_element_mismatch))
.Const(_SC("AppendInvalidRoot"), static_cast< Int32 >(status_append_invalid_root))
.Const(_SC("NoDocumentElement"), static_cast< Int32 >(status_no_document_element))
);
ConstTable(vm).Enum(_SC("SqXmlXpathValueType"), Enumeration(vm)
.Const(_SC("None"), static_cast< Int32 >(xpath_type_none))
.Const(_SC("NodeSet"), static_cast< Int32 >(xpath_type_node_set))
.Const(_SC("Number"), static_cast< Int32 >(xpath_type_number))
.Const(_SC("String"), static_cast< Int32 >(xpath_type_string))
.Const(_SC("Boolean"), static_cast< Int32 >(xpath_type_boolean))
);
}
} // Namespace:: SqMod

File diff suppressed because it is too large Load Diff