int numberOfElements(Tree * current){ if(current==NULL){ return 0; } return (1 +numberOfElements(current->left) + numberOfElements(current->right)); }
BOOL MyContainer::setupItems() { pCnrRecord pcn; HPOINTER hptr; if (isEmpty()) return(TRUE); hptr = WinLoadPointer(HWND_DESKTOP, 0, SAMPLE_MAIN); pcn = allocRecords(numberOfElements()); if(pcn) { RECORDINSERT ri; ULONG counter = 1; pCnrRecord pcnFirst = pcn; pMyRecord record = getFirst(); while(record) { record->Position = counter; pcn->recordCore.cb = sizeof(RECORDCORE); pcn->recordCore.pszText = record->Name; pcn->recordCore.pszIcon = record->Name; pcn->recordCore.pszName = record->Name; pcn->recordCore.hptrIcon = hptr; pcn->Name = record->Name; pcn->Position = record->Position; pcn = (pCnrRecord) pcn->recordCore.preccNextRecord; record = getNext(); counter++; } memset(&ri, 0, sizeof(RECORDINSERT)); ri.cb = sizeof(RECORDINSERT); ri.pRecordOrder = (PRECORDCORE) CMA_END; ri.pRecordParent = (PRECORDCORE) NULL; ri.zOrder = (USHORT) CMA_TOP; ri.cRecordsInsert = numberOfElements(); ri.fInvalidateRecord = TRUE; // insert them in one shot if (insertRecord(pcnFirst, &ri)) { WinSendMsg(parent, WM_CNR_STATUS, MPFROMP("Completed."), NULL); return(TRUE); } } return(FALSE); }
void DistanceTransformNonEuclid(vector<double>& D, const vector<unsigned char>& L, const vector<int>& leadingNbh, const vector<int>& trailingNbh, const vector<double>& leadingWgt, const vector<double>& trailingWgt, int ndim, const int* dims) { int i,j; int nvoxels=numberOfElements(ndim,dims); //construct a subscript representation of the neighborhood //for efficient boundary check vector<int> vcoordsL; for(i=0; i<leadingNbh.size(); ++i) { vector<int> vsub = Ind2SubCentered(leadingNbh[i],ndim,dims); vcoordsL.insert(vcoordsL.end(),vsub.begin(),vsub.end()); } vector<int> vcoordsT; for(i=0; i<leadingNbh.size(); ++i) { vector<int> vsub = Ind2SubCentered(trailingNbh[i],ndim,dims); vcoordsT.insert(vcoordsT.end(),vsub.begin(),vsub.end()); } //first pass - from upper left to lower right for(i=0; i<nvoxels; ++i) { double v1=GetData(D,i,(double)0); double minV=INFINITY; vector<int> vsub = Ind2Sub(i,ndim,dims); for(j=0; j<leadingNbh.size(); ++j) { if(NeighborCheck(vsub.begin(),vcoordsL.begin()+j*ndim,ndim,dims)) { int k=i+leadingNbh[j]; double v2=D[k]; //trust BoundaryCheck - no array boundary check here minV=Min(minV,v2+leadingWgt[j]); } } if(v1>minV) SetData(D,i,minV); } //second pass - from lower right to upper left for(i=nvoxels-1; i>=0; --i) { double v1=GetData(D,i,(double)0); double minV=INFINITY; vector<int> vsub = Ind2Sub(i,ndim,dims); for(j=0; j<trailingNbh.size(); ++j) { if(NeighborCheck(vsub.begin(),vcoordsT.begin()+j*ndim,ndim,dims)) { int k=i+trailingNbh[j]; double v2=D[k]; //trust BoundaryCheck - no array boundary check here minV=Min(minV,v2+trailingWgt[j]); } } if(v1>minV) SetData(D,i,minV); } }
void DistanceTransformF(vector<float>& Df, const vector<unsigned char>& L, int mode, int ndim, const int* dims) { int i; int nvoxels=numberOfElements(ndim,dims); vector<double> D(nvoxels); for(i=0; i<nvoxels; ++i) { if(GetData(L,i,(unsigned char)0)) { SetData(D,i,(double)0); } else { SetData(D,i,INFINITY_FELZENSWALB); } } vector<int> leadingNbh=MakeCausalNeighborhood(ndim,dims); vector<int> trailingNbh=MakeAntiCausalNeighborhood(ndim,dims);; vector<double> leadingWgt; vector<double> trailingWgt; switch(mode) { case DistanceTransformMode_Euclid: DistanceTransformEuclid(D,L,ndim,dims); break; case DistanceTransformMode_QuasiEuclid: leadingWgt = makeQuasiEuclideanDistanceWeight(leadingNbh,ndim,dims); trailingWgt = makeQuasiEuclideanDistanceWeight(trailingNbh,ndim,dims); DistanceTransformNonEuclid(D,L, leadingNbh,trailingNbh, leadingWgt,trailingWgt, ndim,dims); break; case DistanceTransformMode_CityBlockEuclid: leadingWgt = makeCityBlockDistanceWeight(leadingNbh,ndim,dims); trailingWgt = makeCityBlockDistanceWeight(trailingNbh,ndim,dims); DistanceTransformNonEuclid(D,L, leadingNbh,trailingNbh, leadingWgt,trailingWgt, ndim,dims); break; case DistanceTransformMode_CheckerBoardEuclid: leadingWgt = makeCheckerBoardDistanceWeight(leadingNbh,ndim,dims); trailingWgt = makeCheckerBoardDistanceWeight(trailingNbh,ndim,dims); DistanceTransformNonEuclid(D,L, leadingNbh,trailingNbh, leadingWgt,trailingWgt, ndim,dims); break; } for(i=0; i<nvoxels; ++i) { Df[i]=(float)D[i]; } }
int doesDOMcontainResults(void) { if (isDOMpresent()) { return ((numberOfElements("result-processor") > 0) || (numberOfElements("result-task") > 0) || (numberOfElements("result-entry") > 0) || (numberOfElements("result-activity") > 0) || (numberOfElements("result-join-delay") > 0) || (numberOfElements("result-forwarding") > 0) || (numberOfElements("result-activity-distribution") > 0) || (numberOfElements("result-call") > 0)); } return(0); }
void UnstructuredTopology::writeMetadata( xdm::XmlMetadataWrapper& xml ) { Topology::writeMetadata( xml ); // Write the number of Elements xml.setAttribute( "NumberOfElements", numberOfElements() ); // Write the Element type xml.setAttribute( "ElementType", mElementTopology->name() ); // Write the nodes per Element xml.setAttribute( "NodesPerElement", mElementTopology->numberOfNodes() ); }
int WOPR_battle( int argc, char **argv ) { game *aGame; FILE *scenario; aGame = WOPR_createGame( ); if ( !aGame ) { fprintf( stderr, "Can't allocate a game structure\n" ); return FALSE; } scenario = fopen( argv[1], "r" ); if ( !scenario ) { fprintf( stderr, "Can't open the scenario file %s\n", argv[1] ); return FALSE; } if ( WOPR_parse_scenario( scenario, aGame ) ) { player *aPlayer; /* All data is read, precompute some date */ raceStatus( aGame ); preComputeGroupData( aGame ); /* and do battle */ fightphase( aGame, GF_INBATTLE2 ); /* remove empty groups */ joinphase( aGame ); /* Dump some of the result data */ for ( aPlayer = aGame->players; aPlayer; aPlayer = aPlayer->next ) { aPlayer->pswdstate = 1; printf( "%s %d \n", aPlayer->name, numberOfElements( aPlayer->groups ) ); /* Only works if you have the correct directories setup in $HOME/Games */ /* galaxynghome = strdup("/home/chris"); */ saveTurnReport( aGame, aPlayer, 0 ); } fclose( scenario ); } else { fprintf( stderr, "Parse error in file %s\n", argv[1] ); } return TRUE; }
void printLastElements(FILE*g,int x) { int k=0; //n gives the number of elements in the list which are not to be printed int n=numberOfElements()-x; //currentNode is a pointer to the current node NODE *currentNode; currentNode=head; //the list is traversed up to the node starting from which the elements will be printed while (k<n) { currentNode=currentNode->next; k++; } //the last x elements are being printed while (currentNode!=NULL) { fprintf(g,"%d ",currentNode->data); currentNode=currentNode->next; } fprintf(g,"\n"); }
void Benchmark::test(const int algorithm, vector<deque<int>> &out, int n, int m) { out.clear(); out.resize(queries.size()); size_t memoryUsed; int preparingTime; vector<int> searchingTimes(numberOfTestingCycles); ms start, end; string algorithmName = "Unkown"; switch (algorithm) { case 0: { algorithmName = "MinHash (UM)"; start = getTime(); memoryUsed = getCurrentMemoryUsed(); MinHashUM index(text, n, m); index.prepare(); memoryUsed = getCurrentMemoryUsed() - memoryUsed; end = getTime(); preparingTime = (end - start).count(); for (int i = 0; i < numberOfTestingCycles; i++) { out.clear(); out.resize(queries.size()); start = getTime(); index.query(queries, out); end = getTime(); searchingTimes[i] = (end - start).count(); } break; } case 1: { algorithmName = "MinHash (VP)"; start = getTime(); memoryUsed = getCurrentMemoryUsed(); MinHashVP index(text, n, m); index.prepare(); memoryUsed = getCurrentMemoryUsed() - memoryUsed; end = getTime(); preparingTime = (end - start).count(); for (int i = 0; i < numberOfTestingCycles; i++) { out.clear(); out.resize(queries.size()); start = getTime(); index.query(queries, out); end = getTime(); searchingTimes[i] = (end - start).count(); } break; } case 2: { algorithmName = "HashTable"; start = getTime(); memoryUsed = getCurrentMemoryUsed(); HashTable index(text); index.prepare(); memoryUsed = getCurrentMemoryUsed() - memoryUsed; end = getTime(); preparingTime = (end - start).count(); for (int i = 0; i < numberOfTestingCycles; i++) { out.clear(); out.resize(queries.size()); start = getTime(); index.query(queries, out); end = getTime(); searchingTimes[i] = (end - start).count(); } break; } case 3: { algorithmName = "FMIndex"; start = getTime(); memoryUsed = getCurrentMemoryUsed(); FMIndex index(text); index.prepare(); memoryUsed = getCurrentMemoryUsed() - memoryUsed; end = getTime(); preparingTime = (end - start).count(); for (int i = 0; i < numberOfTestingCycles; i++) { out.clear(); out.resize(queries.size()); start = getTime(); index.query(queries, out); end = getTime(); searchingTimes[i] = (end - start).count(); } break; } default: cout << "Unkown algorithm." << endl; return; } printTestResults(algorithmName, pair<int, int>(n, m), vector<int>({ numberOfElements(out), (int)(memoryUsed / 1024 / 1024), preparingTime, averageValue(searchingTimes) }) ); }
void DistanceTransformEuclid(vector<double>& D, const vector<unsigned char>& L, int ndim, const int* dims) { int i,n; for(i=0; i<D.size(); ++i) { if(L[i]) D[i]=0; else D[i]=INFINITY_FELZENSWALB; } int nvoxels=numberOfElements(ndim,dims); int stride=1; vector<int> vsub(ndim); //subscript buffer for(n=0; n<ndim; ++n) { vector<double> buffer(dims[n]); int offset=0; for(int m=0; m<nvoxels/dims[n]; m++) { //compute the offset int m2=m; int k; for(k=0; k<ndim; ++k) { if(k!=n) { vsub[k]=m2 % dims[k]; m2/=dims[k]; } else vsub[k]=0; } int offset=0; int stride2=1; for(k=0; k<ndim; ++k) { offset+=vsub[k]*stride2; stride2*=dims[k]; } //copy relevant line of data for(k=0; k<dims[n]; ++k) buffer[k]=GetData(D,offset+k*stride,(double)0); //do the computation vector<double> dst = dt_Felzenszwalb(buffer,dims[n]); //update the distance for(k=0; k<dims[n]; ++k) SetData(D,offset+k*stride,dst[k]); } stride*=dims[n]; } //take the square root of the distance square for(n=0; n<D.size(); ++n) D[n]=sqrt(D[n]); //no array limit checking... }
void LocalMinimum(vector<unsigned char>& M, const vector<Item>& V, const vector<unsigned char>& L, const vector<int>& nbh, bool strict, int ndim, const int* dims) { int nvoxels = numberOfElements(ndim,dims); if(M.size()<nvoxels || V.size()<nvoxels || L.size()<nvoxels) { //mexPrintf("An input image does not contain enough data.\n"); return; } int i; //construct a subscript representation of the neighborhood //for efficient boundary check vector<int> vcoords; for(i=0; i<nbh.size(); ++i) { vector<int> vsub = Ind2SubCentered(nbh[i],ndim,dims); vcoords.insert(vcoords.end(),vsub.begin(),vsub.end()); } for(i=0; i<nvoxels; ++i) { unsigned char lb=L[i]; if(!lb) continue; //not inside ROI bool bLM=true; bool b0; Item origV=V[i]; vector<int> vsub = Ind2Sub(i,ndim,dims); for(int j=0; j<nbh.size(); ++j) { if(NeighborCheck(vsub.begin(),vcoords.begin()+j*ndim,ndim,dims)) { int k=i+nbh[j]; if(L[k]) { bool b; Item v2=V[k]; if(strict) {// strictly maximum if(v2<=origV) { bLM=false; break; } } else { if(v2<origV) { bLM=false; break; } } } } } if(bLM) { SetData(M,i,(unsigned char) 1); } else { SetData(M,i,(unsigned char) 0); } } }
battle * isBattle(player *players, planet *p) { player *side; participant *participants; battle *aBattle; pdebug(DFULL, "isBattle\n"); participants = NULL; aBattle = NULL; for (side = players; side; side = side->next) { group *aGroup; for (aGroup = side->groups; aGroup; aGroup = aGroup->next) { if (aGroup->location == p) { participant *aParticipant; aParticipant = allocStruct(participant); assert(aParticipant != NULL); aParticipant->who = side; aParticipant->groups = NULL; addList(&participants, aParticipant); break; } } } if (numberOfElements(participants) >= 2) { participant *aParticipant; for (aParticipant = participants; aParticipant; aParticipant = aParticipant->next) { group *aGroup; for (aGroup = aParticipant->who->groups; aGroup; aGroup = aGroup->next) { if (aGroup->location == p) { group *newGroup; newGroup = allocStruct(group); assert(newGroup != NULL); *newGroup = *aGroup; assert(newGroup->ships == aGroup->ships); newGroup->left = aGroup->ships; newGroup->next = NULL; newGroup->name = (char*)malloc(8); sprintf(newGroup->name, "%d", newGroup->number); addList(&(aParticipant->groups), newGroup); } } } if (mustBattle(participants)) { participant *aParticipant; aBattle = allocStruct(battle); assert(aBattle != NULL); aBattle->participants = participants; aBattle->where = p; aBattle->protocol = allocProtocol(); for (aParticipant = participants; aParticipant; aParticipant = aParticipant->next) { group *aGroup; for (aGroup = aParticipant->groups; aGroup; aGroup = aGroup->next) { aGroup->canshoot = alloc(sizeof(int) * (aGroup->ships)); aGroup->alive = alloc(sizeof(int) * (aGroup->ships)); assert(aGroup->canshoot); assert(aGroup->alive); } } } } if (aBattle == NULL) { participant *r, *r2; pdebug(DFULL2, "isBattle : freeing participants.\n"); r = participants; while (r) { freelist(r->groups); r2 = r->next; free(r); r = r2; } } return aBattle; }
int main() { // Part One: // FIXME: Declare variables // Declare two variables: an integer named "age", and a string named "name" with corresponding values (your name and age) int age = 19; char name[] = "Stan"; // FIXME: Print // Print the following sentence in the console "You are NAME and you are AGE years old !". Don't forget to add a newline at the end printf("You are %s and you are %d years old !\n", name, age); // FiXME: Concatenation // Create a new string variable called "hello" which value is "Hello ". Add "name" at the end of "hello" (Concatenation) then print it char hello[] = "Hello "; strcat(hello, name); printf("%s\n", hello); // FIXME: Array // create a new string array called "shoppingList", with three elements of your choice. Create an int variable containing the number of // elements in "shoppingList" (using a function of the array/using the array) char *shoppingList[3] = {"milk", "a Chevy Camaro", "a life"}; const int nbOfElements = numberOfElements(shoppingList); // FIXME: For-loop - Integer // Create a simple for-loop for an integer "i" going from 1 to 10 that print the value of "i" for (int i = 0; i < 10; i++) printf("%d ", i); printf("\n"); // FIXME: For-loop - shoppingList // Create a for loop that iterate through "shoppingList" and prints each element with "You have to buy (elemt)". for (int j = 0; j <nbOfElements; j++) printf("You have to buy %s\n", shoppingList[j]); // FIXME: Foreach-loop // Do the same with a foreach-loop. // The C programming language doesn't have a foreach, but you can look for macros if you are // curious. // FIXME: If-statement // Modify the first for-loop (with i from 1 to 10) such that it prints "(value of i) is even" when "i" is divisible // by 2 (You may want to learn more about "modulo" (%)). Else, print "(value of i) is odd". for (int i = 0; i < 10; i++) { if (i % 2) printf("%d is odd\n", i); else printf("%d is even\n", i); } // FIXME: Sum Up // Create a string variable called "element" with the value of your choice. Then create a for-loop/foreach-loop that checks if "shoppingList" // contains "element". If yes, print "You have to buy (value of element) !", and stop the loop (search how to stop a loop). // If not, print "Nope, you don't need (value of "element")". char element[] = "a life"; for (int k = 0; k < nbOfElements; k++) { if (strcmp(element, shoppingList[k]) == 0) { printf("You have to buy %s !\n", shoppingList[k]); break; } else { printf("Nope, you don't need %s !\n", shoppingList[k]); } } // Part Two: // FIXME: Functions - Ascii // Create a function that returns nothing and which doesn't takes any parameter. It should just be named "TriForce" // and print the TriForce symbol (one triangle over two other ones, can be found on internet) with "TRIFORCE" // Don't forget to call the function ! TriForce(); //Calling the functions in main() // FIXME: Functions - One parameter // Create a function that takes a string as parameter and returns "Hello (value of string) !" // http://stackoverflow.com/questions/1745726/how-to-store-printf-into-a-variable printf("%s", Hello("Stan")); // FIXME: Functions - Multiple parameters // Create a function that takes two integers as parameters and returns the addition of these two. // You can do the same with multiplication, subtraction and division. printf("%d\n", Addition(5, 12)); printf("%d\n", Subtraction(5, 12)); printf("%d\n", Multiplication(5, 12)); printf("%d\n", Division(5, 12)); // returns 0 because "a" and "b" are Integers printf("%d\n", Division(10, 2)); // FIXME: User entry // Create a string variable that takes what the user enter in the console as value. Then print "You entered (value of string)" char userInput[100]; // 100 will be the max length of the input printf("Enter a word:"); scanf("%s", userInput); printf("You entered %s\n", userInput); // FIXME: While loop // Create a while loop that takes a number and divides it by 2 until it is less than 3 int number = 52; while (number > 3) { number /= 2; //or number = number / 2; printf("%d ", number); } printf("\n"); // FIXME: do-While loop // Do the same with a do-while loop int number2 = 84; do { number2 = number2 / 2; printf("%d ", number2); } while (number2 > 3); printf("\n"); // FIXME: Random generator // Create a function that returns a random number srand((unsigned)time(NULL)); // time used for seeding printf("%d\n", rdm()); // FIXME: Random generator with bounds // Create another function that returns a random number between two bounds given as parameters. printf("%d\n", rdmBounds(10, 20)); // FIXME: Multi-dimensionnal array // Create a two dimensionnal int array of 3 columns and 3 rows. Use 2 for-loops to add a random number // between 1 and 9 in each of the 9 rooms. // You may use one of the two previously created function. // Then print them such that they appear like this (with [x1, x9] being the 9 random integers): // {x1, x2, x3, } // {x4, x5, x6, } // {x7, x8, x9, } int multiArray[3][3]; for (int l = 0; l < numberOfElements(multiArray); l++) for (int m = 0; m < numberOfElements(multiArray[l]); m++) multiArray[l][m] = rdmBounds(1, 9); for (int n = 0; n < numberOfElements(multiArray); n++) { printf("{"); for (int o = 0; o < numberOfElements(multiArray[n]); o++) printf("%d, ", multiArray[n][o]); printf("}\n"); } // FIXME: Switch // Create a Switch that takes an integer "a" and return a sentence regarding the value of a // (Create 3 statements for 3 specific values and a default one) int a = 2; switch(a) { case 0: printf("a is 0\n"); break; case 2: printf("a is 2\n"); break; case 37: printf("Who cares about a anyway ?"); break; default: printf("I don't know what \"a\" is... :'(\n"); break; } // FIXME: logic Gates // Create 7 functions for each logic gates (And (0), Or (1), No (2), Nand (3), Nor (4), Xnor (5), Xor (6)). // Each function takes two booleans as parameters and returns the result of the logic gate. // (or You can do it with a switch and only one function) logic_gates(1, 0, 1); logic_gates(1, 1, 1); logic_gates(1, 2, 1); // FIXME - Reverse // Create a function that reverse a string reverse("Hello world"); return 0; }
TimerEventHandle TimerQueue::add( TimerFunc f, void* functionArgs, uint32_t milliseconds, su_time_t now ) { //self check assert( m_length == numberOfElements()) ; assert( 0 != m_length || (NULL == m_head && NULL == m_tail) ) ; assert( 1 != m_length || (m_head == m_tail)) ; assert( m_length < 2 || (m_head != m_tail)) ; assert( !(NULL == m_head && NULL != m_tail)) ; assert( !(NULL == m_tail && NULL != m_head)) ; su_time_t when = su_time_add(now, milliseconds) ; queueEntry_t* entry = new queueEntry_t(this, f, functionArgs, when) ; TimerEventHandle handle = entry ; assert(handle) ; int queueLength ; if( entry ) { #ifndef TEST DR_LOG(log_debug) << m_name << ": Adding entry to go off in " << std::dec << milliseconds << "ms" ; #endif //std::cout << "Adding entry to go off in " << milliseconds << "ms" << std::endl; if( NULL == m_head ) { assert( NULL == m_tail ) ; m_head = m_tail = entry; #ifndef TEST DR_LOG(log_debug) << m_name << ": Adding entry to the head (queue was empty), length: " << dec << m_length+1 ; #endif //std::cout << "Adding entry to the head of the queue (it was empty)" << std::endl ; } else if( NULL != m_tail && su_time_cmp( when, m_tail->m_when ) > 0) { //one class of timer queues will always be appending entries, so check the tail //before starting to iterate through #ifndef TEST DR_LOG(log_debug) << m_name << ": Adding entry to the tail of the queue: length " << dec << m_length+1; #endif //std::cout << "Adding entry to the tail of the queue" << std::endl ; entry->m_prev = m_tail ; m_tail->m_next = entry ; m_tail = entry ; } else { //iterate queueEntry_t* ptr = m_head ; int idx = 0 ; do { if( su_time_cmp( when, ptr->m_when ) < 0) { #ifndef TEST DR_LOG(log_debug) << m_name << ": Adding entry at position " << std::dec << idx << " of the queue, length: " << dec << m_length+1 ; #endif //std::cout << "Adding entry at position " << idx << " of the queue" << std::endl ; entry->m_next = ptr ; if( 0 == idx ) { m_head = entry ; } else { entry->m_prev = ptr->m_prev ; ptr->m_prev->m_next = entry ; } ptr->m_prev = entry ; break ; } idx++ ; } while( NULL != (ptr = ptr->m_next) ) ; assert( NULL != ptr ) ; /* if( NULL == ptr ) { #ifndef TEST DR_LOG(log_debug) << m_name << ": Adding entry to the tail of the queue: length " << dec << m_length+1; #endif //std::cout << "Adding entry to the tail of the queue" << std::endl ; entry->m_prev = m_tail ; m_tail->m_next = entry ; m_tail = entry ; } */ } queueLength = ++m_length ; } else { //DR_LOG(log_error) << "Error allocating queue entry" ; //std::cerr << "Error allocating queue entry" << std::endl ; return NULL ; } //only need to set the timer if we added to the front if( m_head == entry ) { //DR_LOG(log_debug) << "timer add: Setting timer for " << milliseconds << "ms" ; //std::cout << "timer add: Setting timer for " << milliseconds << "ms" << std::endl; int rc = su_timer_set_at(m_timer, timer_function, this, when); assert( 0 == rc ) ; } //DR_LOG(log_debug) << "timer add: queue length is now " << queueLength ; //std::cout << "timer add: queue length is now " << queueLength << std::endl; //self check assert( m_length == numberOfElements()) ; assert( 0 != m_length || (NULL == m_head && NULL == m_tail) ) ; assert( 1 != m_length || (m_head == m_tail)) ; assert( m_length < 2 || (m_head != m_tail)) ; assert( !(NULL == m_head && NULL != m_tail)) ; assert( !(NULL == m_tail && NULL != m_head)) ; return handle ; }
void TimerQueue::doTimer(su_timer_t* timer) { //self check assert( m_length == numberOfElements()) ; assert( 0 != m_length || (NULL == m_head && NULL == m_tail) ) ; assert( 1 != m_length || (m_head == m_tail)) ; assert( m_length < 2 || (m_head != m_tail)) ; assert( !(NULL == m_head && NULL != m_tail)) ; assert( !(NULL == m_tail && NULL != m_head)) ; #ifndef TEST DR_LOG(log_debug) << m_name << ": running timer function" ; #endif //std::cout << "doTimer: running timer function with " << m_length << " timers queued " << std::endl; if( m_in_timer ) return ; m_in_timer = 1 ; queueEntry_t* expired = NULL ; queueEntry_t* tailExpired = NULL ; su_time_t now = su_now() ; assert( NULL != m_head ) ; queueEntry_t* ptr = m_head ; while( ptr && su_time_cmp( ptr->m_when, now ) < 0 ) { //std::cout << "expiring a timer" << std::endl ; m_length-- ; m_head = ptr->m_next ; if( m_head ) m_head->m_prev = NULL ; else m_tail = NULL ; //detach and assemble them into a new queue temporarily if( !expired ) { expired = tailExpired = ptr ; ptr->m_prev = ptr->m_next = NULL ; } else { tailExpired->m_next = ptr ; ptr->m_prev = tailExpired ; tailExpired = ptr ; } ptr = ptr->m_next ; } if( NULL == m_head ) { #ifndef TEST DR_LOG(log_debug) << m_name << ": timer not set (queue is empty after processing expired timers), length: " << dec << m_length ; #endif //std::cout << "doTimer: timer not set (queue is empty after processing expired timers)" << std::endl; assert( 0 == m_length ) ; } else { //std::cout << "doTimer: Setting timer for " << su_duration( m_head->m_when, su_now() ) << "ms after processing expired timers" << std::endl; #ifndef TEST DR_LOG(log_debug) << m_name << ": Setting timer for " << su_duration( m_head->m_when, su_now() ) << "ms after processing expired timers, length: " << dec << m_length ; #endif int rc = su_timer_set_at(m_timer, timer_function, this, m_head->m_when); } m_in_timer = 0 ; while( NULL != expired ) { expired->m_function( expired->m_functionArgs ) ; queueEntry_t* p = expired ; expired = expired->m_next ; delete p ; } //self check assert( m_length == numberOfElements()) ; assert( 0 != m_length || (NULL == m_head && NULL == m_tail) ) ; assert( 1 != m_length || (m_head == m_tail)) ; assert( m_length < 2 || (m_head != m_tail)) ; assert( !(NULL == m_head && NULL != m_tail)) ; assert( !(NULL == m_tail && NULL != m_head)) ; }
void TimerQueue::remove( TimerEventHandle entry) { #ifndef TEST DR_LOG(log_debug) << m_name << ": removing entry, prior to removal length: " << dec << m_length; #endif //self check assert( m_length == numberOfElements()) ; assert( 0 != m_length || (NULL == m_head && NULL == m_tail) ) ; assert( 1 != m_length || (m_head == m_tail)) ; assert( m_length < 2 || (m_head != m_tail)) ; assert( !(NULL == m_head && NULL != m_tail)) ; assert( !(NULL == m_tail && NULL != m_head)) ; assert( m_head && m_length >= 1 ) ; int queueLength ; { if( m_head == entry ) { m_head = entry->m_next ; if( m_head ) m_head->m_prev = NULL ; else { assert( 1 == m_length ) ; m_tail = NULL ; } } else if( m_tail == entry ) { assert( m_head && entry->m_prev ) ; m_tail = entry->m_prev ; m_tail->m_next = NULL ; } else { assert( entry->m_prev ) ; assert( entry->m_next ) ; entry->m_prev->m_next = entry->m_next ; entry->m_next->m_prev = entry->m_prev ; } m_length-- ; assert( m_length >= 0 ) ; if( NULL == m_head ) { #ifndef TEST DR_LOG(log_debug) << m_name << ": removed entry, timer not set (queue is empty after removal), length: " << dec << m_length; #endif //std::cout << "timer not set (queue is empty after removal)" << std::endl; su_timer_reset( m_timer ) ; } else if( m_head == entry->m_next ) { #ifndef TEST DR_LOG(log_debug) << m_name << ": removed entry, setting timer for " << std::dec << su_duration( m_head->m_when, su_now() ) << "ms after removal, length: " << dec << m_length; #endif //std::cout << "Setting timer for " << su_duration( m_head->m_when, su_now() ) << "ms after removal of head entry" << std::endl; int rc = su_timer_set_at(m_timer, timer_function, this, m_head->m_when); } } //DR_LOG(log_debug) << "timer remove: queue length is now " << queueLength ; //std::cout << "timer remove: queue length is now " << queueLength << std::endl; delete entry ; //self check assert( m_length == numberOfElements()) ; assert( 0 != m_length || (NULL == m_head && NULL == m_tail) ) ; assert( 1 != m_length || (m_head == m_tail)) ; assert( m_length < 2 || (m_head != m_tail)) ; assert( !(NULL == m_head && NULL != m_tail)) ; assert( !(NULL == m_tail && NULL != m_head)) ; }