examples/Base/BufsAndStrings/rbufexample/rbufexample.cpp

Go to the documentation of this file.
00001 /*
00002 Copyright (c) 2008-2010 Nokia Corporation and/or its subsidiary(-ies). All rights reserved.
00003 
00004 Redistribution and use in source and binary forms, with or without
00005 modification, are permitted provided that the following conditions are met:
00006 
00007 * Redistributions of source code must retain the above copyright notice, this
00008   list of conditions and the following disclaimer.
00009 * Redistributions in binary form must reproduce the above copyright notice,
00010   this list of conditions and the following disclaimer in the documentation
00011   and/or other materials provided with the distribution.
00012 * Neither the name of Nokia Corporation nor the names of its contributors
00013   may be used to endorse or promote products derived from this software
00014   without specific prior written permission.
00015 
00016 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
00017 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
00018 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
00019 DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
00020 FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
00021 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
00022 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
00023 CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
00024 OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
00025 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
00026 
00027 Description: This example program demonstrates how to use the resizable buffer descriptor class RBuf.  
00028 */
00029 
00030 
00031 
00035 #include "rbufexample.h"
00036 
00037 const TInt KLargeBufSize = 15;
00038 const TInt KSmallBufSize = 3;
00039 const TInt KMedBufSize = 7;
00040 
00041 _LIT(KFailed, "\n Error occurred");
00042 _LIT(KPressAKey, "\n\n Press any key to continue the example\n");
00043 _LIT(KLength,"\n  Length= %d");
00044 _LIT(KMaxLength,"\n  MaxLength= %d");
00045 _LIT(KBuffer1,"11111");
00046 _LIT(KBuffer2,"22222");
00047 
00051 CRBufExample::CRBufExample()
00052         {
00053         }
00054 
00055 void CRBufExample::ConstructL()
00056         {
00057         _LIT(KTitle," RBuf Example");
00058         iConsole = Console::NewL(KTitle, TSize(KConsFullScreen, KConsFullScreen));
00059         
00060         _LIT(KWelcome," Welcome to the RBuf example application");
00061         iConsole->Printf(KWelcome);
00062         
00063         _LIT(KPressAKeyMsg, "\n\n Press any key to step through the example\n");
00064         iConsole->Printf(KPressAKeyMsg );
00065         iConsole->Getch();
00066         }
00067 
00071 CRBufExample::~CRBufExample()
00072         {
00073         delete iConsole;
00074         }
00075 
00080 CRBufExample* CRBufExample::NewL()
00081         {
00082         CRBufExample* self=new(ELeave)CRBufExample();
00083         CleanupStack::PushL(self);
00084         self->ConstructL();
00085         CleanupStack::Pop(self);
00086         return self;
00087         }
00088     
00092 void CRBufExample::CreateRBufL()
00093         {
00094         _LIT(KCreate,"\n Creating an RBuf: \n");
00095 
00096         iConsole->Printf(KCreate);
00097         
00098         RBuf buf;
00099         
00100         // Create an empty buffer descriptor
00101         // The length is zero, the maxlength is 3
00102         User::LeaveIfError(buf.Create(KSmallBufSize));
00103         CleanupClosePushL(buf);
00104         
00105         // Get the length of the buffer
00106         TInt length= buf.Length();
00107         
00108         // Get the maximum length of the buffer
00109         TInt maxLength= buf.MaxLength();
00110         
00111         // Check that length and maximum length are not equal because it was created using Create()
00112         if(length != maxLength)
00113                 {
00114                 _LIT(KUsingCreate, "\n Using Create() API: ");
00115                 iConsole->Printf(KUsingCreate);
00116                 iConsole->Printf(KLength, length);
00117                 iConsole->Printf(KMaxLength, maxLength);
00118                 }
00119         else
00120                 {
00121                 iConsole->Printf(KFailed);
00122                 }       
00123 
00124         // Deallocate the memory assigned to the buffer
00125         CleanupStack::PopAndDestroy(&buf);
00126         
00127         // Create buffer descriptor
00128         // The length is 3, the maxlength is 3
00129         User::LeaveIfError(buf.CreateMax(KSmallBufSize));
00130         CleanupClosePushL(buf);
00131         
00132         // Get the length of the buffer.
00133         length= buf.Length();
00134         
00135         // Get the maximum length of the buffer.
00136         maxLength=buf.MaxLength();
00137         
00138         // Check that length and maximum length are equal because it was created using CreateMax().
00139         if(length == maxLength)
00140                 {
00141                 _LIT(KCreateInAdvance, "\n Using CreateMax() API: ");
00142                 iConsole->Printf(KCreateInAdvance);     
00143                 iConsole->Printf(KLength, length);
00144                 iConsole->Printf(KMaxLength, maxLength);
00145                 }
00146         else
00147                 {
00148                 iConsole->Printf(KFailed);
00149                 }       
00150         
00151         // Deallocate the memory assigned to the buffer.
00152         CleanupStack::PopAndDestroy(&buf);
00153         } 
00154         
00158 void CRBufExample::CreateRBufFromExistingDesL()
00159         {
00160         RBuf buf;
00161         
00162         // Create a buffer descriptor, initialised with some text
00163         buf.CreateL(KBuffer1);
00164         
00165         _LIT(KCreateFromExistingDes, "\n From an existing descriptor ");
00166         iConsole->Printf(KCreateFromExistingDes);
00167 
00168         // Deallocates the memory assigned to the buffer
00169         buf.Close();
00170         } 
00171         
00175 void CRBufExample::CreateRBufFromHBufCL()
00176         {
00177         // Create a pointer to a heap descriptor
00178         HBufC* hptr = HBufC::NewL(KBuffer1().Length());
00179         
00180         // Assign some data to the heap descriptor.
00181         *hptr = KBuffer1; 
00182         
00183         RBuf buf;
00184         
00185         // Assign the HBufC to the buffer. This transfers ownership of the heap descriptor.
00186         buf.Assign(hptr);
00187         
00188         _LIT(KCreateFromHBufC, "\n From HBufC ");
00189         iConsole->Printf(KCreateFromHBufC);
00190         
00191         // Deallocate the memory assigned to the buffer. 
00192         // There is no need to free the HBufC because Assign() transferred ownership.
00193         buf.Close(); 
00194         }
00195         
00199 void CRBufExample::CreateRBufFromAnotherRBufL()
00200         {
00201         RBuf buf;
00202         
00203         // Create a buffer descriptor, initialised with some text
00204         User::LeaveIfError(buf.Create(KBuffer1));
00205                 
00206         RBuf targetBuf;
00207         
00208         // Assign one buffer to the other. 
00209         // Transfers ownership of the source buffer's memory to the target buffer.
00210         // Note that targetBuf should have no memory allocated to it beforehand
00211         // otherwise a memory leak will occur.
00212         targetBuf.Assign(buf);
00213         
00214         _LIT(KCreateFromAnotherRBuf, "\n From another RBuf");
00215         iConsole->Printf(KCreateFromAnotherRBuf);
00216 
00217         // Deallocate the memory assigned to the buffer.
00218         targetBuf.Close();
00219         }
00220                 
00224 void CRBufExample::CreateRBufUsingRReadStreamL()
00225         {
00226         // A handle to a file server session. 
00227         // This is used to create and write to/read from a file.
00228         RFs fs;
00229         
00230         // Connect to the file server.
00231         User::LeaveIfError(fs.Connect());
00232         CleanupClosePushL(fs);
00233         // Create the session path at the process's private path on the system drive.
00234         User::LeaveIfError(fs.CreatePrivatePath(RFs::GetSystemDrive()));
00235 
00236         // Set the session path to point to the process's private path on the system drive.
00237         User::LeaveIfError(fs.SetSessionToPrivate(RFs::GetSystemDrive()));
00238         
00239         // Declare a file stream to write to.
00240         RFileWriteStream wStream;
00241         
00242         _LIT(KFileName,"stream.dat");
00243         
00244         // Create a file, associates it with the stream, and prepares the stream for writing.
00245         User::LeaveIfError(wStream.Replace(fs, KFileName, EFileWrite));
00246         CleanupClosePushL(wStream);
00247         
00248         _LIT(KText, "RBuf Example");
00249 
00250         // Write some text to the stream.
00251         wStream << KText();
00252         wStream.CommitL();
00253         CleanupStack::PopAndDestroy(&wStream);
00254         
00255         // Declare a file stream to read from.
00256         RFileReadStream rStream;
00257         
00258         // Open the file
00259         User::LeaveIfError(rStream.Open(fs, KFileName, EFileRead));
00260         CleanupClosePushL(rStream);
00261         
00262         RBuf buf;
00263         CleanupClosePushL(buf);
00264         
00265         // Create the buffer by passing the open stream object to CreateL().
00266         buf.CreateL(rStream, KLargeBufSize);
00267         
00268         _LIT(KCreateUsingRReadStream, "\n Using RReadStream ");
00269         iConsole->Printf(KCreateUsingRReadStream);
00270         
00271         // Deallocate the memory assigned to the buffer, close the stream and close the file server connection
00272         CleanupStack::PopAndDestroy(&buf);
00273         CleanupStack::PopAndDestroy(&rStream);
00274         CleanupStack::PopAndDestroy(&fs);
00275         }
00276 
00280 void CRBufExample::CreateRBufFromAllocatedMemoryL()
00281         {
00282         RBuf buf;
00283         
00284         // Allocate some memory.
00285         TUint16* allocatedMemory = static_cast<TUint16*>( User::Alloc( KLargeBufSize * sizeof( TUint16) ) ) ;
00286 
00287         // Transfer ownership of the memory to the descriptor.
00288         buf.Assign(allocatedMemory, KLargeBufSize);
00289         
00290         _LIT(KCreateFromAllocatedMemory, "\n By transferring ownership of allocated memory");
00291         iConsole->Printf(KCreateFromAllocatedMemory);
00292         
00293         iConsole->Printf(KPressAKey);
00294         iConsole->Getch();
00295         
00296         // Deallocate the memory assigned to the buffer.
00297         // There is no need to free memory here because Assign() transferred ownership.
00298         buf.Close(); 
00299         }
00300 
00304 void CRBufExample::SwapTwoRBufsL()
00305         {
00306         _LIT(KSwapAndCopy,"\n Swapping and copying data: ");
00307         iConsole->Printf(KSwapAndCopy);
00308         
00309         RBuf buf1;
00310         
00311         // Create a buffer descriptor, initialised with some text
00312         User::LeaveIfError(buf1.Create(KBuffer1));
00313         CleanupClosePushL(buf1);
00314         
00315         RBuf buf2;
00316         
00317         // Create a second buffer descriptor, initialised with some text
00318         User::LeaveIfError(buf2.Create(KBuffer2));
00319         CleanupClosePushL(buf2);
00320         
00321         _LIT(KBeforeSwapping, "\n Before swapping: ");
00322         iConsole->Printf(KBeforeSwapping);
00323         
00324         // Print out the contents of the 2 descriptors
00325         _LIT(KPrintFirstdata,"\n  Data present in first descriptor is: ");
00326         iConsole->Printf(KPrintFirstdata);      
00327         iConsole->Printf(buf1);
00328         
00329         _LIT(KPrintSecondData,"\n  Data present in second descriptor is: ");
00330         iConsole->Printf(KPrintSecondData);     
00331         iConsole->Printf(buf2);
00332         
00333         // Swap them and print out the new contents
00334         buf1.Swap(buf2);
00335         
00336         _LIT(KAfterSwapping, "\n After swapping: ");
00337         iConsole->Printf(KAfterSwapping);
00338         
00339         iConsole->Printf(KPrintFirstdata);      
00340         iConsole->Printf(buf1);
00341         
00342         iConsole->Printf(KPrintSecondData);     
00343         iConsole->Printf(buf2);
00344         
00345         _LIT(KSwap, "\n Swapping between two RBufs is successful");
00346         iConsole->Printf(KSwap);
00347                         
00348         // Deallocate memory assigned to the 2 buffer descriptors.
00349         CleanupStack::PopAndDestroy(2); // buf1, buf2
00350         }
00351         
00355 void CRBufExample::CopyDataUsingAssignmentOperatorL()
00356         {
00357         RBuf buf1;
00358         
00359         // Create a buffer descriptor, initialised with some text
00360         buf1.Create(KBuffer1);
00361         CleanupClosePushL(buf1);
00362 
00363         RBuf buf2;
00364         
00365         // Create a second buffer descriptor, initialised with some text
00366         User::LeaveIfError(buf2.Create(KBuffer2));
00367         CleanupClosePushL(buf2);
00368 
00369         // Copy data using assignment operator from one to the other. 
00370         // Target buffer must be long enough, otherwise a panic occurs.
00371         buf2= buf1;
00372         
00373         // Check the value of the buffers .
00374         if (buf1==buf2)
00375                 {
00376                 _LIT(KCopyDataUsingAssignmentOperator,"\n Copying data using assignment operator from descriptor, and RBuf is successful");
00377                 iConsole->Printf(KCopyDataUsingAssignmentOperator);
00378                 }
00379         else
00380                 {
00381                 iConsole->Printf(KFailed);      
00382                 }       
00383         
00384         iConsole->Printf(KPressAKey);
00385     iConsole->Getch();
00386         
00387         // Deallocate memory assigned to the 2 buffer descriptors.
00388         CleanupStack::PopAndDestroy(2); // buf1, buf2
00389         }
00390         
00394 void CRBufExample::ReallocateAndFreeTheMemoryBufferL()
00395         {
00396         _LIT(KReAllocAndFree,"\n Realloc and free:");
00397         iConsole->Printf(KReAllocAndFree);
00398         
00399         RBuf buf;
00400         
00401         // Create empty buffer descriptor with max length of KSmallBufSize.
00402         User::LeaveIfError(buf.Create(KSmallBufSize));
00403         
00404         // Get the length of the buffer.
00405         TInt length= buf.Length();
00406         
00407         // Get the maximum length of the buffer.
00408         TInt maxLength= buf.MaxLength();
00409         
00410         _LIT(KBeforeReAlloc,"\n Before ReAlloc: ");
00411         iConsole->Printf(KBeforeReAlloc);
00412         
00413         // Print out the length and max length
00414         iConsole->Printf(KLength, length);
00415         iConsole->Printf(KMaxLength, maxLength);        
00416 
00417         // Re-allocate the buffer descriptor. Length doesnt change but maxlength does.
00418         User::LeaveIfError(buf.ReAlloc(KMedBufSize));
00419         
00420         // Get the length of the buffer.
00421         length= buf.Length();
00422         
00423         // Get the maximum length of the reallocated buffer.
00424         maxLength= buf.MaxLength();
00425         
00426         _LIT(KAfterReAlloc,"\n After ReAlloc: ");
00427         iConsole->Printf(KAfterReAlloc);
00428 
00429         // Print out the length and new max length
00430         iConsole->Printf(KLength, length);
00431         iConsole->Printf(KMaxLength, maxLength);        
00432         
00433         // Free the memory buffer. It sets the length and maxlength to zero.
00434         User::LeaveIfError(buf.ReAlloc(0));
00435         
00436         // Get the length of the buffer.
00437         length= buf.Length();
00438         
00439         // Get the maximum length of the buffer.
00440         maxLength= buf.MaxLength();
00441         
00442         _LIT(KFreeBuffer,"\n After free: ");
00443         iConsole->Printf(KFreeBuffer);
00444         
00445         iConsole->Printf(KLength, length);
00446         iConsole->Printf(KMaxLength, maxLength);
00447         }
00448         
00452 void CRBufExample::ReplaceAndModifyTheDataL()
00453         {
00454         RBuf buf;
00455         
00456         // Create a buffer descriptor, initialised with some text
00457         User::LeaveIfError(buf.Create(KBuffer1)); 
00458         CleanupClosePushL(buf);
00459                         
00460         _LIT(KReplaceAndModify,"\n Replace and modify: ");
00461         iConsole->Printf(KReplaceAndModify);
00462         
00463         // Print the original data present in the buffer.
00464         _LIT(KOriginalData,"\n Data present in RBuf is: ");
00465         iConsole->Printf(KOriginalData);
00466         iConsole->Printf(buf);
00467         
00468         TInt pos= 1;
00469         
00470         _LIT(KReplacedMessage,"22");
00471         
00472         TInt length= KReplacedMessage().Length();
00473 
00474         // Replace a portion of the data in the buffer descriptor.
00475         buf.Replace(pos,length, KReplacedMessage);
00476         
00477         // Print the buffer's new contents.
00478         _LIT(KReplacedData,"\n After replacement, data held in RBuf is: ");
00479         iConsole->Printf(KReplacedData);
00480         iConsole->Printf(buf);
00481         
00482         pos=3;
00483         length=1;
00484         
00485         // Delete the replacement text.
00486     buf.Delete(pos,length);
00487     
00488     // Print the buffer's contents again.
00489     _LIT(KModifiedData,"\n After modification, data held in RBuf is: ");
00490     iConsole->Printf(KModifiedData);
00491     iConsole->Printf(buf);
00492     
00493     _LIT(KReplaceAndModifyData,"\n Replacing and modifying the data held in RBuf is successful");
00494     iConsole->Printf(KReplaceAndModifyData);
00495     
00496     // Deallocate the memory assigned to the buffer. 
00497         CleanupStack::PopAndDestroy(&buf);
00498         }
00499         
00503 void CRBufExample::CleanUpRulesL()
00504         {
00505         RBuf buf;
00506         
00507         // Create a buffer descriptor, initialised with some text
00508         User::LeaveIfError(buf.Create(KBuffer1));
00509         
00510         // To avoid memory leaks use RBuf::CleanupClosePushL() to push a cleanup item for the RBuf onto the cleanup stack.
00511         // The effect is to cause Close() to be called on the buffer descriptor if a leave occurs, 
00512         // or when CleanupStack::PopAndDestroy() is called.
00513         buf.CleanupClosePushL();
00514         
00515         // Causes Close() to be called to deallocate the memory assigned to the buffer.
00516         CleanupStack::PopAndDestroy(&buf);
00517         
00518         _LIT(KCleanUp,"\n RBuf cleanup is successful");
00519         iConsole->Printf(KCleanUp);
00520         
00521         _LIT(KExitMsg, "\n\n Press any key to exit the example");
00522     iConsole->Printf(KExitMsg);
00523         iConsole->Getch();
00524         }       
00525 
00526 void MainL()
00527         {
00528         CRBufExample* app= CRBufExample::NewL();
00529         CleanupStack::PushL(app);
00530         
00531         // Creates empty RBuf.
00532         app->CreateRBufL();
00533         
00534         // Creates RBuf from an existing descriptor.
00535         app->CreateRBufFromExistingDesL(); 
00536         
00537         // Creates RBuf from an HBufC.
00538         app->CreateRBufFromHBufCL();
00539         
00540         // Creates RBuf from another RBuf.
00541         app->CreateRBufFromAnotherRBufL();
00542         
00543         // Create RBuf using RReadStream
00544         app->CreateRBufUsingRReadStreamL();
00545         
00546         // Creates RBuf from allocated memory.
00547         app->CreateRBufFromAllocatedMemoryL();
00548                 
00549         // Swaps two RBufs.
00550         app->SwapTwoRBufsL();
00551         
00552         // Copies data using assignment operator.
00553         app->CopyDataUsingAssignmentOperatorL();
00554         
00555         // Reallocates and frees the memory buffer.
00556         app->ReallocateAndFreeTheMemoryBufferL();
00557         
00558         // Replaces and modifies the data in the descriptor.
00559         app->ReplaceAndModifyTheDataL();
00560         
00561         // Demonstrates cleanup.
00562         app->CleanUpRulesL();
00563         
00564         CleanupStack::PopAndDestroy(app);
00565         } 
00566 
00567 GLDEF_C TInt E32Main()
00568         {
00569         __UHEAP_MARK;
00570 
00571         CTrapCleanup* cleanup = CTrapCleanup::New();
00572         if(cleanup == NULL)
00573                 {
00574                 return KErrNoMemory;
00575                 }
00576         TRAPD(err, MainL());
00577         delete cleanup;
00578 
00579         if(err !=KErrNone)
00580                 {
00581                 User::Panic(KFailed, err);
00582                 }       
00583                 
00584         __UHEAP_MARKEND;
00585         return KErrNone;
00586         }
00587   
00588   
00589   
00590   
00591  
00592  
00593  

Generated by  doxygen 1.6.2