static int stringToParent(const String& argsmode) { if(!argsmode.size()) return Object::DISABLE_PARENT; //normalize String smode=argsmode.toUpper(); smode.replace(" ",""); //split std::vector<String> listMode; smode.split("|",listMode); //mode out: int mode=Object::DISABLE_PARENT; //for each mode for(auto& astr:listMode) { if(astr=="ALL") return Object::ENABLE_ALL; else if(astr=="POSITION") mode|=Object::ENABLE_POSITION; else if(astr=="ROTATION") mode|=Object::ENABLE_ROTATION; else if(astr=="SCALE") mode|=Object::ENABLE_SCALE; if(mode==Object::ENABLE_ALL) return Object::ENABLE_ALL; } return mode; }
bool isExtensionManaged(const YString& file) { // Check whether it is a valid jpg file String extension; IO::ExtractExtension(extension, file, false, false); // Only JPG files managed at the moment return (extension.toUpper() == "JPG"); }
bool SystemFile::saveFile(LPCSTR fileName,INT pid) { String name = SQLSTRING(fileName); String sql; SQRes res; sql.printf("SELECT file_id,file_lname FROM tb_file2 WHERE file_pid=%d and file_name='%s';", pid, name.c_str()); res = m_db->exec(sql); if (res->getRows()) { LPCSTR lfile = res->getColumn(1); if (lfile[0] == 0) return false; removeFile(atoi(res->getColumn(0))); } LPCSTR data = Method::POST(); INT length = Method::getPostLength(); std::string hash; MD5::Data(hash, data,length); String localName; localName.printf("%s.dat", hash.c_str()); String saveName; saveName.printf("%s%s", m_dataDir.c_str(), localName.c_str()); FILE* file = fopen(saveName,"wb"); if (file) { fwrite(data, length, 1, file); fclose(file); } String type; String comment; String date; LPCSTR d = strrchr(SQLSTRING(fileName), '.'); if (d) { type = d + 1; type.toUpper(); } Time::getDateTime(date); sql.printf("INSERT INTO tb_file2 values(null,%d,0,'%s','%s','%s',%d,'%s','%s','');", pid, name.c_str(), localName.c_str(), type.c_str(), length, date.c_str(), hash.c_str()); res = m_db->exec(sql); return !res->isError(); }
bool MrcpRtpHandler::received(Message& msg) { String trans = msg.getValue("transport"); trans.toUpper(); bool tls = false; if (trans == "TCP/TLS/MRCPV2") tls = true; else if (trans != "TCP/MRCPV2") return false; Debug(&plugin,DebugAll,"RTP message received, TLS: %s",String::boolText(tls)); return true; }
FileId::Md5Hash FileId::hash(String path) { // Ensure we've a normalized path. if(QDir::isRelativePath(path)) { path = App_BasePath() / path; } #if defined(WIN32) || defined(MACOSX) // This is a case insensitive operation. path = path.toUpper(); #endif return QCryptographicHash::hash(path.toUtf8(), QCryptographicHash::Md5); }
bool SystemFile::saveFile(const MethodFile* file,INT pid) { if(!file || !*file->getName()) return false; String sql; SQRes res; sql.printf("SELECT file_id,file_lname FROM tb_file2 WHERE file_pid=%d and file_name='%s';",pid,file->getName()); res = m_db->exec(sql); if(res->getRows()) { LPCSTR lfile = res->getColumn(1); if(lfile[0] == 0) return false; removeFile(atoi(res->getColumn(0))); } std::string hash; MD5::File(hash,file->getFile()); String localName; localName.printf("%s.dat",hash.c_str()); String saveName; saveName.printf("%s%s",m_dataDir.c_str(),localName.c_str()); if(!file->save(saveName)) return false; String name; String type; String comment; String date; name = SQLSTRING(file->getName()); LPCSTR d = strrchr(SQLSTRING(file->getName()),'.'); if(d) { type = d + 1; type.toUpper(); } Time::getDateTime(date); sql.printf("INSERT INTO tb_file2 values(null,%d,0,'%s','%s','%s',%d,'%s','%s','');", pid,name.c_str(),localName.c_str(),type.c_str(),file->getSize(), date.c_str(),hash.c_str()); res = m_db->exec(sql); return !res->isError(); }
bool MolecularFileDialog::canHandle(const String& fileformat) const { String formats = getSupportedFileFormats(); vector<String> fields; formats.split(fields, "*. "); for (Position p = 0; p < fields.size(); p++) { String s = fields[p]; if (s == fileformat) return true; s.toUpper(); if (s == fileformat) return true; } return false; }
FileTypes::Type FileTypes::nameToType(const String& name) { String tmp = name; tmp.toUpper(); String tmp2; for (int i = 0; i < FileTypes::SIZE_OF_TYPE; ++i) { tmp2 = FileTypes::typeToName((FileTypes::Type)i); tmp2.toUpper(); if (tmp == tmp2) { return (FileTypes::Type)i; } } return FileTypes::UNKNOWN; }
int RenderContext::stringToBlendContant(String fun, int vlDefault) { //normalize fun.replaceAll(" ",""); fun=fun.toUpper(); // if(fun=="ONE") return GL_ONE; if(fun=="ZERO") return GL_ZERO; // if(fun=="ONE::MINUS::DST::COLOR") return GL_ONE_MINUS_DST_COLOR; if(fun=="ONE::MINUS::DST::ALPHA") return GL_ONE_MINUS_DST_ALPHA; if(fun=="ONE::MINUS::SRC::COLOR") return GL_ONE_MINUS_SRC_COLOR; if(fun=="ONE::MINUS::SRC::ALPHA") return GL_ONE_MINUS_SRC_ALPHA; // if(fun=="DST::COLOR") return GL_DST_COLOR; if(fun=="DST::ALPHA") return GL_DST_ALPHA; // if(fun=="SRC::COLOR") return GL_SRC_COLOR; if(fun=="SRC::ALPHA") return GL_SRC_ALPHA; if(fun=="SRC::ALPHA::SATURATE") return GL_SRC_ALPHA_SATURATE; return vlDefault; }
bool Search::setParameter(String param, int value) { #if defined(CLOP) || defined(DEBUG_MODE) param.toUpper(); bool res = true; if (param == "FUTIL_MARGIN") { FUTIL_MARGIN = value; } else if (param == "EXT_FUTILY_MARGIN") { EXT_FUTILY_MARGIN = value; } else if (param == "RAZOR_MARGIN") { RAZOR_MARGIN = value; } else if (param == "ATTACK_KING") { ATTACK_KING = value; } else if (param == "BACKWARD_PAWN") { BACKWARD_PAWN = value; } else if (param == "BISHOP_ON_QUEEN") { BISHOP_ON_QUEEN = value; } else if (param == "BONUS2BISHOP") { BONUS2BISHOP = value; } else if (param == "CONNECTED_ROOKS") { CONNECTED_ROOKS = value; } else if (param == "DOUBLED_ISOLATED_PAWNS") { DOUBLED_ISOLATED_PAWNS = value; } else if (param == "DOUBLED_PAWNS") { DOUBLED_PAWNS = value; } else if (param == "END_OPENING") { END_OPENING = value; } else if (param == "ENEMY_NEAR_KING") { ENEMY_NEAR_KING = value; } else if (param == "FRIEND_NEAR_KING") { FRIEND_NEAR_KING = value; } else if (param == "HALF_OPEN_FILE_Q") { HALF_OPEN_FILE_Q = value; } else if (param == "OPEN_FILE") { OPEN_FILE = value; } else if (param == "OPEN_FILE_Q") { OPEN_FILE_Q = value; } else if (param == "PAWN_IN_7TH") { PAWN_IN_7TH = value; } else if (param == "PAWN_CENTER") { PAWN_CENTER = value; } else if (param == "PAWN_IN_8TH") { PAWN_IN_8TH = value; } else if (param == "PAWN_ISOLATED") { PAWN_ISOLATED = value; } else if (param == "PAWN_NEAR_KING") { PAWN_NEAR_KING = value; } else if (param == "PAWN_BLOCKED") { PAWN_BLOCKED = value; } else if (param == "ROOK_7TH_RANK") { ROOK_7TH_RANK = value; } else if (param == "ROOK_BLOCKED") { ROOK_BLOCKED = value; } else if (param == "ROOK_TRAPPED") { ROOK_TRAPPED = value; } else if (param == "UNDEVELOPED_KNIGHT") { UNDEVELOPED_KNIGHT = value; } else if (param == "UNDEVELOPED_BISHOP") { UNDEVELOPED_BISHOP = value; } else if (param == "VAL_WINDOW") { VAL_WINDOW = value; } else if (param == "UNPROTECTED_PAWNS") { UNPROTECTED_PAWNS = value; } else { res = false; } return res; #else cout << param << " " << value << endl; return false; #endif }
int test(char** argv) { verbose = getenv("PEGASUS_TEST_VERBOSE") ? true : false; String s1 = "Hello World"; String s2 = s1; String s3(s2); PEGASUS_TEST_ASSERT(String::equal(s1, s3)); // Test append characters to String String s4 = "Hello"; s4.append(Char16(0x0000)); s4.append(Char16(0x1234)); s4.append(Char16(0x5678)); s4.append(Char16(0x9cde)); s4.append(Char16(0xffff)); { #ifdef HAVE_SSTREAM stringstream os; #endif #ifdef HAVE_STRSTREAM ostrstream os; #endif os << s4; #ifdef HAVE_STRSTREAM os.put('\0'); #endif #ifndef PEGASUS_HAS_ICU const char EXPECTED[] = "Hello\\x0000\\x1234\\x5678\\x9CDE\\xFFFF"; #else CString cstr = s4.getCString(); const char * EXPECTED = (const char *)cstr; #endif #ifdef HAVE_SSTREAM string os_str = os.str(); const char* tmp = os_str.c_str(); #endif #ifdef HAVE_STRSTREAM char *tmp = os.str(); #endif PEGASUS_TEST_ASSERT(strcmp(EXPECTED, tmp) == 0); #ifdef PEGASUS_PLATFORM_AIX_RS_IBMCXX os.freeze(false); #else #ifdef HAVE_STRSTREAM delete tmp; #endif #endif } { // Test getCString const char STR0[] = "one two three four"; String s = STR0; PEGASUS_TEST_ASSERT(strcmp(s.getCString(), STR0) == 0); } { // Test remove String s = "abcdefg"; s.remove(3, 3); PEGASUS_TEST_ASSERT(String::equal(s, "abcg")); PEGASUS_TEST_ASSERT(s.size() == 4); s = "abcdefg"; s.remove(3, 4); PEGASUS_TEST_ASSERT(String::equal(s, "abc")); PEGASUS_TEST_ASSERT(s.size() == 3); s = "abcdefg"; s.remove(3); PEGASUS_TEST_ASSERT(String::equal(s, "abc")); PEGASUS_TEST_ASSERT(s.size() == 3); s = "abc"; s.remove(3); PEGASUS_TEST_ASSERT(String::equal(s, "abc")); PEGASUS_TEST_ASSERT(s.size() == 3); s = "abc"; s.remove(0); PEGASUS_TEST_ASSERT(String::equal(s, "")); PEGASUS_TEST_ASSERT(s.size() == 0); s = "abc"; s.remove(0, 1); PEGASUS_TEST_ASSERT(String::equal(s, "bc")); PEGASUS_TEST_ASSERT(s.size() == 2); String t1 = "HELLO"; String t2 = t1; t2.toLower(); PEGASUS_TEST_ASSERT(String::equal(t1, "HELLO")); PEGASUS_TEST_ASSERT(String::equal(t2, "hello")); } { // another test of the append method String t1 = "one"; t1.append(" two"); PEGASUS_TEST_ASSERT(String::equal(t1, "one two")); t1.append(' '); t1.append('t'); t1.append('h'); t1.append('r'); t1.append("ee"); PEGASUS_TEST_ASSERT(String::equal(t1,"one two three")); // used as example in Doc. String test = "abc"; test.append("def"); PEGASUS_TEST_ASSERT(test == "abcdef"); } // Test of the different overload operators { // Test the == overload operator String t1 = "one"; String t2 = "one"; PEGASUS_TEST_ASSERT(t1 == "one"); PEGASUS_TEST_ASSERT("one" == t1); PEGASUS_TEST_ASSERT(t1 == t2); PEGASUS_TEST_ASSERT(t2 == t1); PEGASUS_TEST_ASSERT(String("one") == "one"); const char STR0[] = "one two three four"; String s = STR0; CString tmp = s.getCString(); PEGASUS_TEST_ASSERT(tmp == s); PEGASUS_TEST_ASSERT(s == tmp); } { // Tests of the + Overload operator String t1 = "abc"; String t2 = t1 + t1; PEGASUS_TEST_ASSERT(t2 == "abcabc"); t1 = "abc"; t2 = t1 + "def"; PEGASUS_TEST_ASSERT(t2 == "abcdef"); t1 = "ghi"; PEGASUS_TEST_ASSERT(t1 == "ghi"); // ATTN: the following fails because there // is no single character overload operator // KS: Apr 2001 // t2 = t1 + 'k' + 'l' + 'm' + "nop"; t2 = t1 + "k" + "l" + "m" + "nop"; PEGASUS_TEST_ASSERT(t2 == "ghiklmnop"); PEGASUS_TEST_ASSERT(String::equal(t2,"ghiklmnop")); // add tests for != operator. t1 = "abc"; PEGASUS_TEST_ASSERT(t1 != "ghi"); PEGASUS_TEST_ASSERT(t1 != t2); // add tests for other compare operators // Operater < t1 = "ab"; t2 = "cde"; PEGASUS_TEST_ASSERT(t1 < t2); PEGASUS_TEST_ASSERT(t1 <= t2); PEGASUS_TEST_ASSERT(t2 > t1); PEGASUS_TEST_ASSERT(t2 >=t1); PEGASUS_TEST_ASSERT(String::compare(t1,t2) < 0); PEGASUS_TEST_ASSERT(String::compare(t2,t1) > 0); PEGASUS_TEST_ASSERT(String::compare(t1, t2, 1) < 0); PEGASUS_TEST_ASSERT(String::compare(t2, t1, 1) > 0); PEGASUS_TEST_ASSERT(String::compare(t1, t2, 10) < 0); PEGASUS_TEST_ASSERT(String::compare(t2, t1, 10) > 0); PEGASUS_TEST_ASSERT(String::compare(t1, t2, 0) == 0); t2 = t1; PEGASUS_TEST_ASSERT(t1 <= t2); PEGASUS_TEST_ASSERT(t1 >= t2); PEGASUS_TEST_ASSERT(String::compare(t1, t2) == 0); PEGASUS_TEST_ASSERT(String::compare(t1, t2, 0) == 0); PEGASUS_TEST_ASSERT(String::compare(t1, t2, 1) == 0); PEGASUS_TEST_ASSERT(String::compare(t1, t2, 10) == 0); // Tests for compare with same length t1 = "abc"; t2 = "def"; PEGASUS_TEST_ASSERT(t1 < t2); PEGASUS_TEST_ASSERT(String::compare(t1, t2) < 0); PEGASUS_TEST_ASSERT(String::compare(t2, t1) > 0); PEGASUS_TEST_ASSERT(String::compare(t1, t2, 10) < 0); PEGASUS_TEST_ASSERT(String::compare(t1, t2, 0) == 0); t1 = "abc"; t2 = "ABC"; PEGASUS_TEST_ASSERT(String::equalNoCase(t1,t2)); PEGASUS_TEST_ASSERT(!String::equal(t1,t2)); PEGASUS_TEST_ASSERT(String::compareNoCase(t1,t2) == 0); t1.toUpper(); t2.toLower(); PEGASUS_TEST_ASSERT(String::equal(t1, "ABC")); PEGASUS_TEST_ASSERT(String::equal(t2, "abc")); t1 = "1000"; t2 = "1001"; PEGASUS_TEST_ASSERT(String::compareNoCase(t1,t2) < 0); PEGASUS_TEST_ASSERT(String::compare(t1, t2) < 0); PEGASUS_TEST_ASSERT(String::compare(t1, t2, 3) == 0); PEGASUS_TEST_ASSERT(String::compare(t1, t2, 4) < 0); #ifdef PEGASUS_HAS_ICU // // Strings used to test non-ascii case mappings // Tests context sensitve mappings (eg. greek) // Tests expansion after mapping (eg german) // // Lower case german and greek // --latin small letter sharp s (german) (2 of these to cause // ICU overflow error inside of String) // --greek small letter sigma (followed by another letter) // --latin small a // --greek small letter sigma (NOT followed by another letter) const Char16 lowermap[] = { 0xdf, 0xdf, 0x3c3, 'a', 0x3c2, 0x00}; String degkLow(lowermap); // Needed because the german char does not round trip // after an uppercase followed by lower case. // --latin small letters 's' 's' (4 of these due to expansion) // --greek small letter sigma (followed by another letter) // --latin small a // --greek small letter sigma (NOT followed by another letter) const Char16 lowermap2[] = { 's', 's', 's', 's', 0x3c3, 'a', 0x3c2, 0x00}; String degkLow2(lowermap2); // Upper case greek and german // latin cap letter sharp s (german) (4 of these due to expansion) // greek cap letter sigma (followed by another letter) // latin cap A // greek cap letter sigma (NOT followed by another letter) const Char16 uppermap[] = { 'S', 'S', 'S', 'S', 0x3a3, 'A', 0x3a3, 0x00}; String degkUp(uppermap); PEGASUS_TEST_ASSERT(String::compareNoCase(degkLow,degkUp) == 0); // does a binary compare, so lower > upper PEGASUS_TEST_ASSERT(String::compare(degkLow,degkUp) > 0); PEGASUS_TEST_ASSERT(String::equalNoCase(degkLow,degkUp)); String mapTest(degkLow); mapTest.toUpper(); PEGASUS_TEST_ASSERT(String::equal(mapTest, degkUp)); // Note that the German char does not round trip mapTest.toLower(); PEGASUS_TEST_ASSERT(String::equal(mapTest, degkLow2)); #endif } { // Test of the [] operator String t1 = "abc"; Char16 c = t1[1]; // note c is Char16 PEGASUS_TEST_ASSERT(c == 'b'); //ATTN: test for outofbounds exception try { c = t1[200]; } catch (IndexOutOfBoundsException&) { PEGASUS_TEST_ASSERT(true); } } { // Test the find function String t1 = "abcdef"; String t2 = "cde"; String t3 = "xyz"; String t4 = "abc"; String t5 = "abd"; String t6 = "defg"; PEGASUS_TEST_ASSERT(t1.find('c') == 2); PEGASUS_TEST_ASSERT(t1.find(t2)==2); PEGASUS_TEST_ASSERT(t1.find(t3)==PEG_NOT_FOUND); PEGASUS_TEST_ASSERT(t1.find(t4)==0); PEGASUS_TEST_ASSERT(t1.find(t5)==PEG_NOT_FOUND); PEGASUS_TEST_ASSERT(t1.find(t6)==PEG_NOT_FOUND); PEGASUS_TEST_ASSERT(t1.find("cde")==2); PEGASUS_TEST_ASSERT(t1.find("def")==3); PEGASUS_TEST_ASSERT(t1.find("xyz")==PEG_NOT_FOUND); PEGASUS_TEST_ASSERT(t1.find("a") ==0); // test for the case where string // partly occurs and then later // completely occurs String s = "this is an apple"; PEGASUS_TEST_ASSERT(s.find("apple")==11); PEGASUS_TEST_ASSERT(s.find("appld")==PEG_NOT_FOUND); PEGASUS_TEST_ASSERT(s.find("this")==0); PEGASUS_TEST_ASSERT(s.find("t")==0); PEGASUS_TEST_ASSERT(s.find("e")==15); s = "a"; PEGASUS_TEST_ASSERT(s.find("b")==PEG_NOT_FOUND); PEGASUS_TEST_ASSERT(s.find("a")==0); PEGASUS_TEST_ASSERT(s.find(s)==0); s = "aaaapple"; PEGASUS_TEST_ASSERT(s.find("apple")==3); // 20020715-RK This method was removed from the String class //{ // String nameSpace = "a#b#c"; // nameSpace.translate('#', '/'); // PEGASUS_TEST_ASSERT(nameSpace == "a/b/c"); //} } { // // Test String unicode enablement // char utf8chr[] = { '\xCE', '\x99', '\xCE', '\xBF', '\xCF', '\x8D', '\xCE', '\xBD', '\xCE', '\xB9', '\xCE', '\xBA', '\xCE', '\xBF', '\xCE', '\xBD', '\xCF', '\x84', '\0' }; // utf8 string with mutliple byte characters Char16 utf16chr[] = { 0x0399,0x03BF,0x03CD,0x03BD,0x03B9, 0x03BA,0x03BF,0x03BD,0x03C4,0x00 }; // utf16 representation of the utf8 string String utf16string(utf16chr); String utf8string(utf8chr); String utf16merge(utf8string.getChar16Data()); CString temp = utf8string.getCString(); CString temp2 = utf16string.getCString(); PEGASUS_TEST_ASSERT(utf16string == utf8string); PEGASUS_TEST_ASSERT(utf16string == utf16merge); PEGASUS_TEST_ASSERT(utf16string == utf16chr); PEGASUS_TEST_ASSERT(utf8string == utf16chr); PEGASUS_TEST_ASSERT(memcmp(utf8string.getChar16Data(), utf16string.getChar16Data(),sizeof(utf16chr)) == 0); PEGASUS_TEST_ASSERT(strcmp(utf8string.getCString(),utf8chr) == 0); PEGASUS_TEST_ASSERT(strcmp(utf16string.getCString(),utf8chr) == 0); PEGASUS_TEST_ASSERT(strcmp(temp,utf8chr) == 0); PEGASUS_TEST_ASSERT(strcmp(temp2,utf8chr) == 0); Uint32 count = 0; Uint32 size = sizeof(utf8chr); while(count<size) { PEGASUS_TEST_ASSERT(isUTF8(&utf8chr[count]) == true); UTF8_NEXT(utf8chr,count); } // utf8 string with mutliple byte characters char utf8bad[] = { '\xFF','\xFF', '\xFF', '\0', '\0', '\0' }; count = 0; size = 3; while(count<size) { PEGASUS_TEST_ASSERT(isUTF8(&utf8bad[count]) == false); UTF8_NEXT(utf8bad,count); } Char16 utf16Chars[] = { 0x6A19, 0x6E96, 0x842C, 0x570B, 0x78BC, 0x042E, 0x043D, 0x0438, 0x043A, 0x043E, 0x0434, 0x110B, 0x1172, 0x1102, 0x1165, 0x110F, 0x1169, 0x11AE, 0x10E3, 0x10DC, 0x10D8, 0x10D9, 0x10DD, 0x10D3, 0x10D8, 0xdbc0, 0xdc01, 0x05D9, 0x05D5, 0x05E0, 0x05D9, 0x05E7, 0x05D0, 0x05B8, 0x05D3, 0x064A, 0x0648, 0x0646, 0x0650, 0x0643, 0x0648, 0x062F, 0x092F, 0x0942, 0x0928, 0x093F, 0x0915, 0x094B, 0x0921, 0x016A, 0x006E, 0x012D, 0x0063, 0x014D, 0x0064, 0x0065, 0x033D, 0x00E0, 0x248B, 0x0061, 0x2173, 0x0062, 0x1EA6, 0xFF21, 0x00AA, 0x0325, 0x2173, 0x249C, 0x0063, 0x02C8, 0x006A, 0x0075, 0x006E, 0x026A, 0x02CC, 0x006B, 0x006F, 0x02D0, 0x0064, 0x30E6, 0x30CB, 0x30B3, 0x30FC, 0x30C9, 0xFF95, 0xFF86, 0xFF7A, 0xFF70, 0xFF84, 0xFF9E, 0xC720, 0xB2C8, 0xCF5B, 0x7D71, 0x4E00, 0x78BC, 0xdbc0, 0xdc01, 0x00}; String ugly(utf16Chars); PEGASUS_TEST_ASSERT(ugly == utf16Chars); // // Test passing bad utf-8 into String // // A utf-8 sequence with a byte zeroed out in a bad spot char utf8bad1[] = { '\xCE', '\x99', '\xCE', '\xBF', '\xCF', '\x8D', '\xCE', '\xBD', '\xCE', '\0', '\xCE', '\xBA', '\xCE', '\xBF', '\xCE', '\xBD', '\xCF', '\x84', '\0' }; // utf8 string with mutliple byte characters // Test String(char *) try { // the first terminator causes invalid utf-8 String tmp(utf8bad1); PEGASUS_TEST_ASSERT(false); } catch (Exception &) { // expect an error } // Test String(char *, Uint32) try { // bogus utf-8 char in the middle String tmp(utf8bad1, sizeof(utf8bad1)-1); PEGASUS_TEST_ASSERT(false); } catch (Exception &) { // expect an error } // Test String(char *, Uint32) try { // good, but the last utf-8 char extends past the last byte String tmp(utf8chr, sizeof(utf8chr) - 2); PEGASUS_TEST_ASSERT(false); } catch (Exception &) { // expect an error } // Test String::assign(char *) String assigntest(utf8chr); // good so far try { // the first terminator causes invalid utf-8 assigntest.assign(utf8bad1); // bad PEGASUS_TEST_ASSERT(false); } catch (Exception &) { // expect an error } // Test String::assign(char *, Uint32) try { // bogus utf-8 char in the middle assigntest.assign(utf8bad1, sizeof(utf8bad1) - 1); // bad PEGASUS_TEST_ASSERT(false); } catch (Exception &) { // expect an error } // Test String::assign(char *, Uint32) try { // good, but the last utf-8 char extends past the end assigntest.assign(utf8chr, sizeof(utf8chr) - 2); // bad PEGASUS_TEST_ASSERT(false); } catch (Exception &) { // expect an error } // // Test passing in good utf-8 with an embedded terminator // // A utf-8 sequence with a byte zeroed out in an ok spot char utf8good1[] = { '\xCE', '\x99', '\xCE', '\xBF', '\xCF', '\x8D', '\xCE', '\xBD', 'A', '\0', '\xCE', '\xBA', '\xCE', '\xBF', '\xCE', '\xBD', '\xCF', '\x84', '\0' }; // utf8 string with mutliple byte characters // Test String(char *) try { // terminator after 5 chars String tmp(utf8good1); PEGASUS_TEST_ASSERT (tmp.size() == 5); } catch (Exception &) { // didn't see that one coming PEGASUS_TEST_ASSERT(false); } // Test String(char *, Uint32) try { // embedded terminator counts as 1 char String tmp(utf8good1, sizeof(utf8good1) - 1); PEGASUS_TEST_ASSERT (tmp.size() == 10); } catch (Exception &) { // didn't see that one coming PEGASUS_TEST_ASSERT(false); } assigntest.clear(); // Test String::assign(char *) try { // terminator after 5 chars assigntest.assign(utf8good1); PEGASUS_TEST_ASSERT (assigntest.size() == 5); } catch (Exception &) { // didn't see that one coming PEGASUS_TEST_ASSERT(false); } assigntest.clear(); // Test String::assign(char *, Uint32) try { // embedded terminator counts as 1 char assigntest.assign(utf8good1, sizeof(utf8good1) - 1); PEGASUS_TEST_ASSERT (assigntest.size() == 10); } catch (Exception &) { // didn't see that one coming PEGASUS_TEST_ASSERT(false); } // // Casing tests // String little("the quick brown fox jumped over the lazy dog"); String big("THE QUICK BROWN FOX JUMPED OVER THE LAZY DOG"); String tmpBig = big; String tmpLittle = little; tmpBig.toLower(); PEGASUS_TEST_ASSERT(tmpBig == little); tmpBig.toUpper(); PEGASUS_TEST_ASSERT(tmpBig == big); } #if 0 // The match code has been removed from the String class // Test the string match functions { String abc = "abc"; String ABC = "ABC"; PEGASUS_TEST_ASSERT(String::match(abc, "abc")); PEGASUS_TEST_ASSERT(String::match(ABC, "ABC")); PEGASUS_TEST_ASSERT(!String::match(abc, "ABC")); PEGASUS_TEST_ASSERT(!String::match(ABC, "abc")); PEGASUS_TEST_ASSERT(String::matchNoCase(abc, "abc")); PEGASUS_TEST_ASSERT(String::matchNoCase(ABC, "abc")); PEGASUS_TEST_ASSERT(String::matchNoCase(abc, "ABC")); PEGASUS_TEST_ASSERT(String::matchNoCase(ABC, "ABc")); PEGASUS_TEST_ASSERT(String::match(abc, "???")); PEGASUS_TEST_ASSERT(String::match(ABC, "???")); PEGASUS_TEST_ASSERT(String::match(abc, "*")); PEGASUS_TEST_ASSERT(String::match(ABC, "*")); PEGASUS_TEST_ASSERT(String::match(abc, "?bc")); PEGASUS_TEST_ASSERT(String::match(abc, "?b?")); PEGASUS_TEST_ASSERT(String::match(abc, "??c")); PEGASUS_TEST_ASSERT(String::matchNoCase(ABC, "?bc")); PEGASUS_TEST_ASSERT(String::matchNoCase(ABC, "?b?")); PEGASUS_TEST_ASSERT(String::matchNoCase(ABC, "??c")); PEGASUS_TEST_ASSERT(String::match(abc, "*bc")); PEGASUS_TEST_ASSERT(String::match(abc, "a*c")); PEGASUS_TEST_ASSERT(String::match(abc, "ab*")); PEGASUS_TEST_ASSERT(String::match(abc, "a*")); // ATTN-RK-P3-20020603: This match code is broken //PEGASUS_TEST_ASSERT(String::match(abc, "[axy]bc")); PEGASUS_TEST_ASSERT(!String::match(abc, "[xyz]bc")); PEGASUS_TEST_ASSERT(!String::match(abc, "def")); PEGASUS_TEST_ASSERT(!String::match(abc, "[de]bc")); // ATTN-RK-P3-20020603: This match code is broken //PEGASUS_TEST_ASSERT(String::match(abc, "a[a-c]c")); PEGASUS_TEST_ASSERT(!String::match(abc, "a[d-x]c")); // ATTN-RK-P3-20020603: This match code does not yet handle escape chars //PEGASUS_TEST_ASSERT(String::match("*test", "\\*test")); PEGASUS_TEST_ASSERT(String::match("abcdef123", "*[0-9]")); PEGASUS_TEST_ASSERT(String::match("This is a test", "*is*")); PEGASUS_TEST_ASSERT(String::matchNoCase("This is a test", "*IS*")); PEGASUS_TEST_ASSERT(String::match("Hello", "Hello")); PEGASUS_TEST_ASSERT(String::matchNoCase("HELLO", "hello")); PEGASUS_TEST_ASSERT(String::match("This is a test", "This is *")); PEGASUS_TEST_ASSERT(String::match("This is a test", "* is a test")); PEGASUS_TEST_ASSERT(!String::match("Hello", "Goodbye")); String tPattern = "When in the * of human*e??nts it be?ome[sS] [0-9] nec*"; try { String x(reinterpret_cast<const char *>(0)); cerr << "Error: Exception not thrown on NULL passed to" " constructor(const char *)" << endl; } catch ( const NullPointer & ) { // This is the exception that should be thrown. } catch ( ... ) { cerr << "Error: Wrong exception thrown on NULL passed to" " constructor(const char *)" << endl; } try { String x(reinterpret_cast<const Char16 *>(0)); cerr << "Error: Exception not thrown on NULL passed to" " constructor(const Char16 *)" << endl; } catch ( const NullPointer & ) { // This is the exception that should be thrown. } catch ( ... ) { cerr << "Error: Wrong exception thrown on NULL passed to" " constructor(const Char16 *)" << endl; } try { String x; x.assign(reinterpret_cast<const char *>(0)); cerr << "Error: Exception not thrown on NULL passed to" " assign(const char *)" << endl; } catch ( const NullPointer & ) { // This is the exception that should be thrown. } catch ( ... ) { cerr << "Error: Wrong exception thrown on NULL passed to" " assign(const char *)" << endl; } try { String x; x.assign(reinterpret_cast<const Char16 *>(0)); cerr << "Error: Exception not thrown on NULL passed to" " assign(const Char16 *)" << endl; } catch ( const NullPointer & ) { // This is the exception that should be thrown. } catch ( ... ) { cerr << "Error: Wrong exception thrown on NULL passed to" " assign(const Char16 *)" << endl; } try { String x; x.append(reinterpret_cast<const char *>(0)); cerr << "Error: Exception not thrown on NULL passed to" " append(const char *)" << endl; } catch ( const NullPointer & ) { // This is the exception that should be thrown. } catch ( ... ) { cerr << "Error: Wrong exception thrown on NULL passed to" " append(const char *)" << endl; } try { String x; x.append(reinterpret_cast<const Char16 *>(0)); cerr << "Error: Exception not thrown on NULL passed to" " append(const Char16 *)" << endl; } catch ( const NullPointer & ) { // This is the exception that should be thrown. } catch ( ... ) { cerr << "Error: Wrong exception thrown on NULL passed" " to append(const Char16 *)" << endl; } // ATTN-RK-P3-20020603: This match code is broken //PEGASUS_TEST_ASSERT(String::match( // "When in the course of human events it becomes 0 necessary", // tPattern)); //PEGASUS_TEST_ASSERT(String::match( // "When in the xyz of human events it becomes 9 necessary", // tPattern)); //PEGASUS_TEST_ASSERT(String::match( // "When in the of human events it becomes 3 necessary", // tPattern)); } #endif // string() { String s; PEGASUS_TEST_ASSERT(s.size() == 0); PEGASUS_TEST_ASSERT(s[0] == '\0'); } // String(const String& s) { const String s("hello"); const String t = s; PEGASUS_TEST_ASSERT(s.size() == strlen("hello")); PEGASUS_TEST_ASSERT(s == "hello"); PEGASUS_TEST_ASSERT(t.size() == strlen("hello")); PEGASUS_TEST_ASSERT(t == "hello"); } // String(const char*) { const String s("hello"); PEGASUS_TEST_ASSERT(s.size() == strlen("hello")); PEGASUS_TEST_ASSERT(s == "hello"); } // reserve() { String s; s.reserveCapacity(100); PEGASUS_TEST_ASSERT(s.size() == 0); // PEGASUS_TEST_ASSERT(s.getCapacity() >= 100); String t("hello world"); PEGASUS_TEST_ASSERT(t.size() == strlen("hello world")); t.reserveCapacity(500); PEGASUS_TEST_ASSERT(t.size() == strlen("hello world")); PEGASUS_TEST_ASSERT(t == "hello world"); } // assign(const String&) { String s("this is a test"); String t; t = s; PEGASUS_TEST_ASSERT(s.size() == strlen("this is a test")); PEGASUS_TEST_ASSERT(s == "this is a test"); PEGASUS_TEST_ASSERT(t.size() == strlen("this is a test")); PEGASUS_TEST_ASSERT(t == "this is a test"); s = t; PEGASUS_TEST_ASSERT(s.size() == strlen("this is a test")); PEGASUS_TEST_ASSERT(s == "this is a test"); PEGASUS_TEST_ASSERT(t.size() == strlen("this is a test")); PEGASUS_TEST_ASSERT(t == "this is a test"); } // assign(const char*, size_t) { const char MESSAGE[] = "x"; const size_t LENGTH = sizeof(MESSAGE) - 1; String s; s.assign(MESSAGE, LENGTH); PEGASUS_TEST_ASSERT(s.size() == LENGTH); PEGASUS_TEST_ASSERT(s == MESSAGE); String t("dummy", 5); t.assign(MESSAGE, LENGTH); PEGASUS_TEST_ASSERT(t.size() == LENGTH); PEGASUS_TEST_ASSERT(t == MESSAGE); } // assign(const char*) { const char MESSAGE[] = "x"; const size_t LENGTH = sizeof(MESSAGE) - 1; String s; s.assign(MESSAGE); PEGASUS_TEST_ASSERT(s.size() == LENGTH); PEGASUS_TEST_ASSERT(s == MESSAGE); String t("dummy", 5); t.assign(MESSAGE); PEGASUS_TEST_ASSERT(t.size() == LENGTH); PEGASUS_TEST_ASSERT(t == MESSAGE); } // append(const String&) { String s; s.append(String("xxx")); PEGASUS_TEST_ASSERT(s.size() == 3); PEGASUS_TEST_ASSERT(s == "xxx"); s.append(String("yyy")); PEGASUS_TEST_ASSERT(s.size() == 6); PEGASUS_TEST_ASSERT(s == "xxxyyy"); s.append(String("zzz")); PEGASUS_TEST_ASSERT(s.size() == 9); PEGASUS_TEST_ASSERT(s == "xxxyyyzzz"); } // append(const char*) { String s; s.append("xxx"); PEGASUS_TEST_ASSERT(s.size() == 3); PEGASUS_TEST_ASSERT(s == "xxx"); s.append("yyy"); PEGASUS_TEST_ASSERT(s.size() == 6); PEGASUS_TEST_ASSERT(s == "xxxyyy"); s.append("zzz"); PEGASUS_TEST_ASSERT(s.size() == 9); PEGASUS_TEST_ASSERT(s == "xxxyyyzzz"); } // append(const char*) { String s; s.append("xxx"); PEGASUS_TEST_ASSERT(s.size() == 3); PEGASUS_TEST_ASSERT(s == "xxx"); s.append("yyy"); PEGASUS_TEST_ASSERT(s.size() == 6); PEGASUS_TEST_ASSERT(s == "xxxyyy"); s.append("zzz"); PEGASUS_TEST_ASSERT(s.size() == 9); PEGASUS_TEST_ASSERT(s == "xxxyyyzzz"); } // append(char) { String s; for (int i = 'a'; i <= 'z'; i++) { Char16 c = i; s.append(c); } PEGASUS_TEST_ASSERT(s.size() == 26); PEGASUS_TEST_ASSERT(s == "abcdefghijklmnopqrstuvwxyz"); } // clear() { String s("abc"); String t = s; String u = s; s.clear(); PEGASUS_TEST_ASSERT(t.size() == 3); PEGASUS_TEST_ASSERT(t == "abc"); PEGASUS_TEST_ASSERT(t[0] == 'a'); PEGASUS_TEST_ASSERT(u.size() == 3); PEGASUS_TEST_ASSERT(u == "abc"); PEGASUS_TEST_ASSERT(u[0] == 'a'); PEGASUS_TEST_ASSERT(s.size() == 0); PEGASUS_TEST_ASSERT(s[0] == '\0'); t.clear(); PEGASUS_TEST_ASSERT(t.size() == 0); PEGASUS_TEST_ASSERT(t[0] == '\0'); PEGASUS_TEST_ASSERT(t == ""); PEGASUS_TEST_ASSERT(u.size() == 3); PEGASUS_TEST_ASSERT(u == "abc"); PEGASUS_TEST_ASSERT(u[0] == 'a'); PEGASUS_TEST_ASSERT(s.size() == 0); PEGASUS_TEST_ASSERT(s == ""); PEGASUS_TEST_ASSERT(s[0] == '\0'); u.clear(); PEGASUS_TEST_ASSERT(t.size() == 0); PEGASUS_TEST_ASSERT(t == ""); PEGASUS_TEST_ASSERT(t[0] == '\0'); PEGASUS_TEST_ASSERT(u.size() == 0); PEGASUS_TEST_ASSERT(u == ""); PEGASUS_TEST_ASSERT(u[0] == '\0'); PEGASUS_TEST_ASSERT(s.size() == 0); PEGASUS_TEST_ASSERT(s == ""); PEGASUS_TEST_ASSERT(s[0] == '\0'); } // c_str() { String s("abc"); String t("abc"); String u("def"); String v; String w(""); PEGASUS_TEST_ASSERT(s == "abc"); PEGASUS_TEST_ASSERT(t == "abc"); PEGASUS_TEST_ASSERT(u == "def"); PEGASUS_TEST_ASSERT(s == t); PEGASUS_TEST_ASSERT(s != u); PEGASUS_TEST_ASSERT(v == ""); PEGASUS_TEST_ASSERT(v[0] == '\0'); PEGASUS_TEST_ASSERT(v[0] == '\0'); PEGASUS_TEST_ASSERT(w.size() == 0); PEGASUS_TEST_ASSERT(w[0] == '\0'); PEGASUS_TEST_ASSERT(w[0] == '\0'); } // set(size_t, char) { String s("abcdefghijklmnopqrstuvwxyz"); for (int i = 0; i < 26; i++) s[i] = toupper(s[i]); PEGASUS_TEST_ASSERT(s == "ABCDEFGHIJKLMNOPQRSTUVWXYZ"); } // equal(const String&) { String t("abc"); String u("abc"); String v("def"); String w("defg"); String x(""); String y(""); PEGASUS_TEST_ASSERT(String::equal(t, t)); PEGASUS_TEST_ASSERT(String::equal(u, u)); PEGASUS_TEST_ASSERT(String::equal(v, v)); PEGASUS_TEST_ASSERT(String::equal(w, w)); PEGASUS_TEST_ASSERT(String::equal(x, x)); PEGASUS_TEST_ASSERT(String::equal(y, y)); PEGASUS_TEST_ASSERT(String::equal(t, u)); PEGASUS_TEST_ASSERT(String::equal(u, t)); PEGASUS_TEST_ASSERT(!String::equal(t, v)); PEGASUS_TEST_ASSERT(!String::equal(t, w)); PEGASUS_TEST_ASSERT(!String::equal(t, x)); PEGASUS_TEST_ASSERT(!String::equal(t, y)); PEGASUS_TEST_ASSERT(!String::equal(v, t)); PEGASUS_TEST_ASSERT(!String::equal(w, t)); PEGASUS_TEST_ASSERT(!String::equal(x, t)); PEGASUS_TEST_ASSERT(!String::equal(y, t)); PEGASUS_TEST_ASSERT(!String::equal(v, w)); PEGASUS_TEST_ASSERT(!String::equal(w, v)); PEGASUS_TEST_ASSERT(String::equal(x, y)); PEGASUS_TEST_ASSERT(String::equal(y, x)); } // equal(const char*) { String t("abc"); String u("abc"); String v("def"); String w("defg"); String x(""); String y(""); PEGASUS_TEST_ASSERT(String::equal(t, "abc")); PEGASUS_TEST_ASSERT(String::equal(u, "abc")); PEGASUS_TEST_ASSERT(String::equal(v, "def")); PEGASUS_TEST_ASSERT(String::equal(w, "defg")); PEGASUS_TEST_ASSERT(String::equal(x, "")); PEGASUS_TEST_ASSERT(String::equal(y, "")); PEGASUS_TEST_ASSERT(String::equal(t, "abc")); PEGASUS_TEST_ASSERT(String::equal(u, "abc")); PEGASUS_TEST_ASSERT(!String::equal(t, "def")); PEGASUS_TEST_ASSERT(!String::equal(t, "defg")); PEGASUS_TEST_ASSERT(!String::equal(t, "")); PEGASUS_TEST_ASSERT(!String::equal(t, "")); PEGASUS_TEST_ASSERT(!String::equal(v, "abc")); PEGASUS_TEST_ASSERT(!String::equal(w, "abc")); PEGASUS_TEST_ASSERT(!String::equal(x, "abc")); PEGASUS_TEST_ASSERT(!String::equal(y, "abc")); PEGASUS_TEST_ASSERT(!String::equal(v, "defg")); PEGASUS_TEST_ASSERT(!String::equal(w, "def")); PEGASUS_TEST_ASSERT(String::equal(x, "")); PEGASUS_TEST_ASSERT(String::equal(y, "")); } // equali() { String s("abc"); String t("abC"); String u("ABC"); String v("xyz"); String w(""); String x(""); PEGASUS_TEST_ASSERT(String::equalNoCase(s, t)); PEGASUS_TEST_ASSERT(String::equalNoCase(s, u)); PEGASUS_TEST_ASSERT(!String::equalNoCase(s, v)); PEGASUS_TEST_ASSERT(String::equalNoCase(w, x)); PEGASUS_TEST_ASSERT(!String::equalNoCase(w, s)); PEGASUS_TEST_ASSERT(!String::equalNoCase(w, t)); PEGASUS_TEST_ASSERT(!String::equalNoCase(w, v)); } { String t; const char MESSAGE[] = "hello"; const size_t LENGTH = sizeof(MESSAGE) - 1; String s = String(MESSAGE); t = s; String u = String(t); PEGASUS_TEST_ASSERT(t.size() == LENGTH); PEGASUS_TEST_ASSERT(t == MESSAGE); PEGASUS_TEST_ASSERT(s.size() == LENGTH); PEGASUS_TEST_ASSERT(s == MESSAGE); PEGASUS_TEST_ASSERT(u.size() == LENGTH); PEGASUS_TEST_ASSERT(u == MESSAGE); PEGASUS_TEST_ASSERT(t[0] == 'h'); PEGASUS_TEST_ASSERT(t[1] == 'e'); PEGASUS_TEST_ASSERT(t[2] == 'l'); PEGASUS_TEST_ASSERT(t[3] == 'l'); PEGASUS_TEST_ASSERT(t[4] == 'o'); PEGASUS_TEST_ASSERT(t[5] == '\0'); t.append(" world"); PEGASUS_TEST_ASSERT(t.size() == strlen("hello world")); PEGASUS_TEST_ASSERT(t == "hello world"); PEGASUS_TEST_ASSERT(s != "hello world"); PEGASUS_TEST_ASSERT(s == "hello"); PEGASUS_TEST_ASSERT(s.size() == strlen("hello")); t[0] = 'x'; PEGASUS_TEST_ASSERT(t == "xello world"); } // remove() { String s("abcXYZdefLMNOP"); s.remove(0,0); PEGASUS_TEST_ASSERT(s.size() == 14); PEGASUS_TEST_ASSERT(s == "abcXYZdefLMNOP"); s.remove(0, 3); PEGASUS_TEST_ASSERT(s.size() == 11); PEGASUS_TEST_ASSERT(s == "XYZdefLMNOP"); s.remove(3, 3); PEGASUS_TEST_ASSERT(s.size() == 8); PEGASUS_TEST_ASSERT(s == "XYZLMNOP"); s.remove(7, 1); PEGASUS_TEST_ASSERT(s.size() == 7); PEGASUS_TEST_ASSERT(s == "XYZLMNO"); s.remove(0, 1); PEGASUS_TEST_ASSERT(s.size() == 6); PEGASUS_TEST_ASSERT(s == "YZLMNO"); s.remove(2, PEG_NOT_FOUND); PEGASUS_TEST_ASSERT(s.size() == 2); PEGASUS_TEST_ASSERT(s == "YZ"); s.remove(2, 0); PEGASUS_TEST_ASSERT(s.size() == 2); PEGASUS_TEST_ASSERT(s == "YZ"); s.remove(1, 1); PEGASUS_TEST_ASSERT(s.size() == 1); PEGASUS_TEST_ASSERT(s == "Y"); s.remove(0, 1); PEGASUS_TEST_ASSERT(s.size() == 0); PEGASUS_TEST_ASSERT(s == ""); PEGASUS_TEST_ASSERT(s[0] == '\0'); s.remove(0,0); PEGASUS_TEST_ASSERT(s.size() == 0); PEGASUS_TEST_ASSERT(s == ""); PEGASUS_TEST_ASSERT(s[0] == '\0'); } // subString() { String s("one two three"); PEGASUS_TEST_ASSERT(s.subString(0) == "one two three"); PEGASUS_TEST_ASSERT(s.subString(0, 3) == "one"); PEGASUS_TEST_ASSERT(s.subString(4, 3) == "two"); PEGASUS_TEST_ASSERT(s.subString(8, 5) == "three"); PEGASUS_TEST_ASSERT(s.subString(0, 0) == ""); PEGASUS_TEST_ASSERT(s.subString(13, 0) == ""); } // Overflow bool caught_bad_alloc = false; try { String s("junk", Uint32(0xFFFFFFFF)); } catch(...) { caught_bad_alloc = true; } PEGASUS_TEST_ASSERT(caught_bad_alloc); // Added to test funtionality of String(const String& str, Uint32 n) // for memory overflow. Boolean caughtBadAlloc = false; try { String s("abc", 0xFFFF0000); //to check for alloc } catch(const PEGASUS_STD(bad_alloc)&) { caughtBadAlloc = true; } // Added to test funtionality of // void reserveCapacity(Uint32 capacity) for memory overflow. caughtBadAlloc = false; try { String s; s.reserveCapacity(0xFFFF0000); //to check for _reserve } catch (const PEGASUS_STD(bad_alloc)&) { caughtBadAlloc = true; } PEGASUS_TEST_ASSERT(caughtBadAlloc); // Added to test funtionality of // String& append(const char* str, Uint32 size) for memory overflow. caughtBadAlloc = false; try { String s; s.append("xxx", 0xFFFF0000); //to check for _reserve } catch (const PEGASUS_STD(bad_alloc)&) { caughtBadAlloc = true; } PEGASUS_TEST_ASSERT(caughtBadAlloc); // Added to test funtionality of // String& append(const Char16* str, Uint32 n) for memory overflow. caughtBadAlloc = false; try { String s; s.append((Char16 *)"xxx", 0xFFFF0000); //to check for _reserve } catch (const PEGASUS_STD(bad_alloc)&) { caughtBadAlloc = true; } PEGASUS_TEST_ASSERT(caughtBadAlloc); // Added to test funtionality of // String& assign(const char* str, Uint32 n) for memory overflow. caughtBadAlloc = false; try { String s; s.assign("xxx", 0xFFFF0000); //to check for alloc } catch (const PEGASUS_STD(bad_alloc)&) { caughtBadAlloc = true; } PEGASUS_TEST_ASSERT(caughtBadAlloc); // Added to test funtionality of // String& assign(const Char16* str, Uint32 n) for memory overflow. caughtBadAlloc = false; try { String s; s.assign((Char16 *)"xxx", 0xFFFF0000); //to check for alloc } catch (const PEGASUS_STD(bad_alloc)&) { caughtBadAlloc = true; } PEGASUS_TEST_ASSERT(caughtBadAlloc); // Tests for the dump of a bad strings. // 40 good chars, bad char, 10 trailing chars. // Testing the full range of printed data. caughtBadAlloc = false; try { String s1("1234567890123456789012345678901234567890""\xFF""1234567890"); } catch ( Exception& ex ) { caughtBadAlloc = true; PEGASUS_TEST_ASSERT( strstr((const char*)ex.getMessage().getCString(), ": 1234567890123456789012345678901234567890" " 0xFF 0x31 0x32 0x33 0x34 0x35 0x36 0x37 0x38 0x39 0x30") != 0); } PEGASUS_TEST_ASSERT(caughtBadAlloc); // 7 good chars, bad char, 7 trailing chars. // Testing reduced number of chars arround the bad char. caughtBadAlloc = false; try { String s1("0123456""\xAA""0123456"); } catch ( Exception& ex ) { caughtBadAlloc = true; PEGASUS_TEST_ASSERT( strstr((const char*)ex.getMessage().getCString(), ": 0123456 0xAA 0x30 0x31 0x32 0x33 0x34 0x35 0x36") != 0); } PEGASUS_TEST_ASSERT(caughtBadAlloc); // No good chars, bad char , 20 trailing chars // Testing no good chars, bad char at beginning, // more trailing chars available then printed. caughtBadAlloc = false; try { String s1("\xDD""0123456789012345679"); } catch ( Exception& ex ) { caughtBadAlloc = true; PEGASUS_TEST_ASSERT( strstr((const char*)ex.getMessage().getCString(), ": 0xDD 0x30 0x31 0x32 0x33 0x34 0x35 0x36 0x37 0x38 0x39") != 0); } PEGASUS_TEST_ASSERT(caughtBadAlloc); // 50 good chars ( more the printed ), bad char as last char, // no trailing chars. caughtBadAlloc = false; try { String s1("AAAAAAAAAA0123456789012345678901234567890123456789""\xBB"); } catch ( Exception& ex ) { caughtBadAlloc = true; PEGASUS_TEST_ASSERT( strstr((const char*)ex.getMessage().getCString(), ": 0123456789012345678901234567890123456789 0xBB") != 0); } PEGASUS_TEST_ASSERT(caughtBadAlloc); // no good chars, bad char as the only char, no trailing chars. caughtBadAlloc = false; try { String s1("\x80"); } catch ( Exception& ex ) { caughtBadAlloc = true; PEGASUS_TEST_ASSERT( strstr((const char*)ex.getMessage().getCString(),": 0x80") != 0); } PEGASUS_TEST_ASSERT(caughtBadAlloc); cout << argv[0] << " +++++ passed all tests" << endl; char* p = (char*)operator new(88888); operator delete(p); return 0; }
String PepNovoInfile::handlePTMs_(const String& modification, const bool variable) { String locations, key, type; ResidueModification::TermSpecificity ts = ModificationsDB::getInstance()->getModification(modification).getTermSpecificity(); String origin = ModificationsDB::getInstance()->getModification(modification).getOrigin(); double mass = ModificationsDB::getInstance()->getModification(modification).getDiffMonoMass(); String full_name = ModificationsDB::getInstance()->getModification(modification).getFullName(); String full_id = ModificationsDB::getInstance()->getModification(modification).getFullId(); if (variable) { type = "OPTIONAL"; } else { type = "FIXED"; } switch (ts) { case ResidueModification::C_TERM: locations = "C_TERM"; break; case ResidueModification::N_TERM: locations = "N_TERM"; break; case ResidueModification::ANYWHERE: locations = "ALL"; break; default: throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Invalid term specificity", String(ts)); } if (ts == ResidueModification::C_TERM) { key = "$"; } else if (ts == ResidueModification::N_TERM) { key = "^"; } //cout<<"origin: "<<origin<<" loc: "<<locations<<endl; if ((ts == ResidueModification::C_TERM) && (origin == "X")) { origin = "C_TERM"; } else if ((ts == ResidueModification::N_TERM) && (origin == "X")) { origin = "N_TERM"; } else { key = origin; } if (mass >= 0) { key += "+" + String(Math::round(mass)); } else { key += String(Math::round(mass)); } String line = ""; line += origin.toUpper(); line += "\t"; line += mass; line += "\t"; line += type; line += "\t"; line += locations; line += "\t"; line += key; line += "\t"; line += full_name; mods_and_keys_[key] = full_id; return line; }
ExitCodes main_(int, const char**) { //------------------------------------------------------------- // parsing parameters //------------------------------------------------------------- String inputfile_name = getStringOption_("in"); String outputfile_name = getStringOption_("out"); Param fit_algorithm = getParam_().copy("fit_algorithm:", true); fit_algorithm.setValue("out_plot", getStringOption_("out_plot")); // re-assemble full param (was moved to top-level) bool split_charge = getFlag_("split_charge"); bool top_hits_only = getFlag_("top_hits_only"); double fdr_for_targets_smaller = getDoubleOption_("fdr_for_targets_smaller"); bool target_decoy_available = false; bool ignore_bad_data = getFlag_("ignore_bad_data"); bool prob_correct = getFlag_("prob_correct"); // Set fixed e-value threshold smallest_e_value_ = numeric_limits<double>::denorm_min(); //------------------------------------------------------------- // reading input //------------------------------------------------------------- IdXMLFile file; vector<ProteinIdentification> protein_ids; vector<PeptideIdentification> peptide_ids; file.load(inputfile_name, protein_ids, peptide_ids); vector<double> scores; vector<double> decoy; vector<double> target; set<Int> charges; PosteriorErrorProbabilityModel PEP_model; PEP_model.setParameters(fit_algorithm); StringList search_engines = ListUtils::create<String>("XTandem,OMSSA,MASCOT,SpectraST,MyriMatch,SimTandem,MSGFPlus,MS-GF+,Comet"); //------------------------------------------------------------- // calculations //------------------------------------------------------------- if (split_charge) { for (vector<PeptideIdentification>::iterator pep_it = peptide_ids.begin(); pep_it != peptide_ids.end(); ++pep_it) { vector<PeptideHit>& hits = pep_it->getHits(); for (std::vector<PeptideHit>::iterator hit_it = hits.begin(); hit_it != hits.end(); ++hit_it) { charges.insert(hit_it->getCharge()); } } if (charges.empty()) { throw Exception::ElementNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "no charges found!"); } } for (vector<PeptideIdentification>::iterator pep_it = peptide_ids.begin(); pep_it != peptide_ids.end(); ++pep_it) { if (!pep_it->getHits().empty()) { target_decoy_available = ((pep_it->getScoreType() == "q-value") && pep_it->getHits()[0].metaValueExists("target_decoy")); break; } } set<Int>::iterator charge_it = charges.begin(); // charges can be empty, no problem if split_charge is not set if (split_charge && charges.empty()) { throw Exception::Precondition(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "'split_charge' is set, but the list of charge states is empty"); } map<String, vector<vector<double> > > all_scores; char splitter = ','; // to split the engine from the charge state later on do { for (StringList::iterator engine_it = search_engines.begin(); engine_it != search_engines.end(); ++engine_it) { for (vector<ProteinIdentification>::iterator prot_it = protein_ids.begin(); prot_it != protein_ids.end(); ++prot_it) { String searchengine = prot_it->getSearchEngine(); if ((*engine_it == searchengine) || (*engine_it == searchengine.toUpper())) { for (vector<PeptideIdentification>::iterator pep_it = peptide_ids.begin(); pep_it != peptide_ids.end(); ++pep_it) { if (prot_it->getIdentifier() == pep_it->getIdentifier()) { vector<PeptideHit>& hits = pep_it->getHits(); if (top_hits_only) { pep_it->sort(); if (!hits.empty() && (!split_charge || hits[0].getCharge() == *charge_it)) { double score = getScore_(*engine_it, hits[0]); if (!boost::math::isnan(score)) // issue #740: ignore scores with 0 values, otherwise you will get the error "unable to fit data" { scores.push_back(score); if (target_decoy_available) { if (hits[0].getScore() < fdr_for_targets_smaller) { target.push_back(score); } else { decoy.push_back(score); } } } } } else { for (std::vector<PeptideHit>::iterator hit_it = hits.begin(); hit_it != hits.end(); ++hit_it) { if (!split_charge || (hit_it->getCharge() == *charge_it)) { double score = getScore_(*engine_it, *hit_it); if (!boost::math::isnan(score)) // issue #740: ignore scores with 0 values, otherwise you will get the error "unable to fit data" { scores.push_back(score); } } } } } } } } if (scores.size() > 2) { vector<vector<double> > tmp; tmp.push_back(scores); tmp.push_back(target); tmp.push_back(decoy); if (split_charge) { String engine_with_charge_state = *engine_it + String(splitter) + String(*charge_it); all_scores.insert(make_pair(engine_with_charge_state, tmp)); } else { all_scores.insert(make_pair(*engine_it, tmp)); } } scores.clear(); target.clear(); decoy.clear(); } if (split_charge) ++charge_it; } while (charge_it != charges.end()); if (all_scores.empty()) { writeLog_("No data collected. Check whether search engine is supported."); if (!ignore_bad_data) return INPUT_FILE_EMPTY; } String out_plot = fit_algorithm.getValue("out_plot").toString().trim(); for (map<String, vector<vector<double> > >::iterator score_it = all_scores.begin(); score_it != all_scores.end(); ++score_it) { vector<String> engine_info; score_it->first.split(splitter, engine_info); String engine = engine_info[0]; Int charge = -1; if (engine_info.size() == 2) { charge = engine_info[1].toInt(); } if (split_charge) { // only adapt plot output if plot is requested (this badly violates the output rules and needs to change!) // one way to fix this: plot charges into a single file (no renaming of output file needed) - but this requires major code restructuring if (!out_plot.empty()) fit_algorithm.setValue("out_plot", out_plot + "_charge_" + String(charge)); PEP_model.setParameters(fit_algorithm); } const bool return_value = PEP_model.fit(score_it->second[0]); if (!return_value) writeLog_("Unable to fit data. Algorithm did not run through for the following search engine: " + engine); if (!return_value && !ignore_bad_data) return UNEXPECTED_RESULT; if (return_value) { // plot target_decoy if (!out_plot.empty() && top_hits_only && target_decoy_available && (score_it->second[0].size() > 0)) { PEP_model.plotTargetDecoyEstimation(score_it->second[1], score_it->second[2]); //target, decoy } bool unable_to_fit_data = true; bool data_might_not_be_well_fit = true; for (vector<ProteinIdentification>::iterator prot_it = protein_ids.begin(); prot_it != protein_ids.end(); ++prot_it) { String searchengine = prot_it->getSearchEngine(); if ((engine == searchengine) || (engine == searchengine.toUpper())) { for (vector<PeptideIdentification>::iterator pep_it = peptide_ids.begin(); pep_it != peptide_ids.end(); ++pep_it) { if (prot_it->getIdentifier() == pep_it->getIdentifier()) { String score_type = pep_it->getScoreType() + "_score"; vector<PeptideHit> hits = pep_it->getHits(); for (std::vector<PeptideHit>::iterator hit_it = hits.begin(); hit_it != hits.end(); ++hit_it) { if (!split_charge || (hit_it->getCharge() == charge)) { double score; hit_it->setMetaValue(score_type, hit_it->getScore()); score = getScore_(engine, *hit_it); if (boost::math::isnan(score)) // issue #740: ignore scores with 0 values, otherwise you will get the error "unable to fit data" { score = 1.0; } else { score = PEP_model.computeProbability(score); if ((score > 0.0) && (score < 1.0)) unable_to_fit_data = false; // only if all it->second[0] are 0 or 1 unable_to_fit_data stays true if ((score > 0.2) && (score < 0.8)) data_might_not_be_well_fit = false; //same as above } hit_it->setScore(score); if (prob_correct) { hit_it->setScore(1.0 - score); } else { hit_it->setScore(score); } } } pep_it->setHits(hits); } if (prob_correct) { pep_it->setScoreType("Posterior Probability"); pep_it->setHigherScoreBetter(true); } else { pep_it->setScoreType("Posterior Error Probability"); pep_it->setHigherScoreBetter(false); } } } } if (unable_to_fit_data) writeLog_(String("Unable to fit data for search engine: ") + engine); if (unable_to_fit_data && !ignore_bad_data) return UNEXPECTED_RESULT; if (data_might_not_be_well_fit) writeLog_(String("Data might not be well fitted for search engine: ") + engine); } } //------------------------------------------------------------- // writing output //------------------------------------------------------------- file.store(outputfile_name, protein_ids, peptide_ids); return EXECUTION_OK; }
int main(int argc, char** argv) { String a; a = "Testing..."; cout << a << endl; cout << "length: " << a.length() << endl; cout << "capacity: " << a.capacity() << endl; a = a + "one two three"; cout << a << endl; cout << "length: " << a.length() << endl; cout << "capacity: " << a.capacity() << endl; a = "stuff on the front:" + a; cout << a << endl; cout << "length: " << a.length() << endl; cout << "capacity: " << a.capacity() << endl; long intval = 0; if (String("32").parseInt(intval)) cout << "Converting '32' to int: " << intval << endl; else cout << "Error converting string to int.\n"; double doubleval = 0.0; String("3.141592654").parseDouble(doubleval); cout << "Converting 3.141592654 to double: " << doubleval << endl; long hexval = 0; if (String("0x34ab").parseHex(hexval)) cout << "Converting 0x34ab to " << hexval << " (Should be 13483)" << endl; else cout << "Hex conversion failed.\n"; String tflag("true"); String fflag("false"); bool boolval; tflag.parseBool(boolval); if (boolval) cout << "This should have been true (and was)" << endl; else cout << "tflag was false and should have been true." << endl; fflag.parseBool(boolval); if (boolval) cout << "fflag should have been false and wasn't." << endl; else cout << "fflag was false and should have been." << endl; char c; a.charAt(3, c); cout << "\nCharacter at position 3: '" << c << "' \n"; String b("cat"); String d = "cat"; if (b == d) cout << "Yup, equal.\n"; else cout << "Nope, not equal.\n"; if (b == "fark") cout << b << " is less than fark\n"; cout << a.toLower() << endl; cout << a.toUpper() << endl; cout << "Substring..." << endl; String substr_test = "this is a weird string. Much odd."; cout << substr_test.substring(4, 4) << endl; cout << "Regular Expressions\n"; String astring = "This is a test."; if (astring.matches("is a")) cout << " Matched!\n"; else cout << " Didn't match.\n"; String csvstuff = "3.1415 2.71828 42 testing"; ArrayList<String> fields = csvstuff.split(" +"); }
ExitCodes main_(int, const char **) { //---------------------------------------------------------------- // load data //---------------------------------------------------------------- String in = getStringOption_("in"); String in_featureXML = getStringOption_("in_featureXML"); String out = getStringOption_("out"); String format = getStringOption_("out_type"); if (format.trim() == "") // get from filename { try { format = out.suffix('.'); } catch (Exception::ElementNotFound & /*e*/) { format = "nosuffix"; } StringListUtils::toUpper(out_formats_); if (!ListUtils::contains(out_formats_, format.toUpper())) { LOG_ERROR << "No explicit image output format was provided via 'out_type', and the suffix ('" << format << "') does not resemble a valid type. Please fix one of them." << std::endl; return ILLEGAL_PARAMETERS; } } MSExperiment<> exp; MzMLFile f; f.setLogType(log_type_); f.load(in, exp); exp.updateRanges(1); SignedSize rows = getIntOption_("height"); if (rows == 0) { rows = exp.size(); } if (rows <= 0) { writeLog_("Error: Zero rows is not possible."); return ILLEGAL_PARAMETERS; } SignedSize cols = getIntOption_("width"); if (cols == 0) { cols = UInt(ceil(exp.getMaxMZ() - exp.getMinMZ())); } if (cols <= 0) { writeLog_("Error: Zero columns is not possible."); return ILLEGAL_PARAMETERS; } //---------------------------------------------------------------- //Do the actual resampling BilinearInterpolation<double, double> bilip; bilip.getData().resize(rows, cols); if (!getFlag_("transpose")) { // scans run bottom-up: bilip.setMapping_0(0, exp.getMaxRT(), rows - 1, exp.getMinRT()); // peaks run left-right: bilip.setMapping_1(0, exp.getMinMZ(), cols - 1, exp.getMaxMZ()); for (MSExperiment<>::Iterator spec_iter = exp.begin(); spec_iter != exp.end(); ++spec_iter) { if (spec_iter->getMSLevel() != 1) continue; for (MSExperiment<>::SpectrumType::ConstIterator peak1_iter = spec_iter->begin(); peak1_iter != spec_iter->end(); ++peak1_iter) { bilip.addValue(spec_iter->getRT(), peak1_iter->getMZ(), peak1_iter->getIntensity()); } } } else // transpose { // spectra run bottom-up: bilip.setMapping_0(0, exp.getMaxMZ(), rows - 1, exp.getMinMZ()); // scans run left-right: bilip.setMapping_1(0, exp.getMinRT(), cols - 1, exp.getMaxRT()); for (MSExperiment<>::Iterator spec_iter = exp.begin(); spec_iter != exp.end(); ++spec_iter) { if (spec_iter->getMSLevel() != 1) continue; for (MSExperiment<>::SpectrumType::ConstIterator peak1_iter = spec_iter->begin(); peak1_iter != spec_iter->end(); ++peak1_iter) { bilip.addValue(peak1_iter->getMZ(), spec_iter->getRT(), peak1_iter->getIntensity()); } } } //---------------------------------------------------------------- //create and store image int scans = (int) bilip.getData().sizePair().first; int peaks = (int) bilip.getData().sizePair().second; MultiGradient gradient; String gradient_str = getStringOption_("gradient"); if (gradient_str != "") { gradient.fromString(String("Linear|") + gradient_str); } else { gradient.fromString("Linear|0,#FFFFFF;2,#FFFF00;11,#FFAA00;32,#FF0000;55,#AA00FF;78,#5500FF;100,#000000"); } bool use_log = getFlag_("log_intensity"); writeDebug_("log_intensity: " + String(use_log), 1); QImage image(peaks, scans, QImage::Format_RGB32); string s = getStringOption_("background_color"); QColor background_color(s.c_str()); string feature_color_string = getStringOption_("feature_color"); QColor feature_color(feature_color_string.c_str()); QPainter * painter = new QPainter(&image); painter->setPen(background_color); painter->fillRect(0, 0, peaks, scans, Qt::SolidPattern); delete painter; double factor = getDoubleOption_("max_intensity"); if (factor == 0) { factor = (*std::max_element(bilip.getData().begin(), bilip.getData().end())); } // logarithmize max. intensity as well: if (use_log) factor = std::log(factor); factor /= 100.0; for (int i = 0; i < scans; ++i) { for (int j = 0; j < peaks; ++j) { double value = bilip.getData().getValue(i, j); if (use_log) value = std::log(value); if (value > 1e-4) { image.setPixel(j, i, gradient.interpolatedColorAt(value / factor).rgb()); } else { image.setPixel(j, i, background_color.rgb()); } } } if (getFlag_("precursors")) { markMS2Locations_(exp, image, getFlag_("transpose"), getStringOption_("precursor_color").toQString(), Size(getIntOption_("precursor_size"))); } if (!in_featureXML.empty()) { FeatureMap feature_map; FeatureXMLFile ff; ff.load(in_featureXML, feature_map); markFeatureLocations_(feature_map, exp, image, getFlag_("transpose"), feature_color); } if (image.save(out.toQString(), format.c_str())) return EXECUTION_OK; else return CANNOT_WRITE_OUTPUT_FILE; }
Protein* PeptideBuilder::construct() { if (fragment_db_ == 0) { Log.warn() << "PeptideBuilder::construct(): no FragmengDB given!" << std::endl; return 0; } if (sequence_.empty()) { Log.warn() << "PeptideBuilder::construct(): no amino acid sequence specified." << std::endl; return 0; } int id = 1; Protein *protein = new Protein(proteinname_); Chain *chain = new Chain(chainname_); // create the first residue Residue* residue = createResidue_(sequence_[0].getType(), id); chain->insert(*residue); Residue* residueold = residue; std::vector<AminoAcidDescriptor>::iterator i = sequence_.begin(); ++id; // consistency check for empty sequences and sequences of length < 2!! // loop for the remaining residues ; for (++i; i != sequence_.end(); ++i) { // We have to take care of two special cases: // - the residue we are looking at is proline // - the last residue was proline String type = (i-1)->getType(); type.toUpper(); // special case: residue is a proline type = i->getType(); type.toUpper(); is_proline_ = (type == "PRO") ? true : false; Residue* residue2 = createResidue_(i->getType(), id); insert_(*residue2, *residueold); chain->insert(*residue2); // set the torsion angle transform_(i->getPhi(), (i-1)->getPsi(),*residueold, *residue2); peptide_(*residueold,*residue2); // set the peptide bond angle omega setOmega_(*residueold, *residue2, i->getOmega()); residueold=residue2; ++id; } protein->insert(*chain); // read the names for a unique nomenclature protein->apply(fragment_db_->normalize_names); // add missing bonds and atoms (including side chains!) ReconstructFragmentProcessor rfp(*fragment_db_); protein->apply(rfp); protein->apply(fragment_db_->build_bonds); return protein; }