<commit_before>/*
 * Copyright (C) 2022 Red Hat, Inc.
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; If not, see <http://www.gnu.org/licenses/>.
 *
 */

#pragma once

#ifndef __URIPARSER_H_
#define __URIPARSER_H_

#include <algorithm>
#include <iostream>
#include <stdexcept>
#include <string>
#include <unordered_map>

namespace lsm_uri {

using query_key_value = std::unordered_map<std::string, std::string>;

struct uri {
    bool valid = false;
    std::string scheme;
    std::string username;
    std::string host;
    long port = -1;
    std::string path;
    query_key_value query;
    std::string fragment;
};

inline bool verify_scheme(std::string s) {
    if (s.empty() || std::find_if_not(s.begin(), s.end(), [&](char c) {
                         return std::isalnum(c) || c == '+' || c == '.' ||
                                c == '-';
                     }) != s.end()) {
        return false;
    }

    return true;
}

inline std::tuple<std::string, std::string> pair(std::string s) {
    auto i = s.find("=");
    if (i == std::string::npos) {
        return {s, ""};
    }
    return {s.substr(0, i), s.substr(i + 1)};
}

inline query_key_value parse_qs(std::string qs) {
    query_key_value rc;

    std::string key;
    std::string value;

    if (!qs.length())
        return rc;

    std::size_t amp;
    do {
        amp = qs.find("&");

        if (amp == std::string::npos) {
            // No separator found
            std::tie(key, value) = pair(qs);
            rc[key] = value;

        } else {
            // & found
            std::tie(key, value) = pair(qs.substr(0, amp));
            rc[key] = value;
            qs = qs.substr(amp + 1);
        }

    } while (amp != std::string::npos);

    return rc;
}

inline long port(std::string s) {
    long rc = -1;

    if (s.empty() || std::find_if_not(s.begin(), s.end(), [&](char c) {
                         return std::isdigit(c);
                     }) != s.end()) {
        return rc;
    }

    // Convert string to long
    try {
        rc = std::stol(s);
    } catch (const std::invalid_argument &ia) {
    }

    return rc;
}

inline struct uri parse(std::string uri) {
    struct uri rc;

    std::size_t req;

    // Library requires :// in uri
    if (uri.empty() || ((req = uri.find("://")) == std::string::npos)) {
        return rc;
    }

    std::string scheme_tmp = uri.substr(0, req);
    if (!verify_scheme(scheme_tmp)) {
        return rc;
    }

    rc.scheme = scheme_tmp;

    auto remainder = uri.substr(req + 3);

    // Check to see if we have a fragment
    auto frag = remainder.rfind("#");
    if (frag != std::string::npos) {
        rc.fragment = remainder.substr(frag + 1);
        remainder = remainder.substr(0, frag);
    }

    // Check for query string
    auto qs = remainder.rfind("?");
    if (qs != std::string::npos) {
        rc.query = parse_qs(remainder.substr(qs + 1));
        remainder = remainder.substr(0, qs);
    }

    // process location & path
    auto path_start = remainder.find("/");
    if (path_start != std::string::npos) {
        rc.path = remainder.substr(path_start);
        remainder = remainder.substr(0, path_start);
    }

    // process username, port, then host
    auto username = remainder.find("@");
    if (username != std::string::npos) {
        rc.username = remainder.substr(0, username);
        remainder = remainder.substr(username + 1);
    }

    // Check for port on host
    auto port_del = remainder.rfind(":");
    if (port_del != std::string::npos) {
        // Check if this is a valid port, could be ipv6 addr.
        long tmp_port = port(remainder.substr(port_del + 1));
        if (tmp_port != -1) {
            rc.port = tmp_port;
            remainder = remainder.substr(0, port_del);
        }
    }

    // Only part left should be host, which is a ipv4, hostname, or ipv6
    rc.host = remainder;
    rc.valid = true;
    return rc;
}

} // namespace lsm_uri

#endif<commit_msg>EL7: Use alt. tuple syntax<commit_after>/*
 * Copyright (C) 2022 Red Hat, Inc.
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; If not, see <http://www.gnu.org/licenses/>.
 *
 */

#pragma once

#ifndef __URIPARSER_H_
#define __URIPARSER_H_

#include <algorithm>
#include <iostream>
#include <stdexcept>
#include <string>
#include <unordered_map>

namespace lsm_uri {

using query_key_value = std::unordered_map<std::string, std::string>;

struct uri {
    bool valid = false;
    std::string scheme;
    std::string username;
    std::string host;
    long port = -1;
    std::string path;
    query_key_value query;
    std::string fragment;
};

inline bool verify_scheme(std::string s) {
    if (s.empty() || std::find_if_not(s.begin(), s.end(), [&](char c) {
                         return std::isalnum(c) || c == '+' || c == '.' ||
                                c == '-';
                     }) != s.end()) {
        return false;
    }

    return true;
}

inline std::tuple<std::string, std::string> pair(std::string s) {
    auto i = s.find("=");
    if (i == std::string::npos) {
        return std::make_tuple(s, "");
    }
    return std::make_tuple(s.substr(0, i), s.substr(i + 1));
}

inline query_key_value parse_qs(std::string qs) {
    query_key_value rc;

    std::string key;
    std::string value;

    if (!qs.length())
        return rc;

    std::size_t amp;
    do {
        amp = qs.find("&");

        if (amp == std::string::npos) {
            // No separator found
            std::tie(key, value) = pair(qs);
            rc[key] = value;

        } else {
            // & found
            std::tie(key, value) = pair(qs.substr(0, amp));
            rc[key] = value;
            qs = qs.substr(amp + 1);
        }

    } while (amp != std::string::npos);

    return rc;
}

inline long port(std::string s) {
    long rc = -1;

    if (s.empty() || std::find_if_not(s.begin(), s.end(), [&](char c) {
                         return std::isdigit(c);
                     }) != s.end()) {
        return rc;
    }

    // Convert string to long
    try {
        rc = std::stol(s);
    } catch (const std::invalid_argument &ia) {
    }

    return rc;
}

inline struct uri parse(std::string uri) {
    struct uri rc;

    std::size_t req;

    // Library requires :// in uri
    if (uri.empty() || ((req = uri.find("://")) == std::string::npos)) {
        return rc;
    }

    std::string scheme_tmp = uri.substr(0, req);
    if (!verify_scheme(scheme_tmp)) {
        return rc;
    }

    rc.scheme = scheme_tmp;

    auto remainder = uri.substr(req + 3);

    // Check to see if we have a fragment
    auto frag = remainder.rfind("#");
    if (frag != std::string::npos) {
        rc.fragment = remainder.substr(frag + 1);
        remainder = remainder.substr(0, frag);
    }

    // Check for query string
    auto qs = remainder.rfind("?");
    if (qs != std::string::npos) {
        rc.query = parse_qs(remainder.substr(qs + 1));
        remainder = remainder.substr(0, qs);
    }

    // process location & path
    auto path_start = remainder.find("/");
    if (path_start != std::string::npos) {
        rc.path = remainder.substr(path_start);
        remainder = remainder.substr(0, path_start);
    }

    // process username, port, then host
    auto username = remainder.find("@");
    if (username != std::string::npos) {
        rc.username = remainder.substr(0, username);
        remainder = remainder.substr(username + 1);
    }

    // Check for port on host
    auto port_del = remainder.rfind(":");
    if (port_del != std::string::npos) {
        // Check if this is a valid port, could be ipv6 addr.
        long tmp_port = port(remainder.substr(port_del + 1));
        if (tmp_port != -1) {
            rc.port = tmp_port;
            remainder = remainder.substr(0, port_del);
        }
    }

    // Only part left should be host, which is a ipv4, hostname, or ipv6
    rc.host = remainder;
    rc.valid = true;
    return rc;
}

} // namespace lsm_uri

#endif<|endoftext|>


<commit_before>/* Copyright 2015 Samsung Electronics Co., LTD
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "android/log.h"
#include "gvr_cpp_stack_trace.h"

#include <iostream>
#include <sstream>
#include <iomanip>

#include <unwind.h>
#include <dlfcn.h>

#define TAG "gvrf"

namespace {

    struct BacktraceState
    {
        void** current;
        void** end;
    };

    static _Unwind_Reason_Code unwindCallback(struct _Unwind_Context* context, void* arg)
    {
        BacktraceState* state = static_cast<BacktraceState*>(arg);
        uintptr_t pc = _Unwind_GetIP(context);
        if (pc) {
            if (state->current == state->end) {
                return _URC_END_OF_STACK;
            } else {
                *state->current++ = reinterpret_cast<void*>(pc);
            }
        }
        return _URC_NO_REASON;
    }

    size_t captureBacktrace(void** buffer, size_t max)
    {
        BacktraceState state = {buffer, buffer + max};
        _Unwind_Backtrace(unwindCallback, &state);

        return state.current - buffer;
    }

    void dumpBacktrace(std::ostream& os, void** addrs, size_t count)
    {
        for (size_t idx = 0; idx < count; ++idx) {
            const void* addr = addrs[idx];
            const char* symbol = "";

            Dl_info info;
            if (dladdr(addr, &info) && info.dli_sname) {
                symbol = info.dli_sname;
            }

            os << "  #" << std::setw(2) << idx << ": " << addr << "  " << symbol << "\n";
        }
    }

} // namespace

void printStackTrace(unsigned int max_frames)
{
    void* buffer[max_frames];
    std::ostringstream oss;

    dumpBacktrace(oss, buffer, captureBacktrace(buffer, max_frames));

    __android_log_print(ANDROID_LOG_DEBUG, TAG, "%s", oss.str().c_str());
}
<commit_msg>Use log macro for stack trace<commit_after>/* Copyright 2015 Samsung Electronics Co., LTD
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "util/gvr_log.h"
#include "gvr_cpp_stack_trace.h"

#include <iostream>
#include <sstream>
#include <iomanip>

#include <unwind.h>
#include <dlfcn.h>

namespace {

    struct BacktraceState
    {
        void** current;
        void** end;
    };

    static _Unwind_Reason_Code unwindCallback(struct _Unwind_Context* context, void* arg)
    {
        BacktraceState* state = static_cast<BacktraceState*>(arg);
        uintptr_t pc = _Unwind_GetIP(context);
        if (pc) {
            if (state->current == state->end) {
                return _URC_END_OF_STACK;
            } else {
                *state->current++ = reinterpret_cast<void*>(pc);
            }
        }
        return _URC_NO_REASON;
    }

    size_t captureBacktrace(void** buffer, size_t max)
    {
        BacktraceState state = {buffer, buffer + max};
        _Unwind_Backtrace(unwindCallback, &state);

        return state.current - buffer;
    }

    void dumpBacktrace(std::ostream& os, void** addrs, size_t count)
    {
        for (size_t idx = 0; idx < count; ++idx) {
            const void* addr = addrs[idx];
            const char* symbol = "";

            Dl_info info;
            if (dladdr(addr, &info) && info.dli_sname) {
                symbol = info.dli_sname;
            }

            os << "  #" << std::setw(2) << idx << ": " << addr << "  " << symbol << "\n";
        }
    }

} // namespace

void printStackTrace(unsigned int max_frames)
{
    void* buffer[max_frames];
    std::ostringstream oss;

    dumpBacktrace(oss, buffer, captureBacktrace(buffer, max_frames));

    LOGD("%s", oss.str().c_str());
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmloff.hxx"
#include "valueproperties.hxx"
#include "strings.hxx"
#include <com/sun/star/form/FormComponentType.hpp>

//.........................................................................
namespace xmloff
{
//.........................................................................

    using namespace ::com::sun::star::form;

    //=====================================================================
    //= OValuePropertiesMetaData
    //=====================================================================
    //---------------------------------------------------------------------
    void OValuePropertiesMetaData::getValuePropertyNames(
            OControlElement::ElementType _eType, sal_Int16 _nFormComponentType,
            sal_Char const * & _rpCurrentValuePropertyName, sal_Char const * & _rpValuePropertyName)
    {
        // reset the pointers in case we can't determine the property names
        _rpCurrentValuePropertyName = _rpValuePropertyName = NULL;
        switch (_nFormComponentType)
        {
            case FormComponentType::TEXTFIELD:
                if (OControlElement::FORMATTED_TEXT == _eType)
                {
                    _rpCurrentValuePropertyName = PROPERTY_EFFECTIVE_VALUE;
                    _rpValuePropertyName = PROPERTY_EFFECTIVE_DEFAULT;
                }
                else
                {
                    if (OControlElement::PASSWORD != _eType)
                        // no CurrentValue" for passwords
                        _rpCurrentValuePropertyName = PROPERTY_TEXT;
                    _rpValuePropertyName = PROPERTY_DEFAULT_TEXT;
                }
                break;

            case FormComponentType::DATEFIELD:
                _rpCurrentValuePropertyName = PROPERTY_DATE;
                _rpValuePropertyName = PROPERTY_DEFAULT_DATE;
                break;

            case FormComponentType::TIMEFIELD:
                _rpCurrentValuePropertyName = PROPERTY_TIME;
                _rpValuePropertyName = PROPERTY_DEFAULT_TIME;
                break;

            case FormComponentType::NUMERICFIELD:
            case FormComponentType::CURRENCYFIELD:
                _rpCurrentValuePropertyName = PROPERTY_VALUE;
                _rpValuePropertyName = PROPERTY_DEFAULT_VALUE;
                break;

            case FormComponentType::PATTERNFIELD:
            case FormComponentType::FILECONTROL:
            case FormComponentType::COMBOBOX:
                _rpValuePropertyName = PROPERTY_DEFAULT_TEXT;
                // NO BREAK!!
            case FormComponentType::COMMANDBUTTON:
                _rpCurrentValuePropertyName = PROPERTY_TEXT;
                break;

            case FormComponentType::CHECKBOX:
            case FormComponentType::RADIOBUTTON:
                _rpValuePropertyName = PROPERTY_REFVALUE;
                break;

            case FormComponentType::HIDDENCONTROL:
                _rpValuePropertyName = PROPERTY_HIDDEN_VALUE;
                break;

            case FormComponentType::SCROLLBAR:
                _rpCurrentValuePropertyName = PROPERTY_SCROLLVALUE;
                _rpValuePropertyName = PROPERTY_SCROLLVALUE_DEFAULT;
                break;

            case FormComponentType::SPINBUTTON:
                _rpCurrentValuePropertyName = PROPERTY_SPINVALUE;
                _rpValuePropertyName = PROPERTY_DEFAULT_SPINVALUE;
                break;
        }
    }

    //---------------------------------------------------------------------
    void OValuePropertiesMetaData::getValueLimitPropertyNames(sal_Int16 _nFormComponentType,
        sal_Char const * & _rpMinValuePropertyName, sal_Char const * & _rpMaxValuePropertyName)
    {
        _rpMinValuePropertyName = _rpMinValuePropertyName = NULL;
        switch (_nFormComponentType)
        {
            case FormComponentType::DATEFIELD:
                _rpMinValuePropertyName = PROPERTY_DATE_MIN;
                _rpMaxValuePropertyName = PROPERTY_DATE_MAX;
                break;

            case FormComponentType::TIMEFIELD:
                _rpMinValuePropertyName = PROPERTY_TIME_MIN;
                _rpMaxValuePropertyName = PROPERTY_TIME_MAX;
                break;

            case FormComponentType::NUMERICFIELD:
            case FormComponentType::CURRENCYFIELD:
                _rpMinValuePropertyName = PROPERTY_VALUE_MIN;
                _rpMaxValuePropertyName = PROPERTY_VALUE_MAX;
                break;

            case FormComponentType::TEXTFIELD:
                _rpMinValuePropertyName = PROPERTY_EFFECTIVE_MIN;
                _rpMaxValuePropertyName = PROPERTY_EFFECTIVE_MAX;
                break;

            case FormComponentType::SCROLLBAR:
                _rpMinValuePropertyName = PROPERTY_SCROLLVALUE_MIN;
                _rpMaxValuePropertyName = PROPERTY_SCROLLVALUE_MAX;
                break;

            case FormComponentType::SPINBUTTON:
                _rpMinValuePropertyName = PROPERTY_SPINVALUE_MIN;
                _rpMaxValuePropertyName = PROPERTY_SPINVALUE_MAX;
                break;
        }
    }

    //---------------------------------------------------------------------
    void OValuePropertiesMetaData::getRuntimeValuePropertyNames(
        OControlElement::ElementType _eType, sal_Int16 _nFormComponentType,
        sal_Char const * & _rpValuePropertyName, sal_Char const * & _rpDefaultValuePropertyName )
    {
        // reset the pointers in case we can't determine the property names
        _rpValuePropertyName = _rpDefaultValuePropertyName = NULL;
        switch (_nFormComponentType)
        {
            case FormComponentType::TEXTFIELD:
                if (OControlElement::FORMATTED_TEXT == _eType)
                {
                    _rpValuePropertyName = PROPERTY_EFFECTIVE_VALUE;
                    _rpDefaultValuePropertyName = PROPERTY_EFFECTIVE_DEFAULT;
                }
                else
                {
                    _rpValuePropertyName = PROPERTY_TEXT;
                    _rpDefaultValuePropertyName = PROPERTY_DEFAULT_TEXT;
                }
                break;

            case FormComponentType::DATEFIELD:
            case FormComponentType::TIMEFIELD:
            case FormComponentType::NUMERICFIELD:
            case FormComponentType::CURRENCYFIELD:
            case FormComponentType::PATTERNFIELD:
            case FormComponentType::FILECONTROL:
            case FormComponentType::COMBOBOX:
            case FormComponentType::SCROLLBAR:
            case FormComponentType::SPINBUTTON:
                // For these types, the runtime properties are the same as the ones which in the XML
                // stream are named "value properties"
                getValuePropertyNames( _eType, _nFormComponentType, _rpValuePropertyName, _rpDefaultValuePropertyName );
                break;

            case FormComponentType::CHECKBOX:
            case FormComponentType::RADIOBUTTON:
                _rpValuePropertyName = PROPERTY_STATE;
                _rpDefaultValuePropertyName = PROPERTY_DEFAULT_STATE;
                break;
        }
    }

//.........................................................................
}   // namespace xmloff
//.........................................................................

<commit_msg>sw33bf04: #i111381#: OValuePropertiesMetaData: apply patch by tono<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmloff.hxx"
#include "valueproperties.hxx"
#include "strings.hxx"
#include <com/sun/star/form/FormComponentType.hpp>

//.........................................................................
namespace xmloff
{
//.........................................................................

    using namespace ::com::sun::star::form;

    //=====================================================================
    //= OValuePropertiesMetaData
    //=====================================================================
    //---------------------------------------------------------------------
    void OValuePropertiesMetaData::getValuePropertyNames(
            OControlElement::ElementType _eType, sal_Int16 _nFormComponentType,
            sal_Char const * & _rpCurrentValuePropertyName, sal_Char const * & _rpValuePropertyName)
    {
        // reset the pointers in case we can't determine the property names
        _rpCurrentValuePropertyName = _rpValuePropertyName = NULL;
        switch (_nFormComponentType)
        {
            case FormComponentType::TEXTFIELD:
                if (OControlElement::FORMATTED_TEXT == _eType)
                {
                    _rpCurrentValuePropertyName = PROPERTY_EFFECTIVE_VALUE;
                    _rpValuePropertyName = PROPERTY_EFFECTIVE_DEFAULT;
                }
                else
                {
                    if (OControlElement::PASSWORD != _eType)
                        // no CurrentValue" for passwords
                        _rpCurrentValuePropertyName = PROPERTY_TEXT;
                    _rpValuePropertyName = PROPERTY_DEFAULT_TEXT;
                }
                break;

            case FormComponentType::DATEFIELD:
                _rpCurrentValuePropertyName = PROPERTY_DATE;
                _rpValuePropertyName = PROPERTY_DEFAULT_DATE;
                break;

            case FormComponentType::TIMEFIELD:
                _rpCurrentValuePropertyName = PROPERTY_TIME;
                _rpValuePropertyName = PROPERTY_DEFAULT_TIME;
                break;

            case FormComponentType::NUMERICFIELD:
            case FormComponentType::CURRENCYFIELD:
                _rpCurrentValuePropertyName = PROPERTY_VALUE;
                _rpValuePropertyName = PROPERTY_DEFAULT_VALUE;
                break;

            case FormComponentType::PATTERNFIELD:
            case FormComponentType::FILECONTROL:
            case FormComponentType::COMBOBOX:
                _rpValuePropertyName = PROPERTY_DEFAULT_TEXT;
                // NO BREAK!!
            case FormComponentType::COMMANDBUTTON:
                _rpCurrentValuePropertyName = PROPERTY_TEXT;
                break;

            case FormComponentType::CHECKBOX:
            case FormComponentType::RADIOBUTTON:
                _rpValuePropertyName = PROPERTY_REFVALUE;
                break;

            case FormComponentType::HIDDENCONTROL:
                _rpValuePropertyName = PROPERTY_HIDDEN_VALUE;
                break;

            case FormComponentType::SCROLLBAR:
                _rpCurrentValuePropertyName = PROPERTY_SCROLLVALUE;
                _rpValuePropertyName = PROPERTY_SCROLLVALUE_DEFAULT;
                break;

            case FormComponentType::SPINBUTTON:
                _rpCurrentValuePropertyName = PROPERTY_SPINVALUE;
                _rpValuePropertyName = PROPERTY_DEFAULT_SPINVALUE;
                break;
        }
    }

    //---------------------------------------------------------------------
    void OValuePropertiesMetaData::getValueLimitPropertyNames(sal_Int16 _nFormComponentType,
        sal_Char const * & _rpMinValuePropertyName, sal_Char const * & _rpMaxValuePropertyName)
    {
        _rpMinValuePropertyName = _rpMaxValuePropertyName = NULL;
        switch (_nFormComponentType)
        {
            case FormComponentType::DATEFIELD:
                _rpMinValuePropertyName = PROPERTY_DATE_MIN;
                _rpMaxValuePropertyName = PROPERTY_DATE_MAX;
                break;

            case FormComponentType::TIMEFIELD:
                _rpMinValuePropertyName = PROPERTY_TIME_MIN;
                _rpMaxValuePropertyName = PROPERTY_TIME_MAX;
                break;

            case FormComponentType::NUMERICFIELD:
            case FormComponentType::CURRENCYFIELD:
                _rpMinValuePropertyName = PROPERTY_VALUE_MIN;
                _rpMaxValuePropertyName = PROPERTY_VALUE_MAX;
                break;

            case FormComponentType::TEXTFIELD:
                _rpMinValuePropertyName = PROPERTY_EFFECTIVE_MIN;
                _rpMaxValuePropertyName = PROPERTY_EFFECTIVE_MAX;
                break;

            case FormComponentType::SCROLLBAR:
                _rpMinValuePropertyName = PROPERTY_SCROLLVALUE_MIN;
                _rpMaxValuePropertyName = PROPERTY_SCROLLVALUE_MAX;
                break;

            case FormComponentType::SPINBUTTON:
                _rpMinValuePropertyName = PROPERTY_SPINVALUE_MIN;
                _rpMaxValuePropertyName = PROPERTY_SPINVALUE_MAX;
                break;
        }
    }

    //---------------------------------------------------------------------
    void OValuePropertiesMetaData::getRuntimeValuePropertyNames(
        OControlElement::ElementType _eType, sal_Int16 _nFormComponentType,
        sal_Char const * & _rpValuePropertyName, sal_Char const * & _rpDefaultValuePropertyName )
    {
        // reset the pointers in case we can't determine the property names
        _rpValuePropertyName = _rpDefaultValuePropertyName = NULL;
        switch (_nFormComponentType)
        {
            case FormComponentType::TEXTFIELD:
                if (OControlElement::FORMATTED_TEXT == _eType)
                {
                    _rpValuePropertyName = PROPERTY_EFFECTIVE_VALUE;
                    _rpDefaultValuePropertyName = PROPERTY_EFFECTIVE_DEFAULT;
                }
                else
                {
                    _rpValuePropertyName = PROPERTY_TEXT;
                    _rpDefaultValuePropertyName = PROPERTY_DEFAULT_TEXT;
                }
                break;

            case FormComponentType::DATEFIELD:
            case FormComponentType::TIMEFIELD:
            case FormComponentType::NUMERICFIELD:
            case FormComponentType::CURRENCYFIELD:
            case FormComponentType::PATTERNFIELD:
            case FormComponentType::FILECONTROL:
            case FormComponentType::COMBOBOX:
            case FormComponentType::SCROLLBAR:
            case FormComponentType::SPINBUTTON:
                // For these types, the runtime properties are the same as the ones which in the XML
                // stream are named "value properties"
                getValuePropertyNames( _eType, _nFormComponentType, _rpValuePropertyName, _rpDefaultValuePropertyName );
                break;

            case FormComponentType::CHECKBOX:
            case FormComponentType::RADIOBUTTON:
                _rpValuePropertyName = PROPERTY_STATE;
                _rpDefaultValuePropertyName = PROPERTY_DEFAULT_STATE;
                break;
        }
    }

//.........................................................................
}   // namespace xmloff
//.........................................................................

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: saxhelper.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: kz $ $Date: 2007-02-14 15:32:38 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmlsecurity.hxx"

#include <rtl/ustring.hxx>

#include "saxhelper.hxx"
#include "libxml/parserInternals.h"

#ifndef XMLSEC_NO_XSLT
#include "libxslt/xslt.h"
#endif

namespace cssu = com::sun::star::uno;
namespace cssxs = com::sun::star::xml::sax;
namespace cssxcsax = com::sun::star::xml::csax;

/**
 * The return value is NULL terminated. The application has the responsibilty to
 * deallocte the return value.
 */
xmlChar* ous_to_xmlstr( const rtl::OUString& oustr )
{
    rtl::OString ostr = rtl::OUStringToOString( oustr , RTL_TEXTENCODING_UTF8 ) ;
    return xmlStrndup( ( xmlChar* )ostr.getStr(), ( int )ostr.getLength() ) ;
}

/**
 * The return value is NULL terminated. The application has the responsibilty to
 * deallocte the return value.
 */
xmlChar* ous_to_nxmlstr( const rtl::OUString& oustr, int& length )
{
    rtl::OString ostr = rtl::OUStringToOString( oustr , RTL_TEXTENCODING_UTF8 ) ;
    length = ostr.getLength();

    return xmlStrndup( ( xmlChar* )ostr.getStr(), length ) ;
}

/**
 * The input parameter isn't necessaryly NULL terminated.
 */
rtl::OUString xmlchar_to_ous( const xmlChar* pChar, int length )
{
    if( pChar != NULL )
    {
        return rtl::OUString( ( sal_Char* )pChar , length , RTL_TEXTENCODING_UTF8 ) ;
    }
    else
    {
        return rtl::OUString() ;
    }
}

/**
 * The input parameter is NULL terminated
 */
rtl::OUString xmlstr_to_ous( const xmlChar* pStr )
{
    if( pStr != NULL )
    {
        return xmlchar_to_ous( pStr , xmlStrlen( pStr ) ) ;
    }
    else
    {
        return rtl::OUString() ;
    }
}

/**
 * The return value and the referenced value must be NULL terminated.
 * The application has the responsibilty to deallocte the return value.
 */
const xmlChar** attrlist_to_nxmlstr( const cssu::Sequence< cssxcsax::XMLAttribute >& aAttributes )
{
    xmlChar* attname = NULL ;
    xmlChar* attvalue = NULL ;
    const xmlChar** attrs = NULL ;
    rtl::OUString oustr ;

    sal_Int32 nLength = aAttributes.getLength();;

    if( nLength != 0 )
    {
        attrs = ( const xmlChar** )xmlMalloc( ( nLength * 2 + 2 ) * sizeof( xmlChar* ) ) ;
    }
    else
    {
        return NULL ;
    }

    for( int i = 0 , j = 0 ; j < nLength ; ++j )
    {
        attname = ous_to_xmlstr( aAttributes[j].sName ) ;
        attvalue = ous_to_xmlstr( aAttributes[j].sValue ) ;

        if( attname != NULL && attvalue != NULL )
        {
            attrs[i++] = attname ;
            attrs[i++] = attvalue ;
            attrs[i] = NULL ;
            attrs[i+1] = NULL ;
        }
        else
        {
            if( attname != NULL )
                xmlFree( attname ) ;
            if( attvalue != NULL )
                xmlFree( attvalue ) ;
        }
    }

    return attrs ;
}

/**
 * Constructor
 *
 * In this constructor, a libxml sax parser context is initialized. a libxml
 * default sax handler is initialized with the context.
 */
SAXHelper::SAXHelper( )
    : m_pParserCtxt( NULL ),
      m_pSaxHandler( NULL )
{
    xmlInitParser() ;
    LIBXML_TEST_VERSION ;

    /*
     * compile error:
     * xmlLoadExtDtdDefaultValue = XML_DETECT_IDS | XML_COMPLETE_ATTRS ;
     */
    xmlSubstituteEntitiesDefault( 1 ) ;

#ifndef XMLSEC_NO_XSLT
    xmlIndentTreeOutput = 1 ;
#endif /* XMLSEC_NO_XSLT */

    m_pParserCtxt = xmlNewParserCtxt() ;

    /*
     * i41748
     *
     * mmi : re-initialize the SAX handler to version 1
     */

    xmlSAXVersion(m_pParserCtxt->sax, 1);

    /* end */

    if( m_pParserCtxt->inputTab[0] != NULL )
    {
        m_pParserCtxt->inputTab[0] = NULL ;
    }

    if( m_pParserCtxt == NULL )
    {
#ifndef XMLSEC_NO_XSLT
        xsltCleanupGlobals() ;
#endif
//      see issue i74334, we cannot call xmlCleanupParser when libxml is still used
//      in other parts of the office.
//      xmlCleanupParser() ;
        throw cssu::RuntimeException() ;
    }
    else if( m_pParserCtxt->sax == NULL )
    {
        xmlFreeParserCtxt( m_pParserCtxt ) ;

#ifndef XMLSEC_NO_XSLT
        xsltCleanupGlobals() ;
#endif
//      see issue i74334, we cannot call xmlCleanupParser when libxml is still used
//      in other parts of the office.
//      xmlCleanupParser() ;
        m_pParserCtxt = NULL ;
        throw cssu::RuntimeException() ;
    }
    else
    {
        m_pSaxHandler = m_pParserCtxt->sax ;

        //Adjust the context
        m_pParserCtxt->recovery = 1 ;
    }
}

/**
 * Destructor
 *
 * In this destructor, a libxml sax parser context is desturcted. The XML tree
 * in the context is not deallocated because the tree is bind with a document
 * model by the setTargetDocument method, which delegate the target document to
 * destruct the xml tree.
 */
SAXHelper::~SAXHelper() {
    if( m_pParserCtxt != NULL )
    {
        /*
         * In the situation that no object refer the Document, this destructor
         * must deallocate the Document memory
         */
        if( m_pSaxHandler == m_pParserCtxt->sax )
        {
            m_pSaxHandler = NULL ;
        }

        xmlFreeParserCtxt( m_pParserCtxt ) ;
        m_pParserCtxt = NULL ;
    }

    if( m_pSaxHandler != NULL )
    {
        xmlFree( m_pSaxHandler ) ;
        m_pSaxHandler = NULL ;
    }
//      see issue i74334, we cannot call xmlCleanupParser when libxml is still used
//      in other parts of the office.
//  xmlCleanupParser() ;
}

xmlNodePtr SAXHelper::getCurrentNode()
{
    return m_pParserCtxt->node;
}

void SAXHelper::setCurrentNode(const xmlNodePtr pNode)
{
    /*
     * This is really a black trick.
     * When the current node is replaced, the nodeTab
     * stack's top has to been replaced with the same
     * node, in order to make compatibility.
     */
    m_pParserCtxt->nodeTab[m_pParserCtxt->nodeNr - 1]
        = m_pParserCtxt->node
            = pNode;
}

xmlDocPtr SAXHelper::getDocument()
{
    return m_pParserCtxt->myDoc;
}

/**
 * XDocumentHandler -- start an xml document
 */
void SAXHelper::startDocument( void )
    throw( cssxs::SAXException , cssu::RuntimeException )
{
    /*
     * Adjust inputTab
     */
    xmlParserInputPtr pInput = xmlNewInputStream( m_pParserCtxt ) ;

    if( m_pParserCtxt->inputTab != NULL && m_pParserCtxt->inputMax != 0 )
    {
        m_pParserCtxt->inputTab[0] = pInput ;
        m_pParserCtxt->input = pInput ;
    }

    m_pSaxHandler->startDocument( m_pParserCtxt ) ;

    if( m_pParserCtxt == NULL || m_pParserCtxt->myDoc == NULL )
    {
        throw cssu::RuntimeException() ;
    }
}

/**
 * XDocumentHandler -- end an xml document
 */
void SAXHelper::endDocument( void )
    throw( cssxs::SAXException , cssu::RuntimeException )
{
    m_pSaxHandler->endDocument( m_pParserCtxt ) ;
}

/**
 * XDocumentHandler -- start an xml element
 */
void SAXHelper::startElement(
    const rtl::OUString& aName,
    const cssu::Sequence< cssxcsax::XMLAttribute >& aAttributes )
    throw( cssxs::SAXException , cssu::RuntimeException )
{
    const xmlChar* fullName = NULL ;
    const xmlChar** attrs = NULL ;

    fullName = ous_to_xmlstr( aName ) ;
    attrs = attrlist_to_nxmlstr( aAttributes ) ;

    if( fullName != NULL || attrs != NULL )
    {
        m_pSaxHandler->startElement( m_pParserCtxt , fullName , attrs ) ;
    }

    if( fullName != NULL )
    {
        xmlFree( ( xmlChar* )fullName ) ;
        fullName = NULL ;
    }

    if( attrs != NULL )
    {
        for( int i = 0 ; attrs[i] != NULL ; ++i )
        {
            xmlFree( ( xmlChar* )attrs[i] ) ;
            attrs[i] = NULL ;
        }

        xmlFree( ( void* ) attrs ) ;
        attrs = NULL ;
    }
}

/**
 * XDocumentHandler -- end an xml element
 */
void SAXHelper::endElement( const rtl::OUString& aName )
    throw( cssxs::SAXException , cssu::RuntimeException )
{
    xmlChar* fullname = NULL ;

    fullname = ous_to_xmlstr( aName ) ;
    m_pSaxHandler->endElement( m_pParserCtxt , fullname ) ;

    if( fullname != NULL )
    {
        xmlFree( ( xmlChar* )fullname ) ;
        fullname = NULL ;
    }
}

/**
 * XDocumentHandler -- an xml element or cdata characters
 */
void SAXHelper::characters( const rtl::OUString& aChars )
    throw( cssxs::SAXException , cssu::RuntimeException )
{
    const xmlChar* chars = NULL ;
    int length = 0 ;

    chars = ous_to_nxmlstr( aChars, length ) ;
    m_pSaxHandler->characters( m_pParserCtxt , chars , length ) ;

    if( chars != NULL )
    {
        xmlFree( ( xmlChar* )chars ) ;
    }
}

/**
 * XDocumentHandler -- ignorable xml white space
 */
void SAXHelper::ignorableWhitespace( const rtl::OUString& aWhitespaces )
    throw( cssxs::SAXException , cssu::RuntimeException )
{
    const xmlChar* chars = NULL ;
    int length = 0 ;

    chars = ous_to_nxmlstr( aWhitespaces, length ) ;
    m_pSaxHandler->ignorableWhitespace( m_pParserCtxt , chars , length ) ;

    if( chars != NULL )
    {
        xmlFree( ( xmlChar* )chars ) ;
    }
}

/**
 * XDocumentHandler -- preaorocessing instruction
 */
void SAXHelper::processingInstruction(
    const rtl::OUString& aTarget,
    const rtl::OUString& aData )
    throw( cssxs::SAXException , cssu::RuntimeException )
{
    xmlChar* target = NULL ;
    xmlChar* data = NULL ;

    target = ous_to_xmlstr( aTarget ) ;
    data = ous_to_xmlstr( aData ) ;

    m_pSaxHandler->processingInstruction( m_pParserCtxt , target , data ) ;

    if( target != NULL )
    {
        xmlFree( ( xmlChar* )target ) ;
        target = NULL ;
    }

    if( data != NULL )
    {
        xmlFree( ( xmlChar* )data ) ;
        data = NULL ;
    }
}

/**
 * XDocumentHandler -- set document locator
 * In this case, locator is useless.
 */
void SAXHelper::setDocumentLocator(
    const cssu::Reference< cssxs::XLocator > & xLocator )
    throw( cssxs::SAXException , cssu::RuntimeException )
{
    //--Pseudo code if necessary
    //--m_pSaxLocator is a member defined as xmlSAXHabdlerPtr
    //--m_pSaxLocatorHdl is a member defined as Sax_Locator

    //if( m_pSaxLocator != NULL ) {
    //  //Deallocate the memory
    //}
    //if( m_pSaxLocatorHdl != NULL ) {
    //  //Deallocate the memory
    //}

    //m_pSaxLocatorHdl = new Sax_Locator( xLocator ) ;
    //m_pSaxLocator = { m_pSaxLocatorHdl->getPublicId , m_pSaxLocatorHdl->getSystemId , m_pSaxLocatorHdl->getLineNumber , m_pSaxLocatorHdl->getColumnNumber } ;

    //m_pSaxHandler->setDocumentLocator( m_pParserCtxt , m_pSaxLocator ) ;
}

<commit_msg>INTEGRATION: CWS jl51 (1.4.30); FILE MERGED 2007/04/02 14:04:00 jl 1.4.30.2: RESYNC: (1.4-1.5); FILE MERGED 2007/02/05 13:54:21 jl 1.4.30.1: #i69228 warning free code<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: saxhelper.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: ihi $ $Date: 2007-04-17 10:22:56 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmlsecurity.hxx"

#include <rtl/ustring.hxx>

#include "saxhelper.hxx"
#include "libxml/parserInternals.h"

#ifndef XMLSEC_NO_XSLT
#include "libxslt/xslt.h"
#endif

namespace cssu = com::sun::star::uno;
namespace cssxs = com::sun::star::xml::sax;
namespace cssxcsax = com::sun::star::xml::csax;

/**
 * The return value is NULL terminated. The application has the responsibilty to
 * deallocte the return value.
 */
xmlChar* ous_to_xmlstr( const rtl::OUString& oustr )
{
    rtl::OString ostr = rtl::OUStringToOString( oustr , RTL_TEXTENCODING_UTF8 ) ;
    return xmlStrndup( ( xmlChar* )ostr.getStr(), ( int )ostr.getLength() ) ;
}

/**
 * The return value is NULL terminated. The application has the responsibilty to
 * deallocte the return value.
 */
xmlChar* ous_to_nxmlstr( const rtl::OUString& oustr, int& length )
{
    rtl::OString ostr = rtl::OUStringToOString( oustr , RTL_TEXTENCODING_UTF8 ) ;
    length = ostr.getLength();

    return xmlStrndup( ( xmlChar* )ostr.getStr(), length ) ;
}

/**
 * The input parameter isn't necessaryly NULL terminated.
 */
rtl::OUString xmlchar_to_ous( const xmlChar* pChar, int length )
{
    if( pChar != NULL )
    {
        return rtl::OUString( ( sal_Char* )pChar , length , RTL_TEXTENCODING_UTF8 ) ;
    }
    else
    {
        return rtl::OUString() ;
    }
}

/**
 * The input parameter is NULL terminated
 */
rtl::OUString xmlstr_to_ous( const xmlChar* pStr )
{
    if( pStr != NULL )
    {
        return xmlchar_to_ous( pStr , xmlStrlen( pStr ) ) ;
    }
    else
    {
        return rtl::OUString() ;
    }
}

/**
 * The return value and the referenced value must be NULL terminated.
 * The application has the responsibilty to deallocte the return value.
 */
const xmlChar** attrlist_to_nxmlstr( const cssu::Sequence< cssxcsax::XMLAttribute >& aAttributes )
{
    xmlChar* attname = NULL ;
    xmlChar* attvalue = NULL ;
    const xmlChar** attrs = NULL ;
    rtl::OUString oustr ;

    sal_Int32 nLength = aAttributes.getLength();;

    if( nLength != 0 )
    {
        attrs = ( const xmlChar** )xmlMalloc( ( nLength * 2 + 2 ) * sizeof( xmlChar* ) ) ;
    }
    else
    {
        return NULL ;
    }

    for( int i = 0 , j = 0 ; j < nLength ; ++j )
    {
        attname = ous_to_xmlstr( aAttributes[j].sName ) ;
        attvalue = ous_to_xmlstr( aAttributes[j].sValue ) ;

        if( attname != NULL && attvalue != NULL )
        {
            attrs[i++] = attname ;
            attrs[i++] = attvalue ;
            attrs[i] = NULL ;
            attrs[i+1] = NULL ;
        }
        else
        {
            if( attname != NULL )
                xmlFree( attname ) ;
            if( attvalue != NULL )
                xmlFree( attvalue ) ;
        }
    }

    return attrs ;
}

/**
 * Constructor
 *
 * In this constructor, a libxml sax parser context is initialized. a libxml
 * default sax handler is initialized with the context.
 */
SAXHelper::SAXHelper( )
    : m_pParserCtxt( NULL ),
      m_pSaxHandler( NULL )
{
    xmlInitParser() ;
    LIBXML_TEST_VERSION ;

    /*
     * compile error:
     * xmlLoadExtDtdDefaultValue = XML_DETECT_IDS | XML_COMPLETE_ATTRS ;
     */
    xmlSubstituteEntitiesDefault( 1 ) ;

#ifndef XMLSEC_NO_XSLT
    xmlIndentTreeOutput = 1 ;
#endif /* XMLSEC_NO_XSLT */

    m_pParserCtxt = xmlNewParserCtxt() ;

    /*
     * i41748
     *
     * mmi : re-initialize the SAX handler to version 1
     */

    xmlSAXVersion(m_pParserCtxt->sax, 1);

    /* end */

    if( m_pParserCtxt->inputTab[0] != NULL )
    {
        m_pParserCtxt->inputTab[0] = NULL ;
    }

    if( m_pParserCtxt == NULL )
    {
#ifndef XMLSEC_NO_XSLT
        xsltCleanupGlobals() ;
#endif
//      see issue i74334, we cannot call xmlCleanupParser when libxml is still used
//      in other parts of the office.
//      xmlCleanupParser() ;
        throw cssu::RuntimeException() ;
    }
    else if( m_pParserCtxt->sax == NULL )
    {
        xmlFreeParserCtxt( m_pParserCtxt ) ;

#ifndef XMLSEC_NO_XSLT
        xsltCleanupGlobals() ;
#endif
//      see issue i74334, we cannot call xmlCleanupParser when libxml is still used
//      in other parts of the office.
//      xmlCleanupParser() ;
        m_pParserCtxt = NULL ;
        throw cssu::RuntimeException() ;
    }
    else
    {
        m_pSaxHandler = m_pParserCtxt->sax ;

        //Adjust the context
        m_pParserCtxt->recovery = 1 ;
    }
}

/**
 * Destructor
 *
 * In this destructor, a libxml sax parser context is desturcted. The XML tree
 * in the context is not deallocated because the tree is bind with a document
 * model by the setTargetDocument method, which delegate the target document to
 * destruct the xml tree.
 */
SAXHelper::~SAXHelper() {
    if( m_pParserCtxt != NULL )
    {
        /*
         * In the situation that no object refer the Document, this destructor
         * must deallocate the Document memory
         */
        if( m_pSaxHandler == m_pParserCtxt->sax )
        {
            m_pSaxHandler = NULL ;
        }

        xmlFreeParserCtxt( m_pParserCtxt ) ;
        m_pParserCtxt = NULL ;
    }

    if( m_pSaxHandler != NULL )
    {
        xmlFree( m_pSaxHandler ) ;
        m_pSaxHandler = NULL ;
    }
//      see issue i74334, we cannot call xmlCleanupParser when libxml is still used
//      in other parts of the office.
//  xmlCleanupParser() ;
}

xmlNodePtr SAXHelper::getCurrentNode()
{
    return m_pParserCtxt->node;
}

void SAXHelper::setCurrentNode(const xmlNodePtr pNode)
{
    /*
     * This is really a black trick.
     * When the current node is replaced, the nodeTab
     * stack's top has to been replaced with the same
     * node, in order to make compatibility.
     */
    m_pParserCtxt->nodeTab[m_pParserCtxt->nodeNr - 1]
        = m_pParserCtxt->node
            = pNode;
}

xmlDocPtr SAXHelper::getDocument()
{
    return m_pParserCtxt->myDoc;
}

/**
 * XDocumentHandler -- start an xml document
 */
void SAXHelper::startDocument( void )
    throw( cssxs::SAXException , cssu::RuntimeException )
{
    /*
     * Adjust inputTab
     */
    xmlParserInputPtr pInput = xmlNewInputStream( m_pParserCtxt ) ;

    if( m_pParserCtxt->inputTab != NULL && m_pParserCtxt->inputMax != 0 )
    {
        m_pParserCtxt->inputTab[0] = pInput ;
        m_pParserCtxt->input = pInput ;
    }

    m_pSaxHandler->startDocument( m_pParserCtxt ) ;

    if( m_pParserCtxt == NULL || m_pParserCtxt->myDoc == NULL )
    {
        throw cssu::RuntimeException() ;
    }
}

/**
 * XDocumentHandler -- end an xml document
 */
void SAXHelper::endDocument( void )
    throw( cssxs::SAXException , cssu::RuntimeException )
{
    m_pSaxHandler->endDocument( m_pParserCtxt ) ;
}

/**
 * XDocumentHandler -- start an xml element
 */
void SAXHelper::startElement(
    const rtl::OUString& aName,
    const cssu::Sequence< cssxcsax::XMLAttribute >& aAttributes )
    throw( cssxs::SAXException , cssu::RuntimeException )
{
    const xmlChar* fullName = NULL ;
    const xmlChar** attrs = NULL ;

    fullName = ous_to_xmlstr( aName ) ;
    attrs = attrlist_to_nxmlstr( aAttributes ) ;

    if( fullName != NULL || attrs != NULL )
    {
        m_pSaxHandler->startElement( m_pParserCtxt , fullName , attrs ) ;
    }

    if( fullName != NULL )
    {
        xmlFree( ( xmlChar* )fullName ) ;
        fullName = NULL ;
    }

    if( attrs != NULL )
    {
        for( int i = 0 ; attrs[i] != NULL ; ++i )
        {
            xmlFree( ( xmlChar* )attrs[i] ) ;
            attrs[i] = NULL ;
        }

        xmlFree( ( void* ) attrs ) ;
        attrs = NULL ;
    }
}

/**
 * XDocumentHandler -- end an xml element
 */
void SAXHelper::endElement( const rtl::OUString& aName )
    throw( cssxs::SAXException , cssu::RuntimeException )
{
    xmlChar* fullname = NULL ;

    fullname = ous_to_xmlstr( aName ) ;
    m_pSaxHandler->endElement( m_pParserCtxt , fullname ) ;

    if( fullname != NULL )
    {
        xmlFree( ( xmlChar* )fullname ) ;
        fullname = NULL ;
    }
}

/**
 * XDocumentHandler -- an xml element or cdata characters
 */
void SAXHelper::characters( const rtl::OUString& aChars )
    throw( cssxs::SAXException , cssu::RuntimeException )
{
    const xmlChar* chars = NULL ;
    int length = 0 ;

    chars = ous_to_nxmlstr( aChars, length ) ;
    m_pSaxHandler->characters( m_pParserCtxt , chars , length ) ;

    if( chars != NULL )
    {
        xmlFree( ( xmlChar* )chars ) ;
    }
}

/**
 * XDocumentHandler -- ignorable xml white space
 */
void SAXHelper::ignorableWhitespace( const rtl::OUString& aWhitespaces )
    throw( cssxs::SAXException , cssu::RuntimeException )
{
    const xmlChar* chars = NULL ;
    int length = 0 ;

    chars = ous_to_nxmlstr( aWhitespaces, length ) ;
    m_pSaxHandler->ignorableWhitespace( m_pParserCtxt , chars , length ) ;

    if( chars != NULL )
    {
        xmlFree( ( xmlChar* )chars ) ;
    }
}

/**
 * XDocumentHandler -- preaorocessing instruction
 */
void SAXHelper::processingInstruction(
    const rtl::OUString& aTarget,
    const rtl::OUString& aData )
    throw( cssxs::SAXException , cssu::RuntimeException )
{
    xmlChar* target = NULL ;
    xmlChar* data = NULL ;

    target = ous_to_xmlstr( aTarget ) ;
    data = ous_to_xmlstr( aData ) ;

    m_pSaxHandler->processingInstruction( m_pParserCtxt , target , data ) ;

    if( target != NULL )
    {
        xmlFree( ( xmlChar* )target ) ;
        target = NULL ;
    }

    if( data != NULL )
    {
        xmlFree( ( xmlChar* )data ) ;
        data = NULL ;
    }
}

/**
 * XDocumentHandler -- set document locator
 * In this case, locator is useless.
 */
void SAXHelper::setDocumentLocator(
    const cssu::Reference< cssxs::XLocator > &)
    throw( cssxs::SAXException , cssu::RuntimeException )
{
    //--Pseudo code if necessary
    //--m_pSaxLocator is a member defined as xmlSAXHabdlerPtr
    //--m_pSaxLocatorHdl is a member defined as Sax_Locator

    //if( m_pSaxLocator != NULL ) {
    //  //Deallocate the memory
    //}
    //if( m_pSaxLocatorHdl != NULL ) {
    //  //Deallocate the memory
    //}

    //m_pSaxLocatorHdl = new Sax_Locator( xLocator ) ;
    //m_pSaxLocator = { m_pSaxLocatorHdl->getPublicId , m_pSaxLocatorHdl->getSystemId , m_pSaxLocatorHdl->getLineNumber , m_pSaxLocatorHdl->getColumnNumber } ;

    //m_pSaxHandler->setDocumentLocator( m_pParserCtxt , m_pSaxLocator ) ;
}

<|endoftext|>


<commit_before>#include <util/ScanQuery.hpp>

#include <util/Record.hpp>

#include <gtest/gtest.h>

#include <cstdint>
#include <cstring>
#include <memory>
#include <vector>

using namespace tell::store;

namespace {

int64_t gTupleLargenumber = 0x7FFFFFFF00000001;

int32_t gTuple1Number = 12;
crossbow::string gTuple1Text = crossbow::string("Bacon ipsum dolor amet");

int32_t gTuple2Number = 13;
crossbow::string gTuple2Text = crossbow::string("t-bone chicken prosciutto");

/**
 * @brief Test fixture for testing the ScanQuery class
 *
 * Creates a schema with 3 fields and creates two sample tuples.
 */
class ScanQueryTest : public ::testing::Test {
protected:
    ScanQueryTest() {
        mSchema.addField(FieldType::BIGINT, "largenumber", true);
        mSchema.addField(FieldType::INT, "number", true);
        mSchema.addField(FieldType::TEXT, "text", true);
        Record record(mSchema);

        GenericTuple insertTuple1({
                std::make_pair<crossbow::string, boost::any>("largenumber", gTupleLargenumber),
                std::make_pair<crossbow::string, boost::any>("number", gTuple1Number),
                std::make_pair<crossbow::string, boost::any>("text", gTuple1Text),
        });
        mTuple1.reset(record.create(insertTuple1, mTuple1Size));

        GenericTuple insertTuple2({
                std::make_pair<crossbow::string, boost::any>("largenumber", gTupleLargenumber),
                std::make_pair<crossbow::string, boost::any>("number", gTuple2Number),
                std::make_pair<crossbow::string, boost::any>("text", gTuple2Text),
        });
        mTuple2.reset(record.create(insertTuple2, mTuple2Size));
    }

    bool checkQuery(size_t qsize, const char* qbuffer, const char* tuple, size_t bitmapSize, const Record& record);

    ScanQuery mQuery;
    std::vector<bool> mQueryBitMap;

    Schema mSchema;

    uint64_t mTuple1Size;
    std::unique_ptr<char[]> mTuple1;

    uint64_t mTuple2Size;
    std::unique_ptr<char[]> mTuple2;
};

bool ScanQueryTest::checkQuery(size_t qsize, const char* qbuffer, const char* tuple, size_t bitmapSize,
        const Record& record) {
    mQueryBitMap.clear();
    mQuery.query = qbuffer;
    auto q = mQuery.check(tuple, mQueryBitMap, record);
    EXPECT_EQ(qbuffer + qsize, q) << "Returned pointer does not point at end of qbuffer";
    EXPECT_EQ(bitmapSize, mQueryBitMap.size()) << "Query bitmap does not contain the expected number of elements";

    for (auto res : mQueryBitMap) {
        if (!res) {
            return false;
        }
    }
    return true;
}

/**
 * @class ScanQuery
 * @test Check if the check succeeds for a query with no predicates
 *
 * The query is equal to "SELECT *".
 */
TEST_F(ScanQueryTest, noPredicates) {
    Record record(mSchema);

    size_t qsize = 8;
    std::unique_ptr<char[]> qbuffer(new char[qsize]);
    memset(qbuffer.get(), 0, qsize);

    EXPECT_TRUE(checkQuery(qsize, qbuffer.get(), mTuple1.get(), 0, record));
    EXPECT_TRUE(checkQuery(qsize, qbuffer.get(), mTuple2.get(), 0, record));
}

/**
 * @class ScanQuery
 * @test Check if the check succeeds for a simple EQUAL predicate
 *
 * The query is equal to "SELECT * WHERE number == 12".
 */
TEST_F(ScanQueryTest, singlePredicate) {
    Record record(mSchema);
    Record::id_t numberField;
    ASSERT_TRUE(record.idOf("number", numberField)) << "Field not found";

    size_t qsize = 24;
    std::unique_ptr<char[]> qbuffer(new char[qsize]);
    memset(qbuffer.get(), 0, qsize);
    *reinterpret_cast<uint64_t*>(qbuffer.get()) = 0x1u;
    *reinterpret_cast<uint16_t*>(qbuffer.get() + 8) = numberField;
    *reinterpret_cast<uint16_t*>(qbuffer.get() + 10) = 0x1u;
    *reinterpret_cast<uint8_t*>(qbuffer.get() + 16) = to_underlying(PredicateType::EQUAL);
    *reinterpret_cast<uint8_t*>(qbuffer.get() + 17) = 0x0u;
    *reinterpret_cast<int32_t*>(qbuffer.get() + 20) = gTuple1Number;

    EXPECT_TRUE(checkQuery(qsize, qbuffer.get(), mTuple1.get(), 1, record));
    EXPECT_FALSE(checkQuery(qsize, qbuffer.get(), mTuple2.get(), 1, record));
}

/**
 * @class ScanQuery
 * @test Check if the check succeeds for two simple EQUAL predicates linked by an AND.
 *
 * The query is equal to "SELECT * WHERE number = 12 AND largenumber = 0x7FFFFFFF00000001".
 */
TEST_F(ScanQueryTest, andPredicate) {
    Record record(mSchema);
    Record::id_t numberField;
    ASSERT_TRUE(record.idOf("number", numberField)) << "Field not found";
    Record::id_t largenumberField;
    ASSERT_TRUE(record.idOf("largenumber", largenumberField)) << "Field not found";

    size_t qsize = 48;
    std::unique_ptr<char[]> qbuffer(new char[qsize]);
    memset(qbuffer.get(), 0, qsize);
    *reinterpret_cast<uint64_t*>(qbuffer.get()) = 0x2u;
    *reinterpret_cast<uint16_t*>(qbuffer.get() + 8) = numberField;
    *reinterpret_cast<uint16_t*>(qbuffer.get() + 10) = 0x1u;
    *reinterpret_cast<uint8_t*>(qbuffer.get() + 16) = to_underlying(PredicateType::EQUAL);
    *reinterpret_cast<uint8_t*>(qbuffer.get() + 17) = 0x0u;
    *reinterpret_cast<int32_t*>(qbuffer.get() + 20) = gTuple1Number;
    *reinterpret_cast<uint16_t*>(qbuffer.get() + 24) = largenumberField;
    *reinterpret_cast<uint16_t*>(qbuffer.get() + 26) = 0x1u;
    *reinterpret_cast<uint8_t*>(qbuffer.get() + 32) = to_underlying(PredicateType::EQUAL);
    *reinterpret_cast<uint8_t*>(qbuffer.get() + 33) = 0x1u;
    *reinterpret_cast<int64_t*>(qbuffer.get() + 40) = gTupleLargenumber;

    EXPECT_TRUE(checkQuery(qsize, qbuffer.get(), mTuple1.get(), 2, record));
    EXPECT_FALSE(checkQuery(qsize, qbuffer.get(), mTuple2.get(), 2, record));
}

/**
 * @class ScanQuery
 * @test Check if the check succeeds for two simple EQUAL predicates linked by an OR.
 *
 * The query is equal to "SELECT * WHERE number = 12 OR text = 't-bone chicken prosciutto'".
 */
TEST_F(ScanQueryTest, orPredicate) {
    Record record(mSchema);
    Record::id_t numberField;
    ASSERT_TRUE(record.idOf("number", numberField)) << "Field not found";
    Record::id_t textField;
    ASSERT_TRUE(record.idOf("text", textField)) << "Field not found";

    size_t qsize = 44 + gTuple2Text.length();
    qsize += ((qsize % 8 != 0) ? (8 - (qsize % 8)) : 0);
    std::unique_ptr<char[]> qbuffer(new char[qsize]);
    memset(qbuffer.get(), 0, qsize);
    *reinterpret_cast<uint64_t*>(qbuffer.get()) = 0x2u;
    *reinterpret_cast<uint16_t*>(qbuffer.get() + 8) = numberField;
    *reinterpret_cast<uint16_t*>(qbuffer.get() + 10) = 0x1u;
    *reinterpret_cast<uint8_t*>(qbuffer.get() + 16) = to_underlying(PredicateType::EQUAL);
    *reinterpret_cast<uint8_t*>(qbuffer.get() + 17) = 0x0u;
    *reinterpret_cast<int32_t*>(qbuffer.get() + 20) = gTuple1Number;
    *reinterpret_cast<uint16_t*>(qbuffer.get() + 24) = textField;
    *reinterpret_cast<uint16_t*>(qbuffer.get() + 26) = 0x1u;
    *reinterpret_cast<uint8_t*>(qbuffer.get() + 32) = to_underlying(PredicateType::EQUAL);
    *reinterpret_cast<uint8_t*>(qbuffer.get() + 33) = 0x0u;
    *reinterpret_cast<uint32_t*>(qbuffer.get() + 40) = gTuple2Text.length();
    memcpy(qbuffer.get() + 44, gTuple2Text.data(), gTuple2Text.length());

    EXPECT_TRUE(checkQuery(qsize, qbuffer.get(), mTuple1.get(), 1, record));
    EXPECT_TRUE(checkQuery(qsize, qbuffer.get(), mTuple2.get(), 1, record));
}

} // anonymous namespace
<commit_msg>Add one more test case for ScanQuery<commit_after>#include <util/ScanQuery.hpp>

#include <util/Record.hpp>

#include <gtest/gtest.h>

#include <cstdint>
#include <cstring>
#include <memory>
#include <vector>

using namespace tell::store;

namespace {

int64_t gTupleLargenumber = 0x7FFFFFFF00000001;

int32_t gTuple1Number = 12;
crossbow::string gTuple1Text = crossbow::string("Bacon ipsum dolor amet");

int32_t gTuple2Number = 13;
crossbow::string gTuple2Text = crossbow::string("t-bone chicken prosciutto");

/**
 * @brief Test fixture for testing the ScanQuery class
 *
 * Creates a schema with 3 fields and creates two sample tuples.
 */
class ScanQueryTest : public ::testing::Test {
protected:
    ScanQueryTest() {
        mSchema.addField(FieldType::BIGINT, "largenumber", true);
        mSchema.addField(FieldType::INT, "number", true);
        mSchema.addField(FieldType::TEXT, "text", true);
        Record record(mSchema);

        GenericTuple insertTuple1({
                std::make_pair<crossbow::string, boost::any>("largenumber", gTupleLargenumber),
                std::make_pair<crossbow::string, boost::any>("number", gTuple1Number),
                std::make_pair<crossbow::string, boost::any>("text", gTuple1Text),
        });
        mTuple1.reset(record.create(insertTuple1, mTuple1Size));

        GenericTuple insertTuple2({
                std::make_pair<crossbow::string, boost::any>("largenumber", gTupleLargenumber),
                std::make_pair<crossbow::string, boost::any>("number", gTuple2Number),
                std::make_pair<crossbow::string, boost::any>("text", gTuple2Text),
        });
        mTuple2.reset(record.create(insertTuple2, mTuple2Size));
    }

    bool checkQuery(size_t qsize, const char* qbuffer, const char* tuple, size_t bitmapSize, const Record& record);

    ScanQuery mQuery;
    std::vector<bool> mQueryBitMap;

    Schema mSchema;

    uint64_t mTuple1Size;
    std::unique_ptr<char[]> mTuple1;

    uint64_t mTuple2Size;
    std::unique_ptr<char[]> mTuple2;
};

bool ScanQueryTest::checkQuery(size_t qsize, const char* qbuffer, const char* tuple, size_t bitmapSize,
        const Record& record) {
    mQueryBitMap.clear();
    mQuery.query = qbuffer;
    auto q = mQuery.check(tuple, mQueryBitMap, record);
    EXPECT_EQ(qbuffer + qsize, q) << "Returned pointer does not point at end of qbuffer";
    EXPECT_EQ(bitmapSize, mQueryBitMap.size()) << "Query bitmap does not contain the expected number of elements";

    for (auto res : mQueryBitMap) {
        if (!res) {
            return false;
        }
    }
    return true;
}

/**
 * @class ScanQuery
 * @test Check if the check succeeds for a query with no predicates
 *
 * The query is equal to "SELECT *".
 */
TEST_F(ScanQueryTest, noPredicates) {
    Record record(mSchema);

    size_t qsize = 8;
    std::unique_ptr<char[]> qbuffer(new char[qsize]);
    memset(qbuffer.get(), 0, qsize);

    EXPECT_TRUE(checkQuery(qsize, qbuffer.get(), mTuple1.get(), 0, record));
    EXPECT_TRUE(checkQuery(qsize, qbuffer.get(), mTuple2.get(), 0, record));
}

/**
 * @class ScanQuery
 * @test Check if the check succeeds for a simple EQUAL predicate
 *
 * The query is equal to "SELECT * WHERE number == 12".
 */
TEST_F(ScanQueryTest, singlePredicate) {
    Record record(mSchema);
    Record::id_t numberField;
    ASSERT_TRUE(record.idOf("number", numberField)) << "Field not found";

    size_t qsize = 24;
    std::unique_ptr<char[]> qbuffer(new char[qsize]);
    memset(qbuffer.get(), 0, qsize);
    *reinterpret_cast<uint64_t*>(qbuffer.get()) = 0x1u;
    *reinterpret_cast<uint16_t*>(qbuffer.get() + 8) = numberField;
    *reinterpret_cast<uint16_t*>(qbuffer.get() + 10) = 0x1u;
    *reinterpret_cast<uint8_t*>(qbuffer.get() + 16) = to_underlying(PredicateType::EQUAL);
    *reinterpret_cast<uint8_t*>(qbuffer.get() + 17) = 0x0u;
    *reinterpret_cast<int32_t*>(qbuffer.get() + 20) = gTuple1Number;

    EXPECT_TRUE(checkQuery(qsize, qbuffer.get(), mTuple1.get(), 1, record));
    EXPECT_FALSE(checkQuery(qsize, qbuffer.get(), mTuple2.get(), 1, record));
}

/**
 * @class ScanQuery
 * @test Check if the check succeeds for two simple EQUAL predicates linked by an AND.
 *
 * The query is equal to "SELECT * WHERE number = 12 AND largenumber = 0x7FFFFFFF00000001".
 */
TEST_F(ScanQueryTest, andPredicate) {
    Record record(mSchema);
    Record::id_t numberField;
    ASSERT_TRUE(record.idOf("number", numberField)) << "Field not found";
    Record::id_t largenumberField;
    ASSERT_TRUE(record.idOf("largenumber", largenumberField)) << "Field not found";

    size_t qsize = 48;
    std::unique_ptr<char[]> qbuffer(new char[qsize]);
    memset(qbuffer.get(), 0, qsize);
    *reinterpret_cast<uint64_t*>(qbuffer.get()) = 0x2u;
    *reinterpret_cast<uint16_t*>(qbuffer.get() + 8) = numberField;
    *reinterpret_cast<uint16_t*>(qbuffer.get() + 10) = 0x1u;
    *reinterpret_cast<uint8_t*>(qbuffer.get() + 16) = to_underlying(PredicateType::EQUAL);
    *reinterpret_cast<uint8_t*>(qbuffer.get() + 17) = 0x0u;
    *reinterpret_cast<int32_t*>(qbuffer.get() + 20) = gTuple1Number;
    *reinterpret_cast<uint16_t*>(qbuffer.get() + 24) = largenumberField;
    *reinterpret_cast<uint16_t*>(qbuffer.get() + 26) = 0x1u;
    *reinterpret_cast<uint8_t*>(qbuffer.get() + 32) = to_underlying(PredicateType::EQUAL);
    *reinterpret_cast<uint8_t*>(qbuffer.get() + 33) = 0x1u;
    *reinterpret_cast<int64_t*>(qbuffer.get() + 40) = gTupleLargenumber;

    EXPECT_TRUE(checkQuery(qsize, qbuffer.get(), mTuple1.get(), 2, record));
    EXPECT_FALSE(checkQuery(qsize, qbuffer.get(), mTuple2.get(), 2, record));
}

/**
 * @class ScanQuery
 * @test Check if the check succeeds for two simple EQUAL predicates linked by an OR.
 *
 * The query is equal to "SELECT * WHERE number = 12 OR text = 't-bone chicken prosciutto'".
 */
TEST_F(ScanQueryTest, orPredicate) {
    Record record(mSchema);
    Record::id_t numberField;
    ASSERT_TRUE(record.idOf("number", numberField)) << "Field not found";
    Record::id_t textField;
    ASSERT_TRUE(record.idOf("text", textField)) << "Field not found";

    size_t qsize = 44 + gTuple2Text.length();
    qsize += ((qsize % 8 != 0) ? (8 - (qsize % 8)) : 0);
    std::unique_ptr<char[]> qbuffer(new char[qsize]);
    memset(qbuffer.get(), 0, qsize);
    *reinterpret_cast<uint64_t*>(qbuffer.get()) = 0x2u;
    *reinterpret_cast<uint16_t*>(qbuffer.get() + 8) = numberField;
    *reinterpret_cast<uint16_t*>(qbuffer.get() + 10) = 0x1u;
    *reinterpret_cast<uint8_t*>(qbuffer.get() + 16) = to_underlying(PredicateType::EQUAL);
    *reinterpret_cast<uint8_t*>(qbuffer.get() + 17) = 0x0u;
    *reinterpret_cast<int32_t*>(qbuffer.get() + 20) = gTuple1Number;
    *reinterpret_cast<uint16_t*>(qbuffer.get() + 24) = textField;
    *reinterpret_cast<uint16_t*>(qbuffer.get() + 26) = 0x1u;
    *reinterpret_cast<uint8_t*>(qbuffer.get() + 32) = to_underlying(PredicateType::EQUAL);
    *reinterpret_cast<uint8_t*>(qbuffer.get() + 33) = 0x0u;
    *reinterpret_cast<uint32_t*>(qbuffer.get() + 40) = gTuple2Text.length();
    memcpy(qbuffer.get() + 44, gTuple2Text.data(), gTuple2Text.length());

    EXPECT_TRUE(checkQuery(qsize, qbuffer.get(), mTuple1.get(), 1, record));
    EXPECT_TRUE(checkQuery(qsize, qbuffer.get(), mTuple2.get(), 1, record));
}

/**
 * @class ScanQuery
 * @test Check if the check succeeds for two simple EQUAL predicates linked by an OR on the same column.
 *
 * The query is equal to "SELECT * WHERE number = 12 OR number = 13".
 */
TEST_F(ScanQueryTest, sameColumnPredicate) {
    Record record(mSchema);
    Record::id_t numberField;
    ASSERT_TRUE(record.idOf("number", numberField)) << "Field not found";

    size_t qsize = 32;
    std::unique_ptr<char[]> qbuffer(new char[qsize]);
    memset(qbuffer.get(), 0, qsize);
    *reinterpret_cast<uint64_t*>(qbuffer.get()) = 0x1u;
    *reinterpret_cast<uint16_t*>(qbuffer.get() + 8) = numberField;
    *reinterpret_cast<uint16_t*>(qbuffer.get() + 10) = 0x2u;
    *reinterpret_cast<uint8_t*>(qbuffer.get() + 16) = to_underlying(PredicateType::EQUAL);
    *reinterpret_cast<uint8_t*>(qbuffer.get() + 17) = 0x0u;
    *reinterpret_cast<int32_t*>(qbuffer.get() + 20) = gTuple1Number;
    *reinterpret_cast<uint8_t*>(qbuffer.get() + 24) = to_underlying(PredicateType::EQUAL);
    *reinterpret_cast<uint8_t*>(qbuffer.get() + 25) = 0x0u;
    *reinterpret_cast<uint8_t*>(qbuffer.get() + 28) = gTuple2Number;

    EXPECT_TRUE(checkQuery(qsize, qbuffer.get(), mTuple1.get(), 1, record));
    EXPECT_TRUE(checkQuery(qsize, qbuffer.get(), mTuple2.get(), 1, record));
}

} // anonymous namespace
<|endoftext|>


<commit_before>//-----------------------------------------------------------------------------
// Copyright(c) 2016, Jeff Hutchinson
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met :
//
// * Redistributions of source code must retain the above copyright notice, this
//   list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
//   this list of conditions and the following disclaimer in the documentation
//   and / or other materials provided with the distribution.
//
// * Neither the name of threadGL nor the names of its
//   contributors may be used to endorse or promote products derived from
//   this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//-----------------------------------------------------------------------------

#include <stdio.h>
#include "jbl/types.h"
#include "jbl/thread.h"
#include "jbl/mutex.h"
#include "jbl/conditionVariable.h"
#include "jbl/stack.h"

Mutex mutex;
S32 inc = 0;

Mutex pcMutex;
ConditionVariable cv;
Stack<S32> stack;
Mutex pcDoneMtx;
bool pcDone = false;

void incriment()
{
	LockGuard g(&mutex);
	++inc;
	printf("inc is now: %d\n", inc);
}

void myThreadFn(void *arg)
{
	S32 x = *(S32*)arg;
	for (S32 i = 0; i < x; ++i)
		incriment();
	Thread::sleep(1000);
}

void producer(void *)
{
	for (S32 i = 0; i < 20; ++i)
	{
		pcMutex.lock();
		stack.push(i);
		pcMutex.unlock();
		cv.signal();
		Thread::sleep(500);
	}
	pcDoneMtx.lock();
	pcDone = true;
	cv.signal();
	pcDoneMtx.unlock();
}

void consumer(void *)
{
	while (true)
	{
		pcMutex.lock();
		cv.wait(&pcMutex);

		pcDoneMtx.lock();
		if (pcDone)
		{
			pcDoneMtx.unlock();
			pcMutex.unlock();
			break;
		}
		pcDoneMtx.unlock();

		printf("%d\n", stack.getTop());
		stack.pop();
		pcMutex.unlock();
	}
}

S32 main(S32 argc, const char **argv)
{
	S32 x = 20;
	Thread t(myThreadFn, &x);
	Thread t2(myThreadFn, &x);
	t.join();
	t2.join();

	printf("Testing producer consumer condition variable.\n");
	Thread c(consumer, nullptr);
	Thread p(producer, nullptr);
	c.join();
	p.join();

#ifdef _WIN32
   system("pause");
#endif
	return 0;
}<commit_msg>preven spurious wakeup. Also, we only read pcDone in the consumer, so no need to have a lock around it.<commit_after>//-----------------------------------------------------------------------------
// Copyright(c) 2016, Jeff Hutchinson
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met :
//
// * Redistributions of source code must retain the above copyright notice, this
//   list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
//   this list of conditions and the following disclaimer in the documentation
//   and / or other materials provided with the distribution.
//
// * Neither the name of threadGL nor the names of its
//   contributors may be used to endorse or promote products derived from
//   this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//-----------------------------------------------------------------------------

#include <stdio.h>
#include "jbl/types.h"
#include "jbl/thread.h"
#include "jbl/mutex.h"
#include "jbl/conditionVariable.h"
#include "jbl/stack.h"

Mutex mutex;
S32 inc = 0;

Mutex pcMutex;
ConditionVariable cv;
Stack<S32> stack;
volatile bool pcDone = false;

void incriment()
{
	LockGuard g(&mutex);
	++inc;
	printf("inc is now: %d\n", inc);
}

void myThreadFn(void *arg)
{
	S32 x = *(S32*)arg;
	for (S32 i = 0; i < x; ++i)
		incriment();
	Thread::sleep(1000);
}

void producer(void *)
{
	for (S32 i = 0; i < 20; ++i)
	{
		pcMutex.lock();
		stack.push(i);
		pcMutex.unlock();
		cv.signal();
		Thread::sleep(750);
	}
	pcDone = true;
	cv.signal();
}

void consumer(void *)
{
	while (true)
	{
		pcMutex.lock();
		while (!pcDone && stack.isEmpty())
			cv.wait(&pcMutex);

		if (pcDone)
		{
			pcMutex.unlock();
			break;
		}

		printf("%d\n", stack.getTop());
		stack.pop();
		pcMutex.unlock();
	}
}

S32 main(S32 argc, const char **argv)
{
	S32 x = 20;
	Thread t(myThreadFn, &x);
	Thread t2(myThreadFn, &x);
	t.join();
	t2.join();

	printf("Testing producer consumer condition variable.\n");
	Thread c(consumer, nullptr);
	Thread p(producer, nullptr);
	c.join();
	p.join();

#ifdef _WIN32
   system("pause");
#endif
	return 0;
}<|endoftext|>


<commit_before>/*
 * MIT License
 *
 * Copyright (c) 2016-2019 xiongziliang <771730766@qq.com>
 *
 * This file is part of ZLMediaKit(https://github.com/xiongziliang/ZLMediaKit).
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#include <signal.h>
#include <string>
#include <iostream>
#include "Util/MD5.h"
#include "Util/logger.h"
#include "Http/WebSocketClient.h"
using namespace std;
using namespace toolkit;
using namespace mediakit;

class EchoTcpClient : public TcpClient {
public:
    EchoTcpClient(const EventPoller::Ptr &poller = nullptr){
        InfoL;
    }
    ~EchoTcpClient() override {
        InfoL;
    }
protected:
    void onRecv(const Buffer::Ptr &pBuf) override {
        DebugL << pBuf->toString();
    }
    //被动断开连接回调
    void onErr(const SockException &ex) override {
        WarnL << ex.what();
    }
    //tcp连接成功后每2秒触发一次该事件
    void onManager() override {
        send("echo test!");
        DebugL << "send echo test";
    }
    //连接服务器结果回调
    void onConnect(const SockException &ex) override{
        DebugL << ex.what();
    }

    //数据全部发送完毕后回调
    void onFlush() override{
        DebugL;
    }
};

int main(int argc, char *argv[]) {
    //设置退出信号处理函数
    static semaphore sem;
    signal(SIGINT, [](int) { sem.post(); });// 设置退出信号

    //设置日志
    Logger::Instance().add(std::make_shared<ConsoleChannel>());
    Logger::Instance().setWriter(std::make_shared<AsyncLogWriter>());

    WebSocketClient<EchoTcpClient>::Ptr client = std::make_shared<WebSocketClient<EchoTcpClient> >();
    client->startConnect("127.0.0.1",80);

    sem.wait();
    return 0;
}

<commit_msg>替换websocket测试服务器<commit_after>/*
 * MIT License
 *
 * Copyright (c) 2016-2019 xiongziliang <771730766@qq.com>
 *
 * This file is part of ZLMediaKit(https://github.com/xiongziliang/ZLMediaKit).
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#include <signal.h>
#include <string>
#include <iostream>
#include "Util/MD5.h"
#include "Util/logger.h"
#include "Http/WebSocketClient.h"
using namespace std;
using namespace toolkit;
using namespace mediakit;

class EchoTcpClient : public TcpClient {
public:
    EchoTcpClient(const EventPoller::Ptr &poller = nullptr){
        InfoL;
    }
    ~EchoTcpClient() override {
        InfoL;
    }
protected:
    void onRecv(const Buffer::Ptr &pBuf) override {
        DebugL << pBuf->toString();
    }
    //被动断开连接回调
    void onErr(const SockException &ex) override {
        WarnL << ex.what();
    }
    //tcp连接成功后每2秒触发一次该事件
    void onManager() override {
        send("echo test!");
        DebugL << "send echo test";
    }
    //连接服务器结果回调
    void onConnect(const SockException &ex) override{
        DebugL << ex.what();
    }

    //数据全部发送完毕后回调
    void onFlush() override{
        DebugL;
    }
};

int main(int argc, char *argv[]) {
    //设置退出信号处理函数
    static semaphore sem;
    signal(SIGINT, [](int) { sem.post(); });// 设置退出信号

    //设置日志
    Logger::Instance().add(std::make_shared<ConsoleChannel>());
    Logger::Instance().setWriter(std::make_shared<AsyncLogWriter>());

    WebSocketClient<EchoTcpClient>::Ptr client = std::make_shared<WebSocketClient<EchoTcpClient> >();
    client->startConnect("121.40.165.18",8800);

    sem.wait();
    return 0;
}

<|endoftext|>


<commit_before>#include <QtGlobal>
#include <QFileInfo>
#include <QDir>
#include <QProcess>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#include <QtDebug>

void runModelMoc(const QString& header, const QStringList& arguments)
{
    QFile inf(header);
    if(!inf.open(QFile::ReadOnly))
        qFatal("Could not open header file for reading");

    QTextStream in(&inf);

    QProcess p;
    p.start(QString(QT_MOC_PATH), arguments, QIODevice::WriteOnly);
    if(!p.waitForStarted()) {
        qFatal("mmoc: failed to run command '%s'", QT_MOC_PATH);
    }

    QString spaces = "\\s*";
    QString comma = ",";
    QString colon = ":";
    QString parenO = "\\(";
    QString parenC = "\\)";
    QString emptyParen = "\\(\\)";
    QString angleO = "<";
    QString angleC = ">";
    QString braceO = "\\{";
    QString nameSpace = "(?:\\w+::)";
    QString typeName = "\\w+";
    QString pointer = "\\*";
    QString templateName = "\\w+";
    QString plainParam = "(\\w+)";
    QString boolParam = "(true|false)";
    QString anyParam = "(.+)";

    QRegExp propertyRegExp(
            spaces+
            "M_MODEL_PROPERTY"+
            spaces+parenO+spaces+
                "("+
                    "(?:"+
                         nameSpace+"{,1}"+
                         typeName+
                         spaces+
                         pointer+"{,1}"+
                    ")"+
                    "|"+
                    "(?:"+
                         templateName+
                         angleO+
                             spaces+
                             typeName+
                             spaces+
                             pointer+"{,1}"+
                             spaces+
                         angleC+
                     ")"+
                  ")"+
                      spaces+comma+spaces+
                  plainParam+
                      spaces+comma+spaces+
                  plainParam+
                      spaces+comma+spaces+
                  plainParam+
                      spaces+comma+spaces+
                  anyParam+
              spaces+parenC+spaces );

    QRegExp propertyPtrRegExp(
        spaces+
        "M_MODEL_PTR_PROPERTY"+
        spaces+parenO+spaces+
            "("+
                "(?:"+
                    nameSpace+"{,1}"+
                    typeName+
                    spaces+
                    pointer+"{,1}"+
                    spaces+
                ")"+
                "|"+
                "(?:"+
                    templateName+
                    angleO+
                        spaces+
                        typeName+
                        spaces+
                        pointer+"{,1}"+
                        spaces+
                    angleC+
                ")"+
            ")"+
                spaces+comma+spaces+
            plainParam+
                spaces+comma+spaces+
            plainParam+
                spaces+comma+spaces+
            boolParam+
                spaces+comma+spaces+
            anyParam+
        spaces+parenC+spaces );

    QString line;
    while(true) {
        line = in.readLine();
        if(line.isNull()) {
            break;
        }

        line.replace(propertyRegExp, "    Q_PROPERTY(\\1 \\2 READ \\2 WRITE set\\3)");
        line.replace(propertyPtrRegExp, "    Q_PROPERTY(\\1 \\2 READ \\2 WRITE set\\3)");
        p.write(QString(line + "\n").toLatin1());
    }
    p.closeWriteChannel();

    if(!p.waitForFinished()) {
        qFatal("mmoc: failed to run command '%s'", QT_MOC_PATH);
    }
}

void runStyleMoc(const QString& header, const QStringList& arguments)
{
    QFile inf(header);
    if(!inf.open(QFile::ReadOnly))
        qFatal("Could not open header file for reading");

    QTextStream in(&inf);

    QProcess p;
    p.start(QString(QT_MOC_PATH), arguments);
    if(!p.waitForStarted()) {
        qFatal("mmoc: failed to run command '%s'", QT_MOC_PATH);
    }

    QRegExp attributeRegExp("\\s*M_STYLE_ATTRIBUTE\\s*\\(\\s*(\\w+\\:*\\w*)\\s*,\\s*(\\w+)\\s*,\\s*(\\w+)\\s*\\)\\s*");
    QRegExp attributePtrRegExp("\\s*M_STYLE_PTR_ATTRIBUTE\\s*\\(\\s*(\\w+\\:*\\w*\\s*\\*+)\\s*,\\s*(\\w+)\\s*,\\s*(\\w+)\\s*\\)\\s*");

    QString line;
    while(true) {
        line = in.readLine();
        if(line.isNull()) {
            break;
        }

        line.replace(attributeRegExp, "    Q_PROPERTY(\\1 \\2 READ \\2 WRITE set\\3)");
        line.replace(attributePtrRegExp, "    Q_PROPERTY(const \\1 \\2 READ \\2 WRITE set\\3)");
        p.write(QString(line + "\n").toLatin1());
    }
    p.closeWriteChannel();

    if(!p.waitForFinished()) {
        qFatal("mmoc: failed to run command '%s'", QT_MOC_PATH);
    }
}

enum HeaderType {
    Model,
    Style
};

int main(int argc, const char *argv[])
{
    HeaderType type=Model;
    QStringList commandLineParameters;
    QString filename;
    char* mocArgv[argc+1];
    int result;
    pid_t pid;

    mocArgv[0] = strdup(QT_MOC_PATH);
    mocArgv[argc] = NULL;

    for(int i=1; i<argc; ++i) {
        if(QString(argv[i]).endsWith("style.h")) {
            type = Style;
            filename = argv[i];
        } else if(QString(argv[i]).endsWith("model.h")) {
            type = Model;
            filename = argv[i];
        } else {
            commandLineParameters << QString(argv[i]);
            mocArgv[i] = (char*) argv[i];
        }
    }

    if(filename.isEmpty()) {
        if((pid = fork()) == 0) {
            exit(execv(QT_MOC_PATH, mocArgv));
        }
        waitpid(pid, &result, 0);
        if(result != 0) {
            qFatal("mmoc: failed to run command '%s'", QT_MOC_PATH);
        }
    } else {
        commandLineParameters << "-f" + filename;
        if(type == Model) {
            runModelMoc(filename, commandLineParameters);
        } else if(type == Style) {
            runStyleMoc(filename, commandLineParameters);
        }
    }

    free(mocArgv[0]);
    return 0; //success
}

<commit_msg>Changes: Make mmoc work under windows<commit_after>#include <QtGlobal>
#include <QFileInfo>
#include <QDir>
#include <QProcess>
#include <QtDebug>

void runModelMoc(const QString& header, const QStringList& arguments)
{
    QFile inf(header);
    if(!inf.open(QFile::ReadOnly))
        qFatal("Could not open header file for reading");

    QTextStream in(&inf);

    QProcess p;
    p.setProcessChannelMode( QProcess::ForwardedChannels );
    p.start(QString(QT_MOC_PATH), arguments, QIODevice::WriteOnly);
    if(!p.waitForStarted()) {
        qFatal("mmoc: failed to run command '%s'", QT_MOC_PATH);
    }

    QString spaces = "\\s*";
    QString comma = ",";
    QString colon = ":";
    QString parenO = "\\(";
    QString parenC = "\\)";
    QString emptyParen = "\\(\\)";
    QString angleO = "<";
    QString angleC = ">";
    QString braceO = "\\{";
    QString nameSpace = "(?:\\w+::)";
    QString typeName = "\\w+";
    QString pointer = "\\*";
    QString templateName = "\\w+";
    QString plainParam = "(\\w+)";
    QString boolParam = "(true|false)";
    QString anyParam = "(.+)";

    QRegExp propertyRegExp(
            spaces+
            "M_MODEL_PROPERTY"+
            spaces+parenO+spaces+
                "("+
                    "(?:"+
                         nameSpace+"{,1}"+
                         typeName+
                         spaces+
                         pointer+"{,1}"+
                    ")"+
                    "|"+
                    "(?:"+
                         templateName+
                         angleO+
                             spaces+
                             typeName+
                             spaces+
                             pointer+"{,1}"+
                             spaces+
                         angleC+
                     ")"+
                  ")"+
                      spaces+comma+spaces+
                  plainParam+
                      spaces+comma+spaces+
                  plainParam+
                      spaces+comma+spaces+
                  plainParam+
                      spaces+comma+spaces+
                  anyParam+
              spaces+parenC+spaces );

    QRegExp propertyPtrRegExp(
        spaces+
        "M_MODEL_PTR_PROPERTY"+
        spaces+parenO+spaces+
            "("+
                "(?:"+
                    nameSpace+"{,1}"+
                    typeName+
                    spaces+
                    pointer+"{,1}"+
                    spaces+
                ")"+
                "|"+
                "(?:"+
                    templateName+
                    angleO+
                        spaces+
                        typeName+
                        spaces+
                        pointer+"{,1}"+
                        spaces+
                    angleC+
                ")"+
            ")"+
                spaces+comma+spaces+
            plainParam+
                spaces+comma+spaces+
            plainParam+
                spaces+comma+spaces+
            boolParam+
                spaces+comma+spaces+
            anyParam+
        spaces+parenC+spaces );

    QString line;
    while(true) {
        line = in.readLine();
        if(line.isNull()) {
            break;
        }

        line.replace(propertyRegExp, "    Q_PROPERTY(\\1 \\2 READ \\2 WRITE set\\3)");
        line.replace(propertyPtrRegExp, "    Q_PROPERTY(\\1 \\2 READ \\2 WRITE set\\3)");
        p.write(QString(line + "\n").toLatin1());
    }
    p.closeWriteChannel();

    if(!p.waitForFinished()) {
        qFatal("mmoc: failed to run command '%s'", QT_MOC_PATH);
    }
}

void runStyleMoc(const QString& header, const QStringList& arguments)
{
    QFile inf(header);
    if(!inf.open(QFile::ReadOnly))
        qFatal("Could not open header file for reading");

    QTextStream in(&inf);

    QProcess p;
    p.setProcessChannelMode( QProcess::ForwardedChannels );
    p.start(QString(QT_MOC_PATH), arguments);
    if(!p.waitForStarted()) {
        qFatal("mmoc: failed to run command '%s'", QT_MOC_PATH);
    }

    QRegExp attributeRegExp("\\s*M_STYLE_ATTRIBUTE\\s*\\(\\s*(\\w+\\:*\\w*)\\s*,\\s*(\\w+)\\s*,\\s*(\\w+)\\s*\\)\\s*");
    QRegExp attributePtrRegExp("\\s*M_STYLE_PTR_ATTRIBUTE\\s*\\(\\s*(\\w+\\:*\\w*\\s*\\*+)\\s*,\\s*(\\w+)\\s*,\\s*(\\w+)\\s*\\)\\s*");

    QString line;
    while(true) {
        line = in.readLine();
        if(line.isNull()) {
            break;
        }

        line.replace(attributeRegExp, "    Q_PROPERTY(\\1 \\2 READ \\2 WRITE set\\3)");
        line.replace(attributePtrRegExp, "    Q_PROPERTY(const \\1 \\2 READ \\2 WRITE set\\3)");
        p.write(QString(line + "\n").toLatin1());
    }
    p.closeWriteChannel();

    if(!p.waitForFinished()) {
        qFatal("mmoc: failed to run command '%s'", QT_MOC_PATH);
    }
}

void runQtMoc(const QStringList& arguments)
{
    QProcess p;
    p.setProcessChannelMode( QProcess::ForwardedChannels );
    p.start(QString(QT_MOC_PATH), arguments);

    if(!p.waitForStarted()) {
        qFatal("mmoc: failed to run command '%s'", QT_MOC_PATH);
    }

    if(!p.waitForFinished()) {
        qFatal("mmoc: failed to run command '%s'", QT_MOC_PATH);
    }
}

enum HeaderType {
    Model,
    Style
};

int main(int argc, const char *argv[])
{
    HeaderType type=Model;
    QStringList commandLineParameters;
    QString filename;

    for(int i=1; i<argc; ++i) {
        if(QString(argv[i]).endsWith("style.h")) {
            type = Style;
            filename = argv[i];
        } else if(QString(argv[i]).endsWith("model.h")) {
            type = Model;
            filename = argv[i];
        } else {
            commandLineParameters << QString(argv[i]);
        }
    }

    if(filename.isEmpty()) {
        runQtMoc(commandLineParameters);
    } else {
        commandLineParameters << "-f" + filename;
        if(type == Model) {
            runModelMoc(filename, commandLineParameters);
        } else if(type == Style) {
            runStyleMoc(filename, commandLineParameters);
        }
    }

    return 0; //success
}

<|endoftext|>


<commit_before>#include "CTR.h"

std::string & CTR::increment_IV(std::string & IV){
    std::string::size_type i = IV.size();
    while ((i > 0) && (IV[i - 1] == 0xff)){
        IV[i - 1] = 0;
        i--;
    }

    if (i){
        IV[i - 1]++;
    }

    return IV;
}

CTR::CTR(SymAlg * instance, const std::string & iv)
    : algo(instance)
{
    blocksize = algo -> blocksize() >> 3;
    const_IV = iv;
    if (const_IV == ""){
        const_IV = std::string(blocksize, 0);
    }
}

std::string CTR::encrypt(const std::string & data){
    const std::string temp = pkcs5(data, blocksize);
    std::string out = "";
    std::string IV = const_IV;
    for(std::string::size_type x = 0; x < temp.size(); x += blocksize){
        out += xor_strings(algo -> encrypt(IV), temp.substr(0, blocksize));
        increment_IV(IV);
    }
    return out;
}

std::string CTR::decrypt(const std::string & data){
    std::string out = "";
    std::string IV = const_IV;
    for(std::string::size_type x = 0; x < data.size(); x += blocksize){
        out += xor_strings(algo -> encrypt(IV), data.substr(x, blocksize));
        increment_IV(IV);
    }
    return remove_pkcs5(out);
}
<commit_msg>cast comparison values<commit_after>#include "CTR.h"

std::string & CTR::increment_IV(std::string & IV){
    std::string::size_type i = IV.size();
    while ((i > 0) && ((uint8_t) IV[i - 1] == (uint8_t) 0xff)){
        IV[i - 1] = 0;
        i--;
    }

    if (i){
        IV[i - 1]++;
    }

    return IV;
}

CTR::CTR(SymAlg * instance, const std::string & iv)
    : algo(instance)
{
    blocksize = algo -> blocksize() >> 3;
    const_IV = iv;
    if (const_IV == ""){
        const_IV = std::string(blocksize, 0);
    }
}

std::string CTR::encrypt(const std::string & data){
    const std::string temp = pkcs5(data, blocksize);
    std::string out = "";
    std::string IV = const_IV;
    for(std::string::size_type x = 0; x < temp.size(); x += blocksize){
        out += xor_strings(algo -> encrypt(IV), temp.substr(0, blocksize));
        increment_IV(IV);
    }
    return out;
}

std::string CTR::decrypt(const std::string & data){
    std::string out = "";
    std::string IV = const_IV;
    for(std::string::size_type x = 0; x < data.size(); x += blocksize){
        out += xor_strings(algo -> encrypt(IV), data.substr(x, blocksize));
        increment_IV(IV);
    }
    return remove_pkcs5(out);
}
<|endoftext|>