/** * The function converts the character string into double. * * @param aStr [TInt8*] String Value. * * @return The function returns double conversion of the string value if its successfull. * Otherwise, zero is returned. */ TReal64 ALGO_ATOF(const TInt8* aStr) { TReal64 number; TInt32 exponent; TInt32 negative; TInt8 *p = (TInt8 *) aStr; TReal64 p10; TInt32 n; TInt32 num_digits; TInt32 num_decimals; // Skip leading whitespace while (IsSpace(*p)) { p++; } // Handle optional sign negative = 0; switch (*p) { case '-': negative = 1; // Fall through to increment position case '+': p++; } number = 0.; exponent = 0; num_digits = 0; num_decimals = 0; // Process string of digits while (IsDigit(*p)) { number = number * 10. + (*p - '0'); p++; num_digits++; } // Process decimal part if (*p == '.') { p++; while (IsDigit(*p)) { number = number * 10. + (*p - '0'); p++; num_digits++; num_decimals++; } exponent -= num_decimals; } if (num_digits == 0) { return 0.0; } // Correct for sign if (negative) { number = -number; } // Process an exponent string if (*p == 'e' || *p == 'E') { // Handle optional sign negative = 0; switch(*++p) { case '-': negative = 1; // Fall through to increment pos case '+': p++; } // Process string of digits n = 0; while (IsDigit(*p)) { n = n * 10 + (*p - '0'); p++; } if (negative) exponent -= n; else exponent += n; } // Scale the result p10 = 10.; n = exponent; if (n < 0) { n = -n; } while (n) { if (n & 1) { if (exponent < 0) { number /= p10; } else { number *= p10; } } n >>= 1; p10 *= p10; } return number; }
const TCHAR* TiXmlAttribute::Parse( const TCHAR* p, TiXmlParsingData* data ) { p = SkipWhiteSpace( p ); if ( !p || !*p ) return 0; int tabsize = 4; if ( document ) tabsize = document->TabSize(); // TiXmlParsingData data( p, prevData ); if ( data ) { data->Stamp( p ); location = data->Cursor(); } // Read the name, the '=' and the value. const TCHAR* pErr = p; p = ReadName( p, &name ); if ( !p || !*p ) { if ( document ) document->SetError( TIXML_ERROR_READING_ATTRIBUTES, pErr, data ); return 0; } p = SkipWhiteSpace( p ); if ( !p || !*p || *p != '=' ) { if ( document ) document->SetError( TIXML_ERROR_READING_ATTRIBUTES, p, data ); return 0; } ++p; // skip '=' p = SkipWhiteSpace( p ); if ( !p || !*p ) { if ( document ) document->SetError( TIXML_ERROR_READING_ATTRIBUTES, p, data ); return 0; } const TCHAR* end; if ( *p == '\'' ) { ++p; end = TEXT("\'"); p = ReadText( p, &value, false, end, false ); } else if ( *p == '"' ) { ++p; end = TEXT("\""); p = ReadText( p, &value, false, end, false ); } else { // All attribute values should be in single or double quotes. // But this is such a common error that the parser will try // its best, even without them. value = TEXT(""); while ( p && *p // existence && !IsSpace( *p ) && *p != '\n' && *p != '\r' // whitespace && *p != '/' && *p != '>' ) // tag end { value += *p; ++p; } } return p; }
void CMapiMessage::ProcessContentType() { m_mimeContentType.Truncate(); m_mimeBoundary.Truncate(); m_mimeCharset.Truncate(); const char* contentType = m_headers.Value(CMapiMessageHeaders::hdrContentType); if (!contentType) return; const char *begin = contentType, *end; nsCString tStr; // Note: this isn't a complete parser, the content type // we extract could have rfc822 comments in it while (*begin && IsSpace(*begin)) begin++; if (!(*begin)) return; end = begin; while (*end && (*end != ';')) end++; m_mimeContentType.Assign(begin, end-begin); if (!(*end)) return; // look for "boundary=" begin = end + 1; bool haveB; bool haveC; while (*begin) { haveB = false; haveC = false; while (*begin && IsSpace(*begin)) begin++; if (!(*begin)) return; end = begin; while (*end && (*end != '=')) end++; if (end - begin) { tStr.Assign(begin, end-begin); if (tStr.LowerCaseEqualsLiteral("boundary")) haveB = true; else if (tStr.LowerCaseEqualsLiteral("charset")) haveC = true; } if (!(*end)) return; begin = end+1; while (*begin && IsSpace(*begin)) begin++; if (*begin == '"') { begin++; bool slash = false; tStr.Truncate(); while (*begin) { if (slash) { slash = false; tStr.Append(*begin); } else if (*begin == '"') break; else if (*begin != '\\') tStr.Append(*begin); else slash = true; begin++; } if (haveB) { m_mimeBoundary = tStr; haveB = false; } if (haveC) { m_mimeCharset = tStr; haveC = false; } if (!(*begin)) return; begin++; } tStr.Truncate(); while (*begin && (*begin != ';')) { tStr.Append(*(begin++)); } if (haveB) { tStr.Trim(kWhitespace); m_mimeBoundary = tStr; } if (haveC) { tStr.Trim(kWhitespace); m_mimeCharset = tStr; } if (*begin) begin++; } }
nsresult nsLineBreaker::AppendText(nsIAtom* aHyphenationLanguage, const char16_t* aText, uint32_t aLength, uint32_t aFlags, nsILineBreakSink* aSink) { NS_ASSERTION(aLength > 0, "Appending empty text..."); uint32_t offset = 0; // Continue the current word if (mCurrentWord.Length() > 0) { NS_ASSERTION(!mAfterBreakableSpace && !mBreakHere, "These should not be set"); while (offset < aLength && !IsSpace(aText[offset])) { mCurrentWord.AppendElement(aText[offset]); if (!mCurrentWordContainsComplexChar && IsComplexChar(aText[offset])) { mCurrentWordContainsComplexChar = true; } UpdateCurrentWordLanguage(aHyphenationLanguage); ++offset; } if (offset > 0) { mTextItems.AppendElement(TextItem(aSink, 0, offset, aFlags)); } if (offset == aLength) return NS_OK; // We encountered whitespace, so we're done with this word nsresult rv = FlushCurrentWord(); if (NS_FAILED(rv)) return rv; } nsAutoTArray<uint8_t,4000> breakState; if (aSink) { if (!breakState.AppendElements(aLength)) return NS_ERROR_OUT_OF_MEMORY; } bool noCapitalizationNeeded = true; nsTArray<bool> capitalizationState; if (aSink && (aFlags & BREAK_NEED_CAPITALIZATION)) { if (!capitalizationState.AppendElements(aLength)) return NS_ERROR_OUT_OF_MEMORY; memset(capitalizationState.Elements(), false, aLength*sizeof(bool)); noCapitalizationNeeded = false; } uint32_t start = offset; bool noBreaksNeeded = !aSink || ((aFlags & NO_BREAKS_NEEDED_FLAGS) == NO_BREAKS_NEEDED_FLAGS && !mBreakHere && !mAfterBreakableSpace); if (noBreaksNeeded && noCapitalizationNeeded) { // Skip to the space before the last word, since either the break data // here is not needed, or no breaks are set in the sink and there cannot // be any breaks in this chunk; and we don't need to do word-initial // capitalization. All we need is the context for the next chunk (if any). offset = aLength; while (offset > start) { --offset; if (IsSpace(aText[offset])) break; } } uint32_t wordStart = offset; bool wordHasComplexChar = false; nsRefPtr<nsHyphenator> hyphenator; if ((aFlags & BREAK_USE_AUTO_HYPHENATION) && !(aFlags & BREAK_SUPPRESS_INSIDE) && aHyphenationLanguage) { hyphenator = nsHyphenationManager::Instance()->GetHyphenator(aHyphenationLanguage); } for (;;) { char16_t ch = aText[offset]; bool isSpace = IsSpace(ch); bool isBreakableSpace = isSpace && !(aFlags & BREAK_SUPPRESS_INSIDE); if (aSink && !noBreaksNeeded) { breakState[offset] = mBreakHere || (mAfterBreakableSpace && !isBreakableSpace) || (mWordBreak == nsILineBreaker::kWordBreak_BreakAll) ? gfxTextRun::CompressedGlyph::FLAG_BREAK_TYPE_NORMAL : gfxTextRun::CompressedGlyph::FLAG_BREAK_TYPE_NONE; } mBreakHere = false; mAfterBreakableSpace = isBreakableSpace; if (isSpace) { if (offset > wordStart && aSink) { if (!(aFlags & BREAK_SUPPRESS_INSIDE)) { if (wordHasComplexChar) { // Save current start-of-word state because GetJISx4051Breaks will // set it to false uint8_t currentStart = breakState[wordStart]; nsContentUtils::LineBreaker()-> GetJISx4051Breaks(aText + wordStart, offset - wordStart, mWordBreak, breakState.Elements() + wordStart); breakState[wordStart] = currentStart; } if (hyphenator) { FindHyphenationPoints(hyphenator, aText + wordStart, aText + offset, breakState.Elements() + wordStart); } } if (!noCapitalizationNeeded) { SetupCapitalization(aText + wordStart, offset - wordStart, capitalizationState.Elements() + wordStart); } } wordHasComplexChar = false; ++offset; if (offset >= aLength) break; wordStart = offset; } else { if (!wordHasComplexChar && IsComplexChar(ch)) { wordHasComplexChar = true; } ++offset; if (offset >= aLength) { // Save this word mCurrentWordContainsComplexChar = wordHasComplexChar; uint32_t len = offset - wordStart; char16_t* elems = mCurrentWord.AppendElements(len); if (!elems) return NS_ERROR_OUT_OF_MEMORY; memcpy(elems, aText + wordStart, sizeof(char16_t)*len); mTextItems.AppendElement(TextItem(aSink, wordStart, len, aFlags)); // Ensure that the break-before for this word is written out offset = wordStart + 1; UpdateCurrentWordLanguage(aHyphenationLanguage); break; } } } if (aSink) { if (!noBreaksNeeded) { aSink->SetBreaks(start, offset - start, breakState.Elements() + start); } if (!noCapitalizationNeeded) { aSink->SetCapitalization(start, offset - start, capitalizationState.Elements() + start); } } return NS_OK; }
int eval_space(char c) { return (0 != IsSpace(c)); }
void SymbolParserThread::ParseFileSymbols(wxInputStream& input, std::vector<Symbol*>& symbols) { if (!input.IsOk()) { return; } wxString token; unsigned int lineNumber = 1; Symbol *return_symbol = nullptr; wxStack<Symbol *> symStack; symStack.push(nullptr); std::vector<Token> tokens; while (GetToken(input, token, lineNumber)) { tokens.emplace_back(token, lineNumber); } for (unsigned current_token = 0; current_token < tokens.size(); ++current_token) { token = tokens[current_token].token; lineNumber = tokens[current_token].lineNumber; if (token == "function") { unsigned int defLineNumber = lineNumber; Symbol *function = nullptr; // Lua functions can have these forms: // function (...) // function Name (...) // function Module.Function (...) // function Class:Method (...) wxString t1; if (!GetNextToken(tokens, t1, lineNumber, current_token)) break; if (t1 == "(") { // The form function (...) which doesn't have a name. If we // were being really clever we could check to see what is being // done with this value, but we're not. continue; } wxString t2; if (!GetNextToken(tokens, t2, lineNumber, current_token)) break; if (t2 == "(") { function = new Symbol(symStack.top(), t1, defLineNumber); if (return_symbol) { function->typeSymbol = return_symbol; return_symbol = nullptr; } // The form function Name (...). symbols.push_back(function); } else { wxString t3; if (!GetNextToken(tokens, t3, lineNumber, current_token)) break; if (t2 == "." || t2 == ":") { Symbol *module = GetSymbol(t1, symbols); if (module == nullptr) { module = new Symbol(symStack.top(), t1, defLineNumber, SymbolType::Module); symbols.push_back(module); } function = new Symbol(module, t3, defLineNumber); if (return_symbol) { function->typeSymbol = return_symbol; return_symbol = nullptr; } symbols.push_back(function); } } if (function) symStack.push(function); } else if (token == "decodadef") { //A decodadef will be in the form: //decodadef name { Definitions } //decodadef name ret unsigned int defLineNumber = lineNumber; wxString moduleName; if (!GetNextToken(tokens, moduleName, lineNumber, current_token)) break; wxString t1 = PeekNextToken(tokens, current_token, lineNumber); if (t1 == "{") { if (!GetNextToken(tokens, t1, lineNumber, current_token)) break; //outputWin->OutputMessage("Processing " + moduleName); Symbol *module = GetSymbol(moduleName, symbols); if (module == nullptr) { module = new Symbol(symStack.top(), moduleName, lineNumber, SymbolType::Type); symbols.push_back(module); } DecodaDefRecursive(symbols, lineNumber, module, tokens, current_token); } else { DecodaDefFunction(symbols, lineNumber, nullptr, tokens, current_token, moduleName); } } else if (token == "end") { if (symStack.size() > 1) symStack.pop(); } else if (token == "decodaprefix") { //A decodaprefix will be in the form: //decodaprefix Module name /* decodaprefix this __FILENAME__ decodaprefix this { Weapon nil } */ unsigned int defLineNumber = lineNumber; wxString moduleName; if (!GetNextToken(tokens, moduleName, lineNumber, current_token)) break; Symbol *module = GetSymbol(moduleName, symbols, SymbolType::Prefix); if (module == nullptr) { module = new Symbol(nullptr, moduleName, defLineNumber, SymbolType::Prefix); symbols.push_back(module); } wxString t1; if (!GetNextToken(tokens, t1, lineNumber, current_token)) break; //List of if (t1 == "{") { DecodaPrefixRecursive(symbols, lineNumber, module, tokens, current_token); } else { Symbol *sym_prefix = new Symbol(module, t1, defLineNumber, SymbolType::Prefix); sym_prefix->requiredModule = moduleName; symbols.push_back(sym_prefix); } } else if (token == "decodareturn") { //A decodaprefix will be in the form: //decodareturn Module unsigned int defLineNumber = lineNumber; wxString moduleName; if (!GetNextToken(tokens, moduleName, lineNumber, current_token)) break; Symbol *module = GetSymbol(moduleName, symbols); if (module == nullptr) { module = new Symbol(symStack.top(), moduleName, lineNumber, SymbolType::Type); symbols.push_back(module); } return_symbol = module; } else if (token == "=") { unsigned int defLineNumber = lineNumber; //If we find an equal sign, we need to find the left and right hand side unsigned start = current_token; //First handle +=, -=, *=, /= wxString prev = PeekPrevToken(tokens, current_token, lineNumber); if (prev == "+" || prev == "-" || prev == "*" || prev == "/") GetPrevToken(tokens, prev, lineNumber, current_token); wxStack<wxString> lhs_stack; wxString lhs; if (!GetPrevToken(tokens, lhs, lineNumber, current_token)) break; lhs_stack.push(lhs); int currentLine = lineNumber; prev = PeekPrevToken(tokens, current_token, lineNumber); while ((prev == "." || prev == ":" || prev == ")" || prev == "]") && lineNumber == currentLine) { if (prev == "." || prev == ":") { GetPrevToken(tokens, prev, lineNumber, current_token); lhs_stack.push(prev); wxString part; if (!GetPrevToken(tokens, part, lineNumber, current_token)) return; if (part == ")" || part == "]") { current_token++; prev = part; continue; } lhs_stack.push(part); } else if (prev == ")" || prev == "]") { GetPrevToken(tokens, prev, lineNumber, current_token); lhs_stack.push(prev); wxString open; wxString close; if (prev == ")") { open = "("; close = ")"; } else if (prev == "]") { open = "["; close = "]"; } int parenStack = 0; wxString part; if (!GetPrevToken(tokens, part, lineNumber, current_token)) return; for (;;) { if (part == close) parenStack++; if (part == open) { if (parenStack == 0) break; parenStack--; } lhs_stack.push(part); if (!GetPrevToken(tokens, part, lineNumber, current_token)) return; } lhs_stack.push(part); if (!GetPrevToken(tokens, part, lineNumber, current_token)) return; lhs_stack.push(part); } prev = PeekPrevToken(tokens, current_token, lineNumber); } //Parse rhs current_token = start; //First handle +=, -=, *=, /= wxString next = PeekNextToken(tokens, current_token, lineNumber); bool valid = true; for (int i = 0; i < next.size(); ++i) { if (IsSymbol(next[i]) || IsSpace(next[i])) { valid = false; break; } } wxString rhs; if (valid) { GetNextToken(tokens, next, lineNumber, current_token); rhs.Append(next); next = PeekNextToken(tokens, current_token, lineNumber); while ((next == "." || next == ":" || next == "(" || next == "[") && lineNumber == currentLine) { if (next == "." || next == ":") { GetNextToken(tokens, next, lineNumber, current_token); rhs.Append(next); wxString part; if (!GetNextToken(tokens, part, lineNumber, current_token)) return; rhs.Append(part); } else if (next == "(" || next == "[") { GetNextToken(tokens, next, lineNumber, current_token); rhs.Append(next); wxString open; wxString close; if (next == "(") { open = "("; close = ")"; } else if (next == "[") { open = "["; close = "]"; } int parenStack = 0; wxString part; if (!GetNextToken(tokens, part, lineNumber, current_token)) return; for (;;) { if (part == open) parenStack++; if (part == close) { if (parenStack == 0) break; parenStack--; } rhs.Append(part); if (!GetNextToken(tokens, part, lineNumber, current_token)) return; } rhs.Append(part); } next = PeekNextToken(tokens, current_token, lineNumber); } } //Build up the strings with the stacks if (lhs_stack.size() > 0 && rhs.size() > 0) { lhs.Empty(); while (!lhs_stack.empty()) { lhs.Append(lhs_stack.top()); lhs_stack.pop(); } Symbol *assignment = new Symbol(symStack.top(), lhs, defLineNumber, SymbolType::Assignment); assignment->rhs = rhs; symbols.push_back(assignment); } //Reset token current_token = start; } } }
nsresult nsSMILParserUtils::ParseClockValue(const nsAString& aSpec, nsSMILTimeValue* aResult, PRUint32 aFlags, // = 0 PRBool* aIsMedia) // = nsnull { nsSMILTime offset = 0L; double component = 0.0; PRInt8 sign = 0; PRUint8 colonCount = 0; PRBool started = PR_FALSE; PRBool isValid = PR_TRUE; PRInt32 metricMultiplicand = MSEC_PER_SEC; PRBool numIsReal = PR_FALSE; PRBool prevNumCouldBeMin = PR_FALSE; PRBool numCouldBeMin = PR_FALSE; PRBool numCouldBeSec = PR_FALSE; PRBool isIndefinite = PR_FALSE; if (aIsMedia) { *aIsMedia = PR_FALSE; } NS_ConvertUTF16toUTF8 spec(aSpec); const char* start = spec.BeginReading(); const char* end = spec.EndReading(); while (start != end) { if (IsSpace(*start)) { if (started) { ++start; break; } // else, we haven't started yet, ignore initial whitespace ++start; } else if ((aFlags & kClockValueAllowSign) && (*start == '+' || *start == '-')) { if (sign != 0) { // sign has already been set isValid = PR_FALSE; break; } if (started) { // sign appears in the middle of the string isValid = PR_FALSE; break; } sign = (*start == '+') ? 1 : -1; ++start; // The NS_IS_DIGIT etc. macros are not locale-specific } else if (NS_IS_DIGIT(*start)) { prevNumCouldBeMin = numCouldBeMin; if (!ParseClockComponent(start, end, component, numIsReal, numCouldBeMin, numCouldBeSec)) { isValid = PR_FALSE; break; } started = PR_TRUE; } else if (*start == ':') { ++colonCount; // Neither minutes nor hours can be reals if (numIsReal) { isValid = PR_FALSE; break; } // Clock value can't start with a ':' if (!started) { isValid = PR_FALSE; break; } // Can't have more than two colons if (colonCount > 2) { isValid = PR_FALSE; break; } // Multiply the offset by 60 and add the last accumulated component offset = offset * 60 + PRInt64(component); component = 0.0; ++start; } else if (NS_IS_ALPHA(*start)) { if (colonCount > 0) { isValid = PR_FALSE; break; } if ((aFlags & kClockValueAllowIndefinite) && ConsumeSubstring(start, end, "indefinite")) { // We set a separate flag because we don't know what the state of the // passed in time value is and we shouldn't change it in the case of a // bad input string (so we can't initialise it to 0ms for example). isIndefinite = PR_TRUE; if (aResult) { aResult->SetIndefinite(); } } else if (aIsMedia && ConsumeSubstring(start, end, "media")) { *aIsMedia = PR_TRUE; } else if (!ParseMetricMultiplicand(start, end, metricMultiplicand)) { isValid = PR_FALSE; break; } // Nothing must come after the string except whitespace break; } else { isValid = PR_FALSE; break; } } if (!started) { isValid = PR_FALSE; } // Process remainder of string (if any) to ensure it is only trailing // whitespace (embedded whitespace is not allowed) SkipBeginWsp(start, end); if (start != end) { isValid = PR_FALSE; } // No more processing required if the value was "indefinite" or "media". if (isIndefinite || (aIsMedia && *aIsMedia)) return NS_OK; // If there is more than one colon then the previous component must be a // correctly formatted minute (i.e. two digits between 00 and 59) and the // latest component must be a correctly formatted second (i.e. two digits // before the .) if (colonCount > 0 && (!prevNumCouldBeMin || !numCouldBeSec)) { isValid = PR_FALSE; } if (isValid) { // Tack on the last component if (colonCount > 0) { offset = offset * 60 * 1000; component *= 1000; // rounding component = (component >= 0) ? component + 0.5 : component - 0.5; offset += PRInt64(component); } else { component *= metricMultiplicand; // rounding component = (component >= 0) ? component + 0.5 : component - 0.5; offset = PRInt64(component); } if (aResult) { nsSMILTime millis = offset; if (sign == -1) { millis = -offset; } aResult->SetMillis(millis); } } return (isValid) ? NS_OK : NS_ERROR_FAILURE; }
bool mozTXTToHTMLConv::FindURLEnd(const char16_t * aInString, int32_t aInStringLength, const uint32_t pos, const modetype check, const uint32_t start, uint32_t& end) { switch(check) { // no breaks, because end of blocks is never reached case RFC1738: case RFC2396E: { nsString temp(aInString, aInStringLength); int32_t i = temp.FindCharInSet(MOZ_UTF16("<>\""), pos + 1); if (i != kNotFound && temp[uint32_t(i--)] == (check == RFC1738 || temp[start - 1] == '<' ? '>' : '"')) { end = uint32_t(i); return end > pos; } return false; } case freetext: case abbreviated: { uint32_t i = pos + 1; bool isEmail = aInString[pos] == (char16_t)'@'; bool seenOpeningParenthesis = false; // there is a '(' earlier in the URL bool seenOpeningSquareBracket = false; // there is a '[' earlier in the URL for (; int32_t(i) < aInStringLength; i++) { // These chars mark the end of the URL if (aInString[i] == '>' || aInString[i] == '<' || aInString[i] == '"' || aInString[i] == '`' || aInString[i] == '}' || aInString[i] == '{' || aInString[i] == '|' || (aInString[i] == ')' && !seenOpeningParenthesis) || (aInString[i] == ']' && !seenOpeningSquareBracket) || // Allow IPv6 adresses like http://[1080::8:800:200C:417A]/foo. (aInString[i] == '[' && i > 2 && (aInString[i - 1] != '/' || aInString[i - 2] != '/')) || IsSpace(aInString[i])) break; // Disallow non-ascii-characters for email. // Currently correct, but revisit later after standards changed. if (isEmail && ( aInString[i] == '(' || aInString[i] == '\'' || !nsCRT::IsAscii(aInString[i]))) break; if (aInString[i] == '(') seenOpeningParenthesis = true; if (aInString[i] == '[') seenOpeningSquareBracket = true; } // These chars are allowed in the middle of the URL, but not at end. // Technically they are, but are used in normal text after the URL. while (--i > pos && ( aInString[i] == '.' || aInString[i] == ',' || aInString[i] == ';' || aInString[i] == '!' || aInString[i] == '?' || aInString[i] == '-' || aInString[i] == ':' || aInString[i] == '\'' )) ; if (i > pos) { end = i; return true; } return false; } default: return false; } //switch }
static char* check_ident_reply(char* reply) { char* token; char* end; char* vector[USERID_TOKEN_COUNT]; int count = token_vector(reply, ':', vector, USERID_TOKEN_COUNT); if (USERID_TOKEN_COUNT != count) return 0; /* * second token is the reply type */ token = vector[IDENT_REPLY_TYPE]; if (EmptyString(token)) return 0; while (IsSpace(*token)) ++token; if (0 != strncmp(token, "USERID", 6)) return 0; /* * third token is the os type */ token = vector[IDENT_OS_TYPE]; if (EmptyString(token)) return 0; while (IsSpace(*token)) ++token; /* * Unless "OTHER" is specified as the operating system * type, the server is expected to return the "normal" * user identification of the owner of this connection. * "Normal" in this context may be taken to mean a string * of characters which uniquely identifies the connection * owner such as a user identifier assigned by the system * administrator and used by such user as a mail * identifier, or as the "user" part of a user/password * pair used to gain access to system resources. When an * operating system is specified (e.g., anything but * "OTHER"), the user identifier is expected to be in a * more or less immediately useful form - e.g., something * that could be used as an argument to "finger" or as a * mail address. */ if (0 == strncmp(token, "OTHER", 5)) return 0; /* * fourth token is the username */ token = vector[IDENT_INFO]; if (EmptyString(token)) return 0; while (IsSpace(*token)) ++token; /* * look for the end of the username, terminators are '\0, @, <SPACE>, :' */ for (end = token; *end; ++end) { if (IsSpace(*end) || '@' == *end || ':' == *end) break; } *end = '\0'; return token; }
int32_t mozTXTToHTMLConv::CiteLevelTXT(const char16_t *line, uint32_t& logLineStart) { int32_t result = 0; int32_t lineLength = NS_strlen(line); bool moreCites = true; while (moreCites) { /* E.g. the following lines count as quote: > text //#ifdef QUOTE_RECOGNITION_AGGRESSIVE >text //#ifdef QUOTE_RECOGNITION_AGGRESSIVE > text ] text USER> text USER] text //#endif logLineStart is the position of "t" in this example */ uint32_t i = logLineStart; #ifdef QUOTE_RECOGNITION_AGGRESSIVE for (; int32_t(i) < lineLength && IsSpace(line[i]); i++) ; for (; int32_t(i) < lineLength && nsCRT::IsAsciiAlpha(line[i]) && nsCRT::IsUpper(line[i]) ; i++) ; if (int32_t(i) < lineLength && (line[i] == '>' || line[i] == ']')) #else if (int32_t(i) < lineLength && line[i] == '>') #endif { i++; if (int32_t(i) < lineLength && line[i] == ' ') i++; // sendmail/mbox // Placed here for performance increase const char16_t * indexString = &line[logLineStart]; // here, |logLineStart < lineLength| is always true uint32_t minlength = MinInt(6, NS_strlen(indexString)); if (Substring(indexString, indexString+minlength).Equals(Substring(NS_LITERAL_STRING(">From "), 0, minlength), nsCaseInsensitiveStringComparator())) //XXX RFC2646 moreCites = false; else { result++; logLineStart = i; } } else moreCites = false; } return result; }
bool mozTXTToHTMLConv::FindURLStart(const char16_t * aInString, int32_t aInLength, const uint32_t pos, const modetype check, uint32_t& start) { switch(check) { // no breaks, because end of blocks is never reached case RFC1738: { if (!nsCRT::strncmp(&aInString[MaxInt(pos - 4, 0)], MOZ_UTF16("<URL:"), 5)) { start = pos + 1; return true; } else return false; } case RFC2396E: { nsString temp(aInString, aInLength); int32_t i = pos <= 0 ? kNotFound : temp.RFindCharInSet(MOZ_UTF16("<>\""), pos - 1); if (i != kNotFound && (temp[uint32_t(i)] == '<' || temp[uint32_t(i)] == '"')) { start = uint32_t(++i); return start < pos; } else return false; } case freetext: { int32_t i = pos - 1; for (; i >= 0 && ( nsCRT::IsAsciiAlpha(aInString[uint32_t(i)]) || nsCRT::IsAsciiDigit(aInString[uint32_t(i)]) || aInString[uint32_t(i)] == '+' || aInString[uint32_t(i)] == '-' || aInString[uint32_t(i)] == '.' ); i--) ; if (++i >= 0 && uint32_t(i) < pos && nsCRT::IsAsciiAlpha(aInString[uint32_t(i)])) { start = uint32_t(i); return true; } else return false; } case abbreviated: { int32_t i = pos - 1; // This disallows non-ascii-characters for email. // Currently correct, but revisit later after standards changed. bool isEmail = aInString[pos] == (char16_t)'@'; // These chars mark the start of the URL for (; i >= 0 && aInString[uint32_t(i)] != '>' && aInString[uint32_t(i)] != '<' && aInString[uint32_t(i)] != '"' && aInString[uint32_t(i)] != '\'' && aInString[uint32_t(i)] != '`' && aInString[uint32_t(i)] != ',' && aInString[uint32_t(i)] != '{' && aInString[uint32_t(i)] != '[' && aInString[uint32_t(i)] != '(' && aInString[uint32_t(i)] != '|' && aInString[uint32_t(i)] != '\\' && !IsSpace(aInString[uint32_t(i)]) && (!isEmail || nsCRT::IsAscii(aInString[uint32_t(i)])) ; i--) ; if ( ++i >= 0 && uint32_t(i) < pos && ( nsCRT::IsAsciiAlpha(aInString[uint32_t(i)]) || nsCRT::IsAsciiDigit(aInString[uint32_t(i)]) ) ) { start = uint32_t(i); return true; } else return false; } default: return false; } //switch }
bool DoubleFromString(const char *s, double *value_out) { static const double NO_DOUBLE = -123.45; double a = NO_DOUBLE; char remainder[CF_BUFSIZE]; char c = 'X'; if (s == NULL) { return false; } remainder[0] = '\0'; sscanf(s, "%lf%c%s", &a, &c, remainder); if ((a == NO_DOUBLE) || (!IsSpace(remainder))) { Log(LOG_LEVEL_ERR, "Reading assumed real value '%s', anomalous remainder '%s'", s, remainder); return false; } else { switch (c) { case 'k': a = 1000 * a; break; case 'K': a = 1024 * a; break; case 'm': a = 1000 * 1000 * a; break; case 'M': a = 1024 * 1024 * a; break; case 'g': a = 1000 * 1000 * 1000 * a; break; case 'G': a = 1024 * 1024 * 1024 * a; break; case '%': if ((a < 0) || (a > 100)) { Log(LOG_LEVEL_ERR, "Percentage out of range (%.2lf)", a); return false; } else { /* Represent percentages internally as negative numbers */ a = -a; } break; case ' ': break; default: break; } } *value_out = a; return true; }
long IntFromString(const char *s) { long a = CF_NOINT; char c = 'X'; char remainder[CF_BUFSIZE]; if (s == NULL) { return CF_NOINT; } if (strcmp(s, "inf") == 0) { return (long) CF_INFINITY; } if (strcmp(s, "now") == 0) { return (long) CFSTARTTIME; } remainder[0] = '\0'; sscanf(s, "%ld%c%s", &a, &c, remainder); // Test whether remainder is space only if ((a == CF_NOINT) || (!IsSpace(remainder))) { if (THIS_AGENT_TYPE == AGENT_TYPE_COMMON) { Log(LOG_LEVEL_INFO, "Error reading assumed integer value '%s' => 'non-value', found remainder '%s'", s, remainder); if (strchr(s, '$')) { Log(LOG_LEVEL_INFO, "The variable might not yet be expandable - not necessarily an error"); } } } else { switch (c) { case 'k': a = 1000 * a; break; case 'K': a = 1024 * a; break; case 'm': a = 1000 * 1000 * a; break; case 'M': a = 1024 * 1024 * a; break; case 'g': a = 1000 * 1000 * 1000 * a; break; case 'G': a = 1024 * 1024 * 1024 * a; break; case '%': if ((a < 0) || (a > 100)) { Log(LOG_LEVEL_ERR, "Percentage out of range (%ld)", a); return CF_NOINT; } else { /* Represent percentages internally as negative numbers */ a = -a; } break; case ' ': break; default: break; } } return a; }
/*! The function writes the string \c str to the output object that was specified in the wxJSONWriter::Write() function. The function may split strings in two or more lines if the string contains LF characters if the \c m_style data member contains the wxJSONWRITER_SPLIT_STRING flag. The function does not actually write the string: for every character in the provided string the function calls WriteChar() which does the actual character output. The function returns ZERO on success or -1 in case of errors. */ int wxJSONWriter::WriteStringValue( wxOutputStream& os, const wxString& str ) { // JSON values of type STRING are written by converting the whole string // to UTF-8 and then copying the UTF-8 buffer to the 'os' stream // one byte at a time and processing them os.PutC( '\"' ); // open quotes // the buffer that has to be written is either UTF-8 or ANSI c_str() depending // on the 'm_noUtf8' flag char* writeBuff = 0; wxCharBuffer utf8CB = str.ToUTF8(); // the UTF-8 buffer #if !defined( wxJSON_USE_UNICODE ) wxCharBuffer ansiCB( str.c_str()); // the ANSI buffer if ( m_noUtf8 ) { writeBuff = ansiCB.data(); } else { writeBuff = utf8CB.data(); } #else writeBuff = utf8CB.data(); #endif // NOTE: in ANSI builds UTF-8 conversion may fail (see samples/test5.cpp, // test 7.3) although I do not know why if ( writeBuff == 0 ) { const char* err = "<wxJSONWriter::WriteStringValue(): error converting the string to a UTF8 buffer>"; os.Write( err, strlen( err )); return 0; } size_t len = strlen( writeBuff ); int lastChar = 0; // store the column at which the string starts // splitting strings only happen if the string starts within // column wxJSONWRITER_LAST_COL (default 50) // see 'include/wx/json_defs.h' for the defines int tempCol = m_colNo; // now write the UTF8 buffer processing the bytes size_t i; for ( i = 0; i < len; i++ ) { bool shouldEscape = false; unsigned char ch = *writeBuff; ++writeBuff; // point to the next byte // the escaped character char escCh = 0; // for every character we have to check if it is a character that // needs to be escaped: note that characters that should be escaped // may be not if some writer's flags are specified switch ( ch ) { case '\"' : // quotes shouldEscape = true; escCh = '\"'; break; case '\\' : // reverse solidus shouldEscape = true; escCh = '\\'; break; case '/' : // solidus shouldEscape = true; escCh = '/'; break; case '\b' : // backspace shouldEscape = true; escCh = 'b'; break; case '\f' : // formfeed shouldEscape = true; escCh = 'f'; break; case '\n' : // newline shouldEscape = true; escCh = 'n'; break; case '\r' : // carriage-return shouldEscape = true; escCh = 'r'; break; case '\t' : // horizontal tab shouldEscape = true; escCh = 't'; break; default : shouldEscape = false; break; } // end switch // if the character is a control character that is not identified by a // lowercase letter, we should escape it if ( !shouldEscape && ch < 32 ) { char b[8]; snprintf( b, 8, "\\u%04X", (int) ch ); os.Write( b, 6 ); if ( os.GetLastError() != wxSTREAM_NO_ERROR ) { return -1; } } // the char is not a control character else { // some characters that should be escaped are not escaped // if the writer was constructed with some flags if ( shouldEscape && !( m_style & wxJSONWRITER_ESCAPE_SOLIDUS) ) { if ( ch == '/' ) { shouldEscape = false; } } if ( shouldEscape && (m_style & wxJSONWRITER_MULTILINE_STRING)) { if ( ch == '\n' || ch == '\t' ) { shouldEscape = false; } } // now write the character prepended by ESC if it should be escaped if ( shouldEscape ) { os.PutC( '\\' ); os.PutC( escCh ); if ( os.GetLastError() != wxSTREAM_NO_ERROR ) { return -1; } } else { // a normal char or a UTF-8 units: write the character os.PutC( ch ); if ( os.GetLastError() != wxSTREAM_NO_ERROR ) { return -1; } } } // check if SPLIT_STRING flag is set and if the string has to // be splitted if ( (m_style & wxJSONWRITER_STYLED) && (m_style & wxJSONWRITER_SPLIT_STRING)) { // split the string if the character written is LF if ( ch == '\n' ) { // close quotes and CR os.Write( "\"\n", 2 ); lastChar = WriteIndent( os, m_level + 2 ); // write indentation os.PutC( '\"' ); // reopen quotes if ( lastChar < 0 ) { return lastChar; } } // split the string only if there is at least wxJSONWRITER_MIN_LENGTH // character to write and the character written is a punctuation or space // BUG: the following does not work because the columns are not counted else if ( (m_colNo >= wxJSONWRITER_SPLIT_COL) && (tempCol <= wxJSONWRITER_LAST_COL )) { if ( IsSpace( ch ) || IsPunctuation( ch )) { if ( len - i > wxJSONWRITER_MIN_LENGTH ) { // close quotes and CR os.Write( "\"\n", 2 ); lastChar = WriteIndent( os, m_level + 2 ); // write indentation os.PutC( '\"' ); // reopen quotes if ( lastChar < 0 ) { return lastChar; } } } } } } // end for os.PutC( '\"' ); // close quotes return 0; }
// // Find: // Take nodes out of the tree with NextNode, // until null (NextNode will return 0 at the end of our range). // NS_IMETHODIMP nsFind::Find(const PRUnichar *aPatText, nsIDOMRange* aSearchRange, nsIDOMRange* aStartPoint, nsIDOMRange* aEndPoint, nsIDOMRange** aRangeRet) { #ifdef DEBUG_FIND printf("============== nsFind::Find('%s'%s, %p, %p, %p)\n", NS_LossyConvertUTF16toASCII(aPatText).get(), mFindBackward ? " (backward)" : " (forward)", (void*)aSearchRange, (void*)aStartPoint, (void*)aEndPoint); #endif NS_ENSURE_ARG(aSearchRange); NS_ENSURE_ARG(aStartPoint); NS_ENSURE_ARG(aEndPoint); NS_ENSURE_ARG_POINTER(aRangeRet); *aRangeRet = 0; if (!aPatText) return NS_ERROR_NULL_POINTER; ResetAll(); nsAutoString patAutoStr(aPatText); if (!mCaseSensitive) ToLowerCase(patAutoStr); // Ignore soft hyphens in the pattern static const char kShy[] = { CH_SHY, 0 }; patAutoStr.StripChars(kShy); const PRUnichar* patStr = patAutoStr.get(); PRInt32 patLen = patAutoStr.Length() - 1; // current offset into the pattern -- reset to beginning/end: PRInt32 pindex = (mFindBackward ? patLen : 0); // Current offset into the fragment PRInt32 findex = 0; // Direction to move pindex and ptr* int incr = (mFindBackward ? -1 : 1); nsCOMPtr<nsIContent> tc; const nsTextFragment *frag = nsnull; PRInt32 fragLen = 0; // Pointers into the current fragment: const PRUnichar *t2b = nsnull; const char *t1b = nsnull; // Keep track of when we're in whitespace: // (only matters when we're matching) PRBool inWhitespace = PR_FALSE; // Have we extended a search past the endpoint? PRBool continuing = PR_FALSE; // Place to save the range start point in case we find a match: nsCOMPtr<nsIDOMNode> matchAnchorNode; PRInt32 matchAnchorOffset = 0; // Get the end point, so we know when to end searches: nsCOMPtr<nsIDOMNode> endNode; PRInt32 endOffset; aEndPoint->GetEndContainer(getter_AddRefs(endNode)); aEndPoint->GetEndOffset(&endOffset); PRUnichar prevChar = 0; while (1) { #ifdef DEBUG_FIND printf("Loop ...\n"); #endif // If this is our first time on a new node, reset the pointers: if (!frag) { tc = nsnull; NextNode(aSearchRange, aStartPoint, aEndPoint, PR_FALSE); if (!mIterNode) // Out of nodes { // Are we in the middle of a match? // If so, try again with continuation. if (matchAnchorNode && !continuing) NextNode(aSearchRange, aStartPoint, aEndPoint, PR_TRUE); // Reset the iterator, so this nsFind will be usable if // the user wants to search again (from beginning/end). ResetAll(); return NS_OK; } // We have a new text content. If its block parent is different // from the block parent of the last text content, then we // need to clear the match since we don't want to find // across block boundaries. nsCOMPtr<nsIDOMNode> blockParent; GetBlockParent(mIterNode, getter_AddRefs(blockParent)); #ifdef DEBUG_FIND printf("New node: old blockparent = %p, new = %p\n", (void*)mLastBlockParent.get(), (void*)blockParent.get()); #endif if (blockParent != mLastBlockParent) { #ifdef DEBUG_FIND printf("Different block parent!\n"); #endif mLastBlockParent = blockParent; // End any pending match: matchAnchorNode = nsnull; matchAnchorOffset = 0; pindex = (mFindBackward ? patLen : 0); inWhitespace = PR_FALSE; } // Get the text content: tc = do_QueryInterface(mIterNode); if (!tc || !(frag = tc->GetText())) // Out of nodes { mIterator = nsnull; mLastBlockParent = 0; ResetAll(); return NS_OK; } fragLen = frag->GetLength(); // Set our starting point in this node. // If we're going back to the anchor node, which means that we // just ended a partial match, use the saved offset: if (mIterNode == matchAnchorNode) findex = matchAnchorOffset + (mFindBackward ? 1 : 0); // mIterOffset, if set, is the range's idea of an offset, // and points between characters. But when translated // to a string index, it points to a character. If we're // going backward, this is one character too late and // we'll match part of our previous pattern. else if (mIterOffset >= 0) findex = mIterOffset - (mFindBackward ? 1 : 0); // Otherwise, just start at the appropriate end of the fragment: else if (mFindBackward) findex = fragLen - 1; else findex = 0; // Offset can only apply to the first node: mIterOffset = -1; // If this is outside the bounds of the string, then skip this node: if (findex < 0 || findex > fragLen-1) { #ifdef DEBUG_FIND printf("At the end of a text node -- skipping to the next\n"); #endif frag = 0; continue; } #ifdef DEBUG_FIND printf("Starting from offset %d\n", findex); #endif if (frag->Is2b()) { t2b = frag->Get2b(); t1b = nsnull; #ifdef DEBUG_FIND nsAutoString str2(t2b, fragLen); printf("2 byte, '%s'\n", NS_LossyConvertUTF16toASCII(str2).get()); #endif } else { t1b = frag->Get1b(); t2b = nsnull; #ifdef DEBUG_FIND nsCAutoString str1(t1b, fragLen); printf("1 byte, '%s'\n", str1.get()); #endif } } else // still on the old node { // Still on the old node. Advance the pointers, // then see if we need to pull a new node. findex += incr; #ifdef DEBUG_FIND printf("Same node -- (%d, %d)\n", pindex, findex); #endif if (mFindBackward ? (findex < 0) : (findex >= fragLen)) { #ifdef DEBUG_FIND printf("Will need to pull a new node: mAO = %d, frag len=%d\n", matchAnchorOffset, fragLen); #endif // Done with this node. Pull a new one. frag = nsnull; continue; } } // Have we gone past the endpoint yet? // If we have, and we're not in the middle of a match, return. if (mIterNode == endNode && !continuing && ((mFindBackward && (findex < endOffset)) || (!mFindBackward && (findex > endOffset)))) { ResetAll(); return NS_OK; } // The two characters we'll be comparing: PRUnichar c = (t2b ? t2b[findex] : CHAR_TO_UNICHAR(t1b[findex])); PRUnichar patc = patStr[pindex]; #ifdef DEBUG_FIND printf("Comparing '%c'=%x to '%c' (%d of %d), findex=%d%s\n", (char)c, (int)c, patc, pindex, patLen, findex, inWhitespace ? " (inWhitespace)" : ""); #endif // Do we need to go back to non-whitespace mode? // If inWhitespace, then this space in the pat str // has already matched at least one space in the document. if (inWhitespace && !IsSpace(c)) { inWhitespace = PR_FALSE; pindex += incr; #ifdef DEBUG // This shouldn't happen -- if we were still matching, and we // were at the end of the pat string, then we should have // caught it in the last iteration and returned success. if (OVERFLOW_PINDEX) NS_ASSERTION(PR_FALSE, "Missed a whitespace match\n"); #endif patc = patStr[pindex]; } if (!inWhitespace && IsSpace(patc)) inWhitespace = PR_TRUE; // convert to lower case if necessary else if (!inWhitespace && !mCaseSensitive && IsUpperCase(c)) c = ToLowerCase(c); // ignore soft hyphens in the document if (c == CH_SHY) continue; // a '\n' between CJ characters is ignored if (pindex != (mFindBackward ? patLen : 0) && c != patc && !inWhitespace) { if (c == '\n' && t2b && IS_CJ_CHAR(prevChar)) { PRInt32 nindex = findex + incr; if (mFindBackward ? (nindex >= 0) : (nindex < fragLen)) { if (IS_CJ_CHAR(t2b[nindex])) continue; } } } // Compare if ((c == patc) || (inWhitespace && IsSpace(c))) { prevChar = c; #ifdef DEBUG_FIND if (inWhitespace) printf("YES (whitespace)(%d of %d)\n", pindex, patLen); else printf("YES! '%c' == '%c' (%d of %d)\n", c, patc, pindex, patLen); #endif // Save the range anchors if we haven't already: if (!matchAnchorNode) { matchAnchorNode = mIterNode; matchAnchorOffset = findex; } // Are we done? if (DONE_WITH_PINDEX) // Matched the whole string! { #ifdef DEBUG_FIND printf("Found a match!\n"); #endif // Make the range: nsCOMPtr<nsIDOMNode> startParent; nsCOMPtr<nsIDOMNode> endParent; nsCOMPtr<nsIDOMRange> range = CreateRange(); if (range) { PRInt32 matchStartOffset, matchEndOffset; // convert char index to range point: PRInt32 mao = matchAnchorOffset + (mFindBackward ? 1 : 0); if (mFindBackward) { startParent = do_QueryInterface(tc); endParent = matchAnchorNode; matchStartOffset = findex; matchEndOffset = mao; } else { startParent = matchAnchorNode; endParent = do_QueryInterface(tc); matchStartOffset = mao; matchEndOffset = findex+1; } if (startParent && endParent && IsVisibleNode(startParent) && IsVisibleNode(endParent)) { range->SetStart(startParent, matchStartOffset); range->SetEnd(endParent, matchEndOffset); *aRangeRet = range.get(); NS_ADDREF(*aRangeRet); } else { startParent = nsnull; // This match is no good -- invisible or bad range } } if (startParent) { // If startParent == nsnull, we didn't successfully make range // or, we didn't make a range because the start or end node were invisible // Reset the offset to the other end of the found string: mIterOffset = findex + (mFindBackward ? 1 : 0); #ifdef DEBUG_FIND printf("mIterOffset = %d, mIterNode = ", mIterOffset); DumpNode(mIterNode); #endif ResetAll(); return NS_OK; } matchAnchorNode = nsnull; // This match is no good, continue on in document } if (matchAnchorNode) { // Not done, but still matching. // Advance and loop around for the next characters. // But don't advance from a space to a non-space: if (!inWhitespace || DONE_WITH_PINDEX || IsSpace(patStr[pindex+incr])) { pindex += incr; inWhitespace = PR_FALSE; #ifdef DEBUG_FIND printf("Advancing pindex to %d\n", pindex); #endif } continue; } } #ifdef DEBUG_FIND printf("NOT: %c == %c\n", c, patc); #endif // If we were continuing, then this ends our search. if (continuing) { ResetAll(); return NS_OK; } // If we didn't match, go back to the beginning of patStr, // and set findex back to the next char after // we started the current match. if (matchAnchorNode) // we're ending a partial match { findex = matchAnchorOffset; mIterOffset = matchAnchorOffset; // +incr will be added to findex when we continue // Are we going back to a previous node? if (matchAnchorNode != mIterNode) { nsCOMPtr<nsIContent> content (do_QueryInterface(matchAnchorNode)); nsresult rv = NS_ERROR_UNEXPECTED; if (content) rv = mIterator->PositionAt(content); frag = 0; NS_ASSERTION(NS_SUCCEEDED(rv), "Text content wasn't nsIContent!"); #ifdef DEBUG_FIND printf("Repositioned anchor node\n"); #endif } #ifdef DEBUG_FIND printf("Ending a partial match; findex -> %d, mIterOffset -> %d\n", findex, mIterOffset); #endif } matchAnchorNode = nsnull; matchAnchorOffset = 0; inWhitespace = PR_FALSE; pindex = (mFindBackward ? patLen : 0); #ifdef DEBUG_FIND printf("Setting findex back to %d, pindex to %d\n", findex, pindex); #endif } // end while loop // Out of nodes, and didn't match. ResetAll(); return NS_OK; }
/* * parsetinterval -- parse a tinterval string * * output parameters: * i_start, i_end: tinterval margins * * Time interval: * `[' {` '} `'' <AbsTime> `'' {` '} `'' <AbsTime> `'' {` '} `]' * * OR `Undefined Range' (see also INVALID_INTERVAL_STR) * * where <AbsTime> satisfies the syntax of absolute time. * * e.g. [ ' Jan 18 1902' 'Jan 1 00:00:00 1970'] */ static void parsetinterval(char *i_string, AbsoluteTime *i_start, AbsoluteTime *i_end) { char *p, *p1; char c; p = i_string; /* skip leading blanks up to '[' */ while ((c = *p) != '\0') { if (IsSpace(c)) p++; else if (c != '[') goto bogus; /* syntax error */ else break; } if (c == '\0') goto bogus; /* syntax error */ p++; /* skip leading blanks up to '"' */ while ((c = *p) != '\0') { if (IsSpace(c)) p++; else if (c != '"') goto bogus; /* syntax error */ else break; } if (c == '\0') goto bogus; /* syntax error */ p++; if (strncmp(INVALID_INTERVAL_STR, p, strlen(INVALID_INTERVAL_STR)) == 0) goto bogus; /* undefined range, handled like a syntax err. */ /* search for the end of the first date and change it to a \0 */ p1 = p; while ((c = *p1) != '\0') { if (c == '"') break; p1++; } if (c == '\0') goto bogus; /* syntax error */ *p1 = '\0'; /* get the first date */ *i_start = DatumGetAbsoluteTime(DirectFunctionCall1(abstimein, CStringGetDatum(p))); /* undo change to \0 */ *p1 = c; p = ++p1; /* skip blanks up to '"', beginning of second date */ while ((c = *p) != '\0') { if (IsSpace(c)) p++; else if (c != '"') goto bogus; /* syntax error */ else break; } if (c == '\0') goto bogus; /* syntax error */ p++; /* search for the end of the second date and change it to a \0 */ p1 = p; while ((c = *p1) != '\0') { if (c == '"') break; p1++; } if (c == '\0') goto bogus; /* syntax error */ *p1 = '\0'; /* get the second date */ *i_end = DatumGetAbsoluteTime(DirectFunctionCall1(abstimein, CStringGetDatum(p))); /* undo change to \0 */ *p1 = c; p = ++p1; /* skip blanks up to ']' */ while ((c = *p) != '\0') { if (IsSpace(c)) p++; else if (c != ']') goto bogus; /* syntax error */ else break; } if (c == '\0') goto bogus; /* syntax error */ p++; c = *p; if (c != '\0') goto bogus; /* syntax error */ /* it seems to be a valid tinterval */ return; bogus: ereport(ERROR, (errcode(ERRCODE_INVALID_DATETIME_FORMAT), errmsg("invalid input syntax for type tinterval: \"%s\"", i_string), errOmitLocation(true))); *i_start = *i_end = INVALID_ABSTIME; /* keep compiler quiet */ }
bool CDialogDef::r_Verb( CScript & s, CTextConsole * pSrc ) // some command on this object as a target { ADDTOCALLSTACK("CDialogDef::r_Verb"); EXC_TRY("Verb"); // The first part of the key is GUMPCTL_TYPE LPCTSTR pszKey = s.GetKey(); int index = FindTableSorted( pszKey, sm_szLoadKeys, COUNTOF(sm_szLoadKeys)-1 ); if ( index < 0 ) { CGString sVal; CScriptTriggerArgs Args(s.GetArgRaw()); if ( r_Call(s.GetKey(), pSrc, &Args, &sVal) ) return true; if (!m_pObj) return CResourceLink::r_Verb(s, pSrc); return m_pObj->r_Verb(s, pSrc); } LPCTSTR pszArgs = s.GetArgStr(); switch( index ) { case GUMPCTL_PAGE: { if ( m_iControls >= (COUNTOF(m_sControls) - 1) ) return false; GET_ABSOLUTE( page ); if ( page <= 0 ) return true; int iNewPage; if ( m_iPage == 0 || page > m_iPage || page == 0 ) iNewPage = page; else if ( page == m_iPage ) iNewPage = 1; else iNewPage = page + 1; m_sControls[m_iControls].Format( "page %d", iNewPage ); m_iControls++; return true; } case GUMPCTL_BUTTON: // 7 = X,Y,Down gump,Up gump,pressable(1/0),page,id case GUMPCTL_BUTTONTILEART: // 11 = X,Y,Down gump,Up gump,pressable(1/0),page,id,tileart,hue,X,Y { if ( m_iControls >= (COUNTOF(m_sControls) - 1) ) return false; GET_RELATIVE( x, m_iOriginX ); GET_RELATIVE( y, m_iOriginY ); GET_ABSOLUTE( down ); GET_ABSOLUTE( up ); GET_ABSOLUTE( press ); GET_ABSOLUTE( page ); GET_ABSOLUTE( id ); int iNewPage; if ( m_iPage == 0 || page > m_iPage || page == 0 ) iNewPage = page; else if ( page == m_iPage ) iNewPage = 1; else iNewPage = page + 1; if (index == GUMPCTL_BUTTON) m_sControls[m_iControls].Format( "button %d %d %d %d %d %d %d", x, y, down, up, press, iNewPage, id ); else { GET_ABSOLUTE( tileId ); GET_ABSOLUTE( tileHue ); GET_ABSOLUTE( tileX ); GET_ABSOLUTE( tileY ); m_sControls[m_iControls].Format( "buttontileart %d %d %d %d %d %d %d %d %d %d %d", x, y, down, up, press, iNewPage, id, tileId, tileHue, tileX, tileY ); } m_iControls++; return true; } case GUMPCTL_GUMPPIC: { GET_RELATIVE( x, m_iOriginX ); GET_RELATIVE( y, m_iOriginY ); GET_ABSOLUTE( id ); SKIP_ALL( pszArgs ); m_sControls[m_iControls].Format( "gumppic %d %d %d%s%s", x, y, id, *pszArgs ? " hue=" : "", *pszArgs ? pszArgs : "" ); m_iControls++; return true; } case GUMPCTL_GUMPPICTILED: { GET_RELATIVE( x, m_iOriginX ); GET_RELATIVE( y, m_iOriginY ); GET_ABSOLUTE( sX ); GET_ABSOLUTE( sY ); GET_ABSOLUTE( id ); m_sControls[m_iControls].Format( "gumppictiled %d %d %d %d %d", x, y, sX, sY, id ); m_iControls++; return true; } case GUMPCTL_RESIZEPIC: { GET_RELATIVE( x, m_iOriginX ); GET_RELATIVE( y, m_iOriginY ); GET_ABSOLUTE( id ); GET_ABSOLUTE( sX ); GET_ABSOLUTE( sY ); m_sControls[m_iControls].Format( "resizepic %d %d %d %d %d", x, y, id, sX, sY ); m_iControls++; return true; } case GUMPCTL_TILEPIC: case GUMPCTL_TILEPICHUE: { GET_RELATIVE( x, m_iOriginX ); GET_RELATIVE( y, m_iOriginY ); GET_ABSOLUTE( id ); SKIP_ALL( pszArgs ); // TilePic don't use args, TilePicHue yes :) if ( index == GUMPCTL_TILEPIC ) m_sControls[m_iControls].Format( "tilepic %d %d %d", x, y, id ); else m_sControls[m_iControls].Format( "tilepichue %d %d %d%s%s", x, y, id, *pszArgs ? " " : "", *pszArgs ? pszArgs : "" ); m_iControls++; return true; } case GUMPCTL_DTEXT: { if ( m_iControls >= (COUNTOF(m_sControls) - 1) ) return false; if ( m_iTexts >= (COUNTOF(m_sText) - 1) ) return false; GET_RELATIVE( x, m_iOriginX ); GET_RELATIVE( y, m_iOriginY ); GET_ABSOLUTE( hue ); SKIP_ALL( pszArgs ) if ( *pszArgs == '.' ) pszArgs++; size_t iText = GumpAddText( *pszArgs ? pszArgs : "" ); m_sControls[m_iControls].Format( "text %d %d %d %" FMTSIZE_T, x, y, hue, iText ); m_iControls++; return true; } case GUMPCTL_DCROPPEDTEXT: { if ( m_iControls >= (COUNTOF(m_sControls) - 1) ) return false; if ( m_iTexts >= (COUNTOF(m_sText) - 1) ) return false; GET_RELATIVE( x, m_iOriginX ); GET_RELATIVE( y, m_iOriginY ); GET_ABSOLUTE( w ); GET_ABSOLUTE( h ); GET_ABSOLUTE( hue ); SKIP_ALL( pszArgs ) if ( *pszArgs == '.' ) pszArgs++; size_t iText = GumpAddText( *pszArgs ? pszArgs : "" ); m_sControls[m_iControls].Format( "croppedtext %d %d %d %d %d %" FMTSIZE_T, x, y, w, h, hue, iText ); m_iControls++; return true; } case GUMPCTL_DHTMLGUMP: { if ( m_iControls >= (COUNTOF(m_sControls) - 1) ) return false; if ( m_iTexts >= (COUNTOF(m_sText) - 1) ) return false; GET_RELATIVE( x, m_iOriginX ); GET_RELATIVE( y, m_iOriginY ); GET_ABSOLUTE( w ); GET_ABSOLUTE( h ); GET_ABSOLUTE( bck ); GET_ABSOLUTE( options ); SKIP_ALL( pszArgs ) size_t iText = GumpAddText( *pszArgs ? pszArgs : "" ); m_sControls[m_iControls].Format( "htmlgump %d %d %d %d %" FMTSIZE_T " %d %d", x, y, w, h, iText, bck, options ); m_iControls++; return true; } case GUMPCTL_DTEXTENTRY: { if ( m_iControls >= (COUNTOF(m_sControls) - 1) ) return false; if ( m_iTexts >= (COUNTOF(m_sText) - 1) ) return false; GET_RELATIVE( x, m_iOriginX ); GET_RELATIVE( y, m_iOriginY ); GET_ABSOLUTE( w ); GET_ABSOLUTE( h ); GET_ABSOLUTE( hue ); GET_ABSOLUTE( id ); SKIP_ALL( pszArgs ) size_t iText = GumpAddText( *pszArgs ? pszArgs : "" ); m_sControls[m_iControls].Format( "textentry %d %d %d %d %d %d %" FMTSIZE_T, x, y, w, h, hue, id, iText ); m_iControls++; return true; } case GUMPCTL_DTEXTENTRYLIMITED: { if ( m_iControls >= (COUNTOF(m_sControls) - 1) ) return false; if ( m_iTexts >= (COUNTOF(m_sText) - 1) ) return false; GET_RELATIVE( x, m_iOriginX ); GET_RELATIVE( y, m_iOriginY ); GET_ABSOLUTE( w ); GET_ABSOLUTE( h ); GET_ABSOLUTE( hue ); GET_ABSOLUTE( id ); GET_ABSOLUTE( charLimit ); SKIP_ALL( pszArgs ) size_t iText = GumpAddText( *pszArgs ? pszArgs : "" ); m_sControls[m_iControls].Format( "textentrylimited %d %d %d %d %d %d %" FMTSIZE_T " %d", x, y, w, h, hue, id, iText, charLimit ); m_iControls++; return true; } case GUMPCTL_CHECKBOX: { if ( m_iControls >= (COUNTOF(m_sControls) - 1) ) return false; GET_RELATIVE( x, m_iOriginX ); GET_RELATIVE( y, m_iOriginY ); GET_ABSOLUTE( down ); GET_ABSOLUTE( up ); GET_ABSOLUTE( state ); GET_ABSOLUTE( id ); m_sControls[m_iControls].Format( "checkbox %d %d %d %d %d %d", x, y, down, up, state, id ); m_iControls++; return true; } case GUMPCTL_RADIO: { if ( m_iControls >= (COUNTOF(m_sControls) - 1) ) return false; GET_RELATIVE( x, m_iOriginX ); GET_RELATIVE( y, m_iOriginY ); GET_ABSOLUTE( down ); GET_ABSOLUTE( up ); GET_ABSOLUTE( state ); GET_ABSOLUTE( id ); m_sControls[m_iControls].Format( "radio %d %d %d %d %d %d", x, y, down, up, state, id ); m_iControls++; return true; } case GUMPCTL_CHECKERTRANS: { if ( m_iControls >= (COUNTOF(m_sControls) - 1) ) return false; GET_RELATIVE( x, m_iOriginX ); GET_RELATIVE( y, m_iOriginY ); GET_ABSOLUTE( width ); GET_ABSOLUTE( height ); m_sControls[m_iControls].Format( "checkertrans %d %d %d %d", x, y, width, height ); m_iControls++; return true; } case GUMPCTL_DORIGIN: { // GET_RELATIVE( x, m_iOriginX ); // GET_RELATIVE( y, m_iOriginY ); // m_iOriginX = x; // m_iOriginY = y; SKIP_ALL( pszArgs ); if ( *pszArgs == '-' && (IsSpace( pszArgs[1] ) || !pszArgs[1]) ) pszArgs++; else if ( *pszArgs == '*' ) m_iOriginX += Exp_GetSingle( ++pszArgs ); else m_iOriginX = Exp_GetSingle( pszArgs ); SKIP_ALL( pszArgs ); if ( *pszArgs == '-' && (IsSpace( pszArgs[1] ) || !pszArgs[1]) ) pszArgs++; else if ( *pszArgs == '*' ) m_iOriginY += Exp_GetSingle( ++pszArgs ); else m_iOriginY = Exp_GetSingle( pszArgs ); return true; } case GUMPCTL_NODISPOSE: m_bNoDispose = true; break; case GUMPCTL_CROPPEDTEXT: case GUMPCTL_TEXT: case GUMPCTL_TEXTENTRY: case GUMPCTL_TEXTENTRYLIMITED: break; case GUMPCTL_XMFHTMLGUMP: // 7 = x,y,sx,sy, cliloc(1003000) hasBack canScroll case GUMPCTL_XMFHTMLGUMPCOLOR: // 7 + color. { GET_RELATIVE( x, m_iOriginX ); GET_RELATIVE( y, m_iOriginY ); GET_ABSOLUTE( sX ); GET_ABSOLUTE( sY ); GET_ABSOLUTE( cliloc ); GET_ABSOLUTE( hasBack ); GET_ABSOLUTE( canScroll ); //SKIP_ALL( pszArgs ) if ( index == GUMPCTL_XMFHTMLGUMP ) // xmfhtmlgump doesn't use color m_sControls[m_iControls].Format( "xmfhtmlgump %d %d %d %d %d %d %d" , x, y, sX, sY, cliloc, hasBack, canScroll ); else m_sControls[m_iControls].Format( "xmfhtmlgumpcolor %d %d %d %d %d %d %d%s%s", x, y, sX, sY, cliloc, hasBack, canScroll, *pszArgs ? " " : "", *pszArgs ? pszArgs : "" ); m_iControls++; return true; } case GUMPCTL_XMFHTMLTOK: // 9 = x y width height has_background has_scrollbar color cliloc_id @args { GET_RELATIVE(x, m_iOriginX); GET_RELATIVE(y, m_iOriginY); GET_ABSOLUTE(sX); GET_ABSOLUTE(sY); GET_ABSOLUTE(hasBack); GET_ABSOLUTE(canScroll); GET_ABSOLUTE(color); GET_ABSOLUTE(cliloc); SKIP_ALL(pszArgs); m_sControls[m_iControls].Format("xmfhtmltok %d %d %d %d %d %d %d %d %s", x, y, sX, sY, hasBack, canScroll, color, cliloc, *pszArgs ? pszArgs : ""); m_iControls++; return true; } default: break; } if ( m_iControls >= (COUNTOF(m_sControls) - 1) ) return false; m_sControls[m_iControls].Format("%s %s", pszKey, pszArgs); m_iControls++; return true; EXC_CATCH; EXC_DEBUG_START; EXC_ADD_SCRIPTSRC; EXC_DEBUG_END; return false; }
static bool IsTagStandalone(const char *start, const char *tag_start, const char *tag_end, const char **line_begin, const char **line_end) { assert(start <= tag_start); *line_begin = start; for (const char *cur = tag_start - 1; cur >= start; cur--) { if (IsSpace(*cur)) { *line_begin = cur; if (cur == start) { break; } continue; } else if (*cur == '\n') { *line_begin = cur + 1; break; } else { return false; } } *line_end = NULL; for (const char *cur = tag_end; true; cur++) { if (IsSpace(*cur)) { continue; } else if (*cur == '\n') { *line_end = cur + 1; break; } else if (*cur == '\r') { if (*(cur + 1) == '\n') { *line_end = cur + 2; break; } continue; } else if (*cur == '\0') { *line_end = cur; break; } else { return false; } } assert(*line_end); return true; }
bool SearchString(const string& Source, const string& Str, string& ReplaceStr,int& CurPos, int Position,int Case,int WholeWords,int Reverse,int Regexp, int *SearchLength,const wchar_t* WordDiv) { int StrSize=StrLength(Source); *SearchLength = 0; if (!WordDiv) WordDiv=Global->Opt->strWordDiv; if (Reverse) { Position--; if (Position>=StrSize) Position=StrSize-1; if (Position<0) return false; } if ((Position<StrSize || (!Position && !StrSize)) && !Str.IsEmpty()) { if (Regexp) { string strSlash(Str); InsertRegexpQuote(strSlash); RegExp re; // Q: что важнее: опция диалога или опция RegExp`а? if (!re.Compile(strSlash, OP_PERLSTYLE|OP_OPTIMIZE|(!Case?OP_IGNORECASE:0))) return false; SMatch m[10*2], *pm = m; intptr_t n = re.GetBracketsCount(); if (n > static_cast<int>(ARRAYSIZE(m)/2)) { pm = (SMatch *)xf_malloc(2*n*sizeof(SMatch)); if (!pm) return false; } bool found = false; int half = 0; if (!Reverse) { if (re.SearchEx(Source,Source+Position,Source+StrSize,pm,n)) found = true; } else { int pos = 0; for (;;) { if (!re.SearchEx(Source,Source+pos,Source+StrSize,pm+half,n)) break; pos = static_cast<int>(pm[half].start); if (pos > Position) break; found = true; ++pos; half = n - half; } half = n - half; } if (found) { *SearchLength = pm[half].end - pm[half].start; CurPos = pm[half].start; ReplaceStr=ReplaceBrackets(Source,ReplaceStr,pm+half,n); } if (pm != m) xf_free(pm); return found; } if (Position==StrSize) return false; int Length = *SearchLength = (int)Str.GetLength(); for (int I=Position; (Reverse && I>=0) || (!Reverse && I<StrSize); Reverse ? I--:I++) { for (int J=0;; J++) { if (!Str[J]) { CurPos=I; return true; } if (WholeWords) { int locResultLeft=FALSE; int locResultRight=FALSE; wchar_t ChLeft=Source[I-1]; if (I>0) locResultLeft=(IsSpace(ChLeft) || wcschr(WordDiv,ChLeft)); else locResultLeft=TRUE; if (I+Length<StrSize) { wchar_t ChRight=Source[I+Length]; locResultRight=(IsSpace(ChRight) || wcschr(WordDiv,ChRight)); } else { locResultRight=TRUE; } if (!locResultLeft || !locResultRight) break; } wchar_t Ch=Source[I+J]; if (Case) { if (Ch!=Str[J]) break; } else { if (Upper(Ch)!=Upper(Str[J])) break; } } } } return false; }
void WatchWindow::OnKeyDown(wxTreeEvent& event) { if (event.GetKeyCode() == WXK_DELETE || event.GetKeyCode() == WXK_BACK) { wxTreeItemId item = GetSelection(); if (item.IsOk() && GetItemParent(item) == m_root) { wxTreeItemId next = GetNextSibling(item); Delete(item); CreateEmptySlotIfNeeded(); // Select the next item. if (!next.IsOk()) { wxTreeItemIdValue cookie; next = GetLastChild(GetRootItem(), cookie); } SelectItem(next); } } else { // If we're not currently editing a field, begin editing. This // eliminates the need to double click to begin editing. int code = event.GetKeyCode(); if (!m_editing && code < 256 && (isgraph(code) || IsSpace(code))) { // Get the currently selected item in the list. wxTreeItemId item = GetSelection(); if (item.IsOk()) { if (IsSpace(code)) { EditLabel(item, ""); } else { EditLabel(item, wxString(static_cast<char>(code))); } event.Skip(false); } } else { event.Skip(true); } } }
bool TParser::GetToken() { curToken = _T(""); if(pos >= expr.GetLength()) { curToken = _T(""); typToken = PARSER_END; return true; } while(IsSpace()) pos++; if(IsDelim()) { curToken = expr[pos++]; switch(curToken[0]) { case _T('+'): typToken = PARSER_PLUS; return true; case _T('-'): typToken = PARSER_MINUS; return true; case _T('*'): typToken = PARSER_MULTIPLY; return true; case _T('/'): typToken = PARSER_DIVIDE; return true; case _T('%'): typToken = PARSER_PERCENT; return true; case _T('^'): typToken = PARSER_POWER; return true; case _T('['): case _T('('): typToken = PARSER_L_BRACKET; return true; case _T(']'): case _T(')'): typToken = PARSER_R_BRACKET; return true; } } else if(IsComma()) { curToken = expr[pos++]; typToken = PARSER_COMMA; return true; } else if(IsLetter()) { int i=0; curToken = _T(""); while(IsLetter() || IsDigit()) curToken += expr[pos++]; curToken.MakeLower(); if(curToken == _T("pi")) { typToken = PARSER_PI; return true; } else if(curToken == _T("e")) { typToken = PARSER_E; return true; } else if(curToken == _T("sin")) { typToken = PARSER_SIN; return true; } else if(curToken == _T("cos")) { typToken = PARSER_COS; return true; } else if(curToken == _T("tg")) { typToken = PARSER_TG; return true; } else if(curToken == _T("ctg")) { typToken = PARSER_CTG; return true; } else if(curToken == _T("arcsin")) { typToken = PARSER_ARCSIN; return true; } else if(curToken == _T("arccos")) { typToken = PARSER_ARCCOS; return true; } else if(curToken == _T("arctg")) { typToken = PARSER_ARCTG; return true; } else if(curToken == _T("arcctg")) { typToken = PARSER_ARCCTG; return true; } else if(curToken == _T("sh")) { typToken = PARSER_SH; return true; } else if(curToken == _T("ch")) { typToken = PARSER_CH; return true; } else if(curToken == _T("th")) { typToken = PARSER_TH; return true; } else if(curToken == _T("cth")) { typToken = PARSER_CTH; return true; } else if(curToken == _T("exp")) { typToken = PARSER_EXP; return true; } else if(curToken == _T("lg")) { typToken = PARSER_LG; return true; } else if(curToken == _T("ln")) { typToken = PARSER_LN; return true; } else if(curToken == _T("sqrt")) { typToken = PARSER_SQRT; return true; } else if(curToken == _T("abs")) { typToken = PARSER_ABS; return true; } else if(curToken == _T("min")) { typToken = PARSER_MIN; return true; } else if(curToken == _T("max")) { typToken = PARSER_MAX; return true; } else if(curToken == _T("atan2")) { typToken = PARSER_ATAN2; return true; } else if(curToken == _T("if")) { typToken = PARSER_IF; return true; } else if(curToken == _T("left")) { typToken = PARSER_GUIDE; return true; } else if(curToken == _T("right")) { typToken = PARSER_GUIDE; return true; } else if(curToken == _T("top")) { typToken = PARSER_GUIDE; return true; } else if(curToken == _T("bottom")) { typToken = PARSER_GUIDE; return true; } else if(curToken == _T("width")) { typToken = PARSER_GUIDE; return true; } else if(curToken == _T("height")) { typToken = PARSER_GUIDE; return true; } else SendError(0); } else if(IsAdjust()) { int i=0; curToken = _T(""); while((!IsSpace())&&(!IsDelim())) curToken += expr[pos++]; typToken = PARSER_ADJUST; return true; } else if(IsGuide()) { int i=0; curToken = _T(""); while((!IsSpace())&&(!IsDelim())) curToken += expr[pos++]; typToken = PARSER_GUIDE; return true; } else if(IsDigit() || IsPoint()) { int i=0; curToken = _T(""); while(IsDigit()) curToken += expr[pos++]; if(IsPoint()) { curToken += expr[pos++]; while(IsDigit()) curToken += expr[pos++]; } typToken = PARSER_NUMBER; return true; } else { curToken = expr[pos++]; SendError(1); } return false; }
void DizList::Read(const string& Path, const string* DizName) { Reset(); struct DizPreRedrawItem : public PreRedrawItem { DizPreRedrawItem() : PreRedrawItem(PR_ReadingMsg) {} }; SCOPED_ACTION(TPreRedrawFuncGuard)(std::make_unique<DizPreRedrawItem>()); const wchar_t *NamePtr=Global->Opt->Diz.strListNames.data(); for (;;) { if (DizName) { strDizFileName = *DizName; } else { strDizFileName = Path; if (!PathCanHoldRegularFile(strDizFileName)) break; string strArgName; NamePtr = GetCommaWord(NamePtr, strArgName); if (!NamePtr) break; AddEndSlash(strDizFileName); strDizFileName += strArgName; } os::fs::file DizFile; if (DizFile.Open(strDizFileName,GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING)) { clock_t StartTime=clock(); uintptr_t CodePage=CP_DEFAULT; bool bSigFound=false; if (!GetFileFormat(DizFile,CodePage,&bSigFound,false) || !bSigFound) CodePage = Global->Opt->Diz.AnsiByDefault ? CP_ACP : CP_OEMCP; GetFileString GetStr(DizFile, CodePage); auto LastAdded = DizData.end(); string DizText; while (GetStr.GetString(DizText)) { if (!(DizData.size() & 127) && clock() - StartTime > CLOCKS_PER_SEC) { SetCursorType(false, 0); PR_ReadingMsg(); if (CheckForEsc()) break; } RemoveTrailingSpaces(DizText); if (!DizText.empty()) { if(!IsSpace(DizText.front())) { LastAdded = AddRecord(DizText); } else { if (LastAdded != DizData.end()) { LastAdded->second.emplace_back(DizText); } } } } OrigCodePage=CodePage; Modified=false; DizFile.Close(); return; } if (DizName) break; } Modified=false; strDizFileName.clear(); }
nsresult nsLineBreaker::AppendText(nsIAtom* aHyphenationLanguage, const uint8_t* aText, uint32_t aLength, uint32_t aFlags, nsILineBreakSink* aSink) { NS_ASSERTION(aLength > 0, "Appending empty text..."); if (aFlags & (BREAK_NEED_CAPITALIZATION | BREAK_USE_AUTO_HYPHENATION)) { // Defer to the Unicode path if capitalization or hyphenation is required nsAutoString str; const char* cp = reinterpret_cast<const char*>(aText); CopyASCIItoUTF16(nsDependentCSubstring(cp, cp + aLength), str); return AppendText(aHyphenationLanguage, str.get(), aLength, aFlags, aSink); } uint32_t offset = 0; // Continue the current word if (mCurrentWord.Length() > 0) { NS_ASSERTION(!mAfterBreakableSpace && !mBreakHere, "These should not be set"); while (offset < aLength && !IsSpace(aText[offset])) { mCurrentWord.AppendElement(aText[offset]); if (!mCurrentWordContainsComplexChar && IsComplexASCIIChar(aText[offset])) { mCurrentWordContainsComplexChar = true; } ++offset; } if (offset > 0) { mTextItems.AppendElement(TextItem(aSink, 0, offset, aFlags)); } if (offset == aLength) { // We did not encounter whitespace so the word hasn't finished yet. return NS_OK; } // We encountered whitespace, so we're done with this word nsresult rv = FlushCurrentWord(); if (NS_FAILED(rv)) return rv; } nsAutoTArray<uint8_t,4000> breakState; if (aSink) { if (!breakState.AppendElements(aLength)) return NS_ERROR_OUT_OF_MEMORY; } uint32_t start = offset; bool noBreaksNeeded = !aSink || ((aFlags & NO_BREAKS_NEEDED_FLAGS) == NO_BREAKS_NEEDED_FLAGS && !mBreakHere && !mAfterBreakableSpace); if (noBreaksNeeded) { // Skip to the space before the last word, since either the break data // here is not needed, or no breaks are set in the sink and there cannot // be any breaks in this chunk; all we need is the context for the next // chunk (if any) offset = aLength; while (offset > start) { --offset; if (IsSpace(aText[offset])) break; } } uint32_t wordStart = offset; bool wordHasComplexChar = false; for (;;) { uint8_t ch = aText[offset]; bool isSpace = IsSpace(ch); bool isBreakableSpace = isSpace && !(aFlags & BREAK_SUPPRESS_INSIDE); if (aSink) { // Consider word-break style. Since the break position of CJK scripts // will be set by nsILineBreaker, we don't consider CJK at this point. breakState[offset] = mBreakHere || (mAfterBreakableSpace && !isBreakableSpace) || (mWordBreak == nsILineBreaker::kWordBreak_BreakAll) ? gfxTextRun::CompressedGlyph::FLAG_BREAK_TYPE_NORMAL : gfxTextRun::CompressedGlyph::FLAG_BREAK_TYPE_NONE; } mBreakHere = false; mAfterBreakableSpace = isBreakableSpace; if (isSpace) { if (offset > wordStart && wordHasComplexChar) { if (aSink && !(aFlags & BREAK_SUPPRESS_INSIDE)) { // Save current start-of-word state because GetJISx4051Breaks will // set it to false uint8_t currentStart = breakState[wordStart]; nsContentUtils::LineBreaker()-> GetJISx4051Breaks(aText + wordStart, offset - wordStart, mWordBreak, breakState.Elements() + wordStart); breakState[wordStart] = currentStart; } wordHasComplexChar = false; } ++offset; if (offset >= aLength) break; wordStart = offset; } else { if (!wordHasComplexChar && IsComplexASCIIChar(ch)) { wordHasComplexChar = true; } ++offset; if (offset >= aLength) { // Save this word mCurrentWordContainsComplexChar = wordHasComplexChar; uint32_t len = offset - wordStart; char16_t* elems = mCurrentWord.AppendElements(len); if (!elems) return NS_ERROR_OUT_OF_MEMORY; uint32_t i; for (i = wordStart; i < offset; ++i) { elems[i - wordStart] = aText[i]; } mTextItems.AppendElement(TextItem(aSink, wordStart, len, aFlags)); // Ensure that the break-before for this word is written out offset = wordStart + 1; break; } } } if (!noBreaksNeeded) { aSink->SetBreaks(start, offset - start, breakState.Elements() + start); } return NS_OK; }
static const char * skip_space(const char *str, const char *line) { while (IsSpace(*str)) { str++; } return str; }