<commit_before>/*************************************************************************
This software allows for filtering in high-dimensional observation and
state spaces, as described in

M. Wuthrich, P. Pastor, M. Kalakrishnan, J. Bohg, and S. Schaal.
Probabilistic Object Tracking using a Range Camera
IEEE/RSJ Intl Conf on Intelligent Robots and Systems, 2013

In a publication based on this software pleace cite the above reference.

Copyright (C) 2014  Manuel Wuthrich

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program 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 General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*************************************************************************/

#ifndef FAST_FILTERING_UTILS_RANDOM_SEED_HPP
#define FAST_FILTERING_UTILS_RANDOM_SEED_HPP

#include <time.h>

#define RANDOM_SEED (unsigned)std::time(0)//1

#endif

<commit_msg>corrected time() header. std::time exists within ctime header<commit_after>/*************************************************************************
This software allows for filtering in high-dimensional observation and
state spaces, as described in

M. Wuthrich, P. Pastor, M. Kalakrishnan, J. Bohg, and S. Schaal.
Probabilistic Object Tracking using a Range Camera
IEEE/RSJ Intl Conf on Intelligent Robots and Systems, 2013

In a publication based on this software pleace cite the above reference.

Copyright (C) 2014  Manuel Wuthrich

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program 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 General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*************************************************************************/

#ifndef FAST_FILTERING_UTILS_RANDOM_SEED_HPP
#define FAST_FILTERING_UTILS_RANDOM_SEED_HPP

#include <ctime>

#define RANDOM_SEED (unsigned)std::time(0) // 1

#endif

<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: mslangid.cxx,v $
 * $Revision: 1.10.24.4 $
 *
 * 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_i18npool.hxx"
#include <sal/config.h>
#include <rtl/ustring.hxx>
#include <rtl/string.hxx>
#include <com/sun/star/i18n/ScriptType.hpp>

#include "i18npool/mslangid.hxx"

LanguageType MsLangId::nConfiguredSystemLanguage   = LANGUAGE_SYSTEM;
LanguageType MsLangId::nConfiguredSystemUILanguage = LANGUAGE_SYSTEM;

LanguageType MsLangId::nConfiguredWesternFallback  = LANGUAGE_SYSTEM;
LanguageType MsLangId::nConfiguredAsianFallback    = LANGUAGE_SYSTEM;
LanguageType MsLangId::nConfiguredComplexFallback  = LANGUAGE_SYSTEM;

// static
void MsLangId::setConfiguredSystemLanguage( LanguageType nLang )
{
    nConfiguredSystemLanguage = nLang;
}

// static
void MsLangId::setConfiguredSystemUILanguage( LanguageType nLang )
{
    nConfiguredSystemUILanguage = nLang;
}

// static
void MsLangId::setConfiguredWesternFallback( LanguageType nLang )
{
    nConfiguredWesternFallback = nLang;
}

// static
void MsLangId::setConfiguredAsianFallback( LanguageType nLang )
{
    nConfiguredAsianFallback = nLang;
}

// static
void MsLangId::setConfiguredComplexFallback( LanguageType nLang )
{
    nConfiguredComplexFallback = nLang;
}

// static
inline LanguageType MsLangId::simplifySystemLanguages( LanguageType nLang )
{
    switch (nLang)
    {
        case LANGUAGE_PROCESS_OR_USER_DEFAULT :
        case LANGUAGE_SYSTEM_DEFAULT :
        case LANGUAGE_SYSTEM :
            nLang = LANGUAGE_SYSTEM;
            break;
        default:
            ;   // nothing
    }
    return nLang;
}

// static
LanguageType MsLangId::getRealLanguageWithoutConfig( LanguageType nLang )
{
    switch (simplifySystemLanguages( nLang))
    {
        case LANGUAGE_SYSTEM :
            nLang = getSystemLanguage();
            break;
        case LANGUAGE_NONE :
            nLang = getSystemUILanguage();
            break;
        default:
            ;   // nothing
    }
    if (nLang == LANGUAGE_DONTKNOW)
        nLang = LANGUAGE_ENGLISH_US;
    return nLang;
}

// static
LanguageType MsLangId::getRealLanguage( LanguageType nLang )
{
    switch (simplifySystemLanguages( nLang))
    {
        case LANGUAGE_SYSTEM :
            if (nConfiguredSystemLanguage == LANGUAGE_SYSTEM)
                nLang = getSystemLanguage();
            else
                nLang = nConfiguredSystemLanguage;
            break;
        case LANGUAGE_NONE :
            if (nConfiguredSystemUILanguage == LANGUAGE_SYSTEM)
                nLang = getSystemUILanguage();
            else
                nLang = nConfiguredSystemUILanguage;
            break;
        default:
            ;   // nothing
    }
    if (nLang == LANGUAGE_DONTKNOW)
        nLang = LANGUAGE_ENGLISH_US;
    return nLang;
}

// static
LanguageType MsLangId::resolveSystemLanguageByScriptType( LanguageType nLang, sal_Int16 nType )
{
    if (nLang == LANGUAGE_NONE)
        return nLang;

    nLang = getRealLanguage(nLang);
    if (nType != ::com::sun::star::i18n::ScriptType::WEAK && getScriptType(nLang) != nType)
    {
        switch(nType)
        {
            case ::com::sun::star::i18n::ScriptType::ASIAN:
                if (nConfiguredAsianFallback == LANGUAGE_SYSTEM)
                    nLang = LANGUAGE_CHINESE_SIMPLIFIED;
                else
                    nLang = nConfiguredComplexFallback;
                break;
            case ::com::sun::star::i18n::ScriptType::COMPLEX:
                if (nConfiguredComplexFallback == LANGUAGE_SYSTEM)
                    nLang = LANGUAGE_HINDI;
                else
                    nLang = nConfiguredComplexFallback;
                break;
            default:
                if (nConfiguredWesternFallback == LANGUAGE_SYSTEM)
                    nLang = LANGUAGE_ENGLISH_US;
                else
                    nLang = nConfiguredWesternFallback;
                break;
        }
    }
    return nLang;
}

// static
void MsLangId::convertLanguageToLocale( LanguageType nLang,
        ::com::sun::star::lang::Locale & rLocale )
{
    if (rLocale.Variant.getLength())
        rLocale.Variant = rtl::OUString();
    convertLanguageToIsoNames( nLang, rLocale.Language, rLocale.Country);
}

// static
::com::sun::star::lang::Locale MsLangId::convertLanguageToLocale(
        LanguageType nLang, bool bResolveSystem )
{
    ::com::sun::star::lang::Locale aLocale;
    if (!bResolveSystem && simplifySystemLanguages( nLang) == LANGUAGE_SYSTEM)
        ;   // nothing => empty locale
    else
    {
        // Still resolve LANGUAGE_DONTKNOW if resolving is not requested,
        // but not LANGUAGE_NONE or others.
        if (bResolveSystem || nLang == LANGUAGE_DONTKNOW)
            nLang = MsLangId::getRealLanguage( nLang);
        convertLanguageToLocale( nLang, aLocale);
    }
    return aLocale;
}

// static
LanguageType MsLangId::convertLocaleToLanguage(
        const ::com::sun::star::lang::Locale& rLocale )
{
    // empty language => LANGUAGE_SYSTEM
    if (rLocale.Language.getLength() == 0)
        return LANGUAGE_SYSTEM;

    LanguageType nRet = convertIsoNamesToLanguage( rLocale.Language,
            rLocale.Country);
    if (nRet == LANGUAGE_DONTKNOW)
        nRet = LANGUAGE_SYSTEM;

    return nRet;
}

// static
LanguageType MsLangId::convertLocaleToLanguageWithFallback(
            const ::com::sun::star::lang::Locale & rLocale )
{
    // empty language => LANGUAGE_SYSTEM
    if (rLocale.Language.getLength() == 0)
        return lookupFallbackLanguage( LANGUAGE_SYSTEM);

    return lookupFallbackLanguage( rLocale);
}

// static
::com::sun::star::lang::Locale MsLangId::convertLanguageToLocaleWithFallback(
        LanguageType nLang )
{
    return lookupFallbackLocale( MsLangId::getRealLanguage( nLang));
}

// static
::com::sun::star::lang::Locale MsLangId::getFallbackLocale(
            const ::com::sun::star::lang::Locale & rLocale )
{
    // empty language => LANGUAGE_SYSTEM
    if (rLocale.Language.getLength() == 0)
        return convertLanguageToLocaleWithFallback( LANGUAGE_SYSTEM);

    return lookupFallbackLocale( rLocale);
}

// static
LanguageType MsLangId::getFallbackLanguage( LanguageType nLang )
{
    return lookupFallbackLanguage( MsLangId::getRealLanguage( nLang));
}

// static
bool MsLangId::isRightToLeft( LanguageType nLang )
{
    switch( nLang & LANGUAGE_MASK_PRIMARY )
    {
        case LANGUAGE_ARABIC_SAUDI_ARABIA & LANGUAGE_MASK_PRIMARY :
        case LANGUAGE_HEBREW              & LANGUAGE_MASK_PRIMARY :
        case LANGUAGE_YIDDISH             & LANGUAGE_MASK_PRIMARY :
        case LANGUAGE_URDU                & LANGUAGE_MASK_PRIMARY :
        case LANGUAGE_FARSI               & LANGUAGE_MASK_PRIMARY :
        case LANGUAGE_KASHMIRI            & LANGUAGE_MASK_PRIMARY :
        case LANGUAGE_SINDHI              & LANGUAGE_MASK_PRIMARY :
        case LANGUAGE_UIGHUR_CHINA        & LANGUAGE_MASK_PRIMARY :
            return true;

        default:
            break;
    }
    return false;
}

// static
bool MsLangId::hasForbiddenCharacters( LanguageType nLang )
{
    switch (nLang & LANGUAGE_MASK_PRIMARY)
    {
        case LANGUAGE_CHINESE  & LANGUAGE_MASK_PRIMARY:
        case LANGUAGE_JAPANESE & LANGUAGE_MASK_PRIMARY:
        case LANGUAGE_KOREAN   & LANGUAGE_MASK_PRIMARY:
            return true;
        default:
            break;
    }
    return false;
}

// static
bool MsLangId::needsSequenceChecking( LanguageType nLang )
{
    switch (nLang & LANGUAGE_MASK_PRIMARY)
    {
        case LANGUAGE_BURMESE & LANGUAGE_MASK_PRIMARY:
        case LANGUAGE_KHMER   & LANGUAGE_MASK_PRIMARY:
        case LANGUAGE_LAO     & LANGUAGE_MASK_PRIMARY:
        case LANGUAGE_THAI    & LANGUAGE_MASK_PRIMARY:
            return true;
        default:
            break;
    }
    return false;
}

// static
sal_Int16 MsLangId::getScriptType( LanguageType nLang )
{
    sal_Int16 nScript;
    switch( nLang )
    {
        // CJK
        // all LANGUAGE_CHINESE_... are caught below
        case LANGUAGE_JAPANESE:
        case LANGUAGE_KOREAN:
        case LANGUAGE_KOREAN_JOHAB:
        case LANGUAGE_USER_KOREAN_NORTH:
            nScript = ::com::sun::star::i18n::ScriptType::ASIAN;
            break;

        // CTL
        // all LANGUAGE_ARABIC_... are caught below
        case LANGUAGE_AMHARIC_ETHIOPIA:
        case LANGUAGE_ASSAMESE:
        case LANGUAGE_BENGALI:
        case LANGUAGE_BENGALI_BANGLADESH:
        case LANGUAGE_BURMESE:
        case LANGUAGE_FARSI:
        case LANGUAGE_HEBREW:
        case LANGUAGE_YIDDISH:
        case LANGUAGE_MARATHI:
        case LANGUAGE_PUNJABI:
        case LANGUAGE_GUJARATI:
        case LANGUAGE_HINDI:
        case LANGUAGE_KANNADA:
        case LANGUAGE_KASHMIRI:
        case LANGUAGE_KASHMIRI_INDIA:
        case LANGUAGE_KHMER:
        case LANGUAGE_LAO:
        case LANGUAGE_MALAYALAM:
        case LANGUAGE_MANIPURI:
        case LANGUAGE_MONGOLIAN_MONGOLIAN:
        case LANGUAGE_NEPALI:
        case LANGUAGE_NEPALI_INDIA:
        case LANGUAGE_ORIYA:
        case LANGUAGE_SANSKRIT:
        case LANGUAGE_SINDHI:
        case LANGUAGE_SINDHI_PAKISTAN:
        case LANGUAGE_SINHALESE_SRI_LANKA:
        case LANGUAGE_SYRIAC:
        case LANGUAGE_TAMIL:
        case LANGUAGE_TELUGU:
        case LANGUAGE_THAI:
        case LANGUAGE_TIBETAN:
        case LANGUAGE_DZONGKHA:
        case LANGUAGE_URDU:
        case LANGUAGE_URDU_PAKISTAN:
        case LANGUAGE_URDU_INDIA:
        case LANGUAGE_USER_KURDISH_IRAQ:
        case LANGUAGE_USER_KURDISH_IRAN:
        case LANGUAGE_DHIVEHI:
        case LANGUAGE_USER_BODO_INDIA:
        case LANGUAGE_USER_DOGRI_INDIA:
        case LANGUAGE_USER_MAITHILI_INDIA:
            nScript = ::com::sun::star::i18n::ScriptType::COMPLEX;
            break;

// currently not knowing scripttype - defaulted to LATIN:
/*
#define LANGUAGE_ARMENIAN                   0x042B
#define LANGUAGE_INDONESIAN                 0x0421
#define LANGUAGE_KAZAK                      0x043F
#define LANGUAGE_KONKANI                    0x0457
#define LANGUAGE_MACEDONIAN                 0x042F
#define LANGUAGE_TATAR                      0x0444
*/

    default:
        switch ( nLang & LANGUAGE_MASK_PRIMARY )
        {
            // CJK catcher
            case LANGUAGE_CHINESE & LANGUAGE_MASK_PRIMARY:
                nScript = ::com::sun::star::i18n::ScriptType::ASIAN;
                break;
            // CTL catcher
            case LANGUAGE_ARABIC_SAUDI_ARABIA & LANGUAGE_MASK_PRIMARY:
                nScript = ::com::sun::star::i18n::ScriptType::COMPLEX;
                break;
            // Western (actually not necessarily Latin but also Cyrillic, for example)
            default:
                nScript = ::com::sun::star::i18n::ScriptType::LATIN;
        }
        break;
    }
    return nScript;
}

// static
LanguageType MsLangId::getReplacementForObsoleteLanguage( LanguageType nLang )
{
    switch (nLang)
    {
        default:
            break;  // nothing
        case LANGUAGE_OBSOLETE_USER_LATIN:
            nLang = LANGUAGE_LATIN;
            break;
        case LANGUAGE_OBSOLETE_USER_MAORI:
            nLang = LANGUAGE_MAORI_NEW_ZEALAND;
            break;
        case LANGUAGE_OBSOLETE_USER_KINYARWANDA:
            nLang = LANGUAGE_KINYARWANDA_RWANDA;
            break;
        case LANGUAGE_OBSOLETE_USER_UPPER_SORBIAN:
            nLang = LANGUAGE_UPPER_SORBIAN_GERMANY;
            break;
        case LANGUAGE_OBSOLETE_USER_LOWER_SORBIAN:
            nLang = LANGUAGE_LOWER_SORBIAN_GERMANY;
            break;
        case LANGUAGE_OBSOLETE_USER_OCCITAN:
            nLang = LANGUAGE_OCCITAN_FRANCE;
            break;
        case LANGUAGE_OBSOLETE_USER_BRETON:
            nLang = LANGUAGE_BRETON_FRANCE;
            break;
        case LANGUAGE_OBSOLETE_USER_KALAALLISUT:
            nLang = LANGUAGE_KALAALLISUT_GREENLAND;
            break;
        case LANGUAGE_OBSOLETE_USER_LUXEMBOURGISH:
            nLang = LANGUAGE_LUXEMBOURGISH_LUXEMBOURG;
            break;

        // The following are not strictly obsolete but should be mapped to a
        // replacement locale when encountered.

        // no_NO is an alias for nb_NO
        case LANGUAGE_NORWEGIAN:
            nLang = LANGUAGE_NORWEGIAN_BOKMAL;
            break;

        // #i94435# A Spanish variant that differs only in collation details we
        // do not support.
        case LANGUAGE_SPANISH_DATED:
            nLang = LANGUAGE_SPANISH_MODERN;
            break;
    }
    return nLang;
}
<commit_msg>CWS-TOOLING: integrate CWS fwk129_DEV300<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: mslangid.cxx,v $
 * $Revision: 1.10.24.4 $
 *
 * 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_i18npool.hxx"
#include <sal/config.h>
#include <rtl/ustring.hxx>
#include <rtl/string.hxx>
#include <com/sun/star/i18n/ScriptType.hpp>

#include "i18npool/mslangid.hxx"

LanguageType MsLangId::nConfiguredSystemLanguage   = LANGUAGE_SYSTEM;
LanguageType MsLangId::nConfiguredSystemUILanguage = LANGUAGE_SYSTEM;

LanguageType MsLangId::nConfiguredWesternFallback  = LANGUAGE_SYSTEM;
LanguageType MsLangId::nConfiguredAsianFallback    = LANGUAGE_SYSTEM;
LanguageType MsLangId::nConfiguredComplexFallback  = LANGUAGE_SYSTEM;

// static
void MsLangId::setConfiguredSystemLanguage( LanguageType nLang )
{
    nConfiguredSystemLanguage = nLang;
}

// static
void MsLangId::setConfiguredSystemUILanguage( LanguageType nLang )
{
    nConfiguredSystemUILanguage = nLang;
}

// static
void MsLangId::setConfiguredWesternFallback( LanguageType nLang )
{
    nConfiguredWesternFallback = nLang;
}

// static
void MsLangId::setConfiguredAsianFallback( LanguageType nLang )
{
    nConfiguredAsianFallback = nLang;
}

// static
void MsLangId::setConfiguredComplexFallback( LanguageType nLang )
{
    nConfiguredComplexFallback = nLang;
}

// static
inline LanguageType MsLangId::simplifySystemLanguages( LanguageType nLang )
{
    switch (nLang)
    {
        case LANGUAGE_PROCESS_OR_USER_DEFAULT :
        case LANGUAGE_SYSTEM_DEFAULT :
        case LANGUAGE_SYSTEM :
            nLang = LANGUAGE_SYSTEM;
            break;
        default:
            ;   // nothing
    }
    return nLang;
}

// static
LanguageType MsLangId::getRealLanguageWithoutConfig( LanguageType nLang )
{
    switch (simplifySystemLanguages( nLang))
    {
        case LANGUAGE_SYSTEM :
            nLang = getSystemLanguage();
            break;
        case LANGUAGE_NONE :
            nLang = getSystemUILanguage();
            break;
        default:
            ;   // nothing
    }
    if (nLang == LANGUAGE_DONTKNOW)
        nLang = LANGUAGE_ENGLISH_US;
    return nLang;
}

// static
LanguageType MsLangId::getRealLanguage( LanguageType nLang )
{
    switch (simplifySystemLanguages( nLang))
    {
        case LANGUAGE_SYSTEM :
            if (nConfiguredSystemLanguage == LANGUAGE_SYSTEM)
                nLang = getSystemLanguage();
            else
                nLang = nConfiguredSystemLanguage;
            break;
        case LANGUAGE_NONE :
            if (nConfiguredSystemUILanguage == LANGUAGE_SYSTEM)
                nLang = getSystemUILanguage();
            else
                nLang = nConfiguredSystemUILanguage;
            break;
        default:
            ;   // nothing
    }
    if (nLang == LANGUAGE_DONTKNOW)
        nLang = LANGUAGE_ENGLISH_US;
    return nLang;
}

// static
LanguageType MsLangId::resolveSystemLanguageByScriptType( LanguageType nLang, sal_Int16 nType )
{
    if (nLang == LANGUAGE_NONE)
        return nLang;

    nLang = getRealLanguage(nLang);
    if (nType != ::com::sun::star::i18n::ScriptType::WEAK && getScriptType(nLang) != nType)
    {
        switch(nType)
        {
            case ::com::sun::star::i18n::ScriptType::ASIAN:
                if (nConfiguredAsianFallback == LANGUAGE_SYSTEM)
                    nLang = LANGUAGE_CHINESE_SIMPLIFIED;
                else
                    nLang = nConfiguredAsianFallback;
                break;
            case ::com::sun::star::i18n::ScriptType::COMPLEX:
                if (nConfiguredComplexFallback == LANGUAGE_SYSTEM)
                    nLang = LANGUAGE_HINDI;
                else
                    nLang = nConfiguredComplexFallback;
                break;
            default:
                if (nConfiguredWesternFallback == LANGUAGE_SYSTEM)
                    nLang = LANGUAGE_ENGLISH_US;
                else
                    nLang = nConfiguredWesternFallback;
                break;
        }
    }
    return nLang;
}

// static
void MsLangId::convertLanguageToLocale( LanguageType nLang,
        ::com::sun::star::lang::Locale & rLocale )
{
    if (rLocale.Variant.getLength())
        rLocale.Variant = rtl::OUString();
    convertLanguageToIsoNames( nLang, rLocale.Language, rLocale.Country);
}

// static
::com::sun::star::lang::Locale MsLangId::convertLanguageToLocale(
        LanguageType nLang, bool bResolveSystem )
{
    ::com::sun::star::lang::Locale aLocale;
    if (!bResolveSystem && simplifySystemLanguages( nLang) == LANGUAGE_SYSTEM)
        ;   // nothing => empty locale
    else
    {
        // Still resolve LANGUAGE_DONTKNOW if resolving is not requested,
        // but not LANGUAGE_NONE or others.
        if (bResolveSystem || nLang == LANGUAGE_DONTKNOW)
            nLang = MsLangId::getRealLanguage( nLang);
        convertLanguageToLocale( nLang, aLocale);
    }
    return aLocale;
}

// static
LanguageType MsLangId::convertLocaleToLanguage(
        const ::com::sun::star::lang::Locale& rLocale )
{
    // empty language => LANGUAGE_SYSTEM
    if (rLocale.Language.getLength() == 0)
        return LANGUAGE_SYSTEM;

    LanguageType nRet = convertIsoNamesToLanguage( rLocale.Language,
            rLocale.Country);
    if (nRet == LANGUAGE_DONTKNOW)
        nRet = LANGUAGE_SYSTEM;

    return nRet;
}

// static
LanguageType MsLangId::convertLocaleToLanguageWithFallback(
            const ::com::sun::star::lang::Locale & rLocale )
{
    // empty language => LANGUAGE_SYSTEM
    if (rLocale.Language.getLength() == 0)
        return lookupFallbackLanguage( LANGUAGE_SYSTEM);

    return lookupFallbackLanguage( rLocale);
}

// static
::com::sun::star::lang::Locale MsLangId::convertLanguageToLocaleWithFallback(
        LanguageType nLang )
{
    return lookupFallbackLocale( MsLangId::getRealLanguage( nLang));
}

// static
::com::sun::star::lang::Locale MsLangId::getFallbackLocale(
            const ::com::sun::star::lang::Locale & rLocale )
{
    // empty language => LANGUAGE_SYSTEM
    if (rLocale.Language.getLength() == 0)
        return convertLanguageToLocaleWithFallback( LANGUAGE_SYSTEM);

    return lookupFallbackLocale( rLocale);
}

// static
LanguageType MsLangId::getFallbackLanguage( LanguageType nLang )
{
    return lookupFallbackLanguage( MsLangId::getRealLanguage( nLang));
}

// static
bool MsLangId::isRightToLeft( LanguageType nLang )
{
    switch( nLang & LANGUAGE_MASK_PRIMARY )
    {
        case LANGUAGE_ARABIC_SAUDI_ARABIA & LANGUAGE_MASK_PRIMARY :
        case LANGUAGE_HEBREW              & LANGUAGE_MASK_PRIMARY :
        case LANGUAGE_YIDDISH             & LANGUAGE_MASK_PRIMARY :
        case LANGUAGE_URDU                & LANGUAGE_MASK_PRIMARY :
        case LANGUAGE_FARSI               & LANGUAGE_MASK_PRIMARY :
        case LANGUAGE_KASHMIRI            & LANGUAGE_MASK_PRIMARY :
        case LANGUAGE_SINDHI              & LANGUAGE_MASK_PRIMARY :
        case LANGUAGE_UIGHUR_CHINA        & LANGUAGE_MASK_PRIMARY :
            return true;

        default:
            break;
    }
    return false;
}

// static
bool MsLangId::hasForbiddenCharacters( LanguageType nLang )
{
    switch (nLang & LANGUAGE_MASK_PRIMARY)
    {
        case LANGUAGE_CHINESE  & LANGUAGE_MASK_PRIMARY:
        case LANGUAGE_JAPANESE & LANGUAGE_MASK_PRIMARY:
        case LANGUAGE_KOREAN   & LANGUAGE_MASK_PRIMARY:
            return true;
        default:
            break;
    }
    return false;
}

// static
bool MsLangId::needsSequenceChecking( LanguageType nLang )
{
    switch (nLang & LANGUAGE_MASK_PRIMARY)
    {
        case LANGUAGE_BURMESE & LANGUAGE_MASK_PRIMARY:
        case LANGUAGE_KHMER   & LANGUAGE_MASK_PRIMARY:
        case LANGUAGE_LAO     & LANGUAGE_MASK_PRIMARY:
        case LANGUAGE_THAI    & LANGUAGE_MASK_PRIMARY:
            return true;
        default:
            break;
    }
    return false;
}

// static
sal_Int16 MsLangId::getScriptType( LanguageType nLang )
{
    sal_Int16 nScript;
    switch( nLang )
    {
        // CJK
        // all LANGUAGE_CHINESE_... are caught below
        case LANGUAGE_JAPANESE:
        case LANGUAGE_KOREAN:
        case LANGUAGE_KOREAN_JOHAB:
        case LANGUAGE_USER_KOREAN_NORTH:
            nScript = ::com::sun::star::i18n::ScriptType::ASIAN;
            break;

        // CTL
        // all LANGUAGE_ARABIC_... are caught below
        case LANGUAGE_AMHARIC_ETHIOPIA:
        case LANGUAGE_ASSAMESE:
        case LANGUAGE_BENGALI:
        case LANGUAGE_BENGALI_BANGLADESH:
        case LANGUAGE_BURMESE:
        case LANGUAGE_FARSI:
        case LANGUAGE_HEBREW:
        case LANGUAGE_YIDDISH:
        case LANGUAGE_MARATHI:
        case LANGUAGE_PUNJABI:
        case LANGUAGE_GUJARATI:
        case LANGUAGE_HINDI:
        case LANGUAGE_KANNADA:
        case LANGUAGE_KASHMIRI:
        case LANGUAGE_KASHMIRI_INDIA:
        case LANGUAGE_KHMER:
        case LANGUAGE_LAO:
        case LANGUAGE_MALAYALAM:
        case LANGUAGE_MANIPURI:
        case LANGUAGE_MONGOLIAN_MONGOLIAN:
        case LANGUAGE_NEPALI:
        case LANGUAGE_NEPALI_INDIA:
        case LANGUAGE_ORIYA:
        case LANGUAGE_SANSKRIT:
        case LANGUAGE_SINDHI:
        case LANGUAGE_SINDHI_PAKISTAN:
        case LANGUAGE_SINHALESE_SRI_LANKA:
        case LANGUAGE_SYRIAC:
        case LANGUAGE_TAMIL:
        case LANGUAGE_TELUGU:
        case LANGUAGE_THAI:
        case LANGUAGE_TIBETAN:
        case LANGUAGE_DZONGKHA:
        case LANGUAGE_URDU:
        case LANGUAGE_URDU_PAKISTAN:
        case LANGUAGE_URDU_INDIA:
        case LANGUAGE_USER_KURDISH_IRAQ:
        case LANGUAGE_USER_KURDISH_IRAN:
        case LANGUAGE_DHIVEHI:
        case LANGUAGE_USER_BODO_INDIA:
        case LANGUAGE_USER_DOGRI_INDIA:
        case LANGUAGE_USER_MAITHILI_INDIA:
            nScript = ::com::sun::star::i18n::ScriptType::COMPLEX;
            break;

// currently not knowing scripttype - defaulted to LATIN:
/*
#define LANGUAGE_ARMENIAN                   0x042B
#define LANGUAGE_INDONESIAN                 0x0421
#define LANGUAGE_KAZAK                      0x043F
#define LANGUAGE_KONKANI                    0x0457
#define LANGUAGE_MACEDONIAN                 0x042F
#define LANGUAGE_TATAR                      0x0444
*/

    default:
        switch ( nLang & LANGUAGE_MASK_PRIMARY )
        {
            // CJK catcher
            case LANGUAGE_CHINESE & LANGUAGE_MASK_PRIMARY:
                nScript = ::com::sun::star::i18n::ScriptType::ASIAN;
                break;
            // CTL catcher
            case LANGUAGE_ARABIC_SAUDI_ARABIA & LANGUAGE_MASK_PRIMARY:
                nScript = ::com::sun::star::i18n::ScriptType::COMPLEX;
                break;
            // Western (actually not necessarily Latin but also Cyrillic, for example)
            default:
                nScript = ::com::sun::star::i18n::ScriptType::LATIN;
        }
        break;
    }
    return nScript;
}

// static
LanguageType MsLangId::getReplacementForObsoleteLanguage( LanguageType nLang )
{
    switch (nLang)
    {
        default:
            break;  // nothing
        case LANGUAGE_OBSOLETE_USER_LATIN:
            nLang = LANGUAGE_LATIN;
            break;
        case LANGUAGE_OBSOLETE_USER_MAORI:
            nLang = LANGUAGE_MAORI_NEW_ZEALAND;
            break;
        case LANGUAGE_OBSOLETE_USER_KINYARWANDA:
            nLang = LANGUAGE_KINYARWANDA_RWANDA;
            break;
        case LANGUAGE_OBSOLETE_USER_UPPER_SORBIAN:
            nLang = LANGUAGE_UPPER_SORBIAN_GERMANY;
            break;
        case LANGUAGE_OBSOLETE_USER_LOWER_SORBIAN:
            nLang = LANGUAGE_LOWER_SORBIAN_GERMANY;
            break;
        case LANGUAGE_OBSOLETE_USER_OCCITAN:
            nLang = LANGUAGE_OCCITAN_FRANCE;
            break;
        case LANGUAGE_OBSOLETE_USER_BRETON:
            nLang = LANGUAGE_BRETON_FRANCE;
            break;
        case LANGUAGE_OBSOLETE_USER_KALAALLISUT:
            nLang = LANGUAGE_KALAALLISUT_GREENLAND;
            break;
        case LANGUAGE_OBSOLETE_USER_LUXEMBOURGISH:
            nLang = LANGUAGE_LUXEMBOURGISH_LUXEMBOURG;
            break;

        // The following are not strictly obsolete but should be mapped to a
        // replacement locale when encountered.

        // no_NO is an alias for nb_NO
        case LANGUAGE_NORWEGIAN:
            nLang = LANGUAGE_NORWEGIAN_BOKMAL;
            break;

        // #i94435# A Spanish variant that differs only in collation details we
        // do not support.
        case LANGUAGE_SPANISH_DATED:
            nLang = LANGUAGE_SPANISH_MODERN;
            break;
    }
    return nLang;
}
<|endoftext|>


<commit_before>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008 Aristid Breitkreuz, Ruediger Sonderfeld

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.
*/

#ifndef FLUSSPFERD_CURRENT_CONTEXT_SCOPE_HPP
#define FLUSSPFERD_CURRENT_CONTEXT_SCOPE_HPP

#include "flusspferd/init.hpp"
#include "flusspferd/context.hpp"

namespace flusspferd {

class context;

class current_context_scope {
private:
  context c;
  context old;

public:
  current_context_scope(context const &c)
      : c(c)
  {
    old = enter_current_context(this->c);
  }

  ~current_context_scope() {
    if(leave_current_context(c) && old.is_valid())
      enter_current_context(old);
  }
};

}

#endif /* FLUSSPFERD_CURRENT_CONTEXT_SCOPE_HPP */
<commit_msg>doc: add ref docs for current_context_scope<commit_after>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008 Aristid Breitkreuz, Ruediger Sonderfeld

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.
*/

#ifndef FLUSSPFERD_CURRENT_CONTEXT_SCOPE_HPP
#define FLUSSPFERD_CURRENT_CONTEXT_SCOPE_HPP

#include "flusspferd/init.hpp"
#include "flusspferd/context.hpp"

namespace flusspferd {

class context;

/**
 * Load a context while in scope.
 *
 * @ingroup contexts
 */
class current_context_scope {
private:
  context c;
  context old;

public:
  /**
   * Constructor.
   *
   * @param c The context to load.
   */
  current_context_scope(context const &c)
      : c(c)
  {
    old = enter_current_context(this->c);
  }

  /**
   * Destructor.
   */
  ~current_context_scope() {
    if(leave_current_context(c) && old.is_valid())
      enter_current_context(old);
  }
};

}

#endif /* FLUSSPFERD_CURRENT_CONTEXT_SCOPE_HPP */
<|endoftext|>


<commit_before>/**
 * @file   Uri.cpp
 * @brief  Uri class implementation.
 * @author zer0
 * @date   2017-05-19
 */

#include <libtbag/network/Uri.hpp>
#include <libtbag/bitwise/BitFlags.hpp>
#include <libtbag/uvpp/UvCommon.hpp>
#include <libtbag/uvpp/Loop.hpp>
#include <libtbag/uvpp/Dns.hpp>
#include <libtbag/log/Log.hpp>

#include <http_parser.h>
#include <cassert>
#include <utility>

// -------------------
NAMESPACE_LIBTBAG_OPEN
// -------------------

namespace network {

Uri::Uri()
{
    // EMPTY.
}

Uri::Uri(char const * uri, bool is_connect)
{
    parse(std::string(uri), is_connect);
}

Uri::Uri(std::string const & uri, bool is_connect)
{
    parse(uri, is_connect);
}

Uri::Uri(Uri const & obj)
{
    (*this) = obj;
}

Uri::Uri(Uri && obj)
{
    (*this) = std::move(obj);
}

Uri::~Uri()
{
    // EMPTY.
}

Uri & Uri::operator =(char const * uri)
{
    parse(std::string(uri));
    return *this;
}

Uri & Uri::operator =(std::string const & uri)
{
    parse(uri);
    return *this;
}

Uri & Uri::operator =(Uri const & obj)
{
    if (this != &obj) {
        _uri      = obj._uri     ;
        _schema   = obj._schema  ;
        _host     = obj._host    ;
        _port     = obj._port    ;
        _path     = obj._path    ;
        _query    = obj._query   ;
        _fragment = obj._fragment;
        _userinfo = obj._userinfo;
    }
    return *this;
}

Uri & Uri::operator =(Uri && obj)
{
    if (this != &obj) {
        swap(obj);
    }
    return *this;
}

Uri::operator std::string() const
{
    return _uri;
}

Uri::operator char const * () const
{
    return _uri.c_str();
}

void Uri::swap(Uri & obj) TBAG_NOEXCEPT
{
    if (this != &obj) {
        _uri     .swap(obj._uri     );
        _schema  .swap(obj._schema  );
        _host    .swap(obj._host    );
        _port    .swap(obj._port    );
        _path    .swap(obj._path    );
        _query   .swap(obj._query   );
        _fragment.swap(obj._fragment);
        _userinfo.swap(obj._userinfo);
    }
}

int Uri::getPortNumber() const
{
    try {
        return std::stoi(getPort());
    } catch (...) {
        return 0;
    }
}

std::string Uri::getUrl() const
{
    std::string result = getSchema();
    result.append("://");
    if (isUserinfo()) {
        result.append(getUserinfo());
        result.push_back('@');
    }
    result.append(getHost());
    if (isPort()) {
        result.push_back(':');
        result.append(getPort());
    }
    return result;
}

std::string Uri::getRequestPath() const
{
    std::string result = getPath();
    if (isQuery()) {
        result.push_back('?');
        result.append(getQuery());
    }
    if (isFragment()) {
        result.push_back('#');
        result.append(getFragment());
    }

    if (result.empty()) {
        result.push_back('/');
    }
    return result;
}

void Uri::clear()
{
    _uri     .clear();
    _schema  .clear();
    _host    .clear();
    _port    .clear();
    _path    .clear();
    _query   .clear();
    _fragment.clear();
    _userinfo.clear();
}

bool Uri::parse(std::string const & uri, bool is_connect)
{
    _uri = uri;
    if (_uri.empty()) {
        return false;
    }

    http_parser_url parser;
    ::http_parser_url_init(&parser);

    // Parse a URL; return nonzero on failure.
    if (::http_parser_parse_url(_uri.c_str(), _uri.size(), (is_connect ? 1 : 0), &parser) != 0) {
        return false;
    }

    auto updateField = [&](http_parser_url_fields field, FieldInfo & info){
        if (bitwise::checkFlag<uint16_t>(parser.field_set, field)) {
            bool enable = true;
            if (parser.field_data[field].off == 0 && parser.field_data[field].len == 0) {
                enable = false;
            }
            info.set(parser.field_data[field].off, parser.field_data[field].len, enable);
        } else {
            info.clear();
        }
    };

    updateField(UF_SCHEMA  , _schema  );
    updateField(UF_HOST    , _host    );
    updateField(UF_PORT    , _port    );
    updateField(UF_PATH    , _path    );
    updateField(UF_QUERY   , _query   );
    updateField(UF_FRAGMENT, _fragment);
    updateField(UF_USERINFO, _userinfo);
    return true;
}

Err Uri::requestAddrInfo(std::string & host, int & port, AddrFlags flags) const
{
    if (isHost() == false) {
        tDLogE("Uri::requestAddrInfo() Unknown host: {}.", _uri);
        return Err::E_ILLSTATE;
    }

    if (isPort() == false && isSchema() == false) {
        tDLogE("Uri::requestAddrInfo() Unknown schema or port: {}.", _uri);
        return Err::E_ILLSTATE;
    }

    std::string const HOST    = getHost();
    std::string const SERVICE = isSchema() ? getSchema() : std::string();

    assert(HOST.empty() == false);

    uvpp::Loop loop;
    uvpp::DnsAddrInfo addr;

    Err const REQUEST_RESULT = addr.requestAddrInfoWithSync(loop, HOST, SERVICE);
    if (REQUEST_RESULT != Err::E_SUCCESS) {
        return REQUEST_RESULT;
    }

    uvpp::DnsAddrInfo::FindFlag find_flag;
    if (flags == AddrFlags::MOST_IPV6) {
        find_flag = uvpp::DnsAddrInfo::FindFlag::MOST_IPV6;
    } else {
        find_flag = uvpp::DnsAddrInfo::FindFlag::MOST_IPV4;
    }

    auto * info = addr.findSockAddr(find_flag);
    if (info == nullptr) {
        info = addr.findFirst();
        if (info == nullptr) {
            return Err::E_ENFOUND;
        }
    }

    host = uvpp::getIpName(info);
    if (isPort()) {
        port = getPortNumber();
    } else {
        assert(SERVICE.empty() == false);
        port = uvpp::getPortNumber(info);
    }

    return Err::E_SUCCESS;
}

// ---------------
// Static methods.
// ---------------

std::string Uri::getFieldString(std::string const & original, FieldInfo const & info)
{
    return original.substr(info.offset, info.length);
}

} // namespace network

// --------------------
NAMESPACE_LIBTBAG_CLOSE
// --------------------

<commit_msg>Trivial commit.<commit_after>/**
 * @file   Uri.cpp
 * @brief  Uri class implementation.
 * @author zer0
 * @date   2017-05-19
 */

#include <libtbag/network/Uri.hpp>
#include <libtbag/bitwise/BitFlags.hpp>
#include <libtbag/uvpp/UvCommon.hpp>
#include <libtbag/uvpp/Loop.hpp>
#include <libtbag/uvpp/Dns.hpp>
#include <libtbag/log/Log.hpp>

#include <http_parser.h>
#include <cassert>
#include <utility>

// -------------------
NAMESPACE_LIBTBAG_OPEN
// -------------------

namespace network {

Uri::Uri()
{
    // EMPTY.
}

Uri::Uri(char const * uri, bool is_connect)
{
    parse(std::string(uri), is_connect);
}

Uri::Uri(std::string const & uri, bool is_connect)
{
    parse(uri, is_connect);
}

Uri::Uri(Uri const & obj)
{
    (*this) = obj;
}

Uri::Uri(Uri && obj)
{
    (*this) = std::move(obj);
}

Uri::~Uri()
{
    // EMPTY.
}

Uri & Uri::operator =(char const * uri)
{
    parse(std::string(uri));
    return *this;
}

Uri & Uri::operator =(std::string const & uri)
{
    parse(uri);
    return *this;
}

Uri & Uri::operator =(Uri const & obj)
{
    if (this != &obj) {
        _uri      = obj._uri     ;
        _schema   = obj._schema  ;
        _host     = obj._host    ;
        _port     = obj._port    ;
        _path     = obj._path    ;
        _query    = obj._query   ;
        _fragment = obj._fragment;
        _userinfo = obj._userinfo;
    }
    return *this;
}

Uri & Uri::operator =(Uri && obj)
{
    if (this != &obj) {
        swap(obj);
    }
    return *this;
}

Uri::operator std::string() const
{
    return _uri;
}

Uri::operator char const * () const
{
    return _uri.c_str();
}

void Uri::swap(Uri & obj) TBAG_NOEXCEPT
{
    if (this != &obj) {
        _uri     .swap(obj._uri     );
        _schema  .swap(obj._schema  );
        _host    .swap(obj._host    );
        _port    .swap(obj._port    );
        _path    .swap(obj._path    );
        _query   .swap(obj._query   );
        _fragment.swap(obj._fragment);
        _userinfo.swap(obj._userinfo);
    }
}

int Uri::getPortNumber() const
{
    try {
        return std::stoi(getPort());
    } catch (...) {
        return 0;
    }
}

std::string Uri::getUrl() const
{
    std::string result = getSchema();
    result.append("://");
    if (isUserinfo()) {
        result.append(getUserinfo());
        result.push_back('@');
    }
    result.append(getHost());
    if (isPort()) {
        result.push_back(':');
        result.append(getPort());
    }
    return result;
}

std::string Uri::getRequestPath() const
{
    std::string result = getPath();
    if (isQuery()) {
        result.push_back('?');
        result.append(getQuery());
    }
    if (isFragment()) {
        result.push_back('#');
        result.append(getFragment());
    }

    if (result.empty()) {
        result.push_back('/');
    }
    return result;
}

void Uri::clear()
{
    _uri     .clear();
    _schema  .clear();
    _host    .clear();
    _port    .clear();
    _path    .clear();
    _query   .clear();
    _fragment.clear();
    _userinfo.clear();
}

bool Uri::parse(std::string const & uri, bool is_connect)
{
    _uri = uri;
    if (_uri.empty()) {
        return false;
    }

    http_parser_url parser;
    ::http_parser_url_init(&parser);

    // Parse a URL; return nonzero on failure.
    if (::http_parser_parse_url(_uri.c_str(), _uri.size(), (is_connect ? 1 : 0), &parser) != 0) {
        return false;
    }

    auto updateField = [&](http_parser_url_fields field, FieldInfo & info){
        if (bitwise::checkFlag<uint16_t>(parser.field_set, field)) {
            bool enable = true;
            if (parser.field_data[field].off == 0 && parser.field_data[field].len == 0) {
                enable = false;
            }
            info.set(parser.field_data[field].off, parser.field_data[field].len, enable);
        } else {
            info.clear();
        }
    };

    updateField(UF_SCHEMA  , _schema  );
    updateField(UF_HOST    , _host    );
    updateField(UF_PORT    , _port    );
    updateField(UF_PATH    , _path    );
    updateField(UF_QUERY   , _query   );
    updateField(UF_FRAGMENT, _fragment);
    updateField(UF_USERINFO, _userinfo);
    return true;
}

Err Uri::requestAddrInfo(std::string & host, int & port, AddrFlags flags) const
{
    if (isHost() == false) {
        tDLogE("Uri::requestAddrInfo() Unknown host: {}", _uri);
        return Err::E_ILLSTATE;
    }

    if (isPort() == false && isSchema() == false) {
        tDLogE("Uri::requestAddrInfo() Unknown schema or port: {}", _uri);
        return Err::E_ILLSTATE;
    }

    std::string const HOST    = getHost();
    std::string const SERVICE = isSchema() ? getSchema() : std::string();

    assert(HOST.empty() == false);

    uvpp::Loop loop;
    uvpp::DnsAddrInfo addr;

    Err const REQUEST_RESULT = addr.requestAddrInfoWithSync(loop, HOST, SERVICE);
    if (REQUEST_RESULT != Err::E_SUCCESS) {
        return REQUEST_RESULT;
    }

    uvpp::DnsAddrInfo::FindFlag find_flag;
    if (flags == AddrFlags::MOST_IPV6) {
        find_flag = uvpp::DnsAddrInfo::FindFlag::MOST_IPV6;
    } else {
        find_flag = uvpp::DnsAddrInfo::FindFlag::MOST_IPV4;
    }

    auto * info = addr.findSockAddr(find_flag);
    if (info == nullptr) {
        info = addr.findFirst();
        if (info == nullptr) {
            return Err::E_ENFOUND;
        }
    }

    host = uvpp::getIpName(info);
    if (isPort()) {
        port = getPortNumber();
    } else {
        assert(SERVICE.empty() == false);
        port = uvpp::getPortNumber(info);
    }

    return Err::E_SUCCESS;
}

// ---------------
// Static methods.
// ---------------

std::string Uri::getFieldString(std::string const & original, FieldInfo const & info)
{
    return original.substr(info.offset, info.length);
}

} // namespace network

// --------------------
NAMESPACE_LIBTBAG_CLOSE
// --------------------

<|endoftext|>


<commit_before>#ifndef GAMELIB_PROPCOMPONENT_HPP
#define GAMELIB_PROPCOMPONENT_HPP

#include "PropType.hpp"

namespace gamelib
{
    class Component;
    class Entity;
    class PropertyContainer;

    class PropComponent : public PropType<0xe73dee69, Component*>
    {
        public:
            bool loadFromJson(const PropertyHandle& prop, Component** ptr, const Json::Value& node) const;
            void writeToJson(const PropertyHandle& prop, Component* const* ptr, Json::Value& node) const;
            bool drawGui(const PropertyHandle& prop, const std::string& name, Component** ptr) const;

            static Entity* getEntity(const PropertyHandle& prop);
    };

    extern PropComponent propComponent;

    template <typename T, typename U>
    using ComponentPropSetter = NicePropSetterCallback<T*, U>;

    namespace detail
    {
        template <typename T, typename = int>
        struct has_name : std::false_type { };

        template <typename T>
        struct has_name<T, decltype((void) T::name, 0)> : std::true_type { };
    }

    template <typename T, typename U>
    void registerProperty(PropertyContainer& props, const std::string& name, T*& prop, U& self, ComponentPropSetter<T, U> setter, unsigned int filter, int max = 0, const char* const* filternames = nullptr);

    template <typename T, typename U, typename std::enable_if<detail::has_name<T>::value, int>::type = 0>
    void registerProperty(PropertyContainer& props, const std::string& name, T*& prop, U& self, ComponentPropSetter<T, U> setter = nullptr)
    {
        static constexpr const char* hints[] = { T::name };
        registerProperty(props, name, prop, self, setter, 0, 1, hints);
    }

    template <typename T, typename U, typename std::enable_if<!detail::has_name<T>::value, int>::type = 0>
    void registerProperty(PropertyContainer& props, const std::string& name, T*& prop, U& self, ComponentPropSetter<T, U> setter = nullptr)
    {
        registerProperty(props, name, prop, self, setter, T::id);
    }
}

#include "Property.hpp"

namespace gamelib
{
    template <typename T, typename U>
    void registerProperty(PropertyContainer& props, const std::string& name, T*& prop, U& self, ComponentPropSetter<T, U> setter, unsigned int filter, int max, const char* const* filternames)
    {
        static_assert(std::is_base_of<Component, T>(), "Not a component");
        static_assert(std::is_base_of<Component, U>(), "Callback data must be the calling component or the component to search in");
        props.registerProperty(name, prop, setter, &self, &propComponent, filter, max, filternames);
    }
}

#endif
<commit_msg>Add overload to support raw Component* pointers<commit_after>#ifndef GAMELIB_PROPCOMPONENT_HPP
#define GAMELIB_PROPCOMPONENT_HPP

#include "PropType.hpp"

namespace gamelib
{
    class Component;
    class Entity;
    class PropertyContainer;

    class PropComponent : public PropType<0xe73dee69, Component*>
    {
        public:
            bool loadFromJson(const PropertyHandle& prop, Component** ptr, const Json::Value& node) const;
            void writeToJson(const PropertyHandle& prop, Component* const* ptr, Json::Value& node) const;
            bool drawGui(const PropertyHandle& prop, const std::string& name, Component** ptr) const;

            static Entity* getEntity(const PropertyHandle& prop);
    };

    extern PropComponent propComponent;

    template <typename T, typename U>
    using ComponentPropSetter = NicePropSetterCallback<T*, U>;

    namespace detail
    {
        class general_ {};
        class special_ : public general_ {};

        template <typename T>
        constexpr bool has_name(general_) { return false; };

        template <typename T, typename = decltype(T::name)>
        constexpr bool has_name(special_) { return true; };

        template <typename T>
        constexpr bool has_name() { return has_name<T>(special_()); }

        template <typename T>
        constexpr bool has_id(general_) { return false; };

        template <typename T, typename = decltype(T::id)>
        constexpr bool has_id(special_) { return true; };

        template <typename T>
        constexpr bool has_id() { return has_id<T>(special_()); }
    }

    template <typename T, typename U>
    void registerProperty(PropertyContainer& props, const std::string& name, T*& prop, U& self, NicePropSetterCallback<T*, U> setter, unsigned int filter, int max = 0, const char* const* filternames = nullptr);

    template <typename T, typename U, typename std::enable_if<detail::has_name<T>(), int>::type = 0>
    void registerProperty(PropertyContainer& props, const std::string& name, T*& prop, U& self, NicePropSetterCallback<T*, U> setter = nullptr)
    {
        static constexpr const char* hints[] = { T::name };
        registerProperty(props, name, prop, self, setter, 0, 1, hints);
    }

    template <typename T, typename U, typename std::enable_if<!detail::has_name<T>() && detail::has_id<T>(), int>::type = 0>
    void registerProperty(PropertyContainer& props, const std::string& name, T*& prop, U& self, NicePropSetterCallback<T*, U> setter = nullptr)
    {
        registerProperty(props, name, prop, self, setter, T::id);
    }

    template <typename T, typename U, typename std::enable_if<!detail::has_id<T>(), int>::type = 0>
    void registerProperty(PropertyContainer& props, const std::string& name, T*& prop, U& self, NicePropSetterCallback<T*, U> setter = nullptr)
    {
        registerProperty(props, name, prop, self, setter, 0);
    }
}

#include "Property.hpp"

namespace gamelib
{
    template <typename T, typename U>
    void registerProperty(PropertyContainer& props, const std::string& name, T*& prop, U& self, NicePropSetterCallback<T*, U> setter, unsigned int filter, int max, const char* const* filternames)
    {
        static_assert(std::is_base_of<Component, T>(), "Not a component");
        static_assert(std::is_base_of<Component, U>(), "Callback data must be the calling component or the component to search in");
        props.registerProperty(name, prop, setter, &self, &propComponent, filter, max, filternames);
    }
}

#endif
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2001 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. 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.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache\@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
 * ITS 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.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation, and was
 * originally based on software copyright (c) 2001, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

/*
 * $Log$
 * Revision 1.6  2003/07/31 17:07:33  peiyongz
 * Grammar embed grammar description
 *
 * Revision 1.5  2003/05/15 18:48:27  knoaman
 * Partial implementation of the configurable memory manager.
 *
 * Revision 1.4  2002/11/04 14:54:58  tng
 * C++ Namespace Support.
 *
 * Revision 1.3  2002/07/11 18:17:43  knoaman
 * Grammar caching/preparsing - initial implementation.
 *
 * Revision 1.2  2002/07/05 17:08:10  tng
 * [Bug 10119] Grammar::getGrammarType need a const modifier
 *
 * Revision 1.1.1.1  2002/02/01 22:22:38  peiyongz
 * sane_include
 *
 * Revision 1.6  2001/09/14 14:50:22  tng
 * Schema: Fix some wildcard bugs, and some retrieving qualified/unqualified element decl problems.
 *
 * Revision 1.5  2001/05/28 20:56:18  tng
 * Schema: Move getTargetNamespace as virtual function in base class Grammar
 *
 * Revision 1.4  2001/05/11 13:27:18  tng
 * Copyright update.
 *
 * Revision 1.3  2001/05/03 20:34:40  tng
 * Schema: SchemaValidator update
 *
 * Revision 1.2  2001/04/19 18:17:31  tng
 * Schema: SchemaValidator update, and use QName in Content Model
 *
 * Revision 1.1  2001/03/21 21:56:27  tng
 * Schema: Add Schema Grammar, Schema Validator, and split the DTDValidator into DTDValidator, DTDScanner, and DTDGrammar.
 *
 */

#if !defined(GRAMMAR_HPP)
#define GRAMMAR_HPP

#include <xercesc/framework/XMLElementDecl.hpp>
#include <xercesc/framework/XMLEntityDecl.hpp>
#include <xercesc/framework/XMLNotationDecl.hpp>

XERCES_CPP_NAMESPACE_BEGIN

class XMLGrammarDescription;

//
// This abstract class specifies the interface for a Grammar
//

class VALIDATORS_EXPORT Grammar : public XMemory
{
public:

    // -----------------------------------------------------------------------
    //  Class Specific Types
    //
    //  DTDGrammarType    - Indicate this Grammar is built from a DTD.
    //  SchemaGrammarType - Indicate this Grammar is built from a Schema.
    //
    //  TOP_LEVEL_SCOPE - outermost scope level (i.e. global) of a declaration.
    //                    For DTD, all element decls and attribute decls always
    //                    have TOP_LEVEL_SCOPE.  For schema, it may varies if
    //                    it is inside a complex type.
    //
    //  UNKNOWN_SCOPE   - unknown scope level.  None of the decls should have this.
    //
    // -----------------------------------------------------------------------
    enum GrammarType {
        DTDGrammarType
      , SchemaGrammarType
    };

    enum {
         UNKNOWN_SCOPE = -2
       , TOP_LEVEL_SCOPE = -1
    };

    // -----------------------------------------------------------------------
    //  Constructors and Destructor
    // -----------------------------------------------------------------------
    virtual ~Grammar(){};

    // -----------------------------------------------------------------------
    //  Virtual Getter methods
    // -----------------------------------------------------------------------
    virtual GrammarType getGrammarType() const =0;
    virtual const XMLCh* getTargetNamespace() const =0;
    virtual bool getValidated() const = 0;

    // Element Decl
    virtual XMLElementDecl* findOrAddElemDecl
    (
        const   unsigned int    uriId
        , const XMLCh* const    baseName
        , const XMLCh* const    prefixName
        , const XMLCh* const    qName
        , unsigned int          scope
        ,       bool&           wasAdded
    ) = 0;

    virtual unsigned int getElemId
    (
        const   unsigned int    uriId
        , const XMLCh* const    baseName
        , const XMLCh* const    qName
        , unsigned int          scope
    )   const = 0;

    virtual const XMLElementDecl* getElemDecl
    (
        const   unsigned int    uriId
        , const XMLCh* const    baseName
        , const XMLCh* const    qName
        , unsigned int          scope
    )   const = 0;

    virtual XMLElementDecl* getElemDecl
    (
        const   unsigned int    uriId
        , const XMLCh* const    baseName
        , const XMLCh* const    qName
        , unsigned int          scope
    ) = 0;

    virtual const XMLElementDecl* getElemDecl
    (
        const   unsigned int    elemId
    )   const = 0;

    virtual XMLElementDecl* getElemDecl
    (
        const   unsigned int    elemId
    ) = 0;

    // Notation
    virtual const XMLNotationDecl* getNotationDecl
    (
        const   XMLCh* const    notName
    )   const=0;

    virtual XMLNotationDecl* getNotationDecl
    (
        const   XMLCh* const    notName
    )=0;

    // -----------------------------------------------------------------------
    //  Virtual Setter methods
    // -----------------------------------------------------------------------
    virtual XMLElementDecl* putElemDecl
    (
        const   unsigned int    uriId
        , const XMLCh* const    baseName
        , const XMLCh* const    prefixName
        , const XMLCh* const    qName
        , unsigned int          scope
        , const bool            notDeclared = false
    ) = 0;

    virtual unsigned int putElemDecl
    (
        XMLElementDecl* const elemDecl
        , const bool          notDeclared = false
    )   const = 0;

    virtual unsigned int putNotationDecl
    (
        XMLNotationDecl* const notationDecl
    )   const=0;

    virtual void setValidated(const bool newState) = 0;

    // -----------------------------------------------------------------------
    //  Virtual methods
    // -----------------------------------------------------------------------
    virtual void reset()=0;

    virtual void                    setGrammarDescription( XMLGrammarDescription*) = 0;
    virtual XMLGrammarDescription*  getGrammarDescription() const = 0;

protected :
    // -----------------------------------------------------------------------
    //  Hidden constructors
    // -----------------------------------------------------------------------
    Grammar(){};

};

XERCES_CPP_NAMESPACE_END

#endif
<commit_msg>change Grammar::putElemDecl(XMLElementDecl, bool) so that it does not require the Grammar object to be const.  Also, mark findOrAddGrammar as being dangerous in multithreaded situations<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2001 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. 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.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache\@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
 * ITS 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.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation, and was
 * originally based on software copyright (c) 2001, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

/*
 * $Log$
 * Revision 1.7  2003/09/22 19:47:14  neilg
 * change Grammar::putElemDecl(XMLElementDecl, bool) so that it does not require the Grammar object to be const.  Also, mark findOrAddGrammar as being dangerous in multithreaded situations
 *
 * Revision 1.6  2003/07/31 17:07:33  peiyongz
 * Grammar embed grammar description
 *
 * Revision 1.5  2003/05/15 18:48:27  knoaman
 * Partial implementation of the configurable memory manager.
 *
 * Revision 1.4  2002/11/04 14:54:58  tng
 * C++ Namespace Support.
 *
 * Revision 1.3  2002/07/11 18:17:43  knoaman
 * Grammar caching/preparsing - initial implementation.
 *
 * Revision 1.2  2002/07/05 17:08:10  tng
 * [Bug 10119] Grammar::getGrammarType need a const modifier
 *
 * Revision 1.1.1.1  2002/02/01 22:22:38  peiyongz
 * sane_include
 *
 * Revision 1.6  2001/09/14 14:50:22  tng
 * Schema: Fix some wildcard bugs, and some retrieving qualified/unqualified element decl problems.
 *
 * Revision 1.5  2001/05/28 20:56:18  tng
 * Schema: Move getTargetNamespace as virtual function in base class Grammar
 *
 * Revision 1.4  2001/05/11 13:27:18  tng
 * Copyright update.
 *
 * Revision 1.3  2001/05/03 20:34:40  tng
 * Schema: SchemaValidator update
 *
 * Revision 1.2  2001/04/19 18:17:31  tng
 * Schema: SchemaValidator update, and use QName in Content Model
 *
 * Revision 1.1  2001/03/21 21:56:27  tng
 * Schema: Add Schema Grammar, Schema Validator, and split the DTDValidator into DTDValidator, DTDScanner, and DTDGrammar.
 *
 */

#if !defined(GRAMMAR_HPP)
#define GRAMMAR_HPP

#include <xercesc/framework/XMLElementDecl.hpp>
#include <xercesc/framework/XMLEntityDecl.hpp>
#include <xercesc/framework/XMLNotationDecl.hpp>

XERCES_CPP_NAMESPACE_BEGIN

class XMLGrammarDescription;

//
// This abstract class specifies the interface for a Grammar
//

class VALIDATORS_EXPORT Grammar : public XMemory
{
public:

    // -----------------------------------------------------------------------
    //  Class Specific Types
    //
    //  DTDGrammarType    - Indicate this Grammar is built from a DTD.
    //  SchemaGrammarType - Indicate this Grammar is built from a Schema.
    //
    //  TOP_LEVEL_SCOPE - outermost scope level (i.e. global) of a declaration.
    //                    For DTD, all element decls and attribute decls always
    //                    have TOP_LEVEL_SCOPE.  For schema, it may varies if
    //                    it is inside a complex type.
    //
    //  UNKNOWN_SCOPE   - unknown scope level.  None of the decls should have this.
    //
    // -----------------------------------------------------------------------
    enum GrammarType {
        DTDGrammarType
      , SchemaGrammarType
    };

    enum {
         UNKNOWN_SCOPE = -2
       , TOP_LEVEL_SCOPE = -1
    };

    // -----------------------------------------------------------------------
    //  Constructors and Destructor
    // -----------------------------------------------------------------------
    virtual ~Grammar(){};

    // -----------------------------------------------------------------------
    //  Virtual Getter methods
    // -----------------------------------------------------------------------
    virtual GrammarType getGrammarType() const =0;
    virtual const XMLCh* getTargetNamespace() const =0;
    virtual bool getValidated() const = 0;

    // Element Decl

    // this method should only be used while the grammar is being
    // constructed, not while it is being used
    // in a validation episode!
    virtual XMLElementDecl* findOrAddElemDecl
    (
        const   unsigned int    uriId
        , const XMLCh* const    baseName
        , const XMLCh* const    prefixName
        , const XMLCh* const    qName
        , unsigned int          scope
        ,       bool&           wasAdded
    ) = 0;

    virtual unsigned int getElemId
    (
        const   unsigned int    uriId
        , const XMLCh* const    baseName
        , const XMLCh* const    qName
        , unsigned int          scope
    )   const = 0;

    virtual const XMLElementDecl* getElemDecl
    (
        const   unsigned int    uriId
        , const XMLCh* const    baseName
        , const XMLCh* const    qName
        , unsigned int          scope
    )   const = 0;

    virtual XMLElementDecl* getElemDecl
    (
        const   unsigned int    uriId
        , const XMLCh* const    baseName
        , const XMLCh* const    qName
        , unsigned int          scope
    ) = 0;

    virtual const XMLElementDecl* getElemDecl
    (
        const   unsigned int    elemId
    )   const = 0;

    virtual XMLElementDecl* getElemDecl
    (
        const   unsigned int    elemId
    ) = 0;

    // Notation
    virtual const XMLNotationDecl* getNotationDecl
    (
        const   XMLCh* const    notName
    )   const=0;

    virtual XMLNotationDecl* getNotationDecl
    (
        const   XMLCh* const    notName
    )=0;

    // -----------------------------------------------------------------------
    //  Virtual Setter methods
    // -----------------------------------------------------------------------
    virtual XMLElementDecl* putElemDecl
    (
        const   unsigned int    uriId
        , const XMLCh* const    baseName
        , const XMLCh* const    prefixName
        , const XMLCh* const    qName
        , unsigned int          scope
        , const bool            notDeclared = false
    ) = 0;

    virtual unsigned int putElemDecl
    (
        XMLElementDecl* const elemDecl
        , const bool          notDeclared = false
    )   = 0;

    virtual unsigned int putNotationDecl
    (
        XMLNotationDecl* const notationDecl
    )   const=0;

    virtual void setValidated(const bool newState) = 0;

    // -----------------------------------------------------------------------
    //  Virtual methods
    // -----------------------------------------------------------------------
    virtual void reset()=0;

    virtual void                    setGrammarDescription( XMLGrammarDescription*) = 0;
    virtual XMLGrammarDescription*  getGrammarDescription() const = 0;

protected :
    // -----------------------------------------------------------------------
    //  Hidden constructors
    // -----------------------------------------------------------------------
    Grammar(){};

};

XERCES_CPP_NAMESPACE_END

#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: xmlDataSourceSetting.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 14:03:39 $
 *
 *  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
 *
 ************************************************************************/
#ifndef DBA_XMLDATASOURCESETTING_HXX
#define DBA_XMLDATASOURCESETTING_HXX

#ifndef _XMLOFF_XMLICTXT_HXX
#include <xmloff/xmlictxt.hxx>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif

namespace dbaxml
{
    class ODBFilter;
    class OXMLDataSource;
    class OXMLDataSourceSetting : public SvXMLImportContext
    {
        ::com::sun::star::beans::PropertyValue m_aSetting;
        ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any> m_aInfoSequence;
        OXMLDataSource& m_rParent;
        OXMLDataSourceSetting* m_pContainer;
        ::com::sun::star::uno::Type m_aPropType;            // the type of the property the instance imports currently
        sal_Bool m_bIsList;

        ODBFilter& GetOwnImport();
        ::com::sun::star::uno::Any convertString(const ::com::sun::star::uno::Type& _rExpectedType, const ::rtl::OUString& _rReadCharacters);
    public:

        OXMLDataSourceSetting( ODBFilter& rImport, sal_uInt16 nPrfx,
                    const ::rtl::OUString& rLName,
                    const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList
                    ,OXMLDataSource& _rParent
                    ,OXMLDataSourceSetting* _pContainer = NULL);
        virtual ~OXMLDataSourceSetting();

        virtual SvXMLImportContext *CreateChildContext( sal_uInt16 nPrefix,
                    const ::rtl::OUString& rLocalName,
                    const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList );

        virtual void EndElement();

        virtual void Characters( const ::rtl::OUString& rChars );

        /** adds value to property
            @param  _sValue
                The value to add.
        */
        void addValue(const ::rtl::OUString& _sValue);
    };
// -----------------------------------------------------------------------------
} // namespace dbaxml
// -----------------------------------------------------------------------------

#endif // DBA_XMLDATASOURCESETTING_HXX
<commit_msg>INTEGRATION: CWS dbodf12import (1.4.350); FILE MERGED 2007/11/01 09:13:31 oj 1.4.350.1: #i83190# implement odf12 importer<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: xmlDataSourceSetting.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2007-11-09 08:15:16 $
 *
 *  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
 *
 ************************************************************************/
#ifndef DBA_XMLDATASOURCESETTING_HXX
#define DBA_XMLDATASOURCESETTING_HXX

#ifndef _XMLOFF_XMLICTXT_HXX
#include <xmloff/xmlictxt.hxx>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif

namespace dbaxml
{
    class ODBFilter;
    class OXMLDataSource;
    class OXMLDataSourceSetting : public SvXMLImportContext
    {
        ::com::sun::star::beans::PropertyValue m_aSetting;
        ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any> m_aInfoSequence;
        OXMLDataSourceSetting* m_pContainer;
        ::com::sun::star::uno::Type m_aPropType;            // the type of the property the instance imports currently
        sal_Bool m_bIsList;

        ODBFilter& GetOwnImport();
        ::com::sun::star::uno::Any convertString(const ::com::sun::star::uno::Type& _rExpectedType, const ::rtl::OUString& _rReadCharacters);
    public:

        OXMLDataSourceSetting( ODBFilter& rImport, sal_uInt16 nPrfx,
                    const ::rtl::OUString& rLName,
                    const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList
                    ,OXMLDataSourceSetting* _pContainer = NULL);
        virtual ~OXMLDataSourceSetting();

        virtual SvXMLImportContext *CreateChildContext( sal_uInt16 nPrefix,
                    const ::rtl::OUString& rLocalName,
                    const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList );

        virtual void EndElement();

        virtual void Characters( const ::rtl::OUString& rChars );

        /** adds value to property
            @param  _sValue
                The value to add.
        */
        void addValue(const ::rtl::OUString& _sValue);
    };
// -----------------------------------------------------------------------------
} // namespace dbaxml
// -----------------------------------------------------------------------------

#endif // DBA_XMLDATASOURCESETTING_HXX
<|endoftext|>


<commit_before>/* mockturtle: C++ logic network library
 * Copyright (C) 2018  EPFL
 *
 * 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.
 */

/*!
  \file reconv_cut.hpp
  \brief Reconvergence-driven cut

  \author Heinz Riener
*/

#pragma once

#include <algorithm>
#include <cassert>

#include "../traits.hpp"

namespace mockturtle
{

/*! \brief Parameters for reconvergence_driven_cut.
 *
 * The data structure `reconv_cut_params` holds configurable parameters
 * with default arguments for `reconv_cut`.
 */
struct reconv_cut_params
{
  /*! \brief Maximum number of leaves for a cut. */
  uint32_t cut_size{10u};
};

/*! \cond PRIVATE */
namespace detail
{
template<typename Ntk>
class compute_reconvergence_driven_cut_impl
{
public:
  explicit compute_reconvergence_driven_cut_impl( Ntk const &ntk, node<Ntk> const& pivot, reconv_cut_params const& ps )
    : _ntk( ntk )
    , _pivot( pivot )
    , _ps( ps )
  {}

public:
  std::vector<node<Ntk>> run()
  {
    _ntk.clear_values();

    std::vector<node<Ntk>> cut = { _pivot };
    _ntk.set_value( _pivot, 1 );
    compute_cut_recur( cut );
    return cut;
  }

protected:
  void compute_cut_recur( std::vector<node<Ntk>>& cut )
  {
    assert( cut.size() <= _ps.cut_size && "cut-size overflow" );
    std::sort( cut.begin(), cut.end(), [this]( node<Ntk> const& a, node<Ntk> const& b ){ return cost( a ) < cost( b ); } );

    /* find the first non-pi node to extend the cut (because the vector is sorted, the non-pi is cost-minimal) */
    auto const it = std::find_if( cut.begin(), cut.end(), [&]( auto const& node ){ return !_ntk.is_pi( node ); } );
    if ( cut.end() == it )
    {
      /* if all nodes are pis, then the cut cannot be extended */
      return;
    }

    /* the cost is identical to the number of nodes added to the cut if *it is used to expand the cut */
    auto const c = cost( *it );
    if( cut.size() + c > _ps.cut_size )
    {
      /* if the expansion exceeds the cut_size, then the cut cannot be extended */
      return;
    }

    /* otherwise expand the cut with the children of *it and mark *it visited */
    const auto n = *it;
    cut.erase( it );
    _ntk.foreach_fanin( n, [&]( signal<Ntk> const& s ){
        auto const& child = _ntk.get_node( s );
        if ( !_ntk.is_constant( n ) && std::find( cut.begin(), cut.end(), child ) == cut.end() && !_ntk.value( child ) )
        {
          cut.push_back( child );
          _ntk.set_value( child, 1 );
        }
      } );

    compute_cut_recur( cut );
  }

  inline int32_t cost( node<Ntk> const& n ) const
  {
    int32_t current_cost = -1;
    _ntk.foreach_fanin( n, [&]( signal<Ntk> const& s ){
        auto const& child = _ntk.get_node( s );
        if ( !_ntk.is_constant( child ) && !_ntk.value( child ) )
        {
          ++current_cost;
        }
      } );
    return current_cost;
  }

private:
  Ntk const& _ntk;
  node<Ntk> const& _pivot;
  reconv_cut_params const& _ps;
};
} /* namespace detail */
/*! \endcond */

/*! \brief reconv_cut
 *
 * This class implements a generation algorithm for
 * reconvergence-driven cuts.  The cut grows towards the primary
 * inputs starting from a pivot node.
 *
 * **Required network functions:**
 * - `is_constant`
 * - `is_pi`
 * - `clear_values`
 * - `set_value`
 * - `value`
 * - `get_node`
 * - `foreach_fanin`
 *
 */
struct reconv_cut
{
public:
  explicit reconv_cut( reconv_cut_params const& ps = {} )
    : _ps( ps )
  {}

  template<typename Ntk>
  std::vector<node<Ntk>> operator()( Ntk const& ntk, node<Ntk> const& pivot )
  {
    static_assert( is_network_type_v<Ntk>, "Ntk is not a network type" );
    static_assert( has_is_constant_v<Ntk>, "Ntk does not implement the is_constant method" );
    static_assert( has_is_pi_v<Ntk>, "Ntk does not implement the is_pi method" );
    static_assert( has_clear_values_v<Ntk>, "Ntk does not implement the is_pi method" );
    static_assert( has_set_value_v<Ntk>, "Ntk does not implement the is_pi method" );
    static_assert( has_value_v<Ntk>, "Ntk does not implement the is_pi method" );
    static_assert( has_get_node_v<Ntk>, "Ntk does not implement the is_pi method" );
    static_assert( has_foreach_fanin_v<Ntk>, "Ntk does not implement the is_pi method" );

    detail::compute_reconvergence_driven_cut_impl cut_generator( ntk, pivot, _ps );

    return cut_generator.run();
  }

private:
  reconv_cut_params _ps;
};

} /* namespace mockturtle */
<commit_msg>reconvergence-driven cut: multiple pivots.<commit_after>/* mockturtle: C++ logic network library
 * Copyright (C) 2018  EPFL
 *
 * 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.
 */

/*!
  \file reconv_cut.hpp
  \brief Reconvergence-driven cut

  \author Heinz Riener
*/

#pragma once

#include <algorithm>
#include <cassert>

#include "../traits.hpp"

namespace mockturtle
{

/*! \brief Parameters for reconvergence_driven_cut.
 *
 * The data structure `reconv_cut_params` holds configurable parameters
 * with default arguments for `reconv_cut`.
 */
struct reconv_cut_params
{
  /*! \brief Maximum number of leaves for a cut. */
  uint32_t cut_size{10u};
};

/*! \cond PRIVATE */
namespace detail
{
template<typename Ntk>
class compute_reconvergence_driven_cut_impl
{
public:
  explicit compute_reconvergence_driven_cut_impl( Ntk const &ntk, std::vector<node<Ntk>> const& pivots, reconv_cut_params const& ps )
    : _ntk( ntk )
    , _pivots( pivots )
    , _ps( ps )
  {
    assert( _pivots.size() > 0 );
  }

public:
  std::vector<node<Ntk>> run()
  {
    _ntk.clear_values();
    std::vector<node<Ntk>> cut( _pivots );
    for ( const auto& p : _pivots )
    {
      _ntk.set_value( p, 1 );
    }
    compute_cut_recur( cut );
    return cut;
  }

protected:
  void compute_cut_recur( std::vector<node<Ntk>>& cut )
  {
    assert( cut.size() <= _ps.cut_size && "cut-size overflow" );
    std::sort( cut.begin(), cut.end(), [this]( node<Ntk> const& a, node<Ntk> const& b ){ return cost( a ) < cost( b ); } );

    /* find the first non-pi node to extend the cut (because the vector is sorted, the non-pi is cost-minimal) */
    auto const it = std::find_if( cut.begin(), cut.end(), [&]( auto const& node ){ return !_ntk.is_pi( node ); } );
    if ( cut.end() == it )
    {
      /* if all nodes are pis, then the cut cannot be extended */
      return;
    }

    /* the cost is identical to the number of nodes added to the cut if *it is used to expand the cut */
    auto const c = cost( *it );
    if( cut.size() + c > _ps.cut_size )
    {
      /* if the expansion exceeds the cut_size, then the cut cannot be extended */
      return;
    }

    /* otherwise expand the cut with the children of *it and mark *it visited */
    const auto n = *it;
    cut.erase( it );
    _ntk.foreach_fanin( n, [&]( signal<Ntk> const& s ){
        auto const& child = _ntk.get_node( s );
        if ( !_ntk.is_constant( n ) && std::find( cut.begin(), cut.end(), child ) == cut.end() && !_ntk.value( child ) )
        {
          cut.push_back( child );
          _ntk.set_value( child, 1 );
        }
      } );

    compute_cut_recur( cut );
  }

  inline int32_t cost( node<Ntk> const& n ) const
  {
    int32_t current_cost = -1;
    _ntk.foreach_fanin( n, [&]( signal<Ntk> const& s ){
        auto const& child = _ntk.get_node( s );
        if ( !_ntk.is_constant( child ) && !_ntk.value( child ) )
        {
          ++current_cost;
        }
      } );
    return current_cost;
  }

private:
  Ntk const& _ntk;
  std::vector<node<Ntk>> _pivots;
  reconv_cut_params const& _ps;
};
} /* namespace detail */
/*! \endcond */

/*! \brief reconv_cut
 *
 * This class implements a generation algorithm for
 * reconvergence-driven cuts.  The cut grows towards the primary
 * inputs starting from a pivot node.
 *
 * **Required network functions:**
 * - `is_constant`
 * - `is_pi`
 * - `clear_values`
 * - `set_value`
 * - `value`
 * - `get_node`
 * - `foreach_fanin`
 *
 */
struct reconv_cut
{
public:
  explicit reconv_cut( reconv_cut_params const& ps = {} )
    : _ps( ps )
  {}

  template<typename Ntk>
  std::vector<node<Ntk>> operator()( Ntk const& ntk, node<Ntk> const& pivot )
  {
    static_assert( is_network_type_v<Ntk>, "Ntk is not a network type" );
    static_assert( has_is_constant_v<Ntk>, "Ntk does not implement the is_constant method" );
    static_assert( has_is_pi_v<Ntk>, "Ntk does not implement the is_pi method" );
    static_assert( has_clear_values_v<Ntk>, "Ntk does not implement the is_pi method" );
    static_assert( has_set_value_v<Ntk>, "Ntk does not implement the is_pi method" );
    static_assert( has_value_v<Ntk>, "Ntk does not implement the is_pi method" );
    static_assert( has_get_node_v<Ntk>, "Ntk does not implement the is_pi method" );
    static_assert( has_foreach_fanin_v<Ntk>, "Ntk does not implement the is_pi method" );

    detail::compute_reconvergence_driven_cut_impl cut_generator( ntk, { pivot }, _ps );

    return cut_generator.run();
  }

  template<typename Ntk>
  std::vector<node<Ntk>> operator()( Ntk const& ntk, std::vector<node<Ntk>> const& pivots )
  {
    assert( pivots.size() > 0u && "pivots must not be empty");

    static_assert( is_network_type_v<Ntk>, "Ntk is not a network type" );
    static_assert( has_is_constant_v<Ntk>, "Ntk does not implement the is_constant method" );
    static_assert( has_is_pi_v<Ntk>, "Ntk does not implement the is_pi method" );
    static_assert( has_clear_values_v<Ntk>, "Ntk does not implement the is_pi method" );
    static_assert( has_set_value_v<Ntk>, "Ntk does not implement the is_pi method" );
    static_assert( has_value_v<Ntk>, "Ntk does not implement the is_pi method" );
    static_assert( has_get_node_v<Ntk>, "Ntk does not implement the is_pi method" );
    static_assert( has_foreach_fanin_v<Ntk>, "Ntk does not implement the is_pi method" );

    detail::compute_reconvergence_driven_cut_impl cut_generator( ntk, pivots, _ps );

    return cut_generator.run();
  }

private:
  reconv_cut_params _ps;
};

} /* namespace mockturtle */
<|endoftext|>