// -----------------------------------------------------------------------------
// ReadArrayFromStringL
// Reads the array from the string
// -----------------------------------------------------------------------------
//
LOCAL_C void ReadArrayFromStringL( const TDesC8& aString,
                                   RPointerArray<HBufC8>& aArray )
    {
    RMemReadStream inRead( static_cast<const TAny*>( aString.Ptr() ), aString.Size() );
    TInt size = 0;
    HBufC8* addData = NULL;
    TPtr8 dataBuffer(NULL,0,0);
    CleanupClosePushL( inRead );


    aArray.ResetAndDestroy();


    for( TInt i = 0; i < aString.Size();)
        {
        // If there is not enough data to read the integer
        // it means that it's an old version and the whole thing is the
        // string since in previous versions only one string is stored
        if(( aString.Size() - i) < sizeof(TInt) )
            {
            aArray.ResetAndDestroy();
            addData = aString.AllocLC();
            aArray.AppendL( addData );
            CleanupStack::Pop();
            CleanupStack::PopAndDestroy(); // inRead
            return;
            }

        size = inRead.ReadInt32L();
        i += sizeof(TInt);

        // If the size is negative or the size left is not large enough
        // it means that it's an old version and the whole thing is the
        // string since in previous versions only one string is stored.
        if( size < 0 || size > ( aString.Size() - i ) )
            {
            aArray.ResetAndDestroy();
            addData = aString.AllocLC();
            aArray.AppendL( addData );
            CleanupStack::Pop();
            CleanupStack::PopAndDestroy(); // inRead
            return;
            }
        addData = HBufC8::NewMaxLC( size );

        // Set the read buffer:
        dataBuffer.Set(const_cast<TUint8*>(addData->Ptr()), 0, size);

        // Read the data:
        inRead.ReadL( dataBuffer );

        aArray.AppendL( addData );
        CleanupStack::Pop( addData );

        i += size;
        }
    CleanupStack::PopAndDestroy();
    return;
    }
// -----------------------------------------------------------------------------
// CWPPushMessage::SetL
// -----------------------------------------------------------------------------
//
EXPORT_C void CWPPushMessage::SetL( const TDesC8& aHeader, const TDesC8& aBody )
    {
    HBufC8* header = aHeader.AllocLC();
    HBufC8* body = aBody.AllocL();
    CleanupStack::Pop(); // header
    Set( header, body );
    }
// -----------------------------------------------------------------------------
void CPresenceCacheBuddyInfo::SetAnyFieldL( 
    const TDesC16& aKey,
    const TDesC8& aValue )
    {
    if( NPresenceCacheFieldName::KExpiry().CompareF( aKey ) == 0 )
        {
        TPckg<TInt64> expiryPck( iExpiryTime );
        expiryPck.Copy( aValue );
        // write also to key-value map
        }
    
    // Remove old values first
    RemoveField( aKey );    
    
    HBufC8* valueBuffer = aValue.AllocLC();      
    HBufC* keyBuffer = aKey.AllocLC();  
    
    TInt insertPos = iIds.Find(0);
    if ( insertPos < 0 )
        {
        insertPos = iIds.Count();
        iIds.Append( keyBuffer );
        iValues.Append( valueBuffer );
        }
    else
        {
        iIds[insertPos] = keyBuffer;
        iValues[insertPos] = valueBuffer;
        }
    
    iHashMap.InsertL( keyBuffer, insertPos  ); 
    
    CleanupStack::Pop( keyBuffer );
    CleanupStack::Pop( valueBuffer );    
    }
// -----------------------------------------------------------------------------
// CMceAvcCodec::SetConfigKeyL
// -----------------------------------------------------------------------------
//        
EXPORT_C void CMceAvcCodec::SetConfigKeyL( const TDesC8& aConfigKey )
    {
    HBufC8* configKey = aConfigKey.AllocLC();
    _FLAT_DATA->SetConfigKeyL( configKey );
    CleanupStack::PopAndDestroy( configKey );
    
    }
// -----------------------------------------------------------------------------
// CSTSMidletInfo::AppendRootIdL
// Appends end entity ID value (hash of the end entity certificate) to array
// -----------------------------------------------------------------------------
void CSTSMidletInfo::AppendRootIdL(const TDesC8& aRootId)
{
    HBufC8* rootBuf = aRootId.AllocLC();
    //array takes the ownership
    User::LeaveIfError(iRootIds.Append(rootBuf));
    CleanupStack::Pop(rootBuf);

}
// -----------------------------------------------------------------------------
// CSTSMidletInfo::AppendEndEntityIdL
// Appends end entity ID value (hash of the end entity certificate) to array
// -----------------------------------------------------------------------------
void CSTSMidletInfo::AppendEndEntityIdL(const TDesC8& aEndEntityId)
{
    HBufC8* endEntityBuf = aEndEntityId.AllocLC();
    //array takes the ownership
    User::LeaveIfError(iEndEntityIds.Append(endEntityBuf));
    CleanupStack::Pop(endEntityBuf);

}
void CPipeliningConfigTest::AddTransactionUrisL(const TDesC8& aUri, TInt aRepeatNumber)
{
    for (TInt ii = 0; ii< aRepeatNumber; ++ii)
    {
        HBufC8* uri = aUri.AllocLC();
        User::LeaveIfError(iTransactionUris.Append(uri));
        CleanupStack::Pop(uri);
    }
}
// -----------------------------------------------------------------------------
// CMceOutRefer::ConstructL
// -----------------------------------------------------------------------------
//
void CMceOutRefer::ConstructL( 	const TDesC8& aRecipient,
                    	        const TDesC8& aReferTo,
                    	        TType aType,
                    	        const TDesC8& aOriginator )
    {
    HBufC8* originator = aOriginator.AllocLC();
    ConstructL( aRecipient, aReferTo, aType, originator );
    CleanupStack::Pop( originator );
        
    }
// ---------------------------------------------------------
// CMediaDataClient::AddTypeL()
// ---------------------------------------------------------
//
TBool CMediaDataClient::AddTypeL( const TDesC8& aType )
    {
    if ( aType.Length() > COD_TYPE_MAX_LEN || !aType.Length() )
        {
        return EFalse;
        }
    HBufC8* type8 = aType.AllocLC();
    iTypes->AppendL( *type8 );
    CleanupStack::PopAndDestroy(); //type8
    return ETrue;
    }
// -----------------------------------------------------------------------------
// CSIPMessage::SetSIPVersionL
// -----------------------------------------------------------------------------
//
void CSIPMessage::SetSIPVersionL (const TDesC8& aSIPVersion)
	{
	__ASSERT_ALWAYS (SIPSyntaxCheck::SIPVersion(aSIPVersion),
	                 User::Leave(KErrSipCodecSIPVersion));

	HBufC8* tmp = aSIPVersion.AllocLC();
	tmp->Des().UpperCase();
	RStringF tmpString = SIPStrings::Pool().OpenFStringL(*tmp);
	CleanupStack::PopAndDestroy(tmp);		
	iSIPVersion.Close();
	iSIPVersion = tmpString;
	}
// -----------------------------------------------------------------------------
// SIPCodecUtils::CheckAndCreateTokenL
// -----------------------------------------------------------------------------
//
RStringF 
SIPCodecUtils::CheckAndCreateTokenL(const TDesC8& aToken, TInt aLeaveCode)
    {
	HBufC8* tmp = aToken.AllocLC();
	tmp->Des().Trim();
	if (!SIPSyntaxCheck::Token(*tmp))
		{
		User::Leave(aLeaveCode);
		}
	RStringF tmpString = SIPStrings::Pool().OpenFStringL(*tmp);
	CleanupStack::PopAndDestroy(tmp);		
    return tmpString;
    }
// -----------------------------------------------------------------------------
// SIPCodecUtils::CheckAndSetValueL
// -----------------------------------------------------------------------------
//
void SIPCodecUtils::CheckAndSetValueL(HBufC8*& aBuffer, 
                                      const TDesC8& aValue, 
                                      TInt aErr)
    {
	HBufC8* tmp = aValue.AllocLC();
	tmp->Des().Trim();
	if (!SIPSyntaxCheck::Token(*tmp))
		{
		User::Leave(aErr);
		}
	CleanupStack::Pop(tmp);
	delete aBuffer;
	aBuffer = tmp;
    }
// ---------------------------------------------------------------------------
// CNATFWDomainEntry::UpdateTurnSrvAddrL()
//
// ---------------------------------------------------------------------------
//
TInt CNATFWDomainEntry::UpdateTurnSrvAddrL( TInt aIndex, const TDesC8& aAddr )
    {
    if ( aIndex < 0 || aIndex >= iTurnSrvAddrArray.Count() )
        {
        return KErrArgument;
        }
    HBufC8* temp = aAddr.AllocLC();
    delete iTurnSrvAddrArray[ aIndex ];
    iTurnSrvAddrArray.Remove( aIndex );
    iTurnSrvAddrArray.Compress();
    iTurnSrvAddrArray.InsertL( temp, aIndex );
    CleanupStack::Pop( temp );
    
    return KErrNone;
    }
// -----------------------------------------------------------------------------
// CSyncMLFilterProperty::AddDefaultValueText8L
// Adds default value for text8 property.
// This is useful only if data type is text8.
// -----------------------------------------------------------------------------
EXPORT_C void CSyncMLFilterProperty::AddDefaultValueText8L(
                TDesC8& aNewDefaultValue, const TBool aSelected )
	{
	if ( iDataTypeForDefaultValues != ESyncMLDataTypeText8 )
		{
		User::Leave( KErrNotSupported );
		}
	if ( aNewDefaultValue.Length() > iMaxTextLength )
		{
		User::Leave( KErrArgument );
		}
	iDefaultValueText8List.AppendL( aNewDefaultValue.AllocLC() );
	CleanupStack::Pop(); // aNewDefaultValue.AllocLC()
	iDefaultValueSelected.AppendL( aSelected );
	}
// ---------------------------------------------------------------------------
// CNATFWDomainEntry::UpdateStunPasswordL()
//
// ---------------------------------------------------------------------------
//
TInt CNATFWDomainEntry::UpdateStunPasswordL( TInt aIndex,
    const TDesC8& aPassword )
    {
    if ( aIndex < 0 || aIndex >= iStunPasswordArray.Count() )
        {
        return KErrArgument;
        }
    HBufC8* temp = aPassword.AllocLC();
    delete iStunPasswordArray[ aIndex ];
    iStunPasswordArray.Remove( aIndex );
    iStunPasswordArray.Compress();
    iStunPasswordArray.InsertL( temp, aIndex );
    CleanupStack::Pop( temp );
    
    return KErrNone;
    }
// ---------------------------------------------------------------------------
// CSdpMediaField::KeepFormatL
// ---------------------------------------------------------------------------
//
EXPORT_C void CSdpMediaField::KeepFormatL(const TDesC8& aFormat)
{
    if ( !iFormatList )
    {
        User::Leave( KErrSdpCodecMediaField );
    }
    // Empty set will continue to be empty
    if ( iFormatList->Des().Length() > 0 )
    {
        HBufC8* formatList = aFormat.AllocLC();
        // Mark all format attributes not aFormat so that they will be deleted
        RArray<TInt> removedObjs;
        CleanupClosePushL( removedObjs );
        for ( TInt i( 0 ); i < iFmtAttrFields->Count(); i++ )
        {
            if (aFormat.CompareF((*iFmtAttrFields)[i]->Format()) != 0)
            {
                User::LeaveIfError( removedObjs.Append( i ) );
            }
        }
        // Delete attribute fields
        TInt removedCount( 0 );
        while ( removedObjs.Count() > 0 )
        {
            CSdpFmtAttributeField* obj =
                (*iFmtAttrFields)[removedObjs[0] - removedCount];
            delete obj;
            iFmtAttrFields->Remove( removedObjs[0] - removedCount );
            removedObjs.Remove( 0 );
            removedCount++;
        }
        CleanupStack::PopAndDestroy();  // removedObjs
        // Change format list
        delete iFormatList;
        iFormatList = formatList;
        CleanupStack::Pop();    // formatList
    }
}
// -----------------------------------------------------------------------------
// CMceOutRefer::ConstructL
// -----------------------------------------------------------------------------
//
void CMceOutRefer::ConstructL( 	const TDesC8& aRecipient,
                    	        const TDesC8& aReferTo,
                    	        TType aType,
                    	        HBufC8* aOriginator )
    {
    CDesC8ArrayFlat* params = 
        new (ELeave) CDesC8ArrayFlat( KMceArrayGranularity );
	CleanupStack::PushL( params );
    params->AppendL( aReferTo );
    
    if ( iDialogId == KMceNotAssigned )
        {
        params->AppendL( aRecipient );
        if ( aOriginator )
            {
            params->AppendL( *aOriginator );
            }
        else
            {
            params->AppendL( KNullDesC8 );
            }
        }
        
    if ( aType == ENoSuppression )
        {
        HBufC8* originator = NULL;
        if ( aOriginator )
            {
            originator = ( *aOriginator ).AllocL();
            }
        CleanupStack::PushL( originator );
        iOwnedEvent = CMceOutEvent::NewL( iManager,
					                  iProfileId,
					                  aRecipient,
							          KReferEventHeader,
		    				          0,
					                  originator,
					                  iDialogId,
			    	                  KMceDlgTypeRefer,
					                  params );
	    CleanupStack::Pop( originator );
	    CleanupStack::Pop( params );
	    }
    
    HBufC8* recipient = aRecipient.AllocLC();
    HBufC8* referTo = aReferTo.AllocLC();
    
    if ( aType == ENoSuppression )
        {
        CMceRefer::ConstructL( recipient, referTo, aOriginator, NULL );    
        CleanupStack::Pop( referTo );
        CleanupStack::Pop( recipient ); 
        }
    else
        {
        CMceRefer::ConstructL( recipient, referTo, aOriginator, params ); 
        CleanupStack::Pop( referTo );
        CleanupStack::Pop( recipient ); 
        CleanupStack::Pop( params );   
        }
    }
// -----------------------------------------------------------------------------
// CDRMEventHandler::RegisterEventObserverL
// Adds the new handler to the list of handlers.
// Checks is the handler is already in the list
// Sets the active object active if it is not active yet.
// -----------------------------------------------------------------------------
//
void CDRMEventHandler::RegisterEventObserverL(
    MDRMEventObserver& aObserver,
    const TDRMEventType& aEvent,
    const TDesC8& aContentID )
    {
    TInt count = 0;
    TBool addToServer = ETrue;

    if( iIsDelayed )
        {
        TDelayedObserverData* delayData = new (ELeave) TDelayedObserverData;
        CleanupStack::PushL( delayData);
        delayData->iRequest = KRegisterURIOperation;
        delayData->iObserver = &aObserver;
        delayData->iEventType = aEvent;
        delayData->iContentID = aContentID.AllocLC();
        iDelayedObservers->AppendL( delayData );
        CleanupStack::Pop();    // iContentID;
        CleanupStack::Pop();    // delayData;
        return;
        }

    switch ( aEvent )
        {
        case KEventAddRemove:
            if ( iAddRemoveObservers )
                {
                for ( count = 0; count < iAddRemoveObservers->Count(); ++count )
                    {
                    if ( ( *iAddRemoveObservers )[ count ]->iObserver == &aObserver &&
                         ( *iAddRemoveObservers )[ count ]->iContentID &&
                         !( *iAddRemoveObservers )[ count ]->iContentID->Compare( aContentID ) )
                        {
                        return;
                        }
                    else if( addToServer && 
                        !( *iAddRemoveObservers)[ count ]->iContentID->Compare( aContentID ) ) 
                        {
                        addToServer = EFalse;
                        }
                    }
                }
            break;
        case KEventModify:
            if ( iModifyObservers )
                {
                for ( count = 0; count < iModifyObservers->Count(); ++count )
                    {
                    if ( ( *iModifyObservers )[ count ]->iObserver == &aObserver &&
                         ( *iModifyObservers )[ count ]->iContentID &&
                         !( *iModifyObservers )[ count ]->iContentID->Compare( aContentID ) )
                        {
                        return;
                        }
                    else if( addToServer && 
                        !( *iModifyObservers)[ count ]->iContentID->Compare( aContentID ) ) 
                        {
                        addToServer = EFalse;
                        }
                    }
                }
            break;
        default:
            User::Leave(KErrArgument);
            break;
        }  

    HBufC8* contentID = aContentID.AllocLC();
    struct TObserverData* observer = new (ELeave) TObserverData;
    CleanupStack::PushL(observer);

    observer->iObserver = &aObserver;
    observer->iContentID = contentID;

    switch( aEvent )
        {
        case KEventAddRemove:
            if( this->iAddRemoveObservers ) // coverity check
                {
                iAddRemoveObservers->AppendL( observer );
                }
            break;
        case KEventModify:
            if( this->iModifyObservers ) // coverity check
                {
                iModifyObservers->AppendL( observer );
                }
            break;
        default:
            User::Leave(KErrArgument);
            break;
        }
   
    if ( !IsAdded() )
        {
        CActiveScheduler::Add( this );
        }

    if ( !IsActive() )
        {
        if( iStatus != KRequestPending )
            {
            iStatus = KRequestPending;
            iHandler->WaitForCompletion(iStatus);
            }
        SetActive();
        }

    // Register the type to the server
    if ( addToServer )
        {
        iHandler->RegisterForType(aEvent,contentID);
        }

    CleanupStack::Pop(); // contentID
    CleanupStack::Pop(); // observer;
    }
// -----------------------------------------------------------------------------
// CDRMEventHandler::UnRegisterEventObserverL
// Removes the observer from the list of handlers.
// -----------------------------------------------------------------------------
//
void CDRMEventHandler::UnRegisterEventObserverL( 
    MDRMEventObserver& aObserver,
    const TDRMEventType& aEvent,
    const TDesC8& aContentID )
    {
    TInt count = 0;
    TBool removeFromServer = ETrue;

    if( iIsDelayed )
        {
        TDelayedObserverData* delayData = new (ELeave) TDelayedObserverData;
        CleanupStack::PushL( delayData);
        delayData->iRequest = KUnRegisterURIOperation;
        delayData->iObserver = &aObserver;
        delayData->iEventType = aEvent;
        delayData->iContentID = aContentID.AllocLC();
        iDelayedObservers->AppendL( delayData );
        CleanupStack::Pop();    // iContentID;
        CleanupStack::Pop();    // delayData;
        return;
        }

    // Check if something else uses the registration for this event type, if something
    // Does set removeFromServer to EFalse so the registration is not removed from the
    // server
    switch ( aEvent )
        {
        case KEventAddRemove:
            if ( iAddRemoveObservers )
                {
                for ( count = 0; count < iAddRemoveObservers->Count(); ++count )
                    {
                    if( removeFromServer && 
                        !( *iAddRemoveObservers )[ count ]->iContentID->Compare( aContentID ) &&
                        ( *iAddRemoveObservers )[ count ]->iObserver != &aObserver ) 
                        {
                        removeFromServer = EFalse;
                        }
                    }
                }
            break;
        case KEventModify:
            if ( iModifyObservers )
                {
                for ( count = 0; count < iModifyObservers->Count(); ++count )
                    {
                    if( removeFromServer && 
                        !( *iModifyObservers )[ count ]->iContentID->Compare( aContentID ) &&
                        ( *iModifyObservers )[ count ]->iObserver != &aObserver ) 
                        {
                        removeFromServer = EFalse;
                        }
                    }
                }
            break;
        default:
            User::Leave(KErrArgument);
            break;
        }  


    // Remove the registrations from internal lists and possibly from the server
    switch ( aEvent )
        {
        case KEventAddRemove:
            if ( iAddRemoveObservers )
                {
                for ( count = 0; count < iAddRemoveObservers->Count(); ++count )
                    {
                    if ( ( *iAddRemoveObservers )[ count ]->iObserver == &aObserver &&
                         ( *iAddRemoveObservers )[ count ]->iContentID &&
                         !( *iAddRemoveObservers )[ count ]->iContentID->Compare( aContentID ) )
                        {
                        if ( removeFromServer )
                            {
                            // Unregister the type from the server
                            iHandler->UnRegisterFromType(aEvent,(*iAddRemoveObservers)[ count ]->iContentID);
                            }

                        // Free Memory
                        delete ( *iAddRemoveObservers )[ count ]->iContentID;
                        ( *iAddRemoveObservers )[ count ]->iContentID = NULL;
                        delete ( *iAddRemoveObservers )[ count ];
                        ( *iAddRemoveObservers )[ count ] = NULL;

                        // Delete the element from the table
                        iAddRemoveObservers->Delete( count );
                        iAddRemoveObservers->Compress();
                        return;
                        }
                    }
                }
            User::Leave(KErrNotFound);
            break;
        case KEventModify:
            if ( iModifyObservers )
                {
                for ( count = 0; count < iModifyObservers->Count(); ++count )
                    {
                    if ( ( *iModifyObservers )[ count ]->iObserver == &aObserver &&
                         ( *iModifyObservers )[ count ]->iContentID &&
                         !( *iModifyObservers )[ count ]->iContentID->Compare( aContentID ) )
                        {

                        if( removeFromServer )
                            {
                            // Unregister the type from the server
                            iHandler->UnRegisterFromType(aEvent,(*iModifyObservers)[ count ]->iContentID);
                            }

                        // Free Memory
                        delete ( *iModifyObservers )[ count ]->iContentID;
                        ( *iModifyObservers )[ count ]->iContentID = NULL;
                        delete ( *iModifyObservers )[ count ];
                        ( *iModifyObservers )[ count ] = NULL;

                        // Delete the element from the table
                        iModifyObservers->Delete( count );
                        iModifyObservers->Compress();
                        return;
                        }
                    }
                }
            User::Leave(KErrNotFound);
            break;
        default:
            User::Leave(KErrArgument);
            break;
        }  
    // Should never get here
    User::Leave( KErrGeneral );
    }
// ----------------------------------------------------------------------------
// CNATFWDomainEntry::AddTurnSrvAddrL
//
// ----------------------------------------------------------------------------
//
void CNATFWDomainEntry::AddTurnSrvAddrL( const TDesC8& aTurnSrvAddr )
    {
    HBufC8* temp = aTurnSrvAddr.AllocLC();
    iTurnSrvAddrArray.AppendL( temp );
    CleanupStack::Pop( temp );
    }
// ----------------------------------------------------------------------------
// CNATFWDomainEntry::AddTurnUsernameL
//
// ----------------------------------------------------------------------------
//
void CNATFWDomainEntry::AddTurnUsernameL( const TDesC8& aTurnUsername )
    {
    HBufC8* temp = aTurnUsername.AllocLC();
    iTurnUsernameArray.AppendL( temp );
    CleanupStack::Pop( temp );
    }
// ----------------------------------------------------------------------------
// CNATFWDomainEntry::AddTurnPasswordL
//
// ----------------------------------------------------------------------------
//
void CNATFWDomainEntry::AddTurnPasswordL( const TDesC8& aTurnPassword )
    {
    HBufC8* temp = aTurnPassword.AllocLC();
    iTurnPasswordArray.AppendL( temp );
    CleanupStack::Pop( temp );
    }