Example #1
0
double TILParser::toDouble(StringRef s) {
  char* end = nullptr;
  double val = strtod(s.c_str(), &end);
  // FIXME: some proper error handling here?
  assert(end == s.c_str() + s.length() && "Could not parse string.");
  return val;
}
Example #2
0
int TILParser::toInteger(StringRef s) {
  char* end = nullptr;
  long long val = strtol(s.c_str(), &end, 0);
  // FIXME: some proper error handling here?
  assert(end == s.c_str() + s.length() && "Could not parse string.");
  return static_cast<int>(val);
}
Example #3
0
IPAddress::IPAddress(StringRef ip, ushort port, bool isIP6 /*= false*/)
{
	if (isIP6)
	{
		Memory::ClearZero(&mAddress6);
		mAddress6.sin6_family = (int)SocketAddressFamily::IP6;
		mAddress6.sin6_port = BitConverter::HostToNetwork(port);
		if (!ip.IsEmpty())	//0.0.0.0 or "" to bind to any local ip
		{
			if (inet_pton(mAddress6.sin6_family, ip.c_str(), &mAddress6.sin6_addr) <= 0)
			{
				Log::AssertFailedFormat("Invalid ip6:{}", ip);
			}
		}
		
	}
	else
	{
		Memory::ClearZero(&mAddress);
		mAddress.sin_family = (int)SocketAddressFamily::IP;
		mAddress.sin_port = BitConverter::HostToNetwork(port);

		if (!ip.IsEmpty())
		{
			if (inet_pton(mAddress.sin_family, ip.c_str(), &mAddress.sin_addr) <= 0)
			{
				Log::AssertFailedFormat("Invalid ip:{}", ip);
			}
		}
		
	}
}
Example #4
0
void DateTime::Init(const StringRef& dateTimeStr, const StringRef& formaterStr, bool isUTC/*=true*/)
{
	uint year, month, day, hour, minutes, seconds;
#ifdef MEDUSA_WINDOWS
	sscanf_s(dateTimeStr.c_str(), formaterStr.c_str(), &year, &month, &day, &hour, &minutes, &seconds);
#else
	sscanf(dateTimeStr.c_str(), formaterStr.c_str(), &year, &month, &day, &hour, &minutes, &seconds);
#endif
	Init(year, month - 1, day, hour, minutes, seconds, isUTC);
}
Example #5
0
bool TiledImage::Parse(const pugi::xml_node& node)
{
	// Read all the attribute into member variables.
	mSource= FileId::ParseFrom(node.attribute("source").as_string(nullptr));
	if (mSource.IsEmpty())
	{
		Log::AssertFailed("Invalid image xml node source attribute");
		return false;
	}

	mSize.Width = node.attribute("width").as_int(0);
	mSize.Height = node.attribute("height").as_int(0);

	const char* transparentColorStr = node.attribute("trans").as_string(nullptr);
	mTransparentColor = TiledMap::ParseColor(transparentColorStr);


	StringRef formatStr = node.attribute("format").as_string(nullptr);

	if (formatStr == "png")
	{
		mEmbeddedFileType=FileType::png;
	}
	else if (formatStr == "jpg")
	{
		mEmbeddedFileType=FileType::jpeg;
	}
	else if (!formatStr.IsEmpty())
	{
		Log::FormatError("Unsupported image type:{}", formatStr.c_str());
		return false;
	}

	pugi::xml_node dataNode = node.child("data");
	if (!dataNode.empty())
	{
		StringRef encodingStr = node.attribute("encoding").as_string(nullptr);
		StringRef compressionStr = node.attribute("compression").as_string(nullptr);
		if (encodingStr != "base64")
		{
			Log::FormatError("Unsupported encoding type:{}", encodingStr.c_str());
			return false;
		}

		const char* text = dataNode.value();
		Base64Decoder decoder;
		mEmbeddedImageData = decoder.Code(text);
	}

	return true;
}
Example #6
0
bool IPAddress::IsIP6(StringRef val)
{
	RETURN_FALSE_IF_EMPTY(val);
	in6_addr sAddr; // IPv6地址结构体
	int r = inet_pton((int)SocketAddressFamily::IP6, val.c_str(), &sAddr);
	return r > 0;	//<=0 means error
}
Example #7
0
SqlException::SqlException(const StringRef& initialMessage, const int errno, const char *sqlState, const char *errorMessage)
    :std::exception(initialMessage.c_str())
{
    mErrno = errno;
    mSqlState = sqlState;
    mErrorMessage = errorMessage;
}
Example #8
0
SqlException::SqlException(MYSQL *db, const StringRef& initialMessage)
    :std::exception(initialMessage.c_str())
{
    mErrno = mysql_errno(db);
    mErrorMessage = mysql_error(db);
    mSqlState = mysql_sqlstate(db);
}
Example #9
0
SqlException::SqlException(MYSQL_STMT *stmt, const StringRef& initialMessage)
    :std::exception(initialMessage.c_str())
{
    mErrno = mysql_stmt_errno(stmt);
    mErrorMessage = mysql_stmt_error(stmt);
    mSqlState = mysql_stmt_sqlstate(stmt);
}
Example #10
0
bool StringPropertySet::Parse(const StringRef& str)
{
	RETURN_TRUE_IF_EMPTY(str);
	//Key=Value,...
	List<StringRef> outPairs;
	StringParser::Split(str, ",", outPairs);

	List<StringRef> keyValuePair;
	for (auto& optionPair : outPairs)
	{
		keyValuePair.Clear();
		StringParser::Split(optionPair, "=", keyValuePair);
		if (keyValuePair.Count() == 2)
		{
			Add(keyValuePair[0], keyValuePair[1]);
		}
		else if (keyValuePair.Count() == 1)
		{
			Add(keyValuePair[0], HeapString::Empty);
		}
		else
		{
			Log::FormatError("Invalid attribute str:{} in {}", optionPair.c_str(), str.c_str());
			return false;
		}
	}

	return true;
}
void ff::SetDebuggerThreadName(StringRef name, DWORD nThreadID)
{
#ifdef _DEBUG
	if (IsDebuggerPresent())
	{
		CHAR szNameACP[512] = "";
		WideCharToMultiByte(CP_ACP, 0, name.c_str(), -1, szNameACP, _countof(szNameACP), nullptr, nullptr);

		typedef struct tagTHREADNAME_INFO
		{
			ULONG_PTR dwType; // must be 0x1000
			const char *szName; // pointer to name (in user addr space)
			ULONG_PTR dwThreadID; // thread ID (-1=caller thread)
			ULONG_PTR dwFlags; // reserved for future use, must be zero
		} THREADNAME_INFO;

		THREADNAME_INFO info;
		info.dwType = 0x1000;
		info.szName = szNameACP;
		info.dwThreadID = nThreadID ? nThreadID : GetCurrentThreadId();
		info.dwFlags = 0;

		__try
		{
			RaiseException(0x406D1388, 0, sizeof(info) / sizeof(ULONG_PTR), (ULONG_PTR*)&info);
		}
		__except (EXCEPTION_CONTINUE_EXECUTION)
		{
		}
	}

#endif // _DEBUG
}
Example #12
0
bool File::GetFileMode(StringRef filePath, FileMode& outFileMode)
{
	struct stat buf;
	const char* path = filePath.c_str();
	int result = stat(path, &buf);
	if (result == 0)
	{
		if (buf.st_mode&S_IFDIR)
		{
			outFileMode = FileMode::Directory;
		}
		else
		{
			outFileMode = FileMode::File;
		}

		return true;
	}
	else
	{
		if (errno == ENOENT)
		{
			//file not exists
			return false;
		}
		else
		{
			return false;
		}
	}
}
Example #13
0
bool IPAddress::IsIP(StringRef val)
{
	//IP address format:<ddd.ddd.ddd.ddd>
	RETURN_FALSE_IF_EMPTY(val);
	in_addr sAddr; // IPv4地址结构体
	int r = inet_pton((int)SocketAddressFamily::IP, val.c_str(), &sAddr);
	return r > 0;	//<=0 means error
}
Example #14
0
inline void ScriptObject::Invoke(const StringRef& funcName, TArgs&&... args)
{
	asIObjectType* scriptObjectType = mScriptObject->GetObjectType();
	asIScriptFunction* func = scriptObjectType->GetMethodByName(funcName.c_str());
	if (func == nullptr)
	{
		Log::AssertFailedFormat("Cannot find {}::{}", scriptObjectType->GetName(), funcName.c_str());
		return;
	}

	asIScriptContext* context = ScriptEngine::Instance().GetScriptContext();
	context->Prepare(func);
	context->SetObject(mScriptObject);
	SetArgs(context, std::forward<TArgs>(args)...);
	context->Execute();

	asThreadCleanup();
}
Example #15
0
bool BehaviorConfig::LoadFromData(const FileIdRef& fileId, const MemoryData& data, uint format /*= 0*/)
{
	Unload();
	RETURN_FALSE_IF(data.IsNull());

	pugi::xml_document doc;
	pugi::xml_parse_result result = doc.load_buffer(data.Data(), data.Size());
	if (!result)
	{
		Log::AssertFailedFormat("Cannot parse xml:{} because {}", fileId, result.description());
		return false;
	}
	for (const auto& child : doc.first_child().children())
	{
		StringRef typeName = child.name();
		StringRef id = child.attribute("Id").value();
		if (id.IsEmpty())
		{
			id = typeName;
		}

#ifdef MEDUSA_SAFE_CHECK
		if (ContainsId(id))
		{
			Log::AssertFailedFormat("Duplicate id:{} in {}", id.c_str(), typeName.c_str());
		}
#endif

		IBehavior* behavior = BehaviorFactory::Instance().SmartCreate(typeName);
		behavior->LoadFromXmlNode(child);
		behavior->Initialize();
		if (id.EndWith("Behavior"))
		{
			Add(id, behavior);
		}
		else
		{
			Add(id + "Behavior", behavior);
		}
	}


	return true;
}
Example #16
0
IPAddress IPAddress::Resolve(StringRef host)
{
	addrinfo* hostent;
	getaddrinfo(host.c_str(), nullptr, nullptr, &hostent);
	IPAddress result;
	result.mAddress.sin_family = hostent->ai_protocol == IPPROTO_IPV6 ? (int)SocketAddressFamily::IP6 : (int)SocketAddressFamily::IP;
	result.mAddress.sin_addr = *reinterpret_cast<in_addr*>(hostent->ai_addr);
	freeaddrinfo(hostent);
	return result;
}
Example #17
0
bool IActBehavior::LoadFromXmlNode(pugi::xml_node node)
{
	RETURN_FALSE_IF_FALSE(IBehavior::LoadFromXmlNode(node));
	StringRef typeName = node.name();
	StringRef predicateId = node.attribute("Predicate").value();

	if (!predicateId.IsEmpty())
	{
		Log::FormatError("Invalid predicate:{} on {}", predicateId.c_str(), typeName.c_str());
		return false;
	}
	if (node.first_child() != nullptr)
	{
		Log::FormatError("Act behavior cannot have children. {}", typeName.c_str());
		return false;
	}

	return true;
}
Example #18
0
	String Internet::combineUrl(const StringRef& url, const StringRef& parent) {
		Stamina::RegEx regex;
		if (url.empty() || regex.match("#^\\w+://#", url.c_str())) {
			return url;
		}

		// wyci¹gamy poszczególne elementy URLa
		if (!regex.match("#^(\\w+://[^/]+/)([^\\?]+/)?([^\\?/]*)(\\?.*)?$#", parent.c_str()))
			return url;
		if (url.a_str()[0] == '.' && (url.length() < 2 || url.a_str()[1] != '.')) {
			// (http://..../) + (katalog/) + url bez kropki
			return regex[1] + regex[2] + url.substr(1);
		} else if (url.a_str()[0] == '/') {
			// (http://..../) + url bez kreski
			return regex[1] + url.substr(1);
		} else {
			// (http://..../) + (katalog/) + url
			return regex[1] + regex[2] + url;
		}
	}
Example #19
0
void SystemUI::ShowAlertView( StringRef text,Pattern::Action0 callback )
{
	if (mShowAlertViewCallback!=NULL)
	{
		mShowAlertViewCallback(text.c_str(),"Error");
	}
	if (callback!=NULL)
	{
		callback();
		assert(false);
	}
}
RegValue RegKey::getValue( StringRef value ) const
{
  DWORD dtype = 0;
  DWORD dlen = 4096;
  char data[dlen];
  LONG result = RegQueryValueEx( m_hkey, value.c_str(), NULL, &dtype, (BYTE*)data, &dlen );

  if( result != ERROR_SUCCESS )
    throw std::runtime_error( "error iterating values in " + m_name );

  return RegValue( value, data, dlen, dtype );
}
Example #21
0
void DateTime::SetTimeZone(StringRef timezone)
{
	//set TZ=tzn[+|-]hh[:mm[:ss]][dzn] 
	/*
	tzn
	Three-letter time-zone name, such as PST. You must specify the correct offset from local time to UTC.
	hh
	Difference in hours between UTC and local time. Sign (+) optional for positive values.
	mm
	Minutes. Separated from hh by a colon (:).
	ss
	Seconds. Separated from mm by a colon (:).
	dzn
	Three-letter daylight-saving-time zone such as PDT. If daylight saving time is never in effect in the locality, set TZ without a value for dzn. The C run-time library assumes the United States' rules for implementing the calculation of daylight saving time (DST).
	*/
#ifdef MEDUSA_WINDOWS
	_putenv_s("TZ", timezone.c_str());
	_tzset();
#else
	setenv("TZ", timezone.c_str(), 1);
	tzset();
#endif

}
Example #22
0
	int Internet::getUrlPort(const StringRef& url) {
		Stamina::RegEx regex;
		if (regex.match("#:([0-9])#", url.c_str()))
			return Stamina::chtoint( regex[1].c_str() );
		else {
			String protocol = getUrlProtocol(url);
			if(protocol == "http")
				return 80;
			else if(protocol == "ftp")
				return 21;
			else if(protocol == "https")
				return 443;
		}
		return -1;
	}
Example #23
0
// Check if the specified directory exists
// Warning: if 'path' has a trailing '/' or '\\' character, it will be removed!
bool MassStorage::DirectoryExists(const StringRef& path) const
{
	// Remove any trailing '/' from the directory name, it sometimes (but not always) confuses f_opendir
	const size_t len = path.strlen();
	if (len != 0 && (path[len - 1] == '/' || path[len - 1] == '\\'))
	{
		path.Truncate(len - 1);
	}

	DIR dir;
	const bool ok = (f_opendir(&dir, path.c_str()) == FR_OK);
	if (ok)
	{
		f_closedir(&dir);
	}
	return ok;
}
Example #24
0
	String format(const StringRef& fmt, Args... args) {
		const size_t num_args = sizeof...(args);
		String converted[num_args];
		convert_variadic_arguments_to_strings(converted, args...);
		StringBuffer buffer;
		const char* c = fmt.c_str();
		bool escaping = false;
		for (size_t i = 0; i < fmt.length(); ++i) {
			switch (c[i]) {
				case '\\': {
					if (escaping) { escaping = false; buffer.push('\\'); continue; }
					escaping = true;
					continue;
				}
				case '{': {
					if (!escaping) {
						size_t idx = 0;
						bool valid = true;
						bool anything = false;
						size_t j = i + 1;
						for (; j < fmt.length(); ++j) {
							if (is_numeric(c[j])) {
								idx *= 10;
								idx += c[j] - '0';
								anything = true;
							} else if (c[j] == '}') {
								break;
							} else {
								// non-numeric, non-terminator
								valid = false;
								break;
							}
						}
						if (valid && anything && idx < num_args) {
							buffer << converted[idx];
							i = j;
							continue;
						}
					}
				}
			}
			escaping = false;
			buffer.push(c[i]);
		}
		return buffer.to_string();
	}
Example #25
0
	Request::Request(const oConnection& connection, const StringRef& uri, Type type, const char* version, const char* referer, const char** acceptTypes, int flags) {
		this->_uri = RegEx::doReplace("#^[a-z]+://[^/]+#i" , "", uri.c_str() );
		this->_type = type;
		this->_connection = connection;
		const char* verb;
		switch (_type) {
			case typePost:
				verb = "POST";
				break;
			case typeHead:
				verb = "HEAD";
				break;
			default:
				verb = "GET";
		}
		_hRequest = HttpOpenRequest(connection->getHandle(), verb,
			_uri.empty() ? "/" : _uri.c_str(), version, referer, acceptTypes, flags, 1);
		if (!_hRequest) {
			throw ExceptionBadRequest();
		}
	}
Example #26
0
void SkeletonSlot::SetAttachment(const StringRef& attachmentName)
{
	if (attachmentName.IsEmpty())
	{
		SetAttachment(nullptr);
		return;
	}

	if (mAttachment != nullptr&&mAttachment->Name() == attachmentName)
	{
		return;
	}

	ISkeletonAttachmentModel* attachment = mSkeleton->AvatarModel()->FindAttachment(mModel, attachmentName);
	if (attachment == nullptr)
	{
		Log::AssertFailedFormat("Cannot find slot attachment:{}", attachmentName.c_str());
		return;
	}
	SetAttachment(attachment);
}
void ServerSideBrowserModel::getDirectoryItems(const Dir& dir,
                                               const xmms2::Expected<xmms2::List<xmms2::Dict>>& list)
{
    if (list.isError()) {
        directoryLoadFailed(dir, list.error().toString());
        return;
    }
    
    m_dir = dir;
    m_items.clear();
    
    // Explicitly add .. item
    if (!m_dir.isRootPath()) {
        m_items.emplace_back("..", true);
    }
    
    for (auto it = list->getIterator(); it.isValid(); it.next()) {
        bool ok = false;
        xmms2::Dict dict = it.value(&ok);
        if (NCXMMS2_UNLIKELY(!ok))
            continue;
        
        StringRef path = dict.value<StringRef>("path");
        if (NCXMMS2_UNLIKELY(path.isNull()))
            continue;
        
        if (NCXMMS2_UNLIKELY(path == "." || path == ".."))
            continue;
        
        bool isDir = dict.value<int>("isdir", 0);
        m_items.emplace_back(xmms2::getFileNameFromUrl(xmms2::decodeUrl(path.c_str())), isDir);
    }
    
    std::sort(m_items.begin(), m_items.end());
    
    reset();
    directoryLoaded(m_dir);
}
Example #28
0
bool ScriptModule::NewObjects(StringRef className, size_t count, List<ScriptObject*>& outObjects)
{
	outObjects.Clear();
	asIObjectType* scriptObjectType = mScriptModule->GetObjectTypeByName(className.c_str());
	RETURN_FALSE_IF_NULL(scriptObjectType);

	HeapString factoryName = className;
	factoryName += "@ ";
	factoryName += className;
	factoryName += "()";
	asIScriptFunction* factory = scriptObjectType->GetFactoryByDecl(factoryName.c_str());
	RETURN_FALSE_IF_NULL(factory);
	asIScriptContext* context = ScriptEngine::Instance().GetScriptContext();

	List<ScriptObject*> result;
	FOR_EACH_SIZE(i, count)
	{
		context->Prepare(factory);
		context->Execute();
		asIScriptObject* scriptObject = *(asIScriptObject**)context->GetAddressOfReturnValue();
		ScriptObject* temp = new ScriptObject(scriptObject);
		outObjects.Add(temp);
	}
Example #29
0
bool ZipReader::Open( StringRef path)
{
	Close();
	mZipFile = unzOpen(path.c_str());
	if (mZipFile!=nullptr)
	{
		StackString<Path::MaxPathLength> outFileName;
		//unz_file_info64 outFileInfo;

		int err = unzGoToFirstFile(mZipFile);
		//int err = unzGoToFirstFile(mZipFile, &outFileInfo, outFileName.c_str(), static_cast<uLong>((outFileName.Size() - 1)*sizeof(char)));

		outFileName.ForceUpdateLength();
		while (err == UNZ_OK)
		{
			unz_file_pos posInfo;
			int posErr = unzGetFilePos(mZipFile, &posInfo);
			if (posErr == UNZ_OK)
			{
				//TODO: invoke unzGetCurrentFileInfo
				ZipFileInfo entry;
				entry.Pos = posInfo;
				//entry.UncompressedSize = (uLong)outFileInfo.uncompressed_size;
				mFileDict.Add(outFileName.ToString(),entry);
			}
			err = unzGoToNextFile(mZipFile);
			//err = unzGoToNextFile(mZipFile, &outFileInfo, outFileName.c_str(), static_cast<uLong>((outFileName.Size() - 1)*sizeof(char)));

			outFileName.ForceUpdateLength();
		}


		return true;
	}

	return false;
}
Example #30
0
SqlException::SqlException(const StringRef& initialMessage)
    :std::exception(initialMessage.c_str())
{
}