示例#1
0
char* FastASCII::readField(const char* field,
                           const char* line,
                           unsigned int index,
                           void* data)
{
    unsigned int i;
    ScreenManager *S = ScreenManager::singleton();
    CalcServer::CalcServer *C = CalcServer::CalcServer::singleton();
    Variables* vars = C->variables();
    ArrayVariable *var = (ArrayVariable*)vars->get(field);

    // Extract the variable type data
    unsigned int n = vars->typeToN(var->type());
    size_t type_size = vars->typeToBytes(var->type());
    char *type = new char[strlen(var->type()) + 1];
    strcpy(type, var->type());
    if(strchr(type, '*'))
        strcpy(strchr(type, '*'), "");

    // Point to the chunk of data to become read
    void* ptr = (void*)((char*)data + type_size * index);

    // Start reading the sub-fields
    char* pos = (char*)line;
    for(i = 0; i < n; i++){
        char* end_pos = NULL;
        // Let's use different tools depending on the type to become read
        if(!strcmp(type, "unsigned int") ||
           strstr(type, "uivec")){
            unsigned int val = (unsigned int)strtol(pos, &end_pos, 10);
            if(pos == end_pos){
                char *msg = new char[strlen(var->type()) + 64];
                S->addMessageF(3, "Failure reading a field value\n");
                sprintf(msg, "\tWhile extracting it from \"%s\"\n", pos);
                S->addMessage(0, msg);
            }
            memcpy(ptr, &val, sizeof(unsigned int));
        }
        else if(!strcmp(type, "int") ||
           strstr(type, "ivec")){
            int val = (int)strtol(pos, &end_pos, 10);
            if(pos == end_pos){
                char *msg = new char[strlen(var->type()) + 64];
                S->addMessageF(3, "Failure reading a field value\n");
                sprintf(msg, "\tWhile extracting it from \"%s\"\n", pos);
                S->addMessage(0, msg);
            }
            memcpy(ptr, &val, sizeof(int));
        }
        else{
            float val = (float)strtof(pos, &end_pos);
            if(pos == end_pos){
                char *msg = new char[strlen(var->type()) + 64];
                S->addMessageF(3, "Failure reading a field value\n");
                sprintf(msg, "\tWhile extracting it from \"%s\"\n", pos);
                S->addMessage(0, msg);
            }
            memcpy(ptr, &val, sizeof(float));
        }

        // Go to the next field, we already asserted that there are fields
        // enough, so we don't need to care about that
        ptr += type_size / n;
        pos = strchr(end_pos, ',');
        if(pos)
            pos++;
    }

    delete[] type;
    return pos;
}