void test() { List<int> l; for(int i = 0;i < 5;i++) { l.PushBack(i); } for (int i = 5;i < 10;i++) { l.PushFront(i); } List<int>::Iterator it = l.Begin(); while (it != l.End()) { cout<<*it<<" "; it++; } cout<<endl; l.PopBack(); l.PopBack(); l.PopFront(); l.PopFront(); it = l.Begin(); while (it != l.End()) { cout<<*it<<" "; it++; } cout<<endl; }
void compareWithMyList(List<int> &mylist, List<int> &flist) { Iterator<int> iterator = mylist.Begin(); Iterator<int> iter = flist.Begin(); for(; iterator != mylist.End(); iterator++, iter++) if(*iterator != *iter) { std::cout << "Test error: Compare error" << std::endl; return; } std::cout << "Test completed: Full compare" << std::endl; }
ECode CTextServicesManagerService::FinishSpellCheckerService( /* [in] */ ISpellCheckerSessionListener* listener) { if (!CalledFromValidUser()) { return NOERROR; } if (DBG) { Slogger::D(TAG, "FinishSpellCheckerService"); } { AutoLock lock(mSpellCheckerMapLock); List<AutoPtr<SpellCheckerBindGroup> > removeList; ManagedSpellCheckerBindGroupMapIt it = mSpellCheckerBindGroups.Begin(); for (; it != mSpellCheckerBindGroups.End(); ++it) { AutoPtr<SpellCheckerBindGroup> group = it->mSecond; if (group == NULL) continue; removeList.PushBack(group); } List<AutoPtr<SpellCheckerBindGroup> >::Iterator it2 = removeList.Begin(); for (; it2 != removeList.End(); ++it2) { ((*it2).Get())->RemoveListener(listener); } removeList.Clear(); } return NOERROR; }
bool TestList2() { List l; l.PushBack(-1); l.PushBack(0); l.PushBack(1); l.PushBack(2); l.PushBack(3); l.PushBack(4); l.PushBack(5); l.PushBack(6); l.PushBack(7); l.PushBack(8); l.PushBack(9); l.PopFront(); int result[10] = {0}; int* i = Transform(l.Begin(), l.End(), Square, result); if(i != result + 10) return false; if(!CheckResult(result)) return false; return true; }
ECode MessageFormat::FormatToCharacterIterator( /* [in] */ IInterface* object, /* [out] */ IAttributedCharacterIterator** characterIterator) { VALIDATE_NOT_NULL(characterIterator); *characterIterator = NULL; VALIDATE_NOT_NULL(object); StringBuffer buffer; List<AutoPtr<FieldContainer> > fields; // format the message, and find fields AutoPtr<IFieldPosition> position; CFieldPosition::New(0, (IFieldPosition**)&position); AutoPtr<ArrayOf<IInterface*> > arr = ArrayOf<IInterface*>::Alloc(1); arr->Set(0, object); FormatImpl(arr, &buffer, position, &fields); // create an AttributedString with the formatted buffer AutoPtr<IAttributedString> as; String outstr; buffer.Substring(0, buffer.GetLength(),&outstr); CAttributedString::New(outstr, (IAttributedString**)&as); // add MessageFormat field attributes and values to the AttributedString List<AutoPtr<FieldContainer> >::Iterator fc = fields.Begin(); for ( ; fc != fields.End(); ++fc) { FAIL_RETURN(as->AddAttribute((*fc)->mAttribute, (*fc)->mValue, (*fc)->mStart, (*fc)->mEnd)); } // return the CharacterIterator from AttributedString return as->GetIterator(characterIterator); }
bool operator == (const List<T>& x1, const List<T>& x2) { typename List<T>::ConstIterator i1, i2; for ( i1 = x1.Begin(), i2 = x2.Begin(); (i1 != x1.End()) && (i2 != x2.End()); ++i1, ++i2 ) { if (*(i1) != *(i2)) return 0; } if (i1 != x1.End() || i2 != x2.End()) return 0; return 1; }
void Observer::EnablePendingListeners() { List<AutoPtr<IObserverListener> > pendingListeners; { AutoLock lock(this); List<AutoPtr<WrappedListener> >::Iterator it; for (it = mListeners.Begin(); it != mListeners.End(); ++it) { if (!(*it)->mEnabled) { pendingListeners.PushBack((*it)->mListener); (*it)->mEnabled = TRUE; } } } /* we have threading guarantees from the Core that the proxies set will not change * during this call. Therefore, we don't need to do anything special to safeguard * proxies during iteration. */ AutoPtr<ICollection> collection; mProxies->GetValues((ICollection**)&collection); List<AutoPtr<IObserverListener> >::Iterator it; for (it = pendingListeners.Begin(); it != pendingListeners.End(); ++it) { AutoPtr<IIterator> pit; collection->GetIterator((IIterator**)&pit); Boolean hasNext; while (pit->HasNext(&hasNext), hasNext) { AutoPtr<IInterface> obj; pit->GetNext((IInterface**)&obj); (*it)->ObjectDiscovered(IProxyBusObject::Probe(obj)); } } }
ECode CSerialService::GetSerialPorts( /* [out, callee] */ ArrayOf<String>** serialPorts) { FAIL_RETURN(mContext->EnforceCallingOrSelfPermission(Elastos::Droid::Manifest::Permission::SERIAL_PORT, String(NULL))); List<String> ports; Int32 length = mSerialPorts->GetLength(); for (Int32 i = 0; i < length; i++) { String path((*mSerialPorts)[i]); AutoPtr<IFile> file; CFile::New(path, (IFile**)&file); Boolean isExist; file->Exists(&isExist); if (isExist) { ports.PushBack(path); } } *serialPorts = ArrayOf<String>::Alloc(ports.GetSize()); REFCOUNT_ADD(*serialPorts); List<String>::Iterator it = ports.Begin(); for (Int32 i = 0; it != ports.End(); ++it, i++) { (**serialPorts)[i] = *it; } return NOERROR; }
void PrintList2(const List<int>& l1) { List<int>::ConstIterator it = l1.Begin(); for (; it != l1.End(); ++it) { cout<<*it<<" "; } cout<<endl; }
/** * Updates the state of the logical display based on the available display devices. * The logical display might become invalid if it is attached to a display device * that no longer exists. * * @param devices The list of all connected display devices. */ void LogicalDisplay::UpdateLocked( /* [in] */ const List< AutoPtr<DisplayDevice> >& devices) { // Nothing to update if already invalid. if (mPrimaryDisplayDevice == NULL) { return; } // Check whether logical display has become invalid. if (Find(devices.Begin(), devices.End(), mPrimaryDisplayDevice) == devices.End()) { mPrimaryDisplayDevice = NULL; return; } // Bootstrap the logical display using its associated primary physical display. // We might use more elaborate configurations later. It's possible that the // configuration of several physical displays might be used to determine the // logical display that they are sharing. (eg. Adjust size for pixel-perfect // mirroring over HDMI.) AutoPtr<DisplayDeviceInfo> deviceInfo = mPrimaryDisplayDevice->GetDisplayDeviceInfoLocked(); if ((mPrimaryDisplayDeviceInfo == NULL && deviceInfo != NULL) || !mPrimaryDisplayDeviceInfo->Equals(deviceInfo)) { mBaseDisplayInfo->SetLayerStack(mLayerStack); mBaseDisplayInfo->SetFlags(0); if ((deviceInfo->mFlags & DisplayDeviceInfo::FLAG_SUPPORTS_PROTECTED_BUFFERS) != 0) { Int32 flags; mBaseDisplayInfo->GetFlags(&flags); flags |= IDisplay::FLAG_SUPPORTS_PROTECTED_BUFFERS; mBaseDisplayInfo->SetFlags(flags); } if ((deviceInfo->mFlags & DisplayDeviceInfo::FLAG_SECURE) != 0) { Int32 flags; mBaseDisplayInfo->GetFlags(&flags); flags |= IDisplay::FLAG_SECURE; mBaseDisplayInfo->SetFlags(flags); } mBaseDisplayInfo->SetType(deviceInfo->mType); mBaseDisplayInfo->SetAddress(deviceInfo->mAddress); mBaseDisplayInfo->SetName(deviceInfo->mName); mBaseDisplayInfo->SetAppWidth(deviceInfo->mWidth); mBaseDisplayInfo->SetAppHeight(deviceInfo->mHeight); mBaseDisplayInfo->SetLogicalWidth(deviceInfo->mWidth); mBaseDisplayInfo->SetLogicalHeight(deviceInfo->mHeight); mBaseDisplayInfo->SetRotation(ISurface::ROTATION_0); mBaseDisplayInfo->SetRefreshRate(deviceInfo->mRefreshRate); mBaseDisplayInfo->SetLogicalDensityDpi(deviceInfo->mDensityDpi); mBaseDisplayInfo->SetPhysicalXDpi(deviceInfo->mXDpi); mBaseDisplayInfo->SetPhysicalYDpi(deviceInfo->mYDpi); mBaseDisplayInfo->SetSmallestNominalAppWidth(deviceInfo->mWidth); mBaseDisplayInfo->SetSmallestNominalAppHeight(deviceInfo->mHeight); mBaseDisplayInfo->SetLargestNominalAppWidth(deviceInfo->mWidth); mBaseDisplayInfo->SetLargestNominalAppHeight(deviceInfo->mHeight); mPrimaryDisplayDeviceInfo = deviceInfo; mInfo = NULL; } }
void Observer::ObjectDiscovered( /* [in] */ const String& busname, /* [in] */ const String& path, /* [in] */ ArrayOf<String>* interfaces, /* [in] */ Int32 sessionId) { if (DEBUG) { Logger::I(TAG, " >> ObjectDiscovered: busname: %s, path: %s, sessionId: %08x", busname.string(), path.string(), sessionId); for (Int32 i = 0; i < interfaces->GetLength(); ++i) { Logger::I(TAG, " > interface %d: %s", i, (*interfaces)[i].string()); } } List<AutoPtr<IInterfaceInfo> > intfList; HashMap<String, AutoPtr<IInterfaceInfo> >::Iterator mit; for (Int32 i = 0; i < interfaces->GetLength(); ++i) { mit = mInterfaceMap.Find((*interfaces)[i]); if (mit != mInterfaceMap.End()) { intfList.PushBack(mit->mSecond); } } //TODO figure out what to do with secure bus objects Int32 i = 0; AutoPtr<ArrayOf<IInterfaceInfo*> > infos = ArrayOf<IInterfaceInfo*>::Alloc(intfList.GetSize()); List<AutoPtr<IInterfaceInfo> >::Iterator lit; for (lit = intfList.Begin(); lit != intfList.End(); ++lit) { infos->Set(i++, *lit); } AutoPtr<IProxyBusObject> proxy; mBus->GetProxyBusObject(busname, path, sessionId, infos, (IProxyBusObject**)&proxy); AutoPtr< List<AutoPtr<WrappedListener> > > copiedListeners; { AutoLock lock(this); AutoPtr<ObjectId> oid = new ObjectId(busname, path); mProxies->Put(TO_IINTERFACE(oid), proxy); copiedListeners = new List<AutoPtr<WrappedListener> >(mListeners); } /* we do the listener invocation outside of the critical region to avoid * lock ordering issues */ List<AutoPtr<WrappedListener> >::Iterator wit; for (wit = copiedListeners->Begin(); wit != copiedListeners->End(); ++wit) { if ((*wit)->mEnabled) { // protect against exceptions in listener code. if (DEBUG) { Logger::I(TAG, " >> %s ObjectDiscovered: %s", TO_CSTR((*wit)->mListener), TO_CSTR(proxy)); } (*wit)->mListener->ObjectDiscovered(proxy); } } }
void compareWithStlList(List<int> &mylist, std::list<int> &slist) { Iterator<int> iterator = mylist.Begin(); std::list<int>::iterator iter = slist.begin(); for(; iter != slist.end(); iterator++, iter++) if(*iterator != *iter) { std::cout << "Test error: Compare error" << std::endl; return; } std::cout << "Test completed: Full compare" << std::endl; }
List<GameObject*> GameObject::GetChildrenRecursivelyEditor() const { List<GameObject*> cc; for (GameObject *c : m_children) { List<GameObject*> childChildren = c->GetChildrenRecursivelyEditor(); cc.Splice(cc.Begin(), childChildren); cc.PushBack(c); } return cc; }
AutoPtr<IObjectContainer> ActivityChooserModel::TransfromList( /* [in] */ List<AutoPtr<T> >& list) { AutoPtr<IObjectContainer> container; CObjectContainer::New((IObjectContainer**)&container); typename List<AutoPtr<T> >::Iterator it = list.Begin(); for(; it != list.End(); it++) { container->Add(*it); } return container; }
void RenderQueue::PushRenderer(const List<SceneNode *> & nodes) { List<SceneNode *>::ConstIterator whr = nodes.Begin(); List<SceneNode *>::ConstIterator end = nodes.End(); while (whr != end) { _pushRenderer(*whr); ++whr; } }
/** * Filter the given {@link NativeDaemonEvent} list, returning * {@link #getMessage()} for any events matching the requested code. */ AutoPtr< ArrayOf<String> > NativeDaemonEvent::FilterMessageList( /* [in] */ const ArrayOf<NativeDaemonEvent*>& events, /* [in] */ Int32 matchCode) { List<String> resultList; for (Int32 i = 0; i < events.GetLength(); i++) { if (events[i]->GetCode() == matchCode) { resultList.PushBack(events[i]->GetMessage()); } } AutoPtr< ArrayOf<String> > resultArray = ArrayOf<String>::Alloc(resultList.GetSize()); List<String>::Iterator iter; Int32 i; for (iter = resultList.Begin(), i = 0; iter != resultList.End(); ++iter, i++) { (*resultArray)[i] = *iter; } return resultArray; }
void ThreadFunction() { for (;;) { CompiledVariation* workItem = 0; { MutexLock lock(workMutex_); if (!workList_.Empty()) { workItem = workList_.Front(); workList_.Erase(workList_.Begin()); } } if (!workItem) return; // If compile(s) failed, just empty the list, but do not compile more if (!compileFailed_) CompileVariation(workItem); } }
ECode CTextServicesManagerService::SpellCheckerBindGroup::RemoveListener( /* [in] */ ISpellCheckerSessionListener* listener) { /*if (CTextServicesManagerService::DBG) { Slogger::W(TAG, "remove listener: " + listener.hashCode()); }*/ { AutoLock lock(mOwner->mSpellCheckerMapLock); List<AutoPtr<InternalDeathRecipient> > removeList; ManagedInternalDeathRecipientListIt it = mListeners.Begin(); for (; it != mListeners.End(); ++it) { AutoPtr<InternalDeathRecipient> tempRecipient = (*it); if(tempRecipient->HasSpellCheckerListener(listener)) { if (CTextServicesManagerService::DBG) { Slogger::W(TAG, "found existing listener."); } removeList.PushBack(tempRecipient); } } ManagedInternalDeathRecipientListIt it2 = removeList.Begin(); for (Int32 i = 0; it2 != removeList.End(); ++it2, ++i) { if (CTextServicesManagerService::DBG) { Slogger::W(TAG, "SpellCheckerBindGroup::RemoveListener Remove %d", i); } AutoPtr<InternalDeathRecipient> idr = (*it2); AutoPtr<IProxy> proxy = (IProxy*)idr->mScListener->Probe(EIID_IProxy); if (proxy != NULL) { Boolean result; proxy->UnlinkToDeath(idr, 0, &result); } mListeners.Remove(idr); } CleanLocked(); removeList.Clear(); } return NOERROR; }
Boolean Connection::ClearPipe( /* [in] */ List<Request*>& pipe) { Boolean empty = TRUE; if (HttpLog::LOGV) HttpLog::V( "Connection.clearPipe(): clearing pipe %d", pipe.GetSize()); synchronized(mRequestFeeder) { Request* tReq; List<Request*>::Iterator itor; for (itor = pipe.Begin(); itor != pipe.End(); itor++) { tReq = *itor; if (HttpLog::LOGV) HttpLog::V( "clearPipe() adding back %s %s", TO_CSTR(mHost), Object::ToString((IRequest*)tReq).string()); mRequestFeeder->RequeueRequest(tReq); empty = FALSE; } if (empty) { empty = mRequestFeeder->HaveRequest(mHost, &empty); empty = !empty; } } return empty; }
void RegisteredServicesCache::GenerateServicesMap( /* [in] */ Int32 userId) { Slogger::D(TAG, "generateServicesMap() for %d", userId); AutoPtr<IPackageManager> pm; mContext->GetPackageManager((IPackageManager**)&pm); List<AutoPtr<IRegisteredServicesCacheServiceInfo> > serviceInfos; AutoPtr<IList> resolveInfos; AutoPtr<IIntent> intent; CIntent::New(mInterfaceName, (IIntent**)&intent); ASSERT_SUCCEEDED(pm->QueryIntentServicesAsUser(intent, IPackageManager::GET_META_DATA, userId, (IList**)&resolveInfos)); AutoPtr<IIterator> it; resolveInfos->GetIterator((IIterator**)&it); Boolean hasNext; while (it->HasNext(&hasNext), hasNext) { AutoPtr<IInterface> current; it->GetNext((IInterface**)¤t); AutoPtr<IResolveInfo> resolveInfo = IResolveInfo::Probe(current); // try { AutoPtr<IRegisteredServicesCacheServiceInfo> info; ECode ec = ParseServiceInfo(resolveInfo, (IRegisteredServicesCacheServiceInfo**)&info); if (FAILED(ec)) { String s; resolveInfo->ToString(&s); Slogger::W(TAG, "Unable to load service info %s ec = 0x%08x", s.string(), ec); continue; } serviceInfos.PushBack(info); // } catch (XmlPullParserException e) { // Log.w(TAG, "Unable to load service info " + resolveInfo.toString(), e); // } catch (IOException e) { // Log.w(TAG, "Unable to load service info " + resolveInfo.toString(), e); // } } AutoLock lock(mServicesLock); AutoPtr<UserServices> user = FindOrCreateUserLocked(userId); Boolean firstScan = user->mServices == NULL; if (firstScan) { user->mServices = new HashMap<AutoPtr<IInterface>, AutoPtr<IRegisteredServicesCacheServiceInfo> >(); } else { user->mServices->Clear(); } StringBuilder changes; Boolean changed = FALSE; ServiceInfo* info; List<AutoPtr<IRegisteredServicesCacheServiceInfo> >::Iterator itr = serviceInfos.Begin(); for (Int32 i = 0; itr != serviceInfos.End(); ++itr, ++i) { info = (ServiceInfo*)(*itr).Get(); // four cases: // - doesn't exist yet // - add, notify user that it was added // - exists and the UID is the same // - replace, don't notify user // - exists, the UID is different, and the new one is not a system package // - ignore // - exists, the UID is different, and the new one is a system package // - add, notify user that it was added AutoPtr<IInteger32> previousUid; HashMap<AutoPtr<IInterface>, AutoPtr<IInteger32> >::Iterator it = user->mPersistentServices.Find(info->mType); if (it != user->mPersistentServices.End()) { previousUid = it->mSecond; } if (previousUid == NULL) { if (Logger::IsLoggable(TAG, Logger::VERBOSE)) { changes += " New service added: "; changes += Object::ToString(info); changes += "\n"; } changed = TRUE; (*user->mServices)[info->mType] = info; AutoPtr<IInteger32> iuid; CInteger32::New(info->mUid, (IInteger32**)&iuid); (user->mPersistentServices)[info->mType] = iuid; if (!(mPersistentServicesFileDidNotExist && firstScan)) { NotifyListener(info->mType, userId, FALSE /* removed */); } } else { Int32 pUid; previousUid->GetValue(&pUid); if (pUid == info->mUid) { if (Logger::IsLoggable(TAG, Logger::VERBOSE)) { changes += " Existing service (nop): "; changes += Object::ToString(info); changes += "\n"; } (*user->mServices)[info->mType] = info; } else if (InSystemImage(info->mUid) || !ContainsTypeAndUid(&serviceInfos, info->mType, pUid)) { if (InSystemImage(info->mUid)) { if (Logger::IsLoggable(TAG, Logger::VERBOSE)) { changes += (" System service replacing existing: "); changes += Object::ToString(info); changes += ("\n"); } } else { if (Logger::IsLoggable(TAG, Logger::VERBOSE)) { changes += (" Existing service replacing a removed service: "); changes += Object::ToString(info); changes += ("\n"); } } (*user->mServices)[info->mType] = info; AutoPtr<IInteger32> iuid; CInteger32::New(info->mUid, (IInteger32**)&iuid); (user->mPersistentServices)[info->mType] = iuid; NotifyListener(info->mType, userId, FALSE /* removed */); } else { if (Logger::IsLoggable(TAG, Logger::VERBOSE)) { // ignore changes += (" Existing service with new uid ignored: "); changes += Object::ToString(info); changes += ("\n"); } } } } List<AutoPtr<IInterface> > toBeRemoved; HashMap<AutoPtr<IInterface>, AutoPtr<IInteger32> >::Iterator item = user->mPersistentServices.Begin(); for (; item != user->mPersistentServices.End(); ++item) { AutoPtr<IInterface> v1 = item->mFirst; if (!ContainsType(&serviceInfos, v1)) { toBeRemoved.PushBack(v1); } } List<AutoPtr<IInterface> >::Iterator toBeRemItr = toBeRemoved.Begin(); for (; toBeRemItr != toBeRemoved.End(); ++toBeRemItr) { AutoPtr<IInterface> v1 = *toBeRemItr; user->mPersistentServices.Erase(v1); NotifyListener(v1, userId, TRUE /* removed */); changed = TRUE; if (Logger::IsLoggable(TAG, Logger::VERBOSE)) { changes += (" Service removed: "); changes += Object::ToString(v1); changes += ("\n"); } } if (Logger::IsLoggable(TAG, Logger::VERBOSE)) { if (changes.GetLength() > 0) { Logger::D(TAG, "generateServicesMap(%s): %d services:%s\n", mInterfaceName.string(), serviceInfos.GetSize(), changes.ToString().string()); } else { Logger::D(TAG, "generateServicesMap(%s): %d services unchanged", mInterfaceName.string(), serviceInfos.GetSize()); } } if (changed) { WritePersistentServicesLocked(); } }
ECode MessageFormat::ApplyPattern( /* [in] */ const String& tem) { if (tem.IsNull()) { return NOERROR; } AutoPtr<ArrayOf<Char32> > charArray = tem.GetChars(); Int32 length = charArray->GetLength(); StringBuffer buffer(""); AutoPtr<IParsePosition> position; CParsePosition::New(0, (IParsePosition**)&position); List<String> localStrings; Int32 argCount = 0; AutoPtr<ArrayOf<Int32> > args = ArrayOf<Int32>::Alloc(10); Int32 maxArg = -1; List< AutoPtr<IFormat> > localFormats; Int32 index, arg, offset; position->GetIndex(&index); Boolean succeeded; Char32 ch; while (index < length) { if (FormatBase::UpTo(tem, position, buffer, '{', &succeeded), succeeded) { arg = 0; position->GetIndex(&offset); if (offset >= length) { return E_ILLEGAL_ARGUMENT_EXCEPTION; } // Get argument number while ((ch = (*charArray)[offset++]) != '}' && ch != ',') { if (ch < '0' && ch > '9') { return E_ILLEGAL_ARGUMENT_EXCEPTION; } arg = arg * 10 + (ch - '0'); if (arg < 0 || offset >= length) { return E_ILLEGAL_ARGUMENT_EXCEPTION; } } offset--; position->SetIndex(offset); AutoPtr<IFormat> f; FAIL_RETURN(ParseVariable(tem, position, (IFormat**)&f)); localFormats.PushBack(f); if (argCount >= args->GetLength()) { AutoPtr<ArrayOf<Int32> > newArgs = ArrayOf<Int32>::Alloc(args->GetLength() * 2); newArgs->Copy(args); args = newArgs; } (*args)[argCount++] = arg; if (arg > maxArg) { maxArg = arg; } } String outstr; buffer.Substring(0, buffer.GetLength(), &outstr); localStrings.PushBack(outstr); buffer.Reset(); position->GetIndex(&index); } mStrings = ArrayOf<String>::Alloc(localStrings.GetSize()); List<String>::Iterator it = localStrings.Begin(); for (Int32 i = 0; i < (Int32)(localStrings.GetSize()); ++i, ++it) { (*mStrings)[i] = *it; } mArgumentNumbers = args; mFormats = ArrayOf<IFormat* >::Alloc(argCount); List< AutoPtr<IFormat> >::Iterator ite = localFormats.Begin(); for (Int32 i = 0; i < argCount; ++i, ++ite) { mFormats->Set(i, *ite); } mMaxOffset = argCount - 1; mMaxArgumentIndex = maxArg; return NOERROR; }
void List<T>::Append(const List<T>& list) // Appends deep copy of rhs - do not apply to self! { for (ConstIterator i = list.Begin(); i != list.End(); ++i) PushBack(*i); }
int main() { #ifdef _MSC_VER _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); #endif printf("Size of String: %d\n", sizeof(String)); printf("Size of Vector: %d\n", sizeof(Vector<int>)); printf("Size of List: %d\n", sizeof(List<int>)); printf("Size of HashMap: %d\n", sizeof(HashMap<int, int>)); printf("Size of RefCounted: %d\n", sizeof(RefCounted)); { printf("\nTesting AutoPtr assignment\n"); AutoPtr<Test> ptr1(new Test); AutoPtr<Test> ptr2; ptr2 = ptr1; } { printf("\nTesting AutoPtr copy construction\n"); AutoPtr<Test> ptr1(new Test); AutoPtr<Test> ptr2(ptr1); } { printf("\nTesting AutoPtr detaching\n"); AutoPtr<Test> ptr1(new Test); // We would now have a memory leak if we don't manually delete the object Test* object = ptr1.Detach(); delete object; } { printf("\nTesting AutoPtr inside a vector\n"); Vector<AutoPtr<Test> > vec; printf("Filling vector\n"); for (size_t i = 0; i < 4; ++i) vec.Push(new Test()); printf("Clearing vector\n"); vec.Clear(); } { printf("\nTesting SharedPtr\n"); SharedPtr<TestRefCounted> ptr1(new TestRefCounted); SharedPtr<TestRefCounted> ptr2(ptr1); printf("Number of refs: %d\n", ptr1.Refs()); } { printf("\nTesting WeakPtr\n"); TestRefCounted* object = new TestRefCounted; WeakPtr<TestRefCounted> ptr1(object); WeakPtr<TestRefCounted> ptr2(ptr1); printf("Number of weak refs: %d expired: %d\n", ptr1.WeakRefs(), ptr1.IsExpired()); ptr2.Reset(); delete object; printf("Number of weak refs: %d expired: %d\n", ptr1.WeakRefs(), ptr1.IsExpired()); } { printf("\nTesting Vector\n"); HiresTimer t; Vector<int> vec; SetRandomSeed(0); for (size_t i = 0; i < NUM_ITEMS; ++i) vec.Push(Rand()); int sum = 0; int count = 0; for (auto it = vec.Begin(); it != vec.End(); ++it) { sum += *it; ++count; } int usec = (int)t.ElapsedUSec(); printf("Size: %d capacity: %d\n", vec.Size(), vec.Capacity()); printf("Counted vector items %d, sum: %d\n", count, sum); printf("Processing took %d usec\n", usec); } { printf("\nTesting List\n"); HiresTimer t; List<int> list; SetRandomSeed(0); for (size_t i = 0; i < NUM_ITEMS; ++i) list.Push(Rand()); int sum = 0; int count = 0; for (auto it = list.Begin(); it != list.End(); ++it) { sum += *it; ++count; } int usec = (int)t.ElapsedUSec(); printf("Size: %d\n", list.Size()); printf("Counted list items %d, sum: %d\n", count, sum); printf("Processing took %d usec\n", usec); printf("\nTesting List insertion\n"); List<int> list2; List<int> list3; for (int i = 0; i < 10; ++i) list3.Push(i); list2.Insert(list2.End(), list3); for (auto it = list2.Begin(); it != list2.End(); ++it) printf("%d ", *it); printf("\n"); } { printf("\nTesting String\n"); HiresTimer t; String test; for (size_t i = 0; i < NUM_ITEMS/4; ++i) test += "Test"; String test2; test2.AppendWithFormat("Size: %d capacity: %d\n", test.Length(), test.Capacity()); printf(test2.CString()); test2 = test2.ToUpper(); printf(test2.CString()); test2.Replace("SIZE:", "LENGTH:"); printf(test2.CString()); int usec = (int)t.ElapsedUSec(); printf("Processing took %d usec\n", usec); } { printf("\nTesting HashSet\n"); HiresTimer t; size_t found = 0; unsigned sum = 0; HashSet<int> testHashSet; srand(0); found = 0; sum = 0; printf("Insert, search and iteration, %d keys\n", NUM_ITEMS); for (size_t i = 0; i < NUM_ITEMS; ++i) { int number = (rand() & 32767); testHashSet.Insert(number); } for (int i = 0; i < 32768; ++i) { if (testHashSet.Find(i) != testHashSet.End()) ++found; } for (auto it = testHashSet.Begin(); it != testHashSet.End(); ++it) sum += *it; int usec = (int)t.ElapsedUSec(); printf("Set size and sum: %d %d\n", testHashSet.Size(), sum); printf("Processing took %d usec\n", usec); } { printf("\nTesting HashMap\n"); HashMap<int, int> testHashMap; for (int i = 0; i < 10; ++i) testHashMap.Insert(MakePair(i, rand() & 32767)); printf("Keys: "); Vector<int> keys = testHashMap.Keys(); for (size_t i = 0; i < keys.Size(); ++i) printf("%d ", keys[i]); printf("\n"); printf("Values: "); Vector<int> values = testHashMap.Values(); for (size_t i = 0; i < values.Size(); ++i) printf("%d ", values[i]); printf("\n"); } return 0; }
ECode CContentService::NotifyChange( /* [in] */ IUri* uri, /* [in] */ IContentObserver* observer, /* [in] */ Boolean observerWantsSelfNotifications, /* [in] */ Boolean syncToNetwork) { if (Logger::IsLoggable(TAG, Logger::VERBOSE)) { String str("Notifying update of "); if (NULL != uri) { String strUri; uri->ToString(&strUri); str.Append(strUri); } else { str.Append(" null "); } str.Append(" from observer "); //TODO: observer->ToString(); str.Append(", syncToNetwork "); str.Append(syncToNetwork ? " true ":" false "); Logger::V(TAG, str); } // This makes it so that future permission checks will be in the context of this // process rather than the caller's process. We will restore this before returning. //TODO: long identityToken = clearCallingIdentity(); List<AutoPtr<ObserverCall> >* calls = new List<AutoPtr<ObserverCall> >(); Mutex::Autolock lock(mRootNodeLock); FAIL_RETURN(mRootNode->CollectObserversLocked(mRootNode, uri, 0, observer, observerWantsSelfNotifications, calls)); List<AutoPtr<ObserverCall> >::Iterator it; ECode ecode = NOERROR; AutoPtr<ObserverCall> oc; for (it = calls->Begin(); it != calls->End(); it++) { oc = *it; ecode = oc->mObserver->OnChange(oc->mSelfNotify); if (Logger::IsLoggable(TAG, Logger::VERBOSE)) { String str("Notified "); //TODO: oc->mObserver->ToString(); str.Append(" of update at "); if (NULL != uri) { String strUri; uri->ToString(&strUri); str.Append(strUri); } else { str.Append(" null "); } Logger::V(TAG, str); } if (ecode != NOERROR) { Mutex::Autolock lock(mRootNodeLock); Logger::W(TAG, "Found dead observer, removing"); AutoPtr<IContentObserver> tmpObserver = oc->mObserver; //IBinder binder = oc.mObserver.asBinder(); List<AutoPtr<ObserverNode::ObserverEntry> >* list = oc->mNode->mObservers; Int32 size = list->GetSize(); List<AutoPtr<ObserverNode::ObserverEntry> >::Iterator iter; for (Int32 i = 0; i < size; i++) { AutoPtr<ObserverNode::ObserverEntry> oe = (*list)[i]; if (_CObject_Compare(tmpObserver, oe->mObserver)){ list->Remove(oe); i--; size--; } } } } if (syncToNetwork) { AutoPtr<ISyncManager> syncManager = GetSyncManager(); if (NULL != syncManager) { String authority; uri->GetAuthority(&authority); AutoPtr<IAccount> nullAccount; FAIL_RETURN(syncManager->ScheduleLocalSync(nullAccount /* all accounts */, &authority)); } } //TODO: restoreCallingIdentity(identityToken); if (NULL != calls) { calls->Clear(); delete calls; } return NOERROR; }
AutoPtr< ArrayOf<String> > NativeDaemonEvent::UnescapeArgs( /* [in] */ const String& rawEvent) { Boolean DEBUG_ROUTINE = FALSE; String LOGTAG("unescapeArgs"); List<String> parsed; Int32 length = rawEvent.GetLength(); Int32 current = 0; Int32 wordEnd = -1; Boolean quoted = FALSE; // if (DEBUG_ROUTINE) Slog.e(LOGTAG, "parsing '" + rawEvent + "'"); if (rawEvent.GetChar(current) == '\"') { quoted = TRUE; current++; } while (current < length) { // find the end of the word char terminator = quoted ? '\"' : ' '; wordEnd = current; while (wordEnd < length && rawEvent.GetChar(wordEnd) != terminator) { if (rawEvent.GetChar(wordEnd) == '\\') { // skip the escaped char ++wordEnd; } ++wordEnd; } if (wordEnd > length) wordEnd = length; String word = rawEvent.Substring(current, wordEnd); current += word.GetLength(); if (!quoted) { word = word.Trim(); } else { current++; // skip the trailing quote } // unescape stuff within the word String w; StringUtils::ReplaceAll(word, String("\\\\"), String("\\"), &w); StringUtils::ReplaceAll(w, String("\\\""), String("\""), &word); // if (DEBUG_ROUTINE) Slog.e(LOGTAG, "found '" + word + "'"); parsed.PushBack(word); // find the beginning of the next word - either of these options Int32 nextSpace = rawEvent.IndexOf(' ', current); Int32 nextQuote = rawEvent.IndexOf(" \"", current); if (DEBUG_ROUTINE) { // Slog.e(LOGTAG, "nextSpace=" + nextSpace + ", nextQuote=" + nextQuote); } if (nextQuote > -1 && nextQuote <= nextSpace) { quoted = TRUE; current = nextQuote + 2; } else { quoted = FALSE; if (nextSpace > -1) { current = nextSpace + 1; } } // else we just start the next word after the current and read til the end if (DEBUG_ROUTINE) { // Slog.e(LOGTAG, "next loop - current=" + current + // ", length=" + length + ", quoted=" + quoted); } } AutoPtr< ArrayOf<String> > parsedArray = ArrayOf<String>::Alloc(parsed.GetSize()); List<String>::Iterator it; Int32 i; for (it = parsed.Begin(), i = 0; it != parsed.End(); ++it, i++) { (*parsedArray)[i] = *it; } return parsedArray; }
void CompileShader(const String& fileName) { String file = GetFileName(fileName); XMLFile doc(context_); File source(context_); source.Open(fileName); if (!doc.Load(source)) ErrorExit("Could not open input file " + fileName); XMLElement shaders = doc.GetRoot("shaders"); if (!shaders) ErrorExit("No shaders element in " + source.GetName()); if (compileVS_) { ShaderParser vsParser; if (!vsParser.Parse(VS, shaders, defines_, defineValues_)) ErrorExit("VS: " + vsParser.GetErrorMessage()); const HashMap<String, unsigned>& combinations = vsParser.GetAllCombinations(); for (HashMap<String, unsigned>::ConstIterator i = combinations.Begin(); i != combinations.End(); ++i) { if (!compileVariation_ || i->first_ == variationName_) { ShaderCombination src = vsParser.GetCombination(i->first_); CompiledVariation compile; compile.type_ = VS; compile.name_ = file; compile.outFileName_ = outDir_ + file; if (!src.name_.Empty()) { compile.name_ += "_" + src.name_; compile.outFileName_ += "_" + src.name_; } compile.outFileName_ += useSM3_ ? ".vs3" : ".vs2"; compile.defines_ = src.defines_; compile.defineValues_ = src.defineValues_; variations_.Push(compile); workList_.Push(&variations_.Back()); } } } if (compilePS_) { ShaderParser psParser; if (!psParser.Parse(PS, shaders, defines_, defineValues_)) ErrorExit("PS: " + psParser.GetErrorMessage()); const HashMap<String, unsigned>& combinations = psParser.GetAllCombinations(); for (HashMap<String, unsigned>::ConstIterator i = combinations.Begin(); i != combinations.End(); ++i) { if (!compileVariation_ || i->first_ == variationName_) { ShaderCombination src = psParser.GetCombination(i->first_); CompiledVariation compile; compile.type_ = PS; compile.name_ = file; compile.outFileName_ = outDir_ + file; if (!src.name_.Empty()) { compile.name_ += "_" + src.name_; compile.outFileName_ += "_" + src.name_; } compile.outFileName_ += useSM3_ ? ".ps3" : ".ps2"; compile.defines_ = src.defines_; compile.defineValues_ = src.defineValues_; variations_.Push(compile); workList_.Push(&variations_.Back()); } } } if (variations_.Empty()) { PrintLine("No variations to compile"); return; } // Load the shader source code { String inputFileName = inDir_ + file + ".hlsl"; File hlslFile(context_, inputFileName); if (!hlslFile.IsOpen()) ErrorExit("Could not open input file " + inputFileName); hlslCode_.Clear(); while (!hlslFile.IsEof()) hlslCode_ += hlslFile.ReadLine() + "\n"; } if (!compileVariation_) { // Create and start worker threads. Use all logical CPUs except one to not lock up the computer completely unsigned numWorkerThreads = GetNumLogicalCPUs() - 1; if (!numWorkerThreads) numWorkerThreads = 1; Vector<SharedPtr<WorkerThread> > workerThreads; workerThreads.Resize(numWorkerThreads); for (unsigned i = 0; i < workerThreads.Size(); ++i) { workerThreads[i] = new WorkerThread(); workerThreads[i]->Run(); } // This will wait until the thread functions have stopped for (unsigned i = 0; i < workerThreads.Size(); ++i) workerThreads[i]->Stop(); } else { WorkerThread dummyThread; dummyThread.ThreadFunction(); } // Check that all shaders compiled for (List<CompiledVariation>::Iterator i = variations_.Begin(); i != variations_.End(); ++i) { if (!i->errorMsg_.Empty()) { if (i->type_ == VS) ErrorExit("Failed to compile vertex shader " + i->name_ + ": " + i->errorMsg_); else ErrorExit("Failed to compile pixel shader " + i->name_ + ": " + i->errorMsg_); } } }
AutoPtr<IPreferenceActivityHeader> PreferenceActivity::FindBestMatchingHeader( /* [in] */ IPreferenceActivityHeader* cur, /* [in] */ List<AutoPtr<IPreferenceActivityHeader> >& from) { List<AutoPtr<IPreferenceActivityHeader> > matches; List<AutoPtr<IPreferenceActivityHeader> >::Iterator it = from.Begin(); for (; it != from.End(); ++it) { AutoPtr<IPreferenceActivityHeader> lOh = *it; Int64 curId; cur->GetId(&curId); Int64 ohId; lOh->GetId(&ohId); if (cur == lOh || (curId != HEADER_ID_UNDEFINED && curId == ohId)) { // Must be this one. matches.Clear(); matches.PushBack(lOh); break; } String curFragment; AutoPtr<IIntent> curIntent; AutoPtr<ICharSequence> curTitle; if (cur->GetFragment(&curFragment), !curFragment.IsNull()) { String ohFragment; lOh->GetFragment(&ohFragment); if (curFragment.Equals(ohFragment)) { matches.PushBack(lOh); } } else if (cur->GetIntent((IIntent**)&curIntent), curIntent != NULL) { AutoPtr<IIntent> ohIntent; lOh->GetIntent((IIntent**)&ohIntent); AutoPtr<IObject> obj = IObject::Probe(curIntent); Boolean result; if (obj->Equals(ohIntent, &result), result) { matches.PushBack(lOh); } } else if (cur->GetTitle((ICharSequence**)&curTitle), curTitle != NULL) { AutoPtr<ICharSequence> ohTitle; lOh->GetTitle((ICharSequence**)&ohTitle); AutoPtr<IObject> obj = IObject::Probe(curTitle); Boolean result; if (obj->Equals(ohTitle, &result), result) { matches.PushBack(lOh); } } } it = matches.Begin(); if (it != matches.End()) { ++it; if (it == matches.End()) { return *(matches.Begin()); } else { for (it = matches.Begin(); it != matches.End(); ++it) { AutoPtr<IPreferenceActivityHeader> oh = *it; AutoPtr<IBundle> curFragmentArguments; cur->GetFragmentArguments((IBundle**)&curFragmentArguments); if (curFragmentArguments != NULL) { AutoPtr<IBundle> ohFragmentArguments; oh->GetFragmentArguments((IBundle**)&ohFragmentArguments); AutoPtr<IObject> obj = IObject::Probe(curFragmentArguments); Boolean result; if (obj->Equals(ohFragmentArguments, &result), result) { return oh; } } AutoPtr<IBundle> curExtras; cur->GetExtras((IBundle**)&curExtras); if (curExtras != NULL) { AutoPtr<IBundle> ohExtras; oh->GetExtras((IBundle**)&ohExtras); AutoPtr<IObject> obj = IObject::Probe(curExtras); Boolean result; if (obj->Equals(ohExtras, &result), result) { return oh; } } AutoPtr<ICharSequence> curTitle; cur->GetTitle((ICharSequence**)&curTitle); if (curTitle != NULL) { AutoPtr<ICharSequence> ohTitle; oh->GetTitle((ICharSequence**)&ohTitle); AutoPtr<IObject> obj = IObject::Probe(curTitle); Boolean result; if (obj->Equals(ohTitle, &result), result) { return oh; } } } } } return NULL; }