Back out r6976, r6977, r6980, r6981, which were namespace removals.

There is nothing wrong with namespace, and these changes generated 1700 lines of
irrelevant diff output making it difficult to compare various revisions of CommonLibs.
This commit is contained in:
pat.thompson 2014-03-31 12:17:26 +02:00 committed by Michael Iedema
parent c17e42bd8e
commit 0dc6d369e8
18 changed files with 335 additions and 304 deletions

View File

@ -32,6 +32,8 @@
#include <sstream> #include <sstream>
#include <string.h> #include <string.h>
using namespace std;
BitVector::BitVector(const char *valString) BitVector::BitVector(const char *valString)
@ -236,7 +238,7 @@ void BitVector::unmap(const unsigned *map, size_t mapSize, BitVector& dest) cons
std::ostream& operator<<(std::ostream& os, const BitVector& hv) ostream& operator<<(ostream& os, const BitVector& hv)
{ {
for (size_t i=0; i<hv.size(); i++) { for (size_t i=0; i<hv.size(); i++) {
if (hv.bit(i)) os << '1'; if (hv.bit(i)) os << '1';
@ -339,7 +341,7 @@ float SoftVector::getSNR() const
} }
std::ostream& operator<<(std::ostream& os, const SoftVector& sv) ostream& operator<<(ostream& os, const SoftVector& sv)
{ {
for (size_t i=0; i<sv.size(); i++) { for (size_t i=0; i<sv.size(); i++) {
if (sv[i]<0.25) os << "0"; if (sv[i]<0.25) os << "0";
@ -378,7 +380,7 @@ void BitVector::unpack(const unsigned char* src)
fillField(whole,src[bytes] >> (8-rem),rem); fillField(whole,src[bytes] >> (8-rem),rem);
} }
void BitVector::hex(std::ostream& os) const void BitVector::hex(ostream& os) const
{ {
os << std::hex; os << std::hex;
unsigned digits = size()/4; unsigned digits = size()/4;

View File

@ -32,6 +32,8 @@
#include <cstdlib> #include <cstdlib>
#include <string.h> #include <string.h>
using namespace std;
// We must have a gConfig now to include BitVector. // We must have a gConfig now to include BitVector.
#include "Configuration.h" #include "Configuration.h"
ConfigurationTable gConfig; ConfigurationTable gConfig;
@ -40,49 +42,49 @@ ConfigurationTable gConfig;
void origTest() void origTest()
{ {
BitVector v0("0000111100111100101011110000"); BitVector v0("0000111100111100101011110000");
std::cout << v0 << std::endl; cout << v0 << endl;
// (pat) The conversion from a string was inserting garbage into the result BitVector. // (pat) The conversion from a string was inserting garbage into the result BitVector.
// Fixed now so only 0 or 1 are inserted, but lets check: // Fixed now so only 0 or 1 are inserted, but lets check:
for (char *cp = v0.begin(); cp < v0.end(); cp++) std::cout << (int)*cp<<" "; for (char *cp = v0.begin(); cp < v0.end(); cp++) cout << (int)*cp<<" ";
std::cout << std::endl; cout << endl;
BitVector v1(v0); BitVector v1(v0);
v1.LSB8MSB(); v1.LSB8MSB();
std::cout <<v1 << " (byte swapped)" << std::endl; cout <<v1 << " (byte swapped)" << endl;
// Test operator== // Test operator==
assert(v1 == v1); assert(v1 == v1);
std::cout <<"v0="<<v0 <<std::endl; cout <<"v0="<<v0 <<endl;
std::cout <<"v1="<<v1 <<std::endl; cout <<"v1="<<v1 <<endl;
assert(!(v0 == v1)); assert(!(v0 == v1));
BitVector v5("000011110000"); BitVector v5("000011110000");
int r1 = v5.peekField(0,8); int r1 = v5.peekField(0,8);
int r2 = v5.peekField(4,4); int r2 = v5.peekField(4,4);
int r3 = v5.peekField(4,8); int r3 = v5.peekField(4,8);
std::cout << r1 << ' ' << r2 << ' ' << r3 << std::endl; cout << r1 << ' ' << r2 << ' ' << r3 << endl;
std::cout << v5 << std::endl; cout << v5 << endl;
v5.fillField(0,0xa,4); v5.fillField(0,0xa,4);
int r4 = v5.peekField(0,8); int r4 = v5.peekField(0,8);
std::cout << v5 << std::endl; cout << v5 << endl;
std::cout << r4 << std::endl; cout << r4 << endl;
v5.reverse8(); v5.reverse8();
std::cout << v5 << std::endl; cout << v5 << endl;
unsigned char ts[9] = "abcdefgh"; unsigned char ts[9] = "abcdefgh";
BitVector tp(70); BitVector tp(70);
std::cout << "ts=" << ts << std::endl; cout << "ts=" << ts << endl;
tp.unpack(ts); tp.unpack(ts);
std::cout << "tp=" << tp << std::endl; cout << "tp=" << tp << endl;
tp.pack(ts); tp.pack(ts);
std::cout << "ts=" << ts << std::endl; cout << "ts=" << ts << endl;
BitVector v6("010101"); BitVector v6("010101");
BitVector v7(3); BitVector v7(3);
unsigned punk[3] = {1,2,5}; unsigned punk[3] = {1,2,5};
v6.copyPunctured(v7, punk, 3); v6.copyPunctured(v7, punk, 3);
std::cout << "v7=" << v7 << std::endl; cout << "v7=" << v7 << endl;
} }
@ -94,20 +96,20 @@ void foo(TestVector a)
} }
void anotherTest() void anotherTest()
{ {
std::cout << "START BitVector anotherTest" << std::endl; cout << "START BitVector anotherTest" << endl;
TestVector v0("0000111100111100101011110000"); TestVector v0("0000111100111100101011110000");
TestVector atest = v0.head(3); TestVector atest = v0.head(3);
std::cout << atest << std::endl; cout << atest << endl;
std::cout << "Calling head" << std::endl; cout << "Calling head" << endl;
std::cout << v0.head(3) << std::endl; cout << v0.head(3) << endl;
std::cout << "Passing BitVector" << std::endl; cout << "Passing BitVector" << endl;
// This calls Vector const copy constructor. // This calls Vector const copy constructor.
// That is because the implicitly declared copy constructor for BitVector is of the form (BitVector const&) // That is because the implicitly declared copy constructor for BitVector is of the form (BitVector const&)
foo(v0); foo(v0);
const TestVector ctest("0000"); const TestVector ctest("0000");
std::cout << ctest.cloneSegment(0,2) << std::endl; cout << ctest.cloneSegment(0,2) << endl;
std::cout << "after"<<std::endl; cout << "after"<<endl;
std::cout << "FINISH anotherTest" << std::endl; cout << "FINISH anotherTest" << endl;
} }
BitVector randomBitVector(int n) BitVector randomBitVector(int n)

View File

@ -39,6 +39,8 @@
#define debugLogEarly(...) #define debugLogEarly(...)
#endif #endif
using namespace std;
char gCmdName[20] = {0}; // Use a char* to avoid avoid static initialization of string, and race at startup. char gCmdName[20] = {0}; // Use a char* to avoid avoid static initialization of string, and race at startup.
static const char* createConfigTable = { static const char* createConfigTable = {
@ -188,16 +190,16 @@ ConfigurationTable::ConfigurationTable(const char* filename, const char *wCmdNam
try { try {
if (wCmdName == NULL) { wCmdName = ""; } if (wCmdName == NULL) { wCmdName = ""; }
LOG(INFO) << wCmdName << ":" << " List of non-default config parameters:"; LOG(INFO) << wCmdName << ":" << " List of non-default config parameters:";
std::string snippet(""); string snippet("");
ConfigurationKeyMap view = getSimilarKeys(snippet); ConfigurationKeyMap view = getSimilarKeys(snippet);
for (ConfigurationKeyMap::iterator it = view.begin(); it != view.end(); it++) { for (ConfigurationKeyMap::iterator it = view.begin(); it != view.end(); it++) {
std::string name = it->first; string name = it->first;
ConfigurationKey key = it->second; ConfigurationKey key = it->second;
if (name != key.getName()) { if (name != key.getName()) {
LOG(ALERT) << "SQL database is corrupt at name:"<<name <<" != key:"<<key.getName(); LOG(ALERT) << "SQL database is corrupt at name:"<<name <<" != key:"<<key.getName();
} }
std::string defaultValue= key.getDefaultValue(); string defaultValue= key.getDefaultValue();
std::string value = this->getStr(name); string value = this->getStr(name);
if (value != defaultValue) { if (value != defaultValue) {
LOG(INFO) << "Config Variable"<<LOGVAR(name) <<LOGVAR(value) <<LOGVAR(defaultValue); LOG(INFO) << "Config Variable"<<LOGVAR(name) <<LOGVAR(value) <<LOGVAR(defaultValue);
} }
@ -209,22 +211,22 @@ ConfigurationTable::ConfigurationTable(const char* filename, const char *wCmdNam
} }
std::string ConfigurationTable::getDefaultSQL(const std::string& program, const std::string& version) string ConfigurationTable::getDefaultSQL(const std::string& program, const std::string& version)
{ {
std::stringstream ss; stringstream ss;
ConfigurationKeyMap::iterator mp; ConfigurationKeyMap::iterator mp;
ss << "--" << std::endl; ss << "--" << endl;
ss << "-- This file was generated using: " << program << " --gensql" << std::endl; ss << "-- This file was generated using: " << program << " --gensql" << endl;
ss << "-- binary version: " << version << std::endl; ss << "-- binary version: " << version << endl;
ss << "--" << std::endl; ss << "--" << endl;
ss << "-- Future changes should not be put in this file directly but" << std::endl; ss << "-- Future changes should not be put in this file directly but" << endl;
ss << "-- rather in the program's ConfigurationKey schema." << std::endl; ss << "-- rather in the program's ConfigurationKey schema." << endl;
ss << "--" << std::endl; ss << "--" << endl;
ss << "PRAGMA foreign_keys=OFF;" << std::endl; ss << "PRAGMA foreign_keys=OFF;" << endl;
//ss << "PRAGMA journal_mode=WAL;" << std::endl; //ss << "PRAGMA journal_mode=WAL;" << endl;
ss << "BEGIN TRANSACTION;" << std::endl; ss << "BEGIN TRANSACTION;" << endl;
ss << "CREATE TABLE IF NOT EXISTS CONFIG ( KEYSTRING TEXT UNIQUE NOT NULL, VALUESTRING TEXT, STATIC INTEGER DEFAULT 0, OPTIONAL INTEGER DEFAULT 0, COMMENTS TEXT DEFAULT '');" << std::endl; ss << "CREATE TABLE IF NOT EXISTS CONFIG ( KEYSTRING TEXT UNIQUE NOT NULL, VALUESTRING TEXT, STATIC INTEGER DEFAULT 0, OPTIONAL INTEGER DEFAULT 0, COMMENTS TEXT DEFAULT '');" << endl;
mp = mSchema.begin(); mp = mSchema.begin();
while (mp != mSchema.end()) { while (mp != mSchema.end()) {
@ -243,10 +245,10 @@ std::string ConfigurationTable::getDefaultSQL(const std::string& program, const
// optional // optional
ss << "0,"; ss << "0,";
// description // description
const std::string description = mp->second.getDescription(); const string description = mp->second.getDescription();
// Try to use a quote that will work: if the description contains ' quote with " else '. // Try to use a quote that will work: if the description contains ' quote with " else '.
// This is not perfect because these quotes could themselves be quoted. // This is not perfect because these quotes could themselves be quoted.
const char * quote = std::string::npos != description.find('\'') ? "\"" : "'"; const char * quote = string::npos != description.find('\'') ? "\"" : "'";
ss << quote; ss << quote;
if (mp->second.getType() == ConfigurationKey::BOOLEAN) { if (mp->second.getType() == ConfigurationKey::BOOLEAN) {
ss << "1=enabled, 0=disabled - "; ss << "1=enabled, 0=disabled - ";
@ -256,28 +258,28 @@ std::string ConfigurationTable::getDefaultSQL(const std::string& program, const
ss << " Static."; ss << " Static.";
} }
ss << quote; ss << quote;
ss << ");" << std::endl; ss << ");" << endl;
mp++; mp++;
} }
ss << "COMMIT;" << std::endl; ss << "COMMIT;" << endl;
ss << std::endl; ss << endl;
return ss.str(); return ss.str();
} }
std::string ConfigurationTable::getTeX(const std::string& program, const std::string& version) string ConfigurationTable::getTeX(const std::string& program, const std::string& version)
{ {
std::stringstream ss; stringstream ss;
ConfigurationKeyMap::iterator mp; ConfigurationKeyMap::iterator mp;
ss << "% START AUTO-GENERATED CONTENT" << std::endl; ss << "% START AUTO-GENERATED CONTENT" << endl;
ss << "% -- these sections were generated using: " << program << " --gentex" << std::endl; ss << "% -- these sections were generated using: " << program << " --gentex" << endl;
ss << "% -- binary version: " << version << std::endl; ss << "% -- binary version: " << version << endl;
ss << "\\section{Customer Site Parameters}" << std::endl; ss << "\\section{Customer Site Parameters}" << endl;
ss << "These parameters must be changed to fit your site." << std::endl; ss << "These parameters must be changed to fit your site." << endl;
ss << "\\begin{itemize}" << std::endl; ss << "\\begin{itemize}" << endl;
mp = mSchema.begin(); mp = mSchema.begin();
while (mp != mSchema.end()) { while (mp != mSchema.end()) {
if (mp->second.getVisibility() == ConfigurationKey::CUSTOMERSITE) { if (mp->second.getVisibility() == ConfigurationKey::CUSTOMERSITE) {
@ -286,16 +288,16 @@ std::string ConfigurationTable::getTeX(const std::string& program, const std::st
ss << mp->first << "} -- "; ss << mp->first << "} -- ";
// description // description
ss << mp->second.getDescription(); ss << mp->second.getDescription();
ss << std::endl; ss << endl;
} }
mp++; mp++;
} }
ss << "\\end{itemize}" << std::endl; ss << "\\end{itemize}" << endl;
ss << std::endl; ss << endl;
ss << "\\section{Customer Tuneable Parameters}" << std::endl; ss << "\\section{Customer Tuneable Parameters}" << endl;
ss << "These parameters can be changed to optimize your site." << std::endl; ss << "These parameters can be changed to optimize your site." << endl;
ss << "\\begin{itemize}" << std::endl; ss << "\\begin{itemize}" << endl;
mp = mSchema.begin(); mp = mSchema.begin();
while (mp != mSchema.end()) { while (mp != mSchema.end()) {
if (mp->second.getVisibility() != ConfigurationKey::CUSTOMERSITE && if (mp->second.getVisibility() != ConfigurationKey::CUSTOMERSITE &&
@ -309,16 +311,16 @@ std::string ConfigurationTable::getTeX(const std::string& program, const std::st
ss << mp->first << "} -- "; ss << mp->first << "} -- ";
// description // description
ss << mp->second.getDescription(); ss << mp->second.getDescription();
ss << std::endl; ss << endl;
} }
mp++; mp++;
} }
ss << "\\end{itemize}" << std::endl; ss << "\\end{itemize}" << endl;
ss << std::endl; ss << endl;
ss << "\\section{Developer/Factory Parameters}" << std::endl; ss << "\\section{Developer/Factory Parameters}" << endl;
ss << "These parameters should only be changed by when developing new code." << std::endl; ss << "These parameters should only be changed by when developing new code." << endl;
ss << "\\begin{itemize}" << std::endl; ss << "\\begin{itemize}" << endl;
mp = mSchema.begin(); mp = mSchema.begin();
while (mp != mSchema.end()) { while (mp != mSchema.end()) {
if (mp->second.getVisibility() == ConfigurationKey::FACTORY || if (mp->second.getVisibility() == ConfigurationKey::FACTORY ||
@ -328,19 +330,19 @@ std::string ConfigurationTable::getTeX(const std::string& program, const std::st
ss << mp->first << "} -- "; ss << mp->first << "} -- ";
// description // description
ss << mp->second.getDescription(); ss << mp->second.getDescription();
ss << std::endl; ss << endl;
} }
mp++; mp++;
} }
ss << "\\end{itemize}" << std::endl; ss << "\\end{itemize}" << endl;
ss << "% END AUTO-GENERATED CONTENT" << std::endl; ss << "% END AUTO-GENERATED CONTENT" << endl;
ss << std::endl; ss << endl;
std::string tmp = Utils::replaceAll(ss.str(), "^", "\\^"); string tmp = Utils::replaceAll(ss.str(), "^", "\\^");
return Utils::replaceAll(tmp, "_", "\\_"); return Utils::replaceAll(tmp, "_", "\\_");
} }
bool ConfigurationTable::defines(const std::string& key) bool ConfigurationTable::defines(const string& key)
{ {
try { try {
ScopedLock lock(mLock); ScopedLock lock(mLock);
@ -637,7 +639,7 @@ ConfigurationKeyMap ConfigurationTable::getSimilarKeys(const std::string& snippe
return tmp; return tmp;
} }
const ConfigurationRecord& ConfigurationTable::lookup(const std::string& key) const ConfigurationRecord& ConfigurationTable::lookup(const string& key)
{ {
assert(mDB); assert(mDB);
checkCacheAge(); checkCacheAge();
@ -678,7 +680,7 @@ const ConfigurationRecord& ConfigurationTable::lookup(const std::string& key)
bool ConfigurationTable::isStatic(const std::string& key) bool ConfigurationTable::isStatic(const string& key)
{ {
if (keyDefinedInSchema(key)) { if (keyDefinedInSchema(key)) {
return mSchema[key].isStatic(); return mSchema[key].isStatic();
@ -690,7 +692,7 @@ bool ConfigurationTable::isStatic(const std::string& key)
std::string ConfigurationTable::getStr(const std::string& key) string ConfigurationTable::getStr(const string& key)
{ {
// We need the lock because rec is a reference into the cache. // We need the lock because rec is a reference into the cache.
try { try {
@ -704,7 +706,7 @@ std::string ConfigurationTable::getStr(const std::string& key)
} }
bool ConfigurationTable::getBool(const std::string& key) bool ConfigurationTable::getBool(const string& key)
{ {
try { try {
return getNum(key) != 0; return getNum(key) != 0;
@ -716,7 +718,7 @@ bool ConfigurationTable::getBool(const std::string& key)
} }
long ConfigurationTable::getNum(const std::string& key) long ConfigurationTable::getNum(const string& key)
{ {
// We need the lock because rec is a reference into the cache. // We need the lock because rec is a reference into the cache.
try { try {
@ -730,7 +732,7 @@ long ConfigurationTable::getNum(const std::string& key)
} }
float ConfigurationTable::getFloat(const std::string& key) float ConfigurationTable::getFloat(const string& key)
{ {
try { try {
ScopedLock lock(mLock); ScopedLock lock(mLock);
@ -742,7 +744,7 @@ float ConfigurationTable::getFloat(const std::string& key)
} }
} }
std::vector<std::string> ConfigurationTable::getVectorOfStrings(const std::string& key) std::vector<string> ConfigurationTable::getVectorOfStrings(const string& key)
{ {
// Look up the string. // Look up the string.
char *line=NULL; char *line=NULL;
@ -760,7 +762,7 @@ std::vector<std::string> ConfigurationTable::getVectorOfStrings(const std::strin
char *lp = line; char *lp = line;
// Parse the string. // Parse the string.
std::vector<std::string> retVal; std::vector<string> retVal;
while (lp) { while (lp) {
while (*lp==' ') lp++; while (*lp==' ') lp++;
if (*lp == '\0') break; if (*lp == '\0') break;
@ -773,7 +775,7 @@ std::vector<std::string> ConfigurationTable::getVectorOfStrings(const std::strin
} }
std::vector<unsigned> ConfigurationTable::getVector(const std::string& key) std::vector<unsigned> ConfigurationTable::getVector(const string& key)
{ {
// Look up the string. // Look up the string.
char *line=NULL; char *line=NULL;
@ -804,7 +806,7 @@ std::vector<unsigned> ConfigurationTable::getVector(const std::string& key)
} }
bool ConfigurationTable::remove(const std::string& key) bool ConfigurationTable::remove(const string& key)
{ {
assert(mDB); assert(mDB);
@ -813,16 +815,16 @@ bool ConfigurationTable::remove(const std::string& key)
ConfigurationMap::iterator where = mCache.find(key); ConfigurationMap::iterator where = mCache.find(key);
if (where!=mCache.end()) mCache.erase(where); if (where!=mCache.end()) mCache.erase(where);
// Really remove it. // Really remove it.
std::string cmd = "DELETE FROM CONFIG WHERE KEYSTRING=='"+key+"'"; string cmd = "DELETE FROM CONFIG WHERE KEYSTRING=='"+key+"'";
return sqlite3_command(mDB,cmd.c_str()); return sqlite3_command(mDB,cmd.c_str());
} }
void ConfigurationTable::find(const std::string& pat, std::ostream& os) const void ConfigurationTable::find(const string& pat, ostream& os) const
{ {
// Prepare the statement. // Prepare the statement.
std::string cmd = "SELECT KEYSTRING,VALUESTRING FROM CONFIG WHERE KEYSTRING LIKE \"%" + pat + "%\""; string cmd = "SELECT KEYSTRING,VALUESTRING FROM CONFIG WHERE KEYSTRING LIKE \"%" + pat + "%\"";
sqlite3_stmt *stmt; sqlite3_stmt *stmt;
if (sqlite3_prepare_statement(mDB,&stmt,cmd.c_str())) return; if (sqlite3_prepare_statement(mDB,&stmt,cmd.c_str())) return;
// Read the result. // Read the result.
@ -834,8 +836,8 @@ void ConfigurationTable::find(const std::string& pat, std::ostream& os) const
if (value) { if (value) {
len = strlen(value); len = strlen(value);
} }
if (len && value) os << value << std::endl; if (len && value) os << value << endl;
else os << "(disabled)" << std::endl; else os << "(disabled)" << endl;
src = sqlite3_run_query(mDB,stmt); src = sqlite3_run_query(mDB,stmt);
} }
sqlite3_finalize(stmt); sqlite3_finalize(stmt);
@ -847,7 +849,7 @@ ConfigurationRecordMap ConfigurationTable::getAllPairs() const
ConfigurationRecordMap tmp; ConfigurationRecordMap tmp;
// Prepare the statement. // Prepare the statement.
std::string cmd = "SELECT KEYSTRING,VALUESTRING FROM CONFIG"; string cmd = "SELECT KEYSTRING,VALUESTRING FROM CONFIG";
sqlite3_stmt *stmt; sqlite3_stmt *stmt;
if (sqlite3_prepare_statement(mDB,&stmt,cmd.c_str())) return tmp; if (sqlite3_prepare_statement(mDB,&stmt,cmd.c_str())) return tmp;
// Read the result. // Read the result.
@ -856,10 +858,10 @@ ConfigurationRecordMap ConfigurationTable::getAllPairs() const
const char* key = (const char*)sqlite3_column_text(stmt,0); const char* key = (const char*)sqlite3_column_text(stmt,0);
const char* value = (const char*)sqlite3_column_text(stmt,1); const char* value = (const char*)sqlite3_column_text(stmt,1);
if (key && value) { if (key && value) {
std::string skey(key); string skey(key);
tmp[skey] = ConfigurationRecord(skey,value); tmp[skey] = ConfigurationRecord(skey,value);
} else if (key && !value) { } else if (key && !value) {
std::string skey(key); string skey(key);
tmp[skey] = ConfigurationRecord(skey,false); tmp[skey] = ConfigurationRecord(skey,false);
} }
src = sqlite3_run_query(mDB,stmt); src = sqlite3_run_query(mDB,stmt);
@ -869,11 +871,11 @@ ConfigurationRecordMap ConfigurationTable::getAllPairs() const
return tmp; return tmp;
} }
bool ConfigurationTable::set(const std::string& key, const std::string& value) bool ConfigurationTable::set(const string& key, const string& value)
{ {
assert(mDB); assert(mDB);
ScopedLock lock(mLock); ScopedLock lock(mLock);
std::string cmd; string cmd;
if (keyDefinedInSchema(key)) { if (keyDefinedInSchema(key)) {
cmd = "INSERT OR REPLACE INTO CONFIG (KEYSTRING,VALUESTRING,OPTIONAL,COMMENTS) VALUES (\"" + key + "\",\"" + value + "\",1,\'" + mSchema[key].getDescription() + "\')"; cmd = "INSERT OR REPLACE INTO CONFIG (KEYSTRING,VALUESTRING,OPTIONAL,COMMENTS) VALUES (\"" + key + "\",\"" + value + "\",1,\'" + mSchema[key].getDescription() + "\')";
} else { } else {
@ -886,7 +888,7 @@ bool ConfigurationTable::set(const std::string& key, const std::string& value)
return success; return success;
} }
bool ConfigurationTable::set(const std::string& key, long value) bool ConfigurationTable::set(const string& key, long value)
{ {
char buffer[30]; char buffer[30];
sprintf(buffer,"%ld",value); sprintf(buffer,"%ld",value);
@ -931,14 +933,14 @@ void ConfigurationTable::setUpdateHook(void(*func)(void *,int ,char const *,char
} }
void ConfigurationTable::setCrossCheckHook(std::vector<std::string> (*wCrossCheck)(const std::string&)) void ConfigurationTable::setCrossCheckHook(vector<string> (*wCrossCheck)(const string&))
{ {
mCrossCheck = wCrossCheck; mCrossCheck = wCrossCheck;
} }
std::vector<std::string> ConfigurationTable::crossCheck(const std::string& key) { vector<string> ConfigurationTable::crossCheck(const string& key) {
std::vector<std::string> ret; vector<string> ret;
if (mCrossCheck != NULL) { if (mCrossCheck != NULL) {
ret = mCrossCheck(key); ret = mCrossCheck(key);
@ -1152,7 +1154,7 @@ const std::string ConfigurationKey::typeToString(const ConfigurationKey::Type& t
return ret; return ret;
} }
void ConfigurationKey::printKey(const ConfigurationKey &key, const std::string& currentValue, std::ostream& os) { void ConfigurationKey::printKey(const ConfigurationKey &key, const std::string& currentValue, ostream& os) {
os << key.getName() << " "; os << key.getName() << " ";
if (!currentValue.length()) { if (!currentValue.length()) {
os << "(disabled)"; os << "(disabled)";
@ -1162,10 +1164,10 @@ void ConfigurationKey::printKey(const ConfigurationKey &key, const std::string&
if (currentValue.compare(key.getDefaultValue()) == 0) { if (currentValue.compare(key.getDefaultValue()) == 0) {
os << " [default]"; os << " [default]";
} }
os << std::endl; os << endl;
} }
void ConfigurationKey::printDescription(const ConfigurationKey &key, std::ostream& os) { void ConfigurationKey::printDescription(const ConfigurationKey &key, ostream& os) {
std::string tmp; std::string tmp;
unsigned scope; unsigned scope;

View File

@ -30,12 +30,14 @@
#include <iostream> #include <iostream>
#include <string> #include <string>
using namespace std;
ConfigurationKeyMap getConfigurationKeys(); ConfigurationKeyMap getConfigurationKeys();
ConfigurationTable gConfig("exampleconfig.db","test", getConfigurationKeys()); ConfigurationTable gConfig("exampleconfig.db","test", getConfigurationKeys());
void purgeConfig(void*,int,char const*, char const*, sqlite3_int64) void purgeConfig(void*,int,char const*, char const*, sqlite3_int64)
{ {
//std::cout << "update hook" << std::endl; //cout << "update hook" << endl;
gConfig.purge(); gConfig.purge();
} }
@ -52,29 +54,29 @@ int main(int argc, char *argv[])
} }
for (int i=0; i<5; i++) { for (int i=0; i<5; i++) {
std::cout << "table[" << keys[i] << "]=" << gConfig.getStr(keys[i]) << std::endl; cout << "table[" << keys[i] << "]=" << gConfig.getStr(keys[i]) << endl;
std::cout << "table[" << keys[i] << "]=" << gConfig.getNum(keys[i]) << std::endl; cout << "table[" << keys[i] << "]=" << gConfig.getNum(keys[i]) << endl;
} }
for (int i=0; i<5; i++) { for (int i=0; i<5; i++) {
std::cout << "defined table[" << keys[i] << "]=" << gConfig.defines(keys[i]) << std::endl; cout << "defined table[" << keys[i] << "]=" << gConfig.defines(keys[i]) << endl;
} }
gConfig.set("key5","100 200 300 400 "); gConfig.set("key5","100 200 300 400 ");
std::vector<unsigned> vect = gConfig.getVector("key5"); std::vector<unsigned> vect = gConfig.getVector("key5");
std::cout << "vect length " << vect.size() << ": "; cout << "vect length " << vect.size() << ": ";
for (unsigned i=0; i<vect.size(); i++) std::cout << " " << vect[i]; for (unsigned i=0; i<vect.size(); i++) cout << " " << vect[i];
std::cout << std::endl; cout << endl;
std::vector<std::string> svect = gConfig.getVectorOfStrings("key5"); std::vector<string> svect = gConfig.getVectorOfStrings("key5");
std::cout << "vect length " << svect.size() << ": "; cout << "vect length " << svect.size() << ": ";
for (unsigned i=0; i<svect.size(); i++) std::cout << " " << svect[i] << ":"; for (unsigned i=0; i<svect.size(); i++) cout << " " << svect[i] << ":";
std::cout << std::endl; cout << endl;
std::cout << "bool " << gConfig.getBool("booltest") << std::endl; cout << "bool " << gConfig.getBool("booltest") << endl;
gConfig.set("booltest",1); gConfig.set("booltest",1);
std::cout << "bool " << gConfig.getBool("booltest") << std::endl; cout << "bool " << gConfig.getBool("booltest") << endl;
gConfig.set("booltest",0); gConfig.set("booltest",0);
std::cout << "bool " << gConfig.getBool("booltest") << std::endl; cout << "bool " << gConfig.getBool("booltest") << endl;
gConfig.getStr("newstring"); gConfig.getStr("newstring");
gConfig.getNum("numnumber"); gConfig.getNum("numnumber");
@ -82,26 +84,26 @@ int main(int argc, char *argv[])
SimpleKeyValue pairs; SimpleKeyValue pairs;
pairs.addItems(" a=1 b=34 dd=143 "); pairs.addItems(" a=1 b=34 dd=143 ");
std::cout<< pairs.get("a") << std::endl; cout<< pairs.get("a") << endl;
std::cout<< pairs.get("b") << std::endl; cout<< pairs.get("b") << endl;
std::cout<< pairs.get("dd") << std::endl; cout<< pairs.get("dd") << endl;
gConfig.set("fkey","123.456"); gConfig.set("fkey","123.456");
float fval = gConfig.getFloat("fkey"); float fval = gConfig.getFloat("fkey");
std::cout << "fkey " << fval << std::endl; cout << "fkey " << fval << endl;
std::cout << "search fkey:" << std::endl; cout << "search fkey:" << endl;
gConfig.find("fkey",std::cout); gConfig.find("fkey",cout);
std::cout << "search fkey:" << std::endl; cout << "search fkey:" << endl;
gConfig.find("fkey",std::cout); gConfig.find("fkey",cout);
gConfig.remove("fkey"); gConfig.remove("fkey");
std::cout << "search fkey:" << std::endl; cout << "search fkey:" << endl;
gConfig.find("fkey",std::cout); gConfig.find("fkey",cout);
try { try {
gConfig.getNum("supposedtoabort"); gConfig.getNum("supposedtoabort");
} catch (ConfigurationTableKeyNotFound) { } catch (ConfigurationTableKeyNotFound) {
std::cout << "ConfigurationTableKeyNotFound exception successfully caught." << std::endl; cout << "ConfigurationTableKeyNotFound exception successfully caught." << endl;
} }
} }

View File

@ -28,6 +28,8 @@
#include <iostream> #include <iostream>
using namespace std;
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
@ -36,18 +38,18 @@ int main(int argc, char **argv)
F16 c = 2.5 * 1.5; F16 c = 2.5 * 1.5;
F16 d = c + a; F16 d = c + a;
F16 e = 10; F16 e = 10;
std::cout << a << ' ' << b << ' ' << c << ' ' << d << ' ' << e << std::endl; cout << a << ' ' << b << ' ' << c << ' ' << d << ' ' << e << endl;
a *= 3; a *= 3;
b *= 0.3; b *= 0.3;
c *= e; c *= e;
std::cout << a << ' ' << b << ' ' << c << ' ' << d << std::endl; cout << a << ' ' << b << ' ' << c << ' ' << d << endl;
a /= 3; a /= 3;
b /= 0.3; b /= 0.3;
c = d * 0.05; c = d * 0.05;
std::cout << a << ' ' << b << ' ' << c << ' ' << d << std::endl; cout << a << ' ' << b << ' ' << c << ' ' << d << endl;
F16 f = a/d; F16 f = a/d;
std::cout << f << ' ' << f+0.5 << std::endl; cout << f << ' ' << f+0.5 << endl;
} }

View File

@ -31,6 +31,8 @@
#include "Configuration.h" #include "Configuration.h"
ConfigurationTable gConfig; ConfigurationTable gConfig;
using namespace std;
InterthreadQueue<int> gQ; InterthreadQueue<int> gQ;
InterthreadMap<int,int> gMap; InterthreadMap<int,int> gMap;

View File

@ -36,6 +36,8 @@
#include "Threads.h" // pat added #include "Threads.h" // pat added
using namespace std;
// Reference to a global config table, used all over the system. // Reference to a global config table, used all over the system.
extern ConfigurationTable gConfig; extern ConfigurationTable gConfig;
@ -43,8 +45,8 @@ extern ConfigurationTable gConfig;
/**@ The global alarms table. */ /**@ The global alarms table. */
//@{ //@{
Mutex alarmsLock; Mutex alarmsLock;
std::list<std::string> alarmsList; list<string> alarmsList;
void addAlarm(const std::string&); void addAlarm(const string&);
//@} //@}
// (pat 3-2014) Note that the logger is used by multiple programs. // (pat 3-2014) Note that the logger is used by multiple programs.
@ -73,7 +75,7 @@ Mutex gLogToLock;
LogGroup gLogGroup; LogGroup gLogGroup;
int levelStringToInt(const std::string& name) int levelStringToInt(const string& name)
{ {
// Reverse search, since the numerically larger levels are more common. // Reverse search, since the numerically larger levels are more common.
for (int i=numLevels-1; i>=0; i--) { for (int i=numLevels-1; i>=0; i--) {
@ -92,13 +94,13 @@ int levelStringToInt(const std::string& name)
} }
/** Given a string, return the corresponding level name. */ /** Given a string, return the corresponding level name. */
int lookupLevel(const std::string& key) int lookupLevel(const string& key)
{ {
std::string val = gConfig.getStr(key); string val = gConfig.getStr(key);
int level = levelStringToInt(val); int level = levelStringToInt(val);
if (level == -1) { if (level == -1) {
std::string defaultLevel = gConfig.mSchema["Log.Level"].getDefaultValue(); string defaultLevel = gConfig.mSchema["Log.Level"].getDefaultValue();
level = levelStringToInt(defaultLevel); level = levelStringToInt(defaultLevel);
_LOG(CRIT) << "undefined logging level (" << key << " = \"" << val << "\") defaulting to \"" << defaultLevel << ".\" Valid levels are: EMERG, ALERT, CRIT, ERR, WARNING, NOTICE, INFO or DEBUG"; _LOG(CRIT) << "undefined logging level (" << key << " = \"" << val << "\") defaulting to \"" << defaultLevel << ".\" Valid levels are: EMERG, ALERT, CRIT, ERR, WARNING, NOTICE, INFO or DEBUG";
gConfig.set(key, defaultLevel); gConfig.set(key, defaultLevel);
@ -114,7 +116,7 @@ int getLoggingLevel(const char* filename)
if (!filename) return lookupLevel("Log.Level"); if (!filename) return lookupLevel("Log.Level");
// This can afford to be inefficient since it is not called that often. // This can afford to be inefficient since it is not called that often.
const std::string keyName = std::string("Log.Level.") + std::string(filename); const string keyName = string("Log.Level.") + string(filename);
if (gConfig.defines(keyName)) return lookupLevel(keyName); if (gConfig.defines(keyName)) return lookupLevel(keyName);
return lookupLevel("Log.Level"); return lookupLevel("Log.Level");
} }
@ -122,7 +124,7 @@ int getLoggingLevel(const char* filename)
//bool gCheckGroupLogLevel(const char *groupname, int loglevel) //bool gCheckGroupLogLevel(const char *groupname, int loglevel)
//{ //{
// // Gag me // // Gag me
// std::string keyName = std::string("Log.Group.") + groupname; // string keyName = string("Log.Group.") + groupname;
// return gConfig.defines(keyName) ? (lookupLevel(gConfig.getStr(keyName)) >= loglevel) : false; // return gConfig.defines(keyName) ? (lookupLevel(gConfig.getStr(keyName)) >= loglevel) : false;
//} //}
@ -133,7 +135,7 @@ int gGetLoggingLevel(const char* filename)
// This is called a lot and needs to be efficient. // This is called a lot and needs to be efficient.
static Mutex sLogCacheLock; static Mutex sLogCacheLock;
static std::map<uint64_t,int> sLogCache; static map<uint64_t,int> sLogCache;
static unsigned sCacheCount; static unsigned sCacheCount;
static const unsigned sCacheRefreshCount = 1000; static const unsigned sCacheRefreshCount = 1000;
@ -149,7 +151,7 @@ int gGetLoggingLevel(const char* filename)
sCacheCount=0; sCacheCount=0;
} }
// Is it cached already? // Is it cached already?
std::map<uint64_t,int>::const_iterator where = sLogCache.find(key); map<uint64_t,int>::const_iterator where = sLogCache.find(key);
sCacheCount++; sCacheCount++;
if (where!=sLogCache.end()) { if (where!=sLogCache.end()) {
int retVal = where->second; int retVal = where->second;
@ -162,7 +164,7 @@ int gGetLoggingLevel(const char* filename)
sLogCacheLock.unlock(); sLogCacheLock.unlock();
int level = getLoggingLevel(filename); int level = getLoggingLevel(filename);
sLogCacheLock.lock(); sLogCacheLock.lock();
sLogCache.insert(std::pair<uint64_t,int>(key,level)); sLogCache.insert(pair<uint64_t,int>(key,level));
sLogCacheLock.unlock(); sLogCacheLock.unlock();
return level; return level;
} }
@ -172,20 +174,20 @@ int gGetLoggingLevel(const char* filename)
// copies the alarm list and returns it. list supposed to be small. // copies the alarm list and returns it. list supposed to be small.
std::list<std::string> gGetLoggerAlarms() list<string> gGetLoggerAlarms()
{ {
alarmsLock.lock(); alarmsLock.lock();
std::list<std::string> ret; list<string> ret;
// excuse the "complexity", but to use std::copy with a list you need // excuse the "complexity", but to use std::copy with a list you need
// an insert_iterator - copy technically overwrites, doesn't insert. // an insert_iterator - copy technically overwrites, doesn't insert.
std::insert_iterator< std::list<std::string> > ii(ret, ret.begin()); insert_iterator< list<string> > ii(ret, ret.begin());
copy(alarmsList.begin(), alarmsList.end(), ii); copy(alarmsList.begin(), alarmsList.end(), ii);
alarmsLock.unlock(); alarmsLock.unlock();
return ret; return ret;
} }
/** Add an alarm to the alarm list. */ /** Add an alarm to the alarm list. */
void addAlarm(const std::string& s) void addAlarm(const string& s)
{ {
alarmsLock.lock(); alarmsLock.lock();
alarmsList.push_back(s); alarmsList.push_back(s);
@ -202,7 +204,7 @@ Log::~Log()
// Save alarms in the local list and echo them to stderr. // Save alarms in the local list and echo them to stderr.
if (mPriority <= LOG_CRIT) { if (mPriority <= LOG_CRIT) {
if (sLoggerInited) addAlarm(mStream.str().c_str()); if (sLoggerInited) addAlarm(mStream.str().c_str());
std::cerr << mStream.str() << std::endl; cerr << mStream.str() << endl;
} }
// Current logging level was already checked by the macro. // Current logging level was already checked by the macro.
// So just log. // So just log.
@ -244,7 +246,7 @@ Log::Log(const char* name, const char* level, int facility)
} }
std::ostringstream& Log::get() ostringstream& Log::get()
{ {
assert(mPriority<numLevels); assert(mPriority<numLevels);
mStream << levelNames[mPriority] << ' '; mStream << levelNames[mPriority] << ' ';
@ -291,7 +293,7 @@ void gLogInit(const char* name, const char* level, int facility)
// Pat added, tired of the syslog facility. // Pat added, tired of the syslog facility.
// Both the transceiver and OpenBTS use this same facility, but only OpenBTS/OpenNodeB may use this log file: // Both the transceiver and OpenBTS use this same facility, but only OpenBTS/OpenNodeB may use this log file:
std::string str = gConfig.getStr("Log.File"); string str = gConfig.getStr("Log.File");
if (gLogToFile==0 && str.length() && 0==strncmp(gCmdName,"Open",4)) { if (gLogToFile==0 && str.length() && 0==strncmp(gCmdName,"Open",4)) {
const char *fn = str.c_str(); const char *fn = str.c_str();
if (fn && *fn && strlen(fn)>3) { // strlen because a garbage char is getting in sometimes. if (fn && *fn && strlen(fn)>3) { // strlen because a garbage char is getting in sometimes.
@ -371,7 +373,7 @@ static const char *LogGroupPrefix = "Log.Group.";
#if UNUSED #if UNUSED
// Return true if this was a LogGroup config parameter. // Return true if this was a LogGroup config parameter.
// These dont have to be fast. // These dont have to be fast.
bool LogGroup::setGroup(const std::string groupName, const std::string levelName) bool LogGroup::setGroup(const string groupName, const string levelName)
{ {
const int len = strlen(LogGroupPrefix); const int len = strlen(LogGroupPrefix);
if (0 != strncasecmp(groupName.c_str(),LogGroupPrefix,len)) { return false; } if (0 != strncasecmp(groupName.c_str(),LogGroupPrefix,len)) { return false; }
@ -383,13 +385,13 @@ bool LogGroup::setGroup(const std::string groupName, const std::string levelName
} }
//GroupMapType::iterator it = mGroupNameToIndex.find(groupName); //GroupMapType::iterator it = mGroupNameToIndex.find(groupName);
//if (it != std::map::end) { //if (it != map::end) {
// mDebugLevel[it->second] = lookupLevel(levelName); // mDebugLevel[it->second] = lookupLevel(levelName);
//} //}
return true; return true;
} }
bool LogGroup::unsetGroup(const std::string groupName) bool LogGroup::unsetGroup(const string groupName)
{ {
const int len = strlen(LogGroupPrefix); const int len = strlen(LogGroupPrefix);
if (0 != strncasecmp(groupName.c_str(),LogGroupPrefix,len)) { return false; } if (0 != strncasecmp(groupName.c_str(),LogGroupPrefix,len)) { return false; }
@ -401,7 +403,7 @@ bool LogGroup::unsetGroup(const std::string groupName)
} }
//GroupMapType::iterator it = mGroupNameToIndex.find(groupName); //GroupMapType::iterator it = mGroupNameToIndex.find(groupName);
//if (it != std::map::end) { //if (it != map::end) {
// mDebugLevel[it->second] = lookupLevel(levelName); // mDebugLevel[it->second] = lookupLevel(levelName);
//} //}
return true; return true;
@ -411,11 +413,11 @@ bool LogGroup::unsetGroup(const std::string groupName)
void LogGroup::setAll() void LogGroup::setAll()
{ {
LOG(DEBUG); LOG(DEBUG);
std::string prefix = std::string(LogGroupPrefix); string prefix = string(LogGroupPrefix);
for (unsigned g = 0; g < _NumberOfLogGroups; g++) { for (unsigned g = 0; g < _NumberOfLogGroups; g++) {
std::string param = prefix + mGroupNames[g]; string param = prefix + mGroupNames[g];
if (gConfig.defines(param)) { if (gConfig.defines(param)) {
std::string levelName = gConfig.getStr(param); string levelName = gConfig.getStr(param);
LOG(DEBUG) << "Setting "<<LOGVAR(param)<<LOGVAR(levelName); LOG(DEBUG) << "Setting "<<LOGVAR(param)<<LOGVAR(levelName);
//mDebugLevel[g] = lookupLevel(levelName); //mDebugLevel[g] = lookupLevel(levelName);
mDebugLevel[g] = levelStringToInt(levelName); mDebugLevel[g] = levelStringToInt(levelName);

View File

@ -135,8 +135,7 @@ class Log {
Log(int wPriority) Log(int wPriority)
:mPriority(wPriority), mDummyInit(false) :mPriority(wPriority), mDummyInit(false)
{ { }
}
// (pat) This constructor is not used to construct a Log record, it is called once per application // (pat) This constructor is not used to construct a Log record, it is called once per application
// to init the syslog facility. This is a very poor use of C++. // to init the syslog facility. This is a very poor use of C++.

View File

@ -28,6 +28,8 @@
#include "Regexp.h" #include "Regexp.h"
#include <iostream> #include <iostream>
using namespace std;
int main(int argc, char *argv[]) int main(int argc, char *argv[])
{ {
@ -38,9 +40,9 @@ int main(int argc, char *argv[])
const char text1[] = "dburgess@jcis.net test message"; const char text1[] = "dburgess@jcis.net test message";
const char text2[] = "no address text message"; const char text2[] = "no address text message";
std::cout << email.match(text1) << " " << text1 << std::endl; cout << email.match(text1) << " " << text1 << endl;
std::cout << email.match(text2) << " " << text2 << std::endl; cout << email.match(text2) << " " << text2 << endl;
std::cout << simple.match(text1) << " " << text1 << std::endl; cout << simple.match(text1) << " " << text1 << endl;
std::cout << simple.match(text2) << " " << text2 << std::endl; cout << simple.match(text2) << " " << text2 << endl;
} }

View File

@ -33,6 +33,8 @@
#include <errno.h> #include <errno.h>
using namespace std;
int gMutexLogLevel = LOG_INFO; // The mutexes cannot call gConfig or gGetLoggingLevel so we have to get the log level indirectly. int gMutexLogLevel = LOG_INFO; // The mutexes cannot call gConfig or gGetLoggingLevel so we have to get the log level indirectly.
@ -49,13 +51,13 @@ void lockCout()
{ {
gStreamLock.lock(); gStreamLock.lock();
Timeval entryTime; Timeval entryTime;
std::cout << entryTime << " " << pthread_self() << ": "; cout << entryTime << " " << pthread_self() << ": ";
} }
void unlockCout() void unlockCout()
{ {
std::cout << std::dec << std::endl << std::flush; cout << dec << endl << flush;
gStreamLock.unlock(); gStreamLock.unlock();
} }
@ -64,12 +66,12 @@ void lockCerr()
{ {
gStreamLock.lock(); gStreamLock.lock();
Timeval entryTime; Timeval entryTime;
std::cerr << entryTime << " " << pthread_self() << ": "; cerr << entryTime << " " << pthread_self() << ": ";
} }
void unlockCerr() void unlockCerr()
{ {
std::cerr << std::dec << std::endl << std::flush; cerr << dec << endl << flush;
gStreamLock.unlock(); gStreamLock.unlock();
} }
@ -119,9 +121,9 @@ bool Mutex::timedlock(int msecs) // Wait this long in milli-seconds.
return ETIMEDOUT != pthread_mutex_timedlock(&mMutex, &timeout); return ETIMEDOUT != pthread_mutex_timedlock(&mMutex, &timeout);
} }
std::string Mutex::mutext() const string Mutex::mutext() const
{ {
std::string result; string result;
result.reserve(100); result.reserve(100);
//result += format("lockid=%u lockcnt=%d",(unsigned)this,mLockCnt); //result += format("lockid=%u lockcnt=%d",(unsigned)this,mLockCnt);
result += format("lockcnt=%d",mLockCnt); result += format("lockcnt=%d",mLockCnt);

View File

@ -27,6 +27,8 @@
#include "Timeval.h" #include "Timeval.h"
using namespace std;
void Timeval::future(unsigned offset) // In msecs void Timeval::future(unsigned offset) // In msecs
{ {
now(); now();
@ -77,15 +79,15 @@ long Timeval::delta(const Timeval& other) const
std::ostream& operator<<(std::ostream& os, const Timeval& tv) ostream& operator<<(ostream& os, const Timeval& tv)
{ {
os.setf( std::ios::fixed, std::ios::floatfield ); os.setf( ios::fixed, ios::floatfield );
os << tv.seconds(); os << tv.seconds();
return os; return os;
} }
std::ostream& operator<<(std::ostream& os, const struct timespec& ts) ostream& operator<<(ostream& os, const struct timespec& ts)
{ {
os << ts.tv_sec << "," << ts.tv_nsec; os << ts.tv_sec << "," << ts.tv_nsec;
return os; return os;

View File

@ -29,15 +29,17 @@
#include "Timeval.h" #include "Timeval.h"
#include <iostream> #include <iostream>
using namespace std;
int main(int argc, char *argv[]) int main(int argc, char *argv[])
{ {
Timeval then(10000); Timeval then(10000);
std::cout << then.elapsed() << std::endl; cout << then.elapsed() << endl;
while (!then.passed()) { while (!then.passed()) {
std::cout << "now: " << Timeval() << " then: " << then << " remaining: " << then.remaining() << std::endl; cout << "now: " << Timeval() << " then: " << then << " remaining: " << then.remaining() << endl;
usleep(500000); usleep(500000);
} }
std::cout << "now: " << Timeval() << " then: " << then << " remaining: " << then.remaining() << std::endl; cout << "now: " << Timeval() << " then: " << then << " remaining: " << then.remaining() << endl;
} }

View File

@ -5,11 +5,13 @@
#include <string.h> #include <string.h>
#include <ctype.h> #include <ctype.h>
using namespace std;
//based on javascript encodeURIComponent() //based on javascript encodeURIComponent()
std::string URLEncode(const std::string &c) string URLEncode(const string &c)
{ {
static const char *digits = "01234567890ABCDEF"; static const char *digits = "01234567890ABCDEF";
std::string retVal=""; string retVal="";
for (size_t i=0; i<c.length(); i++) for (size_t i=0; i<c.length(); i++)
{ {
const char ch = c[i]; const char ch = c[i];

View File

@ -4,11 +4,14 @@
#include <iostream> #include <iostream>
using namespace std;
int main(int argc, char *argv[]) int main(int argc, char *argv[])
{ {
std::string test = std::string("Testing: !@#$%^&*() " __DATE__ " " __TIME__); string test = string("Testing: !@#$%^&*() " __DATE__ " " __TIME__);
std::cout << test << std::endl; cout << test << endl;
std::cout << URLEncode(test) << std::endl; cout << URLEncode(test) << endl;
} }

143
Utils.cpp
View File

@ -26,6 +26,7 @@
#include "MemoryLeak.h" #include "MemoryLeak.h"
namespace Utils { namespace Utils {
using namespace std;
// (pat) This definition must be in the .cpp file to anchor the class vtable. // (pat) This definition must be in the .cpp file to anchor the class vtable.
RefCntBase::~RefCntBase() { LOG(DEBUG) << typeid(this).name(); } RefCntBase::~RefCntBase() { LOG(DEBUG) << typeid(this).name(); }
@ -67,7 +68,7 @@ MemStats::MemStats()
memset(mMemName,0,sizeof(mMemName)); memset(mMemName,0,sizeof(mMemName));
} }
void MemStats::text(std::ostream &os) void MemStats::text(ostream &os)
{ {
os << "Structs current total:\n"; os << "Structs current total:\n";
for (int i = 0; i < mMax; i++) { for (int i = 0; i < mMax; i++) {
@ -77,7 +78,7 @@ void MemStats::text(std::ostream &os)
void MemStats::memChkNew(MemoryNames memIndex, const char *id) void MemStats::memChkNew(MemoryNames memIndex, const char *id)
{ {
/*std::cout << "new " #type "\n";*/ /*cout << "new " #type "\n";*/
ScopedLock lock(memChkLock); ScopedLock lock(memChkLock);
mMemNow[memIndex]++; mMemNow[memIndex]++;
mMemTotal[memIndex]++; mMemTotal[memIndex]++;
@ -87,7 +88,7 @@ void MemStats::memChkNew(MemoryNames memIndex, const char *id)
void MemStats::memChkDel(MemoryNames memIndex, const char *id) void MemStats::memChkDel(MemoryNames memIndex, const char *id)
{ {
ScopedLock lock(memChkLock); ScopedLock lock(memChkLock);
/*std::cout << "del " #type "\n";*/ /*cout << "del " #type "\n";*/
mMemNow[memIndex]--; mMemNow[memIndex]--;
if (mMemNow[memIndex] < 0) { if (mMemNow[memIndex] < 0) {
LOG(ERR) << "Memory reference count underflow on type "<<id; LOG(ERR) << "Memory reference count underflow on type "<<id;
@ -96,12 +97,12 @@ void MemStats::memChkDel(MemoryNames memIndex, const char *id)
} }
} }
std::ostream& operator<<(std::ostream& os, std::ostringstream& ss) ostream& operator<<(std::ostream& os, std::ostringstream& ss)
{ {
return os << ss.str(); return os << ss.str();
} }
std::ostream &osprintf(std::ostream &os, const char *fmt, ...) ostream &osprintf(std::ostream &os, const char *fmt, ...)
{ {
va_list ap; va_list ap;
char buf[300]; char buf[300];
@ -113,16 +114,16 @@ std::ostream &osprintf(std::ostream &os, const char *fmt, ...)
return os; return os;
} }
std::string format(const char *fmt, ...) string format(const char *fmt, ...)
{ {
va_list ap; va_list ap;
char buf[200]; char buf[200];
va_start(ap,fmt); va_start(ap,fmt);
int n = vsnprintf(buf,199,fmt,ap); int n = vsnprintf(buf,199,fmt,ap);
va_end(ap); va_end(ap);
std::string result; string result;
if (n <= 199) { if (n <= 199) {
result = std::string(buf); result = string(buf);
} else { } else {
if (n > 5000) { LOG(ERR) << "oversized string in format"; n = 5000; } if (n > 5000) { LOG(ERR) << "oversized string in format"; n = 5000; }
// We could use vasprintf but we already computed the length... // We could use vasprintf but we already computed the length...
@ -132,12 +133,12 @@ std::string format(const char *fmt, ...)
vsnprintf(buffer,n+1,fmt,ap); vsnprintf(buffer,n+1,fmt,ap);
va_end(ap); va_end(ap);
//if (n >= (2000-4)) { strcpy(&buf[(2000-4)],"..."); } //if (n >= (2000-4)) { strcpy(&buf[(2000-4)],"..."); }
result = std::string(buffer); result = string(buffer);
free(buffer); free(buffer);
} }
return result; return result;
#if 0 // Maybe ok, but not recommended. data() is const char* #if 0 // Maybe ok, but not recommended. data() is const char*
std::string result; string result;
va_list ap; va_list ap;
va_start(ap,fmt); va_start(ap,fmt);
result.reserve(200); result.reserve(200);
@ -156,16 +157,16 @@ std::string format(const char *fmt, ...)
} }
// Absolutely identical to format above. This sucks... // Absolutely identical to format above. This sucks...
std::string format1(const char *fmt, ...) string format1(const char *fmt, ...)
{ {
va_list ap; va_list ap;
char buf[200]; char buf[200];
va_start(ap,fmt); va_start(ap,fmt);
int n = vsnprintf(buf,199,fmt,ap); int n = vsnprintf(buf,199,fmt,ap);
va_end(ap); va_end(ap);
std::string result; string result;
if (n <= 199) { if (n <= 199) {
result = std::string(buf); result = string(buf);
} else { } else {
if (n > 5000) { LOG(ERR) << "oversized string in format"; n = 5000; } if (n > 5000) { LOG(ERR) << "oversized string in format"; n = 5000; }
// We could use vasprintf but we already computed the length... // We could use vasprintf but we already computed the length...
@ -175,13 +176,13 @@ std::string format1(const char *fmt, ...)
vsnprintf(buffer,n+1,fmt,ap); vsnprintf(buffer,n+1,fmt,ap);
va_end(ap); va_end(ap);
//if (n >= (2000-4)) { strcpy(&buf[(2000-4)],"..."); } //if (n >= (2000-4)) { strcpy(&buf[(2000-4)],"..."); }
result = std::string(buffer); result = string(buffer);
free(buffer); free(buffer);
} }
return result; return result;
} }
int myscanf(const char *str, const char *fmt, std::string *s1) int myscanf(const char *str, const char *fmt, string *s1)
{ {
int maxlen = strlen(str)+1; int maxlen = strlen(str)+1;
char *a1 = (char*)alloca(maxlen); char *a1 = (char*)alloca(maxlen);
@ -189,7 +190,7 @@ int myscanf(const char *str, const char *fmt, std::string *s1)
s1->assign(a1); s1->assign(a1);
return n; return n;
} }
int myscanf(const char *str, const char *fmt, std::string *s1, std::string *s2) int myscanf(const char *str, const char *fmt, string *s1, string *s2)
{ {
int maxlen = strlen(str)+1; int maxlen = strlen(str)+1;
char *a1 = (char*)alloca(maxlen); char *a1 = (char*)alloca(maxlen);
@ -201,7 +202,7 @@ int myscanf(const char *str, const char *fmt, std::string *s1, std::string *s2)
} }
return n; return n;
} }
int myscanf(const char *str, const char *fmt, std::string *s1, std::string *s2, std::string *s3) int myscanf(const char *str, const char *fmt, string *s1, string *s2, string *s3)
{ {
int maxlen = strlen(str)+1; int maxlen = strlen(str)+1;
char *a1 = (char*)alloca(maxlen); char *a1 = (char*)alloca(maxlen);
@ -215,7 +216,7 @@ int myscanf(const char *str, const char *fmt, std::string *s1, std::string *s2,
} }
return n; return n;
} }
int myscanf(const char *str, const char *fmt, std::string *s1, std::string *s2, std::string *s3, std::string *s4) int myscanf(const char *str, const char *fmt, string *s1, string *s2, string *s3, string *s4)
{ {
int maxlen = strlen(str)+1; int maxlen = strlen(str)+1;
char *a1 = (char*)alloca(maxlen); char *a1 = (char*)alloca(maxlen);
@ -233,25 +234,25 @@ int myscanf(const char *str, const char *fmt, std::string *s1, std::string *s2,
} }
#if 0 #if 0
std::string format(const char *fmt, std::string s1) { string format(const char *fmt, string s1) {
return format(fmt,s1.c_str()); return format(fmt,s1.c_str());
} }
std::string format(const char *fmt, std::string s1, std::string s2) { string format(const char *fmt, string s1, string s2) {
return format(fmt,s1.c_str(),s2.c_str()); return format(fmt,s1.c_str(),s2.c_str());
} }
std::string format(const char *fmt, std::string s1, std::string s2, std::string s3) { string format(const char *fmt, string s1, string s2, string s3) {
return format(fmt,s1.c_str(),s2.c_str(),s3.c_str()); return format(fmt,s1.c_str(),s2.c_str(),s3.c_str());
} }
std::string format(const char *fmt, std::string s1, int i1) { string format(const char *fmt, string s1, int i1) {
return format(fmt,s1.c_str(),i1); return format(fmt,s1.c_str(),i1);
} }
std::string format(const char *fmt, int i1, std::string s1) { string format(const char *fmt, int i1, string s1) {
return format(fmt,i1,s1.c_str()); return format(fmt,i1,s1.c_str());
} }
std::string format(const char *fmt, std::string s1, std::string s2, int i1) { string format(const char *fmt, string s1, string s2, int i1) {
return format(fmt,s1.c_str(),s2.c_str(),i1); return format(fmt,s1.c_str(),s2.c_str(),i1);
} }
std::string format(const char *fmt, std::string s1, std::string s2, int i1, int i2) { string format(const char *fmt, string s1, string s2, int i1, int i2) {
return format(fmt,s1.c_str(),s2.c_str(),i1,i2); return format(fmt,s1.c_str(),s2.c_str(),i1,i2);
} }
#endif #endif
@ -265,14 +266,14 @@ double timef()
return tv.tv_usec / 1000000.0 + tv.tv_sec; return tv.tv_usec / 1000000.0 + tv.tv_sec;
} }
const std::string timestr(unsigned fieldwidth, bool addDate) // Use to pick the number of chars in the output. const string timestr(unsigned fieldwidth, bool addDate) // Use to pick the number of chars in the output.
{ {
struct timeval tv; struct timeval tv;
struct tm tm; struct tm tm;
gettimeofday(&tv,NULL); gettimeofday(&tv,NULL);
localtime_r(&tv.tv_sec,&tm); localtime_r(&tv.tv_sec,&tm);
unsigned tenths = tv.tv_usec / 100000; // Rounding down is ok. unsigned tenths = tv.tv_usec / 100000; // Rounding down is ok.
std::string result; string result;
if (addDate) if (addDate)
result = format(" %04d/%02d/%02d %02d:%02d:%02d.%1d", result = format(" %04d/%02d/%02d %02d:%02d:%02d.%1d",
tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
@ -288,7 +289,7 @@ const std::string timestr(unsigned fieldwidth, bool addDate) // Use to pick the
//} //}
} }
const std::string timestr() { return timestr(12); } const string timestr() { return timestr(12); }
// High resolution sleep for the specified time. // High resolution sleep for the specified time.
// Return FALSE if time is already past. // Return FALSE if time is already past.
@ -307,16 +308,16 @@ void sleepf(double howlong)
//sleepf(sleeptime); //sleepf(sleeptime);
//} //}
std::string Text2Str::str() const string Text2Str::str() const
{ {
std::ostringstream ss; ostringstream ss;
text(ss); text(ss);
return ss.str(); return ss.str();
} }
std::ostream& operator<<(std::ostream& os, const Text2Str *val) ostream& operator<<(std::ostream& os, const Text2Str *val)
{ {
std::ostringstream ss; ostringstream ss;
if (val) { if (val) {
val->text(ss); val->text(ss);
os << ss.str(); os << ss.str();
@ -385,7 +386,7 @@ char *cstrGetArg(const char *in, int nth, unsigned *length)
} }
std::vector<std::string>& stringSplit(std::vector<std::string> &result,const char *input) vector<string>& stringSplit(vector<string> &result,const char *input)
{ {
char *argv[40]; char *argv[40];
//char buf[202]; //char buf[202];
@ -393,18 +394,18 @@ std::vector<std::string>& stringSplit(std::vector<std::string> &result,const cha
char *buf = strdup(input); char *buf = strdup(input);
int cnt = cstrSplit(buf,argv,40,NULL); int cnt = cstrSplit(buf,argv,40,NULL);
for (int i = 0; i < cnt; i++) { for (int i = 0; i < cnt; i++) {
result.push_back(std::string(argv[i])); result.push_back(string(argv[i]));
} }
free(buf); free(buf);
return result; return result;
} }
// Print a table formatted as a std::vector of vector of strings. // Print a table formatted as a vector of vector of strings.
// The columns will be aligned. // The columns will be aligned.
// Column size is determined from the columns. // Column size is determined from the columns.
// An entry of "_" is suppressed. // An entry of "_" is suppressed.
void printPrettyTable(prettyTable_t &tab, std::ostream&os, bool tabSeparated) void printPrettyTable(prettyTable_t &tab, ostream&os, bool tabSeparated)
{ {
LOG(DEBUG); LOG(DEBUG);
const unsigned maxcols = 30; const unsigned maxcols = 30;
@ -412,17 +413,17 @@ void printPrettyTable(prettyTable_t &tab, std::ostream&os, bool tabSeparated)
int width[maxcols]; memset(width,0,sizeof(width)); int width[maxcols]; memset(width,0,sizeof(width));
if (!tabSeparated) { if (!tabSeparated) {
for (prettyTable_t::iterator it = tab.begin(); it != tab.end(); ++it) { for (prettyTable_t::iterator it = tab.begin(); it != tab.end(); ++it) {
std::vector<std::string> &row = *it; vector<string> &row = *it;
for (unsigned col = 0; col<maxcols && col<row.size(); col++) { for (unsigned col = 0; col<maxcols && col<row.size(); col++) {
int colwidth = row[col].size(); int colwidth = row[col].size();
if (colwidth > 100) colwidth = 100; if (colwidth > 100) colwidth = 100;
width[col] = std::max(width[col],colwidth); width[col] = max(width[col],colwidth);
} }
} }
} }
// Now print it. // Now print it.
for (unsigned nrow = 0; nrow < tab.size(); nrow++) { for (unsigned nrow = 0; nrow < tab.size(); nrow++) {
std::vector<std::string> &row = tab[nrow]; vector<string> &row = tab[nrow];
// DEBUG: print the column widths. // DEBUG: print the column widths.
if (0 && IS_LOG_LEVEL(DEBUG) && nrow == 0) { if (0 && IS_LOG_LEVEL(DEBUG) && nrow == 0) {
@ -450,25 +451,25 @@ void printPrettyTable(prettyTable_t &tab, std::ostream&os, bool tabSeparated)
} }
os << "\n"; os << "\n";
} }
os << std::endl; os << endl;
} }
std::ostream& operator<<(std::ostream& os, const Statistic<int> &stat) { stat.text(os); return os; } ostream& operator<<(std::ostream& os, const Statistic<int> &stat) { stat.text(os); return os; }
std::ostream& operator<<(std::ostream& os, const Statistic<unsigned> &stat) { stat.text(os); return os; } ostream& operator<<(std::ostream& os, const Statistic<unsigned> &stat) { stat.text(os); return os; }
std::ostream& operator<<(std::ostream& os, const Statistic<float> &stat) { stat.text(os); return os; } ostream& operator<<(std::ostream& os, const Statistic<float> &stat) { stat.text(os); return os; }
std::ostream& operator<<(std::ostream& os, const Statistic<double> &stat) { stat.text(os); return os; } ostream& operator<<(std::ostream& os, const Statistic<double> &stat) { stat.text(os); return os; }
std::string replaceAll(const std::string input, const std::string search, const std::string replace) string replaceAll(const std::string input, const std::string search, const std::string replace)
{ {
std::string output = input; string output = input;
unsigned index1 = 0; unsigned index1 = 0;
while (index1 < output.size()) { while (index1 < output.size()) {
try { try {
index1 = output.find(search, index1); index1 = output.find(search, index1);
if (index1 == std::string::npos) { if (index1 == string::npos) {
break; break;
} }
@ -485,9 +486,9 @@ std::string replaceAll(const std::string input, const std::string search, const
} }
// Efficient string concatenation. // Efficient string concatenation.
std::string stringcat(std::string a, std::string b, std::string c, std::string d, std::string e, std::string f, std::string g) string stringcat(string a, string b, string c, string d, string e, string f, string g)
{ {
std::string result; string result;
result.reserve(a.size() + b.size() + c.size() + d.size() + e.size() + f.size() + g.size()); result.reserve(a.size() + b.size() + c.size() + d.size() + e.size() + f.size() + g.size());
result.append(a); result.append(a);
result.append(b); result.append(b);
@ -499,58 +500,58 @@ std::string stringcat(std::string a, std::string b, std::string c, std::string d
return result; return result;
} }
static std::string emptystring(""); static string emptystring("");
std::string stringcat(std::string a, std::string b) { string stringcat(string a, string b) {
return stringcat(a,b,emptystring,emptystring,emptystring,emptystring,emptystring); return stringcat(a,b,emptystring,emptystring,emptystring,emptystring,emptystring);
} }
std::string stringcat(std::string a, std::string b, std::string c) { string stringcat(string a, string b, string c) {
return stringcat(a,b,c,emptystring,emptystring,emptystring,emptystring); return stringcat(a,b,c,emptystring,emptystring,emptystring,emptystring);
} }
std::string stringcat(std::string a, std::string b, std::string c, std::string d) { string stringcat(string a, string b, string c, string d) {
return stringcat(a,b,c,d,emptystring,emptystring,emptystring); return stringcat(a,b,c,d,emptystring,emptystring,emptystring);
} }
std::string stringcat(std::string a, std::string b, std::string c, std::string d, std::string e) { string stringcat(string a, string b, string c, string d, string e) {
return stringcat(a,b,c,d,e,emptystring,emptystring); return stringcat(a,b,c,d,e,emptystring,emptystring);
} }
std::string stringcat(std::string a, std::string b, std::string c, std::string d, std::string e, std::string f) { string stringcat(string a, string b, string c, string d, string e, string f) {
return stringcat(a,b,c,d,e,f,emptystring); return stringcat(a,b,c,d,e,f,emptystring);
} }
void stringToUint(std::string strRAND, uint64_t *hRAND, uint64_t *lRAND) void stringToUint(string strRAND, uint64_t *hRAND, uint64_t *lRAND)
{ {
assert(strRAND.size() == 32); assert(strRAND.size() == 32);
std::string strhRAND = strRAND.substr(0, 16); string strhRAND = strRAND.substr(0, 16);
std::string strlRAND = strRAND.substr(16, 16); string strlRAND = strRAND.substr(16, 16);
std::stringstream ssh; stringstream ssh;
ssh << std::hex << strhRAND; ssh << hex << strhRAND;
ssh >> *hRAND; ssh >> *hRAND;
std::stringstream ssl; stringstream ssl;
ssl << std::hex << strlRAND; ssl << hex << strlRAND;
ssl >> *lRAND; ssl >> *lRAND;
} }
std::string uintToString(uint64_t h, uint64_t l) string uintToString(uint64_t h, uint64_t l)
{ {
std::ostringstream os1; ostringstream os1;
os1.width(16); os1.width(16);
os1.fill('0'); os1.fill('0');
os1 << std::hex << h; os1 << hex << h;
std::ostringstream os2; ostringstream os2;
os2.width(16); os2.width(16);
os2.fill('0'); os2.fill('0');
os2 << std::hex << l; os2 << hex << l;
std::ostringstream os3; ostringstream os3;
os3 << os1.str() << os2.str(); os3 << os1.str() << os2.str();
return os3.str(); return os3.str();
} }
std::string uintToString(uint32_t x) string uintToString(uint32_t x)
{ {
std::ostringstream os; ostringstream os;
os.width(8); os.width(8);
os.fill('0'); os.fill('0');
os << std::hex << x; os << hex << x;
return os.str(); return os.str();
} }
}; };

52
Utils.h
View File

@ -36,40 +36,40 @@ extern const std::string timestr(unsigned fieldwidth, bool addDate = false); //
extern void sleepf(double howlong); // high resolution sleep extern void sleepf(double howlong); // high resolution sleep
extern int gcd(int x, int y); extern int gcd(int x, int y);
std::string format(const char *fmt, ...) __attribute__((format (printf,1,2))); string format(const char *fmt, ...) __attribute__((format (printf,1,2)));
// format1 used to prevent C++ confusion over what function to call here. // format1 used to prevent C++ confusion over what function to call here.
std::string format1(const char *fmt, ...) __attribute__((format (printf,1,2))); string format1(const char *fmt, ...) __attribute__((format (printf,1,2)));
// We have to enumerate the cross product of argument types here. This is fixed in C++11. // We have to enumerate the cross product of argument types here. This is fixed in C++11.
inline std::string format(const char *fmt, std::string s1) { inline string format(const char *fmt, string s1) {
return format1(fmt,s1.c_str()); return format1(fmt,s1.c_str());
} }
inline std::string format(const char *fmt, std::string s1, std::string s2) { inline string format(const char *fmt, string s1, string s2) {
return format1(fmt,s1.c_str(),s2.c_str()); return format1(fmt,s1.c_str(),s2.c_str());
} }
inline std::string format(const char *fmt, std::string s1, std::string s2, std::string s3) { inline string format(const char *fmt, string s1, string s2, string s3) {
return format1(fmt,s1.c_str(),s2.c_str(),s3.c_str()); return format1(fmt,s1.c_str(),s2.c_str(),s3.c_str());
} }
inline std::string format(const char *fmt, std::string s1, std::string s2, std::string s3, std::string s4) { inline string format(const char *fmt, string s1, string s2, string s3, string s4) {
return format1(fmt,s1.c_str(),s2.c_str(),s3.c_str(),s4.c_str()); return format1(fmt,s1.c_str(),s2.c_str(),s3.c_str(),s4.c_str());
} }
inline std::string format(const char *fmt, std::string s1, int i1) { inline string format(const char *fmt, string s1, int i1) {
return format1(fmt,s1.c_str(),i1); return format1(fmt,s1.c_str(),i1);
} }
inline std::string format(const char *fmt, int i1, std::string s1) { inline string format(const char *fmt, int i1, string s1) {
return format1(fmt,i1,s1.c_str()); return format1(fmt,i1,s1.c_str());
} }
inline std::string format(const char *fmt, std::string s1, std::string s2, int i1) { inline string format(const char *fmt, string s1, string s2, int i1) {
return format1(fmt,s1.c_str(),s2.c_str(),i1); return format1(fmt,s1.c_str(),s2.c_str(),i1);
} }
inline std::string format(const char *fmt, std::string s1, std::string s2, int i1, int i2) { inline string format(const char *fmt, string s1, string s2, int i1, int i2) {
return format1(fmt,s1.c_str(),s2.c_str(),i1,i2); return format1(fmt,s1.c_str(),s2.c_str(),i1,i2);
} }
int myscanf(const char *str, const char *fmt, std::string *s1); int myscanf(const char *str, const char *fmt, string *s1);
int myscanf(const char *str, const char *fmt, std::string *s1, std::string *s2); int myscanf(const char *str, const char *fmt, string *s1, string *s2);
int myscanf(const char *str, const char *fmt, std::string *s1, std::string *s2, std::string *s3); int myscanf(const char *str, const char *fmt, string *s1, string *s2, string *s3);
int myscanf(const char *str, const char *fmt, std::string *s1, std::string *s2, std::string *s3, std::string *s4); int myscanf(const char *str, const char *fmt, string *s1, string *s2, string *s3, string *s4);
int cstrSplit(char *in, char **pargv,int maxargc, const char *splitchars=NULL); int cstrSplit(char *in, char **pargv,int maxargc, const char *splitchars=NULL);
char *cstrGetArg(const char *in, int nth, unsigned *length); char *cstrGetArg(const char *in, int nth, unsigned *length);
@ -178,21 +178,21 @@ std::ostream &osprintf(std::ostream &os, const char *fmt, ...) __attribute__((fo
std::string replaceAll(const std::string input, const std::string search, const std::string replace); std::string replaceAll(const std::string input, const std::string search, const std::string replace);
std::vector<std::string>& stringSplit(std::vector<std::string> &result,const char *input); vector<string>& stringSplit(vector<string> &result,const char *input);
typedef std::vector<std::vector<std::string> > prettyTable_t; typedef vector<vector<string> > prettyTable_t;
void printPrettyTable(prettyTable_t &tab, std::ostream&os, bool tabSeparated = false); void printPrettyTable(prettyTable_t &tab, ostream&os, bool tabSeparated = false);
// The need for this is eliminated in C++11. // The need for this is eliminated in C++11.
std::string stringcat(std::string a, std::string b); string stringcat(string a, string b);
std::string stringcat(std::string a, std::string b, std::string c); string stringcat(string a, string b, string c);
std::string stringcat(std::string a, std::string b, std::string c, std::string d); string stringcat(string a, string b, string c, string d);
std::string stringcat(std::string a, std::string b, std::string c, std::string d, std::string e); string stringcat(string a, string b, string c, string d, string e);
std::string stringcat(std::string a, std::string b, std::string c, std::string d, std::string e, std::string f); string stringcat(string a, string b, string c, string d, string e, string f);
std::string stringcat(std::string a, std::string b, std::string c, std::string d, std::string e, std::string f, std::string g); string stringcat(string a, string b, string c, string d, string e, string f, string g);
extern void stringToUint(std::string strRAND, uint64_t *hRAND, uint64_t *lRAND); extern void stringToUint(string strRAND, uint64_t *hRAND, uint64_t *lRAND);
extern std::string uintToString(uint64_t h, uint64_t l); extern string uintToString(uint64_t h, uint64_t l);
extern std::string uintToString(uint32_t x); extern string uintToString(uint32_t x);
// The class is created with a RefCnt of 0. The caller must assign the constructed result to a pointer // The class is created with a RefCnt of 0. The caller must assign the constructed result to a pointer
// of type RefCntPointer. When the last RefCntPointer is freed, this struct is too. // of type RefCntPointer. When the last RefCntPointer is freed, this struct is too.

View File

@ -32,6 +32,8 @@
#include "Configuration.h" #include "Configuration.h"
ConfigurationTable gConfig; ConfigurationTable gConfig;
using namespace std;
typedef Vector<int> TestVector; typedef Vector<int> TestVector;
int barfo; int barfo;
void foo(TestVector a) void foo(TestVector a)
@ -40,16 +42,16 @@ void foo(TestVector a)
} }
void anotherTest() void anotherTest()
{ {
std::cout << "START Vector anotherTest" << std::endl; cout << "START Vector anotherTest" << endl;
TestVector v0(10); TestVector v0(10);
TestVector atest = v0.head(3); TestVector atest = v0.head(3);
std::cout << atest << std::endl; cout << atest << endl;
std::cout << "calling head" << std::endl; cout << "calling head" << endl;
std::cout << v0.head(3) << std::endl; cout << v0.head(3) << endl;
std::cout << "Passing Vector" << std::endl; cout << "Passing Vector" << endl;
// This calls the Vector non-const copy constructor // This calls the Vector non-const copy constructor
foo(v0); foo(v0);
std::cout << "FINISH anotherTest" << std::endl; cout << "FINISH anotherTest" << endl;
} }
int main(int argc, char *argv[]) int main(int argc, char *argv[])
@ -60,26 +62,26 @@ int main(int argc, char *argv[])
TestVector test2(5); TestVector test2(5);
for (int i=0; i<5; i++) test2[i]=10+i; for (int i=0; i<5; i++) test2[i]=10+i;
std::cout << test1 << std::endl; cout << test1 << endl;
std::cout << test2 << std::endl; cout << test2 << endl;
{ {
TestVector testC(test1,test2); TestVector testC(test1,test2);
std::cout << testC << std::endl; cout << testC << endl;
TestVector foo = testC.head(3); TestVector foo = testC.head(3);
//std::cout << testC.head(3) << std::endl; //cout << testC.head(3) << endl;
std::cout << testC.tail(3) << std::endl; cout << testC.tail(3) << endl;
testC.fill(8); testC.fill(8);
std::cout << testC << std::endl; cout << testC << endl;
test1.copyToSegment(testC,3); test1.copyToSegment(testC,3);
std::cout << testC << std::endl; cout << testC << endl;
TestVector testD(testC.segment(4,3)); TestVector testD(testC.segment(4,3));
std::cout << testD << std::endl; cout << testD << endl;
testD.fill(9); testD.fill(9);
std::cout << testC << std::endl; cout << testC << endl;
std::cout << testD << std::endl; cout << testD << endl;
} }
return 0; return 0;

View File

@ -14,6 +14,8 @@
#include <string> #include <string>
#include <vector> #include <vector>
using namespace std;
// Wrappers to sqlite operations. // Wrappers to sqlite operations.
// These will eventually get moved to commonlibs. // These will eventually get moved to commonlibs.
@ -119,13 +121,13 @@ sqlQuery::~sqlQuery()
if (mStmt) sqlite3_finalize(mStmt); if (mStmt) sqlite3_finalize(mStmt);
} }
std::string sqlQuery::getResultText(int colNum) string sqlQuery::getResultText(int colNum)
{ {
if (sqlSuccess()) { if (sqlSuccess()) {
const char* ptr = (const char*)sqlite3_column_text(mStmt,colNum); const char* ptr = (const char*)sqlite3_column_text(mStmt,colNum);
return ptr ? std::string(ptr,sqlite3_column_bytes(mStmt,colNum)) : std::string(""); return ptr ? string(ptr,sqlite3_column_bytes(mStmt,colNum)) : string("");
} }
return std::string(""); return string("");
} }
sqlite3_int64 sqlQuery::getResultInt(int colNum) sqlite3_int64 sqlQuery::getResultInt(int colNum)
@ -206,16 +208,16 @@ sqlite3_stmt *sqlite_lookup_row_u(sqlite3*db, const char *tableName, const char*
return sqlite_lookup_row(db,tableName,condition_u(conditionBuffer,keyName,keyValue),resultColumns); return sqlite_lookup_row(db,tableName,condition_u(conditionBuffer,keyName,keyValue),resultColumns);
} }
// Pass a comma-separated list of column names to return, or if you want all the columns in the result, pass "*" as the resultColumns. // Pass a comma-separated list of column names to return, or if you want all the columns in the result, pass "*" as the resultColumns.
std::vector<std::string> sqlite_multi_lookup_vector(sqlite3* db, const char* tableName, const char* keyName, const char* keyData, const char *resultColumns) vector<string> sqlite_multi_lookup_vector(sqlite3* db, const char* tableName, const char* keyName, const char* keyData, const char *resultColumns)
{ {
std::vector<std::string> result; vector<string> result;
if (sqlite3_stmt *stmt = sqlite_lookup_row_c(db,tableName,keyName,keyData,resultColumns)) { if (sqlite3_stmt *stmt = sqlite_lookup_row_c(db,tableName,keyName,keyData,resultColumns)) {
int n = sqlite3_column_count(stmt); int n = sqlite3_column_count(stmt);
if (n < 0 || n > 100) { goto done; } // Would like to LOG an error but afraid to use LOG in here. if (n < 0 || n > 100) { goto done; } // Would like to LOG an error but afraid to use LOG in here.
result.reserve(n+1); result.reserve(n+1);
for (int i = 0; i < n; i++) { for (int i = 0; i < n; i++) {
const char* ptr = (const char*)sqlite3_column_text(stmt,i); const char* ptr = (const char*)sqlite3_column_text(stmt,i);
result.push_back(ptr ? std::string(ptr,sqlite3_column_bytes(stmt,i)) : std::string("")); result.push_back(ptr ? string(ptr,sqlite3_column_bytes(stmt,i)) : string(""));
} }
done: done:
sqlite3_finalize(stmt); sqlite3_finalize(stmt);
@ -227,7 +229,7 @@ std::vector<std::string> sqlite_multi_lookup_vector(sqlite3* db, const char* tab
bool sqlite_single_lookup(sqlite3* db, const char* tableName, bool sqlite_single_lookup(sqlite3* db, const char* tableName,
const char* keyName, const char* keyData, const char* keyName, const char* keyData,
const char* resultName, std::string &resultData) const char* resultName, string &resultData)
{ {
sqlQuery query(db,tableName,resultName,keyName,keyData); sqlQuery query(db,tableName,resultName,keyName,keyData);
if (query.sqlSuccess()) { if (query.sqlSuccess()) {
@ -238,7 +240,7 @@ bool sqlite_single_lookup(sqlite3* db, const char* tableName,
#if 0 #if 0
if (sqlite3_stmt *stmt = sqlite_lookup_row_c(db,tableName,keyName,keyData,valueName)) { if (sqlite3_stmt *stmt = sqlite_lookup_row_c(db,tableName,keyName,keyData,valueName)) {
if (const char* ptr = (const char*)sqlite3_column_text(stmt,0)) { if (const char* ptr = (const char*)sqlite3_column_text(stmt,0)) {
valueData = std::string(ptr,sqlite3_column_bytes(stmt,0)); valueData = string(ptr,sqlite3_column_bytes(stmt,0));
} }
sqlite3_finalize(stmt); sqlite3_finalize(stmt);
return true; return true;
@ -249,7 +251,7 @@ bool sqlite_single_lookup(sqlite3* db, const char* tableName,
bool sqlite_single_lookup(sqlite3* db, const char* tableName, bool sqlite_single_lookup(sqlite3* db, const char* tableName,
const char* keyName, unsigned keyValue, const char* keyName, unsigned keyValue,
const char* resultName, std::string &resultData) const char* resultName, string &resultData)
{ {
sqlQuery query(db,tableName,resultName,keyName,keyValue); sqlQuery query(db,tableName,resultName,keyName,keyValue);
if (query.sqlSuccess()) { if (query.sqlSuccess()) {
@ -260,7 +262,7 @@ bool sqlite_single_lookup(sqlite3* db, const char* tableName,
#if 0 #if 0
if (sqlite3_stmt *stmt = sqlite_lookup_row_u(db,tableName,keyName,keyValue,valueName)) { if (sqlite3_stmt *stmt = sqlite_lookup_row_u(db,tableName,keyName,keyValue,valueName)) {
if (const char* ptr = (const char*)sqlite3_column_text(stmt,0)) { if (const char* ptr = (const char*)sqlite3_column_text(stmt,0)) {
valueData = std::string(ptr,sqlite3_column_bytes(stmt,0)); valueData = string(ptr,sqlite3_column_bytes(stmt,0));
} }
sqlite3_finalize(stmt); sqlite3_finalize(stmt);
return true; return true;
@ -271,12 +273,12 @@ bool sqlite_single_lookup(sqlite3* db, const char* tableName,
// Do the lookup and just return the string. // Do the lookup and just return the string.
// For this function an empty value is indistinguishable from failure - both return an empty string. // For this function an empty value is indistinguishable from failure - both return an empty string.
std::string sqlite_single_lookup_string(sqlite3* db, const char* tableName, string sqlite_single_lookup_string(sqlite3* db, const char* tableName,
const char* keyName, const char* keyData, const char* resultName) const char* keyName, const char* keyData, const char* resultName)
{ {
return sqlQuery(db,tableName,resultName,keyName,keyData).getResultText(); return sqlQuery(db,tableName,resultName,keyName,keyData).getResultText();
#if 0 #if 0
std::string result; string result;
(void) sqlite_single_lookup(db,tableName,keyName,keyData,valueName,result); (void) sqlite_single_lookup(db,tableName,keyName,keyData,valueName,result);
return result; return result;
#endif #endif
@ -349,7 +351,7 @@ bool sqlite_set_attr(sqlite3*db,const char *attr_name,const char*attr_value)
return true; return true;
} }
std::string sqlite_get_attr(sqlite3*db,const char *attr_name) string sqlite_get_attr(sqlite3*db,const char *attr_name)
{ {
return sqlite_single_lookup_string(db,"ATTR_TABLE","ATTR_NAME",attr_name,"ATTR_VALUE"); return sqlite_single_lookup_string(db,"ATTR_TABLE","ATTR_NAME",attr_name,"ATTR_VALUE");
} }