Пример #1
0
/// Convert the path separator characters in the given object path to valid directory delimiters for the current
/// platform.
///
/// Note that objects with instance indices are not supported for file paths.  Instance index delimiters will not be
/// converted, and may be invalid file name characters on certain platforms.
///
/// @param[out] rFilePath     Converted file path.
/// @param[in]  rPackagePath  Asset path string to convert (can be the same as the output file path).
void AssetPath::ConvertStringToFilePath( String& rFilePath, const String& rPackagePath )
{
#if HELIUM_PACKAGE_PATH_CHAR != HELIUM_PATH_SEPARATOR_CHAR && HELIUM_PACKAGE_PATH_CHAR != HELIUM_ALT_PATH_SEPARATOR_CHAR
	size_t pathLength = rPackagePath.GetSize();
	if( &rFilePath == &rPackagePath )
	{
		for( size_t characterIndex = 0; characterIndex < pathLength; ++characterIndex )
		{
			char& rCharacter = rFilePath[ characterIndex ];
			if( rCharacter == HELIUM_PACKAGE_PATH_CHAR || rCharacter == HELIUM_OBJECT_PATH_CHAR )
			{
				rCharacter = Helium::s_InternalPathSeparator;
			}
		}
	}
	else
	{
		rFilePath.Remove( 0, rFilePath.GetSize() );
		rFilePath.Reserve( rPackagePath.GetSize() );

		for( size_t characterIndex = 0; characterIndex < pathLength; ++characterIndex )
		{
			char character = rPackagePath[ characterIndex ];
			if( character == HELIUM_PACKAGE_PATH_CHAR || character == HELIUM_OBJECT_PATH_CHAR )
			{
				character = Helium::s_InternalPathSeparator;
			}

			rFilePath.Add( character );
		}
	}
#else
	rFilePath = rPackagePath;
#endif
}
Пример #2
0
/// Write the serialized property data to the given stream.
///
/// @param[in] pStream  Stream to which the property data should be written.
void BinarySerializer::WriteToStream( Stream* pStream ) const
{
    HELIUM_ASSERT( pStream );

    // Write the type and object link tables first.
    uint32_t dependencyCount;
    uint_fast32_t dependencyCountFast;

    HELIUM_ASSERT( m_typeDependencies.GetSize() <= UINT32_MAX );
    dependencyCount = static_cast< uint32_t >( m_typeDependencies.GetSize() );
    pStream->Write( &dependencyCount, sizeof( dependencyCount ), 1 );

    dependencyCountFast = dependencyCount;
    for( uint_fast32_t dependencyIndex = 0; dependencyIndex < dependencyCountFast; ++dependencyIndex )
    {
        const tchar_t* pTypeName = *m_typeDependencies[ dependencyIndex ];

        size_t typeNameSize = StringLength( pTypeName );
        HELIUM_ASSERT( typeNameSize <= UINT32_MAX );
        uint32_t typeNameSize32 = static_cast< uint32_t >( typeNameSize );
        pStream->Write( &typeNameSize32, sizeof( typeNameSize32 ), 1 );
        if( typeNameSize )
        {
            pStream->Write( pTypeName, sizeof( tchar_t ), typeNameSize );
        }
    }

    HELIUM_ASSERT( m_objectDependencies.GetSize() <= UINT32_MAX );
    dependencyCount = static_cast< uint32_t >( m_objectDependencies.GetSize() );
    pStream->Write( &dependencyCount, sizeof( dependencyCount ), 1 );

    String pathString;

    dependencyCountFast = dependencyCount;
    for( uint_fast32_t dependencyIndex = 0; dependencyIndex < dependencyCountFast; ++dependencyIndex )
    {
        m_objectDependencies[ dependencyIndex ].ToString( pathString );

        size_t pathStringSize = pathString.GetSize();
        HELIUM_ASSERT( pathStringSize <= UINT32_MAX );
        uint32_t pathStringSize32 = static_cast< uint32_t >( pathString.GetSize() );
        pStream->Write( &pathStringSize32, sizeof( pathStringSize32 ), 1 );
        if( pathStringSize )
        {
            pStream->Write( pathString.GetData(), sizeof( tchar_t ), pathStringSize );
        }
    }

    // Write the serialized data to the output stream.
    pStream->Write( m_propertyStreamBuffer.GetData(), 1, m_propertyStreamBuffer.GetSize() );
}
Пример #3
0
uint CodeNode::SerializeFrom (const String& source, uint start, uint end)
{
	if (start < end)
	{
		if (end > source.GetSize()) end = source.GetSize();
		while (start < end && source[start] < 33) ++start;

		uint lineStart (start);
		bool prag = (source[start] == '#');

		for (; start <= end; ++start)
		{
			char ch = source[start];

			if ((!prag && ch == ';') || (prag && ch < ' ' && ch != '\t'))
			{
				source.GetTrimmed(mLine, lineStart, start++);
				mLine.TrimCode();
				return start;
			}

			if (ch == '{')
			{
				source.GetTrimmed(mLine, lineStart, start++);
				mLine.TrimCode();

				while (start < end)
				{
					CodeNode& code = mChildren.Expand();
					start = code.SerializeFrom(source, start, end);

					if (code.mLine.IsEmpty())
					{
						mChildren.Shrink();
						break;
					}
				}
				return start;
			}

			if (start < end && source[start] == '}')
			{
				return ++start;
			}
		}
	}
	return end;
}
Пример #4
0
bool String::operator < (const String& compareTo) const
{
	bool lessThan = false;
	if (GetSize() == compareTo.GetSize())
		return lessThan;
	return !(*this > compareTo);
}
Пример #5
0
	/*!
	* \brief Changes the debugging name associated to a thread
	*
	* Changes the debugging name associated with a particular thread, and may helps with debugging tools.
	*
	* \param name The new name of the thread
	*
	* \remark Due to system limitations, thread name cannot exceed 15 characters (excluding null-terminator)
	*
	* \see SetCurrentThreadName
	*/
	void Thread::SetName(const String& name)
	{
		NazaraAssert(m_impl, "Invalid thread");
		NazaraAssert(name.GetSize() < 16, "Thread name is too long");

		m_impl->SetName(name);
	}
void      StringBuffer::operator = (const String& src)
{
    const size_t size = src.GetSize();
    Resize(size);
    OVR_ASSERT((pData != NULL) || (size == 0));
    memcpy(pData, src.ToCStr(), size);
}
Пример #7
0
String ExtractDirectory( const String & s )
{
	const int l = s.GetSize();
	if ( l == 0 )
	{
		return String( "" );
	}

	int	end;
	if ( s[ l - 1 ] == '/' )
	{	// directory ends in a slash
		end = l - 1;
	}
	else
	{
		for ( end = l - 1; end > 0 && s[ end ] != '/'; end-- )
			;
		if ( end == 0 )
		{
			end = l - 1;
		}
	}
	int	start;
	for ( start = end - 1; start > -1 && s[ start ] != '/'; start-- )
		;
	start++;

	return String( &s[ start ], end - start );
}
Пример #8
0
bool String::operator > (const String& compareTo) const
{
	bool greaterThan = false;
	if (GetSize() > compareTo.GetSize())
		greaterThan = true;
	return greaterThan;

}
Пример #9
0
void CodeNode::SerializeFrom (const String& source)
{
	uint start(0), end (source.GetSize());

	while (start < end)
	{
		start = mChildren.Expand().SerializeFrom(source, start, end);
	}
}
Пример #10
0
void WOFile::WriteLine(const String& sLine)
{
	if(!m_File)
	{
		throw FileError("NULL File pointer", EL_BAD, "WOFile::WriteLine", "File hasn't been opened!");
	}

	String sTemp = sLine + "\r\n";
	WriteBuffer((const void*)sTemp.c_str(), sTemp.GetSize());
}
Пример #11
0
/// Generate a string representation of this object path with all package and object delimiters converted to valid
/// directory delimiters for the current platform.
///
/// @param[out] rString  File path string representation of this path.
void AssetPath::ToFilePathString( String& rString ) const
{
	rString.Remove( 0, rString.GetSize() );

	if( !m_pEntry )
	{
		return;
	}

	EntryToFilePathString( *m_pEntry, rString );
}
Пример #12
0
/**
* @date     2011/12/21
*
*  Handler of a request. The WebService request si built from the request, and
*  forwarded to the correct WsInterface.
*
******************************************************************************/
int32_t  WsHandler::RequestReceived(const HttpdRequest &Request,
                                    HttpdRequest *Answer)
{
   int32_t i_Ret = -1;
   ListIterator<AList<WsInterface*>, WsInterface*>  Iterator;
   WsInterface    *p_Interface = NULL;
   const String   *RequestInterface;

   if(HandleCors(Request, Answer) == 0)
      return(0);

   DynObject   Params;
   const uint8_t *Payload;
   uint32_t i_Length;
   i_Ret = Request.GetPayload(&Payload, &i_Length);
   if(i_Ret == 0)
   {
      JsonFlattener Flattener;
      const String PayloadString((const char*)(Payload), i_Length);

      i_Ret = Flattener.UnFlatten(&PayloadString, &Params);
      if(i_Ret == 0)
      {
         i_Ret = Params.FindString("InterfaceName", &RequestInterface);
      }
   }
   if(i_Ret != 0)
      return(-1);

   Iterator.SetTo(&InterfaceList);
   Iterator.First();
   while(Iterator.IsDone() == false)
   {
      if( (Iterator.GetItem(&p_Interface) == 0) && (p_Interface != NULL) )
      {
         if(p_Interface->GetName() == *RequestInterface)
         {
            String   AnswerString;
            i_Ret = p_Interface->Call(Params, &AnswerString);
            if(i_Ret == 0)
            {
               i_Ret = Answer->SetPayload((const uint8_t*)AnswerString.GetString(),
                                          AnswerString.GetSize());
            }
            break;
         }
      }
      Iterator.Next();
   }

   return(i_Ret);
}
Пример #13
0
Value BoundedExpr::Evaluate(SymbolTable* scope, EvalContext& context, bool asbool)
{
	/// Scope override; must do this for every expression that might contain an identifier
	if(this->scope != NULL)
		scope = this->scope;
	// TODO: there really has to be a better way to handle these scope overrides.
	//  Having to put this if statement at the top of certain evaluate methods is kludgy.
	//  Probably the logic for deciding the evaluation scope of a node should be at
	//  a higher level, and all nodes should have their scope of evaluation set that way.

	String* value = new String();

	Value expr_val = expr->Evaluate(scope, context);

	int pos;
	if(index < 0)
		pos = 0;
	else
		pos = size * index;

	try
	{
		// We've specified that any out-of-range access should be filled in
		// with zeroes, so we do a bit of bounds checking here
		String s = expr_val.ToCodeString();

		int over = std::max(0, pos + size - (signed)s.GetSize());
		int valid_size = std::max(0, size - over);

		if(valid_size > 0) {
			// We really ought to make a "substring constructor" --
			// we do this fairly often and it involves an unfortunate
			// amount of copying.
			*value = s.Substring(pos, valid_size);
		}
		for(int i = 0; i < size - valid_size; ++i)
			value->Byte(0);
	}
	catch(Exception& e)
	{
		Error(e.GetMessage());
	}

	return Value(value);
}
Пример #14
0
//Comparison operators: strings are equal when they are the same size
//and they contain the same characters
bool String::operator == (const String& compareTo) const
{
	bool sameSize = true;
	if (GetSize() == compareTo.GetSize() )
	{
		for (int i = 0; i < GetSize(); i++)
		{
			if (Text[i] != compareTo.Text[i])
			{
				sameSize = false;
				break;
			}
		}
	}
	else
		sameSize = false;

	return sameSize;
}
Пример #15
0
String ExtractFile( const String & s )
{
	const int l = s.GetSize();
	if ( l == 0 )
	{
		return String( "" );
	}

	int	end = l;
	if ( s[ l - 1 ] == '/' )
	{	// directory ends in a slash
		end = l - 1;
	}

	int	start;
	for ( start = end - 1; start > -1 && s[ start ] != '/'; start-- )
		;
	start++;

	return String( &s[ start ], end - start );
}
Пример #16
0
//Concatentation operator appends appendix to this String and returns a new string
String String::operator + (const String& appendix) const
{

	// -1 for the '/0' in this
	int newStringLength = GetSize() + appendix.GetSize() + 1 ;

	String newString(newStringLength);

	for (int i = 0; i < GetSize(); i++)
		newString[i] = Text[i];

	int counter = 0;
	for (int i = GetSize(); i < newStringLength - 1; i++)
	{
		newString[i] = appendix.Text[counter];
		counter++;
	}
	
	newString[newStringLength - 1] = '\0';

	return newString;
}
Пример #17
0
	Thread InjectDll(Process& process, const String& dllPath)
	{
		const auto size = (dllPath.GetSize() + 1) * sizeof(TChar);
		auto remotePath = ::VirtualAllocEx(
			process.m_handle,
			NULL,
			size,
			MEM_COMMIT,
			PAGE_READWRITE);
		if (!remotePath)
		{
			THROW_LAST_ERROR_EXCEPTION();
		}

		if (!::WriteProcessMemory(process.m_handle, remotePath, dllPath.GetBuffer(), size, NULL))
		{
			THROW_LAST_ERROR_EXCEPTION();
		}

		auto kernel32 = ::GetModuleHandle(_T("Kernel32"));
		if (!kernel32)
		{
			THROW_LAST_ERROR_EXCEPTION();
		}

#ifdef _UNICODE
		auto loadLibrary = "LoadLibraryW";
#else
		auto loadLibrary = "LoadLibraryA";
#endif

		return process.CreateRemoteThread(
			(LPTHREAD_START_ROUTINE) ::GetProcAddress(kernel32, loadLibrary),
			remotePath);
		// TODO: We must free memory at the end of thread
	}
Пример #18
0
LSTATUS
NTAPI
QqRegQueryValueExW(
    HKEY    hKey,
    PCWSTR  ValueName,
    PULONG  Reserved,
    PULONG  Type,
    PBYTE   Data,
    PULONG  DataSize
)
{
    if (hKey != nullptr)
        return StubRegQueryValueExW(hKey, ValueName, Reserved, Type, Data, DataSize);

    if (StrICompareW(ValueName, L"QQProtectDir") == 0)
    {
        String qqpath;
        ULONG_PTR Length;

        Rtl::GetModuleDirectory(qqpath, nullptr);

        qqpath += L"..\\";

        Length = (ULONG_PTR)(qqpath.GetSize() + 2);
        Length = ML_MIN(Length, *DataSize);
        CopyMemory(Data, (PWSTR)qqpath, Length);
        *DataSize = Length;

        if (Type != nullptr)
            *Type = REG_SZ;

        return NO_ERROR;
    }

    return ERROR_INVALID_HANDLE;
}
Пример #19
0
void OptionSelectionMenu::Render(RenderDevice* prender, String title)
{
    // If we are invisible, render shortcut notifications.
    // Both child and parent have visible == true even if only child is shown.
    if (DisplayState == Display_None)
    {
        renderShortcutChangeMessage(prender);
        return;
    }

    title += Label;

    // Delegate to sub-menu if active.
    if (GetSubmenu() != NULL)
    {
        if (title.GetSize() > 0)
            title += " > ";

        GetSubmenu()->Render(prender, title);
        return;
    }

    Color focusColor(180, 80, 20, 210);
    Color pickedColor(120, 55, 10, 140);
    Color titleColor(0x18, 0x1A, 0x4D, 210);
    Color titleOutlineColor(0x18, 0x18, 0x18, 240);

    float    labelsSize[2]     = {0.0f, 0.0f};
    float    bufferSize[2]     = {0.0f, 0.0f};
    float    valuesSize[2]     = {0.0f, 0.0f};
    float    maxValueWidth     = 0.0f;

    UPInt    selection[2] = { 0, 0 };
    Vector2f labelSelectionRect[2];
    Vector2f valueSelectionRect[2];
    bool     havelLabelSelection = false;
    bool     haveValueSelection = false;

    float textSize = 22.0f;
    prender->MeasureText(&DejaVu, "      ", textSize, bufferSize);

    String values;
    String menuItems;

    int highlightIndex = 0;
    if (DisplayState == Display_Menu)
    {
        highlightIndex = SelectedIndex;
        for (UInt32 i = 0; i < Items.GetSize(); i++)
        {
            if (i > 0)
                values += "\n";
            values += Items[i]->GetValue();
        }

        for (UInt32 i = 0; i < Items.GetSize(); i++)
        {
            if (i > 0)
                menuItems += "\n";
            menuItems += Items[i]->GetLabel();
        }
    }
    else
    {
        values = Items[SelectedIndex]->GetValue();
        menuItems = Items[SelectedIndex]->GetLabel();
    }

    // Measure labels
    const char* menuItemsCStr = menuItems.ToCStr();
    havelLabelSelection = FindLineCharRange(menuItemsCStr, highlightIndex, selection);
    prender->MeasureText(&DejaVu, menuItemsCStr, textSize, labelsSize,
                         selection, labelSelectionRect);

    // Measure label-to-value gap
    const char* valuesCStr = values.ToCStr();
    haveValueSelection = FindLineCharRange(valuesCStr, highlightIndex, selection);
    prender->MeasureText(&DejaVu, valuesCStr, textSize, valuesSize, selection, valueSelectionRect);

    // Measure max value size (absolute size varies, so just use a reasonable max)
    maxValueWidth = prender->MeasureText(&DejaVu, "Max value width", textSize);
    maxValueWidth = Alg::Max(maxValueWidth, valuesSize[0]);

    Vector2f borderSize(4.0f, 4.0f);
    Vector2f totalDimensions = borderSize * 2 + Vector2f(bufferSize[0], 0) + Vector2f(maxValueWidth, 0)
                                + Vector2f(labelsSize[0], labelsSize[1]);
    
    Vector2f fudgeOffset= Vector2f(10.0f, 25.0f);  // This offset looks better
    Vector2f topLeft    = (-totalDimensions / 2.0f)  + fudgeOffset;    
    Vector2f bottomRight = topLeft + totalDimensions;

    // If displaying a single item, shift it down.
    if (DisplayState == Display_SingleItem)
    {
        topLeft.y     += textSize * 7;
        bottomRight.y += textSize * 7;
    }

    prender->FillRect(topLeft.x, topLeft.y, bottomRight.x, bottomRight.y, Color(40,40,100,210));

    Vector2f labelsPos = topLeft + borderSize;
    Vector2f valuesPos = labelsPos + Vector2f(labelsSize[0], 0) + Vector2f(bufferSize[0], 0);

    // Highlight selected label
    Vector2f selectionInset = Vector2f(0.3f, 2.0f);
    if (DisplayState == Display_Menu)
    {
        Vector2f labelSelectionTopLeft = labelsPos + labelSelectionRect[0] - selectionInset;
        Vector2f labelSelectionBottomRight = labelsPos + labelSelectionRect[1] + selectionInset;

        prender->FillRect(labelSelectionTopLeft.x, labelSelectionTopLeft.y,
                          labelSelectionBottomRight.x, labelSelectionBottomRight.y,
                          SelectionActive ? pickedColor : focusColor);
    }

    // Highlight selected value if active
    if (SelectionActive)
    {
        Vector2f valueSelectionTopLeft = valuesPos + valueSelectionRect[0] - selectionInset;
        Vector2f valueSelectionBottomRight = valuesPos + valueSelectionRect[1] + selectionInset;
        prender->FillRect(valueSelectionTopLeft.x, valueSelectionTopLeft.y,
                          valueSelectionBottomRight.x, valueSelectionBottomRight.y,
                          focusColor);
    }

    // Measure and draw title
    if (DisplayState == Display_Menu && title.GetLength() > 0)
    {
        Vector2f titleDimensions;
        prender->MeasureText(&DejaVu, title.ToCStr(), textSize, &titleDimensions.x);
        Vector2f titleTopLeft = topLeft - Vector2f(0, borderSize.y) * 2 - Vector2f(0, titleDimensions.y);
        titleDimensions.x = totalDimensions.x;
        
        prender->FillRect(titleTopLeft.x, titleTopLeft.y,
                          titleTopLeft.x + totalDimensions.x,
                          titleTopLeft.y + titleDimensions.y + borderSize.y * 2,
                          titleOutlineColor);
        
        prender->FillRect(titleTopLeft.x + borderSize.x / 2, titleTopLeft.y + borderSize.y / 2,
                          titleTopLeft.x + totalDimensions.x - borderSize.x / 2,
                          titleTopLeft.y + borderSize.y / 2 + titleDimensions.y,
                          titleColor);
                          
        prender->RenderText(&DejaVu, title.ToCStr(), titleTopLeft.x + borderSize.x,
                            titleTopLeft.y + borderSize.y, textSize, Color(255,255,0,210));
    }

    prender->RenderText(&DejaVu, menuItemsCStr, labelsPos.x, labelsPos.y, textSize, Color(255,255,0,210));

    prender->RenderText(&DejaVu, valuesCStr, valuesPos.x, valuesPos.y, textSize, Color(255,255,0,210));
}
	bool PluginManager::Mount(const String& pluginPath, bool appendExtension)
	{
		if (!Initialize())
		{
			NazaraError("Failed to initialize PluginManager");
			return false;
		}

		String path = pluginPath;
		if (appendExtension && !path.EndsWith(NAZARA_DYNLIB_EXTENSION))
			path += NAZARA_DYNLIB_EXTENSION;

		bool exists = false;
		if (!File::IsAbsolute(path))
		{
			for (const String& dir : s_directories)
			{
				String testPath;
				testPath.Reserve(dir.GetSize() + path.GetSize() + 10);

				testPath = dir;
				testPath += NAZARA_DIRECTORY_SEPARATOR;
				testPath += path;

				if (File::Exists(testPath))
				{
					path = testPath;
					exists = true;
					break;
				}
			}
		}
		else if (File::Exists(path))
			exists = true;

		if (!exists)
		{
			NazaraError("Failed to find plugin file");
			return false;
		}

		std::unique_ptr<DynLib> library(new DynLib);
		if (!library->Load(path))
		{
			NazaraError("Failed to load plugin");
			return false;
		}

		PluginLoad func = reinterpret_cast<PluginLoad>(library->GetSymbol("PluginLoad"));
		if (!func)
		{
			NazaraError("Failed to get symbol PluginLoad");
			return false;
		}

		if (!func())
		{
			NazaraError("Plugin failed to load");
			return false;
		}

		s_plugins[pluginPath] = library.release();

		return true;
	}
Пример #21
0
	void LuaState::PushString(const String& str) const
	{
		lua_pushlstring(m_state, str.GetConstBuffer(), str.GetSize());
	}
Пример #22
0
/// Add or update an entry in the cache.
///
/// @param[in] path          GameObject path.
/// @param[in] subDataIndex  Sub-data index associated with the cached data.
/// @param[in] pData         Data to cache.
/// @param[in] timestamp     Timestamp value to associate with the entry in the cache.
/// @param[in] size          Number of bytes to cache.
///
/// @return  True if the cache was updated successfully, false if not.
bool Cache::CacheEntry(
                       GameObjectPath path,
                       uint32_t subDataIndex,
                       const void* pData,
                       int64_t timestamp,
                       uint32_t size )
{
    HELIUM_ASSERT( pData || size == 0 );

	Status status;
	status.Read( m_cacheFileName.GetData() );
	int64_t cacheFileSize = status.m_Size;
    uint64_t entryOffset = ( cacheFileSize == -1 ? 0 : static_cast< uint64_t >( cacheFileSize ) );

    HELIUM_ASSERT( m_pEntryPool );
    Entry* pEntryUpdate = m_pEntryPool->Allocate();
    HELIUM_ASSERT( pEntryUpdate );
    pEntryUpdate->offset = entryOffset;
    pEntryUpdate->timestamp = timestamp;
    pEntryUpdate->path = path;
    pEntryUpdate->subDataIndex = subDataIndex;
    pEntryUpdate->size = size;

    uint64_t originalOffset = 0;
    int64_t originalTimestamp = 0;
    uint32_t originalSize = 0;

    EntryKey key;
    key.path = path;
    key.subDataIndex = subDataIndex;

    EntryMapType::Accessor entryAccessor;
    bool bNewEntry = m_entryMap.Insert( entryAccessor, KeyValue< EntryKey, Entry* >( key, pEntryUpdate ) );
    if( bNewEntry )
    {
        HELIUM_TRACE( TraceLevels::Info, TXT( "Cache: Adding \"%s\" to cache \"%s\".\n" ), *path.ToString(), *m_cacheFileName );

        m_entries.Push( pEntryUpdate );
    }
    else
    {
        HELIUM_TRACE( TraceLevels::Info, TXT( "Cache: Updating \"%s\" in cache \"%s\".\n" ), *path.ToString(), *m_cacheFileName );

        m_pEntryPool->Release( pEntryUpdate );

        pEntryUpdate = entryAccessor->Second();
        HELIUM_ASSERT( pEntryUpdate );

        originalOffset = pEntryUpdate->offset;
        originalTimestamp = pEntryUpdate->timestamp;
        originalSize = pEntryUpdate->size;

        if( originalSize < size )
        {
            pEntryUpdate->offset = entryOffset;
        }
        else
        {
            entryOffset = originalOffset;
        }

        pEntryUpdate->timestamp = timestamp;
        pEntryUpdate->size = size;
    }

    AsyncLoader& rLoader = AsyncLoader::GetStaticInstance();

    rLoader.Lock();

    bool bCacheSuccess = true;

    FileStream* pCacheStream = FileStream::OpenFileStream( m_cacheFileName, FileStream::MODE_WRITE, false );
    if( !pCacheStream )
    {
        HELIUM_TRACE( TraceLevels::Error, TXT( "Cache: Failed to open cache \"%s\" for writing.\n" ), *m_cacheFileName );

        bCacheSuccess = false;
    }
    else
    {
        HELIUM_TRACE(
            TraceLevels::Info,
            TXT( "Cache: Caching \"%s\" to \"%s\" (%" ) TPRIu32 TXT( " bytes @ offset %" ) TPRIu64 TXT( ").\n" ),
            *path.ToString(),
            *m_cacheFileName,
            size,
            entryOffset );

        uint64_t seekOffset = static_cast< uint64_t >( pCacheStream->Seek(
            static_cast< int64_t >( entryOffset ),
            SeekOrigins::SEEK_ORIGIN_BEGIN ) );
        if( seekOffset != entryOffset )
        {
            HELIUM_TRACE( TraceLevels::Error, TXT( "Cache: Cache file offset seek failed.\n" ) );

            if( bNewEntry )
            {
                m_entries.Pop();
                m_entryMap.Remove( entryAccessor );
                m_pEntryPool->Release( pEntryUpdate );
            }
            else
            {
                pEntryUpdate->offset = originalOffset;
                pEntryUpdate->timestamp = originalTimestamp;
                pEntryUpdate->size = originalSize;
            }

            bCacheSuccess = false;
        }
        else
        {
            size_t writeSize = pCacheStream->Write( pData, 1, size );
            if( writeSize != size )
            {
                HELIUM_TRACE(
                    TraceLevels::Error,
                    ( TXT( "Cache: Failed to write %" ) TPRIu32 TXT( " bytes to cache \"%s\" (%" ) TPRIuSZ
                    TXT( " bytes written).\n" ) ),
                    size,
                    *m_cacheFileName,
                    writeSize );

                if( bNewEntry )
                {
                    m_entries.Pop();
                    m_entryMap.Remove( entryAccessor );
                    m_pEntryPool->Release( pEntryUpdate );
                }
                else
                {
                    pEntryUpdate->offset = originalOffset;
                    pEntryUpdate->timestamp = originalTimestamp;
                    pEntryUpdate->size = originalSize;
                }

                bCacheSuccess = false;
            }
            else
            {
                HELIUM_TRACE( TraceLevels::Info, TXT( "Cache: Rewriting TOC file \"%s\".\n" ), *m_tocFileName );

                FileStream* pTocStream = FileStream::OpenFileStream( m_tocFileName, FileStream::MODE_WRITE, true );
                if( !pTocStream )
                {
                    HELIUM_TRACE( TraceLevels::Error, TXT( "Cache: Failed to open TOC \"%s\" for writing.\n" ), *m_tocFileName );
                }
                else
                {
                    BufferedStream* pBufferedStream = new BufferedStream( pTocStream );
                    HELIUM_ASSERT( pBufferedStream );

                    pBufferedStream->Write( &TOC_MAGIC, sizeof( TOC_MAGIC ), 1 );
                    pBufferedStream->Write( &sm_Version, sizeof( sm_Version ), 1 );

                    uint32_t entryCount = static_cast< uint32_t >( m_entries.GetSize() );
                    pBufferedStream->Write( &entryCount, sizeof( entryCount ), 1 );

                    String entryPath;
                    uint_fast32_t entryCountFast = entryCount;
                    for( uint_fast32_t entryIndex = 0; entryIndex < entryCountFast; ++entryIndex )
                    {
                        Entry* pEntry = m_entries[ entryIndex ];
                        HELIUM_ASSERT( pEntry );

                        pEntry->path.ToString( entryPath );
                        HELIUM_ASSERT( entryPath.GetSize() < UINT16_MAX );
                        uint16_t pathSize = static_cast< uint16_t >( entryPath.GetSize() );
                        pBufferedStream->Write( &pathSize, sizeof( pathSize ), 1 );

                        pBufferedStream->Write( *entryPath, sizeof( tchar_t ), pathSize );

                        pBufferedStream->Write( &pEntry->subDataIndex, sizeof( pEntry->subDataIndex ), 1 );

                        pBufferedStream->Write( &pEntry->offset, sizeof( pEntry->offset ), 1 );
                        pBufferedStream->Write( &pEntry->timestamp, sizeof( pEntry->timestamp ), 1 );
                        pBufferedStream->Write( &pEntry->size, sizeof( pEntry->size ), 1 );
                    }

                    delete pBufferedStream;
                    delete pTocStream;
                }
            }
        }

        delete pCacheStream;
    }

    rLoader.Unlock();

    return bCacheSuccess;
}
Пример #23
0
Value IfExpr::Evaluate(SymbolTable *env, EvalContext& context, bool asbool)
{
	if(this->scope != NULL)
		env = this->scope;

	/*
	 * Lowering an if statement:
	 *
	 *  [condition]
	 *  [iffalse goto falselbl]
	 *  [thenstmt]
	 *  [goto endlbl]
	 * falselbl:
	 *  [elsestmt]
	 * endlbl:
	 */

	String* value = new String();
	
	// Create internal labels
	string labelbase = context.GetUniqueLabelName();
	Anchor* endanchor = new Anchor(labelbase + ".end");
	Anchor* falseanchor = new Anchor(labelbase + ".false");

	// First, we evaluate the condition
	Value cond_val = condition->Evaluate(env, context, true);

	// TODO: this might be an opportunity to do some typechecking on the returned value,
	// instead of just converting it to a string. Maybe some warnings would be appropriate?
	// (i.e., conditioning on a number value, which is almost always meaningless)

	// append cond_val to the output:
	value->Append(cond_val.ToCodeString());

	// Then, we output an "iffalse goto false" instruction, and register a jump reference
	value->Code("1B 02 FF FF FF FF");
	value->AddReference(value->GetSize() - 4, falseanchor);

	// Evaluate the "then" statement
	Value then_val = thenexpr->Evaluate(env, context);
	value->Append(then_val.ToCodeString());


	// Add a "goto end"
	// TODO: strictly speaking, we can dispense with this last goto when
	// there is no 'else' clause. We'll leave it here for now until we
	// get the first round of regression tests in place, and then we'll
	// update it along with the other evaluation refactoring.
	value->Code("0A FF FF FF FF");
	value->AddReference(value->GetPos() - 4, endanchor);

	// Set the position of the false anchor within the string
	value->AddAnchor(falseanchor);

	// Evaluate the "else" statement
	if(elseexpr) {
		Value else_val = elseexpr->Evaluate(env, context);
		value->Append(else_val.ToCodeString());
	}

	// Set the position of the "end" label
	value->AddAnchor(endanchor);

	return Value(value);
}
void      StringBuffer::operator = (const String& src)
{
    Resize(src.GetSize());
    memcpy(pData, src.ToCStr(), src.GetSize());
}
StringBuffer::StringBuffer(const String& src)
    : pData(NULL), Size(0), BufferSize(0), GrowSize(OVR_SBUFF_DEFAULT_GROW_SIZE), LengthIsSize(false)
{
    AppendString(src.ToCStr(), src.GetSize());
}
Пример #26
0
String Texture2D::Reload(const String& filePath, SupportedFileTypes fileType)
{
    if (fileType == UNKNOWN)
    {
        if (filePath.GetSize() < 4)
            return "File-name was too short to infer a type";

        String extension = filePath.SubStr(filePath.GetSize() - 4, 4);

        if (extension == ".png")
            fileType = PNG;
        else if (extension == ".bmp")
            fileType = BMP;
        else
            return "Couldn't infer type from file name";
    }

    switch (fileType)
    {
        case BMP: {

            unsigned long width;
            long height;
            unsigned char *reds,
                          *greens,
                          *blues;
            if (bmp_read(filePath.CStr(), &width, &height, &reds, &greens, &blues))
            {
                return "Error reading the BMP file";
            }

            Resize(width, height);

            //Convert to texture data.
            float invMaxVal = 1.0f / (float)std::numeric_limits<unsigned char>::max();
            for (long y = 0; y < height; ++y)
            {
                for (unsigned long x = 0; x < width; ++x)
                {
                    long i = x + (y * width);
                    Vector3f col((float)reds[i] * invMaxVal,
                                 (float)greens[i] * invMaxVal,
                                 (float)blues[i] * invMaxVal);
                    SetColor(x, y, col);
                }
            }
            } break;

        case PNG: {

            std::vector<unsigned char> bytes;
            unsigned width, height;
            unsigned errCode = lodepng::decode(bytes, width, height, filePath.CStr());
            if (errCode != 0)
            {
                return String("Error reading the PNG file: ") + lodepng_error_text(errCode);
            }

            Resize(width, height);

            //Convert to texture data.
            float invMaxVal = 1.0f / (float)std::numeric_limits<unsigned char>::max();
            for (size_t y = 0; y < height; ++y)
            {
                size_t indexOffset = y * width * 4;

                for (size_t x = 0; x < width; ++x)
                {
                    size_t indexOffset2 = indexOffset + (x * 4);

                    SetColor(x, height - y - 1,
                             Vector3f((float)bytes[indexOffset2] * invMaxVal,
                                      (float)bytes[indexOffset2 + 1] * invMaxVal,
                                      (float)bytes[indexOffset2 + 2] * invMaxVal));
                }
            }
            } break;

        default:
            return String("Unexpected file type enum value: ") + String(fileType);
    }

    return "";
}
Пример #27
0
void INIFile::SetINI(const String& sField, const String& sKey, const String& sValue)
{
	SetPosition(0);

	vector< String > sv;
	String sTemp;
	while(!IsFileEOF())  // Read all original lines into our vector
	{
		sTemp = ReadLine();
		sTemp.Trim();
		sv.push_back(sTemp);
	}

	std::vector< String >::iterator i, iend;
	i = sv.begin();
	iend = sv.end();
	bool bDone = false;
	for(; i != iend; ++i)
	{
		sTemp = *i;
		if(sTemp == "[" + sField + "]")  // find the field
		{
			for(++i; i != iend; ++i)
			{
				if(i->IfContain("["))  // Touch another field
				{
					sv.insert(i, sKey + " = " + sValue);

					bDone = true;
					break;
				}
				else
				{
					sTemp = *i;

					String::size_type PosOfSep = sTemp.find('=');
					if(PosOfSep != String::npos)
					{
						sTemp = sTemp.substr(0, PosOfSep);
					}

					sTemp.Trim();
					if(sTemp == sKey)  // Find the item, set it!
					{
						i->operator = (sKey + " = " + sValue);

						bDone = true;
						break;
					}
				}
			}

			if(!bDone)
			{
				sv.push_back(sKey + " = " + sValue);
				bDone = true;
			}

			break;
		}
	}

	if(!bDone)
	{
		sv.push_back("[" + sField + "]");
		sv.push_back(sKey + " = " + sValue);

		bDone = true;
	}


	// Now update the ini file...

	Close();  // First, close the ini file cause we open it as read-writable file

	WOFile inif;
	inif.SetFilename(m_sFilename);
	inif.Open();

	for(unsigned int j = 0; j < sv.size() - 1; ++j)
	{
		sTemp = sv[j];
		inif.WriteLine(sTemp);
	}
	sTemp = sv[j];  // The last line
	inif.WriteBuffer((const void*)sTemp.c_str(), sTemp.GetSize());

	inif.Close();

	Open();  // Open the ini file for the following use
}
Пример #28
0
	/*!
	* \brief Changes the debugging name associated to the calling thread
	*
	* Changes the debugging name associated with the calling thread, and may helps with debugging tools.
	*
	* \param name The new name associated with this thread
	*
	* \remark Due to system limitations, thread name cannot exceed 15 characters (excluding null-terminator)
	*
	* \see SetName
	*/
	void Thread::SetCurrentThreadName(const String& name)
	{
		NazaraAssert(name.GetSize() < 16, "Thread name is too long");

		ThreadImpl::SetCurrentName(name);
	}
Пример #29
0
	StringStream::StringStream(const String& str) :
	m_bufferSize(str.GetSize())
	{
		m_strings.push_back(str);
	}
Пример #30
0
int main(int argc, char* argv[])
{

    String story(7, '.');
    story.Print();
    cout << endl;

    char* sentence = "Wyimaginowane dolegliwosci sa nieuleczalne.";
    String story2a(sentence);
    story2a.Print();
    cout << endl;

    String story2b('c');
    story2b.Print();
    cout << endl;

    String story2c(story2a);
    story2c.Print();
    cout << endl;

    String story3a_1((char*)"Aaaaa");
    String story3a_2((char*)"Bbbbb");
    cout << ((story3a_1 == story3a_2) ? "equal" : "different") << endl;
    cout << ((story3a_1 != story3a_2) ? "not equal" : "no different") << endl;
    cout << "first is " << 
        ((story3a_1 > story3a_2) ? "bigger" : "smaller") << endl;
     cout << "first is " << 
        ((story3a_1 < story3a_2) ? "smaller" : "bigger") << endl;

     String story4a1("Hello ");
     String story4a2("world!");
     story4a1 = story4a1 + story4a2;
     story4a1.Print();
     cout << endl;

     String story4b("Ala ma ");
     char* kota = "kota.";
     story4b = kota + story4b;
     story4b.Print();
     cout << endl;

     String story4c("AB");
     story4c = story4c + "C";
     story4c.Print();
     cout << endl;

     String story5("1234567890");
     for (int i = 0; i < story5.GetSize(); i++)
     {
         cout << story5[i];
     }
     cout << endl;

     // TASK 6.
     String a;
     String b("string test");
     String c('K');
     String d(story2a);

     cout << "1: \""; a.Print(); cout << "\" length: " << a.GetSize() << endl;
     cout << "2: \""; b.Print(); cout << "\" length: " << b.GetSize() << endl;
     cout << "3: \""; c.Print(); cout << "\" length: " << c.GetSize() << endl;
     cout << "4: \""; d.Print(); cout << "\" length: " << d.GetSize() << endl;

     cout << endl << "Last letters:" << endl;
     cout << story[story.GetSize()-1] << endl;
     cout << story2a[story2a.GetSize()-1] << endl;
     cout << story2b[story2b.GetSize()-1] << endl;
     cout << story2c[story2c.GetSize()-1] << endl;
     cout << story3a_1[story3a_1.GetSize()-1] << endl;
     cout << story3a_2[story3a_2.GetSize()-1] << endl;
     cout << story4a1[story4a1.GetSize()-1] << endl;
     cout << story4a2[story4a2.GetSize()-1] << endl;
     cout << story4b[story4b.GetSize()-1] << endl;
     cout << story4c[story4c.GetSize()-1] << endl;
     cout << story5[story5.GetSize()-1] << endl;
     cout << a[a.GetSize()-1] << endl;
     cout << b[b.GetSize()-1] << endl;
     cout << c[c.GetSize()-1] << endl;
     cout << d[d.GetSize()-1] << endl;


    return 0;
}