Ejemplo n.º 1
0
int main(int argc, char* argv[]){
   Dictionary A = newDictionary();
   printf("got jere");
   FILE* in = fopen("DictionaryClient2.c", "r");
   FILE* out = fopen("DictionaryClient2-out", "w");
   char* key;
   char* value;
   char* keyBuffer = NULL;
   char* valBuffer = NULL;
   int keyBufferOffset = 0, valBufferOffset = 0;
   int keyBufferLength = 0, valBufferLength = 0;
   char line[MAX_LEN+1];
   char label[MAX_LEN+1];
   int i, labelLength, lineLength, lineNumber = 0;
   
   // read input files
   while( fgets(line, MAX_LEN, in)!=NULL ){
      
      // put line in valBuffer
      lineNumber++;
      lineLength = strlen(line)-1;
      line[lineLength] = '\0';  // overwrite newline '\n' with null '\0'
      valBufferLength += (lineLength+1);
      valBuffer = realloc(valBuffer, valBufferLength*sizeof(char) );
      value = &valBuffer[valBufferOffset];
      strcpy(value, line);
      valBufferOffset = valBufferLength;
      
      // put label in keyBuffer
      sprintf(label, "line %d:\t", lineNumber);
      labelLength = strlen(label);
      keyBufferLength += (labelLength+1);
      keyBuffer = realloc(keyBuffer, keyBufferLength*sizeof(char) );
      key = &keyBuffer[keyBufferOffset];
      strcpy(key, label);
      keyBufferOffset = keyBufferLength;
   }

   // put keys and values in dictionary A
   keyBufferOffset = valBufferOffset = 0;
   for(i=0; i<lineNumber; i++){
      key = &keyBuffer[keyBufferOffset];
      value = &valBuffer[valBufferOffset];
      insert(A, key, value);
      keyBufferOffset += (strlen(key) + 1);
      valBufferOffset += (strlen(value) + 1);
   } 

   printDictionary(out, A);

   // free memory and close files
   freeDictionary(&A);
   free(keyBuffer);
   free(valBuffer);
   fclose(in);
   fclose(out);

   return(EXIT_SUCCESS);
}
Ejemplo n.º 2
0
/*
    readDeclaration reads a declaration of a class
*/
static void readClassDeclaration()
{   
    ObjectHandle classObj, metaObj, vars;
    std::string className, superName;
    int i, size, instanceTop;
    // todo: fixed length variables array!
    ObjectHandle instanceVariables[15];
    // todo: horrible fixed length arrays!
    char metaClassName[100];
    char metaSuperClassName[100];

    if (ll.nextToken() != nameconst)
        sysError("bad file format","no name in declaration");
    className = ll.strToken();
    if (ll.nextToken() == nameconst) 
    { /* read superclass name */
        superName = ll.strToken();
        ll.nextToken();
    }
    // todo: sprintf eradication!
    sprintf(metaClassName, "Meta%s", className.c_str());
    if(!superName.empty())
        sprintf(metaSuperClassName, "Meta%s", superName.c_str());
    else
        sprintf(metaSuperClassName, "Class");

    metaObj = createRawClass(metaClassName, "Class", metaSuperClassName);
    classObj = createRawClass(className.c_str(), metaClassName, superName.c_str());
    classObj->_class = metaObj;

    // Get the current class size, we'll build on this as 
    // we add instance variables.
    size = getInteger(classObj->basicAt(sizeInClass));

    if (ll.currentToken() == nameconst) 
    {     /* read instance var names */
        instanceTop = 0;
        while (ll.currentToken() == nameconst) 
        {
            instanceVariables[instanceTop++] = createSymbol(ll.strToken().c_str());
            size++;
            ll.nextToken();
        }
        vars = newArray(instanceTop);
        for (i = 0; i < instanceTop; i++) 
        {
            vars->basicAtPut(i+1, instanceVariables[i]);
        }
        classObj->basicAtPut(variablesInClass, vars);
    }
    classObj->basicAtPut(sizeInClass, newInteger(size));
    classObj->basicAtPut(methodsInClass, newDictionary(39));
}
Ejemplo n.º 3
0
/*
    readRawDeclaration reads a declaration of a class
*/
static void readRawClassDeclaration()
{   
    ObjectHandle classObj, vars;
    std::string className, metaName, superName;
    int i, size, instanceTop;
    // todo: fixed length variables array!
    ObjectHandle instanceVariables[15];

    if (ll.nextToken() != nameconst)
        sysError("bad file format","no name in declaration");
    className = ll.strToken();
    size = 0;
    if (ll.nextToken() == nameconst) 
    { /* read metaclass name */
        metaName = ll.strToken();
        ll.nextToken();
    }
    if (ll.currentToken() == nameconst) 
    { /* read superclass name */
        superName = ll.strToken();
        ll.nextToken();
    }

    classObj = createRawClass(className.c_str(), metaName.c_str(), superName.c_str());

    // Get the current class size, we'll build on this as 
    // we add instance variables.
    size = getInteger(classObj->basicAt(sizeInClass));

    if (ll.currentToken() == nameconst) 
    {     /* read instance var names */
        instanceTop = 0;
        while (ll.currentToken() == nameconst) 
        {
            instanceVariables[instanceTop++] = createSymbol(ll.strToken().c_str());
            size++;
            ll.nextToken();
        }
        vars = newArray(instanceTop);
        for (i = 0; i < instanceTop; i++) 
        {
            vars->basicAtPut(i+1, instanceVariables[i]);
        }
        classObj->basicAtPut(variablesInClass, vars);
    }
    classObj->basicAtPut(sizeInClass, newInteger(size));
    classObj->basicAtPut(methodsInClass, newDictionary(39));
}
Ejemplo n.º 4
0
zHttpRequest * parseRequest(int connectfd){
	int br;
	char socket_buffer[SOCKET_BUFFER_SIZE];

	zHttpRequest *newRequest = (zHttpRequest *)malloc(sizeof(struct zHttpRequest));

	//grab contents of stream, store fd
	newRequest->outfd = connectfd;

  br = read(connectfd, socket_buffer, SOCKET_BUFFER_SIZE);

	socket_buffer[br] = '\0';
	printf("%s\n[%d bytes read]\n", (char*)socket_buffer, br);

	//build header dict, fill with header fields
	newRequest->header = newDictionary();

	int index = 0; //necessary for newNextLine to keep parsing socket_buffer
	//get first line of HTTP Request, store method & location
	char * line = newNextLine(socket_buffer, &index);	
	char * method_type = newIndexToChar(line, 0, ' ');
	addValueForKey(newRequest->header, newString("method"), method_type);
	int start = strlen(method_type)+1;
	char * location_req = newIndexToChar(line, start, ' ');
	addValueForKey(newRequest->header, newString("location"), location_req);
	free(line);

	//parse out rest of header fields, add to dict
	for(;;){
		line = newNextLine(socket_buffer, &index);
		int len = strlen(line);
		if(len <= 1)
			break;
		char * key_string = mutateToLower(newIndexToChar(line, 0, ':'));
		start = strlen(key_string)+2;
		char * val_string = newIndexToChar(line, start, '\r');
		//printf("key: '%s', val: [%s]\n", key_string, val_string);
		addValueForKey(newRequest->header, key_string, val_string);
		free(line);
	}

	//parse and store body
	newRequest->body = newIndexToChar(socket_buffer, index, '\0');
	//printDict(newRequest->header);
	//printf("Body::\n%s\n::end Body\n", newRequest->body);
	return newRequest;
}
int main(int argc, char* argv[]){
   Dictionary A = newDictionary();
   char* k;
   char* v;
   char* word1[] = {"one","two","three","four","five","six","seven"};
   char* word2[] = {"foo","bar","blah","galumph","happy","sad","blue"};
   int i;

   for(i=0; i<7; i++){
      insert(A, word1[i], word2[i]);
   }

   printDictionary(stdout, A);

   for(i=0; i<7; i++){
      k = word1[i];
      v = lookup(A, k);
      printf("key=\"%s\" %s\"%s\"\n", k, (v==NULL?"not found ":"value="), v);
   }

   // insert(A, "five", "glow"); // error: duplicate keys

   delete(A, "one");
   delete(A, "three");
   delete(A, "seven");

   printDictionary(stdout, A);

   for(i=0; i<7; i++){
      k = word1[i];
      v = lookup(A, k);
      printf("key=\"%s\" %s\"%s\"\n", k, (v==NULL?"not found ":"value="), v);
   }

   // delete(A, "one");  // error: key not found

   printf("%s\n", (isEmpty(A)?"true":"false"));
   printf("%d\n", size(A));
   makeEmpty(A);
   printf("%s\n", (isEmpty(A)?"true":"false"));

   freeDictionary(&A);

   return(EXIT_SUCCESS);
}
Ejemplo n.º 6
0
int main(int argc, char* argv[]){
   int v;
   DictionaryRef A = newDictionary();

    insert(A, 1, 111);
    insert(A, 2, 222);
    insert(A, 3, 333);
    insert(A, 4, 444);
    insert(A, 5, 555);
    insert(A, 6, 666);
    insert(A, 7, 777);
    printDictionary(A, stdout);
    v = lookup(A, 1);
    printf("key=1 "); v==UNDEF?printf("not found\n"):printf("value=%d\n", v);
    v = lookup(A, 3);
    printf("key=3 "); v==UNDEF?printf("not found\n"):printf("value=%d\n", v);
    v = lookup(A, 7);
    printf("key=7 "); v==UNDEF?printf("not found\n"):printf("value=%d\n", v);
    v = lookup(A, 8);
    printf("key=8 "); v==UNDEF?printf("not found\n"):printf("value=%d\n", v);
    printf("\n"); 

    /* insert(A, 2, 666); */ /* causes insert() duplicate keys error */
    
    delete(A, 1);
    delete(A, 3);
    delete(A, 7);
    printDictionary(A, stdout);
    
    /* delete(A, 8); */ /* causes delete() non-existent key error */
    
    printf("%s\n", isEmpty(A)?"true":"false");
    printf("%d\n", size(A));
    makeEmpty(A);
    printf("%s\n", isEmpty(A)?"true":"false");
    printDictionary(A, stdout);
    
    freeDictionary(&A);
    return(EXIT_SUCCESS);
}
Ejemplo n.º 7
0
static ObjectHandle findClassWithMeta(const char* name, ObjectHandle metaObj)
{   
    ObjectHandle newObj, nameObj, methTable;
    int size;

    newObj = globalSymbol(name);
    if (newObj == nilobj)
    {
        size = getInteger(metaObj->basicAt(sizeInClass));
        newObj = MemoryManager::Instance()->allocObject(size);
        newObj->_class = metaObj;

        /* now make name */
        nameObj = createSymbol(name);
        newObj->basicAtPut(nameInClass, nameObj);
        methTable = newDictionary(39);
        newObj->basicAtPut(methodsInClass, methTable);
        newObj->basicAtPut(sizeInClass, newInteger(size));

        /* now put in global symbols table */
        nameTableInsert(symbols, strHash(name), nameObj, newObj);
    }
    return newObj;
}
Ejemplo n.º 8
0
char * newSpeak(const char * text, const char * (*replace)[2]) {
    TNODE * dictionary;
    if (NULL == (dictionary = newDictionary(replace))) return NULL;

    unsigned int frontIndex = 0, tailIndex = 0, translationLenght = 0, maxLenght = DEFAULT_LENGHT;
    const char * match;
    char * translation = (char *) malloc(maxLenght + 1);
    translation[0] = '\0';
    for (frontIndex = 0; text[frontIndex] != '\0'; frontIndex++) {
        if (NULL != (match = findTranslation(dictionary, text + frontIndex, &tailIndex))) {
            frontIndex += tailIndex;
            translationLenght += strlen(match);
            while (translationLenght >= maxLenght) translation = reallocString(translation, maxLenght *= 2);
            strcat(translation, match);
        } else {
            if(translationLenght + 1 >= maxLenght) translation = reallocString(translation, maxLenght *= 2);
            translation[translationLenght++] = text[frontIndex];
            translation[translationLenght] = '\0';
        }        
    }

    freeDictionary(dictionary);
    return translation;
}
Ejemplo n.º 9
0
int test_newDictionary(){
	dict = newDictionary();
	return 0;
}
Ejemplo n.º 10
0
/*
    readClass reads a class method description
*/
static void readMethods(FILE* fd, bool printit)
{   
    ObjectHandle classObj, methTable, theMethod, selector;
# define LINEBUFFERSIZE 16384
    char *cp, *eoftest, lineBuffer[LINEBUFFERSIZE];
    ObjectHandle protocol;
    Parser pp;

    lineBuffer[0] = '\0';
    protocol = nilobj;
    if (ll.nextToken() != nameconst)
        sysError("missing name","following Method keyword");
    classObj = findClass(ll.strToken().c_str());
    pp.setInstanceVariables(classObj);
    if (printit)
        cp = objectRef(classObj->basicAt(nameInClass)).charPtr();

    /* now find or create a method table */
    methTable = classObj->basicAt(methodsInClass);
    if (methTable == nilobj) 
    {  /* must make */
        methTable = newDictionary(MethodTableSize);
        classObj->basicAtPut(methodsInClass, methTable);
    }

    if(ll.nextToken() == strconst) 
    {
        protocol = newStString(ll.strToken().c_str());
    }

    /* now go read the methods */
    do {
        if (lineBuffer[0] == '|')   /* get any left over text */
            strcpy(textBuffer,&lineBuffer[1]);
        else
            textBuffer[0] = '\0';
        while((eoftest = fgets(lineBuffer, LINEBUFFERSIZE, fd)) != NULL) {
            if ((lineBuffer[0] == '|') || (lineBuffer[0] == ']'))
                break;
            strcat(textBuffer, lineBuffer);
        }
        if (eoftest == NULL) {
            sysError("unexpected end of file","while reading method");
            break;
        }

        /* now we have a method */
        theMethod = newMethod();
        pp.setLexer(Lexer(textBuffer));
        if (pp.parseMessageHandler(theMethod, savetext)) {
            selector = theMethod->basicAt(messageInMethod);
            theMethod->basicAtPut(methodClassInMethod, classObj);
            theMethod->basicAtPut(protocolInMethod, protocol);
            if (printit)
                dspMethod(cp, selector->charPtr());
            nameTableInsert(methTable, selector.hash(), selector, theMethod);
        }
        else {
            /* get rid of unwanted method */
            givepause();
        }

    } while (lineBuffer[0] != ']');

}
Ejemplo n.º 11
0
int main(int argc, char* argv[]){

    if ( argc != 3 ) // argc should be 3 for correct execution
    {
        printf( "usage: %s input_filename output_filename\n", argv[0] );
    }

	//read text file into input array
	OriginalData* orig = readOriginalData(argv[1]);

	//allocate the same amount of compressed data (lets hope it is enough)
	CompressedData* compressed = newCompressedData(orig->dataLength, 8);

	//initializez the dictionary and the symbols in the dictionary
	Dictionary* dict = newDictionary(8);
	initDictionary(dict);

    printf("Compressing...\n");
	writeToCompressedData(compressed, dict->clearCode);

	MyString* S = newString();
	int codeword;
	int dictReturn;
	while(hasNextSymbol(orig)){
		appendString(S, (uint8_t) nextSymbol(orig));

		if(getCodeword(dict, S) != -1){
			;
		} else {
			//output S minus the last char 
			S->length--;
			codeword = getCodeword(dict, S);
			writeToCompressedData(compressed, codeword);
			S->length++;

			//great for debugging :
			// printf("wrote a %d bit codeword: %d\n", compressed->bitWidth, codeword);         
			// printf("Saved new word: %d    \t", dict->wordCount);
			// printString(S);
			// printf("\n");

			//add S to the dictionary
			dictReturn = addToDictionary(dict, S);

			if(dictReturn == -2){
				//for debugging :
            	// printf("--------------------------Increased Bit Width\n");

				//increase the bit width by one
				compressed->bitWidth++;
				dict->bitWidth *= 2;
			}
			if(dictReturn == -1){
				//dictionary is full, clear it and write a clearCode
				clearDictionary(dict);
				writeToCompressedData(compressed, dict->clearCode);
            	compressed->bitWidth = compressed->rootBitWidth+1;
				//step one symbol back in original data
				orig->nextSymbol--;
				orig->dataLeft++;
				//make S empty
				S->length = 0;
			}else{
				//"delete" the last character (it will still be in the data)
				S->length--;
				S->data[0] = S->data[S->length];//make S start with the "deleted" character
				S->length = 1;	//make the length of S 1, now S is the earlier last character
			}
		}
	}
	//write the last codeword
	codeword = getCodeword(dict, S);
	writeToCompressedData(compressed, codeword);

	//write EOI
	writeToCompressedData(compressed, dict->endOfInformation);

	writeCompressedDataToFile(compressed, argv[2]);  
    printf("File %s compressed succesfully to %s\n", argv[1], argv[2]);
    return 0;
}
Ejemplo n.º 12
0
int main(int argc, char* argv[]){
   Dictionary A = newDictionary();
   Dictionary B = newDictionary();
   Dictionary C = newDictionary();

   //insert() test-------------------------------------------------------
   insert(A,"1","Dan");
   insert(A,"2","brad");
   insert(A,"4","Richard");
   insert(A,"100","Matt");

   insert(B,"A","Tasha");
   insert(B,"G","Tammy");
      
   //to invoke exception
   //insert(D,"AS","rachel");
   //insert(B,"A","Tase");
   
   //size() test---------------------------------------------------------
   printf("%d\n",size(A));
   printf("%d\n",size(B));
   printf("%d\n",size(C));
   printf("\n");   
   //to invoke exception
   //printf("%d", size(D));

   //isEmpty() test------------------------------------------------------
   printf("%s\n", isEmpty(A)?"true":"false");
   printf("%s\n", isEmpty(C)?"true":"false");   
   printf("\n"); 
   //to invoke exception
   //printf("%s/n", isEmpty(D)?"true":"false");

   //lookup() test-------------------------------------------------------
   printf("%s\n",lookup(A,"1"));
   //printf("%s\n",lookup(A,"A"));
   printf("%s\n",lookup(A,"4"));
   printf("%s\n",lookup(A,"100"));
   printf("%s\n",lookup(B,"A"));
   //printf("%s\n",lookup(C,"2"));
   printf("\n");

   //makeEmpty() test----------------------------------------------------
   makeEmpty(B);
   //makeEmpty(D);
   
   //printDictionary() test----------------------------------------------
   printDictionary(stdout,A);
   printDictionary(stdout,B);
   
   //delete() test-------------------------------------------------------
   delete(A,"1");
   delete(A,"4");
   delete(A,"100");

   printDictionary(stdout,A);
   freeDictionary(&A);
   freeDictionary(&B);
   freeDictionary(&C); 
   return(EXIT_SUCCESS);
}
Ejemplo n.º 13
0
/*
 readClass reads a class method description
 */
static void readMethods(FILE *fd, boolean printit)
{
    object classObj, methTable, theMethod, selector;
# define LINEBUFFERSIZE 512
    char *cp, *eoftest, lineBuffer[LINEBUFFERSIZE];

    if (nextToken() != nameconst)
        sysError("missing name", "following Method keyword");
    classObj = findClass(tokenString);
    setInstanceVariables(classObj);
    if (printit)
        cp = charPtr(basicAt(classObj, nameInClass));

    /* now find or create a method table */
    methTable = basicAt(classObj, methodsInClass);
    if (methTable == nilobj)   /* must make */
    {
        methTable = newDictionary(MethodTableSize);
        basicAtPut(classObj, methodsInClass, methTable);
    }

    /* now go read the methods */
    do
    {
        if (lineBuffer[0] == '|') /* get any left over text */
            strcpy(textBuffer, &lineBuffer[1]);
        else
            textBuffer[0] = '\0';
        while ((eoftest = fgets(lineBuffer, LINEBUFFERSIZE, fd)) != NULL)
        {
            if ((lineBuffer[0] == '|') || (lineBuffer[0] == ']'))
                break;
            strcat(textBuffer, lineBuffer);
        }
        if (eoftest == NULL)
        {
            sysError("unexpected end of file", "while reading method");
            break;
        }

        /* now we have a method */
        theMethod = newMethod();
        if (parse(theMethod, textBuffer, savetext))
        {
            selector = basicAt(theMethod, messageInMethod);
            basicAtPut(theMethod, methodClassInMethod, classObj);
            if (printit)
                dspMethod(cp, charPtr(selector));
            nameTableInsert(methTable, (int) selector, selector, theMethod);
        }
        else
        {
            /* get rid of unwanted method */
            incr(theMethod);
            decr(theMethod);
            givepause();
        }

    }
    while (lineBuffer[0] != ']');
}