예제 #1
0
파일: mm.c 프로젝트: bkashyap/ece454
/**********************************************************
 * coalesce
 * Covers the 4 cases discussed in the text:
 * - both neighbours are allocated
        and also add the free block to the front of the
        free list
 * - the next block is available for coalescing
        it will remove the next block from the free list
        coalesce bp and next block together
        and place the coalesced block in front of free list
 * - the previous block is available for coalescing
        it will remove the previous block from the free list
        coalesce bp and previous block together
        and place the coalesced block in front of free list
 * - both neighbours are available for coalescing
        it will remove neighbour blocks from the free list
        coalesce all three blocks together
        and place it in front of the free list
 **********************************************************/
void *coalesce(void *bp)
{
    //printf(" coalesce %p ",bp);
    size_t prev_alloc = GET_ALLOC(FTRP(PREV_BLKP(bp)));
    size_t next_alloc = GET_ALLOC(HDRP(NEXT_BLKP(bp)));
    size_t size = GET_SIZE(HDRP(bp));

    if (prev_alloc && next_alloc) {       /* Case 1 */
        //printf(" 1\n");
        addToFront(bp);
        return bp;
    }

    else if (prev_alloc && !next_alloc) { /* Case 2 */
        //printf(" 2\n");

        rmFromFreeList(NEXT_BLKP(bp));

        size += GET_SIZE(HDRP(NEXT_BLKP(bp)));
        PUT(HDRP(bp), PACK(size, 0));
        PUT(FTRP(bp), PACK(size, 0));

        addToFront(bp);
        return (bp);
    }

    else if (!prev_alloc && next_alloc) { /* Case 3 */
        //printf(" 3\n");

        rmFromFreeList(PREV_BLKP(bp));

        size += GET_SIZE(HDRP(PREV_BLKP(bp)));
        PUT(FTRP(bp), PACK(size, 0));
        PUT(HDRP(PREV_BLKP(bp)), PACK(size, 0));

        addToFront(PREV_BLKP(bp));
        return (PREV_BLKP(bp));
    }

    else {            /* Case 4 */
        //printf(" 4\n");

        rmFromFreeList(PREV_BLKP(bp));
        rmFromFreeList(NEXT_BLKP(bp));

        size += GET_SIZE(HDRP(PREV_BLKP(bp)))  +
            GET_SIZE(FTRP(NEXT_BLKP(bp)))  ;
        PUT(HDRP(PREV_BLKP(bp)), PACK(size,0));
        PUT(FTRP(NEXT_BLKP(bp)), PACK(size,0));

        addToFront(PREV_BLKP(bp));
        return (PREV_BLKP(bp));

    }
}
예제 #2
0
파일: klists.cpp 프로젝트: OmerMor/scummvm
reg_t kAddToFront(EngineState *s, int argc, reg_t *argv) {
	addToFront(s, argv[0], argv[1]);

	if (argc == 3)
		s->_segMan->lookupNode(argv[1])->key = argv[2];

	return s->r_acc;
}
예제 #3
0
void addLitToFront(SLIST *strList, char *lit)
{
	struct String *newStr = createStr();
	SNODE *newNode = (SNODE *)wrp_calloc(1, sizeof(SNODE));
	appendLit(newStr, lit);
	initStrNode(newNode, newStr);
	addToFront(strList, newNode);
}
예제 #4
0
void LinkedList<T>::initList(const T& component )
{
    if(head != nullptr)
    {
        deleteList();
    }
    addToFront(component);

    head->next = nullptr;
    tail = head;
}
예제 #5
0
// Replacement for malloc that stores the pointers allocated. It should store
// the pointers in some kind of list; a linked list would do fine, but insert
// here whatever code you'll need to do so; don't call functions in the
// pre-existing linkedlist.h. Otherwise you'll end up with circular
// dependencies, since you're going to modify the linked list to use talloc.
void *talloc(size_t size) {
    if (!madeList) {
        activeList = malloc(sizeof(Value));
        activeList->type = NULL_TYPE;
        madeList = 1;
    }
    void *ptr = malloc(size);
    Value *valpt = malloc(sizeof(Value));
    valpt->p = ptr;
    valpt->type = PTR_TYPE;
    activeList = addToFront(valpt, activeList);
    
    return ptr;
}
예제 #6
0
/*
	Adds a new node to the end while maintaining the empty node at the end. Returns the front of the list.	
*/
listNode* addToEnd(listNode *front, listNode *newNode){
	if(front->next == NULL){//The list is empty
		return addToFront(front, newNode); 
	}
	else{
		listNode *temp = front;
		while(temp->next->next != NULL){
			temp = temp->next;	
		}
		//temp should now be right before the empty node
		newNode->next = temp->next;
		temp->next = newNode;
		return front;
	}
}
예제 #7
0
int main(){

	struct node *root = (struct node *) malloc(sizeof(struct node));
	struct node *first = (struct node *) malloc(sizeof(struct node));
	
	root->next = first;
	
	first->next = NULL;
	first->data = 10;
	printf("First List\n");
	printList(root->next);
	
	struct node *second = (struct node *) malloc(sizeof(struct node));
	second->data = 5;
	addToFront(second, root);
	printf("Second List\n");
	printList(root->next);
	
	struct node *third = (struct node *) malloc(sizeof(struct node));
	third->data = 15;
	addToLast(third, root);
	printf("Third List\n");
	printList(root->next);
	
	struct node *mid = (struct node *) malloc(sizeof(struct node));
	mid->data = 12;
	addAt(mid, first);
	printf("Fourth List\n");
	printList(root->next);
	
	struct node *mid2 = (struct node *) malloc(sizeof(struct node));
	mid2->data = 14;
	addAt(mid2, mid);
	printf("Fifth List\n");
	printList(root->next);
	
	deleteNode(mid2, root);
	printf("Sixth List\n");
	printList(root->next);
	
	return 0;
}
예제 #8
0
파일: klists.cpp 프로젝트: OmerMor/scummvm
reg_t kAddAfter(EngineState *s, int argc, reg_t *argv) {
	List *list = s->_segMan->lookupList(argv[0]);
	Node *firstnode = argv[1].isNull() ? NULL : s->_segMan->lookupNode(argv[1]);
	Node *newnode = s->_segMan->lookupNode(argv[2]);

#ifdef CHECK_LISTS
	checkListPointer(s->_segMan, argv[0]);
#endif

	if (!newnode) {
		error("New 'node' %04x:%04x is not a node", PRINT_REG(argv[2]));
		return NULL_REG;
	}

	if (argc != 3 && argc != 4) {
		error("kAddAfter: Haven't got 3 or 4 arguments, aborting");
		return NULL_REG;
	}

	if (argc == 4)
		newnode->key = argv[3];

	if (firstnode) { // We're really appending after
		reg_t oldnext = firstnode->succ;

		newnode->pred = argv[1];
		firstnode->succ = argv[2];
		newnode->succ = oldnext;

		if (oldnext.isNull())  // Appended after last node?
			// Set new node as last list node
			list->last = argv[2];
		else
			s->_segMan->lookupNode(oldnext)->pred = argv[2];

	} else { // !firstnode
		addToFront(s, argv[0], argv[2]); // Set as initial list node
	}

	return s->r_acc;
}
예제 #9
0
파일: Hits.cpp 프로젝트: FilipBE/qtextended
	Document& Hits::doc(const int32_t n){
		HitDoc* hitDoc = getHitDoc(n);

		// Update LRU cache of documents
		remove(hitDoc);				  // remove from list, if there
		addToFront(hitDoc);				  // add to front of list
		if (numDocs > maxDocs) {			  // if cache is full
			HitDoc* oldLast = last;
			remove(last);				  // flush last

			_CLDELETE( oldLast->doc );
			oldLast->doc = NULL;
		}

		if (hitDoc->doc == NULL){
			hitDoc->doc = _CLNEW Document;
			searcher->doc(hitDoc->id, hitDoc->doc);	  // cache miss: read document
		}

		return *hitDoc->doc;
	}
예제 #10
0
파일: main.c 프로젝트: njagdale/code-magic
int main(){

    addToFront(6);
    addToFront(5);
    addToFront(4);
    addToFront(3);
    addToFront(2);
    addToFront(1);

    printLL(gHead);

    gHead = oddEvenList(gHead);

    printLL(gHead);

    return 0;
}
예제 #11
0
파일: mm.c 프로젝트: bkashyap/ece454
/**********************************************************
 * place
 * Mark the block as allocated
    place will mark a block from the free list as allocated
    the block is removed from the free list, then checked if it needs 
    to be split. If it needs to be split. it will split it and place
    the second free block into the front of the free list.
 **********************************************************/
void place(void* bp, size_t asize)
{
    //print_free_list();
    //printf("---place\n");

    size_t min_size = DSIZE+DSIZE;
    size_t free_size = GET_SIZE(HDRP(bp));
    size_t bsize;

    rmFromFreeList(bp);

    if (free_size >= asize+min_size) {
        //printf(" and split");
        //pack asize
        //printf(" asize %zu", asize);
        PUT(HDRP(bp), PACK(asize, 1));
        PUT(FTRP(bp), PACK(asize, 1));

        //pack bsize
        bsize = free_size - asize;
        //printf(" bsize %zu \n", bsize);
        void * free_bp = NEXT_BLKP(bp);
        PUT(HDRP(free_bp), PACK(bsize, 0));
        PUT(FTRP(free_bp), PACK(bsize, 0));

        //add bsize to free list
        addToFront(free_bp);
        
    }
    else {
        //printf(" and done");
        //no splitting
        PUT(HDRP(bp), PACK(free_size, 1));
        PUT(FTRP(bp), PACK(free_size, 1));
    }

    //print_free_list();
}
예제 #12
0
/*
 * Listens for incoming connections on a port number specified on the command 
 * line. Once a connection is established, it reads the entirety of the 
 * request from the client and parse the request. It determines whether the 
 * client has sent a valid HTTP request; if so, it then establishes its own
 * connection to the appropriate web server then requests the object the client
 * specified. Finally, the proxy reads the server’s response and forwards it to 
 * the client.
 */
void doit(int fd)
{
	int isnot_safe;
	char buf[MAXLINE], method[MAXLINE], uri[MAXLINE], version[MAXLINE], 
	temp[MAXLINE], host[MAXLINE], clientheaders[MAXLINE], readRequests[MAXLINE],
	path[MAXLINE];
	char *data = malloc(MAX_OBJECT_SIZE*sizeof(char));
	size_t sizeOfTotalData = 0;
	char *dataBuffer = malloc(MAX_OBJECT_SIZE*sizeof(char));
  char *temporaryData = dataBuffer;
	char* port_pointer;
	int port = 80, len, len2;
	rio_t rio, rio1;
	int serverConn_fd;
  cache_node *fileObj = NULL;
  //cache_node *addFile = malloc(sizeof(cache_node));

	//associates rio with the descriptor
	Rio_readinitb(&rio, fd);
	//reads and flushes the buf with the request
	Rio_readlineb(&rio, buf, MAXLINE);
	
	//parsing the initial request
	isnot_safe = safe_scan(sscanf(buf, "%s %s %s\r\n", method, uri, version));

	if (isnot_safe)
		return;

	//cannot perform if it is not a Get method
    if (strcasecmp(method, "GET")) {
		printf("501 Not Implemented Proxy does not handle this method");
		return;
    }
    //printf("Does it reach here after Get?\n");

    //Parse the URL properly
    if (strstr(uri, "http://"))
    {
        isnot_safe = safe_scan(sscanf(uri, "%[^'/']%s", temp,  uri));

        if (isnot_safe)
        	return;

        memmove(uri, uri+2, strlen(uri));
    }

    //printf("%s\n", uri);
    if(strchr(uri, '/') != NULL) {
		isnot_safe = safe_scan(sscanf(uri, "%[^'/']%s", host, path));

        if (isnot_safe)
        	return;
    }
    else {
    	//if no path is specified then it is just "/".
		strcpy(path, "/");
		strcpy(host, uri);
    }
    //printf("HOST %s\n", host);
    //Get the port if it is specified
    if ((port_pointer = strchr(host, ':')) != NULL){
		isnot_safe = safe_scan(sscanf(port_pointer, ":%d", &port));

        if (isnot_safe)
        	return;

		isnot_safe = safe_scan(sscanf(host, "%[^0-9:]", host));

        if (isnot_safe)
        	return;
    }

    //Look up the object in the cache
    if ((fileObj = find(uri)) != NULL)
    {
      rio_writen(fd, fileObj->file, fileObj->size);
      return;
    }    
    //flush the readRequests associated with the path and host
    sprintf(readRequests, "GET %s HTTP/1.0\r\nHost: %s\r\n", path, host);

    //open a server connection with the host and port
    serverConn_fd = Open_clientfd(host, port);

    //associate the file descriptor and write to it from readRequests
    
    Rio_readinitb(&rio1, serverConn_fd);
    isnot_safe = safe_rio(rio_writen(serverConn_fd, readRequests, 
    						strlen(readRequests)));

    if (isnot_safe)
        return;

    //Send in all necessary headers
    isnot_safe = safe_rio(rio_writen(serverConn_fd, (void *) user_agent_hdr, 
                                                  strlen(user_agent_hdr)));

    if (isnot_safe)
        return;

    isnot_safe = safe_rio(rio_writen(serverConn_fd, (void *) accept_hdr, 
                                                  strlen(accept_hdr)));

    if (isnot_safe)
        return;

    isnot_safe = safe_rio(rio_writen(serverConn_fd, 
                (void *) accept_encoding_hdr, strlen(accept_encoding_hdr)));

    if (isnot_safe)
        return;

    isnot_safe = safe_rio(rio_writen(serverConn_fd,
      "Proxy-Connection: close\r\nConnection:\tclose\r\n\r\n", 52));

    if (isnot_safe)
        return;


    //Get additional requests by clients that are not already passed and 
    //pass them through without changing them
    while((len = rio_readlineb(&rio, readRequests, MAXBUF)) && 
    			strcmp(readRequests, "\r\n"))
    {
      //Get the headers
	    isnot_safe = safe_scan(sscanf(readRequests, "%s ",clientheaders));

        if (isnot_safe)
        	return;

        //see if the headers are not the ones we already passed.
	    if(!strstr(clientheaders, "Host:")&& !strstr(clientheaders,"Connection:")
        && !strstr(clientheaders, "User-Agent:") && !strstr(clientheaders,
          "Accept-Encoding:") && !strstr(clientheaders,"Accept:") && 
        !strstr(clientheaders,"Proxy-Connection:"))

	    {

	        isnot_safe = safe_rio(rio_writen(serverConn_fd, readRequests, len));
			
        	if (isnot_safe)
        		return;	   	
    	}
  	}


  //Finally write to the client desciptor what the server responds with
  while((len2 = rio_readnb(&rio1, data, MAXLINE))){
    sizeOfTotalData += len2;

    //Keep writing to the memory at temporaryData as long as size of the data 
    //so far is less than max object size
    if (sizeOfTotalData < MAX_OBJECT_SIZE){
      memcpy(temporaryData,data,len2);
      temporaryData += len2;
    }
    rio_writen(fd, data, len2);
  }

  //We shouldn't add the object to the cache if the size of the
  //data exceeds the max object size or is 0
  if(sizeOfTotalData <= MAX_OBJECT_SIZE && sizeOfTotalData != 0)
  {
    pthread_rwlock_wrlock(&lock);
    addToFront(uri, dataBuffer, sizeOfTotalData);
    pthread_rwlock_unlock(&lock);
  }

  free(data);

  return;

}
예제 #13
0
MusicRec * CreateList(char * fileName)
{
    MusicRec * head;
    MusicRec * toAdd;
    FILE * file;
    char fileContents[200];
    char * line;
    bool headExists;

    /* open the text file and read it */
    file = fopen(fileName, "r");
    if(file == NULL)
    {
        printf("The file specified does not exist. Try again.\n");
        exit(0);
    }
    /* start without a head */
    headExists = false;
    while(fgets(fileContents, sizeof(fileContents), file) != NULL)
    {
        /* split the text file by new lines */
        line = strtok(fileContents, "\n");
        
        /* if the line does not contain at least 1 letter between commas it is too short */
        if(strlen(fileContents) < 8)
            continue;

        /* if we are parsing the first element, we create the head */
        if(!headExists)
        {
            /* create the node to add */
            toAdd = ParseLine(line);

            /* if all went well and it is set, set it to the head */
            if(toAdd != NULL)
            {
                headExists = true;
                head = toAdd;
            }
        }
        else
        {
            toAdd = ParseLine(line);

            if(toAdd != NULL)
            {    
                if(toAdd->type == 'a')
                {
                    /* add it to the front */
                    head = addToFront(head, toAdd);
                }
                else
                {
                    /* add it to the back */
                    head = addToBack(head, toAdd);
                }
            }
        }   
    }
    /* close the file */
    fclose(file);
    
    return head;
}
예제 #14
0
int main(int argc, char * argv[])
{
	FILE * file;
	char * name;
	char * group;
	char line[900][256];
	char ch;
	char type;
	char temp;
	double calories;
	double calTotal = 0;
	double vegTotal = 0, meatTotal = 0, dairyTotal = 0, grainsTotal = 0, fatTotal = 0;
	double vegTot = 0, meatTot = 0, dairyTot = 0, grainsTot = 0, fatTot = 0;
	int i;

	Food * head = (Food *)malloc(sizeof(Food));
	Food * ptr = (Food *)malloc(sizeof(Food));

	head = NULL;
	ptr = NULL;

	if (argc < 2)
	 {
		printf("No argument inputted. Exiting...\n");
		exit(0);
	}

	file = fopen(argv[1], "r");
	if (file == NULL)
	 {
		printf("Error opening file. Exiting...\n");
		exit(0);
	}
	while((ch = fgetc(file)) != EOF)
	 {
		line[i][0] = ch;
		while((ch = fgetc(file)) != '\n')
		 {
			line[i][strlen(line[i])] = ch;
			if (line[i][strlen(line[i])-1] == ',' && isdigit(line[i][strlen(line[i])-2]))
			 {
				temp = fgetc(file);
			}
		}
		name = strtok(line[i], ",");
		group = strtok(NULL, ",");
		calories = atoi(strtok(NULL, ","));
		calTotal += calories;
		type = temp;
		ptr = createRecord(name, group, calories, type);
		if (head == NULL)
		 {
			head = ptr;
		}
		else if (type == 'j')
		 {
			head = addToBack(head, ptr);
		}
		else if (type == 'h')
		 {
			head = addToFront(head, ptr);
		}

		if (strcmp(group, "vegfruit") == 0)
		 {
                vegTotal += calories;
                vegTot += 1;
		}
		else if (strcmp(group, "grains") == 0)
         {
                grainsTotal += calories;
                grainsTot += 1;
        }
		else if (strcmp(group, "dairy") == 0)
         {
                dairyTotal += calories;
                dairyTot += 1;
        }
		else if (strcmp(group, "meat") == 0)
         {
                meatTotal += calories;
                meatTot += 1;
        }
		else if (strcmp(group, "fat") == 0)
         {
                fatTotal += calories;
                fatTot += 1;
        }

		i++;
	}
	printf("%d\n", (int)calTotal);
	printf("%.0f\n", vegTotal / vegTot);
	printf("%.0f\n", meatTotal / meatTot);
	printf("%.0f\n", dairyTotal / dairyTot);
	printf("%.0f\n", grainsTotal / grainsTot);
	printf("%.0f\n", fatTotal / fatTot);
	printList(head);
	destroyList(head);

	return 0;
}
예제 #15
0
void addNode(SLIST *strList, SNODE *node)
{
	SNODE *prevNode;
	//Add node to empty list
	if (strList->length == 0)
	{
		strList->head = node;
		strList->tail = node;
		strList->length++;
	}
	//non-empty list
	else
	{
		//new node should appear alphabetically before strList->head
		if (compareStr(node->str, strList->head->str) == -1)
		{
			addToFront(strList, node);
		}
		//new node is equal to strList->head
		else if (compareStr(node->str, strList->head->str) == 0)
			strList->head->count++;
			
		//node should appear alphabetically after strList->tail
		else if ((compareStr(node->str, strList->tail->str)) == 1)
		{
			addToBack(strList, node);
		}
		//new node is equal to strList->tail
		else if (compareStr(node->str, strList->tail->str) == 0)
			strList->tail->count++;
		//new node is not smaller than strList->head nor greater than strList->tail
		else
		{
			//Start at node after head
			strList->cur = strList->head;
			while (strList->cur != NULL)
			{
				//new node contains the same string as strList->cur
				if (compareStr(node->str, strList->cur->str) == 0)
				{
					strList->cur->count++;
					break;
				}			
				//node->str should appear alphabetically after cur->str
				else if (compareStr(node->str, strList->cur->str) == 1)
				{
					strList->cur = strList->cur->next;					
				}
				//node->str should appear alphabetically before cur->str
				else
				{
					prevNode = strList->cur->prev;
					//First have node point to forwards to current and backwards to previous node
					node->next = strList->cur;
					node->prev = prevNode;
					prevNode->next = node; //Point old previous node to new node
					strList->cur->prev = node;
					strList->length++;
					break;
				}
			}
		}
	}
}
예제 #16
0
void addStrToFront(SLIST *strList, struct String *s)
{
	SNODE *node = (SNODE *)wrp_calloc(1, sizeof(SNODE));
	initStrNode(node, s);
	addToFront(strList, node);
}