Boost logo

Boost :

From: Reece Dunn (msclrhd_at_[hidden])
Date: 2004-04-16 05:45:17


There is currently a static-sized array in the Boost library that allows you
to operate on arrays of fixed size. I was wondering if something similar
exists for strings, in particular, providing buffer-overflow safe string
operations.

I have an nstring< std::size_t n > string class that provides size-safe
copying and comparison, allowing for you to do things like:

   nstring< 20 > s;
   s.copy( "Hello World!" )
   if( s == "Hello" ) ... // note: this will succeed!

This is useful for things like processing file format headers, as it allows
things like:

struct tar_header
{
   nstring< 100 > name;
   ...
   nstring< 8 > magic;
   ...
};

if( hdr.magic == "ustar\x20\x20\0" ) // GNU TAR archive
   ...
else if( hdr.magic == "ustar\0" ) // POSIX TAR archive
   ...
else
   // invalid format

I also have a formatter class that provides buffer-safe printf-like
operations on the constructor and as a functor, e.g.:

   formatter< 512 > fmt( "%s: %s", type, msg );
   std::cout << fmt << '\n';
   std::cout << fmt( "error: %s", msg ) << '\n';

This can be useful when you need to format a string without making use of a
string buffer, e.g.:

   std::ostringstream fmt;

   fmt << type << ": " << msg;
   std::cout << fmt.str() << '\n';

   fmt.str( std::string()); // clear string buffer
   fmt << "error: " << msg;
   std::cout << fmt.str() << '\n';

Regards,
Reece

_________________________________________________________________
Tired of 56k? Get a FREE BT Broadband connection
http://www.msn.co.uk/specials/btbroadband


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk