<commit_before>#pragma once

#include <limits>
#include <algorithm>
#include <vector>
#include <map>
#include <functional>

using std::max;
using std::make_pair;
using std::min;
using std::abs;
using std::hypot;
using std::vector;
using std::map;
using std::function;

namespace search
{
    //
    //  Lifelong planning
    //
    namespace lp
    {
        constexpr auto infinity() -> int
        {
            return std::numeric_limits<int>::max();
        }
        constexpr auto cost() -> int
        {
            return 1;
        }

        struct Coordinate
        {
            const int x, y;

            friend auto operator== (Coordinate l, Coordinate r)
            {
                return l.x == r.x && l.y == r.y;
            }
            friend auto operator!= (Coordinate l, Coordinate r)
            {
                return !(l == r);
            }

            auto neighbours() const -> vector<Coordinate>
            {
                struct Directions : public map< char, function< Coordinate(Coordinate) >>
                {
                    Directions()
                    {
                        (*this)['1'] = [](Coordinate c) -> Coordinate { return{ c.x - 1, c.y - 1 }; };
                        (*this)['2'] = [](Coordinate c) -> Coordinate { return{ c.x - 0, c.y - 1 }; };
                        (*this)['3'] = [](Coordinate c) -> Coordinate { return{ c.x + 1, c.y - 1 }; };
                        (*this)['4'] = [](Coordinate c) -> Coordinate { return{ c.x - 1, c.y - 0 }; };
                        (*this)['5'] = [](Coordinate c) -> Coordinate { return{ c.x + 1, c.y + 0 }; };
                        (*this)['6'] = [](Coordinate c) -> Coordinate { return{ c.x - 1, c.y + 1 }; };
                        (*this)['7'] = [](Coordinate c) -> Coordinate { return{ c.x - 0, c.y + 1 }; };
                        (*this)['8'] = [](Coordinate c) -> Coordinate { return{ c.x + 1, c.y + 1 }; };
                    }
                } static const directions;

                vector<Coordinate> result;
                for (auto n = '1'; n != '9'; ++n)
                    result.push_back(directions.at(n)(*this));
                return result;
            }
        };

        struct LpState
        {
            struct Key
            {
                const int first, second;

                friend auto operator== (Key l, Key r) -> bool
                {
                    return l.first == r.first && l.second == r.second;
                }
                friend auto operator < (Key l, Key r) -> bool
                {
                    return (l.first < r.first) || (l.first == r.first && l.second < r.second);
                }
            };

            const Coordinate coordinate;
            int g, r;

            template<typename Hfunc>
            auto key(Hfunc h) const -> Key
            {
                return{ min(g, r + h(coordinate)), min(g, r) };
            }
        };

        struct LpManhattanDistance
        {
            const Coordinate goal;
            auto operator()(Coordinate c) const -> int
            {
                return max(abs(goal.x - c.x), abs(goal.y - c.y));
            }
        };

        struct LpEuclideanDistance
        {
            const Coordinate goal;
            auto operator()(Coordinate c) const -> int
            {
                auto result = hypot(abs(goal.x - c.x), abs(goal.y - c.y));
                return static_cast<int>(round(result));
            }
        };
    }
}<commit_msg>remove return type<commit_after>#pragma once

#include <limits>
#include <algorithm>
#include <vector>
#include <map>
#include <functional>

using std::max;
using std::make_pair;
using std::min;
using std::abs;
using std::hypot;
using std::vector;
using std::map;
using std::function;

namespace search
{
    //
    //  Lifelong planning
    //
    namespace lp
    {
        constexpr auto infinity()
        {
            return std::numeric_limits<int>::max();
        }
        constexpr auto cost()
        {
            return 1;
        }

        struct Coordinate
        {
            const int x, y;

            friend auto operator== (Coordinate l, Coordinate r)
            {
                return l.x == r.x && l.y == r.y;
            }
            friend auto operator!= (Coordinate l, Coordinate r)
            {
                return !(l == r);
            }

            auto neighbours() const
            {
                struct Directions : public map< char, function< Coordinate(Coordinate) >>
                {
                    Directions()
                    {
                        (*this)['1'] = [](Coordinate c) { return Coordinate{ c.x - 1, c.y - 1 }; };
                        (*this)['2'] = [](Coordinate c) { return Coordinate{ c.x - 0, c.y - 1 }; };
                        (*this)['3'] = [](Coordinate c) { return Coordinate{ c.x + 1, c.y - 1 }; };
                        (*this)['4'] = [](Coordinate c) { return Coordinate{ c.x - 1, c.y - 0 }; };
                        (*this)['5'] = [](Coordinate c) { return Coordinate{ c.x + 1, c.y + 0 }; };
                        (*this)['6'] = [](Coordinate c) { return Coordinate{ c.x - 1, c.y + 1 }; };
                        (*this)['7'] = [](Coordinate c) { return Coordinate{ c.x - 0, c.y + 1 }; };
                        (*this)['8'] = [](Coordinate c) { return Coordinate{ c.x + 1, c.y + 1 }; };
                    }
                } static const directions;

                vector<Coordinate> result;
                for (auto n = '1'; n != '9'; ++n)
                    result.push_back(directions.at(n)(*this));
                return result;
            }
        };

        struct LpState
        {
            struct Key
            {
                const int first, second;

                friend auto operator== (Key l, Key r)
                {
                    return l.first == r.first && l.second == r.second;
                }
                friend auto operator < (Key l, Key r)
                {
                    return (l.first < r.first) || (l.first == r.first && l.second < r.second);
                }
            };

            const Coordinate coordinate;
            int g, r;

            template<typename Hfunc>
            auto key(Hfunc h) const
            {
                return Key{ min(g, r + h(coordinate)), min(g, r) };
            }
        };

        struct LpManhattanDistance
        {
            const Coordinate goal;
            auto operator()(Coordinate c) const
            {
                return max(abs(goal.x - c.x), abs(goal.y - c.y));
            }
        };

        struct LpEuclideanDistance
        {
            const Coordinate goal;
            auto operator()(Coordinate c) const
            {
                auto result = hypot(abs(goal.x - c.x), abs(goal.y - c.y));
                return static_cast<int>(round(result));
            }
        };
    }
}<|endoftext|>


<commit_before>/*
 * ply2json
 *
 * The program is a ply file format to json file format converter for use
 * with three.js. The program uses the C++ libraries from the VTK toolkit
 * in order to read in a ply file and convert it into the json file format
 * which can be recongnized by three.js for rendering in the browsing.
 *
 * @Author Migara Liyanamage
 * @Date 19 June 2014
 * @Version 1.0
 *
 */

// Import for VTK Libraries
#include <vtkPLYReader.h>
#include <vtkSmartPointer.h>
#include <vtkCellArray.h>
#include <vtkDecimatePro.h>

// Import for standard C++ libraries
#include <iostream>
#include <fstream>

// Import for program header
#include "ply2json.h"

using namespace std;

// stores the filename of the input file
static string inputFilename;

// store the filename of the output file
static string outputFilename;

// set amount to decimate by, if set to 1 no decimation occurs
static double decAmount;

/*
 * Main Method
 *
 * This method reads in the file which is to be converted from the command line
 * and calls the appropriate methods to begin the conversion.
 *
 */
int main( int argc, char ** argv )
{
    if (argc  < 3)
    {
        // Print Usage Message
        cout << "Usage: " << argv[0] << " filename.ply outputName [decimate amount 0.0 .. 1.0]" << endl;
        return EXIT_FAILURE;
    }

    if (argc == 4)
    {
        decAmount = atof(argv[3]);
    }
    else
    {
        decAmount = 1.0;
    }

    // Assign appropriate file names for the program
    inputFilename = argv[1];
    outputFilename = argv[2];

    // begin generation
    generateJSON();

    return EXIT_SUCCESS;
}

/*
 * Generate JSON Method
 *
 * This method calls the appropriate methods in the vtk toolkit and outputs the
 * JSON file to the output file name specified
 *
 */
void generateJSON()
{
    // File stream for output file
    std::ofstream outputFile;
    outputFile.open(outputFilename.c_str());

    // begin the json file
    outputFile << "{\n";

    // Reader to read in PLY File
    vtkSmartPointer<vtkPLYReader> reader =
        vtkSmartPointer<vtkPLYReader>::New();

    // Specify filename
    reader->SetFileName ( inputFilename.c_str() );

    // Call vtk pipeline to read in the file
    reader->Update();

    vtkDataSet * data;
    vtkIdType vert;
    vtkPolyData * pdata;
    vtkCellArray * faces;
    vtkSmartPointer<vtkPolyData> decimated;

    if (decAmount >= 1.0)
    {
         // Get the outpuyt for vertices
        data = reader->GetOutput();
        vert = data->GetNumberOfPoints();

        // Get the output for polygons
        pdata = reader->GetOutput();
        faces = pdata->GetPolys();
    }
    else if (decAmount < 0.0)
    {
        cout << "Invalid Decimate Amount, Program will now exit" << endl;
        exit(EXIT_FAILURE);
    } else
    {
        // create decimator
        vtkSmartPointer<vtkDecimatePro> decimate = vtkSmartPointer<vtkDecimatePro>::New();

        // set decimator to the selected file
        decimate->SetInputData(reader->GetOutput());

        // set target to reduce to, and set topology to be preserved
        decimate->PreserveTopologyOn();
        decimate->SetTargetReduction(decAmount);

        // start decimation
        decimate->Update();

        decimated =
            vtkSmartPointer<vtkPolyData>::New();
        decimated->ShallowCopy(decimate->GetOutput());

        // Get the outpuyt for vertices
        data = decimated;
        vert = decimated->GetNumberOfPoints();

        // Get the output for polygons
        faces = decimated->GetPolys();
    }

    vtkIdType numCells = faces->GetNumberOfCells();

    vtkIdType cellLocation = 0;

    // Write the standard format header for the json file
    outputFile << "\"metadata\":{\"formatVersion\":3,\"vertices\":" << vert << ",\"faces\":" << numCells << ",\"materials\":1},\n";
    outputFile << "\"scale\":1.0,\n\"materials\":[{\"DbgColor\":15658734,\"DbgIndex\":0,\"DbgName\":\"default\",\"vertexColors\": false}],\n";

    // Begin writing vertices
    outputFile << "\"vertices\":[";

    // Iterate over all the points and print them to the file
    for(vtkIdType i = 0; i < vert; i++)
    {
        double p[3];
        data->GetPoint(i, p);
        outputFile << p[0] << "," << p[1] << "," << p[2];
        if (i != vert - 1) outputFile << ","; // Avoid putting comma before end bracket
    }
    // End the vertices section
    outputFile << "],\n";

    // Begin writing faces
    outputFile << "\"faces\":[";

    // Iterate over the faces and print them to file
    for (vtkIdType i = 0; i < numCells; i++)
    {
        vtkIdType numIDs;
        vtkIdType * pointIds;

        faces->GetCell(cellLocation, numIDs, pointIds);
        cellLocation += 1 + numIDs; // increment to include already printed faces

        for (vtkIdType j = 0; j < numIDs; j++)
        {
            // print to the file
            // printing the zero is for the bit mask signifying face type
            if (j == 0) outputFile << 0 << ",";
            outputFile << pointIds[j];
            if (i != numCells - 1)
            {
                outputFile << ",";
            }
            else
            {
                if(j != numIDs - 1) outputFile << ","; // avoid additional comma at end
            }
        }
    }

    // end faces section
    outputFile << "]\n";

    // end the json file
    outputFile << "}\n";

    // flush the file stream
    outputFile.flush();

    // close file stream
    outputFile.close();
}
<commit_msg>added more helpful message<commit_after>/*
 * ply2json
 *
 * The program is a ply file format to json file format converter for use
 * with three.js. The program uses the C++ libraries from the VTK toolkit
 * in order to read in a ply file and convert it into the json file format
 * which can be recongnized by three.js for rendering in the browsing.
 *
 * @Author Migara Liyanamage
 * @Date 19 June 2014
 * @Version 1.0
 *
 */

// Import for VTK Libraries
#include <vtkPLYReader.h>
#include <vtkSmartPointer.h>
#include <vtkCellArray.h>
#include <vtkDecimatePro.h>

// Import for standard C++ libraries
#include <iostream>
#include <fstream>

// Import for program header
#include "ply2json.h"

using namespace std;

// stores the filename of the input file
static string inputFilename;

// store the filename of the output file
static string outputFilename;

// set amount to decimate by, if set to 1 no decimation occurs
static double decAmount;

/*
 * Main Method
 *
 * This method reads in the file which is to be converted from the command line
 * and calls the appropriate methods to begin the conversion.
 *
 */
int main( int argc, char ** argv )
{
    if (argc  < 3)
    {
        // Print Usage Message
        cout << "Usage: " << argv[0] << " filename.ply outputName [decimate amount 0.0 .. 1.0]" << endl;
        cout << "\nfilename.ply - Name of PLY file to convert" << endl;
        cout << "outputName - Name of output file with extension" << endl;
        cout << "decimate amount - Amount to decimate image by, zero is no decimation, one is maximum" << endl;
        return EXIT_FAILURE;
    }

    if (argc == 4)
    {
        decAmount = atof(argv[3]);
    }
    else
    {
        decAmount = 1.0;
    }

    // Assign appropriate file names for the program
    inputFilename = argv[1];
    outputFilename = argv[2];

    // begin generation
    generateJSON();

    return EXIT_SUCCESS;
}

/*
 * Generate JSON Method
 *
 * This method calls the appropriate methods in the vtk toolkit and outputs the
 * JSON file to the output file name specified
 *
 */
void generateJSON()
{
    // File stream for output file
    std::ofstream outputFile;
    outputFile.open(outputFilename.c_str());

    // begin the json file
    outputFile << "{\n";

    // Reader to read in PLY File
    vtkSmartPointer<vtkPLYReader> reader =
        vtkSmartPointer<vtkPLYReader>::New();

    // Specify filename
    reader->SetFileName ( inputFilename.c_str() );

    // Call vtk pipeline to read in the file
    reader->Update();

    vtkDataSet * data;
    vtkIdType vert;
    vtkPolyData * pdata;
    vtkCellArray * faces;
    vtkSmartPointer<vtkPolyData> decimated;

    if (decAmount >= 1.0)
    {
         // Get the outpuyt for vertices
        data = reader->GetOutput();
        vert = data->GetNumberOfPoints();

        // Get the output for polygons
        pdata = reader->GetOutput();
        faces = pdata->GetPolys();
    }
    else if (decAmount < 0.0)
    {
        cout << "Invalid Decimate Amount, Program will now exit" << endl;
        exit(EXIT_FAILURE);
    } else
    {
        // create decimator
        vtkSmartPointer<vtkDecimatePro> decimate = vtkSmartPointer<vtkDecimatePro>::New();

        // set decimator to the selected file
        decimate->SetInputData(reader->GetOutput());

        // set target to reduce to, and set topology to be preserved
        decimate->PreserveTopologyOn();
        decimate->SetTargetReduction(decAmount);

        // start decimation
        decimate->Update();

        decimated =
            vtkSmartPointer<vtkPolyData>::New();
        decimated->ShallowCopy(decimate->GetOutput());

        // Get the outpuyt for vertices
        data = decimated;
        vert = decimated->GetNumberOfPoints();

        // Get the output for polygons
        faces = decimated->GetPolys();
    }

    vtkIdType numCells = faces->GetNumberOfCells();

    vtkIdType cellLocation = 0;

    // Write the standard format header for the json file
    outputFile << "\"metadata\":{\"formatVersion\":3,\"vertices\":" << vert << ",\"faces\":" << numCells << ",\"materials\":1},\n";
    outputFile << "\"scale\":1.0,\n\"materials\":[{\"DbgColor\":15658734,\"DbgIndex\":0,\"DbgName\":\"default\",\"vertexColors\": false}],\n";

    // Begin writing vertices
    outputFile << "\"vertices\":[";

    // Iterate over all the points and print them to the file
    for(vtkIdType i = 0; i < vert; i++)
    {
        double p[3];
        data->GetPoint(i, p);
        outputFile << p[0] << "," << p[1] << "," << p[2];
        if (i != vert - 1) outputFile << ","; // Avoid putting comma before end bracket
    }
    // End the vertices section
    outputFile << "],\n";

    // Begin writing faces
    outputFile << "\"faces\":[";

    // Iterate over the faces and print them to file
    for (vtkIdType i = 0; i < numCells; i++)
    {
        vtkIdType numIDs;
        vtkIdType * pointIds;

        faces->GetCell(cellLocation, numIDs, pointIds);
        cellLocation += 1 + numIDs; // increment to include already printed faces

        for (vtkIdType j = 0; j < numIDs; j++)
        {
            // print to the file
            // printing the zero is for the bit mask signifying face type
            if (j == 0) outputFile << 0 << ",";
            outputFile << pointIds[j];
            if (i != numCells - 1)
            {
                outputFile << ",";
            }
            else
            {
                if(j != numIDs - 1) outputFile << ","; // avoid additional comma at end
            }
        }
    }

    // end faces section
    outputFile << "]\n";

    // end the json file
    outputFile << "}\n";

    // flush the file stream
    outputFile.flush();

    // close file stream
    outputFile.close();
}
<|endoftext|>


<commit_before>#include <boost/program_options.hpp>
#include <iostream>
#include "RecommendLister.h"
#include "CategoryLister.h"
#include "ListCollection.h"

using namespace boost::program_options;
using namespace songtaste;
using namespace std;

int main(int argc, char *argv[])
{
    options_description desc("Usage");
    desc.add_options()
    ("help,h",      "show help information")
    ("recommend",   "get recommend list")
    ("category",    "get category list")
    ("catsong",     "get song list from a category, require --catid")
    ("catid",       value<unsigned int>(), "category id")
    ("page",        value<unsigned int>(), "page number, default to 1");

    variables_map vm;
    try {
        store(parse_command_line(argc, argv, desc), vm);
    } catch (std::exception &ex) {
        cout << ex.what() << endl;
        return -1;
    }
    notify(vm);

    try {

        do {
            if (vm.count("help") || argc == 1) {
                cout << desc;
                break;
            }

            if (vm.count("recommend")) {
                unsigned int page = vm.count("page") ? vm["page"].as<unsigned int>() : 1;
                ILister *pLister  = new RecommendLister;
                cout << pLister->getListAt(page)->toJsonString();
                SAFERELEASE(pLister);
                break;
            }

            if (vm.count("category")) {
                ILister *lister = new CategoryLister;
                cout << lister->getListAt()->toJsonString();
                SAFERELEASE(lister);
                break;
            }

            if (vm.count("catsong") && vm.count("catid")) {
                unsigned int catid = vm["catid"].as<unsigned int>();
                unsigned int page  = vm.count("page") ? vm["page"].as<unsigned int>() : 1;
                CategoryLister *lister = new CategoryLister;
                cout << lister->getMusicByCatid(catid, page)->toJsonString();
                break;
            }

        } while (0);

    } catch (const exception &err) {
        cout << err.what() << endl;
    }

    return 0;
}
<commit_msg>修正一处内存泄漏<commit_after>#include <boost/program_options.hpp>
#include <iostream>
#include "RecommendLister.h"
#include "CategoryLister.h"
#include "ListCollection.h"

using namespace boost::program_options;
using namespace songtaste;
using namespace std;

int main(int argc, char *argv[])
{
    options_description desc("Usage");
    desc.add_options()
    ("help,h",      "show help information")
    ("recommend",   "get recommend list")
    ("category",    "get category list")
    ("catsong",     "get song list from a category, require --catid")
    ("catid",       value<unsigned int>(), "category id")
    ("page",        value<unsigned int>(), "page number, default to 1");

    variables_map vm;
    try {
        store(parse_command_line(argc, argv, desc), vm);
    } catch (std::exception &ex) {
        cout << ex.what() << endl;
        return -1;
    }
    notify(vm);

    try {

        do {
            if (vm.count("help") || argc == 1) {
                cout << desc;
                break;
            }

            if (vm.count("recommend")) {
                unsigned int page = vm.count("page") ? vm["page"].as<unsigned int>() : 1;
                ILister *pLister  = new RecommendLister;
                cout << pLister->getListAt(page)->toJsonString();
                SAFERELEASE(pLister);
                break;
            }

            if (vm.count("category")) {
                ILister *lister = new CategoryLister;
                cout << lister->getListAt()->toJsonString();
                SAFERELEASE(lister);
                break;
            }

            if (vm.count("catsong") && vm.count("catid")) {
                unsigned int catid = vm["catid"].as<unsigned int>();
                unsigned int page  = vm.count("page") ? vm["page"].as<unsigned int>() : 1;
                CategoryLister *lister = new CategoryLister;
                cout << lister->getMusicByCatid(catid, page)->toJsonString();
                SAFERELEASE(lister);
                break;
            }

        } while (0);

    } catch (const exception &err) {
        cout << err.what() << endl;
    }

    return 0;
}
<|endoftext|>


<commit_before>/*
 * qconnman - Connman Applet
 * Copyright (C) 2011 O.S. Systems
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License.
 *
 * 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include "ipv4widget.h"

#include <QDebug>

#include <qconnman/service.h>

Ipv4Widget::Ipv4Widget(QWidget *parent):
    QFrame(parent)
{
    ui.setupUi(this);
}

void Ipv4Widget::setSettings(IPV4Data *ipv4)
{
    if (!ipv4)
    {
        ui.autoIpAddress->setChecked(true);
        ui.autoDns->setChecked(true);

        ui.address->clear();
        ui.netmask->clear();
        ui.gateway->clear();

        return;
    }

    ui.autoIpAddress->setChecked(ipv4->method() == "dhcp");
    ui.manualIpAddress->setChecked(ipv4->method() != "dhcp");

    ui.address->setText(ipv4->address());
    ui.netmask->setText(ipv4->netmask());
    if (ipv4->gateway() != "0.0.0.0")
        ui.gateway->setText(ipv4->gateway());
}

void Ipv4Widget::apply(Service *service)
{
    QVariantMap map;

    if (ui.autoIpAddress->isChecked())
    {
        service->ipv4Configuration()->setMethod("dhcp");
    }
    else if (ui.manualIpAddress->isChecked())
    {
        service->ipv4Configuration()->setMethod("manual");
        service->ipv4Configuration()->setAddress(ui.address->text());
        service->ipv4Configuration()->setNetmask(ui.netmask->text());
        if (ui.gateway->text().isEmpty())
            service->ipv4Configuration()->setGateway("0.0.0.0");
        else
            service->ipv4Configuration()->setGateway(ui.gateway->text());
    }
}

void Ipv4Widget::on_autoIpAddress_stateChanged(int state)
{
    ui.manualIpAddress->setChecked(state == Qt::Checked ? false : true);
}

void Ipv4Widget::on_manualIpAddress_toggled(bool on)
{
    ui.autoIpAddress->setCheckState(on ? Qt::Unchecked : Qt::Checked);
    if (on)
        ui.manualDns->setChecked(true);
}

void Ipv4Widget::on_autoDns_stateChanged(int state)
{
    ui.manualDns->setChecked(state == Qt::Checked ? false : true);

    if (state == Qt::Checked)
    {
        ui.autoIpAddress->setCheckState(Qt::Checked);
        ui.preferredDns->clear();
        ui.alternateDns->clear();
    }
}

void Ipv4Widget::on_manualDns_toggled(bool on)
{
    ui.autoDns->setCheckState(on ? Qt::Unchecked : Qt::Checked);
}
<commit_msg>Apply IPV4 configuration<commit_after>/*
 * qconnman - Connman Applet
 * Copyright (C) 2011 O.S. Systems
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License.
 *
 * 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include "ipv4widget.h"

#include <QDebug>

#include <qconnman/service.h>

Ipv4Widget::Ipv4Widget(QWidget *parent):
    QFrame(parent)
{
    ui.setupUi(this);
}

void Ipv4Widget::setSettings(IPV4Data *ipv4)
{
    if (!ipv4)
    {
        ui.autoIpAddress->setChecked(true);
        ui.autoDns->setChecked(true);

        ui.address->clear();
        ui.netmask->clear();
        ui.gateway->clear();

        return;
    }

    ui.autoIpAddress->setChecked(ipv4->method() == "dhcp");
    ui.manualIpAddress->setChecked(ipv4->method() != "dhcp");

    ui.address->setText(ipv4->address());
    ui.netmask->setText(ipv4->netmask());
    if (ipv4->gateway() != "0.0.0.0")
        ui.gateway->setText(ipv4->gateway());
}

void Ipv4Widget::apply(Service *service)
{
    if (ui.autoIpAddress->isChecked())
    {
        service->ipv4Configuration()->setMethod("dhcp");
    }
    else if (ui.manualIpAddress->isChecked())
    {
        service->ipv4Configuration()->setMethod("manual");
        service->ipv4Configuration()->setAddress(ui.address->text());
        service->ipv4Configuration()->setNetmask(ui.netmask->text());
        if (ui.gateway->text().isEmpty())
            service->ipv4Configuration()->setGateway("0.0.0.0");
        else
            service->ipv4Configuration()->setGateway(ui.gateway->text());

        service->ipv4Configuration()->apply();
    }
}

void Ipv4Widget::on_autoIpAddress_stateChanged(int state)
{
    ui.manualIpAddress->setChecked(state == Qt::Checked ? false : true);
}

void Ipv4Widget::on_manualIpAddress_toggled(bool on)
{
    ui.autoIpAddress->setCheckState(on ? Qt::Unchecked : Qt::Checked);
    if (on)
        ui.manualDns->setChecked(true);
}

void Ipv4Widget::on_autoDns_stateChanged(int state)
{
    ui.manualDns->setChecked(state == Qt::Checked ? false : true);

    if (state == Qt::Checked)
    {
        ui.autoIpAddress->setCheckState(Qt::Checked);
        ui.preferredDns->clear();
        ui.alternateDns->clear();
    }
}

void Ipv4Widget::on_manualDns_toggled(bool on)
{
    ui.autoDns->setCheckState(on ? Qt::Unchecked : Qt::Checked);
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: JoinDesignView.cxx,v $
 *
 *  $Revision: 1.18 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-20 03:25:36 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef DBAUI_JOINDESIGNVIEW_HXX
#include "JoinDesignView.hxx"
#endif
#ifndef DBAUI_JOINTABLEVIEW_HXX
#include "JoinTableView.hxx"
#endif
#ifndef DBAUI_JOINCONTROLLER_HXX
#include "JoinController.hxx"
#endif
#ifndef _UNDO_HXX
#include <svtools/undo.hxx>
#endif
#ifndef DBAUI_QYDLGTAB_HXX
#include "adtabdlg.hxx"
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#ifndef DBACCESS_UI_BROWSER_ID_HXX
#include "browserids.hxx"
#endif
#ifndef _DBU_QRY_HRC_
#include "dbu_qry.hrc"
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _CONNECTIVITY_DBTOOLS_HXX_
#include <connectivity/dbtools.hxx>
#endif
#ifndef _COM_SUN_STAR_SDBC_DATATYPE_HPP_
#include <com/sun/star/sdbc/DataType.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef DBAUI_TABLECONNECTION_HXX
#include "TableConnection.hxx"
#endif
#ifndef DBAUI_CONNECTIONLINE_HXX
#include "ConnectionLine.hxx"
#endif
#ifndef DBAUI_CONNECTIONLINEDATA_HXX
#include "ConnectionLineData.hxx"
#endif
#ifndef DBAUI_TABLECONNECTIONDATA_HXX
#include "TableConnectionData.hxx"
#endif
#ifndef DBACCESS_SHARED_DBUSTRINGS_HRC
#include "dbustrings.hrc"
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef DBAUI_TOOLS_HXX
#include "UITools.hxx"
#endif
#ifndef DBAUI_JOINTABLEVIEW_HXX
#include "JoinTableView.hxx"
#endif
//  #include <com/sun/star/util/URL.hdl>

using namespace ::dbaui;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::i18n;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::util;
DBG_NAME(OJoinDesignView)

OJoinDesignView::OJoinDesignView(Window* _pParent, OJoinController* _pController,const Reference< XMultiServiceFactory >& _rFactory)
    :ODataView(_pParent,_pController,_rFactory)
    ,m_pTableView(NULL)
    ,m_pAddTabDlg(NULL)
    ,m_pController(_pController)
{
    DBG_CTOR(OJoinDesignView,NULL);

    m_pScrollWindow = new OScrollWindowHelper(this);
}
// -----------------------------------------------------------------------------
OJoinDesignView::~OJoinDesignView()
{
    if ( m_pController )
        m_pController->clearAddTableDialog();
    ::std::auto_ptr<Window> aT3(m_pScrollWindow);
    m_pScrollWindow = NULL;
    ::std::auto_ptr<Window> aT2(m_pTableView);
    m_pTableView = NULL;
    ::std::auto_ptr<Window> aT1(m_pAddTabDlg);
    m_pAddTabDlg = NULL;

    DBG_DTOR(OJoinDesignView,NULL);
}
// -------------------------------------------------------------------------
void OJoinDesignView::Construct()
{
    m_pScrollWindow->setTableView(m_pTableView);
    m_pScrollWindow->Show();
    m_pTableView->Show();

    m_pAddTabDlg = new OAddTableDlg(m_pScrollWindow,m_pTableView);
    SetBackground( Wallpaper( Application::GetSettings().GetStyleSettings().GetFaceColor()) );

    ODataView::Construct();
}
// -----------------------------------------------------------------------------
void OJoinDesignView::initialize()
{
    //  getAddTableDialog()->Update();
}
// -------------------------------------------------------------------------
void OJoinDesignView::resizeDocumentView(Rectangle& _rPlayground)
{
    m_pScrollWindow->SetPosSizePixel( _rPlayground.TopLeft(), _rPlayground.GetSize() );

    // just for completeness: there is no space left, we occupied it all ...
    _rPlayground.SetPos( _rPlayground.BottomRight() );
    _rPlayground.SetSize( Size( 0, 0 ) );
}
// -----------------------------------------------------------------------------
void OJoinDesignView::setReadOnly(sal_Bool /*_bReadOnly*/)
{
}
// -----------------------------------------------------------------------------
void OJoinDesignView::TableDeleted(const ::rtl::OUString& /*rAliasName*/)
{
}
// -----------------------------------------------------------------------------
void OJoinDesignView::zoomTableView(const Fraction& _rFraction)
{
    m_pTableView->SetZoom(_rFraction);
}
// -----------------------------------------------------------------------------
void OJoinDesignView::SaveUIConfig()
{
    OJoinController* pCtrl = getController();
    if (pCtrl)
        pCtrl->SaveTabWinsPosSize( m_pTableView->GetTabWinMap(), m_pScrollWindow->GetHScrollBar()->GetThumbPos(), m_pScrollWindow->GetVScrollBar()->GetThumbPos() );
}
// -----------------------------------------------------------------------------
void OJoinDesignView::SaveTabWinUIConfig(OTableWindow* pWin)
{
    getController()->SaveTabWinPosSize(pWin, m_pScrollWindow->GetHScrollBar()->GetThumbPos(), m_pScrollWindow->GetVScrollBar()->GetThumbPos());
}
// -----------------------------------------------------------------------------
void OJoinDesignView::KeyInput( const KeyEvent& rEvt )
{
    if ( m_pTableView && m_pTableView->IsVisible() )
        m_pTableView->KeyInput( rEvt );
    else
        ODataView::KeyInput(rEvt);
}
// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS qiq (1.17.118); FILE MERGED 2006/06/28 10:31:11 fs 1.17.118.4: #i10000# 2006/06/27 12:51:59 fs 1.17.118.3: RESYNC: (1.17-1.18); FILE MERGED 2006/05/17 11:45:29 fs 1.17.118.2: #i51143# AddTableDialog is now in the responsibility of the controller, not the view (allows late construction as needed) 2006/05/12 11:11:02 fs 1.17.118.1: #i51143# callback from the AddTabDialog now via dedicated interface<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: JoinDesignView.cxx,v $
 *
 *  $Revision: 1.19 $
 *
 *  last change: $Author: obo $ $Date: 2006-07-10 15:40:20 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef DBAUI_JOINDESIGNVIEW_HXX
#include "JoinDesignView.hxx"
#endif
#ifndef DBAUI_JOINTABLEVIEW_HXX
#include "JoinTableView.hxx"
#endif
#ifndef DBAUI_JOINCONTROLLER_HXX
#include "JoinController.hxx"
#endif
#ifndef _UNDO_HXX
#include <svtools/undo.hxx>
#endif
#ifndef DBAUI_QYDLGTAB_HXX
#include "adtabdlg.hxx"
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#ifndef DBACCESS_UI_BROWSER_ID_HXX
#include "browserids.hxx"
#endif
#ifndef _DBU_QRY_HRC_
#include "dbu_qry.hrc"
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _CONNECTIVITY_DBTOOLS_HXX_
#include <connectivity/dbtools.hxx>
#endif
#ifndef _COM_SUN_STAR_SDBC_DATATYPE_HPP_
#include <com/sun/star/sdbc/DataType.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef DBAUI_TABLECONNECTION_HXX
#include "TableConnection.hxx"
#endif
#ifndef DBAUI_CONNECTIONLINE_HXX
#include "ConnectionLine.hxx"
#endif
#ifndef DBAUI_CONNECTIONLINEDATA_HXX
#include "ConnectionLineData.hxx"
#endif
#ifndef DBAUI_TABLECONNECTIONDATA_HXX
#include "TableConnectionData.hxx"
#endif
#ifndef DBACCESS_SHARED_DBUSTRINGS_HRC
#include "dbustrings.hrc"
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef DBAUI_TOOLS_HXX
#include "UITools.hxx"
#endif
#ifndef DBAUI_JOINTABLEVIEW_HXX
#include "JoinTableView.hxx"
#endif
//  #include <com/sun/star/util/URL.hdl>

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::i18n;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::util;

namespace dbaui
{

// =============================================================================
// = OJoinDesignView
// =============================================================================
// -----------------------------------------------------------------------------
OJoinDesignView::OJoinDesignView(Window* _pParent, OJoinController* _pController,const Reference< XMultiServiceFactory >& _rFactory)
    :ODataView(_pParent,_pController,_rFactory)
    ,m_pTableView(NULL)
    ,m_pController(_pController)
{
    m_pScrollWindow = new OScrollWindowHelper(this);
}
// -----------------------------------------------------------------------------
OJoinDesignView::~OJoinDesignView()
{
    ::std::auto_ptr<Window> aT3(m_pScrollWindow);
    m_pScrollWindow = NULL;
    ::std::auto_ptr<Window> aT2(m_pTableView);
    m_pTableView = NULL;
}
// -------------------------------------------------------------------------
void OJoinDesignView::Construct()
{
    m_pScrollWindow->setTableView(m_pTableView);
    m_pScrollWindow->Show();
    m_pTableView->Show();

    SetBackground( Wallpaper( Application::GetSettings().GetStyleSettings().GetFaceColor()) );

    ODataView::Construct();
}
// -----------------------------------------------------------------------------
void OJoinDesignView::initialize()
{
    //  getAddTableDialog()->Update();
}
// -------------------------------------------------------------------------
void OJoinDesignView::resizeDocumentView(Rectangle& _rPlayground)
{
    m_pScrollWindow->SetPosSizePixel( _rPlayground.TopLeft(), _rPlayground.GetSize() );

    // just for completeness: there is no space left, we occupied it all ...
    _rPlayground.SetPos( _rPlayground.BottomRight() );
    _rPlayground.SetSize( Size( 0, 0 ) );
}
// -----------------------------------------------------------------------------
void OJoinDesignView::setReadOnly(sal_Bool /*_bReadOnly*/)
{
}
// -----------------------------------------------------------------------------
void OJoinDesignView::TableDeleted(const ::rtl::OUString& /*rAliasName*/)
{
}
// -----------------------------------------------------------------------------
void OJoinDesignView::zoomTableView(const Fraction& _rFraction)
{
    m_pTableView->SetZoom(_rFraction);
}
// -----------------------------------------------------------------------------
void OJoinDesignView::SaveUIConfig()
{
    OJoinController* pCtrl = getController();
    if (pCtrl)
        pCtrl->SaveTabWinsPosSize( m_pTableView->GetTabWinMap(), m_pScrollWindow->GetHScrollBar()->GetThumbPos(), m_pScrollWindow->GetVScrollBar()->GetThumbPos() );
}
// -----------------------------------------------------------------------------
void OJoinDesignView::SaveTabWinUIConfig(OTableWindow* pWin)
{
    getController()->SaveTabWinPosSize(pWin, m_pScrollWindow->GetHScrollBar()->GetThumbPos(), m_pScrollWindow->GetVScrollBar()->GetThumbPos());
}
// -----------------------------------------------------------------------------
void OJoinDesignView::KeyInput( const KeyEvent& rEvt )
{
    if ( m_pTableView && m_pTableView->IsVisible() )
        m_pTableView->KeyInput( rEvt );
    else
        ODataView::KeyInput(rEvt);
}
// -----------------------------------------------------------------------------

}   // namespace dbaui

<|endoftext|>


<commit_before>#include "Music.hpp"

//#include <Plinth/Generic.hpp>

Music::Music():
m_track(Track::Ready),
m_pMusic(&m_ready),
m_isDimmed(false)
{
	const std::string resourcePath = "resources/";
	if (!m_ready.openFromFile(resourcePath + "puzza-ready.ogg") ||
		!m_play.openFromFile(resourcePath + "puzza-play.ogg"))
		throw("Could not find music.");

	m_ready.setLoop(true);
	m_play.setLoop(true);
}

void Music::play(Track track)
{
	m_track = track;
	m_pMusic->stop();
	switch (m_track)
	{
	case Track::Play:
		m_pMusic = &m_play;
		break;
	case Track::Ready:
	default:
		m_pMusic = &m_ready;
	}
	m_pMusic->setVolume(0.f);
	m_pMusic->play();
	m_timer.restart();
}

void Music::update()
{
	const kairos::Duration fadeInLength(2.0); // in seconds
	float volume = 100.f;
	if (m_timer.getTime() < fadeInLength)
		volume = static_cast<float>((m_timer.getTime().asSeconds() / fadeInLength.asSeconds()) * 100.0);
	if (m_isDimmed)
		volume /= 2.f;
	m_pMusic->setVolume(volume);
}

void Music::dim()
{
	m_isDimmed = true;
}

void Music::undim()
{
	m_isDimmed = false;
}
<commit_msg>add music permission info<commit_after>#include "Music.hpp"

//#include <Plinth/Generic.hpp>

Music::Music():
m_track(Track::Ready),
m_pMusic(&m_ready),
m_isDimmed(false)
{
	const std::string resourcePath = "resources/";
	// music used with permission by Hapax Perplexia (https://soundcloud.com/hapaxperplexia/puzza-soundtrack)
	if (!m_ready.openFromFile(resourcePath + "puzza-ready.ogg") ||
		!m_play.openFromFile(resourcePath + "puzza-play.ogg"))
		throw("Could not find music.");

	m_ready.setLoop(true);
	m_play.setLoop(true);
}

void Music::play(Track track)
{
	m_track = track;
	m_pMusic->stop();
	switch (m_track)
	{
	case Track::Play:
		m_pMusic = &m_play;
		break;
	case Track::Ready:
	default:
		m_pMusic = &m_ready;
	}
	m_pMusic->setVolume(0.f);
	m_pMusic->play();
	m_timer.restart();
}

void Music::update()
{
	const kairos::Duration fadeInLength(2.0); // in seconds
	float volume = 100.f;
	if (m_timer.getTime() < fadeInLength)
		volume = static_cast<float>((m_timer.getTime().asSeconds() / fadeInLength.asSeconds()) * 100.0);
	if (m_isDimmed)
		volume /= 2.f;
	m_pMusic->setVolume(volume);
}

void Music::dim()
{
	m_isDimmed = true;
}

void Music::undim()
{
	m_isDimmed = false;
}
<|endoftext|>


<commit_before>#include "matchstick.h"
#include "types.h"
#include "compile.h"
#include "compile_consts.h"

namespace _matchstick_compile {

    FSM_MATCH * const pick_special_match(MS_CHAR **cursor) {
        FSM_MATCH *match = NULL;
        MS_CHAR *pos;
        if ((pos = wcsrchr(SPECIAL_MATCH, **cursor))) {
            match = new FSM_MATCH_BASIC(SPECIAL_MATCH_TYPE[pos - SPECIAL_MATCH]);
            ++*cursor;
        }
        return match;
    }

    FSM_MATCH * const pick_special_slash_match(MS_CHAR **cursor, int in_charset) {
        FSM_MATCH *match = NULL;
        MS_CHAR *pos;
        MS_CHAR *temp_cursor = *cursor;
        if (**cursor == '\\') {
            ++temp_cursor;
            if (!(*temp_cursor == 'b' && in_charset) && (pos = wcsrchr(SPECIAL_SLASH_MATCH, **cursor))) {
                match = new FSM_MATCH_BASIC(SPECIAL_SLASH_MATCH_TYPE[pos - SPECIAL_SLASH_MATCH]);
                ++temp_cursor;
                *cursor = temp_cursor;
            }
        }
        return match;
    }

    const MS_CHAR pick_escaped_char(MS_CHAR **cursor, int in_charset) {
        MS_CHAR *pos;
        MS_CHAR *temp_cursor = *cursor;
        if (**cursor == '\\') {
            ++temp_cursor;
            if (!(*temp_cursor == 'b' && !in_charset) && (pos = wcsrchr(ESCAPE, **cursor))) {
                ++temp_cursor;
                *cursor = temp_cursor;
                return ESCAPE_DECODED[pos - ESCAPE];
            } else {
                return (MS_CHAR) 0;
            }
        } else {
            return (MS_CHAR) 0;
        }
    }

    const MS_CHAR pick_char(MS_CHAR **cursor, int in_charset) {
        MS_CHAR *pos;
        if (in_charset) {
            pos = wcsrchr(INVALID_CHAR_CHARSET, **cursor);
        } else {
            pos = wcsrchr(INVALID_CHAR_N_CHARSET, **cursor);
        }
        if (pos) {
            return (MS_CHAR) 0;
        } else {
            MS_CHAR ret;
            MS_CHAR *temp_cursor = *cursor;
            ret = pick_escaped_char(&temp_cursor, in_charset);
            if (temp_cursor == *cursor) {
                ++*cursor;
                return *temp_cursor;
            } else {
                *cursor = temp_cursor;
                return ret;
            }
        }
    }

    MS_CHAR * const pick_string(MS_CHAR **cursor) {
        MS_CHARS *chars = NULL;
        MS_CHARS *chars_cursor = NULL;
        unsigned int length = 0;
        MS_CHAR picked_char;
        MS_CHAR *temp_cursor = *cursor;
        do {
            *cursor = temp_cursor;
            picked_char = pick_char(&temp_cursor, 0);
            if (temp_cursor != *cursor) {
                if (chars_cursor) {
                    chars_cursor->next = new MS_CHARS(picked_char);
                    chars_cursor = chars_cursor->next;
                } else {
                    chars_cursor = new MS_CHARS(picked_char);
                    chars = chars_cursor;
                }
                ++length;
            }
        } while (temp_cursor != *cursor);
        if (chars) {
            MS_CHAR * str = new MS_CHAR[length + 1];
            for (int i = 0; i < length; ++i) {
                str[i] = chars -> value;
                chars = chars -> next;
            }
            str[length] = '\0';
            return str;
        } else {
            return NULL;
        }
    }

    FSM_MATCH * const pick_range_match(MS_CHAR **cursor) {
        MS_CHAR * temp_cursor = *cursor;
        MS_CHAR min = pick_char(&temp_cursor, 1);
        MS_CHAR max;
        if (temp_cursor == *cursor || *temp_cursor != '-' || *temp_cursor == ']') {
            return NULL;
        } else {
            // to avoid CLion from thinking temp_cursor == temp_cursor2 to be always true
            MS_CHAR * temp_cursor2 = temp_cursor + 1;
            ++temp_cursor;
            if (*temp_cursor == ']') {
                return NULL;
            } else {
                max = pick_char(&temp_cursor2, 1);
                if (temp_cursor == temp_cursor2) {
                    return NULL;
                } else {
                    *cursor = temp_cursor2;
                    FSM_MATCH_RANGE *match = new FSM_MATCH_RANGE(min, max);
                    return static_cast<FSM_MATCH *> (match);
                }
            }
        }
    }

    // assumed to be in charset
    FSM_MATCH * const pick_char_match(MS_CHAR **cursor) {
        MS_CHAR * temp_cursor = *cursor;
        MS_CHAR c = pick_char(&temp_cursor, 1);
        if (temp_cursor == *cursor) {
            return NULL;
        } else {
            FSM_MATCH_EXACT * match = new FSM_MATCH_EXACT(c);
            return static_cast<FSM_MATCH *> (match);
        }
    }

    FSM_RULE * const pick_charset(MS_CHAR **cursor) {
        FSM_RULE_TYPE rule_type;
        FSM_RULE_BASIC * rule;
        FSM_MATCH * first_match = NULL;
        FSM_MATCH * match_cursor = NULL;
        if (**cursor != '[') {
            return NULL;
        } else {
            ++*cursor;
            if (**cursor == '^') {
                ++*cursor;
                rule_type = FSM_RULE_TYPE_EXCLUDE;
            } else {
                rule_type = FSM_RULE_TYPE_INCLUDE;
            }
            MS_CHAR * temp_cursor;
            FSM_MATCH * match;
            while (**cursor != ']') {
                match = NULL;
                temp_cursor = *cursor;
                if (temp_cursor == *cursor) {
                    match = pick_range_match(cursor);
                }
                if (temp_cursor == *cursor) {
                    match = pick_char_match(cursor);
                }
                if (!match) {
                    if (first_match) {
                        delete first_match;
                    }
                    return NULL;
                } else {
                    if (match_cursor) {
                        match_cursor->next_match = match;
                        match_cursor = match_cursor->next_match;
                    } else {
                        match_cursor = match;
                        first_match = match;
                    }
                }
            }
            if (first_match) {
                rule = new FSM_RULE_BASIC(rule_type, first_match);
                return static_cast<FSM_RULE *> (rule);
            } else {
                return NULL;
            }
        }
    }
    unsigned int pick_number(MS_CHAR **cursor) {
        if (**cursor < '0' || **cursor > '9') {
            return INVALID_NUM;
        } else {
            unsigned int num = 0;
            while (**cursor >= '0' && **cursor <= '9') {
                num *= 10;
                num += **cursor - '0';
                ++*cursor;
            }
            return num;
        }
    }
    using namespace _matchstick;

}
<commit_msg>implement pick_counter_mode<commit_after>#include "matchstick.h"
#include "types.h"
#include "compile.h"
#include "compile_consts.h"

namespace _matchstick_compile {

    FSM_MATCH * const pick_special_match(MS_CHAR **cursor) {
        FSM_MATCH *match = NULL;
        MS_CHAR *pos;
        if ((pos = wcsrchr(SPECIAL_MATCH, **cursor))) {
            match = new FSM_MATCH_BASIC(SPECIAL_MATCH_TYPE[pos - SPECIAL_MATCH]);
            ++*cursor;
        }
        return match;
    }

    FSM_MATCH * const pick_special_slash_match(MS_CHAR **cursor, int in_charset) {
        FSM_MATCH *match = NULL;
        MS_CHAR *pos;
        MS_CHAR *temp_cursor = *cursor;
        if (**cursor == '\\') {
            ++temp_cursor;
            if (!(*temp_cursor == 'b' && in_charset) && (pos = wcsrchr(SPECIAL_SLASH_MATCH, **cursor))) {
                match = new FSM_MATCH_BASIC(SPECIAL_SLASH_MATCH_TYPE[pos - SPECIAL_SLASH_MATCH]);
                ++temp_cursor;
                *cursor = temp_cursor;
            }
        }
        return match;
    }

    const MS_CHAR pick_escaped_char(MS_CHAR **cursor, int in_charset) {
        MS_CHAR *pos;
        MS_CHAR *temp_cursor = *cursor;
        if (**cursor == '\\') {
            ++temp_cursor;
            if (!(*temp_cursor == 'b' && !in_charset) && (pos = wcsrchr(ESCAPE, **cursor))) {
                ++temp_cursor;
                *cursor = temp_cursor;
                return ESCAPE_DECODED[pos - ESCAPE];
            } else {
                return (MS_CHAR) 0;
            }
        } else {
            return (MS_CHAR) 0;
        }
    }

    const MS_CHAR pick_char(MS_CHAR **cursor, int in_charset) {
        MS_CHAR *pos;
        if (in_charset) {
            pos = wcsrchr(INVALID_CHAR_CHARSET, **cursor);
        } else {
            pos = wcsrchr(INVALID_CHAR_N_CHARSET, **cursor);
        }
        if (pos) {
            return (MS_CHAR) 0;
        } else {
            MS_CHAR ret;
            MS_CHAR *temp_cursor = *cursor;
            ret = pick_escaped_char(&temp_cursor, in_charset);
            if (temp_cursor == *cursor) {
                ++*cursor;
                return *temp_cursor;
            } else {
                *cursor = temp_cursor;
                return ret;
            }
        }
    }

    MS_CHAR * const pick_string(MS_CHAR **cursor) {
        MS_CHARS *chars = NULL;
        MS_CHARS *chars_cursor = NULL;
        unsigned int length = 0;
        MS_CHAR picked_char;
        MS_CHAR *temp_cursor = *cursor;
        do {
            *cursor = temp_cursor;
            picked_char = pick_char(&temp_cursor, 0);
            if (temp_cursor != *cursor) {
                if (chars_cursor) {
                    chars_cursor->next = new MS_CHARS(picked_char);
                    chars_cursor = chars_cursor->next;
                } else {
                    chars_cursor = new MS_CHARS(picked_char);
                    chars = chars_cursor;
                }
                ++length;
            }
        } while (temp_cursor != *cursor);
        if (chars) {
            MS_CHAR * str = new MS_CHAR[length + 1];
            for (int i = 0; i < length; ++i) {
                str[i] = chars -> value;
                chars = chars -> next;
            }
            str[length] = '\0';
            return str;
        } else {
            return NULL;
        }
    }

    FSM_MATCH * const pick_range_match(MS_CHAR **cursor) {
        MS_CHAR * temp_cursor = *cursor;
        MS_CHAR min = pick_char(&temp_cursor, 1);
        MS_CHAR max;
        if (temp_cursor == *cursor || *temp_cursor != '-' || *temp_cursor == ']') {
            return NULL;
        } else {
            // to avoid CLion from thinking temp_cursor == temp_cursor2 to be always true
            MS_CHAR * temp_cursor2 = temp_cursor + 1;
            ++temp_cursor;
            if (*temp_cursor == ']') {
                return NULL;
            } else {
                max = pick_char(&temp_cursor2, 1);
                if (temp_cursor == temp_cursor2) {
                    return NULL;
                } else {
                    *cursor = temp_cursor2;
                    FSM_MATCH_RANGE *match = new FSM_MATCH_RANGE(min, max);
                    return static_cast<FSM_MATCH *> (match);
                }
            }
        }
    }

    // assumed to be in charset
    FSM_MATCH * const pick_char_match(MS_CHAR **cursor) {
        MS_CHAR * temp_cursor = *cursor;
        MS_CHAR c = pick_char(&temp_cursor, 1);
        if (temp_cursor == *cursor) {
            return NULL;
        } else {
            FSM_MATCH_EXACT * match = new FSM_MATCH_EXACT(c);
            return static_cast<FSM_MATCH *> (match);
        }
    }

    FSM_RULE * const pick_charset(MS_CHAR **cursor) {
        FSM_RULE_TYPE rule_type;
        FSM_RULE_BASIC * rule;
        FSM_MATCH * first_match = NULL;
        FSM_MATCH * match_cursor = NULL;
        if (**cursor != '[') {
            return NULL;
        } else {
            ++*cursor;
            if (**cursor == '^') {
                ++*cursor;
                rule_type = FSM_RULE_TYPE_EXCLUDE;
            } else {
                rule_type = FSM_RULE_TYPE_INCLUDE;
            }
            MS_CHAR * temp_cursor;
            FSM_MATCH * match;
            while (**cursor != ']') {
                match = NULL;
                temp_cursor = *cursor;
                if (temp_cursor == *cursor) {
                    match = pick_range_match(cursor);
                }
                if (temp_cursor == *cursor) {
                    match = pick_char_match(cursor);
                }
                if (!match) {
                    if (first_match) {
                        delete first_match;
                    }
                    return NULL;
                } else {
                    if (match_cursor) {
                        match_cursor->next_match = match;
                        match_cursor = match_cursor->next_match;
                    } else {
                        match_cursor = match;
                        first_match = match;
                    }
                }
            }
            if (first_match) {
                rule = new FSM_RULE_BASIC(rule_type, first_match);
                return static_cast<FSM_RULE *> (rule);
            } else {
                return NULL;
            }
        }
    }
    unsigned int pick_number(MS_CHAR **cursor) {
        if (**cursor < '0' || **cursor > '9') {
            return INVALID_NUM;
        } else {
            unsigned int num = 0;
            while (**cursor >= '0' && **cursor <= '9') {
                num *= 10;
                num += **cursor - '0';
                ++*cursor;
            }
            return num;
        }
    }

    enum FSM_COUNTER_MODE pick_counter_mode(MS_CHAR **cursor) {
        switch (**cursor) {
            case '?':
                ++*cursor;
                return FSM_COUNTER_MODE_RELUCTANT;
                break;
            case '+':
                ++*cursor;
                return FSM_COUNTER_MODE_POSSESSIVE;
                break;
            default:
                return FSM_COUNTER_MODE_GREEDY;
        }
    }
    using namespace _matchstick;

}
<|endoftext|>


<commit_before>#include <tools/string.hxx>

struct hw_pair
{
    sal_Unicode         nFrom;
    sal_Unicode         nTo;
};

#define MAKE_PAIR(a,b) { a, b }

static struct hw_pair aHWPairs[] =
{
  MAKE_PAIR( 0xFF65, 0x30FB ),  // HALFWIDTH KATAKANA MIDDLE DOT --> KATAKANA MIDDLE DOT
  MAKE_PAIR( 0xFF66, 0x30F2 ),  // HALFWIDTH KATAKANA LETTER WO --> KATAKANA LETTER WO
  MAKE_PAIR( 0xFF67, 0x30A1 ),  // HALFWIDTH KATAKANA LETTER SMALL A --> KATAKANA LETTER SMALL A
  MAKE_PAIR( 0xFF68, 0x30A3 ),  // HALFWIDTH KATAKANA LETTER SMALL I --> KATAKANA LETTER SMALL I
  MAKE_PAIR( 0xFF69, 0x30A5 ),  // HALFWIDTH KATAKANA LETTER SMALL U --> KATAKANA LETTER SMALL U
  MAKE_PAIR( 0xFF6A, 0x30A7 ),  // HALFWIDTH KATAKANA LETTER SMALL E --> KATAKANA LETTER SMALL E
  MAKE_PAIR( 0xFF6B, 0x30A9 ),  // HALFWIDTH KATAKANA LETTER SMALL O --> KATAKANA LETTER SMALL O
  MAKE_PAIR( 0xFF6C, 0x30E3 ),  // HALFWIDTH KATAKANA LETTER SMALL YA --> KATAKANA LETTER SMALL YA
  MAKE_PAIR( 0xFF6D, 0x30E5 ),  // HALFWIDTH KATAKANA LETTER SMALL YU --> KATAKANA LETTER SMALL YU
  MAKE_PAIR( 0xFF6E, 0x30E7 ),  // HALFWIDTH KATAKANA LETTER SMALL YO --> KATAKANA LETTER SMALL YO
  MAKE_PAIR( 0xFF6F, 0x30C3 ),  // HALFWIDTH KATAKANA LETTER SMALL TU --> KATAKANA LETTER SMALL TU
  MAKE_PAIR( 0xFF70, 0x30FC ),  // HALFWIDTH KATAKANA-HIRAGANA PROLONGED SOUND MARK --> KATAKANA-HIRAGANA PROLONGED SOUND MARK
  MAKE_PAIR( 0xFF71, 0x30A2 ),  // HALFWIDTH KATAKANA LETTER A --> KATAKANA LETTER A
  MAKE_PAIR( 0xFF72, 0x30A4 ),  // HALFWIDTH KATAKANA LETTER I --> KATAKANA LETTER I
  MAKE_PAIR( 0xFF73, 0x30A6 ),  // HALFWIDTH KATAKANA LETTER U --> KATAKANA LETTER U
  MAKE_PAIR( 0xFF74, 0x30A8 ),  // HALFWIDTH KATAKANA LETTER E --> KATAKANA LETTER E
  MAKE_PAIR( 0xFF75, 0x30AA ),  // HALFWIDTH KATAKANA LETTER O --> KATAKANA LETTER O
  MAKE_PAIR( 0xFF76, 0x30AB ),  // HALFWIDTH KATAKANA LETTER KA --> KATAKANA LETTER KA
  MAKE_PAIR( 0xFF77, 0x30AD ),  // HALFWIDTH KATAKANA LETTER KI --> KATAKANA LETTER KI
  MAKE_PAIR( 0xFF78, 0x30AF ),  // HALFWIDTH KATAKANA LETTER KU --> KATAKANA LETTER KU
  MAKE_PAIR( 0xFF79, 0x30B1 ),  // HALFWIDTH KATAKANA LETTER KE --> KATAKANA LETTER KE
  MAKE_PAIR( 0xFF7A, 0x30B3 ),  // HALFWIDTH KATAKANA LETTER KO --> KATAKANA LETTER KO
  MAKE_PAIR( 0xFF7B, 0x30B5 ),  // HALFWIDTH KATAKANA LETTER SA --> KATAKANA LETTER SA
  MAKE_PAIR( 0xFF7C, 0x30B7 ),  // HALFWIDTH KATAKANA LETTER SI --> KATAKANA LETTER SI
  MAKE_PAIR( 0xFF7D, 0x30B9 ),  // HALFWIDTH KATAKANA LETTER SU --> KATAKANA LETTER SU
  MAKE_PAIR( 0xFF7E, 0x30BB ),  // HALFWIDTH KATAKANA LETTER SE --> KATAKANA LETTER SE
  MAKE_PAIR( 0xFF7F, 0x30BD ),  // HALFWIDTH KATAKANA LETTER SO --> KATAKANA LETTER SO
  MAKE_PAIR( 0xFF80, 0x30BF ),  // HALFWIDTH KATAKANA LETTER TA --> KATAKANA LETTER TA
  MAKE_PAIR( 0xFF81, 0x30C1 ),  // HALFWIDTH KATAKANA LETTER TI --> KATAKANA LETTER TI
  MAKE_PAIR( 0xFF82, 0x30C4 ),  // HALFWIDTH KATAKANA LETTER TU --> KATAKANA LETTER TU
  MAKE_PAIR( 0xFF83, 0x30C6 ),  // HALFWIDTH KATAKANA LETTER TE --> KATAKANA LETTER TE
  MAKE_PAIR( 0xFF84, 0x30C8 ),  // HALFWIDTH KATAKANA LETTER TO --> KATAKANA LETTER TO
  MAKE_PAIR( 0xFF85, 0x30CA ),  // HALFWIDTH KATAKANA LETTER NA --> KATAKANA LETTER NA
  MAKE_PAIR( 0xFF86, 0x30CB ),  // HALFWIDTH KATAKANA LETTER NI --> KATAKANA LETTER NI
  MAKE_PAIR( 0xFF87, 0x30CC ),  // HALFWIDTH KATAKANA LETTER NU --> KATAKANA LETTER NU
  MAKE_PAIR( 0xFF88, 0x30CD ),  // HALFWIDTH KATAKANA LETTER NE --> KATAKANA LETTER NE
  MAKE_PAIR( 0xFF89, 0x30CE ),  // HALFWIDTH KATAKANA LETTER NO --> KATAKANA LETTER NO
  MAKE_PAIR( 0xFF8A, 0x30CF ),  // HALFWIDTH KATAKANA LETTER HA --> KATAKANA LETTER HA
  MAKE_PAIR( 0xFF8B, 0x30D2 ),  // HALFWIDTH KATAKANA LETTER HI --> KATAKANA LETTER HI
  MAKE_PAIR( 0xFF8C, 0x30D5 ),  // HALFWIDTH KATAKANA LETTER HU --> KATAKANA LETTER HU
  MAKE_PAIR( 0xFF8D, 0x30D8 ),  // HALFWIDTH KATAKANA LETTER HE --> KATAKANA LETTER HE
  MAKE_PAIR( 0xFF8E, 0x30DB ),  // HALFWIDTH KATAKANA LETTER HO --> KATAKANA LETTER HO
  MAKE_PAIR( 0xFF8F, 0x30DE ),  // HALFWIDTH KATAKANA LETTER MA --> KATAKANA LETTER MA
  MAKE_PAIR( 0xFF90, 0x30DF ),  // HALFWIDTH KATAKANA LETTER MI --> KATAKANA LETTER MI
  MAKE_PAIR( 0xFF91, 0x30E0 ),  // HALFWIDTH KATAKANA LETTER MU --> KATAKANA LETTER MU
  MAKE_PAIR( 0xFF92, 0x30E1 ),  // HALFWIDTH KATAKANA LETTER ME --> KATAKANA LETTER ME
  MAKE_PAIR( 0xFF93, 0x30E2 ),  // HALFWIDTH KATAKANA LETTER MO --> KATAKANA LETTER MO
  MAKE_PAIR( 0xFF94, 0x30E4 ),  // HALFWIDTH KATAKANA LETTER YA --> KATAKANA LETTER YA
  MAKE_PAIR( 0xFF95, 0x30E6 ),  // HALFWIDTH KATAKANA LETTER YU --> KATAKANA LETTER YU
  MAKE_PAIR( 0xFF96, 0x30E8 ),  // HALFWIDTH KATAKANA LETTER YO --> KATAKANA LETTER YO
  MAKE_PAIR( 0xFF97, 0x30E9 ),  // HALFWIDTH KATAKANA LETTER RA --> KATAKANA LETTER RA
  MAKE_PAIR( 0xFF98, 0x30EA ),  // HALFWIDTH KATAKANA LETTER RI --> KATAKANA LETTER RI
  MAKE_PAIR( 0xFF99, 0x30EB ),  // HALFWIDTH KATAKANA LETTER RU --> KATAKANA LETTER RU
  MAKE_PAIR( 0xFF9A, 0x30EC ),  // HALFWIDTH KATAKANA LETTER RE --> KATAKANA LETTER RE
  MAKE_PAIR( 0xFF9B, 0x30ED ),  // HALFWIDTH KATAKANA LETTER RO --> KATAKANA LETTER RO
  MAKE_PAIR( 0xFF9C, 0x30EF ),  // HALFWIDTH KATAKANA LETTER WA --> KATAKANA LETTER WA
  MAKE_PAIR( 0xFF9D, 0x30F3 ),  // HALFWIDTH KATAKANA LETTER N --> KATAKANA LETTER N
  MAKE_PAIR( 0xFF9E, 0x3099 ),  // HALFWIDTH KATAKANA VOICED SOUND MARK --> COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK
  MAKE_PAIR( 0xFF9F, 0x309A )   // HALFWIDTH KATAKANA SEMI-VOICED SOUND MARK --> COMBINING KATAKANA-
};

static struct hw_pair aCombine3099[] =
{
    { 0x30a6, 0x30f4 },
    { 0x30ab, 0x30ac },
    { 0x30ad, 0x30ae },
    { 0x30af, 0x30b0 },
    { 0x30b1, 0x30b2 },
    { 0x30b3, 0x30b4 },
    { 0x30b5, 0x30b6 },
    { 0x30b7, 0x30b8 },
    { 0x30b9, 0x30ba },
    { 0x30bb, 0x30bc },
    { 0x30bd, 0x30be },
    { 0x30bf, 0x30c0 },
    { 0x30c1, 0x30c2 },
    { 0x30c4, 0x30c5 },
    { 0x30c6, 0x30c7 },
    { 0x30c8, 0x30c9 },
    { 0x30cf, 0x30d0 },
    { 0x30d2, 0x30d3 },
    { 0x30d5, 0x30d6 },
    { 0x30d8, 0x30d9 },
    { 0x30db, 0x30dc },
    { 0x30ef, 0x30f7 },
    { 0x30f0, 0x30f8 },
    { 0x30f1, 0x30f9 },
    { 0x30f2, 0x30fa },
    { 0x30fd, 0x30fe }
};

static struct hw_pair aCombine309A[] =
{
    { 0x30cf, 0x30d1 },
    { 0x30d2, 0x30d4 },
    { 0x30d5, 0x30d7 },
    { 0x30d8, 0x30da },
    { 0x30db, 0x30dd }
};

int ImplReplaceFullWidth( sal_Unicode* pString, int nLen )
{
    sal_Unicode* pRead  = pString;
    sal_Unicode* pWrite = pRead;
    int nNewLen = nLen;

    while( (pRead - pString) < nLen )
    {
        if( pWrite != pRead )
            *pWrite = *pRead;

        if( *pRead >= 0xff65 && *pRead <= 0xff9f )
        {
            *pWrite = aHWPairs[ *pRead - 0xff65 ].nTo;

            struct hw_pair* pTable = NULL;
            int nTableEntries = 0;
            if( *pWrite == 0x3099 )
            {
                // replace 0x3099 combinations
                pTable = aCombine3099;
                nTableEntries = sizeof(aCombine3099)/sizeof(aCombine3099[0]);
            }
            else if( *pWrite == 0x309a )
            {
                // replace 0x309a combinations
                pTable = aCombine309A;
                nTableEntries = sizeof(aCombine309A)/sizeof(aCombine309A[0]);
            }
            if( pTable )
            {
                sal_Unicode c = pWrite[-1];
                for( int i = 0; i < nTableEntries; i++ )
                    if( c == pTable[i].nFrom )
                    {
                        pWrite--;
                        *pWrite = pTable[i].nTo;
                        nNewLen--;
                        break;
                    }
            }
        }
        pRead++;
        pWrite++;
    }
    if( pWrite < pRead )
        *pWrite = 0;

    return nNewLen;
}

void ConvertHalfwitdhToFullwidth( String& rString )
{
    int nNewLen = ImplReplaceFullWidth( rString.GetBufferAccess(), rString.Len() );
    rString.ReleaseBufferAccess( nNewLen );
}
<commit_msg>INTEGRATION: CWS warnings01 (1.1.252); FILE MERGED 2006/03/09 19:26:52 ihi 1.1.252.1: #i57362# Warning free wntmsci10<commit_after>#include <tools/string.hxx>

struct hw_pair
{
    sal_Unicode         nFrom;
    sal_Unicode         nTo;
};

#define MAKE_PAIR(a,b) { a, b }

static struct hw_pair aHWPairs[] =
{
  MAKE_PAIR( 0xFF65, 0x30FB ),  // HALFWIDTH KATAKANA MIDDLE DOT --> KATAKANA MIDDLE DOT
  MAKE_PAIR( 0xFF66, 0x30F2 ),  // HALFWIDTH KATAKANA LETTER WO --> KATAKANA LETTER WO
  MAKE_PAIR( 0xFF67, 0x30A1 ),  // HALFWIDTH KATAKANA LETTER SMALL A --> KATAKANA LETTER SMALL A
  MAKE_PAIR( 0xFF68, 0x30A3 ),  // HALFWIDTH KATAKANA LETTER SMALL I --> KATAKANA LETTER SMALL I
  MAKE_PAIR( 0xFF69, 0x30A5 ),  // HALFWIDTH KATAKANA LETTER SMALL U --> KATAKANA LETTER SMALL U
  MAKE_PAIR( 0xFF6A, 0x30A7 ),  // HALFWIDTH KATAKANA LETTER SMALL E --> KATAKANA LETTER SMALL E
  MAKE_PAIR( 0xFF6B, 0x30A9 ),  // HALFWIDTH KATAKANA LETTER SMALL O --> KATAKANA LETTER SMALL O
  MAKE_PAIR( 0xFF6C, 0x30E3 ),  // HALFWIDTH KATAKANA LETTER SMALL YA --> KATAKANA LETTER SMALL YA
  MAKE_PAIR( 0xFF6D, 0x30E5 ),  // HALFWIDTH KATAKANA LETTER SMALL YU --> KATAKANA LETTER SMALL YU
  MAKE_PAIR( 0xFF6E, 0x30E7 ),  // HALFWIDTH KATAKANA LETTER SMALL YO --> KATAKANA LETTER SMALL YO
  MAKE_PAIR( 0xFF6F, 0x30C3 ),  // HALFWIDTH KATAKANA LETTER SMALL TU --> KATAKANA LETTER SMALL TU
  MAKE_PAIR( 0xFF70, 0x30FC ),  // HALFWIDTH KATAKANA-HIRAGANA PROLONGED SOUND MARK --> KATAKANA-HIRAGANA PROLONGED SOUND MARK
  MAKE_PAIR( 0xFF71, 0x30A2 ),  // HALFWIDTH KATAKANA LETTER A --> KATAKANA LETTER A
  MAKE_PAIR( 0xFF72, 0x30A4 ),  // HALFWIDTH KATAKANA LETTER I --> KATAKANA LETTER I
  MAKE_PAIR( 0xFF73, 0x30A6 ),  // HALFWIDTH KATAKANA LETTER U --> KATAKANA LETTER U
  MAKE_PAIR( 0xFF74, 0x30A8 ),  // HALFWIDTH KATAKANA LETTER E --> KATAKANA LETTER E
  MAKE_PAIR( 0xFF75, 0x30AA ),  // HALFWIDTH KATAKANA LETTER O --> KATAKANA LETTER O
  MAKE_PAIR( 0xFF76, 0x30AB ),  // HALFWIDTH KATAKANA LETTER KA --> KATAKANA LETTER KA
  MAKE_PAIR( 0xFF77, 0x30AD ),  // HALFWIDTH KATAKANA LETTER KI --> KATAKANA LETTER KI
  MAKE_PAIR( 0xFF78, 0x30AF ),  // HALFWIDTH KATAKANA LETTER KU --> KATAKANA LETTER KU
  MAKE_PAIR( 0xFF79, 0x30B1 ),  // HALFWIDTH KATAKANA LETTER KE --> KATAKANA LETTER KE
  MAKE_PAIR( 0xFF7A, 0x30B3 ),  // HALFWIDTH KATAKANA LETTER KO --> KATAKANA LETTER KO
  MAKE_PAIR( 0xFF7B, 0x30B5 ),  // HALFWIDTH KATAKANA LETTER SA --> KATAKANA LETTER SA
  MAKE_PAIR( 0xFF7C, 0x30B7 ),  // HALFWIDTH KATAKANA LETTER SI --> KATAKANA LETTER SI
  MAKE_PAIR( 0xFF7D, 0x30B9 ),  // HALFWIDTH KATAKANA LETTER SU --> KATAKANA LETTER SU
  MAKE_PAIR( 0xFF7E, 0x30BB ),  // HALFWIDTH KATAKANA LETTER SE --> KATAKANA LETTER SE
  MAKE_PAIR( 0xFF7F, 0x30BD ),  // HALFWIDTH KATAKANA LETTER SO --> KATAKANA LETTER SO
  MAKE_PAIR( 0xFF80, 0x30BF ),  // HALFWIDTH KATAKANA LETTER TA --> KATAKANA LETTER TA
  MAKE_PAIR( 0xFF81, 0x30C1 ),  // HALFWIDTH KATAKANA LETTER TI --> KATAKANA LETTER TI
  MAKE_PAIR( 0xFF82, 0x30C4 ),  // HALFWIDTH KATAKANA LETTER TU --> KATAKANA LETTER TU
  MAKE_PAIR( 0xFF83, 0x30C6 ),  // HALFWIDTH KATAKANA LETTER TE --> KATAKANA LETTER TE
  MAKE_PAIR( 0xFF84, 0x30C8 ),  // HALFWIDTH KATAKANA LETTER TO --> KATAKANA LETTER TO
  MAKE_PAIR( 0xFF85, 0x30CA ),  // HALFWIDTH KATAKANA LETTER NA --> KATAKANA LETTER NA
  MAKE_PAIR( 0xFF86, 0x30CB ),  // HALFWIDTH KATAKANA LETTER NI --> KATAKANA LETTER NI
  MAKE_PAIR( 0xFF87, 0x30CC ),  // HALFWIDTH KATAKANA LETTER NU --> KATAKANA LETTER NU
  MAKE_PAIR( 0xFF88, 0x30CD ),  // HALFWIDTH KATAKANA LETTER NE --> KATAKANA LETTER NE
  MAKE_PAIR( 0xFF89, 0x30CE ),  // HALFWIDTH KATAKANA LETTER NO --> KATAKANA LETTER NO
  MAKE_PAIR( 0xFF8A, 0x30CF ),  // HALFWIDTH KATAKANA LETTER HA --> KATAKANA LETTER HA
  MAKE_PAIR( 0xFF8B, 0x30D2 ),  // HALFWIDTH KATAKANA LETTER HI --> KATAKANA LETTER HI
  MAKE_PAIR( 0xFF8C, 0x30D5 ),  // HALFWIDTH KATAKANA LETTER HU --> KATAKANA LETTER HU
  MAKE_PAIR( 0xFF8D, 0x30D8 ),  // HALFWIDTH KATAKANA LETTER HE --> KATAKANA LETTER HE
  MAKE_PAIR( 0xFF8E, 0x30DB ),  // HALFWIDTH KATAKANA LETTER HO --> KATAKANA LETTER HO
  MAKE_PAIR( 0xFF8F, 0x30DE ),  // HALFWIDTH KATAKANA LETTER MA --> KATAKANA LETTER MA
  MAKE_PAIR( 0xFF90, 0x30DF ),  // HALFWIDTH KATAKANA LETTER MI --> KATAKANA LETTER MI
  MAKE_PAIR( 0xFF91, 0x30E0 ),  // HALFWIDTH KATAKANA LETTER MU --> KATAKANA LETTER MU
  MAKE_PAIR( 0xFF92, 0x30E1 ),  // HALFWIDTH KATAKANA LETTER ME --> KATAKANA LETTER ME
  MAKE_PAIR( 0xFF93, 0x30E2 ),  // HALFWIDTH KATAKANA LETTER MO --> KATAKANA LETTER MO
  MAKE_PAIR( 0xFF94, 0x30E4 ),  // HALFWIDTH KATAKANA LETTER YA --> KATAKANA LETTER YA
  MAKE_PAIR( 0xFF95, 0x30E6 ),  // HALFWIDTH KATAKANA LETTER YU --> KATAKANA LETTER YU
  MAKE_PAIR( 0xFF96, 0x30E8 ),  // HALFWIDTH KATAKANA LETTER YO --> KATAKANA LETTER YO
  MAKE_PAIR( 0xFF97, 0x30E9 ),  // HALFWIDTH KATAKANA LETTER RA --> KATAKANA LETTER RA
  MAKE_PAIR( 0xFF98, 0x30EA ),  // HALFWIDTH KATAKANA LETTER RI --> KATAKANA LETTER RI
  MAKE_PAIR( 0xFF99, 0x30EB ),  // HALFWIDTH KATAKANA LETTER RU --> KATAKANA LETTER RU
  MAKE_PAIR( 0xFF9A, 0x30EC ),  // HALFWIDTH KATAKANA LETTER RE --> KATAKANA LETTER RE
  MAKE_PAIR( 0xFF9B, 0x30ED ),  // HALFWIDTH KATAKANA LETTER RO --> KATAKANA LETTER RO
  MAKE_PAIR( 0xFF9C, 0x30EF ),  // HALFWIDTH KATAKANA LETTER WA --> KATAKANA LETTER WA
  MAKE_PAIR( 0xFF9D, 0x30F3 ),  // HALFWIDTH KATAKANA LETTER N --> KATAKANA LETTER N
  MAKE_PAIR( 0xFF9E, 0x3099 ),  // HALFWIDTH KATAKANA VOICED SOUND MARK --> COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK
  MAKE_PAIR( 0xFF9F, 0x309A )   // HALFWIDTH KATAKANA SEMI-VOICED SOUND MARK --> COMBINING KATAKANA-
};

static struct hw_pair aCombine3099[] =
{
    { 0x30a6, 0x30f4 },
    { 0x30ab, 0x30ac },
    { 0x30ad, 0x30ae },
    { 0x30af, 0x30b0 },
    { 0x30b1, 0x30b2 },
    { 0x30b3, 0x30b4 },
    { 0x30b5, 0x30b6 },
    { 0x30b7, 0x30b8 },
    { 0x30b9, 0x30ba },
    { 0x30bb, 0x30bc },
    { 0x30bd, 0x30be },
    { 0x30bf, 0x30c0 },
    { 0x30c1, 0x30c2 },
    { 0x30c4, 0x30c5 },
    { 0x30c6, 0x30c7 },
    { 0x30c8, 0x30c9 },
    { 0x30cf, 0x30d0 },
    { 0x30d2, 0x30d3 },
    { 0x30d5, 0x30d6 },
    { 0x30d8, 0x30d9 },
    { 0x30db, 0x30dc },
    { 0x30ef, 0x30f7 },
    { 0x30f0, 0x30f8 },
    { 0x30f1, 0x30f9 },
    { 0x30f2, 0x30fa },
    { 0x30fd, 0x30fe }
};

static struct hw_pair aCombine309A[] =
{
    { 0x30cf, 0x30d1 },
    { 0x30d2, 0x30d4 },
    { 0x30d5, 0x30d7 },
    { 0x30d8, 0x30da },
    { 0x30db, 0x30dd }
};

USHORT ImplReplaceFullWidth( sal_Unicode* pString, USHORT nLen )
{
    sal_Unicode* pRead  = pString;
    sal_Unicode* pWrite = pRead;
    USHORT nNewLen = nLen;

    while( (pRead - pString) < nLen )
    {
        if( pWrite != pRead )
            *pWrite = *pRead;

        if( *pRead >= 0xff65 && *pRead <= 0xff9f )
        {
            *pWrite = aHWPairs[ *pRead - 0xff65 ].nTo;

            struct hw_pair* pTable = NULL;
            int nTableEntries = 0;
            if( *pWrite == 0x3099 )
            {
                // replace 0x3099 combinations
                pTable = aCombine3099;
                nTableEntries = sizeof(aCombine3099)/sizeof(aCombine3099[0]);
            }
            else if( *pWrite == 0x309a )
            {
                // replace 0x309a combinations
                pTable = aCombine309A;
                nTableEntries = sizeof(aCombine309A)/sizeof(aCombine309A[0]);
            }
            if( pTable )
            {
                sal_Unicode c = pWrite[-1];
                for( int i = 0; i < nTableEntries; i++ )
                    if( c == pTable[i].nFrom )
                    {
                        pWrite--;
                        *pWrite = pTable[i].nTo;
                        nNewLen--;
                        break;
                    }
            }
        }
        pRead++;
        pWrite++;
    }
    if( pWrite < pRead )
        *pWrite = 0;

    return nNewLen;
}

void ConvertHalfwitdhToFullwidth( String& rString )
{
    USHORT nNewLen = ImplReplaceFullWidth( rString.GetBufferAccess(), rString.Len() );
    rString.ReleaseBufferAccess( nNewLen );
}
<|endoftext|>


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

#include "tink/aead/aes_ctr_hmac_aead_key_manager.h"

#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "tink/config.h"
#include "tink/mac/mac_config.h"
#include "tink/subtle/aead_test_util.h"
#include "tink/subtle/aes_ctr_boringssl.h"
#include "tink/subtle/encrypt_then_authenticate.h"
#include "tink/subtle/hmac_boringssl.h"
#include "tink/util/enums.h"
#include "tink/util/status.h"
#include "tink/util/statusor.h"
#include "tink/util/test_matchers.h"
#include "proto/aes_ctr_hmac_aead.pb.h"
#include "proto/aes_gcm.pb.h"
#include "proto/common.pb.h"
#include "proto/tink.pb.h"

namespace crypto {
namespace tink {

using ::crypto::tink::test::IsOk;
using ::crypto::tink::test::StatusIs;
using ::crypto::tink::util::StatusOr;
using ::google::crypto::tink::AesCtrHmacAeadKey;
using ::google::crypto::tink::AesCtrHmacAeadKeyFormat;
using ::google::crypto::tink::HashType;
using ::google::crypto::tink::KeyData;
using ::testing::Eq;
using ::testing::Not;
using ::testing::SizeIs;

namespace {

TEST(AesCtrHmacAeadKeyManagerTest, Basics) {
  EXPECT_THAT(AesCtrHmacAeadKeyManager().get_version(), Eq(0));
  EXPECT_THAT(AesCtrHmacAeadKeyManager().get_key_type(),
              Eq("type.googleapis.com/google.crypto.tink.AesCtrHmacAeadKey"));
  EXPECT_THAT(AesCtrHmacAeadKeyManager().key_material_type(),
              Eq(google::crypto::tink::KeyData::SYMMETRIC));
}

TEST(AesCtrHmacAeadKeyManagerTest, ValidateEmptyKey) {
  EXPECT_THAT(AesCtrHmacAeadKeyManager().ValidateKey(AesCtrHmacAeadKey()),
              StatusIs(util::error::INVALID_ARGUMENT));
}

AesCtrHmacAeadKey CreateValidKey() {
  AesCtrHmacAeadKey key;
  key.set_version(0);
  auto aes_ctr_key = key.mutable_aes_ctr_key();
  aes_ctr_key->set_key_value(std::string(16, 'a'));
  aes_ctr_key->mutable_params()->set_iv_size(12);
  auto hmac_key = key.mutable_hmac_key();
  hmac_key->set_key_value(std::string(16, 'b'));
  hmac_key->mutable_params()->set_hash(HashType::SHA1);
  hmac_key->mutable_params()->set_tag_size(10);
  return key;
}

TEST(AesCtrHmacAeadKeyManagerTest, ValidKey) {
  EXPECT_THAT(AesCtrHmacAeadKeyManager().ValidateKey(CreateValidKey()), IsOk());
}

TEST(AesCtrHmacAeadKeyManagerTest, AesKeySizes) {
  AesCtrHmacAeadKey key = CreateValidKey();
  for (int len = 0; len < 42; len++) {
    key.mutable_aes_ctr_key()->set_key_value(std::string(len, 'a'));
    if (len == 16 || len == 32) {
      EXPECT_THAT(AesCtrHmacAeadKeyManager().ValidateKey(key), IsOk())
          << " for length " << len;
    } else {
      EXPECT_THAT(AesCtrHmacAeadKeyManager().ValidateKey(key), Not(IsOk()))
          << " for length " << len;
    }
  }
}

TEST(AesCtrHmacAeadKeyManagerTest, HmacKeySizes) {
  AesCtrHmacAeadKey key = CreateValidKey();
  for (int len = 0; len < 42; len++) {
    key.mutable_hmac_key()->set_key_value(std::string(len, 'b'));
    if (len >= 16) {
      EXPECT_THAT(AesCtrHmacAeadKeyManager().ValidateKey(key), IsOk())
          << " for length " << len;
    } else {
      EXPECT_THAT(AesCtrHmacAeadKeyManager().ValidateKey(key), Not(IsOk()))
          << " for length " << len;
    }
  }
}

AesCtrHmacAeadKeyFormat CreateValidKeyFormat() {
  AesCtrHmacAeadKeyFormat key_format;
  auto aes_ctr_key_format = key_format.mutable_aes_ctr_key_format();
  aes_ctr_key_format->set_key_size(16);
  aes_ctr_key_format->mutable_params()->set_iv_size(16);
  auto hmac_key_format = key_format.mutable_hmac_key_format();
  hmac_key_format->set_key_size(21);
  hmac_key_format->mutable_params()->set_hash(HashType::SHA256);
  hmac_key_format->mutable_params()->set_tag_size(16);
  return key_format;
}

TEST(AesCtrHmacAeadKeyManagerTest, ValidateKeyFormat) {
  AesCtrHmacAeadKeyFormat key_format = CreateValidKeyFormat();
  EXPECT_THAT(
      AesCtrHmacAeadKeyManager().ValidateKeyFormat(CreateValidKeyFormat()),
      IsOk());
}

TEST(AesCtrHmacAeadKeyManagerTest, ValidateEmptyKeyFormat) {
  EXPECT_THAT(
      AesCtrHmacAeadKeyManager().ValidateKeyFormat(AesCtrHmacAeadKeyFormat()),
      Not(IsOk()));
}

TEST(AesCtrHmacAeadKeyManagerTest, ValidateKeyFormatKeySizes) {
  AesCtrHmacAeadKeyFormat key_format = CreateValidKeyFormat();
  for (int len = 0; len < 42; ++len) {
    key_format.mutable_aes_ctr_key_format()->set_key_size(len);
    if (len == 16 || len == 32) {
      EXPECT_THAT(AesCtrHmacAeadKeyManager().ValidateKeyFormat(key_format),
                  IsOk())
          << "for length " << len;
    } else {
      EXPECT_THAT(AesCtrHmacAeadKeyManager().ValidateKeyFormat(key_format),
                  Not(IsOk()))
          << "for length " << len;
    }
  }
}

TEST(AesCtrHmacAeadKeyManagerTest, ValidateKeyFormatHmacKeySizes) {
  AesCtrHmacAeadKeyFormat key_format = CreateValidKeyFormat();
  for (int len = 0; len < 42; ++len) {
    key_format.mutable_hmac_key_format()->set_key_size(len);
    if (len >= 16) {
      EXPECT_THAT(AesCtrHmacAeadKeyManager().ValidateKeyFormat(key_format),
                  IsOk())
          << "for length " << len;
    } else {
      EXPECT_THAT(AesCtrHmacAeadKeyManager().ValidateKeyFormat(key_format),
                  Not(IsOk()))
          << "for length " << len;
    }
  }
}

TEST(AesCtrHmacAeadKeyManagerTest, CreateKey) {
  AesCtrHmacAeadKeyFormat key_format = CreateValidKeyFormat();
  StatusOr<AesCtrHmacAeadKey> key_or =
      AesCtrHmacAeadKeyManager().CreateKey(key_format);
  ASSERT_THAT(key_or.status(), IsOk());
  const AesCtrHmacAeadKey& key = key_or.ValueOrDie();
  EXPECT_THAT(AesCtrHmacAeadKeyManager().ValidateKey(key),
              IsOk());
  EXPECT_THAT(key.aes_ctr_key().params().iv_size(),
              Eq(key_format.aes_ctr_key_format().params().iv_size()));
  EXPECT_THAT(key.aes_ctr_key().key_value(),
              SizeIs(key_format.aes_ctr_key_format().key_size()));
  EXPECT_THAT(key.hmac_key().params().hash(),
              Eq(key_format.hmac_key_format().params().hash()));
  EXPECT_THAT(key.hmac_key().params().tag_size(),
              Eq(key_format.hmac_key_format().params().tag_size()));
  EXPECT_THAT(key.hmac_key().key_value(),
              SizeIs(key_format.hmac_key_format().key_size()));
}

TEST(AesCtrHmacAeadKeyManagerTest, CreateAead) {
  AesCtrHmacAeadKey key = CreateValidKey();

  StatusOr<std::unique_ptr<Aead>> aead_or =
      AesCtrHmacAeadKeyManager().GetPrimitive<Aead>(key);
  ASSERT_THAT(aead_or.status(), IsOk());

  auto direct_aes_ctr_or = subtle::AesCtrBoringSsl::New(
      key.aes_ctr_key().key_value(), key.aes_ctr_key().params().iv_size());
  ASSERT_THAT(direct_aes_ctr_or.status(), IsOk());

  auto direct_hmac_or = subtle::HmacBoringSsl::New(
      util::Enums::ProtoToSubtle(key.hmac_key().params().hash()),
      key.hmac_key().params().tag_size(), key.hmac_key().key_value());
  ASSERT_THAT(direct_hmac_or.status(), IsOk());

  auto direct_aead_or = subtle::EncryptThenAuthenticate::New(
      std::move(direct_aes_ctr_or.ValueOrDie()),
      std::move(direct_hmac_or.ValueOrDie()),
      key.hmac_key().params().tag_size());
  ASSERT_THAT(direct_aead_or.status(), IsOk());

  EXPECT_THAT(EncryptThenDecrypt(aead_or.ValueOrDie().get(),
                                 direct_aead_or.ValueOrDie().get(),
                                 "message", "aad"),
              IsOk());
}

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

#include "tink/aead/aes_ctr_hmac_aead_key_manager.h"

#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "tink/config.h"
#include "tink/mac/mac_config.h"
#include "tink/subtle/aead_test_util.h"
#include "tink/subtle/aes_ctr_boringssl.h"
#include "tink/subtle/encrypt_then_authenticate.h"
#include "tink/subtle/hmac_boringssl.h"
#include "tink/util/enums.h"
#include "tink/util/status.h"
#include "tink/util/statusor.h"
#include "tink/util/test_matchers.h"
#include "proto/aes_ctr_hmac_aead.pb.h"
#include "proto/common.pb.h"
#include "proto/tink.pb.h"

namespace crypto {
namespace tink {

using ::crypto::tink::test::IsOk;
using ::crypto::tink::test::StatusIs;
using ::crypto::tink::util::StatusOr;
using ::google::crypto::tink::AesCtrHmacAeadKey;
using ::google::crypto::tink::AesCtrHmacAeadKeyFormat;
using ::google::crypto::tink::HashType;
using ::google::crypto::tink::KeyData;
using ::testing::Eq;
using ::testing::Not;
using ::testing::SizeIs;

namespace {

TEST(AesCtrHmacAeadKeyManagerTest, Basics) {
  EXPECT_THAT(AesCtrHmacAeadKeyManager().get_version(), Eq(0));
  EXPECT_THAT(AesCtrHmacAeadKeyManager().get_key_type(),
              Eq("type.googleapis.com/google.crypto.tink.AesCtrHmacAeadKey"));
  EXPECT_THAT(AesCtrHmacAeadKeyManager().key_material_type(),
              Eq(google::crypto::tink::KeyData::SYMMETRIC));
}

TEST(AesCtrHmacAeadKeyManagerTest, ValidateEmptyKey) {
  EXPECT_THAT(AesCtrHmacAeadKeyManager().ValidateKey(AesCtrHmacAeadKey()),
              StatusIs(util::error::INVALID_ARGUMENT));
}

AesCtrHmacAeadKey CreateValidKey() {
  AesCtrHmacAeadKey key;
  key.set_version(0);
  auto aes_ctr_key = key.mutable_aes_ctr_key();
  aes_ctr_key->set_key_value(std::string(16, 'a'));
  aes_ctr_key->mutable_params()->set_iv_size(12);
  auto hmac_key = key.mutable_hmac_key();
  hmac_key->set_key_value(std::string(16, 'b'));
  hmac_key->mutable_params()->set_hash(HashType::SHA1);
  hmac_key->mutable_params()->set_tag_size(10);
  return key;
}

TEST(AesCtrHmacAeadKeyManagerTest, ValidKey) {
  EXPECT_THAT(AesCtrHmacAeadKeyManager().ValidateKey(CreateValidKey()), IsOk());
}

TEST(AesCtrHmacAeadKeyManagerTest, AesKeySizes) {
  AesCtrHmacAeadKey key = CreateValidKey();
  for (int len = 0; len < 42; len++) {
    key.mutable_aes_ctr_key()->set_key_value(std::string(len, 'a'));
    if (len == 16 || len == 32) {
      EXPECT_THAT(AesCtrHmacAeadKeyManager().ValidateKey(key), IsOk())
          << " for length " << len;
    } else {
      EXPECT_THAT(AesCtrHmacAeadKeyManager().ValidateKey(key), Not(IsOk()))
          << " for length " << len;
    }
  }
}

TEST(AesCtrHmacAeadKeyManagerTest, HmacKeySizes) {
  AesCtrHmacAeadKey key = CreateValidKey();
  for (int len = 0; len < 42; len++) {
    key.mutable_hmac_key()->set_key_value(std::string(len, 'b'));
    if (len >= 16) {
      EXPECT_THAT(AesCtrHmacAeadKeyManager().ValidateKey(key), IsOk())
          << " for length " << len;
    } else {
      EXPECT_THAT(AesCtrHmacAeadKeyManager().ValidateKey(key), Not(IsOk()))
          << " for length " << len;
    }
  }
}

AesCtrHmacAeadKeyFormat CreateValidKeyFormat() {
  AesCtrHmacAeadKeyFormat key_format;
  auto aes_ctr_key_format = key_format.mutable_aes_ctr_key_format();
  aes_ctr_key_format->set_key_size(16);
  aes_ctr_key_format->mutable_params()->set_iv_size(16);
  auto hmac_key_format = key_format.mutable_hmac_key_format();
  hmac_key_format->set_key_size(21);
  hmac_key_format->mutable_params()->set_hash(HashType::SHA256);
  hmac_key_format->mutable_params()->set_tag_size(16);
  return key_format;
}

TEST(AesCtrHmacAeadKeyManagerTest, ValidateKeyFormat) {
  AesCtrHmacAeadKeyFormat key_format = CreateValidKeyFormat();
  EXPECT_THAT(
      AesCtrHmacAeadKeyManager().ValidateKeyFormat(CreateValidKeyFormat()),
      IsOk());
}

TEST(AesCtrHmacAeadKeyManagerTest, ValidateEmptyKeyFormat) {
  EXPECT_THAT(
      AesCtrHmacAeadKeyManager().ValidateKeyFormat(AesCtrHmacAeadKeyFormat()),
      Not(IsOk()));
}

TEST(AesCtrHmacAeadKeyManagerTest, ValidateKeyFormatKeySizes) {
  AesCtrHmacAeadKeyFormat key_format = CreateValidKeyFormat();
  for (int len = 0; len < 42; ++len) {
    key_format.mutable_aes_ctr_key_format()->set_key_size(len);
    if (len == 16 || len == 32) {
      EXPECT_THAT(AesCtrHmacAeadKeyManager().ValidateKeyFormat(key_format),
                  IsOk())
          << "for length " << len;
    } else {
      EXPECT_THAT(AesCtrHmacAeadKeyManager().ValidateKeyFormat(key_format),
                  Not(IsOk()))
          << "for length " << len;
    }
  }
}

TEST(AesCtrHmacAeadKeyManagerTest, ValidateKeyFormatHmacKeySizes) {
  AesCtrHmacAeadKeyFormat key_format = CreateValidKeyFormat();
  for (int len = 0; len < 42; ++len) {
    key_format.mutable_hmac_key_format()->set_key_size(len);
    if (len >= 16) {
      EXPECT_THAT(AesCtrHmacAeadKeyManager().ValidateKeyFormat(key_format),
                  IsOk())
          << "for length " << len;
    } else {
      EXPECT_THAT(AesCtrHmacAeadKeyManager().ValidateKeyFormat(key_format),
                  Not(IsOk()))
          << "for length " << len;
    }
  }
}

TEST(AesCtrHmacAeadKeyManagerTest, CreateKey) {
  AesCtrHmacAeadKeyFormat key_format = CreateValidKeyFormat();
  StatusOr<AesCtrHmacAeadKey> key_or =
      AesCtrHmacAeadKeyManager().CreateKey(key_format);
  ASSERT_THAT(key_or.status(), IsOk());
  const AesCtrHmacAeadKey& key = key_or.ValueOrDie();
  EXPECT_THAT(AesCtrHmacAeadKeyManager().ValidateKey(key),
              IsOk());
  EXPECT_THAT(key.aes_ctr_key().params().iv_size(),
              Eq(key_format.aes_ctr_key_format().params().iv_size()));
  EXPECT_THAT(key.aes_ctr_key().key_value(),
              SizeIs(key_format.aes_ctr_key_format().key_size()));
  EXPECT_THAT(key.hmac_key().params().hash(),
              Eq(key_format.hmac_key_format().params().hash()));
  EXPECT_THAT(key.hmac_key().params().tag_size(),
              Eq(key_format.hmac_key_format().params().tag_size()));
  EXPECT_THAT(key.hmac_key().key_value(),
              SizeIs(key_format.hmac_key_format().key_size()));
}

TEST(AesCtrHmacAeadKeyManagerTest, CreateAead) {
  AesCtrHmacAeadKey key = CreateValidKey();

  StatusOr<std::unique_ptr<Aead>> aead_or =
      AesCtrHmacAeadKeyManager().GetPrimitive<Aead>(key);
  ASSERT_THAT(aead_or.status(), IsOk());

  auto direct_aes_ctr_or = subtle::AesCtrBoringSsl::New(
      key.aes_ctr_key().key_value(), key.aes_ctr_key().params().iv_size());
  ASSERT_THAT(direct_aes_ctr_or.status(), IsOk());

  auto direct_hmac_or = subtle::HmacBoringSsl::New(
      util::Enums::ProtoToSubtle(key.hmac_key().params().hash()),
      key.hmac_key().params().tag_size(), key.hmac_key().key_value());
  ASSERT_THAT(direct_hmac_or.status(), IsOk());

  auto direct_aead_or = subtle::EncryptThenAuthenticate::New(
      std::move(direct_aes_ctr_or.ValueOrDie()),
      std::move(direct_hmac_or.ValueOrDie()),
      key.hmac_key().params().tag_size());
  ASSERT_THAT(direct_aead_or.status(), IsOk());

  EXPECT_THAT(EncryptThenDecrypt(aead_or.ValueOrDie().get(),
                                 direct_aead_or.ValueOrDie().get(),
                                 "message", "aad"),
              IsOk());
}

}  // namespace
}  // namespace tink
}  // namespace crypto
<|endoftext|>


<commit_before>#ifndef UTILS_HPP_
#define UTILS_HPP_
#include "basics.hpp"

#include <algorithm>
#include <vector>

#include <boost/math/special_functions.hpp>

namespace NPDivs {

template <typename T>
bool cmp_with_inf(T i, T j) { return boost::math::isinf(i) || i < j; }

template <typename T>
struct greater_than {
    greater_than(T x) : base(x) {}
    bool operator()(T y) { return y > base; }

    private:
        T base;
};

template <typename T>
void fix_terms(std::vector<T> &terms, double ub = .99) {
    /* Takes a vector of elements and replaces any infinite or very-large
     * elements with the value of the highest non-very-large element, as well
     * as possibly changing the order. "Very-large" is defined as the ub-th
     * quantile if ub < 1, otherwise the largest non-inf element.
     */
    typedef typename std::vector<T>::size_type sz;

    using std::max_element;
    using std::nth_element;
    using std::replace_if;
    using std::remove_if;

    T cutoff;
    bool find_noninf_max = true;

    // throw away any nans
    remove_if(terms.begin(), terms.end(), boost::math::isnan<T>);

    // try finding the ub-th percentile
    if (ub < 1) {
        sz k = terms.size() * ub; // the index we want
        nth_element(terms.begin(), terms.begin() + k, terms.end());
        cutoff = terms[k];

        find_noninf_max = boost::math::isinf(cutoff);
    }

    // just use the highest non-inf element
    if (find_noninf_max) {
        cutoff = *max_element(terms.begin(), terms.end(), cmp_with_inf<T>);
    }

    // replace anything greater than cutoff with cutoff
    replace_if(terms.begin(), terms.end(), greater_than<T>(cutoff), cutoff);
}

}

#endif
<commit_msg>hoping against hope this will work with old boost<commit_after>#ifndef FIX_TERMS_HPP_
#define FIX_TERMS_HPP_
#include "basics.hpp"

#include <algorithm>
#include <vector>

#include <boost/math/special_functions/fpclassify.hpp>

namespace NPDivs {

template <typename T>
bool cmp_with_inf(T i, T j) { return boost::math::isinf(i) || i < j; }

template <typename T>
struct greater_than {
    greater_than(T x) : base(x) {}
    bool operator()(T y) { return y > base; }

    private:
        T base;
};

template <typename T>
void fix_terms(std::vector<T> &terms, double ub = .99) {
    /* Takes a vector of elements and replaces any infinite or very-large
     * elements with the value of the highest non-very-large element, as well
     * as throwing away any nan values, possibly changing the order.
     * "Very-large" is defined as the ub-th quantile if ub < 1, otherwise the
     * largest non-inf element. Note that values of -inf are not altered.
     */
    typedef typename std::vector<T>::size_type sz;

    using std::max_element;
    using std::nth_element;
    using std::replace_if;
    using std::remove_if;

    T cutoff;
    bool find_noninf_max = true;

    // throw away any nans
    remove_if(terms.begin(), terms.end(), boost::math::isnan<T>);

    // try finding the ub-th percentile
    if (ub < 1) {
        sz k = terms.size() * ub; // the index we want
        nth_element(terms.begin(), terms.begin() + k, terms.end());
        cutoff = terms[k];

        find_noninf_max = boost::math::isinf(cutoff);
    }

    // just use the highest non-inf element
    if (find_noninf_max) {
        cutoff = *max_element(terms.begin(), terms.end(), cmp_with_inf<T>);
    }

    // replace anything greater than cutoff with cutoff
    replace_if(terms.begin(), terms.end(), greater_than<T>(cutoff), cutoff);
}

}

#endif
<|endoftext|>