コード例 #1
0
std::string stf_output_device::execute(int argc, char **argv)
{
	std::vector<std::string> argvOutput;
	STI::Utils::convertArgs(argc, argv, argvOutput);

	uInt32 time = 10000; //enough time to load events for a single line timing file
	uInt32 channel;
	bool value;
	bool convertSuccess;

	if(argvOutput.size() == 2)
	{
		// just expect a 32 bit number
		// not supported yet
		return "failed";
	}
	else if(argvOutput.size() == 3)
	{
		// expect channel, bool
		convertSuccess = stringToValue(argvOutput.at(1), channel);
		convertSuccess = stringToValue(argvOutput.at(2), value);
	}
	else
		return "failed"; // don't know what the user was trying to do

	RawEvent rawEvent(time, channel, value, 1);


	write(channel, value);
//	write(rawEvent); //runs parseDeviceEvents on rawEvent and executes a short timing sequence

	return "worked";
}
コード例 #2
0
std::string stf_da_slow_device::execute(int argc, char **argv)
{
	std::vector<std::string> argvOutput;
	STI::Utils::convertArgs(argc, argv, argvOutput);

//	uInt32 time = 10000; //enough time to load events for a single line timing file
	uInt32 channel;
	double value;
	bool convertSuccess = true;

	if(argvOutput.size() == 3)
	{
		// expect channel, value
		convertSuccess = stringToValue(argvOutput.at(1), channel);
		if(!convertSuccess)
			return "Error: Unable to convert channel argument.";

		convertSuccess &= stringToValue(argvOutput.at(2), value);
		if(!convertSuccess)
			return "Error: Unable to convert value argument.";
	}
	else
		return "Error: Invalid argument list. Expecting 'channel' and 'value'."; // don't know what the user was trying to do

//	RawEvent rawEvent(time, channel, value, 1); //time channel value eventNumber

	if(write(channel, value)) //runs parseDeviceEvents on rawEvent and executes a short timing sequence
		return "";
	else
		return "Error: Failed when attempting to write.";
}
コード例 #3
0
ファイル: hp83711bDevice.cpp プロジェクト: jasonhogan/sti
bool hp83711bDevice::readChannel(unsigned short channel, const MixedValue& valueIn, MixedData& dataOut)
{
	//
	
	bool measureSuccess;
	std::string measurementResult;

	if(channel == 0)
	{
		measurementResult = queryDevice("FREQ:CW?");
		std::cerr << measurementResult << std::endl;
		//measurementResult.erase(0,2);
		measureSuccess = stringToValue(measurementResult, frequency, std::ios::dec, 10);
		//wavelength = wavelength * 1000000000; // multiply by 10^9
		std::cerr.precision(10);
		std::cerr << "The output frequency is:" << frequency << " Hz" << std::endl;
		dataOut.setValue(frequency);
		return measureSuccess;
	}
	else if(channel == 1)
	{
		measurementResult = queryDevice("POW:LEV?");
		std::cerr << measurementResult << std::endl;
		//measurementResult.erase(0,2);
		measureSuccess = stringToValue(measurementResult, power);
		std::cerr << "The output power is: " << power << "dBm" << std::endl;
		dataOut.setValue(power);
		return measureSuccess;
	}

	std::cerr << "Expecting either Channel 0 or 1" << std::endl;
	return false;
}
コード例 #4
0
ファイル: test_expr.c プロジェクト: YizhiGu/Project
// ************************************************************
void
testValueSerialize (void)
{
    testName = "test value serialization and deserialization";
    
    ASSERT_EQUALS_STRING(serializeValue(stringToValue("i10")), "10", "create Value 10");
    ASSERT_EQUALS_STRING(serializeValue(stringToValue("f5.3")), "5.300000", "create Value 5.3");
    ASSERT_EQUALS_STRING(serializeValue(stringToValue("sHello World")), "Hello World", "create Value Hello World");
    ASSERT_EQUALS_STRING(serializeValue(stringToValue("bt")), "true", "create Value true");
    ASSERT_EQUALS_STRING(serializeValue(stringToValue("btrue")), "true", "create Value true");
    
    TEST_DONE();
}
コード例 #5
0
ファイル: mccUSBDAQDevice.cpp プロジェクト: jasonhogan/sti
std::string MccUSBDAQDevice::execute(int argc, char **argv)
{
	int channel;
	bool channelSuccess;
	int query = 0; //true (1) or false (0) if the command is expecting a response
	bool querySuccess;
	bool measureSuccess;
	double measuredValue = 0;
	bool commandSuccess;
	float commandValue;
	bool outputSuccess;
	string result;

	//command comes as "channel query(t/f)? value"
	if(argc == 3)
	{
		channelSuccess = stringToValue(argv[1], channel);
		querySuccess = stringToValue(argv[2], query);
		//std::cerr << " i got 3 values" << std::endl;
		//std::cerr << " channel is: " << channel << std::endl;
		//std::cerr << "query (tf)? " << query << std::endl;
	}
	else if(argc == 4)
	{
		channelSuccess = stringToValue(argv[1], channel);
		querySuccess = stringToValue(argv[2], query);
		commandSuccess = stringToValue(argv[3], commandValue);
	}
	else
		return "0"; //command needs to contain 2 pieces of information

	if(query == 1 && querySuccess)
	{
		// measure channel
		measureSuccess = readInputChannel(channel, measuredValue);
		//std::cerr << "measured value? " << measuredValue << std::endl;
		result = valueToString(measuredValue);
		return result;
	}
	else if(!query && querySuccess)
	{
		//command an output voltage
		outputSuccess = setOutputVoltage(channel, commandValue );
		if(outputSuccess)
			return "1";
		else
			return "0";
	}
	else
		return "0";	
}
コード例 #6
0
bool NovatechChannelPair::updateAttribute(string key, string value)
{
	double tempDouble;  //the value entered, converted to a number
	int tempInt;

	bool successDouble = stringToValue(value, tempDouble);
	bool successInt = stringToValue(value, tempInt);

	bool success = successDouble || successInt;

	if(key.compare("Frequency Ramp Rate (MHz/ms)") == 0 && successDouble)
	{
		success = true;

		if (tempDouble >= 0)
			freqRampRate = tempDouble;
		else
			success = false;
	}
	else if(key.compare("Min Ramp Resolution (MHz)") == 0 && successDouble)
	{
		success = true;

		if (tempDouble > 0)
			maxResolution = tempDouble;
		else
			success = false;
	}
	else if(key.compare("Low Freq Channel") == 0 && successInt)
	{
		success = true;

		if (tempInt >= 0 && tempInt < 4)
			lowFreqChannel = tempInt;
		else
			success = false;
	}
	else if(key.compare("High Freq Channel") == 0 && successInt)
	{
		success = true;

		if (tempInt >= 0 && tempInt < 4)
			highFreqChannel = tempInt;
		else
			success = false;
	}
	else
		success = false;

	return success;
}
コード例 #7
0
ファイル: test_expr.c プロジェクト: YizhiGu/Project
// ************************************************************
void
testExpressions (void)
{
    Expr *op, *l, *r;
    Value *res;
    testName = "test complex expressions";
    
    MAKE_CONS(l, stringToValue("i10"));
    evalExpr(NULL, NULL, l, &res);
    OP_TRUE(stringToValue("i10"), res, valueEquals, "Const 10");
    
    MAKE_CONS(r, stringToValue("i20"));
    evalExpr(NULL, NULL, r, &res);
    OP_TRUE(stringToValue("i20"), res, valueEquals, "Const 20");
    
    MAKE_BINOP_EXPR(op, l, r, OP_COMP_SMALLER);
    evalExpr(NULL, NULL, op, &res);
    OP_TRUE(stringToValue("bt"), res, valueEquals, "Const 10 < Const 20");
    
    MAKE_CONS(l, stringToValue("bt"));
    evalExpr(NULL, NULL, l, &res);
    OP_TRUE(stringToValue("bt"), res, valueEquals, "Const true");
    
    r = op;
    MAKE_BINOP_EXPR(op, r, l, OP_BOOL_AND);
    evalExpr(NULL, NULL, op, &res);
    OP_TRUE(stringToValue("bt"), res, valueEquals, "(Const 10 < Const 20) AND true");
    
    TEST_DONE();
}
コード例 #8
0
bool STF_AD_FAST::
STF_AD_FAST_Device::updateAttribute(std::string key, std::string value)
{
	unsigned tempInt;
//	bool successDouble = stringToValue(value, tempDouble);

	bool success = false;

	if(key.compare("Hold Before Measuring") == 0)
	{
		if(value.compare("True")==0) {
			holdMeasurements = true;
			success = true;
		}
		else if(value.compare("False")==0) {
			holdMeasurements = false;
			success = true;
		}
	}
	if(key.compare("Measurement delay") == 0 && stringToValue(value, tempInt))
	{
		delay_ns = tempInt;
		success = true;
	}
	if(key.compare("Channel 1 command") == 0 && stringToValue(value, tempInt))
	{
		channelCommand = tempInt;
		success = true;
	}

/*	bool success = false;

	if(key.compare("DAQ Frequency") == 0 && successDouble)
		success = setDaqFreq(tempDouble);
	else if(key.compare("Warp Mode") == 0)
	{
		success = true;

		if(value.compare("Off") == 0)
			setMode(0);
		else if(key.compare("On") == 0)
		{
			setMode(1);
		}
		else
			success = false;
	}
*/
	return success;
}
コード例 #9
0
ファイル: hp83711bDevice.cpp プロジェクト: jasonhogan/sti
std::string hp83711bDevice::execute(int argc, char** argv)
{
	//command structure:  >analogIn readChannel 1
	//returns the value as a string

	if(argc < 3)
		return "Error: Invalid argument list. Expecting 'channel'.";

	int channel;
	bool channelSuccess = stringToValue(argv[2], channel);

	if(channelSuccess && channel >=0 && channel <= 1)
	{
		MixedData data;
		bool success = readChannel(channel, 0, data);

		if(success)
		{
			cerr << "Result to transfer = " << data.getDouble() << endl;
			return valueToString( data.getDouble() );
		}
		else
			return "Error: Failed when attempting to read.";
	}

	return "Error";
}
コード例 #10
0
int GotoDialog::address()
{
	if(currentSymbol)
		return currentSymbol->value();
	else
		return stringToValue(edtAddress->text());
}
コード例 #11
0
ファイル: string_stream.cpp プロジェクト: coupdair/STL.test
int main(int argc, char *argv[])
{
//string to value
  int value=123;
  std::string str("default");
  if(argc>1)
  {//get first argument on command line
    str=argv[1];
    std::cerr<<"* command line argument from stringToValue function:"<<std::endl;
    std::cerr<<"  first command line argument (i.e. \""<<str<<"\") used."<<std::endl;
    stringToValue(str,value);
  }
  std::cout<<"value="<<value<<"\n"<<std::flush;
  std::cout<<"str =\""<<str<<"\"."<<std::endl;

//cat
  std::cerr<<"* cat string or char (i.e. + operator):"<<std::endl;
  str="basename_"+str+".ext";
  std::cout<<"str =\""<<str<<"\"."<<std::endl;

//value to string
  std::cerr<<"* valueToString function:"<<std::endl;
  str=valueToString(value);
  std::cout<<"str =\""<<str<<"\"."<<std::endl;

//value to string (fill with)
  std::cerr<<"* valueToString function:"<<std::endl;
  int zeros=5;
  if(argc==3)
  {//get second argument on command line
    str=argv[2];
    std::cerr<<"* command line argument from stringToValue function:"<<std::endl;
    std::cerr<<"  second command line argument (i.e. \""<<str<<"\") used."<<std::endl;
    stringToValue(str,zeros);
  }
  str=valueToString(value,zeros);
  std::cerr<<"output number using "<<zeros<<" character(s) filling with 0."<<std::endl;
  std::cout<<"str =\""<<str<<"\"."<<std::endl;

//cat
  std::cerr<<"* cat string or char (i.e. + operator):"<<std::endl;
  str="basename_"+valueToString(value,zeros)+".ext";
  std::cout<<"str =\""<<str<<"\"."<<std::endl;

  return 0;
}
コード例 #12
0
void ConfigEntry::setStringValue( const QString& str )
{
  m_value = stringToValue( str, DoNotUnescape );
  // When setting a string to empty (and there's no default), we need to act like resetToDefault
  // Otherwise we try e.g. "ocsp-responder:0:" and gpgconf answers:
  // "gpgconf: argument required for option ocsp-responder"
  m_dirty = true;
}
コード例 #13
0
QGpgMECryptoConfigEntry::QGpgMECryptoConfigEntry( QGpgMECryptoConfigGroup * group, const QStringList& parsedLine )
    : mGroup( group )
{
  // Format: NAME:FLAGS:LEVEL:DESCRIPTION:TYPE:ALT-TYPE:ARGNAME:DEFAULT:ARGDEF:VALUE
  assert( parsedLine.count() >= 10 ); // called checked for it already
  QStringList::const_iterator it = parsedLine.constBegin();
  mName = *it++;
  mFlags = (*it++).toInt();
  mLevel = (*it++).toInt();
  mDescription = *it++;
  bool ok;
  // we keep the real (int) arg type, since it influences the parsing (e.g. for ldap urls)
  mRealArgType = (*it++).toInt();
  mArgType = knownArgType( mRealArgType, ok );
  if ( !ok && !(*it).isEmpty() ) {
    // use ALT-TYPE
    mRealArgType = (*it).toInt();
    mArgType = knownArgType( mRealArgType, ok );
  }
  if ( !ok )
    kWarning(5150) <<"Unsupported datatype:" << parsedLine[4] <<" :" << *it <<" for" << parsedLine[0];
  ++it; // done with alt-type
  ++it; // skip argname (not useful in GUIs)

  mSet = false;
  QString value;
  if ( mFlags & GPGCONF_FLAG_DEFAULT ) {
    value = *it; // get default value
    mDefaultValue = stringToValue( value, true );
  }
  ++it; // done with DEFAULT
  ++it; // ### skip ARGDEF for now. It's only for options with an "optional arg"
  //kDebug(5150) <<"Entry" << parsedLine[0] <<" val=" << *it;

  if ( !(*it).isEmpty() ) {  // a real value was set
    mSet = true;
    value = *it;
    mValue = stringToValue( value, true );
  }
  else {
    mValue = mDefaultValue;
  }

  mDirty = false;
}
コード例 #14
0
void Novatech409B::parseQUE(std::string queOutput)
{
	std::string chInfo;

	size_t locBegin = 0;
	size_t locEnd = 0;

	FrequencyChannel tempFC;
	int tempVal;

	for (int i = 0; i < 4; i++)
	{
		locBegin = queOutput.find_first_of('\n', locEnd);
		if (locBegin == std::string::npos)
			return;

		locEnd = queOutput.find_first_of('\n',locBegin+1);
		if (locEnd == std::string::npos)
			return;

		//return if the substring isn't be long enough to contain the required information
		if (locEnd - locBegin < 20)
			return;

		chInfo.assign(queOutput.begin()+ locBegin + 1, queOutput.begin()+locEnd-1);
		//std::cerr << chInfo << std::endl;

		//Get the frequency (which comes in units of 0.1 Hz (so 1 Hz is written as 10 in decimal)
		stringToValue(chInfo.substr(0,8),tempVal,ios::hex);
		tempFC.frequency = static_cast<double>(tempVal)/10/1000000;  //write frequency in MHz

		//Get the phase
		stringToValue(chInfo.substr(9,4),tempVal,ios::hex);
		tempFC.phase = (static_cast<double>(tempVal) / static_cast<double>(phaseMaxVal)) * 360.0;

		//Get the amplitude
		stringToValue(chInfo.substr(14,4),tempVal,ios::hex);
		tempFC.amplitude = ( static_cast<double>(tempVal) / static_cast<double>(amplitudeMaxVal) ) * 100;

		frequencyChannels.push_back(tempFC);
	}

	return;
}
コード例 #15
0
ファイル: mccUSBDAQDevice.cpp プロジェクト: jasonhogan/sti
bool MccUSBDAQDevice::updateAttribute(string key, string value)
{
	double tempDouble;  //the value entered, converted to a number
	int tempInt;

	bool successDouble = stringToValue(value, tempDouble);
	bool successInt = stringToValue(value, tempInt);

	bool success = successDouble || successInt;

	//Doesn't actually do anything; this device monitors only

	if(key.compare("AD In gain") == 0)
	{
		success = true;
		std::map <int, std::string>::iterator it;
		for (it = availableADInRanges.begin(); it != availableADInRanges.end(); it++)
		{
			if (it->second.compare(value) == 0)
				break;
		}

		if (it == availableADInRanges.end())
			success = false;
		else
			ADInRange = it->first;
	}
	else if(key.compare("DA Out gain") == 0)
	{
		success = true;
		std::map <int, std::string>::iterator it;
		for (it = availableDAOutRanges.begin(); it != availableDAOutRanges.end(); it++)
		{
			if (it->second.compare(value) == 0)
				break;
		}

		if (it == availableDAOutRanges.end())
			success = false;
		else
			DAOutRange = it->first;
	}
	return success;
}
コード例 #16
0
void QGpgMECryptoConfigEntry::setStringValue( const QString& str )
{
  mValue = stringToValue( str, false );
  // When setting a string to empty (and there's no default), we need to act like resetToDefault
  // Otherwise we try e.g. "ocsp-responder:0:" and gpgconf answers:
  // "gpgconf: argument required for option ocsp-responder"
  if ( str.isEmpty() && !isOptional() )
    mSet = false;
  else
    mSet = true;
  mDirty = true;
}
コード例 #17
0
void GotoDialog::addressChanged(const QString& text)
{
	int addr = stringToValue(text);
	if (addr == -1 && debugSession) {
		// try finding a label
		currentSymbol = debugSession->symbolTable().getAddressSymbol(text);
		if (!currentSymbol) currentSymbol = debugSession->symbolTable().getAddressSymbol(text, Qt::CaseInsensitive);
		if (currentSymbol) addr = currentSymbol->value();
	}

	QPalette pal;
	pal.setColor(QPalette::Text, addr==-1 ? Qt::red : Qt::black);
	edtAddress->setPalette(pal);
}
コード例 #18
0
void
testRecords (void)
{
  TestRecord expected[] = { 
    {1, "aaaa", 3}, 
  };
  Schema *schema;
  Record *r;
  Value *value;
  testName = "test creating records and manipulating attributes";

  // check attributes of created record
  schema = testSchema();
  r = fromTestRecord(schema, expected[0]);

    getAttr(r, schema, 0, &value);
  printf("\n Value is %d",value->v.intV);
   OP_TRUE(stringToValue("i1"), value, valueEquals, "first attr");
  freeVal(value);

  getAttr(r, schema, 1, &value);
  OP_TRUE(stringToValue("saaaa"), value, valueEquals, "second attr");
  freeVal(value);

  getAttr(r, schema, 2, &value);
  OP_TRUE(stringToValue("i3"), value, valueEquals, "third attr");
  freeVal(value);

  //modify attrs
  setAttr(r, schema, 2, stringToValue("i4"));
  getAttr(r, schema, 2, &value);
  OP_TRUE(stringToValue("i4"), value, valueEquals, "third attr after setting");
  freeVal(value);

  freeRecord(r);
  TEST_DONE();
}
コード例 #19
0
std::string STF_AD_FAST::STF_AD_FAST_Device::execute(int argc, char **argv)
{

	//command structure:  >analogIn readChannel 1
	//returns the value as a string

	if(argc < 3)
		return "Error: Invalid argument list. Expecting 'channel'.";

	int channel;
	bool channelSuccess = stringToValue(argv[2], channel);

	if(channelSuccess && channel >= 0 && channel <= 1)
	{
		//RawEvent rawEvent(10000, channel, 0);	//time = 1, event number = 0

	//	DataMeasurement measurement(10000, channel, 0);

	//	writeChannel(rawEvent); //runs parseDeviceEvents on rawEvent and executes a short timing sequence

		MixedData data;
		bool success = read(channel, 0, data);
//		makeMeasurement( measurement );


		//DataMeasurementVector& results = getMeasurements();

//		waitForEvent(0)

//int x=0;
//while(x != 3)
//{		
//cerr << "Waiting to send..." << endl;
//cin >> x;
//}


		if(success)
		{
			cerr << "Result to transfer = " << data.getDouble() << endl;
			return valueToString( data.getDouble() );
		}
		else
			return "Error: Failed when attempting to read.";
	}

	return "Error";
}
コード例 #20
0
void
testMultipleScans(void)
{
  RM_TableData *table = (RM_TableData *) malloc(sizeof(RM_TableData));
  TestRecord inserts[] = { 
    {1, "aaaa", 3}, 
    {2, "bbbb", 2},
    {3, "cccc", 1},
    {4, "dddd", 3},
    {5, "eeee", 5},
    {6, "ffff", 1},
    {7, "gggg", 3},
    {8, "hhhh", 3},
    {9, "iiii", 2},
    {10, "jjjj", 5},
  };
  int numInserts = 10, i, scanOne=0, scanTwo=0;
  Record *r;
  RID *rids;
  Schema *schema;
  testName = "test running muliple scans ";
  schema = testSchema();
  rids = (RID *) malloc(sizeof(RID) * numInserts);
  RM_ScanHandle *sc1 = (RM_ScanHandle *) malloc(sizeof(RM_ScanHandle));
  RM_ScanHandle *sc2 = (RM_ScanHandle *) malloc(sizeof(RM_ScanHandle));
  Expr *se1, *left, *right;
  int rc,rc2;
  
  TEST_CHECK(initRecordManager(NULL));
  TEST_CHECK(createTable("test_table_r",schema));
  TEST_CHECK(openTable(table, "test_table_r"));
  
  // insert rows into table
  for(i = 0; i < numInserts; i++)
  {
      r = fromTestRecord(schema, inserts[i]);
      TEST_CHECK(insertRecord(table,r)); 
      rids[i] = r->id;
  }

  // Mix 2 scans with c=3 as condition
  MAKE_CONS(left, stringToValue("i3"));
  MAKE_ATTRREF(right, 2);
  MAKE_BINOP_EXPR(se1, left, right, OP_COMP_EQUAL);
  createRecord(&r, schema);
  TEST_CHECK(startScan(table, sc1, se1));
  TEST_CHECK(startScan(table, sc2, se1));
  if ((rc2 = next(sc2, r)) == RC_OK)
    scanTwo++;
  i = 0;
  while((rc = next(sc1, r)) == RC_OK)
  {
      scanOne++;
      i++;
      if (i % 3 == 0)
          if ((rc2 = next(sc2, r)) == RC_OK)
              scanTwo++;
  }
  while((rc2 = next(sc2, r)) == RC_OK)
    scanTwo++;

  ASSERT_TRUE(scanOne == scanTwo, "scans returned same number of tuples");
  if (rc != RC_NO_TUPLES)
    TEST_CHECK(rc);
  TEST_CHECK(closeScan(sc1));
  TEST_CHECK(closeScan(sc2));
 
  TEST_CHECK(closeTable(table));
  TEST_CHECK(deleteTable("test_table_r"));
  TEST_CHECK(shutdownRecordManager());

  free(rids);
  free(table);
  TEST_DONE();
}
コード例 #21
0
ファイル: test_expr.c プロジェクト: YizhiGu/Project
// ************************************************************
void
testOperators (void)
{
    Value *result;
    testName = "test value comparison and boolean operators";
    MAKE_VALUE(result, DT_INT, 0);
    
    // equality
    OP_TRUE(stringToValue("i10"),stringToValue("i10"), valueEquals, "10 = 10");
    OP_FALSE(stringToValue("i9"),stringToValue("i10"), valueEquals, "9 != 10");
    OP_TRUE(stringToValue("sHello World"),stringToValue("sHello World"), valueEquals, "Hello World = Hello World");
    OP_FALSE(stringToValue("sHello Worl"),stringToValue("sHello World"), valueEquals, "Hello Worl != Hello World");
    OP_FALSE(stringToValue("sHello Worl"),stringToValue("sHello Wor"), valueEquals, "Hello Worl != Hello Wor");
    
    // smaller
    OP_TRUE(stringToValue("i3"),stringToValue("i10"), valueSmaller, "3 < 10");
    OP_TRUE(stringToValue("f5.0"),stringToValue("f6.5"), valueSmaller, "5.0 < 6.5");
    
    // boolean
    OP_TRUE(stringToValue("bt"),stringToValue("bt"), boolAnd, "t AND t = t");
    OP_FALSE(stringToValue("bt"),stringToValue("bf"), boolAnd, "t AND f = f");
    
    OP_TRUE(stringToValue("bt"),stringToValue("bf"), boolOr, "t OR f = t");
    OP_FALSE(stringToValue("bf"),stringToValue("bf"), boolOr, "f OR f = f");
    
    TEST_CHECK(boolNot(stringToValue("bf"), result));
    ASSERT_TRUE(result->v.boolV, "!f = t");
    
    TEST_DONE();
}
コード例 #22
0
ファイル: dit_access_utils.c プロジェクト: bahamas10/openzfs
/*
 * Convert the datum to an array of RuleValues
 */
__nis_rule_value_t *
datumToRuleValue(datum *key, datum *value, __nis_table_mapping_t *t,
			int *nv, char *domain, bool_t readonly, int *statP) {

	__nis_rule_value_t	*rvq, *subrvq, *newrvq;
	__nis_value_t		*val;
	__nis_value_t		**valA;
	__nis_table_mapping_t	*sf;
	int			valueLen, comLen, numVals, nr, count = 1;
	int			i, j, k, l;
	char			*ipaddr, *ipvalue;

	/*  At this point, 't' is always non NULL */

	/* Initialize rule-value */
	if ((rvq = initRuleValue(1, 0)) == 0) {
		*statP = MAP_INTERNAL_ERROR;
		return (0);
	}

	/* Add domainname to rule-value */
	if (addCol2RuleValue(vt_string, N2LDOMAIN, domain, strlen(domain),
						rvq)) {
		freeRuleValue(rvq, 1);
		*statP = MAP_INTERNAL_ERROR;
		return (0);
	}

	/* Handle key */
	if (key != 0) {
		/* Add field=value pair for N2LKEY */
		i = addCol2RuleValue(vt_string, N2LKEY, key->dptr, key->dsize,
						rvq);

		/* For readonly, add field=value pair for N2LSEARCHKEY */
		if (readonly == TRUE && i == 0) {
			i = addCol2RuleValue(vt_string, N2LSEARCHKEY, key->dptr,
						key->dsize, rvq);
		}
		if (i) {
			freeRuleValue(rvq, 1);
			*statP = MAP_INTERNAL_ERROR;
			return (0);
		}

		/* Add field=value pairs for IP addresses */
		if (checkIPaddress(key->dptr, key->dsize, &ipaddr) > 0) {
			/* If key is IPaddress, use preferred format */
			ipvalue = ipaddr;
			valueLen = strlen(ipaddr);
			i = addCol2RuleValue(vt_string, N2LIPKEY, ipvalue,
						valueLen, rvq);
		} else {
			/* If not, use original value for N2LSEARCHIPKEY */
			ipaddr = 0;
			ipvalue = key->dptr;
			valueLen = key->dsize;
			i = 0;
		}

		if (readonly == TRUE && i == 0) {
			i = addCol2RuleValue(vt_string, N2LSEARCHIPKEY, ipvalue,
								valueLen, rvq);
		}
		sfree(ipaddr);
		if (i) {
			freeRuleValue(rvq, 1);
			*statP = MAP_INTERNAL_ERROR;
			return (0);
		}
	}

	/* Handle datum value */
	if (value != 0 && t->e) {
		valueLen = value->dsize;
		/*
		 * Extract the comment, if any, and add it to
		 * the rule-value.
		 */
		if (t->commentChar != '\0') {
			/*
			 * We loop on value->dsize because value->dptr
			 * may not be NULL-terminated.
			 */
			for (i = 0; i < value->dsize; i++) {
				if (value->dptr[i] == t->commentChar) {
					valueLen = i;
					comLen = value->dsize - i - 1;
					if (comLen == 0)
						break;
					if (addCol2RuleValue(vt_string,
						N2LCOMMENT, value->dptr + i + 1,
						comLen, rvq)) {
						freeRuleValue(rvq, 1);
						*statP = MAP_INTERNAL_ERROR;
						return (0);
					}
					break;
				}
			}
		}

		/* Skip trailing whitespaces */
		for (; valueLen > 0 && (value->dptr[valueLen - 1] == ' ' ||
			value->dptr[valueLen - 1] == '\t'); valueLen--);

		/*
		 * At this point valueLen is the effective length of
		 * the data. Convert value into __nis_value_t so that
		 * we can use the matchMappingItem function to break it
		 * into fields.
		 */
		if ((val = stringToValue(value->dptr, valueLen)) == 0) {
			freeRuleValue(rvq, 1);
			*statP = MAP_NO_MEMORY;
			return (0);
		}

		/* Perform namefield match */
		valA = matchMappingItem(t->e->element.match.fmt, val,
							&numVals, 0, 0);
		if (valA == 0) {
			freeValue(val, 1);
			freeRuleValue(rvq, 1);
			*statP = MAP_NAMEFIELD_MATCH_ERROR;
			return (0);
		}

		/* We don't need val anymore, so free it */
		freeValue(val, 1);

		/*
		 * Since matchMappingItem only returns us an array of
		 * __nis_value_t's, we need to associate each value
		 * in the array with the corresponding item name.
		 * This code assumes that numVals will be less than or
		 * equal to the number of item names associated with
		 * the format.
		 * These name=value pairs are added to rvq.
		 */
		for (i = 0, *statP = SUCCESS; i < numVals; i++) {
			for (j = 0; j < count; j++) {
				if (addCol2RuleValue(vt_string,
					t->e->element.match.item[i].name,
					valA[i]->val->value,
					valA[i]->val->length, &rvq[j])) {
					*statP = MAP_INTERNAL_ERROR;
					break;
				}
			}
			if (*statP == MAP_INTERNAL_ERROR)
				break;

			/*
			 * Check if splitField exists for the field.
			 * Since splitfields are also stored as mapping
			 * structures, we need to get the hash table entry
			 * corresponding to the splitfield name
			 */
			sf = mappingFromMap(t->e->element.match.item[i].name,
					domain, statP);
			if (*statP == MAP_NO_MEMORY)
				break;
			*statP = SUCCESS;
			if (sf == 0)
				continue;

			/*
			 * Process and add splitFields to rule-value rvq
			 */
			subrvq = processSplitField(sf, valA[i], &nr, statP);

			if (subrvq == 0) {
				/* statP would have been set */
				break;
			}

			/*
			 * We merge 'count' rule-values in rvq with 'nr'
			 * rule-values from subrvq to give us a whopping
			 * 'count * nr' rule-values
			 */

			/* Initialize the new rule-value array */
			if ((newrvq = initRuleValue(count * nr, 0)) == 0) {
				*statP = MAP_INTERNAL_ERROR;
				freeRuleValue(subrvq, nr);
				break;
			}

			for (j = 0, l = 0; j < nr; j++) {
				for (k = 0; k < count; k++, l++) {
					if ((mergeRuleValue(&newrvq[l],
							&rvq[k]) == -1) ||
							(mergeRuleValue(
							&newrvq[l],
							&subrvq[j]) == -1)) {
						*statP = MAP_INTERNAL_ERROR;
						for (i = 0; i < numVals; i++)
							freeValue(valA[i], 1);
						sfree(valA);
						freeRuleValue(rvq, count);
						freeRuleValue(newrvq,
								count * nr);
						freeRuleValue(subrvq, nr);
						return (0);
					}
				}
			}

			freeRuleValue(rvq, count);
			rvq = newrvq;
			count = l;
			freeRuleValue(subrvq, nr);

		}

		/* We don't need valA anymore, so free it */
		for (i = 0; i < numVals; i++)
			freeValue(valA[i], 1);
		sfree(valA);

		if (*statP != SUCCESS) {
			freeRuleValue(rvq, count);
			return (0);
		}

	} /* if value */

	if (nv != 0)
		*nv = count;
	return (rvq);

}
コード例 #23
0
ファイル: abstractexpression.cpp プロジェクト: TeaTips/voltdb
AbstractExpression*
AbstractExpression::buildExpressionTree_recurse(json_spirit::Object &obj)
{
    // build a tree recursively from the bottom upwards.
    // when the expression node is instantiated, its type,
    // value and child types will have been discovered.

    ExpressionType peek_type = EXPRESSION_TYPE_INVALID;
    ValueType value_type = VALUE_TYPE_INVALID;
    AbstractExpression *left_child = NULL;
    AbstractExpression *right_child = NULL;
    std::vector<AbstractExpression*>* argsVector = NULL;

    // read the expression type
    json_spirit::Value expressionTypeValue = json_spirit::find_value(obj,
                                                                     "TYPE");
    if (expressionTypeValue == json_spirit::Value::null) {
        throw SerializableEEException(VOLT_EE_EXCEPTION_TYPE_EEEXCEPTION,
                                      "AbstractExpression::"
                                      "buildExpressionTree_recurse:"
                                      " Couldn't find TYPE value");
    }
    assert(stringToExpression(expressionTypeValue.get_str()) != EXPRESSION_TYPE_INVALID);
    peek_type = stringToExpression(expressionTypeValue.get_str());

    // and the value type
    json_spirit::Value valueTypeValue = json_spirit::find_value(obj,
                                                                "VALUE_TYPE");
    if (valueTypeValue == json_spirit::Value::null) {
        throw SerializableEEException(VOLT_EE_EXCEPTION_TYPE_EEEXCEPTION,
                                      "AbstractExpression::"
                                      "buildExpressionTree_recurse:"
                                      " Couldn't find VALUE_TYPE value");
    }
    std::string valueTypeString = valueTypeValue.get_str();
    value_type = stringToValue(valueTypeString);

    assert(value_type != VALUE_TYPE_INVALID);

    // add the value size
    json_spirit::Value valueSizeValue = json_spirit::find_value(obj,
                                                                "VALUE_SIZE");
    if (valueSizeValue == json_spirit::Value::null) {
        throw SerializableEEException(VOLT_EE_EXCEPTION_TYPE_EEEXCEPTION,
                                      "AbstractExpression::"
                                      "buildExpressionTree_recurse:"
                                      " Couldn't find VALUE_SIZE value");
    }
    int valueSize = valueSizeValue.get_int();

    // recurse to children
    try {
        json_spirit::Value leftValue = json_spirit::find_value(obj, "LEFT");
        if (!(leftValue == json_spirit::Value::null)) {
            left_child = AbstractExpression::buildExpressionTree_recurse(leftValue.get_obj());
        }

        json_spirit::Value rightValue = json_spirit::find_value( obj, "RIGHT");
        if (!(rightValue == json_spirit::Value::null)) {
            right_child = AbstractExpression::buildExpressionTree_recurse(rightValue.get_obj());
        }

        // NULL argsVector corresponds to a missing ARGS value
        // vs. an empty argsVector which corresponds to an empty array ARGS value.
        // Different expression types could assert either a NULL or non-NULL argsVector initializer.
        json_spirit::Value argsValue = json_spirit::find_value(obj, "ARGS");
        if (!(argsValue == json_spirit::Value::null)) {
            argsVector = new std::vector<AbstractExpression*>();

            json_spirit::Array argsArray = argsValue.get_array();
            for (int ii = 0; ii < argsArray.size(); ii++) {
                json_spirit::Value argValue = argsArray[ii];
                AbstractExpression* argExpr = AbstractExpression::buildExpressionTree_recurse(argValue.get_obj());
                argsVector->push_back(argExpr);
            }
        }
        // invoke the factory. obviously it has to handle null children.
        // pass it the serialization stream in case a subclass has more
        // to read. yes, the per-class data really does follow the
        // child serializations.
        return ExpressionUtil::expressionFactory(obj, peek_type, value_type, valueSize,
                                                 left_child, right_child, argsVector);
    }
    catch (const SerializableEEException &ex) {
        delete left_child;
        delete right_child;
        delete argsVector;
        throw;
    }
}
コード例 #24
0
AbstractExpression*
AbstractExpression::buildExpressionTree_recurse(json_spirit::Object &obj)
{
    // build a tree recursively from the bottom upwards.
    // when the expression node is instantiated, its type,
    // value and child types will have been discovered.

    ExpressionType peek_type = EXPRESSION_TYPE_INVALID;
    ValueType value_type = VALUE_TYPE_INVALID;
    AbstractExpression *left_child = NULL;
    AbstractExpression *right_child = NULL;

    // read the expression type
    json_spirit::Value expressionTypeValue = json_spirit::find_value(obj,
                                                                     "TYPE");
    if (expressionTypeValue == json_spirit::Value::null) {
        throw SerializableEEException(VOLT_EE_EXCEPTION_TYPE_EEEXCEPTION,
                                      "AbstractExpression::"
                                      "buildExpressionTree_recurse:"
                                      " Couldn't find TYPE value");
    }
    assert(stringToExpression(expressionTypeValue.get_str()) != EXPRESSION_TYPE_INVALID);
    peek_type = stringToExpression(expressionTypeValue.get_str());

    // and the value type
    json_spirit::Value valueTypeValue = json_spirit::find_value(obj,
                                                                "VALUE_TYPE");
    if (valueTypeValue == json_spirit::Value::null) {
        throw SerializableEEException(VOLT_EE_EXCEPTION_TYPE_EEEXCEPTION,
                                      "AbstractExpression::"
                                      "buildExpressionTree_recurse:"
                                      " Couldn't find VALUE_TYPE value");
    }
    std::string valueTypeString = valueTypeValue.get_str();
    value_type = stringToValue(valueTypeString);

    // this should be relatively safe, though it ignores overflow.
    if ((value_type == VALUE_TYPE_TINYINT)  ||
        (value_type == VALUE_TYPE_SMALLINT) ||
        (value_type == VALUE_TYPE_INTEGER))
    {
        value_type = VALUE_TYPE_BIGINT;
    }

    assert(value_type != VALUE_TYPE_INVALID);

    // add the value size
    json_spirit::Value valueSizeValue = json_spirit::find_value(obj,
                                                                "VALUE_SIZE");
    if (valueSizeValue == json_spirit::Value::null) {
        throw SerializableEEException(VOLT_EE_EXCEPTION_TYPE_EEEXCEPTION,
                                      "AbstractExpression::"
                                      "buildExpressionTree_recurse:"
                                      " Couldn't find VALUE_SIZE value");
    }
    int valueSize = valueSizeValue.get_int();

    // recurse to children
    try {
        json_spirit::Value leftValue = json_spirit::find_value(obj, "LEFT");
        if (!(leftValue == json_spirit::Value::null)) {
            left_child = AbstractExpression::buildExpressionTree_recurse(leftValue.get_obj());
        } else {
            left_child = NULL;
        }

        json_spirit::Value rightValue = json_spirit::find_value( obj, "RIGHT");
        if (!(rightValue == json_spirit::Value::null)) {
            right_child = AbstractExpression::buildExpressionTree_recurse(rightValue.get_obj());
        } else {
            right_child = NULL;
        }

        // invoke the factory. obviously it has to handle null children.
        // pass it the serialization stream in case a subclass has more
        // to read. yes, the per-class data really does follow the
        // child serializations.
        return expressionFactory(obj,
                                 peek_type, value_type, valueSize,
                                 left_child, right_child);
    }
    catch (SerializableEEException &ex) {
        delete left_child;
        delete right_child;
        throw;
    }
}
コード例 #25
0
double CEditListNumericEditor::getDoubleValue() {
  return stringToValue(getWindowText(this));
}
コード例 #26
0
void ConfigEntry::setValueFromUiString( const QString& raw )
{
    m_value = stringToValue( raw, DoNotUnescape );
}
コード例 #27
0
void testScans (void)
{
  RM_TableData *table = (RM_TableData *) malloc(sizeof(RM_TableData));
  TestRecord inserts[] = { 
    {1, "aaaa", 3}, 
    {2, "bbbb", 2},
    {3, "cccc", 1},
    {4, "dddd", 3},
    {5, "eeee", 5},
    {6, "ffff", 1},
    {7, "gggg", 3},
    {8, "hhhh", 3},
    {9, "iiii", 2},
    {10, "jjjj", 5},
  };
  TestRecord scanOneResult[] = { 
    {3, "cccc", 1},
    {6, "ffff", 1},
  };
  bool foundScan[] = {
    FALSE,
    FALSE
  };
  int numInserts = 10, scanSizeOne = 2, i;
  Record *r;
  RID *rids;
  Schema *schema;
  RM_ScanHandle *sc = (RM_ScanHandle *) malloc(sizeof(RM_ScanHandle));
  Expr *sel, *left, *right;
  int rc;

  testName = "test creating a new table and inserting tuples";
  schema = testSchema();
  rids = (RID *) malloc(sizeof(RID) * numInserts);
  
  TEST_CHECK(initRecordManager(NULL));
  TEST_CHECK(createTable("test_table_r",schema));
  TEST_CHECK(openTable(table, "test_table_r"));
  
  // insert rows into table
  for(i = 0; i < numInserts; i++)
  {
      r = fromTestRecord(schema, inserts[i]);
      TEST_CHECK(insertRecord(table,r)); 
      rids[i] = r->id;
  }

  TEST_CHECK(closeTable(table));
  TEST_CHECK(openTable(table, "test_table_r"));

  // run some scans
  MAKE_CONS(left, stringToValue("i1"));
  MAKE_ATTRREF(right, 2);
  MAKE_BINOP_EXPR(sel, left, right, OP_COMP_EQUAL);

  TEST_CHECK(startScan(table, sc, sel));
  while((rc = next(sc, r)) == RC_OK)
  {
      for(i = 0; i < scanSizeOne; i++)
      {
          if (memcmp(fromTestRecord(schema, scanOneResult[i])->data,r->data,getRecordSize(schema)) == 0)
              foundScan[i] = TRUE;
      }
  }
  if (rc != RC_NO_TUPLES)
    TEST_CHECK(rc);
  TEST_CHECK(closeScan(sc));
  for(i = 0; i < scanSizeOne; i++)
    ASSERT_TRUE(foundScan[i], "check for scan result");
  
  // clean up
  TEST_CHECK(closeTable(table));
  TEST_CHECK(deleteTable("test_table_r"));
  TEST_CHECK(shutdownRecordManager());

  free(table);
  free(sc);
  freeExpr(sel);
  TEST_DONE();
}
コード例 #28
0
bool Novatech409B::updateAttribute(string key, string value)
{
	double tempDouble;  //the value entered, converted to a number
	int tempInt;

	bool successDouble = stringToValue(value, tempDouble);
	bool successInt = stringToValue(value, tempInt);

	bool success = successDouble || successInt;

	if(key.compare("Kp Value") == 0 && successInt)
	{
		success = true;
		int extraTerm;
		int writeValue;

		double referenceFrequency;

		if (referenceIsInternal)
			referenceFrequency = 28.6331153067;
		else
			referenceFrequency = externalRefFreq;

		writeValue = tempInt;

		if (!referenceIsInternal && (100 <= tempInt*referenceFrequency && tempInt*referenceFrequency <= 160) || (255 <= tempInt*referenceFrequency && tempInt*referenceFrequency <= 500))
		{
			if(100 < tempInt*referenceFrequency && tempInt*referenceFrequency <160)
			{
				extraTerm = 64;
			}
			else if(255 < tempInt*referenceFrequency && tempInt*referenceFrequency <500)
			{
				extraTerm = 128;
			}
			writeValue += extraTerm;
		}
		else
		{
			std::cerr << "Warning: Kp is out of range w.r.t the external clock. Kp" << std::endl;
		}

/*
		if((tempInt == 1||(3 < tempInt && tempInt <10)||tempInt == 15)&&
			((100 < tempInt*referenceFrequency && tempInt*referenceFrequency < 160 || (255 < tempInt*referenceFrequency && tempInt*referenceFrequency <500)))
		{
			//frequencyString = "f" + valueToString(channel) + " " + valueToString(frequency, "", ios::dec, 10);
			//string firstDigit;
			//if (tempInt > 15)
			//	firstDigit = "";
			//else 
			//	firstDigit = "0";

			//std::string KpString = "Kp " + firstDigit + valueToString(tempInt, "", ios::hex);

			int extraTerm;
			int writeValue;
			
			if(tempInt == 1||(3 < tempInt && tempInt <10))
			{
				if(100 < tempInt*referenceFrequency && tempInt*referenceFrequency <160)
				{
					extraTerm = 64;
				}
				else if(255 < tempInt*referenceFrequency && tempInt*referenceFrequency <500)
				{
					extraTerm = 128;
				}
				writeValue = tempInt + extraTerm;
			}

			if(tempInt == 15)
			{
				if(100 < tempInt*referenceFrequency && tempInt*referenceFrequency <160)
				{
					writeValue = 85;
				}
				else if(255 < tempInt*referenceFrequency && tempInt*referenceFrequency <500)
				{
					writeValue = 149;
				}
			}
*/


		std::string KpString = "Kp " + valueToString(writeValue, "", ios::hex);
		std::string queryResult = serialController->queryDevice(KpString, 50, 30);
		if (queryResult.find("OK") == std::string::npos)
		{
			std::cerr << "Unable to set Kp of " << this->getDeviceName() << std::endl;
			success = false;
		}
		if(success)
		{
			KpValue = tempInt;
		}

	}
	else if (key.compare("External Reference Frequency (MHz)") == 0 && successDouble)
	{
		externalRefFreq = tempDouble;
		success = true;
		
	}
	else if (key.compare("Reference Source") == 0)
	{
		success = true;

		std::string commandString;
		if (value.compare("Internal")==0)
			commandString = "C i";
		else if (value.compare("External")==0)
			commandString = "C e";
		else
			return false;

		std::string queryResult = serialController->queryDevice(commandString, 50, 30);
		if (queryResult.find("OK") == std::string::npos)
		{
			std::cerr << "Unable to set reference source of " << this->getDeviceName() << std::endl;
			success = false;
		}
		if(success)
		{
			if (value.compare("Internal")==0)
				referenceIsInternal = true;
			else if (value.compare("External")==0)
				referenceIsInternal = false;
			
		}
		
	}
	else
	{
		success = false;
	}

	return success;
}
コード例 #29
0
void testScansTwo (void)
{
  RM_TableData *table = (RM_TableData *) malloc(sizeof(RM_TableData));
  TestRecord inserts[] = { 
    {1, "aaaa", 3}, 
    {2, "bbbb", 2},
    {3, "cccc", 1},
    {4, "dddd", 3},
    {5, "eeee", 5},
    {6, "ffff", 1},
    {7, "gggg", 3},
    {8, "hhhh", 3},
    {9, "iiii", 2},
    {10, "jjjj", 5},
  };
  bool foundScan[] = {
    FALSE,
    FALSE,
    FALSE,
    FALSE,
    FALSE,
    FALSE,
    FALSE,
    FALSE,
    FALSE,
    FALSE
  };
  int numInserts = 10, i;
  Record *r;
  RID *rids;
  Schema *schema;
  RM_ScanHandle *sc = (RM_ScanHandle *) malloc(sizeof(RM_ScanHandle));
  Expr *sel, *left, *right, *first, *se;
  int rc;

  testName = "test creating a new table and inserting tuples";
  schema = testSchema();
  rids = (RID *) malloc(sizeof(RID) * numInserts);
  
  TEST_CHECK(initRecordManager(NULL));
  TEST_CHECK(createTable("test_table_r",schema));
  TEST_CHECK(openTable(table, "test_table_r"));
  
  // insert rows into table
  for(i = 0; i < numInserts; i++)
  {
    r = fromTestRecord(schema, inserts[i]);
    TEST_CHECK(insertRecord(table,r)); 
    rids[i] = r->id;
  }

  TEST_CHECK(closeTable(table));
  TEST_CHECK(openTable(table, "test_table_r"));

  // Select 1 record with INT in condition a=2.
  MAKE_CONS(left, stringToValue("i2"));
  MAKE_ATTRREF(right, 0);
  MAKE_BINOP_EXPR(sel, left, right, OP_COMP_EQUAL);
  createRecord(&r, schema);
  TEST_CHECK(startScan(table, sc, sel));
  while((rc = next(sc, r)) == RC_OK)
  {
     ASSERT_EQUALS_RECORDS(fromTestRecord(schema, inserts[1]), r, schema, "compare records");
  }
  if (rc != RC_NO_TUPLES)
    TEST_CHECK(rc);
  TEST_CHECK(closeScan(sc));
  
  // Select 1 record with STRING in condition b='ffff'.
  MAKE_CONS(left, stringToValue("sffff"));
  MAKE_ATTRREF(right, 1);
  MAKE_BINOP_EXPR(sel, left, right, OP_COMP_EQUAL);
  createRecord(&r, schema);
  TEST_CHECK(startScan(table, sc, sel));
  while((rc = next(sc, r)) == RC_OK)
  {
     ASSERT_EQUALS_RECORDS(fromTestRecord(schema, inserts[5]), r, schema, "compare records");
     serializeRecord(r, schema);
  }
  if (rc != RC_NO_TUPLES)
    TEST_CHECK(rc);
  TEST_CHECK(closeScan(sc));
  
  // Select all records, with condition being false
  MAKE_CONS(left, stringToValue("i4"));
  MAKE_ATTRREF(right, 2);
  MAKE_BINOP_EXPR(first, right, left, OP_COMP_SMALLER);
  MAKE_UNOP_EXPR(se, first, OP_BOOL_NOT);
  TEST_CHECK(startScan(table, sc, se));
    while((rc = next(sc, r)) == RC_OK)
    {
     serializeRecord(r, schema);
     for(i = 0; i < numInserts; i++)
     {
       if (memcmp(fromTestRecord(schema, inserts[i])->data,r->data,getRecordSize(schema)) == 0)
	     foundScan[i] = TRUE;
     }
    }
  if (rc != RC_NO_TUPLES)
    TEST_CHECK(rc);
  TEST_CHECK(closeScan(sc));
  
  ASSERT_TRUE(!foundScan[0], "not greater than four");
  ASSERT_TRUE(foundScan[4], "greater than four");
  ASSERT_TRUE(foundScan[9], "greater than four");

  // clean up
  TEST_CHECK(closeTable(table));
  TEST_CHECK(deleteTable("test_table_r"));
  TEST_CHECK(shutdownRecordManager());

  freeRecord(r);
  free(table);
  free(sc);
  freeExpr(sel);
  TEST_DONE();
}
コード例 #30
0
ファイル: dit_access_utils.c プロジェクト: bahamas10/openzfs
/*
 * Returns an array of rule-values corresponding to the
 * splitfields.
 */
__nis_rule_value_t *
processSplitField(__nis_table_mapping_t *sf, __nis_value_t *inVal,
			int *nv, int *statP) {

	char			*sepset;
	__nis_rule_value_t	*rvq;
	__nis_value_t		**valA, *tempVal;
	int			i, j, res, numVals, oldlen, count;
	char			*str, *oldstr;

	/* sf will be non NULL */

	if (inVal == 0 || inVal->type != vt_string) {
		*statP =  MAP_PARAM_ERROR;
		return (0);
	}

	/* Get the separator list */
	sepset = sf->separatorStr;

	/* Initialize rule-value */
	rvq = 0;
	count = 0;

	if ((tempVal = stringToValue(inVal->val->value,
			inVal->val->length)) == 0) {
		*statP = MAP_NO_MEMORY;
		return (0);
	}

	str = oldstr = tempVal->val->value;
	oldlen = tempVal->val->length;

	while (str) {
		tempVal->val->value = str;
		tempVal->val->length = strlen(str) + 1;

		/* Loop to check which format matches str */
		for (i = 0; i <= sf->numSplits; i++) {
			valA = matchMappingItem(sf->e[i].element.match.fmt,
				tempVal, &numVals, sepset, &str);
			if (valA == 0) {
				/* The format didn't match. Try the next one */
				continue;
			}

			/*
			 * If we are here means we had a match.
			 * Each new set of values obtained from the match is
			 * added to a new rule-value. This is to preserve the
			 * the distinction between each set.
			 */
			rvq = growRuleValue(count, count + 1, rvq, 0);
			if (rvq == 0) {
				*statP = MAP_INTERNAL_ERROR;
				for (j = 0; j < numVals; j++)
					freeValue(valA[j], 1);
				sfree(valA);
				tempVal->val->value = oldstr;
				tempVal->val->length = oldlen;
				freeValue(tempVal, 1);
				return (0);
			}
			count++;

			for (j = 0; j < numVals; j++) {
				res = addCol2RuleValue(vt_string,
					sf->e[i].element.match.item[j].name,
					valA[j]->val->value,
					valA[j]->val->length,
					&rvq[count - 1]);
				if (res == -1) {
					*statP = MAP_INTERNAL_ERROR;
					for (; j < numVals; j++)
						freeValue(valA[j], 1);
					sfree(valA);
					tempVal->val->value = oldstr;
					tempVal->val->length = oldlen;
					freeValue(tempVal, 1);
					freeRuleValue(rvq, count);
					return (0);
				}
				freeValue(valA[j], 1);
			}
			sfree(valA);

			/*
			 * Since we had a match, break out of this loop
			 * to parse remainder of str
			 */
			break;
		}

		/* Didn't find any match, so get out of the loop */
		if (i > sf->numSplits) {
			str = 0;
			break;
		}

		/* Skip the separators before looping back */
		if (str) {
			str = str + strspn(str, sepset);
			if (*str == '\0')
				break;
		}
	}

	tempVal->val->value = oldstr;
	tempVal->val->length = oldlen;
	freeValue(tempVal, 1);

	if (str == 0) {
		freeRuleValue(rvq, count);
		return (0);
	}

	if (nv != 0)
		*nv = count;

	return (rvq);
}