void AvHGamerules::DisplayVersioning() { struct MemoryStruct theChunk; CURLcode theCode = PopulateChunkFromURL(BuildVersionURL(), theChunk); // Now parse data and add users for each mask if((theCode == CURLE_OK) && theChunk.memory) { string theString(theChunk.memory, theChunk.size); string theDelimiters("\r\n"); StringVector theLines; Tokenizer::split(theString, theDelimiters, theLines); if(theLines.size() > 0) { string theCurrentVersion(theLines[0]); string theCurrentGameVersion = AvHSUGetGameVersionString(); char theMessage[1024]; if(theCurrentGameVersion != theCurrentVersion) { sprintf(theMessage, "\tServer out of date. NS version %s is now available!\n", theCurrentVersion.c_str()); ALERT(at_console, theMessage); } else { sprintf(theMessage, "\tServer version is up to date.\n"); ALERT(at_console, theMessage); } } } }
void Draw(BRect updateRect) { const float kSpacing = 20.0; const float kTopOffset = kSpacing + 5; const uint32 kTruncateModes[] = { B_TRUNCATE_BEGINNING, B_TRUNCATE_MIDDLE, B_TRUNCATE_END }; const uint32 kTruncateModeCount = sizeof(kTruncateModes) / sizeof(kTruncateModes[0]); BString theString("ö&ä|ü-é#"); BPoint point(10, kTopOffset); BString truncated; for (float length = 5; length < 65; length += 3) { SetHighColor(255, 0, 0); StrokeRect(BRect(point.x, point.y - kSpacing, point.x + length, point.y + kSpacing * kTruncateModeCount)); SetHighColor(0, 0, 0); for (uint32 i = 0; i < kTruncateModeCount; i++) { truncated = theString; TruncateString(&truncated, kTruncateModes[i], length); DrawString(truncated.String(), point); point.y += kSpacing; } point.x += length + kSpacing; point.y = kTopOffset; } }
XObjectPtr FunctionFormatNumber::execute( XPathExecutionContext& executionContext, XalanNode* context, const XObjectPtr arg1, const XObjectPtr arg2, const XObjectPtr arg3, const LocatorType* locator) const { assert(arg1.null() == false && arg2.null() == false && arg3.null() == false); const double theNumber = arg1->num(); const XalanDOMString& thePattern = arg2->str(); const XalanDOMString& theDFSName = arg3->str(); assert(length(theDFSName) != 0); typedef XPathExecutionContext::GetAndReleaseCachedString GetAndReleaseCachedString; GetAndReleaseCachedString theString(executionContext); executionContext.formatNumber( theNumber, thePattern, theDFSName, theString.get(), context, locator); return executionContext.getXObjectFactory().createString(theString); }
void CTEFActiveFixtureUT::TestCTestConfig_Negtive() { TInt theInt = 10; iConfig.WriteInt(_L("Int"),theInt); (void)iConfig.GetInt(_L("Int"),theInt); TBool theBool = false; (void)iConfig.WriteBool(_L("BoolFalse"),theBool); (void)iConfig.GetBool(_L("BoolFalse"),theBool); (void)iConfig.GetBool(_L("BoolTrue"),theBool); theInt = 0xff; (void)iConfig.WriteHex(_L("Hex"),theInt); (void)iConfig.GetHex(_L("Hex"),theInt); _LIT(KTestString,"To Be A Drummer! # comments"); TPtrC theString(KTestString); (void)iConfig.WriteString(_L("String"),theString); TBool res = iConfig.GetString(_L("String"),theString); ASSERT_TRUE(res); }
void ZStrimW_WinDebug::Imp_WriteUTF8(const UTF8* iSource, size_t iCountCU, size_t* oCountCU) { std::string theString(iSource, iCountCU); ::OutputDebugStringA(theString.c_str()); if (oCountCU) *oCountCU = iCountCU; }
void ZipTest::test_openAppendToZipWithFileAlreadyExisting() { bool expected = false; std::string zipFileName = tempFolder + "/" + zipFile; createFolder(zipFileName); copyFile(zipFile, zipFileName); //first open zip->open(zipFileName, OpenFlags::OpenExisting); std::string theString("Lorem Ipsum..."); std::vector<unsigned char> content; content.insert(content.end(), theString.begin(), theString.end()); zip->addFile("file1.txt", content); zip->close(); //second open zip->open(zipFileName, OpenFlags::OpenExisting); theString = "Lorem Ipsum Number 2..."; content.insert(content.end(), theString.begin(), theString.end()); bool actual = zip->addFile("file1.txt", content); zip->close(); CPPUNIT_ASSERT_EQUAL_MESSAGE("add", expected, actual); CPPUNIT_ASSERT_EQUAL_MESSAGE("contains", true, containsFile(zipFileName, "file1.txt")); CPPUNIT_ASSERT_EQUAL_MESSAGE("count", 7, numFilesInZip(zipFileName)); }
std::string transcodeString( const XMLCh *const toTranscode ) { char *fLocalForm = xercesc::XMLString::transcode( toTranscode ); std::string theString( fLocalForm ); xercesc::XMLString::release( &fLocalForm ); return theString; }
TPtrC8 CTzDbStringsTable::GetStringL(TUint aReferenceToString) { const TInt KStringsBaseAddress = (TInt)&iPersistedEntity; const TInt KLengthAddress = KStringsBaseAddress + aReferenceToString; const TInt KStringAddress = KLengthAddress + 1; // length occupies 1 byte TUint8 length = *(reinterpret_cast<TUint8*>(KLengthAddress)); TPtrC8 theString(reinterpret_cast<TUint8*>(KStringAddress),length); return theString; }
static string sReadString(const ZStreamU& s) { const int32 stringLength = sReadInteger(s); const uint8 terminator = s.ReadUInt8(); if (terminator != ':') throw runtime_error("Expected ':' terminator for string length"); string theString(stringLength, 0); s.Read(const_cast<char*>(theString.data()), stringLength); return theString; }
void readString(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { if(nlhs < 1) mexErrMsgTxt("One output argument required."); NetClient *nc = GetNetClient(nrhs, prhs); try { std::string theString ( nc->receiveString() ); plhs[0] = mxCreateString(theString.c_str()); } catch (const SocketException & e) { mexWarnMsgTxt(e.why().c_str()); RETURN_NULL(); // note empty return.. } }
void sendString(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { NetClient *nc = GetNetClient(nrhs, prhs); if(nrhs != 2) mexErrMsgTxt("Two arguments required: handle, string."); //if(nlhs < 1) mexErrMsgTxt("One output argument required."); if(mxGetClassID(prhs[1]) != mxCHAR_CLASS) mexErrMsgTxt("Argument 2 must be a string."); char *tmp = mxArrayToString(prhs[1]); std::string theString (tmp); mxFree(tmp); try { nc->sendString(theString); } catch (const SocketException & e) { mexWarnMsgTxt(e.why().c_str()); RETURN_NULL(); } RETURN(1); }
void CTEFActiveFixtureUT::TestCTestConfig() { TInt theInt = 10; TBool res = iConfig.GetInt(_L("Int"),theInt); ASSERT_TRUE(res); ASSERT_TRUE(theInt == 10); TBool theBool = false; res = iConfig.WriteBool(_L("BoolFalse"),theBool); ASSERT_TRUE(res); res = iConfig.GetBool(_L("BoolFalse"),theBool); ASSERT_TRUE(res); ASSERT_TRUE(theBool == false); res = iConfig.GetBool(_L("BoolTrue"),theBool); ASSERT_TRUE(res); ASSERT_TRUE(theBool == true); theInt = 0xff; res = iConfig.WriteHex(_L("Hex"),theInt); ASSERT_TRUE(res); res = iConfig.GetHex(_L("Hex"),theInt); ASSERT_TRUE(res); ASSERT_TRUE(theInt == 0xff); _LIT(KTestString,"To Be A Drummer! # comments"); TPtrC theString(KTestString); res = iConfig.WriteString(_L("String"),theString); ASSERT_TRUE(res); res = iConfig.GetString(_L("String"),theString); ASSERT_TRUE(res); ASSERT_FALSE(theString.Compare(KTestString) ); test_Int64_Step_Suite(); }
Bool16 StringParser::Test() { static char* string1 = "RTSP 200 OK\r\nContent-Type: MeowMix\r\n\t \n3450"; StrPtrLen theString(string1, strlen(string1)); StringParser victim(&theString); StrPtrLen rtsp; SInt32 theInt = victim.ConsumeInteger(); if (theInt != 0) return false; victim.ConsumeWord(&rtsp); if ((rtsp.len != 4) && (strncmp(rtsp.Ptr, "RTSP", 4) != 0)) return false; victim.ConsumeWhiteSpace(); theInt = victim.ConsumeInteger(); if (theInt != 200) return false; return true; }
NS_IMETHODIMP nsPrefBranch::GetComplexValue(const char *aPrefName, const nsIID & aType, void * *_retval) { nsresult rv; nsXPIDLCString utf8String; // we have to do this one first because it's different than all the rest if (aType.Equals(NS_GET_IID(nsIPrefLocalizedString))) { nsCOMPtr<nsIPrefLocalizedString> theString(do_CreateInstance(NS_PREFLOCALIZEDSTRING_CONTRACTID, &rv)); if (NS_SUCCEEDED(rv)) { const char *pref; PRBool bNeedDefault = PR_FALSE; rv = getValidatedPrefName(aPrefName, &pref); if (NS_FAILED(rv)) return rv; if (mIsDefault) { bNeedDefault = PR_TRUE; } else { // if there is no user (or locked) value if (!PREF_HasUserPref(pref) && !PREF_PrefIsLocked(pref)) { bNeedDefault = PR_TRUE; } } // if we need to fetch the default value, do that instead, otherwise use the // value we pulled in at the top of this function if (bNeedDefault) { nsXPIDLString utf16String; rv = GetDefaultFromPropertiesFile(pref, getter_Copies(utf16String)); if (NS_SUCCEEDED(rv)) { rv = theString->SetData(utf16String.get()); } } else { rv = GetCharPref(aPrefName, getter_Copies(utf8String)); if (NS_SUCCEEDED(rv)) { rv = theString->SetData(NS_ConvertUTF8toUCS2(utf8String).get()); } } if (NS_SUCCEEDED(rv)) { nsIPrefLocalizedString *temp = theString; NS_ADDREF(temp); *_retval = (void *)temp; } } return rv; } // if we can't get the pref, there's no point in being here rv = GetCharPref(aPrefName, getter_Copies(utf8String)); if (NS_FAILED(rv)) { return rv; } if (aType.Equals(NS_GET_IID(nsILocalFile))) { nsCOMPtr<nsILocalFile> file(do_CreateInstance(NS_LOCAL_FILE_CONTRACTID, &rv)); if (NS_SUCCEEDED(rv)) { rv = file->SetPersistentDescriptor(utf8String); if (NS_SUCCEEDED(rv)) { nsILocalFile *temp = file; NS_ADDREF(temp); *_retval = (void *)temp; return NS_OK; } } return rv; } if (aType.Equals(NS_GET_IID(nsIRelativeFilePref))) { nsACString::const_iterator keyBegin, strEnd; utf8String.BeginReading(keyBegin); utf8String.EndReading(strEnd); // The pref has the format: [fromKey]a/b/c if (*keyBegin++ != '[') return NS_ERROR_FAILURE; nsACString::const_iterator keyEnd(keyBegin); if (!FindCharInReadable(']', keyEnd, strEnd)) return NS_ERROR_FAILURE; nsCAutoString key(Substring(keyBegin, keyEnd)); nsCOMPtr<nsILocalFile> fromFile; nsCOMPtr<nsIProperties> directoryService(do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID, &rv)); if (NS_FAILED(rv)) return rv; rv = directoryService->Get(key.get(), NS_GET_IID(nsILocalFile), getter_AddRefs(fromFile)); if (NS_FAILED(rv)) return rv; nsCOMPtr<nsILocalFile> theFile; rv = NS_NewNativeLocalFile(EmptyCString(), PR_TRUE, getter_AddRefs(theFile)); if (NS_FAILED(rv)) return rv; rv = theFile->SetRelativeDescriptor(fromFile, Substring(++keyEnd, strEnd)); if (NS_FAILED(rv)) return rv; nsCOMPtr<nsIRelativeFilePref> relativePref; rv = NS_NewRelativeFilePref(theFile, key, getter_AddRefs(relativePref)); if (NS_FAILED(rv)) return rv; *_retval = relativePref; NS_ADDREF(NS_STATIC_CAST(nsIRelativeFilePref*, *_retval)); return NS_OK; }
size_t wxMBConv_cf::ToWChar(wchar_t * dst, size_t dstSize, const char * src, size_t srcSize) const { wxCHECK(src, wxCONV_FAILED); /* NOTE: This is wrong if the source encoding has an element size * other than char (e.g. it's kCFStringEncodingUnicode) * If the user specifies it, it's presumably right though. * Right now we don't support UTF-16 in anyway since wx can do a better job. */ if(srcSize == wxNO_LEN) srcSize = strlen(src) + 1; // First create the temporary CFString wxCFRef<CFStringRef> theString( CFStringCreateWithBytes ( NULL, //the allocator (const UInt8*)src, srcSize, m_encoding, false //no BOM/external representation )); if ( theString == NULL ) return wxCONV_FAILED; // Ensure that the string is in canonical composed form (NFC): this is // important because Darwin uses decomposed form (NFD) for e.g. file // names but we want to use NFC internally. wxCFRef<CFMutableStringRef> cfMutableString(CFStringCreateMutableCopy(NULL, 0, theString)); CFStringNormalize(cfMutableString, kCFStringNormalizationFormC); theString = cfMutableString; /* NOTE: The string content includes the NULL element if the source string did * That means we have to do nothing special because the destination will have * the NULL element iff the source did and the NULL element will be included * in the count iff it was included in the source count. */ /* If we're compiling against Tiger headers we can support direct conversion * to UTF32. If we are then run against a pre-Tiger system, the encoding * won't be available so we'll defer to the string->UTF-16->UTF-32 conversion. */ if(CFStringIsEncodingAvailable(wxCFStringEncodingWcharT)) { CFRange fullStringRange = CFRangeMake(0, CFStringGetLength(theString)); CFIndex usedBufLen; CFIndex charsConverted = CFStringGetBytes( theString, fullStringRange, wxCFStringEncodingWcharT, 0, false, // if dstSize is 0 then pass NULL to get required length in usedBufLen dstSize != 0?(UInt8*)dst:NULL, dstSize * sizeof(wchar_t), &usedBufLen); if(charsConverted < CFStringGetLength(theString)) return wxCONV_FAILED; /* usedBufLen is the number of bytes written, so we divide by * sizeof(wchar_t) to get the number of elements written. */ wxASSERT( (usedBufLen % sizeof(wchar_t)) == 0 ); // CFStringGetBytes does exactly the right thing when buffer // pointer is NULL and returns the number of bytes required return usedBufLen / sizeof(wchar_t); } else { // NOTE: Includes NULL iff source did /* NOTE: This is an approximation. The eventual UTF-32 will * possibly have less elements but certainly not more. */ size_t returnSize = CFStringGetLength(theString); if (dstSize == 0 || dst == NULL) { return returnSize; } // Convert the entire string.. too hard to figure out how many UTF-16 we'd need // for an undersized UTF-32 destination buffer. CFRange fullStringRange = CFRangeMake(0, CFStringGetLength(theString)); UniChar *szUniCharBuffer = new UniChar[fullStringRange.length]; CFStringGetCharacters(theString, fullStringRange, szUniCharBuffer); wxMBConvUTF16 converter; returnSize = converter.ToWChar( dst, dstSize, (const char*)szUniCharBuffer, fullStringRange.length ); delete [] szUniCharBuffer; return returnSize; } // NOTREACHED }
void AvHGamerules::InitializeAuthentication() { bool theSuccess = false; ALERT(at_console, "\tReading authentication data..."); struct MemoryStruct theChunk; CURLcode theCode = PopulateChunkFromURL(BuildAuthenticationURL(), theChunk); // Now parse data and add users for each mask if((theCode == CURLE_OK) && theChunk.memory) { // Clear existing authentication data, only after lookup succeeds gAuthMaskList.clear(); string theString(theChunk.memory); string theDelimiters("\r\n"); StringVector theLines; Tokenizer::split(theString, theDelimiters, theLines); // Run through each line int theNumConstellationMembers = 0; for(StringVector::const_iterator theIter = theLines.begin(); theIter != theLines.end(); theIter++) { char *msg=(char *)(*theIter).c_str(); // If it's not empty and not a comment char theFirstChar = (*theIter)[0]; if((theFirstChar != '/') && (theFirstChar != '#')) { // Split up tag and number StringVector theTokens; if(Tokenizer::split(*theIter, " ", theTokens) == 3) { // Translate tag to auth mask string theTag = theTokens[0]; string theWONID = theTokens[1]; string theSteamID = theTokens[2]; // Upper-case prefix UppercaseString(theSteamID); // Make sure it starts with "STEAM_X:Y" if(strncmp(theSteamID.c_str(), kSteamIDPrefix, strlen(kSteamIDPrefix))) { string theNewSteamID = kSteamIDPrefix + theSteamID; theSteamID = theNewSteamID; } // Add auth status AvHPlayerAuthentication theMask = PLAYERAUTH_NONE; if(TagToAuthMask(theTag, theMask)) { // Count Constellation members fyi if(theMask & PLAYERAUTH_CONTRIBUTOR) { theNumConstellationMembers++; } if((theWONID != "") || (theSteamID != "")) { #ifdef DEBUG char theMessage[512]; sprintf(theMessage, " Adding auth mask: %s %s %s\n", theTag.c_str(), theWONID.c_str(), theSteamID.c_str()); ALERT(at_logged, theMessage); #endif this->AddAuthStatus(theMask, theWONID, theSteamID); theSuccess = true; } } } } } // Breakpoint to see how many Constellation members there are (don't even think of printing or logging) int a = 0; } else { int a = 0; } // Now build server op list this->mServerOpList.clear(); // Parse contents server op variable string theServerOpsString(avh_serverops.string); // Tokenize string StringVector theServerOpsStrings; Tokenizer::split(theServerOpsString, ";", theServerOpsStrings); // For each in list, add as an int to our list for(StringVector::const_iterator theIter = theServerOpsStrings.begin(); theIter != theServerOpsStrings.end(); theIter++) { // Add whatever the put in this line as both the WONID and SteamID string theCurrentAuthID = *theIter; this->mServerOpList.push_back( make_pair(theCurrentAuthID, theCurrentAuthID)); } if(theSuccess) { ALERT(at_console, "success.\n"); } else { ALERT(at_console, "failure.\n"); } gTimeLastUpdatedUplink = AvHSUTimeGetTime(); }
void processEvent(podio::EventStore& store, bool verboser, unsigned eventNum) { auto& failing = store.get<ExampleClusterCollection>("notthere"); if(failing.isValid() == true) { throw std::runtime_error("Collection 'notthere' should not be valid"); }; auto& strings = store.get<ExampleWithStringCollection>("strings"); if(strings.isValid()){ auto string = strings[0]; if (string.theString() != "SomeString") { throw std::runtime_error("Couldn't read string properly"); } } else { throw std::runtime_error("Collection 'strings' should be present."); } auto& clusters = store.get<ExampleClusterCollection>("clusters"); if(clusters.isValid()){ auto cluster = clusters[0]; for (auto i = cluster.Hits_begin(), end = cluster.Hits_end(); i!=end; ++i){ std::cout << " Referenced hit has an energy of " << i->energy() << std::endl; glob++; } } else { throw std::runtime_error("Collection 'clusters' should be present"); } auto& mcps = store.get<ExampleMCCollection>("mcparticles"); if( mcps.isValid() ){ // check that we can retrieve the correct parent daughter relation // set in write.cpp : // particle 0 has particles 2,3,4 and 5 as daughters: auto p = mcps[0] ; //-------- print relations for debugging: for( auto p : mcps ){ std::cout << " particle " << p.getObjectID().index << " has daughters: " ; for(auto it = p.daughters_begin(), end = p.daughters_end() ; it!=end ; ++it ){ std::cout << " " << it->getObjectID().index ; } std::cout << " and parents: " ; for(auto it = p.parents_begin(), end = p.parents_end() ; it!=end ; ++it ){ std::cout << " " << it->getObjectID().index ; } std::cout << std::endl ; } auto d0 = p.daughters(0) ; auto d1 = p.daughters(1) ; auto d2 = p.daughters(2) ; auto d3 = p.daughters(3) ; if( ! ( d0 == mcps[2] ) ) throw std::runtime_error(" error: 1. daughter of particle 0 is not particle 2 "); if( ! ( d1 == mcps[3] ) ) throw std::runtime_error(" error: 2. daughter of particle 0 is not particle 3 "); if( ! ( d2 == mcps[4] ) ) throw std::runtime_error(" error: 3. daughter of particle 0 is not particle 4 "); if( ! ( d3 == mcps[5] ) ) throw std::runtime_error(" error: 4. daughter of particle 0 is not particle 5 "); // particle 3 has particles 6,7,8 and 9 as daughters: p = mcps[3] ; d0 = p.daughters(0) ; d1 = p.daughters(1) ; d2 = p.daughters(2) ; d3 = p.daughters(3) ; if( ! ( d0 == mcps[6] ) ) throw std::runtime_error(" error: 1. daughter of particle 3 is not particle 6 "); if( ! ( d1 == mcps[7] ) ) throw std::runtime_error(" error: 2. daughter of particle 3 is not particle 7 "); if( ! ( d2 == mcps[8] ) ) throw std::runtime_error(" error: 3. daughter of particle 3 is not particle 8 "); if( ! ( d3 == mcps[9] ) ) throw std::runtime_error(" error: 4. daughter of particle 3 is not particle 9 "); } else { throw std::runtime_error("Collection 'mcparticles' should be present"); } //std::cout << "Fetching collection 'refs'" << std::endl; auto& refs = store.get<ExampleReferencingTypeCollection>("refs"); if(refs.isValid()){ auto ref = refs[0]; for (auto j = ref.Clusters_begin(), end = ref.Clusters_end(); j!=end; ++j){ for (auto i = j->Hits_begin(), end = j->Hits_end(); i!=end; ++i){ //std::cout << " Referenced object has an energy of " << i->energy() << std::endl; glob++; } } } else { throw std::runtime_error("Collection 'refs' should be present"); } //std::cout << "Fetching collection 'OneRelation'" << std::endl; auto& rels = store.get<ExampleWithOneRelationCollection>("OneRelation"); if(rels.isValid()) { //std::cout << "Referenced object has an energy of " << (*rels)[0].cluster().energy() << std::endl; glob++; } else { throw std::runtime_error("Collection 'OneRelation' should be present"); } // std::cout << "Fetching collection 'WithVectorMember'" << std::endl; auto& vecs = store.get<ExampleWithVectorMemberCollection>("WithVectorMember"); if(vecs.isValid()) { std::cout << vecs.size() << std::endl; for( auto item : vecs ) for (auto c = item.count_begin(), end = item.count_end(); c!=end; ++c){ std::cout << " Counter value " << (*c) << std::endl; glob++; } } else { throw std::runtime_error("Collection 'WithVectorMember' should be present"); } auto& comps = store.get<ExampleWithComponentCollection>("Component"); if (comps.isValid()) { auto comp = comps[0]; int a = comp.component().data.x + comp.component().data.z; } auto& arrays = store.get<ExampleWithArrayCollection>("arrays"); if (arrays.isValid() && arrays.size() != 0) { auto array = arrays[0]; if (array.myArray(1) != eventNum) { throw std::runtime_error("Array not properly set."); } if (array.arrayStruct().data.p.at(2) != 2*eventNum) { throw std::runtime_error("Array not properly set."); } if (array.structArray(0).x != eventNum) { throw std::runtime_error("Array of struct not properly set."); } } else { throw std::runtime_error("Collection 'arrays' should be present"); } auto& nmspaces = store.get<ex::ExampleWithARelationCollection>("WithNamespaceRelation"); auto& copies = store.get<ex::ExampleWithARelationCollection>("WithNamespaceRelationCopy"); auto& cpytest = store.create<ex::ExampleWithARelationCollection>("TestConstCopy"); if (nmspaces.isValid() && copies.isValid()) { for (int j = 0; j < nmspaces.size(); j++) { auto nmsp = nmspaces[j]; auto cpy = copies[j]; cpytest.push_back(nmsp.clone()); if (nmsp.ref().isAvailable()) { if (nmsp.ref().data().x != cpy.ref().data().x || nmsp.ref().data().y != cpy.ref().data().y) { throw std::runtime_error("Copied item has differing data in OneToOne referenced item."); } // check direct accessors of POD sub members if (nmsp.ref().x() != cpy.ref().x()) { throw std::runtime_error("Getting wrong values when using direct accessors for sub members."); } if (nmsp.number() != cpy.number()) { throw std::runtime_error("Copied item has differing member."); } if (!(nmsp.ref().getObjectID() == cpy.ref().getObjectID())) { throw std::runtime_error("Copied item has wrong OneToOne references."); } } auto cpy_it = cpy.refs_begin(); for (auto it = nmsp.refs_begin(); it != nmsp.refs_end(); ++it, ++cpy_it) { if (it->data().x != cpy_it->data().x || it->data().y != cpy_it->data().y) { throw std::runtime_error("Copied item has differing data in OneToMany referenced item."); } if (!(it->getObjectID() == cpy_it->getObjectID())) { throw std::runtime_error("Copied item has wrong OneToMany references."); } } } } else { throw std::runtime_error("Collection 'WithNamespaceRelation' and 'WithNamespaceRelationCopy' should be present"); } }
void RefPtrTest::onEnter() { UnitTestDemo::onEnter(); #if DEBUG // TEST(constructors) { // Default constructor RefPtr<Ref> ref1; CC_ASSERT(nullptr == ref1.get()); // Parameter constructor RefPtr<__String> ref2(cocos2d::String::create("Hello")); CC_ASSERT(strcmp("Hello", ref2->getCString()) == 0); CC_ASSERT(2 == ref2->getReferenceCount()); // Parameter constructor with nullptr RefPtr<__String> ref3(nullptr); CC_ASSERT((__String*) nullptr == ref3.get()); // Copy constructor RefPtr<__String> ref4(ref2); CC_ASSERT(strcmp("Hello", ref4->getCString()) == 0); CC_ASSERT(3 == ref2->getReferenceCount()); CC_ASSERT(3 == ref4->getReferenceCount()); // Copy constructor with nullptr reference RefPtr<Ref> ref5(ref1); CC_ASSERT((Ref*) nullptr == ref5.get()); } // TEST(destructor) { __String * hello = __String::create("Hello"); CC_ASSERT(1 == hello->getReferenceCount()); { RefPtr<Ref> ref(hello); CC_ASSERT(2 == hello->getReferenceCount()); } CC_ASSERT(1 == hello->getReferenceCount()); } // TEST(assignmentOperator) { // Test basic assignment with pointer RefPtr<__String> ref1; CC_ASSERT((Ref*) nullptr == ref1.get()); ref1 = __String::create("World"); CC_ASSERT(strcmp("World", ref1->getCString()) == 0); CC_ASSERT(2 == ref1->getReferenceCount()); // Assigment back to nullptr __String * world = ref1; CC_ASSERT(2 == world->getReferenceCount()); ref1 = nullptr; CC_ASSERT(1 == world->getReferenceCount()); // Assignment swapping ref1 = __String::create("Hello"); CC_ASSERT(strcmp("Hello", ref1->getCString()) == 0); CC_ASSERT(2 == ref1->getReferenceCount()); __String * hello = (__String*) ref1; CC_ASSERT(2 == hello->getReferenceCount()); ref1 = world; CC_ASSERT(1 == hello->getReferenceCount()); CC_ASSERT(2 == world->getReferenceCount()); // Test assignment with another reference RefPtr<__String> ref2 = __String::create("blah"); __String * blah = ref2; CC_ASSERT(2 == blah->getReferenceCount()); ref2 = ref1; CC_ASSERT(1 == blah->getReferenceCount()); CC_ASSERT(3 == world->getReferenceCount()); } // TEST(castBackToPointerOperator) { RefPtr<__String> ref1 = __String::create("Hello"); __String * helloPtr = ref1; Ref * objectPtr = ref1; CC_ASSERT(helloPtr == objectPtr); } // TEST(dereferenceOperators) { RefPtr<__String> ref1 = __String::create("Hello"); CC_ASSERT(strcmp("Hello", ref1->getCString()) == 0); CC_ASSERT(strcmp("Hello", (*ref1).getCString()) == 0); } // TEST(convertToBooleanOperator) { RefPtr<__String> ref1 = __String::create("Hello"); CC_ASSERT(true == (bool) ref1); ref1 = nullptr; CC_ASSERT(false == (bool) ref1); } // TEST(get) { RefPtr<__String> ref1 = __String::create("Hello"); CC_ASSERT(strcmp("Hello", ref1.get()->getCString()) == 0); ref1.reset(); CC_ASSERT((__String*) nullptr == ref1.get()); } // TEST(reset) { RefPtr<__String> ref1; CC_ASSERT((__String*) nullptr == ref1.get()); ref1.reset(); CC_ASSERT((__String*) nullptr == ref1.get()); ref1 = __String::create("Hello"); CC_ASSERT(strcmp("Hello", ref1.get()->getCString()) == 0); __String * hello = ref1.get(); CC_ASSERT(2 == hello->getReferenceCount()); ref1.reset(); CC_ASSERT((__String*) nullptr == ref1.get()); CC_ASSERT(1 == hello->getReferenceCount()); } // TEST(swap) { RefPtr<__String> ref1; RefPtr<__String> ref2; CC_ASSERT((__String*) nullptr == ref1.get()); CC_ASSERT((__String*) nullptr == ref2.get()); ref1.swap(ref2); CC_ASSERT((__String*) nullptr == ref1.get()); CC_ASSERT((__String*) nullptr == ref2.get()); __String * hello = __String::create("Hello"); CC_ASSERT(1 == hello->getReferenceCount()); ref1 = hello; CC_ASSERT(2 == hello->getReferenceCount()); ref1.swap(ref2); CC_ASSERT(2 == hello->getReferenceCount()); CC_ASSERT((__String*) nullptr == ref1.get()); CC_ASSERT(strcmp("Hello", ref2->getCString()) == 0); ref1.swap(ref2); CC_ASSERT(2 == hello->getReferenceCount()); CC_ASSERT(strcmp("Hello", ref1->getCString()) == 0); CC_ASSERT((__String*) nullptr == ref2.get()); __String * world = __String::create("World"); CC_ASSERT(1 == world->getReferenceCount()); ref2 = world; CC_ASSERT(2 == world->getReferenceCount()); ref2.swap(ref1); CC_ASSERT(strcmp("World", ref1->getCString()) == 0); CC_ASSERT(strcmp("Hello", ref2->getCString()) == 0); CC_ASSERT(2 == hello->getReferenceCount()); CC_ASSERT(2 == world->getReferenceCount()); ref1.swap(ref2); CC_ASSERT(strcmp("Hello", ref1->getCString()) == 0); CC_ASSERT(strcmp("World", ref2->getCString()) == 0); CC_ASSERT(2 == hello->getReferenceCount()); CC_ASSERT(2 == world->getReferenceCount()); } // TEST(staticPointerCast) { RefPtr<__String> ref1 = __String::create("Hello"); CC_ASSERT(2 == ref1->getReferenceCount()); RefPtr<Ref> ref2 = static_pointer_cast<Ref>(ref1); CC_ASSERT(strcmp("Hello", ((__String*) ref2.get())->getCString()) == 0); CC_ASSERT(3 == ref1->getReferenceCount()); } // TEST(dynamicPointerCast) { RefPtr<__String> ref1 = cocos2d::String::create("Hello"); CC_ASSERT(2 == ref1->getReferenceCount()); RefPtr<Ref> ref2 = dynamic_pointer_cast<Ref>(ref1); CC_ASSERT(strcmp("Hello", ((__String*) ref2.get())->getCString()) == 0); CC_ASSERT(3 == ref1->getReferenceCount()); RefPtr<__String> ref3 = dynamic_pointer_cast<__String>(ref2); CC_ASSERT(strcmp("Hello", ref3->getCString()) == 0); CC_ASSERT(4 == ref1->getReferenceCount()); RefPtr<cocos2d::Node> ref4 = dynamic_pointer_cast<cocos2d::Node>(ref2); CC_ASSERT((Ref*) nullptr == ref4.get()); } // TEST(weakAssign) { RefPtr<__String> ref1; __String * string1 = new __String("Hello"); ref1.weakAssign(string1); CC_ASSERT(1 == string1->getReferenceCount()); RefPtr<__String> ref2 = ref1; CC_ASSERT(2 == string1->getReferenceCount()); __String * string2 = new __String("World"); ref1.weakAssign(string2); CC_ASSERT(1 == string1->getReferenceCount()); CC_ASSERT(1 == ref2->getReferenceCount()); __String * string3 = new __String("Blah"); RefPtr<__String> ref3; ref3.weakAssign(string3); CC_ASSERT(1 == string3->getReferenceCount()); string3->retain(); CC_ASSERT(2 == string3->getReferenceCount()); ref3.weakAssign(nullptr); CC_ASSERT(1 == string3->getReferenceCount()); CC_SAFE_RELEASE_NULL(string3); } // TEST(comparisonOperators) { RefPtr<Ref> ref1; RefPtr<Ref> ref2; CC_ASSERT(true == (ref1 == ref2)); CC_ASSERT(false == (ref1 != ref2)); CC_ASSERT(false == (ref1 < ref2)); CC_ASSERT(false == (ref1 > ref2)); CC_ASSERT(true == (ref1 <= ref2)); CC_ASSERT(true == (ref1 >= ref2)); CC_ASSERT(true == (ref1 == nullptr)); CC_ASSERT(false == (ref1 != nullptr)); CC_ASSERT(false == (ref1 < nullptr)); CC_ASSERT(false == (ref1 > nullptr)); CC_ASSERT(true == (ref1 <= nullptr)); CC_ASSERT(true == (ref1 >= nullptr)); CC_ASSERT(false == (ref1 == __String::create("Hello"))); CC_ASSERT(true == (ref1 != __String::create("Hello"))); CC_ASSERT(true == (ref1 < __String::create("Hello"))); CC_ASSERT(false == (ref1 > __String::create("Hello"))); CC_ASSERT(true == (ref1 <= __String::create("Hello"))); CC_ASSERT(false == (ref1 >= __String::create("Hello"))); ref1 = __String::create("Hello"); CC_ASSERT(false == (ref1 == ref2)); CC_ASSERT(true == (ref1 != ref2)); CC_ASSERT(false == (ref1 < ref2)); CC_ASSERT(true == (ref1 > ref2)); CC_ASSERT(false == (ref1 <= ref2)); CC_ASSERT(true == (ref1 >= ref2)); } // TEST(moveConstructor) { auto someFunc = []() -> RefPtr<__String> { return __String::create("Hello world!"); }; // Note: std::move will turn the rvalue into an rvalue reference and thus cause the move constructor to be invoked. // Have to use this because the compiler will try and optimize how we handle the return value otherwise and skip the move constructor. RefPtr<__String> theString(std::move(someFunc())); CC_ASSERT(theString->getReferenceCount() == 2); CC_ASSERT(theString->compare("Hello world!") == 0); __String * theStringPtr = theString; theString.reset(); CC_ASSERT(theStringPtr->getReferenceCount() == 1); CC_ASSERT(theStringPtr->compare("Hello world!") == 0); } // TEST(moveAssignmentOperator) { auto someFunc = []() -> RefPtr<__String> { return __String::create("Hello world!"); }; RefPtr<__String> theString(someFunc()); CC_ASSERT(theString->getReferenceCount() == 2); CC_ASSERT(theString->compare("Hello world!") == 0); theString = someFunc(); // No need to use std::move here, compiler should figure out that move semantics are appropriate for this statement. CC_ASSERT(theString->getReferenceCount() == 2); CC_ASSERT(theString->compare("Hello world!") == 0); } #else log("RefPtr tests are not executed in release mode"); #endif }