<commit_before>/*
    Author : David Barnett
    Date   : 03-10-2013
    License: MIT License
*/
#include "Settings.h"

#include <iosfwd>
#include <iostream>

using namespace IO;

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sstream>
#include <algorithm>
#include <iterator>
#include "../etc/string.h"

//#define SETTINGS_VERBOSE

Settings::Settings() {
    this->loading_flag = SETTING_LOAD_NOTHING;
}

Settings::Settings(SettingsLoadFlags flag)
{
    this->loading_flag = flag;
}

Settings::~Settings()
{
    this->stored_settings.clear();
}

/**
 * @brief removes all currently loaded settings
 */
void Settings::clear()
{
    this->stored_settings.clear();
}

/**
 * @brief Checks if a given setting exists, and loads it if flags permit
 * @param header section header
 * @param key name of the setting to be accessed
 * @return true on exists
 */
bool Settings::exists (std::string header ,std::string  key)
{
    if (this->exists(header))
    {
        INISection* section = &(this->stored_settings[header]);
        if (section->loaded) {
            return section->properties.find(key) != section->properties.end();
        } else {
            //Load Header's properties?
            if ( this->loading_flag == SETTING_LOAD_ON_REQUEST ) {
                this->load_section ( header , SETTINGS_DUPLICATES_INGORED );
                return this->exists ( header , key);
            } else {
                return false;
            }
        }
    } else {
        return false;
    }
}

/**
 * @brief Checks if a header exits
 * @param header Name of section
 * @return true on success
 */
bool Settings::exists (std::string header)
{
    return this->stored_settings.find(header) != this->stored_settings.end();
}

/**
 * @brief Loads settings from a file
 * @param file_name
 * @param flag
 */
void Settings::load(std::string file_name , SettingsDuplicateFlags flag)
{
<<<<<<< HEAD
#ifdef SETTINGS_VERBOSE
=======
#ifdef SETTINGS_VERBOOSE
>>>>>>> 86e3c99... Settings Fix
    std::cout << "Loading " << file_name << std::endl;
#endif
    std::fstream file;
    file.open(file_name.c_str());
    this->file_name = file_name;
    //Check if the file is open
    if (!(file.is_open()))
    {
        return;
    }

    //Seek to the beginning of the file
    file.seekg( 0 , file.beg );
    file.peek();

    //Calculate the offset from the 1st byte to the 0th element
    int sys_error = file.tellg();
    file.seekg( 0, file.end );
    int file_size = (int)file.tellg();
    file.seekg( 0, file.beg );

    std::string line;
    INISection section;
    section.header_name = "";
    section.loaded = false;
    section.start_index = 0;
<<<<<<< HEAD
#ifdef SETTINGS_VERBOSE
=======
#ifdef SETTINGS_VERBOOSE
>>>>>>> 86e3c99... Settings Fix
    std::cout << "sys error is " << sys_error << " Pos " << file.tellg() << std::endl;
    std::cout << "root  S:" << section.start_index;
#endif
    while ( ! file.eof() )
    {
        //Get current position with the sys error offset
        int start_pos = (int)(file.tellg()) - sys_error;
        std::getline( file , line );

        if (line.length() == 0)
            continue;

        line = etc::trim(line);

        //Treat lines starting with ; as comments and do not process
        if ( etc::startswith( line , ";" ) )
        {
            continue;
        }
        //Check if the line has the beginning of a section
        if (etc::startswith( line , "[" ) && etc::endswith( line , "]" ))
        {
            //Close last section
            section.end_index = (int)file.tellg();
            this->stored_settings[section.header_name] = section;
<<<<<<< HEAD
#ifdef SETTINGS_VERBOSE
            std::cout << " E:" << section.end_index << std::endl;
#endif

=======
#ifdef SETTINGS_VERBOOSE
            std::cout << " E:" << section.end_index << std::endl;
#endif
>>>>>>> 86e3c99... Settings Fix
            //Refresh section
            section = INISection();
            //Remove the brackets
            section.header_name = line.substr ( 1 , line.size() - 2 );

            if ( this->exists(section.header_name)) {
                //Warning text
                std::cout << "ERROR : Another " << this->file_name << "::" << section.header_name << " has been defined!\nSections will be damaged." << std::endl;
            } else {
                //-2 constant is to correct the position of the start index
                section.start_index = start_pos ;
                section.loaded = false;
                section.properties = SettingsMap();
<<<<<<< HEAD

#ifdef SETTINGS_VERBOSE
            std::cout << section.header_name  << " S:" << section.start_index;
#endif

=======
#ifdef SETTINGS_VERBOOSE
            std::cout << section.header_name  << " S:" << section.start_index;
#endif
>>>>>>> 86e3c99... Settings Fix
            }
            continue;
        }
    }

    section.end_index = file_size;
    this->stored_settings[section.header_name] = section;
<<<<<<< HEAD

#ifdef SETTINGS_VERBOSE
            std::cout << " E:" << section.end_index << std::endl;
#endif

=======
#ifdef SETTINGS_VERBOOSE
            std::cout << " E:" << section.end_index << std::endl;
#endif
>>>>>>> 86e3c99... Settings Fix
    file.close();
}

/**
 * @brief Loads a section's data into memory
 * @param header Section name
 * @param flag Settings Duplicate Flags
 */
void Settings::load_section ( std::string header , SettingsDuplicateFlags flag) {
    std::fstream file;

    if (this->exists(header) == false)
        return;

    INISection* section = &(this->stored_settings[header]);

    file.open( this->file_name.c_str() );
    int file_pos_max = section->end_index;
    //Check if the file is open
    if (!(file.is_open()))
    {
        return;
    }

    //Seek to the beginning of the file
    file.seekg( 0 , file.beg );
    file.peek();

    file.seekg( section->start_index , file.beg );

    bool start = false;
    while ( file.tellg() < file_pos_max && !file.eof() )
    {
        std::string line;
        std::getline ( file, line );
        line = etc::trim ( line );

        if (line == "")
        {
            continue;
        }
        if ( etc::startswith( line , ";" ) )
        {
            continue;
        }
        //Check if the line has the beginning of a section
        if ( etc::startswith( line , "[" ) || etc::endswith( line , "]") )
        {
            std::string header_name = line.substr ( 1 , line.size() - 2 );
            //If another section is in contact, LEAVE NOW
            if (header_name != section->header_name) {
                break;
            } else {
                //Found the start of the section we are looking for
                start = true;
            }
            continue;
        }

        if (start == false)
        {
            continue;
        }

        //Find the equal part of the line
        std::size_t equal_pos = line.find_first_of('=', 0);

        if (equal_pos == line.npos) {
            continue;
        }

        std::string key = etc::trim ( line.substr( 0 , equal_pos ) );
        std::string value = etc::trim ( line.substr( equal_pos + 1  , line.length() - 1 ) );

        if (key == "") {
            continue;
        }

        if ( section->properties.find( key ) !=  section->properties.end() )
        {
            //There is another copy of the key, check if it is OK to override
            if (flag == SETTINGS_DUPLICATES_OVERRIDE)
            {
                section->properties[key] = value;
            }
        }
        else
        {
            section->properties[key] = value;
<<<<<<< HEAD
#ifdef SETTINGS_VERBOSE
=======
#ifdef SETTINGS_VERBOOSE
>>>>>>> 86e3c99... Settings Fix
            std::cout << section->header_name << "::" << key << "=" << value << std::endl;
#endif
        }
    }
    //Update loaded status
    section->loaded = true;
    file.close();

}

/**
 * @brief Unloads a specified section
 * @param header a section name
 */
void Settings::unload_section (std::string header)
{
    if (this->exists(header)) {
        this->stored_settings[header].properties.clear();
        this->stored_settings[header].loaded = false;
    }
}

/**
 * @brief Gets the string of the given setting and copies it into the out string
 * @param header the name of the section
 * @param key the name of setting
 * @param out A string to be written to
 * @return true on successful copy
 */
bool Settings::get (std::string header , std::string  key, std::string* out)
{
    if (this->exists(header ,key))
    {
        *out = this->stored_settings[header].properties[key];
        return true;
    }
    else
    {
        return false;
    }
}

/**
 * @brief Gets the value and converts it to a bool
 * @see Settings::get
 * @param bol Returns the value
 * @return
 */
bool Settings::getBool (std::string header , std::string  key , bool* bol)
{
    std::string b;
    if (this->get(header, key , &b) == false)
        return false;
    b = etc::toLower(b);
    if (b != "")
    {
        *bol = ( b == "true" ? true : false );
        return true;
    }
    else
    {
        return false;
    }
}

bool Settings::getInt (std::string header , std::string  key , int* num)
{
    std::string b;
    if (this->get(header, key , &b) == false)
        return false;

    if ( etc::is_number(b) )
    {
        *num = atoi( b.c_str() );
        return true;
    }
    else
    {
        return false;
    }
}

bool Settings::add (std::string header , std::string key , std::string value)
{
    if (!this->exists(header , key))
    {
        this->stored_settings[header].properties[key] = value;
        return true;
    }
    else
    {
        return false;
    }
}

bool Settings::set (std::string header , std::string key , std::string value)
{
     if (this->exists( header , key ) ) {
        this->stored_settings[header].properties[key] = value;
        return true;
     }
     return false;
}

/**
 * @brief Saves all the sections of a given file
 * @warning Deletes original file and then renames a temp file to replace it
 * @param filename Saves all headers that belong to a file
 * @return bool true on success
 */
bool Settings::save ()
{
    //The File to be read from
    std::ifstream file_in;
    //The File to be written to
    std::fstream file_out;
    //Stream are separate to prevent cross-contamination

    //Open the input file
    file_in.open( this->file_name.c_str() );

    //Check for errors
    if (file_in.is_open() == false) {
        std::cout << "Error input file : " << this->file_name.c_str() << " could not be opened." << std::endl;
        return false;
    }

    //Open the output file
    file_out.open( ("temp~" + this->file_name).c_str() , std::ofstream::out );

    //Check for errors
    if (file_out.is_open() == false) {
        std::cout << "Error output file : " << ("temp~" + this->file_name).c_str() << " could not be opened." << std::endl;
        return false;
    }

    //Go through whole file
    INISection* current_section = &(this->stored_settings[""]);
    while ( file_in.eof() == false )
    {
        std::string line;
        std::getline ( file_in , line );
        line = etc::trim ( line );

        std::size_t equal_pos = line.find_first_of('=', 0);

        if (line == "")
        {

        }
        else if ( etc::startswith( line , ";" ) )
        {

        }
        else if ( etc::startswith( line , "[" ) || etc::endswith( line , "]") )
        {
            //Check if the line has the beginning of a section
            //Update current_section
            if (current_section != nullptr)
            {
                current_section->end_index = file_out.tellg();
            }

            current_section = &( this->stored_settings[ line.substr ( 1 , line.size() - 2 )] );
            current_section->start_index = (int)file_out.tellg() - 1;
        }
        else if (equal_pos != line.npos) {
            std::string key = etc::trim ( line.substr( 0 , equal_pos ) );
            std::string value = current_section->properties[key];
            if (value == "") {
                value = etc::trim ( line.substr( equal_pos + 1  , line.length() - 1 ) );
            }

            file_out << key << '=' << value << std::endl;
            continue;
        }

        //Standard copy line out
        file_out << line << std::endl;
    }

    file_out.close();
    file_in.close();

    //File operations
    //File operation return value
    int file_op = 0;

    //Remove old version
    file_op = std::remove( this->file_name.c_str() );

    //Check if there was an error
    if (file_op != 0) {
        std::cout << "Error while removing the file " << this->file_name.c_str() << std::endl;
        return false;
    }

    //Rename the temp version to replace the deleted version
    file_op = std::rename( ("temp~" + this->file_name).c_str()  , this->file_name.c_str() );

    //Check if there was an error
    if (file_op != 0) {
        std::cout << "Error while renaming the file from " << ("temp~" + this->file_name).c_str() << " to " << this->file_name.c_str() << std::endl;
        return false;
    }

    return true;
}
<commit_msg>Resolved Conflicts <commit_after>/*
    Author : David Barnett
    Date   : 03-10-2013
    License: MIT License
*/
#include "Settings.h"

#include <iosfwd>
#include <iostream>

using namespace IO;

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sstream>
#include <algorithm>
#include <iterator>
#include "../etc/string.h"

//#define SETTINGS_VERBOSE

Settings::Settings() {
    this->loading_flag = SETTING_LOAD_NOTHING;
}

Settings::Settings(SettingsLoadFlags flag)
{
    this->loading_flag = flag;
}

Settings::~Settings()
{
    this->stored_settings.clear();
}

/**
 * @brief removes all currently loaded settings
 */
void Settings::clear()
{
    this->stored_settings.clear();
}

/**
 * @brief Checks if a given setting exists, and loads it if flags permit
 * @param header section header
 * @param key name of the setting to be accessed
 * @return true on exists
 */
bool Settings::exists (std::string header ,std::string  key)
{
    if (this->exists(header))
    {
        INISection* section = &(this->stored_settings[header]);
        if (section->loaded) {
            return section->properties.find(key) != section->properties.end();
        } else {
            //Load Header's properties?
            if ( this->loading_flag == SETTING_LOAD_ON_REQUEST ) {
                this->load_section ( header , SETTINGS_DUPLICATES_INGORED );
                return this->exists ( header , key);
            } else {
                return false;
            }
        }
    } else {
        return false;
    }
}

/**
 * @brief Checks if a header exits
 * @param header Name of section
 * @return true on success
 */
bool Settings::exists (std::string header)
{
    return this->stored_settings.find(header) != this->stored_settings.end();
}

/**
 * @brief Loads settings from a file
 * @param file_name
 * @param flag
 */
void Settings::load(std::string file_name , SettingsDuplicateFlags flag)
{
#ifdef SETTINGS_VERBOSE

    std::cout << "Loading " << file_name << std::endl;
#endif
    std::fstream file;
    file.open(file_name.c_str());
    this->file_name = file_name;
    //Check if the file is open
    if (!(file.is_open()))
    {
        return;
    }

    //Seek to the beginning of the file
    file.seekg( 0 , file.beg );
    file.peek();

    //Calculate the offset from the 1st byte to the 0th element
    int sys_error = file.tellg();
    file.seekg( 0, file.end );
    int file_size = (int)file.tellg();
    file.seekg( 0, file.beg );

    std::string line;
    INISection section;
    section.header_name = "";
    section.loaded = false;
    section.start_index = 0;
#ifdef SETTINGS_VERBOSE

    std::cout << "sys error is " << sys_error << " Pos " << file.tellg() << std::endl;
    std::cout << "root  S:" << section.start_index;
#endif
    while ( ! file.eof() )
    {
        //Get current position with the sys error offset
        int start_pos = (int)(file.tellg()) - sys_error;
        std::getline( file , line );

        if (line.length() == 0)
            continue;

        line = etc::trim(line);

        //Treat lines starting with ; as comments and do not process
        if ( etc::startswith( line , ";" ) )
        {
            continue;
        }
        //Check if the line has the beginning of a section
        if (etc::startswith( line , "[" ) && etc::endswith( line , "]" ))
        {
            //Close last section
            section.end_index = (int)file.tellg();
            this->stored_settings[section.header_name] = section;
#ifdef SETTINGS_VERBOSE
            std::cout << " E:" << section.end_index << std::endl;
#endif

            //Refresh section
            section = INISection();
            //Remove the brackets
            section.header_name = line.substr ( 1 , line.size() - 2 );

            if ( this->exists(section.header_name)) {
                //Warning text
                std::cout << "ERROR : Another " << this->file_name << "::" << section.header_name << " has been defined!\nSections will be damaged." << std::endl;
            } else {
                //-2 constant is to correct the position of the start index
                section.start_index = start_pos ;
                section.loaded = false;
                section.properties = SettingsMap();

#ifdef SETTINGS_VERBOSE
            std::cout << section.header_name  << " S:" << section.start_index;
#endif

            }
            continue;
        }
    }

    section.end_index = file_size;
    this->stored_settings[section.header_name] = section;

#ifdef SETTINGS_VERBOSE
            std::cout << " E:" << section.end_index << std::endl;
#endif

    file.close();
}

/**
 * @brief Loads a section's data into memory
 * @param header Section name
 * @param flag Settings Duplicate Flags
 */
void Settings::load_section ( std::string header , SettingsDuplicateFlags flag) {
    std::fstream file;

    if (this->exists(header) == false)
        return;

    INISection* section = &(this->stored_settings[header]);

    file.open( this->file_name.c_str() );
    int file_pos_max = section->end_index;
    //Check if the file is open
    if (!(file.is_open()))
    {
        return;
    }

    //Seek to the beginning of the file
    file.seekg( 0 , file.beg );
    file.peek();

    file.seekg( section->start_index , file.beg );

    bool start = false;
    while ( file.tellg() < file_pos_max && !file.eof() )
    {
        std::string line;
        std::getline ( file, line );
        line = etc::trim ( line );

        if (line == "")
        {
            continue;
        }
        if ( etc::startswith( line , ";" ) )
        {
            continue;
        }
        //Check if the line has the beginning of a section
        if ( etc::startswith( line , "[" ) || etc::endswith( line , "]") )
        {
            std::string header_name = line.substr ( 1 , line.size() - 2 );
            //If another section is in contact, LEAVE NOW
            if (header_name != section->header_name) {
                break;
            } else {
                //Found the start of the section we are looking for
                start = true;
            }
            continue;
        }

        if (start == false)
        {
            continue;
        }

        //Find the equal part of the line
        std::size_t equal_pos = line.find_first_of('=', 0);

        if (equal_pos == line.npos) {
            continue;
        }

        std::string key = etc::trim ( line.substr( 0 , equal_pos ) );
        std::string value = etc::trim ( line.substr( equal_pos + 1  , line.length() - 1 ) );

        if (key == "") {
            continue;
        }

        if ( section->properties.find( key ) !=  section->properties.end() )
        {
            //There is another copy of the key, check if it is OK to override
            if (flag == SETTINGS_DUPLICATES_OVERRIDE)
            {
                section->properties[key] = value;
            }
        }
        else
        {
            section->properties[key] = value;
#ifdef SETTINGS_VERBOSE

            std::cout << section->header_name << "::" << key << "=" << value << std::endl;
#endif
        }
    }
    //Update loaded status
    section->loaded = true;
    file.close();

}

/**
 * @brief Unloads a specified section
 * @param header a section name
 */
void Settings::unload_section (std::string header)
{
    if (this->exists(header)) {
        this->stored_settings[header].properties.clear();
        this->stored_settings[header].loaded = false;
    }
}

/**
 * @brief Gets the string of the given setting and copies it into the out string
 * @param header the name of the section
 * @param key the name of setting
 * @param out A string to be written to
 * @return true on successful copy
 */
bool Settings::get (std::string header , std::string  key, std::string* out)
{
    if (this->exists(header ,key))
    {
        *out = this->stored_settings[header].properties[key];
        return true;
    }
    else
    {
        return false;
    }
}

/**
 * @brief Gets the value and converts it to a bool
 * @see Settings::get
 * @param bol Returns the value
 * @return
 */
bool Settings::getBool (std::string header , std::string  key , bool* bol)
{
    std::string b;
    if (this->get(header, key , &b) == false)
        return false;
    b = etc::toLower(b);
    if (b != "")
    {
        *bol = ( b == "true" ? true : false );
        return true;
    }
    else
    {
        return false;
    }
}

bool Settings::getInt (std::string header , std::string  key , int* num)
{
    std::string b;
    if (this->get(header, key , &b) == false)
        return false;

    if ( etc::is_number(b) )
    {
        *num = atoi( b.c_str() );
        return true;
    }
    else
    {
        return false;
    }
}

bool Settings::add (std::string header , std::string key , std::string value)
{
    if (!this->exists(header , key))
    {
        this->stored_settings[header].properties[key] = value;
        return true;
    }
    else
    {
        return false;
    }
}

bool Settings::set (std::string header , std::string key , std::string value)
{
     if (this->exists( header , key ) ) {
        this->stored_settings[header].properties[key] = value;
        return true;
     }
     return false;
}

/**
 * @brief Saves all the sections of a given file
 * @warning Deletes original file and then renames a temp file to replace it
 * @param filename Saves all headers that belong to a file
 * @return bool true on success
 */
bool Settings::save ()
{
    //The File to be read from
    std::ifstream file_in;
    //The File to be written to
    std::fstream file_out;
    //Stream are separate to prevent cross-contamination

    //Open the input file
    file_in.open( this->file_name.c_str() );

    //Check for errors
    if (file_in.is_open() == false) {
        std::cout << "Error input file : " << this->file_name.c_str() << " could not be opened." << std::endl;
        return false;
    }

    //Open the output file
    file_out.open( ("temp~" + this->file_name).c_str() , std::ofstream::out );

    //Check for errors
    if (file_out.is_open() == false) {
        std::cout << "Error output file : " << ("temp~" + this->file_name).c_str() << " could not be opened." << std::endl;
        return false;
    }

    //Go through whole file
    INISection* current_section = &(this->stored_settings[""]);
    while ( file_in.eof() == false )
    {
        std::string line;
        std::getline ( file_in , line );
        line = etc::trim ( line );

        std::size_t equal_pos = line.find_first_of('=', 0);

        if (line == "")
        {

        }
        else if ( etc::startswith( line , ";" ) )
        {

        }
        else if ( etc::startswith( line , "[" ) || etc::endswith( line , "]") )
        {
            //Check if the line has the beginning of a section
            //Update current_section
            if (current_section != nullptr)
            {
                current_section->end_index = file_out.tellg();
            }

            current_section = &( this->stored_settings[ line.substr ( 1 , line.size() - 2 )] );
            current_section->start_index = (int)file_out.tellg() - 1;
        }
        else if (equal_pos != line.npos) {
            std::string key = etc::trim ( line.substr( 0 , equal_pos ) );
            std::string value = current_section->properties[key];
            if (value == "") {
                value = etc::trim ( line.substr( equal_pos + 1  , line.length() - 1 ) );
            }

            file_out << key << '=' << value << std::endl;
            continue;
        }

        //Standard copy line out
        file_out << line << std::endl;
    }

    file_out.close();
    file_in.close();

    //File operations
    //File operation return value
    int file_op = 0;

    //Remove old version
    file_op = std::remove( this->file_name.c_str() );

    //Check if there was an error
    if (file_op != 0) {
        std::cout << "Error while removing the file " << this->file_name.c_str() << std::endl;
        return false;
    }

    //Rename the temp version to replace the deleted version
    file_op = std::rename( ("temp~" + this->file_name).c_str()  , this->file_name.c_str() );

    //Check if there was an error
    if (file_op != 0) {
        std::cout << "Error while renaming the file from " << ("temp~" + this->file_name).c_str() << " to " << this->file_name.c_str() << std::endl;
        return false;
    }

    return true;
}
<|endoftext|>


<commit_before>#include <windows.h>
#include <tchar.h>
#include "resource.h"
#include "MyMsgProc.h"
#include "server\LowDbAccess.h"
#include "server\VarController.h"

int GetMsgWidth(HWND WndHndl, TCHAR* Msg);
int GetMsgHeight(HWND WndHndl, TCHAR* Msg);

HWND HttpHdDelHttp = NULL;
bool HttpHdDelHttpFlag = false;
HWND HttpHdAddHttp = NULL;
bool HttpHdAddHttpFlag = false;
HWND HttpHdContentLen = NULL;
bool HttpHdContentLenFlag = false;
HWND HttpHdDate = NULL;
bool HttpHdDateFlag = false;
HWND HttpHdRequest = NULL;
bool HttpHdRequestFlag = false;
HWND HttpHdResponse = NULL;
bool HttpHdResponseFlag = false;
HWND HttpHttpHeaderEd = NULL;

void ChangeHttpHeader()
{
	bool HttpHdFlag = false;
	if (HttpHdAddHttpFlag == false) {
		HttpHdFlag = false;
		SendMessage(HttpHdAddHttp, BM_SETCHECK, BST_UNCHECKED, 0L);
		EnableWindow(HttpHdAddHttp, true);
	} else {
		HttpHdFlag = true;
		SendMessage(HttpHdAddHttp, BM_SETCHECK, BST_CHECKED, 0L);
		EnableWindow(HttpHdAddHttp, true);
	}
	EnableWindow(HttpHdContentLen, HttpHdFlag);
	EnableWindow(HttpHdDate, HttpHdFlag);
	EnableWindow(HttpHdRequest, HttpHdFlag);
	EnableWindow(HttpHdResponse, HttpHdFlag);
	EnableWindow(HttpHttpHeaderEd, HttpHdFlag);
	SendMessage(HttpHdContentLen, BM_SETCHECK, (HttpHdContentLenFlag == false) ? BST_UNCHECKED : BST_CHECKED, 0L);
	SendMessage(HttpHdDate, BM_SETCHECK, (HttpHdDateFlag == false) ? BST_UNCHECKED : BST_CHECKED, 0L);
	SendMessage(HttpHdRequest, BM_SETCHECK, (HttpHdRequestFlag == false) ? BST_UNCHECKED : BST_CHECKED, 0L);
	SendMessage(HttpHdResponse, BM_SETCHECK, (HttpHdResponseFlag == false) ? BST_UNCHECKED : BST_CHECKED, 0L);
}

void HttpHeader(int CurrentId, int Type, HINSTANCE InstHndl, HWND WndHndl, UINT message, WPARAM wParam, LPARAM lParam)
{
	RECT Rect;
	GetClientRect(WndHndl, &Rect);

	if (message == WM_CREATE) {
		HttpHdDelHttp = CreateWindow(_T("BUTTON"), MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_DELETEFROM), WS_CHILD | WS_VISIBLE | BS_CHECKBOX, 10, 100,
			GetMsgWidth(WndHndl, MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_DELETEFROM)) + 30,
			GetMsgHeight(WndHndl, MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_DELETEFROM)),
			WndHndl, (HMENU)IDC_HTTPHD_DELETE, InstHndl, NULL);
		HttpHdAddHttp = CreateWindow(_T("BUTTON"), MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_INSERTINTO), WS_CHILD | WS_VISIBLE | BS_CHECKBOX, 10, 130,
			GetMsgWidth(WndHndl, MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_INSERTINTO)) + 30,
			GetMsgHeight(WndHndl, MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_INSERTINTO)),
			WndHndl, (HMENU)IDC_HTTPHD_ADD, InstHndl, NULL);
		HttpHdContentLen = CreateWindow(_T("BUTTON"), MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_CONTLEN), WS_CHILD | WS_VISIBLE | BS_CHECKBOX, 40, 160,
			GetMsgWidth(WndHndl, MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_CONTLEN)) + 30,
			GetMsgHeight(WndHndl, MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_CONTLEN)),
			WndHndl, (HMENU)IDC_HTTPHD_CONTLEN, InstHndl, NULL);
		HttpHdDate = CreateWindow(_T("BUTTON"), MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_DATE), WS_CHILD | WS_VISIBLE | BS_CHECKBOX, 40, 190,
			GetMsgWidth(WndHndl, MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_DATE)) + 30,
			GetMsgHeight(WndHndl, MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_DATE)),
			WndHndl, (HMENU)IDC_HTTPHD_DATE, InstHndl, NULL);
		HttpHdRequest = CreateWindow(_T("BUTTON"), MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_REQUEST), WS_CHILD | WS_VISIBLE | BS_CHECKBOX, 40, 220,
			GetMsgWidth(WndHndl, MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_REQUEST)) + 30,
			GetMsgHeight(WndHndl, MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_REQUEST)),
			WndHndl, (HMENU)IDC_HTTPHD_REQUEST, InstHndl, NULL);
		HttpHdResponse = CreateWindow(_T("BUTTON"), MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_RESPONSE), WS_CHILD | WS_VISIBLE | BS_CHECKBOX, 40, 250,
			GetMsgWidth(WndHndl, MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_RESPONSE)) + 30,
			GetMsgHeight(WndHndl, MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_RESPONSE)),
			WndHndl, (HMENU)IDC_HTTPHD_RESPONSE, InstHndl, NULL);
		HttpHttpHeaderEd = CreateWindowEx(WS_EX_CLIENTEDGE, _T("EDIT"), _T(""), WS_CHILD | WS_VISIBLE | ES_AUTOHSCROLL, Rect.left + 40, 280, Rect.right - 50, 210, WndHndl, NULL, InstHndl, NULL);
		ChangeHttpHeader();
	}
	if (message == WM_COMMAND) {
		if (HIWORD(wParam) == BN_CLICKED) {
			if (LOWORD(wParam) == IDC_HTTPHD_DELETE) {
				if (HttpHdDelHttpFlag == false) {
					HttpHdDelHttpFlag = true;
					SendMessage(HttpHdDelHttp, BM_SETCHECK, BST_CHECKED, 0L);
					EnableWindow(HttpHdDelHttp, true);
				} else {
					HttpHdDelHttpFlag = false;
					SendMessage(HttpHdDelHttp, BM_SETCHECK, BST_UNCHECKED, 0L);
					EnableWindow(HttpHdDelHttp, true);
				}
			}
			if (LOWORD(wParam) == IDC_HTTPHD_ADD) {
				if (HttpHdAddHttpFlag == false) {
					HttpHdAddHttpFlag = true;
				} else {
					HttpHdAddHttpFlag = false;
				}
			}
			if (LOWORD(wParam) == IDC_HTTPHD_CONTLEN) {
				if (HttpHdContentLenFlag == false) {
					HttpHdContentLenFlag = true;
				} else {
					HttpHdContentLenFlag = false;
				}
			}
			if (LOWORD(wParam) == IDC_HTTPHD_DATE) {
				if (HttpHdDateFlag == false) {
					HttpHdDateFlag = true;
				} else {
					HttpHdDateFlag = false;
				}
			}
			if (LOWORD(wParam) == IDC_HTTPHD_REQUEST) {
				if (HttpHdRequestFlag == false) {
					HttpHdRequestFlag = true;
				} else {
					HttpHdRequestFlag = false;
				}
			}
			if (LOWORD(wParam) == IDC_HTTPHD_RESPONSE) {
				if (HttpHdResponseFlag == false) {
					HttpHdResponseFlag = true;
				} else {
					HttpHdResponseFlag = false;
				}
			}
			ChangeHttpHeader();
		}
	}
}
<commit_msg>#41 : Code optimization<commit_after>#include <windows.h>
#include <tchar.h>
#include "resource.h"
#include "MyMsgProc.h"
#include "server\LowDbAccess.h"
#include "server\VarController.h"

int GetMsgWidth(HWND WndHndl, TCHAR* Msg);
int GetMsgHeight(HWND WndHndl, TCHAR* Msg);

HWND HttpHdDelHttp = NULL;
bool HttpHdDelHttpFlag = false;
HWND HttpHdAddHttp = NULL;
bool HttpHdAddHttpFlag = false;
HWND HttpHdContentLen = NULL;
bool HttpHdContentLenFlag = false;
HWND HttpHdDate = NULL;
bool HttpHdDateFlag = false;
HWND HttpHdRequest = NULL;
bool HttpHdRequestFlag = false;
HWND HttpHdResponse = NULL;
HWND HttpHeaderEd = NULL;

wchar_t HttpHeaderEdBox[1024] = L"";

void ChangeHttpHeader()
{
	if (HttpHdDelHttpFlag == true) {
		SendMessage(HttpHdDelHttp, BM_SETCHECK, BST_CHECKED, 0L);
		EnableWindow(HttpHdDelHttp, true);
	} else {
		SendMessage(HttpHdDelHttp, BM_SETCHECK, BST_UNCHECKED, 0L);
		EnableWindow(HttpHdDelHttp, true);
	}
	bool HttpHdFlag = false;
	if (HttpHdAddHttpFlag == false) {
		HttpHdFlag = false;
		SendMessage(HttpHdAddHttp, BM_SETCHECK, BST_UNCHECKED, 0L);
		EnableWindow(HttpHdAddHttp, true);
	} else {
		HttpHdFlag = true;
		SendMessage(HttpHdAddHttp, BM_SETCHECK, BST_CHECKED, 0L);
		EnableWindow(HttpHdAddHttp, true);
	}
	EnableWindow(HttpHdContentLen, HttpHdFlag);
	EnableWindow(HttpHdDate, HttpHdFlag);
	EnableWindow(HttpHdRequest, HttpHdFlag);
	EnableWindow(HttpHdResponse, HttpHdFlag);
	EnableWindow(HttpHeaderEd, HttpHdFlag);
	SendMessage(HttpHdContentLen, BM_SETCHECK, (HttpHdContentLenFlag == false) ? BST_UNCHECKED : BST_CHECKED, 0L);
	SendMessage(HttpHdDate, BM_SETCHECK, (HttpHdDateFlag == false) ? BST_UNCHECKED : BST_CHECKED, 0L);
	SendMessage(HttpHdRequest, BM_SETCHECK, (HttpHdRequestFlag == false) ? BST_UNCHECKED : BST_CHECKED, 0L);
	SendMessage(HttpHdResponse, BM_SETCHECK, (HttpHdRequestFlag == true) ? BST_UNCHECKED : BST_CHECKED, 0L);
}

void HttpHeader(int CurrentId, int Type, HINSTANCE InstHndl, HWND WndHndl, UINT message, WPARAM wParam, LPARAM lParam)
{
	RECT Rect;
	GetClientRect(WndHndl, &Rect);

	if (message == WM_CREATE) {
		HttpHdDelHttp = CreateWindow(_T("BUTTON"), MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_DELETEFROM), WS_CHILD | WS_VISIBLE | BS_CHECKBOX, 10, 100,
			GetMsgWidth(WndHndl, MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_DELETEFROM)) + 30,
			GetMsgHeight(WndHndl, MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_DELETEFROM)),
			WndHndl, (HMENU)IDC_HTTPHD_DELETE, InstHndl, NULL);
		HttpHdAddHttp = CreateWindow(_T("BUTTON"), MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_INSERTINTO), WS_CHILD | WS_VISIBLE | BS_CHECKBOX, 10, 130,
			GetMsgWidth(WndHndl, MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_INSERTINTO)) + 30,
			GetMsgHeight(WndHndl, MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_INSERTINTO)),
			WndHndl, (HMENU)IDC_HTTPHD_ADD, InstHndl, NULL);
		HttpHdContentLen = CreateWindow(_T("BUTTON"), MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_CONTLEN), WS_CHILD | WS_VISIBLE | BS_CHECKBOX, 40, 160,
			GetMsgWidth(WndHndl, MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_CONTLEN)) + 30,
			GetMsgHeight(WndHndl, MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_CONTLEN)),
			WndHndl, (HMENU)IDC_HTTPHD_CONTLEN, InstHndl, NULL);
		HttpHdDate = CreateWindow(_T("BUTTON"), MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_DATE), WS_CHILD | WS_VISIBLE | BS_CHECKBOX, 40, 190,
			GetMsgWidth(WndHndl, MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_DATE)) + 30,
			GetMsgHeight(WndHndl, MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_DATE)),
			WndHndl, (HMENU)IDC_HTTPHD_DATE, InstHndl, NULL);
		HttpHdRequest = CreateWindow(_T("BUTTON"), MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_REQUEST), WS_CHILD | WS_VISIBLE | BS_RADIOBUTTON, 40, 220,
			GetMsgWidth(WndHndl, MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_REQUEST)) + 30,
			GetMsgHeight(WndHndl, MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_REQUEST)),
			WndHndl, (HMENU)IDC_HTTPHD_REQUEST, InstHndl, NULL);
		HttpHdResponse = CreateWindow(_T("BUTTON"), MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_RESPONSE), WS_CHILD | WS_VISIBLE | BS_RADIOBUTTON, 40, 250,
			GetMsgWidth(WndHndl, MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_RESPONSE)) + 30,
			GetMsgHeight(WndHndl, MyMsgProc::GetMsg(MyMsgProc::PROP_HTTPHEADER_RESPONSE)),
			WndHndl, (HMENU)IDC_HTTPHD_RESPONSE, InstHndl, NULL);
		HttpHeaderEd = CreateWindowEx(WS_EX_CLIENTEDGE, _T("EDIT"), _T(""), WS_CHILD | WS_VISIBLE | ES_AUTOHSCROLL, Rect.left + 40, 280, Rect.right - 50, 210, WndHndl, NULL, InstHndl, NULL);
		SendMessage(HttpHeaderEd, EM_SETLIMITTEXT, (WPARAM)1024, (LPARAM)0);
		SendMessage(HttpHeaderEd, WM_SETTEXT, (WPARAM)0, (LPARAM)HttpHeaderEdBox);

		ChangeHttpHeader();
	}
	if (message == WM_COMMAND) {
		if (HIWORD(wParam) == BN_CLICKED) {
			if (LOWORD(wParam) == IDC_HTTPHD_DELETE) {
				if (HttpHdDelHttpFlag == false) {
					HttpHdDelHttpFlag = true;
				} else {
					HttpHdDelHttpFlag = false;
				}
			}
			if (LOWORD(wParam) == IDC_HTTPHD_ADD) {
				if (HttpHdAddHttpFlag == false) {
					HttpHdAddHttpFlag = true;
				} else {
					HttpHdAddHttpFlag = false;
				}
			}
			if (LOWORD(wParam) == IDC_HTTPHD_CONTLEN) {
				if (HttpHdContentLenFlag == false) {
					HttpHdContentLenFlag = true;
				} else {
					HttpHdContentLenFlag = false;
				}
			}
			if (LOWORD(wParam) == IDC_HTTPHD_DATE) {
				if (HttpHdDateFlag == false) {
					HttpHdDateFlag = true;
				} else {
					HttpHdDateFlag = false;
				}
			}
			if (LOWORD(wParam) == IDC_HTTPHD_REQUEST) {
				HttpHdRequestFlag = true;
			}
			if (LOWORD(wParam) == IDC_HTTPHD_RESPONSE) {
				HttpHdRequestFlag = false;
			}
			ChangeHttpHeader();
		}
	}
}
<|endoftext|>


<commit_before>#ifndef RABENDALIB_STL_ALGOBASE
#define RABENDALIB_STL_ALGOBASE

#include "stl_config.hpp"
#include "stl_iterator_base.hpp"
#include "stl_pair.hpp"
#include "type_traits.hpp"
NAMESPACE_BEGIN(stl)

template<class InputIterator1, class InputIterator2>
inline bool equal(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2)
{
	for(; first1 != last1; ++first1, ++first2)
	{
		if (*first1 != *first2)
			return false;
	}
	return true;
}

template<class InputIterator1, class InputIterator2, class BinaryOperation>
inline bool equal(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, BinaryOperation binary_pred)
{
	for (; first1 != last1; ++first1, ++first2)
	{
		if (!binary_pred(*first1, *first2))
			return false;
	}
	return true;
}

template<class ForwardIterator, class T>
void fill(ForwardIterator first, ForwardIterator last, const T& value)
{
	for(; first != last; ++first)
	{
		*first = value;
	}
}

template<class OutputIterator, class Size, class T>
OutputIterator fill_n(OutputIterator first, Size n, const T& value)
{
	for (; n > 0; --n, ++first)
		*first = value;
	return first;
}

template<class ForwardIterator1, class ForwardIterator2>
inline void iter_swap(ForwardIterator1 a, ForwardIterator2 b)
{
	__iter_swap(a, b, __VALUE_TYPE(a));
}

template<class ForwardIterator1, class ForwardIterator2, class T>
inline void __iter_swap(ForwardIterator1 a, ForwardIterator2 b, T*)
{
	T tmp = *a;
	*a = *b;
	*b = tmp;
}

template<class InputIterator1, class InputIterator2>
bool lexicographical_compare(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2)
{
	for(; first1 != last1 && first2 != last2; ++first1, ++first2)
	{
		if (*first1 < *first2)
			return true;
		else if (*first2 < *first1)
			return false;
	}
	return first1 == last1 && first2 != last2;
}

template<class InputIterator1, class InputIterator2, class Compare>
bool lexicographical_compare(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, Compare comp)
{
	for (; first1 != last1 && first2 != last2; ++first1, ++first2)
	{
		if (comp(*first1, *first2))
			return true;
		else if (comp(*first2, *first1))
			return false;
	}
	return first1 == last1 && first2 != last2;
}

template<class T>
inline const T& max(const T& a, const T& b)
{
	return a < b ? b : a;
}

template<class T, class Compare>
inline const T& max(const T& a, const T& b, Compare comp)
{
	return comp(a, b) ? b : a;
}

template<class T>
inline const T& min(const T& a, const T& b)
{
	return b < a ? b : a;
}

template<class T, class Compare>
inline const T& min(const T& a, const T& b, Compare comp)
{
	return comp(b, a) ? b : a;
}

inline bool lexicographical_compare(const unsigned char* first1, const unsigned char* last1, const unsigned char* first2, const unsigned char* last2)
{
	const size_t len1 = last1 - first1;
	const size_t len2 = last2 - first2;

	const int result = memcmp(first1, first2, NAMESPACE_GET(stl)::min(len1, len2));

	return result != 0 ? result < 0 : len1 < len2;
}

template<class InputIterator1, class InputIterator2>
pair<InputIterator1, InputIterator2> mismatch(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2)
{
	while(first1 != last1 && *first1 == *first2)
	{
		++first1;
		++first2;
	}
	return pair<InputIterator1, InputIterator2>(first1, first2);
}

template<class InputIterator1, class InputIterator2, class BinaryPredicate>
pair<InputIterator1, InputIterator2> mismatch(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, BinaryPredicate binary_pred)
{
	while (first1 != last1 && binary_pred(*first1, *first2))
	{
		++first1;
		++first2;
	}
	return pair<InputIterator1, InputIterator2>(first1, first2);
}

template<class T>
inline void swap(T& a, T& b) noexcept
{
	T tmp = a;
	a = b;
	b = tmp;
}

template<class InputIterator, class OutputIterator>
inline OutputIterator copy(InputIterator first, InputIterator last, OutputIterator result)
{
	return __copy_dispatch<InputIterator, OutputIterator>()(first, last, result);
}

inline char* copy(const char* first, const char* last, char* result)
{
	memmove(result, first, last - first);
	return result + (last - first);
}

inline wchar_t* copy(const wchar_t* first, const wchar_t* last, wchar_t* result)
{
	memmove(result, first, sizeof(wchar_t) * (last - first));
	return result + (last - first);
}

template<class InputIterator, class OutputIterator>
struct __copy_dispatch
{
	OutputIterator operator()(InputIterator first, InputIterator last, OutputIterator result)
	{
		return __copy(first, last, result, value_type(first));
	}
};

template<class T>
struct __copy_dispatch<T*, T*>
{
	T* operator()(T* first, T* second, T* result)
	{
		using t = typename type_traits<T>::has_trivial_assignment_operator;
		return __copy_t(first, second, result, t());
	}
};

template<class T>
struct __copy_dispatch<const T*, T*>
{
	T* operator()(T* first, T* second, T* result)
	{
		using t = typename type_traits<T>::has_trivial_assignment_operator;
		return __copy_t(first, second, result, t());
	}
};

template<class InputIterator, class OutputIterator>
inline OutputIterator __copy(InputIterator first, InputIterator last, OutputIterator result, input_iterator_tag)
{
	for (; first != last; ++first, ++result)
		*result = *first;
	return result;
}

template<class RandomAccessIterator, class OutputIterator>
inline OutputIterator __copy(RandomAccessIterator first, RandomAccessIterator last, OutputIterator result, random_access_iterator_tag)
{
	return __copy_d(first, last, result, distance_type(first));
}

template<class RandomAccessIterator, class OutputIterator, class Distance>
inline OutputIterator __copy_d(RandomAccessIterator first, RandomAccessIterator last, OutputIterator result, Distance*)
{
	for (Distance n = last - first; n > 0; --n, ++first, ++result)
		*result = *first;
	return result;
}

template<class T>
inline T* __copy_t(const T* first, const T* last, T* result, true_type)
{
	memmove(result, first, sizeof(T) * (last - first));
	return result + (last - first);
}

template<class T>
inline T* __copy_t(const T* first, const T* last, T* result, false_type)
{
	return __copy_d(first, last, result, (ptrdiff_t*)0);
}

NAMESPACE_END(stl)

#endif //RABENDALIB_STL_ALGOBASE

<commit_msg>reformat<commit_after>#ifndef RABENDALIB_STL_ALGOBASE
#define RABENDALIB_STL_ALGOBASE

#include "stl_config.hpp"
#include "stl_iterator_base.hpp"
#include "stl_pair.hpp"
#include "type_traits.hpp"

NAMESPACE_BEGIN(stl)

	template<class InputIterator1, class InputIterator2>
	inline bool equal(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2) {
		for (; first1 != last1; ++first1, ++first2) {
			if (*first1 != *first2)
				return false;
		}
		return true;
	}

	template<class InputIterator1, class InputIterator2, class BinaryOperation>
	inline bool equal(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, BinaryOperation binary_pred) {
		for (; first1 != last1; ++first1, ++first2) {
			if (!binary_pred(*first1, *first2))
				return false;
		}
		return true;
	}

	template<class ForwardIterator, class T>
	void fill(ForwardIterator first, ForwardIterator last, const T &value) {
		for (; first != last; ++first) {
			*first = value;
		}
	}

	template<class OutputIterator, class Size, class T>
	OutputIterator fill_n(OutputIterator first, Size n, const T &value) {
		for (; n > 0; --n, ++first)
			*first = value;
		return first;
	}

	template<class ForwardIterator1, class ForwardIterator2>
	inline void iter_swap(ForwardIterator1 a, ForwardIterator2 b) {
		__iter_swap(a, b, __VALUE_TYPE(a));
	}

	template<class ForwardIterator1, class ForwardIterator2, class T>
	inline void __iter_swap(ForwardIterator1 a, ForwardIterator2 b, T *) {
		T tmp = *a;
		*a = *b;
		*b = tmp;
	}

	template<class InputIterator1, class InputIterator2>
	bool
	lexicographical_compare(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2) {
		for (; first1 != last1 && first2 != last2; ++first1, ++first2) {
			if (*first1 < *first2)
				return true;
			else if (*first2 < *first1)
				return false;
		}
		return first1 == last1 && first2 != last2;
	}

	template<class InputIterator1, class InputIterator2, class Compare>
	bool
	lexicographical_compare(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2,
	                        Compare comp) {
		for (; first1 != last1 && first2 != last2; ++first1, ++first2) {
			if (comp(*first1, *first2))
				return true;
			else if (comp(*first2, *first1))
				return false;
		}
		return first1 == last1 && first2 != last2;
	}

	template<class T>
	inline const T &max(const T &a, const T &b) {
		return a < b ? b : a;
	}

	template<class T, class Compare>
	inline const T &max(const T &a, const T &b, Compare comp) {
		return comp(a, b) ? b : a;
	}

	template<class T>
	inline const T &min(const T &a, const T &b) {
		return b < a ? b : a;
	}

	template<class T, class Compare>
	inline const T &min(const T &a, const T &b, Compare comp) {
		return comp(b, a) ? b : a;
	}

	inline bool
	lexicographical_compare(const unsigned char *first1, const unsigned char *last1, const unsigned char *first2,
	                        const unsigned char *last2) {
		const size_t len1 = last1 - first1;
		const size_t len2 = last2 - first2;

		const int result = memcmp(first1, first2, NAMESPACE_GET(stl)::min(len1, len2));

		return result != 0 ? result < 0 : len1 < len2;
	}

	template<class InputIterator1, class InputIterator2>
	pair<InputIterator1,
		InputIterator2> mismatch(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2) {
		while (first1 != last1 && *first1 == *first2) {
			++first1;
			++first2;
		}
		return pair<InputIterator1,
			InputIterator2>(first1, first2);
	}

	template<class InputIterator1, class InputIterator2, class BinaryPredicate>
	pair<InputIterator1,
		InputIterator2>
	mismatch(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, BinaryPredicate binary_pred) {
		while (first1 != last1 && binary_pred(*first1, *first2)) {
			++first1;
			++first2;
		}
		return pair<InputIterator1,
			InputIterator2>(first1, first2);
	}

	template<class T>
	inline void swap(T &a, T &b) noexcept {
		T tmp = a;
		a = b;
		b = tmp;
	}

	template<class InputIterator, class OutputIterator>
	inline OutputIterator copy(InputIterator first, InputIterator last, OutputIterator result) {
		return __copy_dispatch<InputIterator,
			OutputIterator>()(first, last, result);
	}

	inline char *copy(const char *first, const char *last, char *result) {
		memmove(result, first, last - first);
		return result + (last - first);
	}

	inline wchar_t *copy(const wchar_t *first, const wchar_t *last, wchar_t *result) {
		memmove(result, first, sizeof(wchar_t) * (last - first));
		return result + (last - first);
	}

	template<class InputIterator, class OutputIterator>
	struct __copy_dispatch {
		OutputIterator operator()(InputIterator first, InputIterator last, OutputIterator result) {
			return __copy(first, last, result, value_type(first));
		}
	};

	template<class T>
	struct __copy_dispatch<T *,
		T *> {
		T *operator()(T *first, T *second, T *result) {
			using t = typename type_traits<T>::has_trivial_assignment_operator;
			return __copy_t(first, second, result, t());
		}
	};

	template<class T>
	struct __copy_dispatch<const T *,
		T *> {
		T *operator()(T *first, T *second, T *result) {
			using t = typename type_traits<T>::has_trivial_assignment_operator;
			return __copy_t(first, second, result, t());
		}
	};

	template<class InputIterator, class OutputIterator>
	inline OutputIterator __copy(InputIterator first, InputIterator last, OutputIterator result, input_iterator_tag) {
		for (; first != last; ++first, ++result)
			*result = *first;
		return result;
	}

	template<class RandomAccessIterator, class OutputIterator>
	inline OutputIterator
	__copy(RandomAccessIterator first, RandomAccessIterator last, OutputIterator result, random_access_iterator_tag) {
		return __copy_d(first, last, result, distance_type(first));
	}

	template<class RandomAccessIterator, class OutputIterator, class Distance>
	inline OutputIterator
	__copy_d(RandomAccessIterator first, RandomAccessIterator last, OutputIterator result, Distance *) {
		for (Distance n = last - first; n > 0; --n, ++first, ++result)
			*result = *first;
		return result;
	}

	template<class T>
	inline T *__copy_t(const T *first, const T *last, T *result, true_type) {
		memmove(result, first, sizeof(T) * (last - first));
		return result + (last - first);
	}

	template<class T>
	inline T *__copy_t(const T *first, const T *last, T *result, false_type) {
		return __copy_d(first, last, result, (ptrdiff_t *) 0);
	}

NAMESPACE_END(stl)

#endif //RABENDALIB_STL_ALGOBASE

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: acc_pipe.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 18:27:19 $
 *
 *  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
 *
 ************************************************************************/
#include "osl/security.hxx"
#include "acceptor.hxx"
#include <com/sun/star/connection/ConnectionSetupException.hpp>

#include <cppuhelper/implbase1.hxx>

using namespace ::rtl;
using namespace ::osl;
using namespace ::cppu;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::connection;
using namespace ::com::sun::star::io;

namespace io_acceptor
{

    typedef WeakImplHelper1< XConnection > MyPipeConnection;

    class PipeConnection :
        public MyPipeConnection
    {
    public:
        PipeConnection( const OUString & s , const OUString &sConnectionDescription);
        ~PipeConnection();

        virtual sal_Int32 SAL_CALL read( Sequence< sal_Int8 >& aReadBytes, sal_Int32 nBytesToRead )
            throw(::com::sun::star::io::IOException,
                  ::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL write( const Sequence< sal_Int8 >& aData )
            throw(::com::sun::star::io::IOException,
                  ::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL flush(  ) throw(
            ::com::sun::star::io::IOException,
            ::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL close(  )
            throw(::com::sun::star::io::IOException,
                  ::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getDescription(  )
            throw(::com::sun::star::uno::RuntimeException);
    public:
        ::osl::StreamPipe m_pipe;
        oslInterlockedCount m_nStatus;
        OUString m_sDescription;
    };

    PipeConnection::PipeConnection( const OUString &s, const OUString &sConnectionDescription) :
        m_nStatus( 0 ),
        m_sDescription( sConnectionDescription )
    {
        g_moduleCount.modCnt.acquire( &g_moduleCount.modCnt );

        // make it unique
        m_sDescription += OUString::createFromAscii( ",uniqueValue=" );
        m_sDescription += OUString::valueOf( (sal_Int64) &m_pipe , 10 );
    }

    PipeConnection::~PipeConnection()
    {
        g_moduleCount.modCnt.release( &g_moduleCount.modCnt );
    }

    sal_Int32 PipeConnection::read( Sequence < sal_Int8 > & aReadBytes , sal_Int32 nBytesToRead )
        throw(::com::sun::star::io::IOException,
              ::com::sun::star::uno::RuntimeException)
    {
        if( ! m_nStatus )
        {
            if( aReadBytes.getLength() != nBytesToRead )
            {
                aReadBytes.realloc( nBytesToRead );
            }
            return m_pipe.read( aReadBytes.getArray()  , aReadBytes.getLength() );
        }
        else {
            throw IOException();
        }

        return 0;
    }

    void PipeConnection::write( const Sequence < sal_Int8 > &seq )
            throw(::com::sun::star::io::IOException,
                  ::com::sun::star::uno::RuntimeException)
    {
        if( ! m_nStatus )
        {
            if( m_pipe.write( seq.getConstArray() , seq.getLength() ) != seq.getLength() )
            {
                throw IOException();
            }
        }
        else {
            throw IOException();
        }
    }

    void PipeConnection::flush( )
        throw(  ::com::sun::star::io::IOException,
                ::com::sun::star::uno::RuntimeException)
    {
    }

    void PipeConnection::close()
        throw( ::com::sun::star::io::IOException,
               ::com::sun::star::uno::RuntimeException)
    {
        if(  1 == osl_incrementInterlockedCount( (&m_nStatus) ) )
        {
            m_pipe.close();
        }
    }

    OUString PipeConnection::getDescription()
            throw(::com::sun::star::uno::RuntimeException)
    {
        return m_sDescription;
    }

    /***************
     * PipeAcceptor
     **************/
    PipeAcceptor::PipeAcceptor( const OUString &sPipeName , const OUString & sConnectionDescription) :
        m_bClosed( sal_False ),
        m_sPipeName( sPipeName ),
        m_sConnectionDescription( sConnectionDescription )
    {
    }

    void PipeAcceptor::init()
    {
        m_pipe = Pipe( m_sPipeName.pData , osl_Pipe_CREATE , osl::Security() );
        if( ! m_pipe.is() )
        {
            OUString error = OUString::createFromAscii( "io.acceptor: Couldn't setup pipe " );
            error += m_sPipeName;
            throw ConnectionSetupException( error, Reference< XInterface > () );
        }
    }

    Reference< XConnection > PipeAcceptor::accept( )
    {
        Pipe pipe;
        {
            MutexGuard guard( m_mutex );
            pipe = m_pipe;
        }
        if( ! pipe.is() )
        {
            OUString error = OUString::createFromAscii( "io.acceptor: pipe already closed" );
            error += m_sPipeName;
            throw ConnectionSetupException( error, Reference< XInterface > () );
        }
        PipeConnection *pConn = new PipeConnection( m_sPipeName , m_sConnectionDescription );

        oslPipeError status = pipe.accept( pConn->m_pipe );

        if( m_bClosed )
        {
            // stopAccepting was called !
            delete pConn;
            return Reference < XConnection >();
        }
        else if( osl_Pipe_E_None == status )
        {
            return Reference < XConnection > ( (XConnection * ) pConn );
        }
        else
        {
            OUString error = OUString::createFromAscii( "io.acceptor: Couldn't setup pipe " );
            error += m_sPipeName;
            throw ConnectionSetupException( error, Reference< XInterface > ());
        }
    }

    void PipeAcceptor::stopAccepting()
    {
        m_bClosed = sal_True;
        Pipe pipe;
        {
            MutexGuard guard( m_mutex );
            pipe = m_pipe;
            m_pipe.clear();
        }
        if( pipe.is() )
        {
            pipe.close();
        }
    }
}
<commit_msg>INTEGRATION: CWS warnings01 (1.6.22); FILE MERGED 2005/09/22 20:26:40 sb 1.6.22.4: RESYNC: (1.6-1.7); FILE MERGED 2005/09/07 14:14:50 sb 1.6.22.3: #i53898# Made code warning-free. 2005/09/06 10:11:10 sb 1.6.22.2: #i53898# sal::reinterpret_int_cast is not needed. 2005/09/01 08:14:26 sb 1.6.22.1: #i53898# Made code warning-free.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: acc_pipe.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-20 00:15:53 $
 *
 *  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
 *
 ************************************************************************/
#include "osl/security.hxx"
#include "acceptor.hxx"
#include <com/sun/star/connection/ConnectionSetupException.hpp>

#include <cppuhelper/implbase1.hxx>

using namespace ::rtl;
using namespace ::osl;
using namespace ::cppu;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::connection;
using namespace ::com::sun::star::io;

namespace io_acceptor
{

    typedef WeakImplHelper1< XConnection > MyPipeConnection;

    class PipeConnection :
        public MyPipeConnection
    {
    public:
        PipeConnection( const OUString &sConnectionDescription);
        ~PipeConnection();

        virtual sal_Int32 SAL_CALL read( Sequence< sal_Int8 >& aReadBytes, sal_Int32 nBytesToRead )
            throw(::com::sun::star::io::IOException,
                  ::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL write( const Sequence< sal_Int8 >& aData )
            throw(::com::sun::star::io::IOException,
                  ::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL flush(  ) throw(
            ::com::sun::star::io::IOException,
            ::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL close(  )
            throw(::com::sun::star::io::IOException,
                  ::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getDescription(  )
            throw(::com::sun::star::uno::RuntimeException);
    public:
        ::osl::StreamPipe m_pipe;
        oslInterlockedCount m_nStatus;
        OUString m_sDescription;
    };

    PipeConnection::PipeConnection( const OUString &sConnectionDescription) :
        m_nStatus( 0 ),
        m_sDescription( sConnectionDescription )
    {
        g_moduleCount.modCnt.acquire( &g_moduleCount.modCnt );

        // make it unique
        m_sDescription += OUString::createFromAscii( ",uniqueValue=" );
        m_sDescription += OUString::valueOf(
            sal::static_int_cast<sal_Int64 >(
                reinterpret_cast< sal_IntPtr >(&m_pipe)),
            10 );
    }

    PipeConnection::~PipeConnection()
    {
        g_moduleCount.modCnt.release( &g_moduleCount.modCnt );
    }

    sal_Int32 PipeConnection::read( Sequence < sal_Int8 > & aReadBytes , sal_Int32 nBytesToRead )
        throw(::com::sun::star::io::IOException,
              ::com::sun::star::uno::RuntimeException)
    {
        if( ! m_nStatus )
        {
            if( aReadBytes.getLength() != nBytesToRead )
            {
                aReadBytes.realloc( nBytesToRead );
            }
            return m_pipe.read( aReadBytes.getArray()  , aReadBytes.getLength() );
        }
        else {
            throw IOException();
        }
    }

    void PipeConnection::write( const Sequence < sal_Int8 > &seq )
            throw(::com::sun::star::io::IOException,
                  ::com::sun::star::uno::RuntimeException)
    {
        if( ! m_nStatus )
        {
            if( m_pipe.write( seq.getConstArray() , seq.getLength() ) != seq.getLength() )
            {
                throw IOException();
            }
        }
        else {
            throw IOException();
        }
    }

    void PipeConnection::flush( )
        throw(  ::com::sun::star::io::IOException,
                ::com::sun::star::uno::RuntimeException)
    {
    }

    void PipeConnection::close()
        throw( ::com::sun::star::io::IOException,
               ::com::sun::star::uno::RuntimeException)
    {
        if(  1 == osl_incrementInterlockedCount( (&m_nStatus) ) )
        {
            m_pipe.close();
        }
    }

    OUString PipeConnection::getDescription()
            throw(::com::sun::star::uno::RuntimeException)
    {
        return m_sDescription;
    }

    /***************
     * PipeAcceptor
     **************/
    PipeAcceptor::PipeAcceptor( const OUString &sPipeName , const OUString & sConnectionDescription) :
        m_sPipeName( sPipeName ),
        m_sConnectionDescription( sConnectionDescription ),
        m_bClosed( sal_False )
    {
    }

    void PipeAcceptor::init()
    {
        m_pipe = Pipe( m_sPipeName.pData , osl_Pipe_CREATE , osl::Security() );
        if( ! m_pipe.is() )
        {
            OUString error = OUString::createFromAscii( "io.acceptor: Couldn't setup pipe " );
            error += m_sPipeName;
            throw ConnectionSetupException( error, Reference< XInterface > () );
        }
    }

    Reference< XConnection > PipeAcceptor::accept( )
    {
        Pipe pipe;
        {
            MutexGuard guard( m_mutex );
            pipe = m_pipe;
        }
        if( ! pipe.is() )
        {
            OUString error = OUString::createFromAscii( "io.acceptor: pipe already closed" );
            error += m_sPipeName;
            throw ConnectionSetupException( error, Reference< XInterface > () );
        }
        PipeConnection *pConn = new PipeConnection( m_sConnectionDescription );

        oslPipeError status = pipe.accept( pConn->m_pipe );

        if( m_bClosed )
        {
            // stopAccepting was called !
            delete pConn;
            return Reference < XConnection >();
        }
        else if( osl_Pipe_E_None == status )
        {
            return Reference < XConnection > ( (XConnection * ) pConn );
        }
        else
        {
            OUString error = OUString::createFromAscii( "io.acceptor: Couldn't setup pipe " );
            error += m_sPipeName;
            throw ConnectionSetupException( error, Reference< XInterface > ());
        }
    }

    void PipeAcceptor::stopAccepting()
    {
        m_bClosed = sal_True;
        Pipe pipe;
        {
            MutexGuard guard( m_mutex );
            pipe = m_pipe;
            m_pipe.clear();
        }
        if( pipe.is() )
        {
            pipe.close();
        }
    }
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: acceptor.cxx,v $
 *
 *  $Revision: 1.15 $
 *
 *  last change: $Author: hr $ $Date: 2004-02-02 20:23:23 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#include <osl/mutex.hxx>

#include <uno/mapping.hxx>

#include <cppuhelper/factory.hxx>
#include <cppuhelper/implbase2.hxx>
#include <cppuhelper/implementationentry.hxx>
#include "cppuhelper/unourl.hxx"
#include "rtl/malformeduriexception.hxx"

#include <com/sun/star/connection/XAcceptor.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>

#include "acceptor.hxx"

#define IMPLEMENTATION_NAME "com.sun.star.comp.io.Acceptor"
#define SERVICE_NAME "com.sun.star.connection.Acceptor"

using namespace ::osl;
using namespace ::rtl;
using namespace ::cppu;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::registry;
using namespace ::com::sun::star::connection;

namespace io_acceptor
{
    rtl_StandardModuleCount g_moduleCount = MODULE_COUNT_INIT;

    class OAcceptor : public WeakImplHelper2< XAcceptor, XServiceInfo >
    {
    public:
        OAcceptor(const Reference< XComponentContext > & xCtx);
        virtual ~OAcceptor();
    public:
        // Methods
        virtual Reference< XConnection > SAL_CALL accept( const OUString& sConnectionDescription )
            throw( AlreadyAcceptingException,
                   ConnectionSetupException,
                   IllegalArgumentException,
                   RuntimeException);
        virtual void SAL_CALL stopAccepting(  ) throw( RuntimeException);

    public: // XServiceInfo
                virtual OUString              SAL_CALL getImplementationName() throw();
                virtual Sequence< OUString >  SAL_CALL getSupportedServiceNames(void) throw();
                virtual sal_Bool              SAL_CALL supportsService(const OUString& ServiceName) throw();

    private:
        PipeAcceptor *m_pPipe;
        SocketAcceptor *m_pSocket;
        Mutex m_mutex;
        OUString m_sLastDescription;
        sal_Bool m_bInAccept;

        Reference< XMultiComponentFactory > _xSMgr;
        Reference< XComponentContext > _xCtx;
        Reference<XAcceptor>         _xAcceptor;
    };

    OAcceptor::OAcceptor( const Reference< XComponentContext > & xCtx )
        : m_pPipe( 0 )
        , m_pSocket( 0 )
        , _xSMgr( xCtx->getServiceManager() )
        , _xCtx( xCtx )
        , m_bInAccept( sal_False )
    {
        g_moduleCount.modCnt.acquire( &g_moduleCount.modCnt );
    }

    OAcceptor::~OAcceptor()
    {
        if( m_pPipe )
        {
            delete m_pPipe;
        }
        if( m_pSocket )
        {
            delete m_pSocket;
        }
        g_moduleCount.modCnt.release( &g_moduleCount.modCnt );
    }

    struct BeingInAccept
    {
        BeingInAccept( sal_Bool *pFlag,const OUString & sConnectionDescription  ) throw( AlreadyAcceptingException)
            : m_pFlag( pFlag )
            {
                  if( *m_pFlag )
                  {
                      OUString sMessage( RTL_CONSTASCII_USTRINGPARAM( "AlreadyAcceptingException :" ) );
                      sMessage += sConnectionDescription;
                      throw AlreadyAcceptingException( sMessage , Reference< XInterface > () );
                  }
                  *m_pFlag = sal_True;
            }
        ~BeingInAccept()
            {
                *m_pFlag = sal_False;
            }
        sal_Bool *m_pFlag;
    };

    Reference< XConnection > OAcceptor::accept( const OUString &sConnectionDescription )
        throw( AlreadyAcceptingException,
               ConnectionSetupException,
               IllegalArgumentException,
               RuntimeException)
    {
#if OSL_DEBUG_LEVEL > 1
        OString tmp = OUStringToOString(sConnectionDescription, RTL_TEXTENCODING_ASCII_US);
        OSL_TRACE("acceptor %s\n", tmp.getStr());
#endif
        // if there is a thread alread accepting in this object, throw an exception.
        struct BeingInAccept guard( &m_bInAccept, sConnectionDescription );

        Reference< XConnection > r;
        if( m_sLastDescription.getLength() &&
            m_sLastDescription != sConnectionDescription )
        {
            // instantiate another acceptor for different ports
            OUString sMessage = OUString( RTL_CONSTASCII_USTRINGPARAM(
                "acceptor::accept called multiple times with different conncetion strings\n" ) );
            throw ConnectionSetupException( sMessage, Reference< XInterface > () );
        }

        if( ! m_sLastDescription.getLength() )
        {
            // setup the acceptor
            try
            {
                cppu::UnoUrlDescriptor aDesc(sConnectionDescription);
                if (aDesc.getName().equalsAsciiL(
                        RTL_CONSTASCII_STRINGPARAM("pipe")))
                {
                    rtl::OUString aName(
                        aDesc.getParameter(
                            rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
                                              "name"))));

                    m_pPipe = new PipeAcceptor(aName, sConnectionDescription);

                    try
                    {
                        m_pPipe->init();
                    }
                    catch( ... )
                    {
                        {
                            MutexGuard guard( m_mutex );
                            delete m_pPipe;
                            m_pPipe = 0;
                        }
                        throw;
                    }
                }
                else if (aDesc.getName().equalsAsciiL(
                             RTL_CONSTASCII_STRINGPARAM("socket")))
                {
                    rtl::OUString aHost;
                    if (aDesc.hasParameter(
                            rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("host"))))
                        aHost = aDesc.getParameter(
                            rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("host")));
                    else
                        aHost = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
                                                  "localhost"));
                    sal_uInt16 nPort = static_cast< sal_uInt16 >(
                        aDesc.getParameter(
                            rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("port"))).
                        toInt32());
                    bool bTcpNoDelay
                        = aDesc.getParameter(
                            rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
                                              "tcpnodelay"))).toInt32() != 0;

                    m_pSocket = new SocketAcceptor(
                        aHost, nPort, bTcpNoDelay, sConnectionDescription);

                    try
                    {
                        m_pSocket->init();
                    }
                    catch( ... )
                    {
                        {
                            MutexGuard guard( m_mutex );
                            delete m_pSocket;
                            m_pSocket = 0;
                        }
                        throw;
                    }
                }
                else
                {
                    OUString delegatee = OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.connection.Acceptor."));
                    delegatee += aDesc.getName();

#if OSL_DEBUG_LEVEL > 1
                    OString tmp = OUStringToOString(delegatee, RTL_TEXTENCODING_ASCII_US);
                    OSL_TRACE("trying to get service %s\n", tmp.getStr());
#endif
                    _xAcceptor = Reference<XAcceptor>(
                        _xSMgr->createInstanceWithContext(delegatee, _xCtx), UNO_QUERY);

                    if(!_xAcceptor.is())
                    {
                        OUString message(RTL_CONSTASCII_USTRINGPARAM("Acceptor: unknown delegatee "));
                        message += delegatee;

                        throw ConnectionSetupException(message, Reference<XInterface>());
                    }
                }
            }
            catch (rtl::MalformedUriException & rEx)
            {
                throw IllegalArgumentException(
                    rEx.getMessage(),
                    Reference< XInterface > (),
                    0 );
            }
            m_sLastDescription = sConnectionDescription;
        }

        if( m_pPipe )
        {
            r = m_pPipe->accept();
        }
        else if( m_pSocket )
        {
            r = m_pSocket->accept();
        }
        else
        {
            r = _xAcceptor->accept(sConnectionDescription);
        }

        return r;
    }

    void SAL_CALL OAcceptor::stopAccepting(  ) throw( RuntimeException)
    {
        MutexGuard guard( m_mutex );

        if( m_pPipe )
        {
            m_pPipe->stopAccepting();
        }
        else if ( m_pSocket )
        {
            m_pSocket->stopAccepting();
        }
        else if( _xAcceptor.is() )
        {
            _xAcceptor->stopAccepting();
        }

    }

    OUString acceptor_getImplementationName()
    {
        return OUString( RTL_CONSTASCII_USTRINGPARAM( IMPLEMENTATION_NAME ) );
    }

    Reference< XInterface > SAL_CALL acceptor_CreateInstance( const Reference< XComponentContext > & xCtx)
    {
        return Reference < XInterface >( ( OWeakObject * ) new OAcceptor(xCtx) );
    }

    Sequence< OUString > acceptor_getSupportedServiceNames()
    {
        static Sequence < OUString > *pNames = 0;
        if( ! pNames )
        {
            MutexGuard guard( Mutex::getGlobalMutex() );
            if( !pNames )
            {
                static Sequence< OUString > seqNames(1);
                seqNames.getArray()[0] = OUString::createFromAscii( SERVICE_NAME );
                pNames = &seqNames;
            }
        }
        return *pNames;
    }

        OUString OAcceptor::getImplementationName() throw()
    {
        return acceptor_getImplementationName();
    }

        sal_Bool OAcceptor::supportsService(const OUString& ServiceName) throw()
    {
        Sequence< OUString > aSNL = getSupportedServiceNames();
        const OUString * pArray = aSNL.getConstArray();

        for( sal_Int32 i = 0; i < aSNL.getLength(); i++ )
            if( pArray[i] == ServiceName )
                return sal_True;

        return sal_False;
    }

        Sequence< OUString > OAcceptor::getSupportedServiceNames(void) throw()
    {
        return acceptor_getSupportedServiceNames();
    }

}

using namespace io_acceptor;

static struct ImplementationEntry g_entries[] =
{
    {
        acceptor_CreateInstance, acceptor_getImplementationName ,
        acceptor_getSupportedServiceNames, createSingleComponentFactory ,
        &g_moduleCount.modCnt , 0
    },
    { 0, 0, 0, 0, 0, 0 }
};

extern "C"
{

sal_Bool SAL_CALL component_canUnload( TimeValue *pTime )
{
    return g_moduleCount.canUnload( &g_moduleCount , pTime );
}

//==================================================================================================
void SAL_CALL component_getImplementationEnvironment(
    const sal_Char ** ppEnvTypeName, uno_Environment ** ppEnv )
{
    *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}
//==================================================================================================
sal_Bool SAL_CALL component_writeInfo(
    void * pServiceManager, void * pRegistryKey )
{
    return component_writeInfoHelper( pServiceManager, pRegistryKey, g_entries );
}
//==================================================================================================
void * SAL_CALL component_getFactory(
    const sal_Char * pImplName, void * pServiceManager, void * pRegistryKey )
{
    return component_getFactoryHelper( pImplName, pServiceManager, pRegistryKey , g_entries );
}
}

<commit_msg>INTEGRATION: CWS ooo19126 (1.15.26); FILE MERGED 2005/09/05 17:14:45 rt 1.15.26.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: acceptor.cxx,v $
 *
 *  $Revision: 1.16 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 18:27: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
 *
 ************************************************************************/
#include <osl/mutex.hxx>

#include <uno/mapping.hxx>

#include <cppuhelper/factory.hxx>
#include <cppuhelper/implbase2.hxx>
#include <cppuhelper/implementationentry.hxx>
#include "cppuhelper/unourl.hxx"
#include "rtl/malformeduriexception.hxx"

#include <com/sun/star/connection/XAcceptor.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>

#include "acceptor.hxx"

#define IMPLEMENTATION_NAME "com.sun.star.comp.io.Acceptor"
#define SERVICE_NAME "com.sun.star.connection.Acceptor"

using namespace ::osl;
using namespace ::rtl;
using namespace ::cppu;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::registry;
using namespace ::com::sun::star::connection;

namespace io_acceptor
{
    rtl_StandardModuleCount g_moduleCount = MODULE_COUNT_INIT;

    class OAcceptor : public WeakImplHelper2< XAcceptor, XServiceInfo >
    {
    public:
        OAcceptor(const Reference< XComponentContext > & xCtx);
        virtual ~OAcceptor();
    public:
        // Methods
        virtual Reference< XConnection > SAL_CALL accept( const OUString& sConnectionDescription )
            throw( AlreadyAcceptingException,
                   ConnectionSetupException,
                   IllegalArgumentException,
                   RuntimeException);
        virtual void SAL_CALL stopAccepting(  ) throw( RuntimeException);

    public: // XServiceInfo
                virtual OUString              SAL_CALL getImplementationName() throw();
                virtual Sequence< OUString >  SAL_CALL getSupportedServiceNames(void) throw();
                virtual sal_Bool              SAL_CALL supportsService(const OUString& ServiceName) throw();

    private:
        PipeAcceptor *m_pPipe;
        SocketAcceptor *m_pSocket;
        Mutex m_mutex;
        OUString m_sLastDescription;
        sal_Bool m_bInAccept;

        Reference< XMultiComponentFactory > _xSMgr;
        Reference< XComponentContext > _xCtx;
        Reference<XAcceptor>         _xAcceptor;
    };

    OAcceptor::OAcceptor( const Reference< XComponentContext > & xCtx )
        : m_pPipe( 0 )
        , m_pSocket( 0 )
        , _xSMgr( xCtx->getServiceManager() )
        , _xCtx( xCtx )
        , m_bInAccept( sal_False )
    {
        g_moduleCount.modCnt.acquire( &g_moduleCount.modCnt );
    }

    OAcceptor::~OAcceptor()
    {
        if( m_pPipe )
        {
            delete m_pPipe;
        }
        if( m_pSocket )
        {
            delete m_pSocket;
        }
        g_moduleCount.modCnt.release( &g_moduleCount.modCnt );
    }

    struct BeingInAccept
    {
        BeingInAccept( sal_Bool *pFlag,const OUString & sConnectionDescription  ) throw( AlreadyAcceptingException)
            : m_pFlag( pFlag )
            {
                  if( *m_pFlag )
                  {
                      OUString sMessage( RTL_CONSTASCII_USTRINGPARAM( "AlreadyAcceptingException :" ) );
                      sMessage += sConnectionDescription;
                      throw AlreadyAcceptingException( sMessage , Reference< XInterface > () );
                  }
                  *m_pFlag = sal_True;
            }
        ~BeingInAccept()
            {
                *m_pFlag = sal_False;
            }
        sal_Bool *m_pFlag;
    };

    Reference< XConnection > OAcceptor::accept( const OUString &sConnectionDescription )
        throw( AlreadyAcceptingException,
               ConnectionSetupException,
               IllegalArgumentException,
               RuntimeException)
    {
#if OSL_DEBUG_LEVEL > 1
        OString tmp = OUStringToOString(sConnectionDescription, RTL_TEXTENCODING_ASCII_US);
        OSL_TRACE("acceptor %s\n", tmp.getStr());
#endif
        // if there is a thread alread accepting in this object, throw an exception.
        struct BeingInAccept guard( &m_bInAccept, sConnectionDescription );

        Reference< XConnection > r;
        if( m_sLastDescription.getLength() &&
            m_sLastDescription != sConnectionDescription )
        {
            // instantiate another acceptor for different ports
            OUString sMessage = OUString( RTL_CONSTASCII_USTRINGPARAM(
                "acceptor::accept called multiple times with different conncetion strings\n" ) );
            throw ConnectionSetupException( sMessage, Reference< XInterface > () );
        }

        if( ! m_sLastDescription.getLength() )
        {
            // setup the acceptor
            try
            {
                cppu::UnoUrlDescriptor aDesc(sConnectionDescription);
                if (aDesc.getName().equalsAsciiL(
                        RTL_CONSTASCII_STRINGPARAM("pipe")))
                {
                    rtl::OUString aName(
                        aDesc.getParameter(
                            rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
                                              "name"))));

                    m_pPipe = new PipeAcceptor(aName, sConnectionDescription);

                    try
                    {
                        m_pPipe->init();
                    }
                    catch( ... )
                    {
                        {
                            MutexGuard guard( m_mutex );
                            delete m_pPipe;
                            m_pPipe = 0;
                        }
                        throw;
                    }
                }
                else if (aDesc.getName().equalsAsciiL(
                             RTL_CONSTASCII_STRINGPARAM("socket")))
                {
                    rtl::OUString aHost;
                    if (aDesc.hasParameter(
                            rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("host"))))
                        aHost = aDesc.getParameter(
                            rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("host")));
                    else
                        aHost = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
                                                  "localhost"));
                    sal_uInt16 nPort = static_cast< sal_uInt16 >(
                        aDesc.getParameter(
                            rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("port"))).
                        toInt32());
                    bool bTcpNoDelay
                        = aDesc.getParameter(
                            rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
                                              "tcpnodelay"))).toInt32() != 0;

                    m_pSocket = new SocketAcceptor(
                        aHost, nPort, bTcpNoDelay, sConnectionDescription);

                    try
                    {
                        m_pSocket->init();
                    }
                    catch( ... )
                    {
                        {
                            MutexGuard guard( m_mutex );
                            delete m_pSocket;
                            m_pSocket = 0;
                        }
                        throw;
                    }
                }
                else
                {
                    OUString delegatee = OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.connection.Acceptor."));
                    delegatee += aDesc.getName();

#if OSL_DEBUG_LEVEL > 1
                    OString tmp = OUStringToOString(delegatee, RTL_TEXTENCODING_ASCII_US);
                    OSL_TRACE("trying to get service %s\n", tmp.getStr());
#endif
                    _xAcceptor = Reference<XAcceptor>(
                        _xSMgr->createInstanceWithContext(delegatee, _xCtx), UNO_QUERY);

                    if(!_xAcceptor.is())
                    {
                        OUString message(RTL_CONSTASCII_USTRINGPARAM("Acceptor: unknown delegatee "));
                        message += delegatee;

                        throw ConnectionSetupException(message, Reference<XInterface>());
                    }
                }
            }
            catch (rtl::MalformedUriException & rEx)
            {
                throw IllegalArgumentException(
                    rEx.getMessage(),
                    Reference< XInterface > (),
                    0 );
            }
            m_sLastDescription = sConnectionDescription;
        }

        if( m_pPipe )
        {
            r = m_pPipe->accept();
        }
        else if( m_pSocket )
        {
            r = m_pSocket->accept();
        }
        else
        {
            r = _xAcceptor->accept(sConnectionDescription);
        }

        return r;
    }

    void SAL_CALL OAcceptor::stopAccepting(  ) throw( RuntimeException)
    {
        MutexGuard guard( m_mutex );

        if( m_pPipe )
        {
            m_pPipe->stopAccepting();
        }
        else if ( m_pSocket )
        {
            m_pSocket->stopAccepting();
        }
        else if( _xAcceptor.is() )
        {
            _xAcceptor->stopAccepting();
        }

    }

    OUString acceptor_getImplementationName()
    {
        return OUString( RTL_CONSTASCII_USTRINGPARAM( IMPLEMENTATION_NAME ) );
    }

    Reference< XInterface > SAL_CALL acceptor_CreateInstance( const Reference< XComponentContext > & xCtx)
    {
        return Reference < XInterface >( ( OWeakObject * ) new OAcceptor(xCtx) );
    }

    Sequence< OUString > acceptor_getSupportedServiceNames()
    {
        static Sequence < OUString > *pNames = 0;
        if( ! pNames )
        {
            MutexGuard guard( Mutex::getGlobalMutex() );
            if( !pNames )
            {
                static Sequence< OUString > seqNames(1);
                seqNames.getArray()[0] = OUString::createFromAscii( SERVICE_NAME );
                pNames = &seqNames;
            }
        }
        return *pNames;
    }

        OUString OAcceptor::getImplementationName() throw()
    {
        return acceptor_getImplementationName();
    }

        sal_Bool OAcceptor::supportsService(const OUString& ServiceName) throw()
    {
        Sequence< OUString > aSNL = getSupportedServiceNames();
        const OUString * pArray = aSNL.getConstArray();

        for( sal_Int32 i = 0; i < aSNL.getLength(); i++ )
            if( pArray[i] == ServiceName )
                return sal_True;

        return sal_False;
    }

        Sequence< OUString > OAcceptor::getSupportedServiceNames(void) throw()
    {
        return acceptor_getSupportedServiceNames();
    }

}

using namespace io_acceptor;

static struct ImplementationEntry g_entries[] =
{
    {
        acceptor_CreateInstance, acceptor_getImplementationName ,
        acceptor_getSupportedServiceNames, createSingleComponentFactory ,
        &g_moduleCount.modCnt , 0
    },
    { 0, 0, 0, 0, 0, 0 }
};

extern "C"
{

sal_Bool SAL_CALL component_canUnload( TimeValue *pTime )
{
    return g_moduleCount.canUnload( &g_moduleCount , pTime );
}

//==================================================================================================
void SAL_CALL component_getImplementationEnvironment(
    const sal_Char ** ppEnvTypeName, uno_Environment ** ppEnv )
{
    *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}
//==================================================================================================
sal_Bool SAL_CALL component_writeInfo(
    void * pServiceManager, void * pRegistryKey )
{
    return component_writeInfoHelper( pServiceManager, pRegistryKey, g_entries );
}
//==================================================================================================
void * SAL_CALL component_getFactory(
    const sal_Char * pImplName, void * pServiceManager, void * pRegistryKey )
{
    return component_getFactoryHelper( pImplName, pServiceManager, pRegistryKey , g_entries );
}
}

<|endoftext|>


<commit_before>#pragma once

#include "../../../../include/cpp/ListNode.hxx"

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
  ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
    ListNode* solution = new ListNode{0};
    ListNode* curr = solution;

    ListNode* linkA = l1, * linkB = l2;

    int sum;
    bool isGreater10{false};
    for (; linkA != nullptr && linkB != nullptr; (linkA = linkA->next), linkB = linkB->next) {
      sum = linkA->val + linkB->val;

      if (isGreater10) {
        ++sum;
      }

      isGreater10 = sum > 9;

      if (isGreater10) {
        sum -= 10;
      }

      curr->val = sum;

      if (linkA->next != nullptr) {
        curr->next = new ListNode{1};
        curr = curr->next;
      }
    }

    if (isGreater10) {
      curr->next = new ListNode{1};
    }

    return solution;
  }
};
<commit_msg>add checks for null<commit_after>#pragma once

#include "../../../../include/cpp/ListNode.hxx"

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
  ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
    ListNode* solution = new ListNode{0};
    ListNode* curr = solution;

    ListNode* linkA = l1, * linkB = l2;

    int sum;
    bool isGreater10{false};
    for (; linkA != nullptr || linkB != nullptr; ) {
      sum = linkA->val + linkB->val;

      if (isGreater10) {
        ++sum;
      }

      isGreater10 = sum > 9;

      if (isGreater10) {
        sum -= 10;
      }

      curr->val = sum;

      if (linkA != nullptr) {
        linkA = linkA->next;
      }

      if (linkB != nullptr) {
        linkB = linkB->next;
      }

      if (linkA == nullptr && linkB == nullptr) {
        curr->next = new ListNode{1};
        curr = curr->next;
      }
    }

    if (isGreater10) {
      curr->next = new ListNode{1};
    }

    return solution;
  }
};
<|endoftext|>