<commit_before>/* -----------------------------------------------------------------------------
 * dicom.cpp
 * -----------------------------------------------------------------------------
 * Copyright (c) 2015 Blaine Rister et al., see LICENSE for details.
 * -----------------------------------------------------------------------------
 * C-language wrapper for the DCMTK library.
 * -----------------------------------------------------------------------------
 */

/*----------------Include the very picky DCMTK----------------*/
#include "dcmtk/config/osconfig.h"    /* make sure OS specific configuration is included first */

//XXX
#include "dcmtk/config/cfunix.h"

#define INCLUDE_CSTDIO
#define INCLUDE_CSTRING
#include "dcmtk/ofstd/ofstdinc.h"

#ifdef HAVE_GUSI_H
#include <GUSI.h>
#endif

#include "dcmtk/dcmdata/dctk.h"          /* for various dcmdata headers */
#include "dcmtk/dcmdata/cmdlnarg.h"      /* for prepareCmdLineArgs */
#include "dcmtk/dcmdata/dcuid.h"         /* for dcmtk version name */

#include "dcmtk/ofstd/ofconapp.h"        /* for OFConsoleApplication */
#include "dcmtk/ofstd/ofcmdln.h"         /* for OFCommandLine */

#include "dcmtk/oflog/oflog.h"           /* for OFLogger */

#include "dcmtk/dcmimgle/dcmimage.h"     /* for DicomImage */
#include "dcmtk/dcmimage/diregist.h"     /* include to support color images */
#include "dcmtk/dcmdata/dcrledrg.h"      /* for DcmRLEDecoderRegistration */

#ifdef BUILD_DCMSCALE_AS_DCMJSCAL
#include "dcmtk/dcmjpeg/djdecode.h"      /* for dcmjpeg decoders */
#include "dcmtk/dcmjpeg/dipijpeg.h"      /* for dcmimage JPEG plugin */
#endif

#ifdef WITH_ZLIB
#include <zlib.h>          /* for zlibVersion() */
#endif
/*---------------------------------------------------------*/

/* Other includes */
#include <iostream>
#include <stdint.h>
#include "imutil.h"
#include "macros.h"
#include "dicom.h"

/* Macro to call a C++ function and catch any exceptions it throws,
 * returning SIFT3D_FAILURE when an exception is caught. */
#define CATCH_EXCEPTIONS(tag, fun, ...) \
        try { \
                (fun)( __VA_ARGS__ ); \
        } catch (std::exception &e) { \
\
                std::cerr << e.what() << std::endl; \
\
        } catch (...) { \
\
                std::cerr << tag ": unexpected exception " << std::endl; \
\
                return SIFT3D_FAILURE; \
        } \

/* Read a DICOM file into an Image struct. */
int read_dcm(const char *path, Image *const im) {

        CATCH_EXCEPTIONS("read_dcm", read_dcm, path, im);

        return SIFT3D_SUCCESS;
}

/* Read all of the DICOM files from a directory into an Image struct. Slices
 * must be ordered alphanumerically, starting with z = 0. */
int read_dcm_dir(const char *path, Image *const im) {

        CATCH_EXCEPTIONS("read_dcm_dir", read_dcm_dir, path, im);

        return SIFT3D_SUCCESS;
}

/* Write an Image struct into a DICOM file. */
int write_dcm(const char *path, const Image *const im) {

        CATCH_EXCEPTIONS("write_dcm", write_dcm, path, im);

        return SIFT3D_SUCCESS;
}

/* Write an Image struct into a directory of DICOM files. */
int write_dcm_dir(const char *path, const Image *const im) {

        CATCH_EXCEPTIONS("write_dcm_dir", write_dcm_dir, path, im);

        return SIFT3D_SUCCESS;
}

/* Helper function to read a DICOM file using C++ */
static int read_dcm_cpp(const char *path, Image *const im) {

        // Load the image
        DicomImage dicom(path);
        if (dicom.getStatus() != EIS_Normal) {
               std::cerr << "read_dcm_cpp: failed to open image " <<
                        path << " (" <<
                        DicomImage::getString(dicom.getStatus()) << ")" <<
                        std::endl;
                return SIFT3D_FAILURE;
        }

        // Check for color images
        if (!dicom.isMonochrome()) {
                std::cerr << "read_dcm_cpp: reading of color DICOM " <<
                        "images is not supported at this time" << std::endl;
                return SIFT3D_FAILURE;
        }

        // Set the window
        dicom.setMinMaxWindow();

        // Get the dimensions
        const int nx = dicom.getWidth();
        const int ny = dicom.getHeight();
        const int nz = dicom.getFrameCount();

        // Resize the output
        im->nx = nx;
        im->ny = ny;
        im->nz = nz;
        im->nc = 1;
        im_default_stride(im);
        if (im_resize(im))
                return SIFT3D_FAILURE;

        // Load the image as a DcmFileFormat
        DcmFileFormat fileformat;
        OFCondition status = fileformat.loadFile(path);
        if (!status.good()) {
               std::cerr << "read_dcm_cpp: failed to read DICOM file " <<
                        path << " (" << status.text() << ")" <<
                        std::endl;
                return SIFT3D_FAILURE;
        }

        // Read the pixel spacing
        Float64 pixelSpacing;
        status =  fileformat.getMetaInfo()->findAndGetFloat64(DCM_PixelSpacing,
                pixelSpacing);
        if (!status.good()) {
                std::cerr << "read_dcm_cpp: failed to get pixel spacing " <<
                        "from file " << path << " (" << status.text() << ")" <<
                        std::endl;
                return SIFT3D_FAILURE;
        }
        const double ux = static_cast<double>(pixelSpacing);
        if (ux <= 0.0) {
                std::cerr << "read_dcm_cpp: file " << path << " has " <<
                        "invalid pixel spacing: " << ux << std::endl;
                return SIFT3D_FAILURE;
        }

        // Read the slice thickness
        Float64 sliceThickness;
        status = fileformat.getMetaInfo()->findAndGetFloat64(DCM_SliceThickness,
                sliceThickness);
        if (!status.good()) {
                std::cerr << "read_dcm_cpp: failed to get slice thickness " <<
                        "from file " << path << " (" << status.text() << ")" <<
                        std::endl;
        }

        // Convert to double
        const double uz = static_cast<double>(sliceThickness);
        if (uz  <= 0.0) {
                std::cerr << "read_dcm_cpp: file " << path << " has " <<
                        "invalid slice thickness: " << uz << std::endl;
                return SIFT3D_FAILURE;
        }

        //TODO
        // im->ux = ux;
        // im->uy = ux * dicom.getHeightWidthRatio();
        // im->uz = uz;

        // Read each frame
        for (int i = 0; i < nz; i++) {

                // Get a pointer to the data, rendered as a 32-bit int
                const uint32_t *const frameData =
                        static_cast<const uint32_t *const >(
                                dicom.getOutputData(32, i));
                if (frameData == NULL) {
                        std::cerr << "read_dcm_dir_cpp: could not get data "
                                << "from image " << path << " frame " << i <<
                                " (" <<
                                DicomImage::getString(dicom.getStatus()) <<
                                ")" << std::endl;
                }

                // Copy the frame
                const int x_start = 0;
                const int y_start = 0;
                const int z_start = i;
                const int x_end = nx - 1;
                const int y_end = ny - 1;
                const int z_end = z_start;
                int x, y, z;
                SIFT3D_IM_LOOP_LIMITED_START(im, x, y, z, x_start, x_end,
                        y_start, y_end, z_start, z_end)

                        SIFT3D_IM_GET_VOX(im, x, y, z, 0) =
                                static_cast<float>(frameData[x + y * nx]);

                SIFT3D_IM_LOOP_END
        }

        return SIFT3D_SUCCESS;
}

/* Helper funciton to read a directory of DICOM files using C++ */
static int read_dcm_dir_cpp(const char *path, Image *const im) {

        //TODO: Check if the directory exists, find the dicom images,
        // call read_dcm on them in order, reading to a dummy image,
        // copy the dummy image to each slice

        return SIFT3D_SUCCESS;
}

/* Helper function to write a DICOM file using C++ */
int write_dcm_cpp(const char *path, const Image *const im) {

        //TODO

        return SIFT3D_SUCCESS;
}

/* Helper function to write an image to a directory of DICOM files using C++ */
int write_dcm_dir_cpp(const char *path, const Image *const im) {

        //TODO copy each frame to a dummy image, write it with write_dcm

        return SIFT3D_SUCCESS;
}
<commit_msg>added dicom voxel spacing<commit_after>/* -----------------------------------------------------------------------------
 * dicom.cpp
 * -----------------------------------------------------------------------------
 * Copyright (c) 2015 Blaine Rister et al., see LICENSE for details.
 * -----------------------------------------------------------------------------
 * C-language wrapper for the DCMTK library.
 * -----------------------------------------------------------------------------
 */

/*----------------Include the very picky DCMTK----------------*/
#include "dcmtk/config/osconfig.h"    /* make sure OS specific configuration is included first */

//XXX
#include "dcmtk/config/cfunix.h"

#define INCLUDE_CSTDIO
#define INCLUDE_CSTRING
#include "dcmtk/ofstd/ofstdinc.h"

#ifdef HAVE_GUSI_H
#include <GUSI.h>
#endif

#include "dcmtk/dcmdata/dctk.h"          /* for various dcmdata headers */
#include "dcmtk/dcmdata/cmdlnarg.h"      /* for prepareCmdLineArgs */
#include "dcmtk/dcmdata/dcuid.h"         /* for dcmtk version name */

#include "dcmtk/ofstd/ofconapp.h"        /* for OFConsoleApplication */
#include "dcmtk/ofstd/ofcmdln.h"         /* for OFCommandLine */

#include "dcmtk/oflog/oflog.h"           /* for OFLogger */

#include "dcmtk/dcmimgle/dcmimage.h"     /* for DicomImage */
#include "dcmtk/dcmimage/diregist.h"     /* include to support color images */
#include "dcmtk/dcmdata/dcrledrg.h"      /* for DcmRLEDecoderRegistration */

#ifdef BUILD_DCMSCALE_AS_DCMJSCAL
#include "dcmtk/dcmjpeg/djdecode.h"      /* for dcmjpeg decoders */
#include "dcmtk/dcmjpeg/dipijpeg.h"      /* for dcmimage JPEG plugin */
#endif

#ifdef WITH_ZLIB
#include <zlib.h>          /* for zlibVersion() */
#endif
/*---------------------------------------------------------*/

/* Other includes */
#include <iostream>
#include <stdint.h>
#include "imutil.h"
#include "macros.h"
#include "dicom.h"

/* Macro to call a C++ function and catch any exceptions it throws,
 * returning SIFT3D_FAILURE when an exception is caught. */
#define CATCH_EXCEPTIONS(tag, fun, ...) \
        try { \
                (fun)( __VA_ARGS__ ); \
        } catch (std::exception &e) { \
\
                std::cerr << e.what() << std::endl; \
\
        } catch (...) { \
\
                std::cerr << tag ": unexpected exception " << std::endl; \
\
                return SIFT3D_FAILURE; \
        } \

/* Read a DICOM file into an Image struct. */
int read_dcm(const char *path, Image *const im) {

        CATCH_EXCEPTIONS("read_dcm", read_dcm, path, im);

        return SIFT3D_SUCCESS;
}

/* Read all of the DICOM files from a directory into an Image struct. Slices
 * must be ordered alphanumerically, starting with z = 0. */
int read_dcm_dir(const char *path, Image *const im) {

        CATCH_EXCEPTIONS("read_dcm_dir", read_dcm_dir, path, im);

        return SIFT3D_SUCCESS;
}

/* Write an Image struct into a DICOM file. */
int write_dcm(const char *path, const Image *const im) {

        CATCH_EXCEPTIONS("write_dcm", write_dcm, path, im);

        return SIFT3D_SUCCESS;
}

/* Write an Image struct into a directory of DICOM files. */
int write_dcm_dir(const char *path, const Image *const im) {

        CATCH_EXCEPTIONS("write_dcm_dir", write_dcm_dir, path, im);

        return SIFT3D_SUCCESS;
}

/* Helper function to read a DICOM file using C++ */
static int read_dcm_cpp(const char *path, Image *const im) {

        // Load the image
        DicomImage dicom(path);
        if (dicom.getStatus() != EIS_Normal) {
               std::cerr << "read_dcm_cpp: failed to open image " <<
                        path << " (" <<
                        DicomImage::getString(dicom.getStatus()) << ")" <<
                        std::endl;
                return SIFT3D_FAILURE;
        }

        // Check for color images
        if (!dicom.isMonochrome()) {
                std::cerr << "read_dcm_cpp: reading of color DICOM " <<
                        "images is not supported at this time" << std::endl;
                return SIFT3D_FAILURE;
        }

        // Set the window
        dicom.setMinMaxWindow();

        // Get the dimensions
        const int nx = dicom.getWidth();
        const int ny = dicom.getHeight();
        const int nz = dicom.getFrameCount();

        // Resize the output
        im->nx = nx;
        im->ny = ny;
        im->nz = nz;
        im->nc = 1;
        im_default_stride(im);
        if (im_resize(im))
                return SIFT3D_FAILURE;

        // Load the image as a DcmFileFormat
        DcmFileFormat fileformat;
        OFCondition status = fileformat.loadFile(path);
        if (!status.good()) {
               std::cerr << "read_dcm_cpp: failed to read DICOM file " <<
                        path << " (" << status.text() << ")" <<
                        std::endl;
                return SIFT3D_FAILURE;
        }

        // Read the pixel spacing
        Float64 pixelSpacing;
        status =  fileformat.getMetaInfo()->findAndGetFloat64(DCM_PixelSpacing,
                pixelSpacing);
        if (!status.good()) {
                std::cerr << "read_dcm_cpp: failed to get pixel spacing " <<
                        "from file " << path << " (" << status.text() << ")" <<
                        std::endl;
                return SIFT3D_FAILURE;
        }
        const double ux = static_cast<double>(pixelSpacing);
        if (ux <= 0.0) {
                std::cerr << "read_dcm_cpp: file " << path << " has " <<
                        "invalid pixel spacing: " << ux << std::endl;
                return SIFT3D_FAILURE;
        }

        // Read the slice thickness
        Float64 sliceThickness;
        status = fileformat.getMetaInfo()->findAndGetFloat64(DCM_SliceThickness,
                sliceThickness);
        if (!status.good()) {
                std::cerr << "read_dcm_cpp: failed to get slice thickness " <<
                        "from file " << path << " (" << status.text() << ")" <<
                        std::endl;
        }

        // Convert to double
        const double uz = static_cast<double>(sliceThickness);
        if (uz  <= 0.0) {
                std::cerr << "read_dcm_cpp: file " << path << " has " <<
                        "invalid slice thickness: " << uz << std::endl;
                return SIFT3D_FAILURE;
        }

        // Store the voxel spacing
        im->ux = ux;
        im->uy = ux * dicom.getHeightWidthRatio();
        im->uz = uz;

        // Read each frame
        for (int i = 0; i < nz; i++) {

                // Get a pointer to the data, rendered as a 32-bit int
                const uint32_t *const frameData =
                        static_cast<const uint32_t *const >(
                                dicom.getOutputData(32, i));
                if (frameData == NULL) {
                        std::cerr << "read_dcm_dir_cpp: could not get data "
                                << "from image " << path << " frame " << i <<
                                " (" <<
                                DicomImage::getString(dicom.getStatus()) <<
                                ")" << std::endl;
                }

                // Copy the frame
                const int x_start = 0;
                const int y_start = 0;
                const int z_start = i;
                const int x_end = nx - 1;
                const int y_end = ny - 1;
                const int z_end = z_start;
                int x, y, z;
                SIFT3D_IM_LOOP_LIMITED_START(im, x, y, z, x_start, x_end,
                        y_start, y_end, z_start, z_end)

                        SIFT3D_IM_GET_VOX(im, x, y, z, 0) =
                                static_cast<float>(frameData[x + y * nx]);

                SIFT3D_IM_LOOP_END
        }

        return SIFT3D_SUCCESS;
}

/* Helper funciton to read a directory of DICOM files using C++ */
static int read_dcm_dir_cpp(const char *path, Image *const im) {

        //TODO: Check if the directory exists, find the dicom images,
        // call read_dcm on them in order, reading to a dummy image,
        // copy the dummy image to each slice

        return SIFT3D_SUCCESS;
}

/* Helper function to write a DICOM file using C++ */
int write_dcm_cpp(const char *path, const Image *const im) {

        //TODO

        return SIFT3D_SUCCESS;
}

/* Helper function to write an image to a directory of DICOM files using C++ */
int write_dcm_dir_cpp(const char *path, const Image *const im) {

        //TODO copy each frame to a dummy image, write it with write_dcm

        return SIFT3D_SUCCESS;
}
<|endoftext|>


<commit_before>#include <numeric>

#include <catch.hpp>
#include <sliding_window.hpp>

TEST_CASE("default construct sliding_windows", "[sliding_window]")
{
    helene::stack_sliding_window<int, 3> ssw;

    SECTION("push back value 1")
    {
        ssw.push_back(1);

        CHECK(ssw.back() == 1);

        CHECK(ssw[0] == 0);
        CHECK(ssw[1] == 0);
        CHECK(ssw[2] == 1);
    }

    SECTION("push front value 1")
    {
        ssw.push_front(1);

        CHECK(ssw.front() == 1);

        CHECK(ssw[0] == 1);
        CHECK(ssw[1] == 0);
        CHECK(ssw[2] == 0);
    }

    SECTION("set all elements in window by iterators")
    {
        auto beg_it = ssw.begin();
        auto end_it = ssw.end();

        CHECK(std::distance(beg_it, end_it) == 3);

        std::iota(beg_it, end_it, 10);

        CHECK(ssw[0] == 10);
        CHECK(ssw[1] == 11);
        CHECK(ssw[2] == 12);

        SECTION("push_back 2 elements")
        {
            ssw.push_back(int(), 2);

            CHECK(ssw[0] == 12);
            CHECK(ssw[1] == int());
            CHECK(ssw[2] == int());
        }
    }

    SECTION("push back 2 values")
    {
        ssw.push_back(100, 2);

        CHECK(ssw[0] == 0);
        CHECK(ssw[1] == 100);
        CHECK(ssw[2] == 100);
    }

    SECTION("push back 10 values")
    {
        ssw.push_back(100, 10);

        CHECK(ssw[0] == 100);
        CHECK(ssw[1] == 100);
        CHECK(ssw[2] == 100);
    }

    SECTION("push_front 2 values")
    {
        ssw.push_front(11, 2);

        CHECK(ssw[0] == 11);
        CHECK(ssw[1] == 11);
        CHECK(ssw[2] == 0);
    }

    SECTION("push_front 10 values")
    {
        ssw.push_front(12, 10);

        CHECK(ssw[0] == 12);
        CHECK(ssw[1] == 12);
        CHECK(ssw[2] == 12);

        SECTION("copy construct")
        {
            decltype(ssw) ssw2 = ssw;

            CHECK(ssw[0] == 12);
            CHECK(ssw[1] == 12);
            CHECK(ssw[2] == 12);
            CHECK(ssw2[0] == 12);
            CHECK(ssw2[1] == 12);
            CHECK(ssw2[2] == 12);

            SECTION("modify original")
            {
                ssw[0] = 50;

                CHECK(ssw[0] == 50);
                CHECK(ssw[1] == 12);
                CHECK(ssw[2] == 12);
                CHECK(ssw2[0] == 12);
                CHECK(ssw2[1] == 12);
                CHECK(ssw2[2] == 12);
            }
        }
        SECTION("copy assign")
        {
            decltype(ssw) ssw2;
            ssw2 = ssw;

            CHECK(ssw[0] == 12);
            CHECK(ssw[1] == 12);
            CHECK(ssw[2] == 12);
            CHECK(ssw2[0] == 12);
            CHECK(ssw2[1] == 12);
            CHECK(ssw2[2] == 12);

            SECTION("modify original")
            {
                ssw[0] = 50;

                CHECK(ssw[0] == 50);
                CHECK(ssw[1] == 12);
                CHECK(ssw[2] == 12);
                CHECK(ssw2[0] == 12);
                CHECK(ssw2[1] == 12);
                CHECK(ssw2[2] == 12);
            }
        }
    }
}

TEST_CASE("construct static_heap_sliding_window with iterators to range")
{
    std::string initial_message("hello world");
    helene::static_heap_sliding_window<std::string::value_type, 11> message(
        initial_message.begin(), initial_message.end());

    CHECK(message[0] == 'h');
    CHECK(message[1] == 'e');
    CHECK(message[2] == 'l');
    CHECK(message[3] == 'l');
    CHECK(message[4] == 'o');
    CHECK(message[5] == ' ');
    CHECK(message[6] == 'w');
    CHECK(message[7] == 'o');
    CHECK(message[8] == 'r');
    CHECK(message[9] == 'l');
    CHECK(message[10] == 'd');
}

TEST_CASE("construct static_heap_sliding_window with iterators to range bigger "
          "than Size")
{
    std::vector<int> range{1, 2, 3, 4, 5};

    helene::static_heap_sliding_window<int, 3> shsw(range.begin(), range.end());

    CHECK(shsw[0] == 3);
    CHECK(shsw[1] == 4);
    CHECK(shsw[2] == 5);
}

TEST_CASE("construct static_heap_sliding_window with iterators to range "
          "smaller than Size")
{
    std::vector<int> range{1, 2, 3};

    helene::static_heap_sliding_window<int, 5> shsw(range.begin(), range.end());

    CHECK(shsw[0] == 0);
    CHECK(shsw[1] == 0);
    CHECK(shsw[2] == 1);
    CHECK(shsw[3] == 2);
    CHECK(shsw[4] == 3);
}
<commit_msg>Add unit tests for move semantics. 	modified:   tests/test_sliding_window.cpp<commit_after>#include <numeric>

#include <catch.hpp>
#include <sliding_window.hpp>

TEST_CASE("default construct sliding_windows", "[sliding_window]")
{
    helene::stack_sliding_window<int, 3> ssw;

    SECTION("push back value 1")
    {
        ssw.push_back(1);

        CHECK(ssw.back() == 1);

        CHECK(ssw[0] == 0);
        CHECK(ssw[1] == 0);
        CHECK(ssw[2] == 1);
    }

    SECTION("push front value 1")
    {
        ssw.push_front(1);

        CHECK(ssw.front() == 1);

        CHECK(ssw[0] == 1);
        CHECK(ssw[1] == 0);
        CHECK(ssw[2] == 0);
    }

    SECTION("set all elements in window by iterators")
    {
        auto beg_it = ssw.begin();
        auto end_it = ssw.end();

        CHECK(std::distance(beg_it, end_it) == 3);

        std::iota(beg_it, end_it, 10);

        CHECK(ssw[0] == 10);
        CHECK(ssw[1] == 11);
        CHECK(ssw[2] == 12);

        SECTION("push_back 2 elements")
        {
            ssw.push_back(int(), 2);

            CHECK(ssw[0] == 12);
            CHECK(ssw[1] == int());
            CHECK(ssw[2] == int());
        }
    }

    SECTION("push back 2 values")
    {
        ssw.push_back(100, 2);

        CHECK(ssw[0] == 0);
        CHECK(ssw[1] == 100);
        CHECK(ssw[2] == 100);
    }

    SECTION("push back 10 values")
    {
        ssw.push_back(100, 10);

        CHECK(ssw[0] == 100);
        CHECK(ssw[1] == 100);
        CHECK(ssw[2] == 100);
    }

    SECTION("push_front 2 values")
    {
        ssw.push_front(11, 2);

        CHECK(ssw[0] == 11);
        CHECK(ssw[1] == 11);
        CHECK(ssw[2] == 0);
    }

    SECTION("push_front 10 values")
    {
        ssw.push_front(12, 10);

        CHECK(ssw[0] == 12);
        CHECK(ssw[1] == 12);
        CHECK(ssw[2] == 12);

        SECTION("copy construct")
        {
            decltype(ssw) ssw2 = ssw;

            CHECK(ssw[0] == 12);
            CHECK(ssw[1] == 12);
            CHECK(ssw[2] == 12);
            CHECK(ssw2[0] == 12);
            CHECK(ssw2[1] == 12);
            CHECK(ssw2[2] == 12);

            SECTION("modify original")
            {
                ssw[0] = 50;

                CHECK(ssw[0] == 50);
                CHECK(ssw[1] == 12);
                CHECK(ssw[2] == 12);
                CHECK(ssw2[0] == 12);
                CHECK(ssw2[1] == 12);
                CHECK(ssw2[2] == 12);
            }
        }

        SECTION("copy assign")
        {
            decltype(ssw) ssw2;
            ssw2 = ssw;

            CHECK(ssw[0] == 12);
            CHECK(ssw[1] == 12);
            CHECK(ssw[2] == 12);
            CHECK(ssw2[0] == 12);
            CHECK(ssw2[1] == 12);
            CHECK(ssw2[2] == 12);

            SECTION("modify original")
            {
                ssw[0] = 50;

                CHECK(ssw[0] == 50);
                CHECK(ssw[1] == 12);
                CHECK(ssw[2] == 12);
                CHECK(ssw2[0] == 12);
                CHECK(ssw2[1] == 12);
                CHECK(ssw2[2] == 12);
            }
        }

        SECTION("move construct")
        {
            decltype(ssw) ssw2(std::move(ssw));

            CHECK(ssw2[0] == 12);
            CHECK(ssw2[1] == 12);
            CHECK(ssw2[2] == 12);
        }

        SECTION("move assign")
        {
            decltype(ssw) ssw2;
            ssw2 = std::move(ssw);

            CHECK(ssw2[0] == 12);
            CHECK(ssw2[1] == 12);
            CHECK(ssw2[2] == 12);
        }
    }
}

TEST_CASE("construct static_heap_sliding_window with iterators to range")
{
    std::string initial_message("hello world");
    helene::static_heap_sliding_window<std::string::value_type, 11> message(
        initial_message.begin(), initial_message.end());

    CHECK(message[0] == 'h');
    CHECK(message[1] == 'e');
    CHECK(message[2] == 'l');
    CHECK(message[3] == 'l');
    CHECK(message[4] == 'o');
    CHECK(message[5] == ' ');
    CHECK(message[6] == 'w');
    CHECK(message[7] == 'o');
    CHECK(message[8] == 'r');
    CHECK(message[9] == 'l');
    CHECK(message[10] == 'd');
}

TEST_CASE("construct static_heap_sliding_window with iterators to range bigger "
          "than Size")
{
    std::vector<int> range{1, 2, 3, 4, 5};

    helene::static_heap_sliding_window<int, 3> shsw(range.begin(), range.end());

    CHECK(shsw[0] == 3);
    CHECK(shsw[1] == 4);
    CHECK(shsw[2] == 5);
}

TEST_CASE("construct static_heap_sliding_window with iterators to range "
          "smaller than Size")
{
    std::vector<int> range{1, 2, 3};

    helene::static_heap_sliding_window<int, 5> shsw(range.begin(), range.end());

    CHECK(shsw[0] == 0);
    CHECK(shsw[1] == 0);
    CHECK(shsw[2] == 1);
    CHECK(shsw[3] == 2);
    CHECK(shsw[4] == 3);
}
<|endoftext|>


<commit_before>// @(#)root/gui:$Id$
// Author: Fons Rademakers   20/02/98

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TRootDialog                                                          //
//                                                                      //
// A TRootDialog is used to prompt for the arguments of an object's     //
// member function. A TRootDialog is created via the context menu's     //
// when selecting a member function taking arguments.                   //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "TRootDialog.h"
#include "TRootContextMenu.h"
#include "TContextMenu.h"
#include "TClassMenuItem.h"
#include "TList.h"
#include "TGLabel.h"
#include "TGTextEntry.h"
#include "TGButton.h"
#include "TObjString.h"
#include "KeySymbols.h"

extern TGTextEntry *gBlinkingEntry;

ClassImp(TRootDialog)

//______________________________________________________________________________
TRootDialog::TRootDialog(TRootContextMenu *cmenu, const TGWindow *main,
    const char *title, Bool_t okB, Bool_t cancelB, Bool_t applyB,
    Bool_t helpB) : TGTransientFrame(gClient->GetRoot(), main, 200, 100)
{
   // Create a method argument prompt dialog.

   fMenu   = cmenu;

   fOk     = okB;
   fCancel = cancelB;
   fApply  = applyB;
   fHelp   = helpB;

   fWidgets = new TList;

   fL1 = new TGLayoutHints(kLHintsTop | kLHintsCenterX, 0, 0, 5, 0);
   fL2 = new TGLayoutHints(kLHintsTop | kLHintsLeft, 5, 5, 5, 5);

   SetWindowName(title);
   SetIconName(title);
   SetEditDisabled(kEditDisable);

   AddInput(kKeyPressMask | kEnterWindowMask | kLeaveWindowMask);
}

//______________________________________________________________________________
TRootDialog::~TRootDialog()
{
   // Delete the dialog.

   fWidgets->Delete();
   delete fWidgets;
   delete fL1;
   delete fL2;
}

//______________________________________________________________________________
void TRootDialog::Add(const char *argname, const char *value, const char *type)
{
   // Add a label and text input field.

   TGLabel      *l = new TGLabel(this, argname);
   TGTextBuffer *b = new TGTextBuffer(20); b->AddText(0, value);
   TGTextEntry  *t = new TGTextEntry(this, b);

   t->Connect("TabPressed()", "TRootDialog", this, "TabPressed()");

   t->Associate(fMenu);
   t->Resize(260, t->GetDefaultHeight());
   AddFrame(l, fL1);
   AddFrame(t, fL2);

   fWidgets->Add(l);
   fWidgets->Add(t);   // TGTextBuffer will be deleted by TGTextEntry
   fWidgets->Add(new TObjString(type));
}

//______________________________________________________________________________
const char *TRootDialog::GetParameters()
{
   // Get parameter string (called by contextmenu after OK or Apply has
   // been selected).

   static TString params;
   TString param;

   TObjString   *str;
   TObject      *obj;

   Int_t selfobjpos;
   if (fMenu->GetContextMenu()->GetSelectedMenuItem())
      selfobjpos = fMenu->GetContextMenu()->GetSelectedMenuItem()->GetSelfObjectPos();
   else
      selfobjpos = -1;

   params.Clear();
   TIter next(fWidgets);
   Int_t nparam = 0;

   while ((obj = next())) {        // first element is label, skip...
      if (obj->IsA() != TGLabel::Class()) break;
      obj = next();                // get either TGTextEntry or TGComboBox
      str = (TObjString *) next(); // get type string

      nparam++;

      const char *type = str->GetString().Data();
      const char *data = 0;

      if (obj->IsA() == TGTextEntry::Class())
         data = ((TGTextEntry *) obj)->GetBuffer()->GetString();

      // TODO: Combobox...

      // if necessary, replace the selected object by it's address
      if (selfobjpos == nparam-1) {
         if (params.Length()) params += ",";
         param = TString::Format("(TObject*)0x%lx",
               (Long_t)fMenu->GetContextMenu()->GetSelectedObject());
         params += param;
      }

      if (params.Length()) params += ",";
      if (data) {
         if (!strncmp(type, "char*", 5))
            param = TString::Format("\"%s\"", data);
         else
            param = data;
      } else
         param = "0";

      params += param;
   }

   // if selected object is the last argument, have to insert it here
   if (selfobjpos == nparam) {
      if (params.Length()) params += ",";
      param = TString::Format("(TObject*)0x%lx",
            (Long_t)fMenu->GetContextMenu()->GetSelectedObject());
      params += param;
   }

   return params.Data();
}

//______________________________________________________________________________
void TRootDialog::Popup()
{
   // Popup dialog.

   //--- create the OK, Apply and Cancel buttons

   UInt_t  nb = 0, width = 0, height = 0;

   TGHorizontalFrame *hf = new TGHorizontalFrame(this, 60, 20, kFixedWidth);
   TGLayoutHints     *l1 = new TGLayoutHints(kLHintsCenterY | kLHintsExpandX, 5, 5, 0, 0);

   // put hf as last in the list to be deleted
   fWidgets->Add(l1);

   TGTextButton *b;
   if (fOk) {
      b = new TGTextButton(hf, "&OK", 1);
      fWidgets->Add(b);
      b->Associate(fMenu);
      hf->AddFrame(b, l1);
      height = b->GetDefaultHeight();
      width  = TMath::Max(width, b->GetDefaultWidth()); ++nb;
   }
   if (fApply) {
      b = new TGTextButton(hf, "&Apply", 2);
      fWidgets->Add(b);
      b->Associate(fMenu);
      hf->AddFrame(b, l1);
      height = b->GetDefaultHeight();
      width  = TMath::Max(width, b->GetDefaultWidth()); ++nb;
   }
   if (fCancel) {
      b = new TGTextButton(hf, "&Cancel", 3);
      fWidgets->Add(b);
      b->Associate(fMenu);
      hf->AddFrame(b, l1);
      height = b->GetDefaultHeight();
      width  = TMath::Max(width, b->GetDefaultWidth()); ++nb;
   }
   if (fHelp) {
      b = new TGTextButton(hf, "Online &Help", 4);
      fWidgets->Add(b);
      b->Associate(fMenu);
      hf->AddFrame(b, l1);
      height = b->GetDefaultHeight();
      width  = TMath::Max(width, b->GetDefaultWidth()); ++nb;
   }

   // place buttons at the bottom
   l1 = new TGLayoutHints(kLHintsBottom | kLHintsCenterX, 0, 0, 5, 5);
   fWidgets->Add(l1);
   fWidgets->Add(hf);

   AddFrame(hf, l1);

   // keep the buttons centered and with the same width
   hf->Resize((width + 20) * nb, height);

   // map all widgets and calculate size of dialog
   MapSubwindows();

   width  = GetDefaultWidth();
   height = GetDefaultHeight();

   Resize(width, height);

   // position relative to the parent's window
   CenterOnParent();

   // make the message box non-resizable
   SetWMSize(width, height);
   SetWMSizeHints(width, height, width, height, 0, 0);

   SetMWMHints(kMWMDecorAll | kMWMDecorResizeH  | kMWMDecorMaximize |
                              kMWMDecorMinimize | kMWMDecorMenu,
               kMWMFuncAll  | kMWMFuncResize    | kMWMFuncMaximize |
                              kMWMFuncMinimize,
               kMWMInputModeless);

   MapWindow();
   fClient->WaitFor(this);
}

//______________________________________________________________________________
void TRootDialog::CloseWindow()
{
   // Called when closed via window manager action.

   // Send Cancel button message to context menu eventhandler
   SendMessage(fMenu, MK_MSG(kC_COMMAND, kCM_BUTTON), 3, 0);
}

//______________________________________________________________________________
void TRootDialog::TabPressed()
{
   // Handle Tab keyboard navigation in this dialog.

   Bool_t setNext = kFALSE;
   TGTextEntry *entry;
   TIter next(fWidgets);

   while ( TObject* obj = next() ) {
      if ( obj->IsA() == TGTextEntry::Class() ) {
         entry = (TGTextEntry*) obj;
         if ( entry == gBlinkingEntry ) {
            setNext = kTRUE;
         } else if ( setNext ) {
            entry->SetFocus();
            entry->End();
            return;
         }
      }
   }

   next.Reset();
   while ( TObject* obj = next() ) {
      if ( obj->IsA() == TGTextEntry::Class() ) {
         entry = (TGTextEntry*) obj;
         entry->SetFocus();
         entry->End();
         return;
      }
   }
}

//______________________________________________________________________________
Bool_t TRootDialog::HandleKey(Event_t* event)
{
   // The key press event handler in this dialog.

   char   tmp[10];
   UInt_t keysym;
   gVirtualX->LookupString(event, tmp, sizeof(tmp), keysym);
   if ((EKeySym)keysym  == kKey_Tab) {

      TGTextEntry *entry;
      TIter next(fWidgets);

      while ( TObject* obj = next() ) {
         if ( obj->IsA() == TGTextEntry::Class() ) {
            entry = (TGTextEntry*) obj;
            entry->TabPressed();
            return kTRUE;
         }
      }
   }

   return TGMainFrame::HandleKey(event);
}
<commit_msg>Fix coverity report #36018 (dereference null return)<commit_after>// @(#)root/gui:$Id$
// Author: Fons Rademakers   20/02/98

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TRootDialog                                                          //
//                                                                      //
// A TRootDialog is used to prompt for the arguments of an object's     //
// member function. A TRootDialog is created via the context menu's     //
// when selecting a member function taking arguments.                   //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "TRootDialog.h"
#include "TRootContextMenu.h"
#include "TContextMenu.h"
#include "TClassMenuItem.h"
#include "TList.h"
#include "TGLabel.h"
#include "TGTextEntry.h"
#include "TGButton.h"
#include "TObjString.h"
#include "KeySymbols.h"

extern TGTextEntry *gBlinkingEntry;

ClassImp(TRootDialog)

//______________________________________________________________________________
TRootDialog::TRootDialog(TRootContextMenu *cmenu, const TGWindow *main,
    const char *title, Bool_t okB, Bool_t cancelB, Bool_t applyB,
    Bool_t helpB) : TGTransientFrame(gClient->GetRoot(), main, 200, 100)
{
   // Create a method argument prompt dialog.

   fMenu   = cmenu;

   fOk     = okB;
   fCancel = cancelB;
   fApply  = applyB;
   fHelp   = helpB;

   fWidgets = new TList;

   fL1 = new TGLayoutHints(kLHintsTop | kLHintsCenterX, 0, 0, 5, 0);
   fL2 = new TGLayoutHints(kLHintsTop | kLHintsLeft, 5, 5, 5, 5);

   SetWindowName(title);
   SetIconName(title);
   SetEditDisabled(kEditDisable);

   AddInput(kKeyPressMask | kEnterWindowMask | kLeaveWindowMask);
}

//______________________________________________________________________________
TRootDialog::~TRootDialog()
{
   // Delete the dialog.

   fWidgets->Delete();
   delete fWidgets;
   delete fL1;
   delete fL2;
}

//______________________________________________________________________________
void TRootDialog::Add(const char *argname, const char *value, const char *type)
{
   // Add a label and text input field.

   TGLabel      *l = new TGLabel(this, argname);
   TGTextBuffer *b = new TGTextBuffer(20); b->AddText(0, value);
   TGTextEntry  *t = new TGTextEntry(this, b);

   t->Connect("TabPressed()", "TRootDialog", this, "TabPressed()");

   t->Associate(fMenu);
   t->Resize(260, t->GetDefaultHeight());
   AddFrame(l, fL1);
   AddFrame(t, fL2);

   fWidgets->Add(l);
   fWidgets->Add(t);   // TGTextBuffer will be deleted by TGTextEntry
   fWidgets->Add(new TObjString(type));
}

//______________________________________________________________________________
const char *TRootDialog::GetParameters()
{
   // Get parameter string (called by contextmenu after OK or Apply has
   // been selected).

   static TString params;
   TString param;

   TObjString   *str;
   TObject      *obj;

   Int_t selfobjpos;
   if (fMenu->GetContextMenu()->GetSelectedMenuItem())
      selfobjpos = fMenu->GetContextMenu()->GetSelectedMenuItem()->GetSelfObjectPos();
   else
      selfobjpos = -1;

   params.Clear();
   TIter next(fWidgets);
   Int_t nparam = 0;

   while ((obj = next())) {        // first element is label, skip...
      if (obj->IsA() != TGLabel::Class()) break;
      obj = next();                // get either TGTextEntry or TGComboBox
      str = (TObjString *) next(); // get type string

      nparam++;

      const char *type = str ? str->GetString().Data() : 0;
      const char *data = 0;

      if (obj && obj->IsA() == TGTextEntry::Class())
         data = ((TGTextEntry *) obj)->GetBuffer()->GetString();

      // TODO: Combobox...

      // if necessary, replace the selected object by it's address
      if (selfobjpos == nparam-1) {
         if (params.Length()) params += ",";
         param = TString::Format("(TObject*)0x%lx",
               (Long_t)fMenu->GetContextMenu()->GetSelectedObject());
         params += param;
      }

      if (params.Length()) params += ",";
      if (type && data) {
         if (!strncmp(type, "char*", 5))
            param = TString::Format("\"%s\"", data);
         else
            param = data;
      } else
         param = "0";

      params += param;
   }

   // if selected object is the last argument, have to insert it here
   if (selfobjpos == nparam) {
      if (params.Length()) params += ",";
      param = TString::Format("(TObject*)0x%lx",
            (Long_t)fMenu->GetContextMenu()->GetSelectedObject());
      params += param;
   }

   return params.Data();
}

//______________________________________________________________________________
void TRootDialog::Popup()
{
   // Popup dialog.

   //--- create the OK, Apply and Cancel buttons

   UInt_t  nb = 0, width = 0, height = 0;

   TGHorizontalFrame *hf = new TGHorizontalFrame(this, 60, 20, kFixedWidth);
   TGLayoutHints     *l1 = new TGLayoutHints(kLHintsCenterY | kLHintsExpandX, 5, 5, 0, 0);

   // put hf as last in the list to be deleted
   fWidgets->Add(l1);

   TGTextButton *b;
   if (fOk) {
      b = new TGTextButton(hf, "&OK", 1);
      fWidgets->Add(b);
      b->Associate(fMenu);
      hf->AddFrame(b, l1);
      height = b->GetDefaultHeight();
      width  = TMath::Max(width, b->GetDefaultWidth()); ++nb;
   }
   if (fApply) {
      b = new TGTextButton(hf, "&Apply", 2);
      fWidgets->Add(b);
      b->Associate(fMenu);
      hf->AddFrame(b, l1);
      height = b->GetDefaultHeight();
      width  = TMath::Max(width, b->GetDefaultWidth()); ++nb;
   }
   if (fCancel) {
      b = new TGTextButton(hf, "&Cancel", 3);
      fWidgets->Add(b);
      b->Associate(fMenu);
      hf->AddFrame(b, l1);
      height = b->GetDefaultHeight();
      width  = TMath::Max(width, b->GetDefaultWidth()); ++nb;
   }
   if (fHelp) {
      b = new TGTextButton(hf, "Online &Help", 4);
      fWidgets->Add(b);
      b->Associate(fMenu);
      hf->AddFrame(b, l1);
      height = b->GetDefaultHeight();
      width  = TMath::Max(width, b->GetDefaultWidth()); ++nb;
   }

   // place buttons at the bottom
   l1 = new TGLayoutHints(kLHintsBottom | kLHintsCenterX, 0, 0, 5, 5);
   fWidgets->Add(l1);
   fWidgets->Add(hf);

   AddFrame(hf, l1);

   // keep the buttons centered and with the same width
   hf->Resize((width + 20) * nb, height);

   // map all widgets and calculate size of dialog
   MapSubwindows();

   width  = GetDefaultWidth();
   height = GetDefaultHeight();

   Resize(width, height);

   // position relative to the parent's window
   CenterOnParent();

   // make the message box non-resizable
   SetWMSize(width, height);
   SetWMSizeHints(width, height, width, height, 0, 0);

   SetMWMHints(kMWMDecorAll | kMWMDecorResizeH  | kMWMDecorMaximize |
                              kMWMDecorMinimize | kMWMDecorMenu,
               kMWMFuncAll  | kMWMFuncResize    | kMWMFuncMaximize |
                              kMWMFuncMinimize,
               kMWMInputModeless);

   MapWindow();
   fClient->WaitFor(this);
}

//______________________________________________________________________________
void TRootDialog::CloseWindow()
{
   // Called when closed via window manager action.

   // Send Cancel button message to context menu eventhandler
   SendMessage(fMenu, MK_MSG(kC_COMMAND, kCM_BUTTON), 3, 0);
}

//______________________________________________________________________________
void TRootDialog::TabPressed()
{
   // Handle Tab keyboard navigation in this dialog.

   Bool_t setNext = kFALSE;
   TGTextEntry *entry;
   TIter next(fWidgets);

   while ( TObject* obj = next() ) {
      if ( obj->IsA() == TGTextEntry::Class() ) {
         entry = (TGTextEntry*) obj;
         if ( entry == gBlinkingEntry ) {
            setNext = kTRUE;
         } else if ( setNext ) {
            entry->SetFocus();
            entry->End();
            return;
         }
      }
   }

   next.Reset();
   while ( TObject* obj = next() ) {
      if ( obj->IsA() == TGTextEntry::Class() ) {
         entry = (TGTextEntry*) obj;
         entry->SetFocus();
         entry->End();
         return;
      }
   }
}

//______________________________________________________________________________
Bool_t TRootDialog::HandleKey(Event_t* event)
{
   // The key press event handler in this dialog.

   char   tmp[10];
   UInt_t keysym;
   gVirtualX->LookupString(event, tmp, sizeof(tmp), keysym);
   if ((EKeySym)keysym  == kKey_Tab) {

      TGTextEntry *entry;
      TIter next(fWidgets);

      while ( TObject* obj = next() ) {
         if ( obj->IsA() == TGTextEntry::Class() ) {
            entry = (TGTextEntry*) obj;
            entry->TabPressed();
            return kTRUE;
         }
      }
   }

   return TGMainFrame::HandleKey(event);
}
<|endoftext|>


<commit_before>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.

#include "catch.hpp"
#include "mfem.hpp"
#include <fstream>
#include <iostream>
#include "../../../fem/libceed/ceed.hpp"

using namespace mfem;

namespace ceed_test
{

#ifdef MFEM_USE_CEED

double coeff_function(const Vector &x)
{
   return 1.0 + x[0]*x[0];
}

// Velocity coefficient
void velocity_function(const Vector &x, Vector &v)
{
   int dim = x.Size();
   switch (dim)
   {
      case 1: v(0) = 1.0; break;
      case 2: v(0) = 1.0; v(1) = 1.0; break;
      case 3: v(0) = 1.0; v(1) = 1.0; v(2) = 1.0; break;
   }
}

static std::string getString(AssemblyLevel assembly)
{
   switch (assembly)
   {
   case AssemblyLevel::NONE:
      return "NONE";
      break;
   case AssemblyLevel::PARTIAL:
      return "PARTIAL";
      break;
   case AssemblyLevel::ELEMENT:
      return "ELEMENT";
      break;
   case AssemblyLevel::FULL:
      return "FULL";
      break;
   case AssemblyLevel::LEGACYFULL:
      return "LEGACYFULL";
      break;
   }
   mfem_error("Unknown AssemblyLevel.");
   return "";
}

static std::string getString(CeedCoeff coeff_type)
{
   switch (coeff_type)
   {
   case CeedCoeff::Const:
      return "Const";
      break;
   case CeedCoeff::Grid:
      return "Grid";
      break;
   case CeedCoeff::Quad:
      return "Quad";
      break;
   case CeedCoeff::VecConst:
      return "VecConst";
      break;
   case CeedCoeff::VecGrid:
      return "VecGrid";
      break;
   case CeedCoeff::VecQuad:
      return "VecQuad";
      break;
   }
   mfem_error("Unknown CeedCoeff.");
   return "";
}

enum class Problem {Mass, Convection, Diffusion, VectorMass, VectorDiffusion};

static std::string getString(Problem pb)
{
   switch (pb)
   {
   case Problem::Mass:
      return "Mass";
      break;
   case Problem::Convection:
      return "Convection";
      break;
   case Problem::Diffusion:
      return "Diffusion";
      break;
   case Problem::VectorMass:
      return "VectorMass";
      break;
   case Problem::VectorDiffusion:
      return "VectorDiffusion";
      break;
   }
   mfem_error("Unknown Problem.");
   return "";
}

enum class NLProblem {Convection};

static std::string getString(NLProblem pb)
{
   switch (pb)
   {
   case NLProblem::Convection:
      return "Convection";
      break;
   }
   mfem_error("Unknown Problem.");
   return "";
}

static void InitCoeff(Mesh &mesh, FiniteElementCollection &fec, const int dim,
                      const CeedCoeff coeff_type, GridFunction *&gf,
                      FiniteElementSpace *& coeff_fes,
                      Coefficient *&coeff, VectorCoefficient *&vcoeff)
{
   switch (coeff_type)
   {
      case CeedCoeff::Const:
         coeff = new ConstantCoefficient(1.0);
         break;
      case CeedCoeff::Grid:
      {
         FunctionCoefficient f_coeff(coeff_function);
         coeff_fes = new FiniteElementSpace(&mesh, &fec);
         gf = new GridFunction(coeff_fes);
         gf->ProjectCoefficient(f_coeff);
         coeff = new GridFunctionCoefficient(gf);
         break;
      }
      case CeedCoeff::Quad:
         coeff = new FunctionCoefficient(coeff_function);
         break;
      case CeedCoeff::VecConst:
      {
         Vector val(dim);
         for (int i = 0; i < dim; i++)
         {
            val(i) = 1.0;
         }
         vcoeff = new VectorConstantCoefficient(val);
         break;
      }
      case CeedCoeff::VecGrid:
      {
         VectorFunctionCoefficient f_vcoeff(dim, velocity_function);
         coeff_fes = new FiniteElementSpace(&mesh, &fec, dim);
         gf = new GridFunction(coeff_fes);
         gf->ProjectCoefficient(f_vcoeff);
         vcoeff = new VectorGridFunctionCoefficient(gf);
         break;
      }
      case CeedCoeff::VecQuad:
         vcoeff = new VectorFunctionCoefficient(dim, velocity_function);
         break;
   }
}

void test_ceed_operator(const char* input, int order, const CeedCoeff coeff_type,
                        const Problem pb, const AssemblyLevel assembly)
{
   std::string section = "assembly: " + getString(assembly) + "\n" +
                         "coeff_type: " + getString(coeff_type) + "\n" +
                         "pb: " + getString(pb) + "\n" +
                         "order: " + std::to_string(order) + "\n" +
                         "mesh: " + input;
   INFO(section);
   Mesh mesh(input, 1, 1);
   mesh.EnsureNodes();
   int dim = mesh.Dimension();
   H1_FECollection fec(order, dim);

   // Coefficient Initialization
   GridFunction *gf = nullptr;
   FiniteElementSpace *coeff_fes = nullptr;
   Coefficient *coeff = nullptr;
   VectorCoefficient *vcoeff = nullptr;
   InitCoeff(mesh, fec, dim, coeff_type, gf, coeff_fes, coeff, vcoeff);

   // Build the BilinearForm
   bool vecOp = pb == Problem::VectorMass || pb == Problem::VectorDiffusion;
   const int vdim = vecOp ? dim : 1;
   FiniteElementSpace fes(&mesh, &fec, vdim);

   BilinearForm k_test(&fes);
   BilinearForm k_ref(&fes);
   switch (pb)
   {
   case Problem::Mass:
      k_ref.AddDomainIntegrator(new MassIntegrator(*coeff));
      k_test.AddDomainIntegrator(new MassIntegrator(*coeff));
      break;
   case Problem::Convection:
      k_ref.AddDomainIntegrator(new ConvectionIntegrator(*vcoeff));
      k_test.AddDomainIntegrator(new ConvectionIntegrator(*vcoeff));
      break;
   case Problem::Diffusion:
      k_ref.AddDomainIntegrator(new DiffusionIntegrator(*coeff));
      k_test.AddDomainIntegrator(new DiffusionIntegrator(*coeff));
      break;
   case Problem::VectorMass:
      k_ref.AddDomainIntegrator(new VectorMassIntegrator(*coeff));
      k_test.AddDomainIntegrator(new VectorMassIntegrator(*coeff));
      break;
   case Problem::VectorDiffusion:
      k_ref.AddDomainIntegrator(new VectorDiffusionIntegrator(*coeff));
      k_test.AddDomainIntegrator(new VectorDiffusionIntegrator(*coeff));
      break;
   }

   k_ref.Assemble();
   k_ref.Finalize();

   k_test.SetAssemblyLevel(assembly);
   k_test.Assemble();

   // Compare ceed with mfem.
   GridFunction x(&fes), y_ref(&fes), y_test(&fes);

   x.Randomize(1);

   k_ref.Mult(x,y_ref);
   k_test.Mult(x,y_test);

   y_test -= y_ref;

   REQUIRE(y_test.Norml2() < 1.e-12);
   delete gf;
   delete coeff_fes;
   delete coeff;
   delete vcoeff;
}

void test_ceed_nloperator(const char* input, int order, const CeedCoeff coeff_type,
                          const NLProblem pb, const AssemblyLevel assembly)
{
   std::string section = "assembly: " + getString(assembly) + "\n" +
                         "coeff_type: " + getString(coeff_type) + "\n" +
                         "pb: " + getString(pb) + "\n" +
                         "order: " + std::to_string(order) + "\n" +
                         "mesh: " + input;
   INFO(section);
   Mesh mesh(input, 1, 1);
   mesh.EnsureNodes();
   int dim = mesh.Dimension();
   H1_FECollection fec(order, dim);

   // Coefficient Initialization
   GridFunction *gf = nullptr;
   FiniteElementSpace *coeff_fes = nullptr;
   Coefficient *coeff = nullptr;
   VectorCoefficient *vcoeff = nullptr;
   InitCoeff(mesh, fec, dim, coeff_type, gf, coeff_fes, coeff, vcoeff);

   // Build the NonlinearForm
   bool vecOp = pb == NLProblem::Convection;
   const int vdim = vecOp ? dim : 1;
   FiniteElementSpace fes(&mesh, &fec, vdim);

   NonlinearForm k_test(&fes);
   NonlinearForm k_ref(&fes);
   switch (pb)
   {
   case NLProblem::Convection:
      k_ref.AddDomainIntegrator(new VectorConvectionNLFIntegrator(*coeff));
      k_test.AddDomainIntegrator(new VectorConvectionNLFIntegrator(*coeff));
      break;
   }

   k_test.SetAssemblyLevel(assembly);
   k_test.Setup();
   k_ref.Setup();

   // Compare ceed with mfem.
   GridFunction x(&fes), y_ref(&fes), y_test(&fes);

   x.Randomize(1);

   k_ref.Mult(x,y_ref);
   k_test.Mult(x,y_test);

   y_test -= y_ref;

   REQUIRE(y_test.Norml2() < 1.e-12);
   delete gf;
   delete coeff_fes;
   delete coeff;
   delete vcoeff;
}

TEST_CASE("CEED mass & diffusion", "[CEED]")
{
   auto assembly = GENERATE(AssemblyLevel::PARTIAL,AssemblyLevel::NONE);
   auto coeff_type = GENERATE(CeedCoeff::Const,CeedCoeff::Grid,CeedCoeff::Quad);
   auto pb = GENERATE(Problem::Mass,Problem::Diffusion,
                      Problem::VectorMass,Problem::VectorDiffusion);
   auto order = GENERATE(1,2,3);
   auto mesh = GENERATE("../../data/inline-quad.mesh","../../data/inline-hex.mesh",
                        "../../data/periodic-square.mesh",
                        "../../data/star-q2.mesh","../../data/fichera-q2.mesh",
                        "../../data/amr-quad.mesh","../../data/fichera-amr.mesh");
   test_ceed_operator(mesh, order, coeff_type, pb, assembly);
} // test case

TEST_CASE("CEED convection", "[CEED],[Convection]")
{
   auto assembly = GENERATE(AssemblyLevel::PARTIAL,AssemblyLevel::NONE);
   auto coeff_type = GENERATE(CeedCoeff::VecConst,CeedCoeff::VecGrid,
                              CeedCoeff::VecQuad);
   auto pb = GENERATE(Problem::Convection);
   auto order = GENERATE(1,2,3);
   auto mesh = GENERATE("../../data/inline-quad.mesh","../../data/inline-hex.mesh",
                        "../../data/star-q2.mesh","../../data/fichera-q2.mesh",
                        "../../data/amr-quad.mesh","../../data/fichera-amr.mesh");
   test_ceed_operator(mesh, order, coeff_type, pb, assembly);
} // test case

TEST_CASE("CEED non-linear convection", "[CEED],[NLConvection]")
{
   auto assembly = GENERATE(AssemblyLevel::PARTIAL,AssemblyLevel::NONE);
   auto coeff_type = GENERATE(CeedCoeff::Const,CeedCoeff::Grid,CeedCoeff::Quad);
   auto pb = GENERATE(NLProblem::Convection);
   auto order = GENERATE(1,2,3);
   auto mesh = GENERATE("../../data/inline-quad.mesh",
                        "../../data/inline-hex.mesh",
                        "../../data/periodic-square.mesh",
                        "../../data/star-q2.mesh",
                        "../../data/fichera.mesh");
   test_ceed_nloperator(mesh, order, coeff_type, pb, assembly);
} // test case

#endif

} // namespace ceed_test
<commit_msg>Change velocity coefficient in tests.<commit_after>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.

#include "catch.hpp"
#include "mfem.hpp"
#include <fstream>
#include <iostream>
#include "../../../fem/libceed/ceed.hpp"

using namespace mfem;

namespace ceed_test
{

#ifdef MFEM_USE_CEED

double coeff_function(const Vector &x)
{
   return 1.0 + x[0]*x[0];
}

// Velocity coefficient
void velocity_function(const Vector &x, Vector &v)
{
   int dim = x.Size();
   switch (dim)
   {
      case 1: v(0) = 1.0; break;
      case 2: v(0) = sqrt(2./3.); v(1) = sqrt(1./3.); break;
      case 3: v(0) = sqrt(3./6.); v(1) = sqrt(2./6.); v(2) = sqrt(1./6.); break;
   }
}

static std::string getString(AssemblyLevel assembly)
{
   switch (assembly)
   {
   case AssemblyLevel::NONE:
      return "NONE";
      break;
   case AssemblyLevel::PARTIAL:
      return "PARTIAL";
      break;
   case AssemblyLevel::ELEMENT:
      return "ELEMENT";
      break;
   case AssemblyLevel::FULL:
      return "FULL";
      break;
   case AssemblyLevel::LEGACYFULL:
      return "LEGACYFULL";
      break;
   }
   mfem_error("Unknown AssemblyLevel.");
   return "";
}

static std::string getString(CeedCoeff coeff_type)
{
   switch (coeff_type)
   {
   case CeedCoeff::Const:
      return "Const";
      break;
   case CeedCoeff::Grid:
      return "Grid";
      break;
   case CeedCoeff::Quad:
      return "Quad";
      break;
   case CeedCoeff::VecConst:
      return "VecConst";
      break;
   case CeedCoeff::VecGrid:
      return "VecGrid";
      break;
   case CeedCoeff::VecQuad:
      return "VecQuad";
      break;
   }
   mfem_error("Unknown CeedCoeff.");
   return "";
}

enum class Problem {Mass, Convection, Diffusion, VectorMass, VectorDiffusion};

static std::string getString(Problem pb)
{
   switch (pb)
   {
   case Problem::Mass:
      return "Mass";
      break;
   case Problem::Convection:
      return "Convection";
      break;
   case Problem::Diffusion:
      return "Diffusion";
      break;
   case Problem::VectorMass:
      return "VectorMass";
      break;
   case Problem::VectorDiffusion:
      return "VectorDiffusion";
      break;
   }
   mfem_error("Unknown Problem.");
   return "";
}

enum class NLProblem {Convection};

static std::string getString(NLProblem pb)
{
   switch (pb)
   {
   case NLProblem::Convection:
      return "Convection";
      break;
   }
   mfem_error("Unknown Problem.");
   return "";
}

static void InitCoeff(Mesh &mesh, FiniteElementCollection &fec, const int dim,
                      const CeedCoeff coeff_type, GridFunction *&gf,
                      FiniteElementSpace *& coeff_fes,
                      Coefficient *&coeff, VectorCoefficient *&vcoeff)
{
   switch (coeff_type)
   {
      case CeedCoeff::Const:
         coeff = new ConstantCoefficient(1.0);
         break;
      case CeedCoeff::Grid:
      {
         FunctionCoefficient f_coeff(coeff_function);
         coeff_fes = new FiniteElementSpace(&mesh, &fec);
         gf = new GridFunction(coeff_fes);
         gf->ProjectCoefficient(f_coeff);
         coeff = new GridFunctionCoefficient(gf);
         break;
      }
      case CeedCoeff::Quad:
         coeff = new FunctionCoefficient(coeff_function);
         break;
      case CeedCoeff::VecConst:
      {
         Vector val(dim);
         for (int i = 0; i < dim; i++)
         {
            val(i) = 1.0;
         }
         vcoeff = new VectorConstantCoefficient(val);
         break;
      }
      case CeedCoeff::VecGrid:
      {
         VectorFunctionCoefficient f_vcoeff(dim, velocity_function);
         coeff_fes = new FiniteElementSpace(&mesh, &fec, dim);
         gf = new GridFunction(coeff_fes);
         gf->ProjectCoefficient(f_vcoeff);
         vcoeff = new VectorGridFunctionCoefficient(gf);
         break;
      }
      case CeedCoeff::VecQuad:
         vcoeff = new VectorFunctionCoefficient(dim, velocity_function);
         break;
   }
}

void test_ceed_operator(const char* input, int order, const CeedCoeff coeff_type,
                        const Problem pb, const AssemblyLevel assembly)
{
   std::string section = "assembly: " + getString(assembly) + "\n" +
                         "coeff_type: " + getString(coeff_type) + "\n" +
                         "pb: " + getString(pb) + "\n" +
                         "order: " + std::to_string(order) + "\n" +
                         "mesh: " + input;
   INFO(section);
   Mesh mesh(input, 1, 1);
   mesh.EnsureNodes();
   int dim = mesh.Dimension();
   H1_FECollection fec(order, dim);

   // Coefficient Initialization
   GridFunction *gf = nullptr;
   FiniteElementSpace *coeff_fes = nullptr;
   Coefficient *coeff = nullptr;
   VectorCoefficient *vcoeff = nullptr;
   InitCoeff(mesh, fec, dim, coeff_type, gf, coeff_fes, coeff, vcoeff);

   // Build the BilinearForm
   bool vecOp = pb == Problem::VectorMass || pb == Problem::VectorDiffusion;
   const int vdim = vecOp ? dim : 1;
   FiniteElementSpace fes(&mesh, &fec, vdim);

   BilinearForm k_test(&fes);
   BilinearForm k_ref(&fes);
   switch (pb)
   {
   case Problem::Mass:
      k_ref.AddDomainIntegrator(new MassIntegrator(*coeff));
      k_test.AddDomainIntegrator(new MassIntegrator(*coeff));
      break;
   case Problem::Convection:
      k_ref.AddDomainIntegrator(new ConvectionIntegrator(*vcoeff));
      k_test.AddDomainIntegrator(new ConvectionIntegrator(*vcoeff));
      break;
   case Problem::Diffusion:
      k_ref.AddDomainIntegrator(new DiffusionIntegrator(*coeff));
      k_test.AddDomainIntegrator(new DiffusionIntegrator(*coeff));
      break;
   case Problem::VectorMass:
      k_ref.AddDomainIntegrator(new VectorMassIntegrator(*coeff));
      k_test.AddDomainIntegrator(new VectorMassIntegrator(*coeff));
      break;
   case Problem::VectorDiffusion:
      k_ref.AddDomainIntegrator(new VectorDiffusionIntegrator(*coeff));
      k_test.AddDomainIntegrator(new VectorDiffusionIntegrator(*coeff));
      break;
   }

   k_ref.Assemble();
   k_ref.Finalize();

   k_test.SetAssemblyLevel(assembly);
   k_test.Assemble();

   // Compare ceed with mfem.
   GridFunction x(&fes), y_ref(&fes), y_test(&fes);

   x.Randomize(1);

   k_ref.Mult(x,y_ref);
   k_test.Mult(x,y_test);

   y_test -= y_ref;

   REQUIRE(y_test.Norml2() < 1.e-12);
   delete gf;
   delete coeff_fes;
   delete coeff;
   delete vcoeff;
}

void test_ceed_nloperator(const char* input, int order, const CeedCoeff coeff_type,
                          const NLProblem pb, const AssemblyLevel assembly)
{
   std::string section = "assembly: " + getString(assembly) + "\n" +
                         "coeff_type: " + getString(coeff_type) + "\n" +
                         "pb: " + getString(pb) + "\n" +
                         "order: " + std::to_string(order) + "\n" +
                         "mesh: " + input;
   INFO(section);
   Mesh mesh(input, 1, 1);
   mesh.EnsureNodes();
   int dim = mesh.Dimension();
   H1_FECollection fec(order, dim);

   // Coefficient Initialization
   GridFunction *gf = nullptr;
   FiniteElementSpace *coeff_fes = nullptr;
   Coefficient *coeff = nullptr;
   VectorCoefficient *vcoeff = nullptr;
   InitCoeff(mesh, fec, dim, coeff_type, gf, coeff_fes, coeff, vcoeff);

   // Build the NonlinearForm
   bool vecOp = pb == NLProblem::Convection;
   const int vdim = vecOp ? dim : 1;
   FiniteElementSpace fes(&mesh, &fec, vdim);

   NonlinearForm k_test(&fes);
   NonlinearForm k_ref(&fes);
   switch (pb)
   {
   case NLProblem::Convection:
      k_ref.AddDomainIntegrator(new VectorConvectionNLFIntegrator(*coeff));
      k_test.AddDomainIntegrator(new VectorConvectionNLFIntegrator(*coeff));
      break;
   }

   k_test.SetAssemblyLevel(assembly);
   k_test.Setup();
   k_ref.Setup();

   // Compare ceed with mfem.
   GridFunction x(&fes), y_ref(&fes), y_test(&fes);

   x.Randomize(1);

   k_ref.Mult(x,y_ref);
   k_test.Mult(x,y_test);

   y_test -= y_ref;

   REQUIRE(y_test.Norml2() < 1.e-12);
   delete gf;
   delete coeff_fes;
   delete coeff;
   delete vcoeff;
}

TEST_CASE("CEED mass & diffusion", "[CEED]")
{
   auto assembly = GENERATE(AssemblyLevel::PARTIAL,AssemblyLevel::NONE);
   auto coeff_type = GENERATE(CeedCoeff::Const,CeedCoeff::Grid,CeedCoeff::Quad);
   auto pb = GENERATE(Problem::Mass,Problem::Diffusion,
                      Problem::VectorMass,Problem::VectorDiffusion);
   auto order = GENERATE(1,2,3);
   auto mesh = GENERATE("../../data/inline-quad.mesh","../../data/inline-hex.mesh",
                        "../../data/periodic-square.mesh",
                        "../../data/star-q2.mesh","../../data/fichera-q2.mesh",
                        "../../data/amr-quad.mesh","../../data/fichera-amr.mesh");
   test_ceed_operator(mesh, order, coeff_type, pb, assembly);
} // test case

TEST_CASE("CEED convection", "[CEED],[Convection]")
{
   auto assembly = GENERATE(AssemblyLevel::PARTIAL,AssemblyLevel::NONE);
   auto coeff_type = GENERATE(CeedCoeff::VecConst,CeedCoeff::VecGrid,
                              CeedCoeff::VecQuad);
   auto pb = GENERATE(Problem::Convection);
   auto order = GENERATE(1,2,3);
   auto mesh = GENERATE("../../data/inline-quad.mesh","../../data/inline-hex.mesh",
                        "../../data/star-q2.mesh","../../data/fichera-q2.mesh",
                        "../../data/amr-quad.mesh","../../data/fichera-amr.mesh");
   test_ceed_operator(mesh, order, coeff_type, pb, assembly);
} // test case

TEST_CASE("CEED non-linear convection", "[CEED],[NLConvection]")
{
   auto assembly = GENERATE(AssemblyLevel::PARTIAL,AssemblyLevel::NONE);
   auto coeff_type = GENERATE(CeedCoeff::Const,CeedCoeff::Grid,CeedCoeff::Quad);
   auto pb = GENERATE(NLProblem::Convection);
   auto order = GENERATE(1,2,3);
   auto mesh = GENERATE("../../data/inline-quad.mesh",
                        "../../data/inline-hex.mesh",
                        "../../data/periodic-square.mesh",
                        "../../data/star-q2.mesh",
                        "../../data/fichera.mesh");
   test_ceed_nloperator(mesh, order, coeff_type, pb, assembly);
} // test case

#endif

} // namespace ceed_test
<|endoftext|>


<commit_before>#include "Nearest.h"

using namespace std;

namespace nearest {

    // to print Point to cout
    std::ostream& operator<<(std::ostream &o, const nearest::Point& p) {
        o << "(" << p.x << ", " << p.y << ", " << p.z << ")" << std::endl;
        return o;
    }

    // defines sorting order for points
    struct ByDistance {
        const Point& origin;

        bool operator()(const Point& lp, const Point& rp) {
            return dist(origin, lp) < dist(origin, rp);
        }

        static double dist(const Point& lp, const Point& rp){
            double xs = (lp.x - rp.x) * (lp.x - rp.x);
            double ys = (lp.y - rp.y) * (lp.y - rp.y);
            double zs = (lp.z - rp.z) * (lp.z - rp.z);
            return sqrt(xs + ys + zs);
        }
    };

    vector<Point> nearestN(const vector<Point>& points, int N) {
        if (points.size() == 0) {
            vector<Point> empty;
            return empty;
        }
        return nearestN(points, N, points[0], INFINITY);
    }

    vector<Point> nearestN(const vector<Point>& points,
                           int N,
                           const Point& reference,
                           double distanceThreshold) {

        vector<Point> temp;
        temp.insert(temp.begin(), points.begin(), points.end());

        // filtering vector to remove all points far then distance from reference
        temp.erase(remove_if(temp.begin(),
                             temp.end(),
                             [&reference, distanceThreshold](Point& p){ return ByDistance::dist(p, reference) > distanceThreshold; }),
                   temp.end());

        ByDistance distance = {reference};
        sort(temp.begin(), temp.end(), distance);

        auto sz = min(static_cast<int>(temp.size()), N);
        vector<Point> result(sz);
        copy_n(temp.begin(), sz, result.begin());
        return result;
    }
}
<commit_msg>Resizing vector to reuse<commit_after>#include "Nearest.h"

using namespace std;

namespace nearest {

    // to print Point to cout
    std::ostream& operator<<(std::ostream &o, const nearest::Point& p) {
        o << "(" << p.x << ", " << p.y << ", " << p.z << ")" << std::endl;
        return o;
    }

    // defines sorting order for points
    struct ByDistance {
        const Point& origin;

        bool operator()(const Point& lp, const Point& rp) {
            return dist(origin, lp) < dist(origin, rp);
        }

        static double dist(const Point& lp, const Point& rp){
            double xs = (lp.x - rp.x) * (lp.x - rp.x);
            double ys = (lp.y - rp.y) * (lp.y - rp.y);
            double zs = (lp.z - rp.z) * (lp.z - rp.z);
            return sqrt(xs + ys + zs);
        }
    };

    vector<Point> nearestN(const vector<Point>& points, int N) {
        if (points.size() == 0) {
            vector<Point> empty;
            return empty;
        }
        return nearestN(points, N, points[0], INFINITY);
    }

    vector<Point> nearestN(const vector<Point>& points,
                           int N,
                           const Point& reference,
                           double distanceThreshold) {

        vector<Point> temp;
        temp.insert(temp.begin(), points.begin(), points.end());

        // filtering vector to remove all points far then distance from reference
        temp.erase(remove_if(temp.begin(),
                             temp.end(),
                             [&reference, distanceThreshold](Point& p){ return ByDistance::dist(p, reference) > distanceThreshold; }),
                   temp.end());

        ByDistance distance = {reference};
        sort(temp.begin(), temp.end(), distance);

        auto sz = min(static_cast<int>(temp.size()), N);
        temp.resize(sz);
        return temp;
    }
}
<|endoftext|>


<commit_before>#include "vec3.h"

namespace fd {
namespace core {
namespace math {

vec3::vec3() : x(0), y(0), z(0) {}

vec3::vec3(float32 x, float32 y, float32 z) : x(x), y(y), z(z) {}

#pragma region vec-vec
//Asss
//float32
vec3& vec3::Add(const vec3& v) {
	__m128 vxmm = _mm_set_ps(0, v.z, v.y, v.x);
	__m128 xmm = _mm_set_ps(0, z, y, x);
	xmm = _mm_add_ps(xmm, vxmm);

	x = xmm.m128_f32[0];
	y = xmm.m128_f32[1];
	z = xmm.m128_f32[2];

	return *this;
}

//sub
//float32
vec3& vec3::Sub(const vec3& v) {
	__m128 vxmm = _mm_set_ps(0, v.z, v.y, v.x);
	__m128 xmm = _mm_set_ps(0, z, y, x);
	xmm = _mm_sub_ps(xmm, vxmm);

	x = xmm.m128_f32[0];
	y = xmm.m128_f32[1];
	z = xmm.m128_f32[2];

	return *this;
}

//Mul
//float32
vec3& vec3::Mul(const vec3& v) {
	__m128 vxmm = _mm_set_ps(0, v.z, v.y, v.x);
	__m128 xmm = _mm_set_ps(0, z, y, x);
	xmm = _mm_mul_ps(xmm, vxmm);

	x = xmm.m128_f32[0];
	y = xmm.m128_f32[1];
	z = xmm.m128_f32[2];

	return *this;
}

//Div
//float32
vec3& vec3::Div(const vec3& v) {
	__m128 vxmm = _mm_set_ps(0, v.z, v.y, v.x);
	__m128 xmm = _mm_set_ps(0, z, y, x);
	xmm = _mm_div_ps(xmm, vxmm);

	x = xmm.m128_f32[0];
	y = xmm.m128_f32[1];
	z = xmm.m128_f32[2];

	return *this;
}

#pragma endregion

#pragma region vec-shit

//Add
//float32
vec3& vec3::Add(float32 v) {
	__m128 vxmm = _mm_set_ps(0, v, v, v);
	__m128 xmm = _mm_set_ps(0, z, y, x);
	xmm = _mm_add_ps(xmm, vxmm);

	x = xmm.m128_f32[0];
	y = xmm.m128_f32[1];
	z = xmm.m128_f32[2];

	return *this;
}

//Sub
//float32
vec3& vec3::Sub(float32 v) {
	__m128 vxmm = _mm_set_ps(0, v, v, v);
	__m128 xmm = _mm_set_ps(0, z, y, x);
	xmm = _mm_sub_ps(xmm, vxmm);

	x = xmm.m128_f32[0];
	y = xmm.m128_f32[1];
	z = xmm.m128_f32[2];

	return *this;
}

//Mul
//float32
vec3& vec3::Mul(float32 v) {
	__m128 vxmm = _mm_set_ps(0, v, v, v);
	__m128 xmm = _mm_set_ps(0, z, y, x);
	xmm = _mm_mul_ps(xmm, vxmm);

	x = xmm.m128_f32[0];
	y = xmm.m128_f32[1];
	z = xmm.m128_f32[2];

	return *this;
}

//Div
//float32
vec3& vec3::Div(float32 v) {
	__m128 vxmm = _mm_set_ps(0, v, v, v);
	__m128 xmm = _mm_set_ps(0, z, y, x);
	xmm = _mm_div_ps(xmm, vxmm);

	x = xmm.m128_f32[0];
	y = xmm.m128_f32[1];
	z = xmm.m128_f32[2];

	return *this;
}

float32 vec3::Length() const {
	return sqrtf(x * x + y * y + z * z);
}

vec3& vec3::Normalize() {
	return Mul(1.0f / Length());
}

vec3 vec3::Cross(const vec3& v) const {
	__m128 xmm0 = _mm_set_ps(0, x, z, y);
	__m128 vxmm0 = _mm_set_ps(0, v.y, v.x, v.z);

	__m128 xmm1 = _mm_set_ps(0, y, x, z);
	__m128 vxmm1 = _mm_set_ps(0, v.x, v.z, v.y);

	xmm0 = _mm_mul_ps(xmm0, vxmm0);
	xmm1 = _mm_mul_ps(xmm1, vxmm1);

	xmm0 = _mm_sub_ps(xmm0, xmm1);

	return vec3(xmm0.m128_f32[0], xmm0.m128_f32[1], xmm0.m128_f32[2]);
}

float32 vec3::Dot(const vec3& v) const {
	__m128 xmm = _mm_set_ps(0, v.z, v.y, v.x);
	xmm = _mm_mul_ps(xmm, _mm_set_ps(0, y, z, x));
	return xmm.m128_f32[0] + xmm.m128_f32[1] + xmm.m128_f32[2];
}

#pragma endregion

}
}
}<commit_msg>LNX: vec3<commit_after>#include "vec3.h"

namespace fd {
namespace core {
namespace math {

vec3::vec3() : x(0), y(0), z(0) {}

vec3::vec3(float32 x, float32 y, float32 z) : x(x), y(y), z(z) {}

#pragma region vec-vec
//Asss
//float32
vec3& vec3::Add(const vec3& v) {
	__m128 vxmm = _mm_set_ps(0, v.z, v.y, v.x);
	__m128 xmm = _mm_set_ps(0, z, y, x);
	xmm = _mm_add_ps(xmm, vxmm);

	x = M128(xmm, 0);
	y = M128(xmm, 1);
	z = M128(xmm, 2);

	return *this;
}

//sub
//float32
vec3& vec3::Sub(const vec3& v) {
	__m128 vxmm = _mm_set_ps(0, v.z, v.y, v.x);
	__m128 xmm = _mm_set_ps(0, z, y, x);
	xmm = _mm_sub_ps(xmm, vxmm);

	x = M128(xmm, 0);
	y = M128(xmm, 1);
	z = M128(xmm, 2);

	return *this;
}

//Mul
//float32
vec3& vec3::Mul(const vec3& v) {
	__m128 vxmm = _mm_set_ps(0, v.z, v.y, v.x);
	__m128 xmm = _mm_set_ps(0, z, y, x);
	xmm = _mm_mul_ps(xmm, vxmm);

	x = M128(xmm, 0);
	y = M128(xmm, 1);
	z = M128(xmm, 2);

	return *this;
}

//Div
//float32
vec3& vec3::Div(const vec3& v) {
	__m128 vxmm = _mm_set_ps(0, v.z, v.y, v.x);
	__m128 xmm = _mm_set_ps(0, z, y, x);
	xmm = _mm_div_ps(xmm, vxmm);

	x = M128(xmm, 0);
	y = M128(xmm, 1);
	z = M128(xmm, 2);

	return *this;
}

#pragma endregion

#pragma region vec-shit

//Add
//float32
vec3& vec3::Add(float32 v) {
	__m128 vxmm = _mm_set_ps(0, v, v, v);
	__m128 xmm = _mm_set_ps(0, z, y, x);
	xmm = _mm_add_ps(xmm, vxmm);

	x = M128(xmm, 0);
	y = M128(xmm, 1);
	z = M128(xmm, 2);

	return *this;
}

//Sub
//float32
vec3& vec3::Sub(float32 v) {
	__m128 vxmm = _mm_set_ps(0, v, v, v);
	__m128 xmm = _mm_set_ps(0, z, y, x);
	xmm = _mm_sub_ps(xmm, vxmm);

	x = M128(xmm, 0);
	y = M128(xmm, 1);
	z = M128(xmm, 2);

	return *this;
}

//Mul
//float32
vec3& vec3::Mul(float32 v) {
	__m128 vxmm = _mm_set_ps(0, v, v, v);
	__m128 xmm = _mm_set_ps(0, z, y, x);
	xmm = _mm_mul_ps(xmm, vxmm);

	x = M128(xmm, 0);
	y = M128(xmm, 1);
	z = M128(xmm, 2);

	return *this;
}

//Div
//float32
vec3& vec3::Div(float32 v) {
	__m128 vxmm = _mm_set_ps(0, v, v, v);
	__m128 xmm = _mm_set_ps(0, z, y, x);
	xmm = _mm_div_ps(xmm, vxmm);

	x = M128(xmm, 0);
	y = M128(xmm, 1);
	z = M128(xmm, 2);

	return *this;
}

float32 vec3::Length() const {
	return sqrtf(x * x + y * y + z * z);
}

vec3& vec3::Normalize() {
	return Mul(1.0f / Length());
}

vec3 vec3::Cross(const vec3& v) const {
	__m128 xmm0 = _mm_set_ps(0, x, z, y);
	__m128 vxmm0 = _mm_set_ps(0, v.y, v.x, v.z);

	__m128 xmm1 = _mm_set_ps(0, y, x, z);
	__m128 vxmm1 = _mm_set_ps(0, v.x, v.z, v.y);

	xmm0 = _mm_mul_ps(xmm0, vxmm0);
	xmm1 = _mm_mul_ps(xmm1, vxmm1);

	xmm0 = _mm_sub_ps(xmm0, xmm1);

	return vec3(xmm0.m128_f32[0], xmm0.m128_f32[1], xmm0.m128_f32[2]);
}

float32 vec3::Dot(const vec3& v) const {
	__m128 xmm = _mm_set_ps(0, v.z, v.y, v.x);
	xmm = _mm_mul_ps(xmm, _mm_set_ps(0, y, z, x));
	return M128(xmm, 0) + M128(xmm, 1) + M128(xmm, 2);
}

#pragma endregion

}
}
}<|endoftext|>


<commit_before>/*
 * Copyright 2006-2008 The FLWOR Foundation.
 *
 * 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 "zorbaerrors/error_manager.h"
#include "zorbaerrors/Assert.h"

#include "system/globalenv.h"

#include "context/namespace_context.h"
#include "context/static_context.h"

#include "runtime/accessors/accessors.h"

#include "runtime/visitors/planiter_visitor.h"

#include "store/api/item.h"
#include "store/api/iterator.h"
#include "store/api/item_factory.h"

namespace zorba {

/*******************************************************************************
  2.1 fn:node-name
********************************************************************************/
bool NodeNameIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
  store::Item_t inNode;

  PlanIteratorState *state;
  DEFAULT_STACK_INIT(PlanIteratorState, state, planState);

  if (consumeNext(inNode, theChildren[0].getp(), planState))
  {
    if( inNode->getNodeKind() == store::StoreConsts::elementNode ||
        inNode->getNodeKind() == store::StoreConsts::attributeNode)
    {
      result = inNode->getNodeName();
      STACK_PUSH(true, state);
    }
    else if(inNode->getNodeKind() == store::StoreConsts::piNode)
    {
      GENV_ITEMFACTORY->createQName(result, xqp_string().getStore(),
                                    xqp_string().getStore(),
                                        inNode->getTarget());
      STACK_PUSH(true, state);
    }
  }
  STACK_END (state);
}

/*******************************************************************************
  2.2 fn:nilled
********************************************************************************/
bool NilledIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
  store::Item_t inNode;

  PlanIteratorState *state;
  DEFAULT_STACK_INIT(PlanIteratorState, state, planState);

  if (consumeNext(inNode, theChildren[0].getp(), planState))
  {
    if (inNode->isNode()) {
      result = inNode->getNilled();
      STACK_PUSH(result != NULL, state);
    } else
      ZORBA_ERROR_LOC_DESC(XPTY0004, loc,
                            "The argument of the fn:nilled function is not a node");
  }

  STACK_END (state);
}

/*******************************************************************************
  2.3 fn:string
********************************************************************************/
bool FnStringIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
  store::Item_t inVal;
  xqpStringStore_t strval;

  FnStringIteratorState* state;
  DEFAULT_STACK_INIT(FnStringIteratorState, state, planState);

  while(consumeNext(inVal, theChildren[0], planState))
  {
    state->hasOutput = true;
    strval = inVal->getStringValue();
    GENV_ITEMFACTORY->createString(result, strval);
    STACK_PUSH(true, state);
  }

  if (!state->hasOutput && theEmptyStringOnNULL)
  {
    state->hasOutput = true;
    strval = new xqpStringStore("");
    GENV_ITEMFACTORY->createString(result, strval);
    STACK_PUSH(true, state);
  }

  STACK_END (state);
}

/*******************************************************************************
  2.3 fn:data
********************************************************************************/
bool
FnDataIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
  PlanIter_t iter;
  store::Item_t itemNode;

  FnDataIteratorState* state;
  DEFAULT_STACK_INIT(FnDataIteratorState, state, planState);

  while (true)
  {
    if (!consumeNext(result, theChildren[0], planState))
      break;

    if (result->isAtomic())
    {
      STACK_PUSH(true, state);
    }
    else
    {
      assert(result->isNode());

      {
        store::Item* typeName = result->getType();

        TypeManager* typeMgr = theSctx->get_typemanager();

        xqtref_t schemaType = typeMgr->create_named_type(typeName);
        if ( schemaType->content_kind()==XQType::ELEMENT_ONLY_CONTENT_KIND )
        {
          ZORBA_ERROR_LOC_DESC(FOTY0012, loc,
            "fn:data applied on a complex type with element only content");
        }
      }
      itemNode.transfer(result);
      itemNode->getTypedValue(result, state->theTypedValueIter);

      if (state->theTypedValueIter == NULL)
      {
        if (result == NULL)
          continue;

        STACK_PUSH(true, state );
      }
      else
      {
        state->theTypedValueIter->open();

        while (true)
        {
          if (!state->theTypedValueIter->next(result))
            break;

          assert(!result->isNode());
          STACK_PUSH(true, state );
        }
      }
    }
  }

  state->theTypedValueIter = 0; // TODO remove???
  STACK_END (state);
}

/*******************************************************************************
2.5 fn:base-uri
********************************************************************************/
bool BaseUriIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
  store::Item_t inNode;
  xqpStringStore_t baseuri;

  PlanIteratorState *state;
  DEFAULT_STACK_INIT(PlanIteratorState, state, planState);

  if (consumeNext(inNode, theChildren[0].getp(), planState))
  {
    baseuri = inNode->getBaseURI();
    if (baseuri != NULL) {
      GENV_ITEMFACTORY->createAnyURI(result, baseuri);
      STACK_PUSH(true, state);
    }
  }

  STACK_END (state);
}

/*******************************************************************************
  2.6 fn:document-uri
********************************************************************************/
bool DocumentUriIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
  xqpStringStore_t docuri;

  PlanIteratorState *state;
  DEFAULT_STACK_INIT(PlanIteratorState, state, planState);

  if (consumeNext(result, theChildren[0].getp(), planState))
  {
    docuri = result->getDocumentURI();
    if (docuri != NULL) {
      STACK_PUSH(GENV_ITEMFACTORY->createAnyURI(result, docuri), state);
    }
  }

  STACK_END (state);
}

/*******************************************************************************
  14.9 fn:root
********************************************************************************/
bool RootIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
  store::Item_t contextNode;
  store::Item_t parentNode;

  PlanIteratorState* state;
  DEFAULT_STACK_INIT(PlanIteratorState, state, planState);

  if (!consumeNext(result, theChildren[0].getp(), planState))
    return false;

  parentNode = result->getParent();

  while (parentNode != NULL)
  {
    result = parentNode;
    parentNode = parentNode->getParent();
  }

  STACK_PUSH(true, state);
  STACK_END (state);
}

} /* namespace zorba */
/* vim:set ts=2 sw=2: */
<commit_msg>fnData error fix.<commit_after>/*
 * Copyright 2006-2008 The FLWOR Foundation.
 *
 * 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 "zorbaerrors/error_manager.h"
#include "zorbaerrors/Assert.h"

#include "system/globalenv.h"

#include "context/namespace_context.h"
#include "context/static_context.h"

#include "runtime/accessors/accessors.h"

#include "runtime/visitors/planiter_visitor.h"

#include "store/api/item.h"
#include "store/api/iterator.h"
#include "store/api/item_factory.h"

namespace zorba {

/*******************************************************************************
  2.1 fn:node-name
********************************************************************************/
bool NodeNameIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
  store::Item_t inNode;

  PlanIteratorState *state;
  DEFAULT_STACK_INIT(PlanIteratorState, state, planState);

  if (consumeNext(inNode, theChildren[0].getp(), planState))
  {
    if( inNode->getNodeKind() == store::StoreConsts::elementNode ||
        inNode->getNodeKind() == store::StoreConsts::attributeNode)
    {
      result = inNode->getNodeName();
      STACK_PUSH(true, state);
    }
    else if(inNode->getNodeKind() == store::StoreConsts::piNode)
    {
      GENV_ITEMFACTORY->createQName(result, xqp_string().getStore(),
                                    xqp_string().getStore(),
                                        inNode->getTarget());
      STACK_PUSH(true, state);
    }
  }
  STACK_END (state);
}

/*******************************************************************************
  2.2 fn:nilled
********************************************************************************/
bool NilledIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
  store::Item_t inNode;

  PlanIteratorState *state;
  DEFAULT_STACK_INIT(PlanIteratorState, state, planState);

  if (consumeNext(inNode, theChildren[0].getp(), planState))
  {
    if (inNode->isNode()) {
      result = inNode->getNilled();
      STACK_PUSH(result != NULL, state);
    } else
      ZORBA_ERROR_LOC_DESC(XPTY0004, loc,
                            "The argument of the fn:nilled function is not a node");
  }

  STACK_END (state);
}

/*******************************************************************************
  2.3 fn:string
********************************************************************************/
bool FnStringIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
  store::Item_t inVal;
  xqpStringStore_t strval;

  FnStringIteratorState* state;
  DEFAULT_STACK_INIT(FnStringIteratorState, state, planState);

  while(consumeNext(inVal, theChildren[0], planState))
  {
    state->hasOutput = true;
    strval = inVal->getStringValue();
    GENV_ITEMFACTORY->createString(result, strval);
    STACK_PUSH(true, state);
  }

  if (!state->hasOutput && theEmptyStringOnNULL)
  {
    state->hasOutput = true;
    strval = new xqpStringStore("");
    GENV_ITEMFACTORY->createString(result, strval);
    STACK_PUSH(true, state);
  }

  STACK_END (state);
}

/*******************************************************************************
  2.3 fn:data
********************************************************************************/
bool
FnDataIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
  PlanIter_t iter;
  store::Item_t itemNode;

  FnDataIteratorState* state;
  DEFAULT_STACK_INIT(FnDataIteratorState, state, planState);

  while (true)
  {
    if (!consumeNext(result, theChildren[0], planState))
      break;

    if (result->isAtomic())
    {
      STACK_PUSH(true, state);
    }
    else
    {
      assert(result->isNode());

      {
        store::Item* typeName = result->getType();

        TypeManager* typeMgr = theSctx->get_typemanager();

        if ( typeName!=NULL && typeMgr!=NULL )
        {
          xqtref_t schemaType = typeMgr->create_named_type(typeName);
          if ( schemaType->content_kind()==XQType::ELEMENT_ONLY_CONTENT_KIND )
          {
            ZORBA_ERROR_LOC_DESC(FOTY0012, loc,
              "fn:data applied on a complex type with element only content");
          }
        }
      }

      itemNode.transfer(result);
      itemNode->getTypedValue(result, state->theTypedValueIter);

      if (state->theTypedValueIter == NULL)
      {
        if (result == NULL)
          continue;

        STACK_PUSH(true, state );
      }
      else
      {
        state->theTypedValueIter->open();

        while (true)
        {
          if (!state->theTypedValueIter->next(result))
            break;

          assert(!result->isNode());
          STACK_PUSH(true, state );
        }
      }
    }
  }

  state->theTypedValueIter = 0; // TODO remove???
  STACK_END (state);
}

/*******************************************************************************
2.5 fn:base-uri
********************************************************************************/
bool BaseUriIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
  store::Item_t inNode;
  xqpStringStore_t baseuri;

  PlanIteratorState *state;
  DEFAULT_STACK_INIT(PlanIteratorState, state, planState);

  if (consumeNext(inNode, theChildren[0].getp(), planState))
  {
    baseuri = inNode->getBaseURI();
    if (baseuri != NULL) {
      GENV_ITEMFACTORY->createAnyURI(result, baseuri);
      STACK_PUSH(true, state);
    }
  }

  STACK_END (state);
}

/*******************************************************************************
  2.6 fn:document-uri
********************************************************************************/
bool DocumentUriIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
  xqpStringStore_t docuri;

  PlanIteratorState *state;
  DEFAULT_STACK_INIT(PlanIteratorState, state, planState);

  if (consumeNext(result, theChildren[0].getp(), planState))
  {
    docuri = result->getDocumentURI();
    if (docuri != NULL) {
      STACK_PUSH(GENV_ITEMFACTORY->createAnyURI(result, docuri), state);
    }
  }

  STACK_END (state);
}

/*******************************************************************************
  14.9 fn:root
********************************************************************************/
bool RootIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
  store::Item_t contextNode;
  store::Item_t parentNode;

  PlanIteratorState* state;
  DEFAULT_STACK_INIT(PlanIteratorState, state, planState);

  if (!consumeNext(result, theChildren[0].getp(), planState))
    return false;

  parentNode = result->getParent();

  while (parentNode != NULL)
  {
    result = parentNode;
    parentNode = parentNode->getParent();
  }

  STACK_PUSH(true, state);
  STACK_END (state);
}

} /* namespace zorba */
/* vim:set ts=2 sw=2: */
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/
**
** This file is part of the QtSystems module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qservicerequest_p.h"

// Default constructor - required by meta-type system - note that we could just
// fall back on the one automatically created by the compiler but let's be
// explicit so no mistakes are made - eg, does m_reply get set to zero?
QServiceRequest::QServiceRequest()
    : m_reply(0), m_type(DefaultInterfaceRequest), m_scope(QService::UserScope)
{
    // nothing to do here
}

QServiceRequest::QServiceRequest(const QString &interfaceName)
    : m_interfaceName(interfaceName),
      m_reply(0),
      m_type(DefaultInterfaceRequest),
      m_scope(QService::UserScope)
{
    // nothing to do here
}

QServiceRequest::QServiceRequest(const QServiceInterfaceDescriptor &descriptor)
    : m_descriptor(descriptor),
      m_reply(0),
      m_type(DescriptorRequest),
      m_scope(QService::UserScope)
{
    // nothing to do here
}

// copy constructor - required by meta-type system - again let's be explicit
QServiceRequest::QServiceRequest(const QServiceRequest &other)
{
    m_interfaceName = other.m_interfaceName;
    m_descriptor = other.m_descriptor;
    m_reply = other.m_reply;
    m_type = other.m_type;
    m_scope = other.m_scope;
}

// public destructor - required by meta-type system
QServiceRequest::~QServiceRequest()
{
    // nothing to do here
}

// assignment operator - not needed by meta-type but handy anyway
QServiceRequest & QServiceRequest::operator=(const QServiceRequest &rhs)
{
    if (&rhs == this)
        return *this;

    m_interfaceName = rhs.m_interfaceName;
    m_descriptor = rhs.m_descriptor;
    m_reply = rhs.m_reply;
    m_type = rhs.m_type;
    m_scope = rhs.m_scope;
    return *this;
}

QServiceInterfaceDescriptor QServiceRequest::descriptor() const
{
    return m_descriptor;
}

void QServiceRequest::setDescriptor(const QServiceInterfaceDescriptor &descriptor)
{
    m_type = DescriptorRequest;
    m_descriptor = descriptor;
}

void QServiceRequest::setInterfaceName(const QString &interfaceName)
{
    m_type = DefaultInterfaceRequest;
    m_interfaceName = interfaceName;
}

QString QServiceRequest::interfaceName() const
{
    return m_interfaceName;
}

QServiceReply *QServiceRequest::reply() const
{
    return m_reply;
}

void QServiceRequest::setReply(QServiceReply *reply)
{
    m_reply = reply;
}

QService::Scope QServiceRequest::scope() const
{
    return m_scope;
}

void QServiceRequest::setScope(QService::Scope scope)
{
    m_scope = scope;
}

QServiceRequest::Request QServiceRequest::requestType() const
{
    return m_type;
}
<commit_msg>Fix compiler warning about order of initialization.<commit_after>/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/
**
** This file is part of the QtSystems module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qservicerequest_p.h"

// Default constructor - required by meta-type system - note that we could just
// fall back on the one automatically created by the compiler but let's be
// explicit so no mistakes are made - eg, does m_reply get set to zero?
QServiceRequest::QServiceRequest()
    : m_reply(0), m_scope(QService::UserScope), m_type(DefaultInterfaceRequest)
{
    // nothing to do here
}

QServiceRequest::QServiceRequest(const QString &interfaceName)
    : m_interfaceName(interfaceName),
      m_reply(0),
      m_scope(QService::UserScope),
      m_type(DefaultInterfaceRequest)
{
    // nothing to do here
}

QServiceRequest::QServiceRequest(const QServiceInterfaceDescriptor &descriptor)
    : m_descriptor(descriptor),
      m_reply(0),
      m_scope(QService::UserScope),
      m_type(DescriptorRequest)
{
    // nothing to do here
}

// copy constructor - required by meta-type system - again let's be explicit
QServiceRequest::QServiceRequest(const QServiceRequest &other)
    : m_interfaceName(other.m_interfaceName),
      m_descriptor(other.m_descriptor),
      m_reply(other.m_reply),
      m_scope(other.m_scope),
      m_type(other.m_type)
{
}

// public destructor - required by meta-type system
QServiceRequest::~QServiceRequest()
{
    // nothing to do here
}

// assignment operator - not needed by meta-type but handy anyway
QServiceRequest & QServiceRequest::operator=(const QServiceRequest &rhs)
{
    if (&rhs == this)
        return *this;

    m_interfaceName = rhs.m_interfaceName;
    m_descriptor = rhs.m_descriptor;
    m_reply = rhs.m_reply;
    m_type = rhs.m_type;
    m_scope = rhs.m_scope;
    return *this;
}

QServiceInterfaceDescriptor QServiceRequest::descriptor() const
{
    return m_descriptor;
}

void QServiceRequest::setDescriptor(const QServiceInterfaceDescriptor &descriptor)
{
    m_type = DescriptorRequest;
    m_descriptor = descriptor;
}

void QServiceRequest::setInterfaceName(const QString &interfaceName)
{
    m_type = DefaultInterfaceRequest;
    m_interfaceName = interfaceName;
}

QString QServiceRequest::interfaceName() const
{
    return m_interfaceName;
}

QServiceReply *QServiceRequest::reply() const
{
    return m_reply;
}

void QServiceRequest::setReply(QServiceReply *reply)
{
    m_reply = reply;
}

QService::Scope QServiceRequest::scope() const
{
    return m_scope;
}

void QServiceRequest::setScope(QService::Scope scope)
{
    m_scope = scope;
}

QServiceRequest::Request QServiceRequest::requestType() const
{
    return m_type;
}
<|endoftext|>