/// searchForAssignment - Look for a cached solution for a query.
///
/// \param key - The query to look up.
/// \param result [out] - The cached result, if the lookup is succesful. This is
/// either a satisfying assignment (for a satisfiable query), or 0 (for an
/// unsatisfiable query).
/// \return - True if a cached result was found.
bool CexCachingSolver::searchForAssignment(KeyType &key, Assignment *&result) {
    Assignment * const *lookup = cache.lookup(key);
    if (lookup) {
        result = *lookup;
        return true;
    }

    if (CexCacheTryAll) {
        // Look for a satisfying assignment for a superset, which is trivially an
        // assignment for any subset.
        Assignment **lookup = cache.findSuperset(key, NonNullAssignment());

        // Otherwise, look for a subset which is unsatisfiable, see below.
        if (!lookup)
            lookup = cache.findSubset(key, NullAssignment());

        // If either lookup succeeded, then we have a cached solution.
        if (lookup) {
            result = *lookup;
            return true;
        }

        // Otherwise, iterate through the set of current assignments to see if one
        // of them satisfies the query.
        for (assignmentsTable_ty::iterator it = assignmentsTable.begin(),
                ie = assignmentsTable.end(); it != ie; ++it) {
            Assignment *a = *it;
            if (a->satisfies(key.begin(), key.end())) {
                result = a;
                return true;
            }
        }
    } else {
        // FIXME: Which order? one is sure to be better.

        // Look for a satisfying assignment for a superset, which is trivially an
        // assignment for any subset.
        Assignment **lookup = cache.findSuperset(key, NonNullAssignment());

        // Otherwise, look for a subset which is unsatisfiable -- if the subset is
        // unsatisfiable then no additional constraints can produce a valid
        // assignment. While searching subsets, we also explicitly the solutions for
        // satisfiable subsets to see if they solve the current query and return
        // them if so. This is cheap and frequently succeeds.
        if (!lookup)
            lookup = cache.findSubset(key, NullOrSatisfyingAssignment(key));

        // If either lookup succeeded, then we have a cached solution.
        if (lookup) {
            result = *lookup;
            return true;
        }
    }

    return false;
}
Beispiel #2
0
Int32Vector Adfgvx::getPermutationKey() const
{
    KeyType key = getKey();
    KeyType sorted_key(key);
    sorted_key.sort();

    Int32Vector perm_key;
    perm_key.reserve(key.length());
    for (const auto c : key)
    {
        perm_key.push_back(sorted_key.find(c));
    }

    return perm_key;
}
Beispiel #3
0
/// lookupAssignment - Lookup a cached result for the given \arg query.
///
/// \param query - The query to lookup.
/// \param key [out] - On return, the key constructed for the query.
/// \param result [out] - The cached result, if the lookup is succesful. This is
/// either a satisfying assignment (for a satisfiable query), or 0 (for an
/// unsatisfiable query).
/// \return True if a cached result was found.
bool CexCachingSolver::lookupAssignment(const Query &query, 
                                        KeyType &key,
                                        Assignment *&result) {
  key = KeyType(query.constraints.begin(), query.constraints.end());
  ref<Expr> neg = Expr::createIsZero(query.expr);
  bool keyHasAddedConstraint = false;
  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(neg)) {
    if (CE->isFalse()) {
      result = (Assignment*) 0;
      ++stats::queryCexCacheHits;
      return true;
    }
  } else {
    key.insert(neg);
    keyHasAddedConstraint = true;
  }

  bool found = searchForAssignment(key, result);
  if (found)
    ++stats::queryCexCacheHits;
  else ++stats::queryCexCacheMisses;

  if (keyHasAddedConstraint && !unsatCore.empty()) {
      /// Here we remove the added component (neg)
      /// from the unsatisfiability core.
    unsatCore.erase(std::remove(unsatCore.begin(), unsatCore.end(), neg),
                    unsatCore.end());
  }
    
  return found;
}
bool TableCursorKey::putField(int i, const String &s) {
  if(s.length() > m_keydef.getFieldDef(i).getLen()) {
    switch(m_relop) {
    case RELOP_EQ:
      m_key.init();
      m_fieldCount = 0;
      m_relop      = RELOP_FALSE;
      return true;
    case RELOP_GE:
    case RELOP_GT:
      m_keydef.put(m_key,i,left(s,m_keydef.getFieldDef(i).getLen()));
      m_relop      = RELOP_GT;
      m_fieldCount = i + 1;
      return true;
    case RELOP_LE:
    case RELOP_LT:
      m_keydef.put(m_key,i,left(s,m_keydef.getFieldDef(i).getLen()));
      m_relop      = RELOP_LT;
      m_fieldCount = i + 1;
      return true;
    }
  }
  m_keydef.put(m_key, i, s);
  return false;
}
bool TableCursorKey::putField(int i, const varchar &v) {
  if(v.len() > m_keydef.getFieldDef(i).getLen()) {
    varchar tmp(m_keydef.getFieldDef(i).getLen(),v.data());
    switch(m_relop) {
    case RELOP_EQ:
      m_key.init();
      m_fieldCount = 0;
      m_relop      = RELOP_FALSE;
      return true;
    case RELOP_GE:
    case RELOP_GT:
      m_keydef.put(m_key,i,tmp);
      m_relop      = RELOP_GT;
      m_fieldCount = i + 1;
      return true;
    case RELOP_LE:
    case RELOP_LT:
      m_keydef.put(m_key,i,tmp);
      m_relop      = RELOP_LT;
      m_fieldCount = i + 1;
      return true;
    }
  }
  m_keydef.put(m_key, i, v);
  return false;
}
Beispiel #6
0
bool CexCachingSolver::getAssignment(const Query& query, Assignment *&result) {
  KeyType key;

  if (lookupAssignment(query, key, result))
    return true;

  std::vector<const Array*> objects;
  findSymbolicObjects(key.begin(), key.end(), objects);

  std::vector< std::vector<unsigned char> > values;
  bool hasSolution;
  if (!solver->impl->computeInitialValues(query, objects, values, 
                                          hasSolution))
    return false;
    
  AssignmentCacheWrapper *bindingWrapper;
  Assignment *binding;
  if (hasSolution) {
    binding = new Assignment(objects, values);

    // Memoize the result.
    std::pair<assignmentsTable_ty::iterator, bool>
      res = assignmentsTable.insert(binding);
    if (!res.second) {
      delete binding;
      binding = *res.first;
    }
    
    if (DebugCexCacheCheckBinding)
      if (!binding->satisfies(key.begin(), key.end())) {
        query.dump();
        binding->dump();
        klee_error("Generated assignment doesn't match query");
      }

    bindingWrapper = new AssignmentCacheWrapper(binding);
  } else {
    unsatCore = solver->impl->getUnsatCore();
    binding = (Assignment *) 0;
    bindingWrapper = new AssignmentCacheWrapper(unsatCore);
  }
  
  result = binding;
  cache.insert(key, bindingWrapper);

  return true;
}
Beispiel #7
0
bool ObjectWrapper::SetValue(const KeyType key, JSValueRef value)
{
    JSStringRef strKey = JSStringCreateWithUTF8CString(key.c_str());
    JSObjectSetProperty(g_ctx, m_obj, strKey, value, kJSPropertyAttributeNone, NULL);
    JSStringRelease(strKey);

    return true;
}
Beispiel #8
0
JSValueRef ObjectWrapper::GetValue(const KeyType key)
{
    JSStringRef strKey = JSStringCreateWithUTF8CString(key.c_str());
    JSValueRef value = JSObjectGetProperty(g_ctx, m_obj, strKey, NULL);
    JSStringRelease(strKey);

    return value;
}
Beispiel #9
0
bool ObjectWrapper::Remove(const KeyType& key)
{
    JSStringRef strKey = JSStringCreateWithUTF8CString(key.c_str());
    JSObjectDeleteProperty(g_ctx, m_obj, strKey, NULL);
    JSStringRelease(strKey);

    return true;
}
Beispiel #10
0
bool ObjectWrapper::HasKey(const KeyType& key)
{
    JSStringRef strKey = JSStringCreateWithUTF8CString(key.c_str());
    bool hasProperty = JSObjectHasProperty(g_ctx, m_obj, strKey);
    JSStringRelease(strKey);
    
    return hasProperty;
}
bool StringCipherWithPermutationKey::isUniqueWithoutMissingIntegers(const KeyType &key)
{
    const uint32_t key_len = key.size();
    const std::set<int32_t> sorted_key(key.begin(), key.end());
    if (key_len != sorted_key.size())
    {
        return false;
    }

    // Check if all integers are between 0 and the size of the key.
    const uint32_t max_int = *std::max_element(sorted_key.begin(), sorted_key.end());
    if (max_int >= key_len)
    {
        return false;
    }

    return true;
}
Beispiel #12
0
ClassicalType Adfgvx::encode(const ClassicalType &clear_text)
{
    // Take the coordinates of each letter and replace them by A,D,F,G,V or X such that
    // A=0, D=1, F=2, G=3, V=4, X=5. For example, if 'K' has coordinates (2,3), then
    // we encode K as FG.
    const KeyType key = getKey();
    ClassicalType first_encoding((clear_text.length() + key.length()) * 2);

    for (const auto c : clear_text)
    {
        const Coordinates coords = grid_key.getCharCoordinates(c);
        first_encoding.push_back(code[coords.y]);
        first_encoding.push_back(code[coords.x]);
    }

    TranspositionCompleteColumns TCC(getPermutationKey());

    return TCC.encode(first_encoding);
}
void KeyHandler::freeKey(KeyType keyId, int playerId)
{
	// assert - the right key with player
	assert(keyId.getOwnerId() == playerId);
#ifdef _DEBUG
	// DEBUG - assert - the key already exists
	assert(mFreeKeysChecker[playerId].find(keyId) == mFreeKeysChecker[playerId].end());
	// DEBUG - add key to the map
	mFreeKeysChecker[playerId][keyId] = true;
#endif
	// add the key to the stack
	mFreeKeys[playerId].push(keyId);
}
Beispiel #14
0
bool CexCachingSolver::getAssignment(const Query& query, Assignment *&result) {
    KeyType key;
    if (lookupAssignment(query, key, result))
        return true;

    std::vector<const Array*> objects;
    findSymbolicObjects(key.begin(), key.end(), objects);

    std::vector< std::vector<unsigned char> > values;
    bool hasSolution;
    if (!solver->impl->computeInitialValues(query, objects, values,
                                            hasSolution))
        return false;

    Assignment *binding;
    if (hasSolution) {
        binding = new Assignment(objects, values);

        // Memoize the result.
        std::pair<assignmentsTable_ty::iterator, bool>
        res = assignmentsTable.insert(binding);
        if (!res.second) {
            delete binding;
            binding = *res.first;
        }

        if (DebugCexCacheCheckBinding)
            assert(binding->satisfies(key.begin(), key.end()));
    } else {
        binding = (Assignment*) 0;
    }

    result = binding;
    cache.insert(key, binding);

    return true;
}
void StringCipherWithPermutationKey::setKey(const KeyType &key)
{
    if (key.empty())
    {
        throw EmptyKey("Your key is empty.");
    }

    if (!isUniqueWithoutMissingIntegers(key))
    {
        throw BadPermutationKey("Your permutation key has to contain unique integers and / or integers "
                "between 0 and the size of your key have to be all there.");
    }

    this->key = key;
}
void TableCursorKey::setUndefinedField(int i) {
  switch(m_relop) {
  case RELOP_EQ:
    m_key.init();
    m_relop      = RELOP_FALSE;
    m_fieldCount = 0;
    return;
  case RELOP_GE:
  case RELOP_GT:
  case RELOP_LE:
  case RELOP_LT:
    m_fieldCount = i;
    return;
  }
}
Beispiel #17
0
      std::string operator()( const KeyType& key ) const {
         using data_type = typename KeyType::data_type;
         constexpr int position = Storage::template position<KeyType>();
         constexpr bool is_default = position == DefaultPosition;

         checksummed_data<data_type> wrapper;
         wrapper.data = key.serialize();
         wrapper.check = checksummed_data<data_type>::calculate_checksum(wrapper.data, !is_default ? Prefixes[position] : nullptr);
         auto packed = raw::pack( wrapper );
         auto data_str = to_base58( packed.data(), packed.size() );
         if (!is_default) {
            data_str = string(Prefixes[position]) + "_" + data_str;
         }

         return data_str;
      }
Beispiel #18
0
/// lookupAssignment - Lookup a cached result for the given \arg query.
///
/// \param query - The query to lookup.
/// \param key [out] - On return, the key constructed for the query.
/// \param result [out] - The cached result, if the lookup is succesful. This is
/// either a satisfying assignment (for a satisfiable query), or 0 (for an
/// unsatisfiable query).
/// \return True if a cached result was found.
bool CexCachingSolver::lookupAssignment(const Query &query, 
                                        KeyType &key,
                                        Assignment *&result) {
  key = KeyType(query.constraints.begin(), query.constraints.end());
  ref<Expr> neg = Expr::createIsZero(query.expr);
  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(neg)) {
    if (CE->isFalse()) {
      result = (Assignment*) 0;
      return true;
    }
  } else {
    key.insert(neg);
  }

  return searchForAssignment(key, result);
}
 static constexpr LocalKeyType getLocalKey(const KeyType& k) {
   return LocalKeyType(k.hash());
 }
Beispiel #20
0
int main()
{
    Library article;
    ElementType fileData;
    KeyType keyData;
    bool showMenu = true;

    // Open file of name "fileName"; return an error and exit the program upon
    // failure
    ifstream file;
    char fileName[15] = "cacmpubs10.txt";
    file.open(fileName);

    cout << "\n$ cacmLibrary " << fileName << endl;

    if (file.fail())
    {
        cout << "The file \"" << fileName << "\" failed to open.\n\n";
        exit(1);
    }
    else
        cout << "Loading library, please wait..." << endl;

    // Continues reading, storing, and inserting data as long as there are
    // contents left in the file
    while (!file.eof())
    {
        // Reads and stores the article's key
        getline(file, keyData);
        fileData.key = keyData.substr(0, keyData.size()-1);

        // Reads and stores the article's author
        getline(file, fileData.author);

        // Reads and stores the article's title
        getline(file, fileData.title);

        // Checks to make sure the file is not reading a blank line (or keyless
        // article) If valid, inserts the compiled stored data into the linked
        // list
        if (fileData.key != "")
            article.insert(fileData);
    }

    file.clear();
    file.close();

    cout << "Welcome to the CACM Library!\n\n";

    // Continues to show the user a menu of program options until he indicates
    // he would like to exit
    while (showMenu == true)
    {
        char menuChoice = toupper(menu());

        switch (menuChoice)
        {
            case 'F':
                findArticle(article);
                break;
            case 'L':
                cout << article;  //article.display()
                break;
            case 'A':
                addArticle(article);
                break;
            case 'R':
                removeArticle(article);
                break;
            case 'E':
                showMenu = false;
                break;
            default:
                cout << "Invalid Menu Choice -- Please Try Again\n\n";
                break;
         }
    }

    cout << "Thank you for using the CACM Library!\n$\n";

    return 0;
}
Beispiel #21
0
 static bool CheckKey(const KeyType &k) { return !k.isNull(); };
Beispiel #22
0
static void test_binHashKey()
{
    const char* testStringA = "abcdABCD";
    const char* testStringB = "abcdBBCD";
    enum {
        kDataLenUsedForKey = 8
    };

    typedef GrBinHashKey<BogusEntry, kDataLenUsedForKey> KeyType;

    KeyType keyA;
    int passCnt = 0;
    while (keyA.doPass()) {
        ++passCnt;
        keyA.keyData(reinterpret_cast<const uint32_t*>(testStringA), kDataLenUsedForKey);
    }
    GrAssert(passCnt == 1); //We expect the static allocation to suffice
    GrBinHashKey<BogusEntry, kDataLenUsedForKey-1> keyBust;
    passCnt = 0;
    while (keyBust.doPass()) {
        ++passCnt;
        // Exceed static storage by 1
        keyBust.keyData(reinterpret_cast<const uint32_t*>(testStringA), kDataLenUsedForKey);
    }
    GrAssert(passCnt == 2); //We expect dynamic allocation to be necessary
    GrAssert(keyA.getHash() == keyBust.getHash());

    // Test that adding keyData in chunks gives
    // the same hash as with one chunk
    KeyType keyA2;
    while (keyA2.doPass()) {
        keyA2.keyData(reinterpret_cast<const uint32_t*>(testStringA), 4);
        keyA2.keyData(&reinterpret_cast<const uint32_t*>(testStringA)[4], kDataLenUsedForKey-4);
    }
    GrAssert(keyA.getHash() == keyA2.getHash());

    KeyType keyB;
    while (keyB.doPass()){
        keyB.keyData(reinterpret_cast<const uint32_t*>(testStringB), kDataLenUsedForKey);
    }
    GrAssert(keyA.compare(keyB) < 0);
    GrAssert(keyA.compare(keyA2) == 0);

    //Test ownership tranfer and copying
    keyB.copyAndTakeOwnership(keyA);
    GrAssert(keyA.fIsValid == false);
    GrAssert(keyB.fIsValid);
    GrAssert(keyB.getHash() == keyA2.getHash());
    GrAssert(keyB.compare(keyA2) == 0);
    keyA.deepCopyFrom(keyB);
    GrAssert(keyA.fIsValid);
    GrAssert(keyB.fIsValid);
    GrAssert(keyA.getHash() == keyA2.getHash());
    GrAssert(keyA.compare(keyA2) == 0);

    //Test ownership tranfer and copying with key on heap
    GrBinHashKey<BogusEntry, kDataLenUsedForKey-1> keyBust2;
    keyBust2.deepCopyFrom(keyBust);
    GrAssert(keyBust.fIsValid);
    GrAssert(keyBust2.fIsValid);
    GrAssert(keyBust.getHash() == keyBust2.getHash());
    GrAssert(keyBust.compare(keyBust2) == 0);
    GrBinHashKey<BogusEntry, kDataLenUsedForKey-1> keyBust3;
    keyBust3.deepCopyFrom(keyBust);
    GrAssert(keyBust.fIsValid == false);
    GrAssert(keyBust3.fIsValid);
    GrAssert(keyBust3.getHash() == keyBust2.getHash());
    GrAssert(keyBust3.compare(keyBust2) == 0);
}
Beispiel #23
0
ConfigFile::LineType ConfigFile::parseLine(const char* fileName, const String& input, KeyType& key, String& value)
{
	int inString = 0;
	String::size_type valStart = 0;
	String::size_type eol = String::npos;
	bool hasSub = false;
	const char* include = "include";
	const unsigned incLen = strlen(include);

	for (String::size_type n = 0; n < input.length(); ++n)
	{
		switch (input[n])
		{
		case '"':
			if (key.isEmpty())		// quoted string to the left of = doesn't make sense
				return LINE_BAD;
			if (inString >= 2)		// one more quote after quoted string doesn't make sense
				return LINE_BAD;
			inString++;
			break;

		case '=':
			if (key.isEmpty())
			{
				key = input.substr(0, n).ToNoCaseString();
				key.rtrim(" \t\r");
				if (key.isEmpty())		// not good - no key
					return LINE_BAD;
				valStart = n + 1;
			}
			else if (inString >= 2)		// Something after the end of line
				return LINE_BAD;
			break;

		case '#':
			if (inString != 1)
			{
				eol = n;
				n = input.length();	// skip the rest of symbols
			}
			break;

		case ' ':
		case '\t':
			if (n == incLen && key.isEmpty())
			{
				KeyType inc = input.substr(0, n).ToNoCaseString();
				if (inc == include)
				{
					value = input.substr(n);
					value.alltrim(" \t\r");

					if (!macroParse(value, fileName))
					{
						return LINE_BAD;
					}
					return LINE_INCLUDE;
				}
			}
			// fall down ...
		case '\r':
			break;

		case '{':
		case '}':
			if (flags & HAS_SUB_CONF)
			{
				if (inString != 1)
				{
					if (input[n] == '}')	// Subconf close mark not expected
					{
						return LINE_BAD;
					}

					hasSub = true;
					inString = 2;
					eol = n;
				}
				break;
			}
			// fall through ....

		default:
			if (inString >= 2)		// Something after the end of line
				return LINE_BAD;
			break;
		}
	}

	if (inString == 1)				// If we are still inside a string, it's error
		return LINE_BAD;

	if (key.isEmpty())
	{
		key = input.substr(0, eol).ToNoCaseString();
		key.rtrim(" \t\r");
		value.erase();
	}
	else
	{
		value = input.substr(valStart, eol - valStart);
		value.alltrim(" \t\r");
		value.alltrim("\"");
	}

	// Now expand macros in value
	if (!macroParse(value, fileName))
	{
		return LINE_BAD;
	}

	return hasSub ? LINE_START_SUB : LINE_REGULAR;
}
bool TableCursorKey::putField(int i, double d) {
  DbFieldType keyType = m_keydef.getFieldDef(i).getType();
  int c = rangecmp(d,keyType);
  if(c == 0) {
    if(isIntegerType(keyType)) {
      if(isInteger(d))
        putNumberInKey(i,d);
      else {
        switch(m_relop) {
        case RELOP_EQ:
          m_key.init();
          m_fieldCount = 0;
          m_relop      = RELOP_FALSE;
          return true;
        case RELOP_GE:
        case RELOP_GT:
          putNumberInKey(i,roundup(d));
          m_relop      = RELOP_GE;
          m_fieldCount = i + 1;
          return true;
        case RELOP_LE:
        case RELOP_LT:
          putNumberInKey(i,floor(d));
          m_relop      = RELOP_LE;
          m_fieldCount = i + 1;
          return true;
        }
      }
    } else if(keyType == DBTYPE_FLOAT || keyType == DBTYPE_FLOATN) {
      if(validFloat(d)) {
        putNumberInKey(i,d);
      } else {
        switch(m_relop) {
        case RELOP_EQ:
          m_key.init();
          m_fieldCount = 0;
          m_relop      = RELOP_FALSE;
          return true;
        case RELOP_GE:
        case RELOP_GT:
          putNumberInKey(i,roundUpToNearestFloat(d));
          m_relop      = RELOP_GE;
          m_fieldCount = i + 1;
          return true;
        case RELOP_LE:
        case RELOP_LT:
          putNumberInKey(i,roundDownToNearestFloat(d));
          m_relop      = RELOP_LE;
          m_fieldCount = i + 1;
          return true;
        }
      }
    } else {
      putNumberInKey(i,d);
    }
  } else if(c < 0) {
    switch(m_relop) {
    case RELOP_EQ:
      m_key.init();
      m_fieldCount = 0;
      m_relop      = RELOP_FALSE;
      return true;
    case RELOP_GE:
    case RELOP_GT:
      m_fieldCount = i;
      return true;
    case RELOP_LE:
    case RELOP_LT:
      m_relop      = RELOP_LT;
      m_fieldCount = i;
      return true;
    }
  } else { // c > 0
    switch(m_relop) {
    case RELOP_EQ:
      m_key.init();
      m_fieldCount = 0;
      m_relop      = RELOP_FALSE;
      return true;
    case RELOP_GE:
    case RELOP_GT:
      m_relop      = RELOP_GT;
      m_fieldCount = i;
      return true;
    case RELOP_LE:
    case RELOP_LT:
      m_fieldCount = i;
      return true;
    }
  }
  return false;
}
Beispiel #25
0
 bool operator()(const KeyType &a) const {
    const auto &b = _b.template get<KeyType>();
    return a.serialize() < b.serialize();
 }