Developers.Hash.Guid.Sample

From Shareaza Wiki
Jump to navigation Jump to search

Here's a sample from camper. It shows how to pass GUIDs around and convert them to strings in various different formats.

<source lang="c"> Hashes::Guid g; CString s = g.toString(); // s == "" // toString() will always return an empty string on invalid hashes

// s is empty because g hasn't been validated // if we try: g.validate(); CString s0 = g.toString(); // s0 == "" // Guids use ZeroInit Policy, so it's initial value is all zeros, but since it uses ZeroCheck as well, zero values are forbidden from being valid, so // the result is the same, we need to give the guid a value before it may be used.

// Here I'm copying MyProfile.oGUID into an unguarded GUID Hashes::Guid g2 = MyProfile.oGUID; CString s2 = g2.toString(); // s2 is is your local guid (assuming MyProfile.oGUID was initialized before) as a windows style guid string but stripped of the curly braces // you could also use toString() without a named guid (but we need to do an explicit cast in this case, so a temporary copy is created anyway): CString s3 = Hashes::Guid( MyProfile.oGUID ).toString();

// if we wanted a hex string we'd do CString s4 = g2.toString< Hashes::base16Encoding >();

// for a base32 string we do CString s5 = g2.toString< Hashes::base32Encoding >();

// now lets create some random GUID (not very elegant, but it will do) Hashes::Guid random; for ( size_t i = 0; i < Hashes::Guid::byteCount; ++i ) random[ i ] = uchar( rand() ); random.validate(); // don't forget // now have fun with it

// or lets use CNetwork::CreateID() Hashes::Guid random2; Network.CreateID( random2 ); // makes you think why CreateID takes a reference parameter instead of returning a GUID // have fun with random2 </source>