<commit_before>/*
 *
 *    Copyright (c) 2020 Project CHIP Authors
 *    Copyright (c) 2018 Nest Labs, Inc.
 *    All rights reserved.
 *
 *    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.
 */

/**
 *    @file
 *          Provides an implementation of the PlatformManager object
 *          for the ESP32 platform.
 */
/* this file behaves like a config.h, comes first */
#include <platform/internal/CHIPDeviceLayerInternal.h>

#include <crypto/CHIPCryptoPAL.h>
#include <platform/PlatformManager.h>
#include <platform/internal/GenericPlatformManagerImpl_FreeRTOS.cpp>

#include "esp_event.h"
#include "esp_heap_caps_init.h"
#include "esp_log.h"
#include "esp_netif.h"
#include "esp_spi_flash.h"
#include "esp_system.h"
#include "esp_wifi.h"

namespace chip {
namespace DeviceLayer {

namespace Internal {
extern CHIP_ERROR InitLwIPCoreLock(void);
}

PlatformManagerImpl PlatformManagerImpl::sInstance;

static int app_entropy_source(void * data, unsigned char * output, size_t len, size_t * olen)
{
    esp_fill_random(output, len);
    *olen = len;
    return 0;
}

CHIP_ERROR PlatformManagerImpl::_InitChipStack(void)
{
    CHIP_ERROR err;
    wifi_init_config_t cfg;
    uint8_t ap_mac[6];

    esp_fill_random(ap_mac, sizeof(ap_mac));
    /* Bit 0 of the first octet of MAC Address should always be 0 */
    ap_mac[0] &= (uint8_t) ~0x01;

    // Make sure the LwIP core lock has been initialized
    err = Internal::InitLwIPCoreLock();
    SuccessOrExit(err);

    err = esp_netif_init();
    SuccessOrExit(err);

    // Arrange for the ESP event loop to deliver events into the CHIP Device layer.
    err = esp_event_loop_create_default();
    SuccessOrExit(err);

    esp_netif_create_default_wifi_ap();
    esp_netif_create_default_wifi_sta();

    esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID, PlatformManagerImpl::HandleESPSystemEvent, NULL);
    SuccessOrExit(err);
    esp_event_handler_register(IP_EVENT, ESP_EVENT_ANY_ID, PlatformManagerImpl::HandleESPSystemEvent, NULL);
    SuccessOrExit(err);

    // Initialize the ESP WiFi layer.
    cfg = WIFI_INIT_CONFIG_DEFAULT();
    err = esp_wifi_init(&cfg);
    SuccessOrExit(err);

    err = esp_wifi_set_mac(ESP_IF_WIFI_AP, ap_mac);
    SuccessOrExit(err);

    // Call _InitChipStack() on the generic implementation base class
    // to finish the initialization process.
    err = Internal::GenericPlatformManagerImpl_FreeRTOS<PlatformManagerImpl>::_InitChipStack();
    SuccessOrExit(err);

    err = chip::Crypto::add_entropy_source(app_entropy_source, NULL, 16);
    SuccessOrExit(err);

exit:
    return err;
}

CHIP_ERROR PlatformManagerImpl::InitLwIPCoreLock(void)
{
    return Internal::InitLwIPCoreLock();
}

void PlatformManagerImpl::HandleESPSystemEvent(void * arg, esp_event_base_t eventBase, int32_t eventId, void * eventData)
{
    ChipDeviceEvent event;
    memset(&event, 0, sizeof(event));
    event.Type                         = DeviceEventType::kESPSystemEvent;
    event.Platform.ESPSystemEvent.Base = eventBase;
    event.Platform.ESPSystemEvent.Id   = eventId;
    if (eventBase == IP_EVENT)
    {
        switch (eventId)
        {
        case IP_EVENT_STA_GOT_IP:
            memcpy(&event.Platform.ESPSystemEvent.Data.IpGotIp, eventData, sizeof(event.Platform.ESPSystemEvent.Data.IpGotIp));
            break;
        case IP_EVENT_GOT_IP6:
            memcpy(&event.Platform.ESPSystemEvent.Data.IpGotIp6, eventData, sizeof(event.Platform.ESPSystemEvent.Data.IpGotIp6));
            break;
        case IP_EVENT_AP_STAIPASSIGNED:
            memcpy(&event.Platform.ESPSystemEvent.Data.IpApStaIpAssigned, eventData,
                   sizeof(event.Platform.ESPSystemEvent.Data.IpApStaIpAssigned));
            break;
        default:
            break;
        }
    }
    else if (eventBase == WIFI_EVENT)
    {
        switch (eventId)
        {
        case WIFI_EVENT_SCAN_DONE:
            memcpy(&event.Platform.ESPSystemEvent.Data.WifiStaScanDone, eventData,
                   sizeof(event.Platform.ESPSystemEvent.Data.WifiStaScanDone));
            break;
        case WIFI_EVENT_STA_CONNECTED:
            memcpy(&event.Platform.ESPSystemEvent.Data.WifiStaConnected, eventData,
                   sizeof(event.Platform.ESPSystemEvent.Data.WifiStaConnected));
            break;
        case WIFI_EVENT_STA_DISCONNECTED:
            memcpy(&event.Platform.ESPSystemEvent.Data.WifiStaDisconnected, eventData,
                   sizeof(event.Platform.ESPSystemEvent.Data.WifiStaDisconnected));
            break;
        case WIFI_EVENT_STA_AUTHMODE_CHANGE:
            memcpy(&event.Platform.ESPSystemEvent.Data.WifiStaAuthModeChange, eventData,
                   sizeof(event.Platform.ESPSystemEvent.Data.WifiStaAuthModeChange));
            break;
        case WIFI_EVENT_STA_WPS_ER_PIN:
            memcpy(&event.Platform.ESPSystemEvent.Data.WifiStaWpsErPin, eventData,
                   sizeof(event.Platform.ESPSystemEvent.Data.WifiStaWpsErPin));
            break;
        case WIFI_EVENT_STA_WPS_ER_FAILED:
            memcpy(&event.Platform.ESPSystemEvent.Data.WifiStaWpsErFailed, eventData,
                   sizeof(event.Platform.ESPSystemEvent.Data.WifiStaWpsErFailed));
            break;
        case WIFI_EVENT_AP_STACONNECTED:
            memcpy(&event.Platform.ESPSystemEvent.Data.WifiApStaConnected, eventData,
                   sizeof(event.Platform.ESPSystemEvent.Data.WifiApStaConnected));
            break;
        case WIFI_EVENT_AP_STADISCONNECTED:
            memcpy(&event.Platform.ESPSystemEvent.Data.WifiApStaDisconnected, eventData,
                   sizeof(event.Platform.ESPSystemEvent.Data.WifiApStaDisconnected));
            break;
        case WIFI_EVENT_AP_PROBEREQRECVED:
            memcpy(&event.Platform.ESPSystemEvent.Data.WifiApProbeReqRecved, eventData,
                   sizeof(event.Platform.ESPSystemEvent.Data.WifiApProbeReqRecved));
            break;
        default:
            break;
        }
    }

    sInstance.PostEvent(&event);
}

} // namespace DeviceLayer
} // namespace chip
<commit_msg>ESP32: Fix all-clusters-app for Rendezvous BLE (#5535)<commit_after>/*
 *
 *    Copyright (c) 2020 Project CHIP Authors
 *    Copyright (c) 2018 Nest Labs, Inc.
 *    All rights reserved.
 *
 *    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.
 */

/**
 *    @file
 *          Provides an implementation of the PlatformManager object
 *          for the ESP32 platform.
 */
/* this file behaves like a config.h, comes first */
#include <platform/internal/CHIPDeviceLayerInternal.h>

#include <crypto/CHIPCryptoPAL.h>
#include <platform/PlatformManager.h>
#include <platform/internal/GenericPlatformManagerImpl_FreeRTOS.cpp>

#include "esp_event.h"
#include "esp_heap_caps_init.h"
#include "esp_log.h"
#include "esp_netif.h"
#include "esp_spi_flash.h"
#include "esp_system.h"
#include "esp_wifi.h"

namespace chip {
namespace DeviceLayer {

namespace Internal {
extern CHIP_ERROR InitLwIPCoreLock(void);
}

PlatformManagerImpl PlatformManagerImpl::sInstance;

static int app_entropy_source(void * data, unsigned char * output, size_t len, size_t * olen)
{
    esp_fill_random(output, len);
    *olen = len;
    return 0;
}

CHIP_ERROR PlatformManagerImpl::_InitChipStack(void)
{
    CHIP_ERROR err;
    wifi_init_config_t cfg;
    uint8_t ap_mac[6];
    wifi_mode_t mode;

    // Make sure the LwIP core lock has been initialized
    err = Internal::InitLwIPCoreLock();
    SuccessOrExit(err);

    err = esp_netif_init();
    SuccessOrExit(err);

    // Arrange for the ESP event loop to deliver events into the CHIP Device layer.
    err = esp_event_loop_create_default();
    SuccessOrExit(err);

    esp_netif_create_default_wifi_ap();
    esp_netif_create_default_wifi_sta();

    esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID, PlatformManagerImpl::HandleESPSystemEvent, NULL);
    SuccessOrExit(err);
    esp_event_handler_register(IP_EVENT, ESP_EVENT_ANY_ID, PlatformManagerImpl::HandleESPSystemEvent, NULL);
    SuccessOrExit(err);

    // Initialize the ESP WiFi layer.
    cfg = WIFI_INIT_CONFIG_DEFAULT();
    err = esp_wifi_init(&cfg);
    SuccessOrExit(err);

    esp_wifi_get_mode(&mode);
    if ((mode == WIFI_MODE_AP) || (mode == WIFI_MODE_APSTA))
    {
        esp_fill_random(ap_mac, sizeof(ap_mac));
        /* Bit 0 of the first octet of MAC Address should always be 0 */
        ap_mac[0] &= (uint8_t) ~0x01;
        err = esp_wifi_set_mac(ESP_IF_WIFI_AP, ap_mac);
        SuccessOrExit(err);
    }

    // Call _InitChipStack() on the generic implementation base class
    // to finish the initialization process.
    err = Internal::GenericPlatformManagerImpl_FreeRTOS<PlatformManagerImpl>::_InitChipStack();
    SuccessOrExit(err);

    err = chip::Crypto::add_entropy_source(app_entropy_source, NULL, 16);
    SuccessOrExit(err);

exit:
    return err;
}

CHIP_ERROR PlatformManagerImpl::InitLwIPCoreLock(void)
{
    return Internal::InitLwIPCoreLock();
}

void PlatformManagerImpl::HandleESPSystemEvent(void * arg, esp_event_base_t eventBase, int32_t eventId, void * eventData)
{
    ChipDeviceEvent event;
    memset(&event, 0, sizeof(event));
    event.Type                         = DeviceEventType::kESPSystemEvent;
    event.Platform.ESPSystemEvent.Base = eventBase;
    event.Platform.ESPSystemEvent.Id   = eventId;
    if (eventBase == IP_EVENT)
    {
        switch (eventId)
        {
        case IP_EVENT_STA_GOT_IP:
            memcpy(&event.Platform.ESPSystemEvent.Data.IpGotIp, eventData, sizeof(event.Platform.ESPSystemEvent.Data.IpGotIp));
            break;
        case IP_EVENT_GOT_IP6:
            memcpy(&event.Platform.ESPSystemEvent.Data.IpGotIp6, eventData, sizeof(event.Platform.ESPSystemEvent.Data.IpGotIp6));
            break;
        case IP_EVENT_AP_STAIPASSIGNED:
            memcpy(&event.Platform.ESPSystemEvent.Data.IpApStaIpAssigned, eventData,
                   sizeof(event.Platform.ESPSystemEvent.Data.IpApStaIpAssigned));
            break;
        default:
            break;
        }
    }
    else if (eventBase == WIFI_EVENT)
    {
        switch (eventId)
        {
        case WIFI_EVENT_SCAN_DONE:
            memcpy(&event.Platform.ESPSystemEvent.Data.WifiStaScanDone, eventData,
                   sizeof(event.Platform.ESPSystemEvent.Data.WifiStaScanDone));
            break;
        case WIFI_EVENT_STA_CONNECTED:
            memcpy(&event.Platform.ESPSystemEvent.Data.WifiStaConnected, eventData,
                   sizeof(event.Platform.ESPSystemEvent.Data.WifiStaConnected));
            break;
        case WIFI_EVENT_STA_DISCONNECTED:
            memcpy(&event.Platform.ESPSystemEvent.Data.WifiStaDisconnected, eventData,
                   sizeof(event.Platform.ESPSystemEvent.Data.WifiStaDisconnected));
            break;
        case WIFI_EVENT_STA_AUTHMODE_CHANGE:
            memcpy(&event.Platform.ESPSystemEvent.Data.WifiStaAuthModeChange, eventData,
                   sizeof(event.Platform.ESPSystemEvent.Data.WifiStaAuthModeChange));
            break;
        case WIFI_EVENT_STA_WPS_ER_PIN:
            memcpy(&event.Platform.ESPSystemEvent.Data.WifiStaWpsErPin, eventData,
                   sizeof(event.Platform.ESPSystemEvent.Data.WifiStaWpsErPin));
            break;
        case WIFI_EVENT_STA_WPS_ER_FAILED:
            memcpy(&event.Platform.ESPSystemEvent.Data.WifiStaWpsErFailed, eventData,
                   sizeof(event.Platform.ESPSystemEvent.Data.WifiStaWpsErFailed));
            break;
        case WIFI_EVENT_AP_STACONNECTED:
            memcpy(&event.Platform.ESPSystemEvent.Data.WifiApStaConnected, eventData,
                   sizeof(event.Platform.ESPSystemEvent.Data.WifiApStaConnected));
            break;
        case WIFI_EVENT_AP_STADISCONNECTED:
            memcpy(&event.Platform.ESPSystemEvent.Data.WifiApStaDisconnected, eventData,
                   sizeof(event.Platform.ESPSystemEvent.Data.WifiApStaDisconnected));
            break;
        case WIFI_EVENT_AP_PROBEREQRECVED:
            memcpy(&event.Platform.ESPSystemEvent.Data.WifiApProbeReqRecved, eventData,
                   sizeof(event.Platform.ESPSystemEvent.Data.WifiApProbeReqRecved));
            break;
        default:
            break;
        }
    }

    sInstance.PostEvent(&event);
}

} // namespace DeviceLayer
} // namespace chip
<|endoftext|>


<commit_before>//
// test-rtx-controller.cc
//
//  Created by Peter Gusev on 23 August 2017.
//  Copyright 2013-2016 Regents of the University of California
//

#include <stdlib.h>
#include <algorithm>
#include <ctime>

#include <ndn-cpp/interest.hpp>
#include <ndn-cpp/name.hpp>
#include <boost/shared_ptr.hpp>

#include "gtest/gtest.h"
#include "tests-helpers.hpp"

#include "mock-objects/rtx-observer-mock.hpp"
#include "mock-objects/buffer-mock.hpp"
#include "mock-objects/playback-queue-mock.hpp"

#include "statistics.hpp"
#include "src/frame-data.hpp"
#include "src/frame-buffer.hpp"
#include "src/rtx-controller.hpp"

using namespace ndnrtc;
using namespace ndnrtc::statistics;
using namespace ndn;
using namespace testing;

TEST(TestRtxController, TestRtx){
	boost::shared_ptr<StatisticsStorage> storage(StatisticsStorage::createConsumerStatistics());
	boost::shared_ptr<MockPlaybackQueue> playbackQueue(boost::make_shared<MockPlaybackQueue>());

	MockRtxObserver rtxObserverMock;
	RetransmissionController rtx = RetransmissionController(storage, playbackQueue);
	rtx.attach(&rtxObserverMock);

	int nPackets = 10;
	std::srand(std::time(0));
	std::string frameName = "/ndn/edu/ucla/remap/peter/ndncon/instance1/ndnrtc/%FD%02/video/camera/hi/d";
	IBufferObserver *bufferObserver = &rtx;

	std::set<Name> rtxInterestNames;
	EXPECT_CALL(rtxObserverMock, onRetransmissionRequired(_))
		.Times(AtLeast(nPackets/2))
		.WillRepeatedly(Invoke([&rtxInterestNames](const std::vector<boost::shared_ptr<const ndn::Interest>> interests){
			GT_PRINTF("RTX for %d interests\n", interests.size());

			for (auto i:interests)
			{
				if (rtxInterestNames.find(i->getName()) != rtxInterestNames.end())
					FAIL() << "RTX for already retransmitted interest";
				rtxInterestNames.insert(i->getName());
			}
		}));

	for (int i = 0; i < nPackets; ++i)
	{
		std::vector<boost::shared_ptr<const Interest>> interests;
		int nInterests = std::rand()%30+10;
		for (int j = 0; j < nInterests; ++j)
		{
			boost::shared_ptr<Interest> interest(boost::make_shared<Interest>(Name(frameName).appendSequenceNumber(i).appendSegment(j), 1000));
			int nonce = 0x1234+i*10+j;
			interest->setNonce(Blob((uint8_t*)&nonce, sizeof(int)));
			interests.push_back(interest);
		}

		boost::shared_ptr<BufferSlot> slot = boost::make_shared<BufferSlot>();
		slot->segmentsRequested(interests);

		EXPECT_CALL(*playbackQueue, size())
			.Times(AtLeast(1))
			.WillRepeatedly(Invoke([](){ return 100; }));
		EXPECT_CALL(*playbackQueue, pendingSize())
			.Times(AtLeast(1))
			.WillRepeatedly(Invoke([](){ return 100; }));

		bufferObserver->onNewRequest(slot);

		usleep(33000);
	}
}

//******************************************************************************
int main(int argc, char **argv) {
	::testing::InitGoogleTest(&argc, argv);
	return RUN_ALL_TESTS();
}
<commit_msg>updated RTC controller unit test<commit_after>//
// test-rtx-controller.cc
//
//  Created by Peter Gusev on 23 August 2017.
//  Copyright 2013-2016 Regents of the University of California
//

#include <stdlib.h>
#include <algorithm>
#include <ctime>

#include <ndn-cpp/interest.hpp>
#include <ndn-cpp/name.hpp>
#include <boost/shared_ptr.hpp>

#include "gtest/gtest.h"
#include "tests-helpers.hpp"

#include "mock-objects/rtx-observer-mock.hpp"
#include "mock-objects/buffer-mock.hpp"
#include "mock-objects/playback-queue-mock.hpp"

#include "statistics.hpp"
#include "src/frame-data.hpp"
#include "src/frame-buffer.hpp"
#include "src/rtx-controller.hpp"

using namespace ndnrtc;
using namespace ndnrtc::statistics;
using namespace ndn;
using namespace testing;

TEST(TestRtxController, TestRtx){
	boost::shared_ptr<StatisticsStorage> storage(StatisticsStorage::createConsumerStatistics());
	boost::shared_ptr<MockPlaybackQueue> playbackQueue(boost::make_shared<MockPlaybackQueue>());

	MockRtxObserver rtxObserverMock;
	RetransmissionController rtx = RetransmissionController(storage, playbackQueue);
	rtx.attach(&rtxObserverMock);

	int nPackets = 10;
	std::string frameName = "/ndn/edu/ucla/remap/peter/ndncon/instance1/ndnrtc/%FD%02/video/camera/hi/d";
	IBufferObserver *bufferObserver = &rtx;

	std::set<Name> rtxInterestNames;
	EXPECT_CALL(rtxObserverMock, onRetransmissionRequired(_))
		.Times(AtLeast(nPackets/2))
		.WillRepeatedly(Invoke([&rtxInterestNames](const std::vector<boost::shared_ptr<const ndn::Interest>> interests){
			GT_PRINTF("RTX for %d interests\n", interests.size());

			for (auto i:interests)
			{
				if (rtxInterestNames.find(i->getName()) != rtxInterestNames.end())
					FAIL() << "RTX for already retransmitted interest";
				rtxInterestNames.insert(i->getName());
				EXPECT_GE(i->getName()[-1].toSegment(), 5);
			}
		}));

	std::vector<boost::shared_ptr<BufferSlot>> slots;
	for (int i = 0; i < nPackets; ++i)
	{
		std::vector<boost::shared_ptr<const Interest>> interests;
		int nInterests = std::rand()%30+10;
		for (int j = 0; j < nInterests; ++j)
		{
			boost::shared_ptr<Interest> interest(boost::make_shared<Interest>(Name(frameName).appendSequenceNumber(i).appendSegment(j), 1000));
			int nonce = 0x1234+i*10+j;
			interest->setNonce(Blob((uint8_t*)&nonce, sizeof(int)));
			interests.push_back(interest);
		}

		boost::shared_ptr<BufferSlot> slot = boost::make_shared<BufferSlot>();
		slots.push_back(slot);
		slot->segmentsRequested(interests);

		EXPECT_CALL(*playbackQueue, size())
			.Times(AtLeast(1))
			.WillRepeatedly(Invoke([](){ return 100; }));
		EXPECT_CALL(*playbackQueue, pendingSize())
			.Times(AtLeast(1))
			.WillRepeatedly(Invoke([](){ return 100; }));

		bufferObserver->onNewRequest(slot);

		// add some data (5 segments) - some interests will require RTX, as we requested at least 10 segments per slot
		VideoFramePacket vp = getVideoFramePacket();
		std::vector<VideoFrameSegment> segments = sliceFrame(vp);

		Name n(frameName);
		n.appendSequenceNumber(i);
		std::vector<boost::shared_ptr<ndn::Data>> dataObjects = dataFromSegments(n.toUri(), segments);

		for (auto o:dataObjects)
		{
			boost::shared_ptr<const Interest> interest;
			for (auto i:interests)
				if (i->getName() == o->getName())
				{
					interest = i;
					break;
				}
			if (interest)
			{
				boost::shared_ptr<WireSegment> segment = boost::make_shared<WireSegment>(o, interest);
				slot->segmentReceived(segment);
			}
		}

		usleep(33000);
	}
}

//******************************************************************************
int main(int argc, char **argv) {
	::testing::InitGoogleTest(&argc, argv);
	return RUN_ALL_TESTS();
}
<|endoftext|>


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

#include "openrasp_ini.h"
#include <regex>
#include <limits>

Openrasp_ini openrasp_ini;

ZEND_INI_MH(OnUpdateOpenraspDoubleGEZero)
{
    double tmp = zend_string_to_double(new_value, new_value_length);
    if (tmp < 0 || tmp > std::numeric_limits<double>::max())
    {
        return FAILURE;
    }
    *reinterpret_cast<double *>(mh_arg1) = tmp;
    return SUCCESS;
}

ZEND_INI_MH(OnUpdateOpenraspIntGEZero)
{
    long tmp = zend_atol(new_value, new_value_length);
    if (tmp < 0 || tmp > std::numeric_limits<unsigned int>::max())
    {
        return FAILURE;
    }
    *reinterpret_cast<int *>(mh_arg1) = tmp;
    return SUCCESS;
}

ZEND_INI_MH(OnUpdateOpenraspCString)
{
    *reinterpret_cast<char **>(mh_arg1) = new_value_length ? new_value : nullptr;
    return SUCCESS;
}

ZEND_INI_MH(OnUpdateOpenraspBool)
{
    bool *tmp = reinterpret_cast<bool *>(mh_arg1);
    *tmp = strtobool(new_value, new_value_length);
    return SUCCESS;
}

ZEND_INI_MH(OnUpdateOpenraspSet)
{
    std::unordered_set<std::string> *p = reinterpret_cast<std::unordered_set<std::string> *>(mh_arg1);
    p->clear();
    if (new_value)
    {
        std::regex re(R"([\s,]+)");
        const std::cregex_token_iterator end;
        for (std::cregex_token_iterator it(new_value, new_value + new_value_length, re, -1); it != end; it++)
        {
            p->insert(it->str());
        }
    }
    return SUCCESS;
}

bool strtobool(const char *str, int len)
{
    if (len == 2 && strcasecmp("on", str) == 0)
    {
        return true;
    }
    else if (len == 3 && strcasecmp("yes", str) == 0)
    {
        return true;
    }
    else if (len == 4 && strcasecmp("true", str) == 0)
    {
        return true;
    }
    else
    {
        return atoi(str);
    }
}<commit_msg>refactor(php5) OnUpdateOpenraspSet method<commit_after>/*
 * Copyright 2017-2018 Baidu Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "openrasp_ini.h"
// #include <regex>
#include <limits>

Openrasp_ini openrasp_ini;

ZEND_INI_MH(OnUpdateOpenraspDoubleGEZero)
{
    double tmp = zend_string_to_double(new_value, new_value_length);
    if (tmp < 0 || tmp > std::numeric_limits<double>::max())
    {
        return FAILURE;
    }
    *reinterpret_cast<double *>(mh_arg1) = tmp;
    return SUCCESS;
}

ZEND_INI_MH(OnUpdateOpenraspIntGEZero)
{
    long tmp = zend_atol(new_value, new_value_length);
    if (tmp < 0 || tmp > std::numeric_limits<unsigned int>::max())
    {
        return FAILURE;
    }
    *reinterpret_cast<int *>(mh_arg1) = tmp;
    return SUCCESS;
}

ZEND_INI_MH(OnUpdateOpenraspCString)
{
    *reinterpret_cast<char **>(mh_arg1) = new_value_length ? new_value : nullptr;
    return SUCCESS;
}

ZEND_INI_MH(OnUpdateOpenraspBool)
{
    bool *tmp = reinterpret_cast<bool *>(mh_arg1);
    *tmp = strtobool(new_value, new_value_length);
    return SUCCESS;
}

ZEND_INI_MH(OnUpdateOpenraspSet)
{
    std::unordered_set<std::string> *p = reinterpret_cast<std::unordered_set<std::string> *>(mh_arg1);
    p->clear();
    char *tmp;
    if (new_value && (tmp = strdup(new_value)))
    {
        char *s = nullptr, *e = tmp;
        while (*e)
        {
            switch (*e)
            {
            case ' ':
            case ',':
                if (s)
                {
                    *e = '\0';
                    p->insert(std::string(s, e - s));
                    s = nullptr;
                }
                break;
            default:
                if (!s)
                {
                    s = e;
                }
                break;
            }
            e++;
        }
        if (s)
        {
            p->insert(std::string(s, e - s));
        }
        free(tmp);
    }
    // if (new_value)
    // {
    //     std::regex re(R"([\s,]+)");
    //     const std::cregex_token_iterator end;
    //     for (std::cregex_token_iterator it(new_value, new_value + new_value_length, re, -1); it != end; it++)
    //     {
    //         p->insert(it->str());
    //     }
    // }
    return SUCCESS;
}

bool strtobool(const char *str, int len)
{
    if (len == 2 && strcasecmp("on", str) == 0)
    {
        return true;
    }
    else if (len == 3 && strcasecmp("yes", str) == 0)
    {
        return true;
    }
    else if (len == 4 && strcasecmp("true", str) == 0)
    {
        return true;
    }
    else
    {
        return atoi(str);
    }
}<|endoftext|>


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

#ifndef _EXCIMP8_HXX
#define _EXCIMP8_HXX

#include <string.h>

#ifndef _IMP_OP_HXX
#include "imp_op.hxx"
#endif
#ifndef _ROOT_HXX
#include "root.hxx"
#endif
#ifndef _EXCSCEN_HXX
#include "excscen.hxx"
#endif
#ifndef _EXCDEFS_HXX
#include "excdefs.hxx"
#endif

#ifndef SC_FTOOLS_HXX
#include "ftools.hxx"
#endif

class SotStorage;

class ScBaseCell;
class ScRangeList;
class ScDBData;

class ScfSimpleProgressBar;

class XclImpStream;

class ImportExcel8 : public ImportExcel
{
    protected:
        ExcScenarioList         aScenList;

        BOOL                    bHasBasic;

        void                    RecString( void );              // 0x07
        void                    Calccount( void );              // 0x0C
        void                    Precision( void );              // 0x0E
        void                    Delta( void );                  // 0x10
        void                    Iteration( void );              // 0x11
        void                    Note( void );                   // 0x1C
        void                    WinProtection(  void );         // 0x19
        void                    Boundsheet( void );             // 0x85
        void                    FilterMode( void );             // 0x9B
        void                    AutoFilterInfo( void );         // 0x9D
        void                    AutoFilter( void );             // 0x9E
        void                    Scenman( void );                // 0xAE
        void                    Scenario( void );               // 0xAF
        void                    ReadBasic( void );              // 0xD3
        void                    Cellmerging( void );            // 0xE5     geraten...
        void                    Labelsst( void );               // 0xFD

        void                    Hlink( void );                  // 0x01B8
        void                    Codename( BOOL bWBGlobals );    // 0x01BA

        virtual void            EndSheet( void );
        virtual void            PostDocLoad( void );

    public:
                                ImportExcel8( XclImpRootData& rImpData, SvStream& rStrm );
        virtual                 ~ImportExcel8( void );

        virtual FltError        Read( void );
};

//___________________________________________________________________
// classes AutoFilterData, AutoFilterBuffer

class XclImpAutoFilterData : private ExcRoot
{
private:
    ScDBData*                   pCurrDBData;
    ScQueryParam                aParam;
    SCSIZE                      nFirstEmpty;
    BOOL                        bActive;
    BOOL                        bHasConflict;
    BOOL                        bCriteria;
    BOOL                        bAutoOrAdvanced;
    ScRange                     aCriteriaRange;
    String                      aFilterName;

    void                        CreateFromDouble( String& rStr, double fVal );
    void                        SetCellAttribs();
    void                        InsertQueryParam();
    void                        AmendAFName(const BOOL bUseUnNamed);

protected:
public:
                                XclImpAutoFilterData(
                                    RootData* pRoot,
                                    const ScRange& rRange,
                                    const String& rName );

    inline bool                 IsActive() const    { return bActive; }
    inline SCTAB                Tab() const         { return aParam.nTab; }
    inline SCCOL                StartCol() const    { return aParam.nCol1; }
    inline SCROW                StartRow() const    { return aParam.nRow1; }
    inline SCCOL                EndCol() const      { return aParam.nCol2; }
    inline SCROW                EndRow() const      { return aParam.nRow2; }

    void                        ReadAutoFilter( XclImpStream& rStrm );

    inline void                 Activate()          { bActive = TRUE; }
    void                        SetAdvancedRange( const ScRange* pRange );
    void                        SetExtractPos( const ScAddress& rAddr );
    inline void                 SetAutoOrAdvanced()  { bAutoOrAdvanced = TRUE; }
    void                        Apply( const BOOL bUseUnNamed = FALSE );
    void                        CreateScDBData( const BOOL bUseUnNamed );
    void                        EnableRemoveFilter();
};

class XclImpAutoFilterBuffer : private List
{
private:
    UINT16                      nAFActiveCount;

    inline XclImpAutoFilterData* _First()   { return (XclImpAutoFilterData*) List::First(); }
    inline XclImpAutoFilterData* _Next()    { return (XclImpAutoFilterData*) List::Next(); }

    inline void                 Append( XclImpAutoFilterData* pData )
                                    { List::Insert( pData, LIST_APPEND ); }
protected:
public:
                                XclImpAutoFilterBuffer();
    virtual                     ~XclImpAutoFilterBuffer();

    void                        Insert( RootData* pRoot, const ScRange& rRange,
                                                const String& rName );
    void                        AddAdvancedRange( const ScRange& rRange );
    void                        AddExtractPos( const ScRange& rRange );
    void                        Apply();

    XclImpAutoFilterData*       GetByTab( SCTAB nTab );
    inline void                 IncrementActiveAF() { nAFActiveCount++; }
    inline BOOL                 UseUnNamed() { return nAFActiveCount == 1; }
};

#endif

<commit_msg>INTEGRATION: CWS calc37 (1.65.36); FILE MERGED 2006/07/17 14:10:12 dr 1.65.36.1: #i67106# ignore STRING record<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: excimp8.hxx,v $
 *
 *  $Revision: 1.66 $
 *
 *  last change: $Author: rt $ $Date: 2006-07-25 09:58:58 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _EXCIMP8_HXX
#define _EXCIMP8_HXX

#include <string.h>

#ifndef _IMP_OP_HXX
#include "imp_op.hxx"
#endif
#ifndef _ROOT_HXX
#include "root.hxx"
#endif
#ifndef _EXCSCEN_HXX
#include "excscen.hxx"
#endif
#ifndef _EXCDEFS_HXX
#include "excdefs.hxx"
#endif

#ifndef SC_FTOOLS_HXX
#include "ftools.hxx"
#endif

class SotStorage;

class ScBaseCell;
class ScRangeList;
class ScDBData;

class ScfSimpleProgressBar;

class XclImpStream;

class ImportExcel8 : public ImportExcel
{
    protected:
        ExcScenarioList         aScenList;

        BOOL                    bHasBasic;

        void                    Calccount( void );              // 0x0C
        void                    Precision( void );              // 0x0E
        void                    Delta( void );                  // 0x10
        void                    Iteration( void );              // 0x11
        void                    Note( void );                   // 0x1C
        void                    WinProtection(  void );         // 0x19
        void                    Boundsheet( void );             // 0x85
        void                    FilterMode( void );             // 0x9B
        void                    AutoFilterInfo( void );         // 0x9D
        void                    AutoFilter( void );             // 0x9E
        void                    Scenman( void );                // 0xAE
        void                    Scenario( void );               // 0xAF
        void                    ReadBasic( void );              // 0xD3
        void                    Cellmerging( void );            // 0xE5     geraten...
        void                    Labelsst( void );               // 0xFD

        void                    Hlink( void );                  // 0x01B8
        void                    Codename( BOOL bWBGlobals );    // 0x01BA

        virtual void            EndSheet( void );
        virtual void            PostDocLoad( void );

    public:
                                ImportExcel8( XclImpRootData& rImpData, SvStream& rStrm );
        virtual                 ~ImportExcel8( void );

        virtual FltError        Read( void );
};

//___________________________________________________________________
// classes AutoFilterData, AutoFilterBuffer

class XclImpAutoFilterData : private ExcRoot
{
private:
    ScDBData*                   pCurrDBData;
    ScQueryParam                aParam;
    SCSIZE                      nFirstEmpty;
    BOOL                        bActive;
    BOOL                        bHasConflict;
    BOOL                        bCriteria;
    BOOL                        bAutoOrAdvanced;
    ScRange                     aCriteriaRange;
    String                      aFilterName;

    void                        CreateFromDouble( String& rStr, double fVal );
    void                        SetCellAttribs();
    void                        InsertQueryParam();
    void                        AmendAFName(const BOOL bUseUnNamed);

protected:
public:
                                XclImpAutoFilterData(
                                    RootData* pRoot,
                                    const ScRange& rRange,
                                    const String& rName );

    inline bool                 IsActive() const    { return bActive; }
    inline SCTAB                Tab() const         { return aParam.nTab; }
    inline SCCOL                StartCol() const    { return aParam.nCol1; }
    inline SCROW                StartRow() const    { return aParam.nRow1; }
    inline SCCOL                EndCol() const      { return aParam.nCol2; }
    inline SCROW                EndRow() const      { return aParam.nRow2; }

    void                        ReadAutoFilter( XclImpStream& rStrm );

    inline void                 Activate()          { bActive = TRUE; }
    void                        SetAdvancedRange( const ScRange* pRange );
    void                        SetExtractPos( const ScAddress& rAddr );
    inline void                 SetAutoOrAdvanced()  { bAutoOrAdvanced = TRUE; }
    void                        Apply( const BOOL bUseUnNamed = FALSE );
    void                        CreateScDBData( const BOOL bUseUnNamed );
    void                        EnableRemoveFilter();
};

class XclImpAutoFilterBuffer : private List
{
private:
    UINT16                      nAFActiveCount;

    inline XclImpAutoFilterData* _First()   { return (XclImpAutoFilterData*) List::First(); }
    inline XclImpAutoFilterData* _Next()    { return (XclImpAutoFilterData*) List::Next(); }

    inline void                 Append( XclImpAutoFilterData* pData )
                                    { List::Insert( pData, LIST_APPEND ); }
protected:
public:
                                XclImpAutoFilterBuffer();
    virtual                     ~XclImpAutoFilterBuffer();

    void                        Insert( RootData* pRoot, const ScRange& rRange,
                                                const String& rName );
    void                        AddAdvancedRange( const ScRange& rRange );
    void                        AddExtractPos( const ScRange& rRange );
    void                        Apply();

    XclImpAutoFilterData*       GetByTab( SCTAB nTab );
    inline void                 IncrementActiveAF() { nAFActiveCount++; }
    inline BOOL                 UseUnNamed() { return nAFActiveCount == 1; }
};

#endif

<|endoftext|>


<commit_before>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2009 Scientific Computing and Imaging Institute,
   University of Utah.

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/
/**
  \file    BrickedDataset.h
  \author  Tom Fogal
           SCI Institute
           University of Utah
*/
#include <cassert>
#include <stdexcept>
#include "BrickedDataset.h"
#include "Controller/Controller.h"

namespace tuvok {

BrickedDataset::BrickedDataset() { }
BrickedDataset::~BrickedDataset() { }

void BrickedDataset::NBricksHint(size_t n) {

// The following line implements bricks.reserve(n);
// in a portable way. unordered_map does not define
// a reserve function but is seems gcc's tr1 does
  bricks.rehash(size_t(ceil(float(n) / bricks.max_load_factor())));
}

/// Adds a brick to the dataset.
void BrickedDataset::AddBrick(const BrickKey& bk,
                              const BrickMD& brick)
{
/*  MESSAGE("adding brick (%u, %u, %u) -> ((%g,%g,%g), (%g,%g,%g), (%u,%u,%u))",
          static_cast<unsigned>(std::get<0>(bk)),
          static_cast<unsigned>(std::get<1>(bk)),
          static_cast<unsigned>(std::get<2>(bk)),
          brick.center[0], brick.center[1], brick.center[2],
          brick.extents[0], brick.extents[1], brick.extents[2],
          static_cast<unsigned>(brick.n_voxels[0]),
          static_cast<unsigned>(brick.n_voxels[1]),
          static_cast<unsigned>(brick.n_voxels[2]));*/
  this->bricks.insert(std::make_pair(bk, brick));
}

/// Looks up the spatial range of a brick.
FLOATVECTOR3 BrickedDataset::GetBrickExtents(const BrickKey &bk) const
{
  BrickTable::const_iterator iter = this->bricks.find(bk);
  if(iter == this->bricks.end()) {
    T_ERROR("Unknown brick (%u, %u, %u)",
            static_cast<unsigned>(std::get<0>(bk)),
            static_cast<unsigned>(std::get<1>(bk)),
            static_cast<unsigned>(std::get<2>(bk)));
    return FLOATVECTOR3(0.0f, 0.0f, 0.0f);
  }
  return iter->second.extents;
}
UINTVECTOR3 BrickedDataset::GetBrickVoxelCounts(const BrickKey& bk) const {
  BrickTable::const_iterator iter = this->bricks.find(bk);
  if(this->bricks.end() == iter) {
    throw std::domain_error("unknown brick.");
  }
  return iter->second.n_voxels;
}

/// @return an iterator that can be used to visit every brick in the dataset.
BrickTable::const_iterator BrickedDataset::BricksBegin() const
{
  return this->bricks.begin();
}

BrickTable::const_iterator BrickedDataset::BricksEnd() const
{
  return this->bricks.end();
}

/// @return the number of bricks at the given LOD.
BrickTable::size_type BrickedDataset::GetBrickCount(size_t lod, size_t ts) const
{
  BrickTable::size_type count = 0;
  BrickTable::const_iterator iter = this->bricks.begin();
  for(; iter != this->bricks.end(); ++iter) {
    if(std::get<0>(iter->first) == ts &&
       std::get<1>(iter->first) == lod) {
      ++count;
    }
  }
  return count;
}

size_t BrickedDataset::GetLargestSingleBrickLOD(size_t ts) const {
  const size_t n_lods = this->GetLODLevelCount();
  for(size_t lod=0; lod < n_lods; ++lod) {
    if(this->GetBrickCount(lod, ts) == 1) {
      return lod;
    }
  }
  assert("not reachable");
  return 0;
}

uint64_t BrickedDataset::GetTotalBrickCount() const {
  return static_cast<uint64_t>(this->bricks.size());
}

const BrickMD& BrickedDataset::GetBrickMetadata(const BrickKey& k) const
{
  return this->bricks.find(k)->second;
}

bool
BrickedDataset::BrickIsFirstInDimension(size_t dim, const BrickKey& k) const
{
  assert(dim <= 3);
  const BrickMD& md = this->bricks.find(k)->second;
  for(BrickTable::const_iterator iter = this->BricksBegin();
      iter != this->BricksEnd(); ++iter) {
    if(iter->second.center[dim] < md.center[dim]) {
      return false;
    }
  }
  return true;
}

bool
BrickedDataset::BrickIsLastInDimension(size_t dim, const BrickKey& k) const
{
  assert(dim <= 3);
  const BrickMD& md = this->bricks.find(k)->second;
  for(BrickTable::const_iterator iter = this->BricksBegin();
      iter != this->BricksEnd(); ++iter) {
    if(iter->second.center[dim] > md.center[dim]) {
      return false;
    }
  }
  return true;
}

void BrickedDataset::Clear() {
  MESSAGE("Clearing brick metadata.");
  bricks.clear();
}

} // namespace tuvok
<commit_msg>Switch commented 'add' message to #if.<commit_after>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2009 Scientific Computing and Imaging Institute,
   University of Utah.

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/
/**
  \file    BrickedDataset.h
  \author  Tom Fogal
           SCI Institute
           University of Utah
*/
#include <cassert>
#include <stdexcept>
#include "BrickedDataset.h"
#include "Controller/Controller.h"

namespace tuvok {

BrickedDataset::BrickedDataset() { }
BrickedDataset::~BrickedDataset() { }

void BrickedDataset::NBricksHint(size_t n) {

// The following line implements bricks.reserve(n);
// in a portable way. unordered_map does not define
// a reserve function but is seems gcc's tr1 does
  bricks.rehash(size_t(ceil(float(n) / bricks.max_load_factor())));
}

/// Adds a brick to the dataset.
void BrickedDataset::AddBrick(const BrickKey& bk,
                              const BrickMD& brick)
{
#if 0
  MESSAGE("adding brick <%u,%u,%u> -> ((%g,%g,%g), (%g,%g,%g), (%u,%u,%u))",
          static_cast<unsigned>(std::get<0>(bk)),
          static_cast<unsigned>(std::get<1>(bk)),
          static_cast<unsigned>(std::get<2>(bk)),
          brick.center[0], brick.center[1], brick.center[2],
          brick.extents[0], brick.extents[1], brick.extents[2],
          static_cast<unsigned>(brick.n_voxels[0]),
          static_cast<unsigned>(brick.n_voxels[1]),
          static_cast<unsigned>(brick.n_voxels[2]));
#endif
  this->bricks.insert(std::make_pair(bk, brick));
}

/// Looks up the spatial range of a brick.
FLOATVECTOR3 BrickedDataset::GetBrickExtents(const BrickKey &bk) const
{
  BrickTable::const_iterator iter = this->bricks.find(bk);
  if(iter == this->bricks.end()) {
    T_ERROR("Unknown brick (%u, %u, %u)",
            static_cast<unsigned>(std::get<0>(bk)),
            static_cast<unsigned>(std::get<1>(bk)),
            static_cast<unsigned>(std::get<2>(bk)));
    return FLOATVECTOR3(0.0f, 0.0f, 0.0f);
  }
  return iter->second.extents;
}
UINTVECTOR3 BrickedDataset::GetBrickVoxelCounts(const BrickKey& bk) const {
  BrickTable::const_iterator iter = this->bricks.find(bk);
  if(this->bricks.end() == iter) {
    throw std::domain_error("unknown brick.");
  }
  return iter->second.n_voxels;
}

/// @return an iterator that can be used to visit every brick in the dataset.
BrickTable::const_iterator BrickedDataset::BricksBegin() const
{
  return this->bricks.begin();
}

BrickTable::const_iterator BrickedDataset::BricksEnd() const
{
  return this->bricks.end();
}

/// @return the number of bricks at the given LOD.
BrickTable::size_type BrickedDataset::GetBrickCount(size_t lod, size_t ts) const
{
  BrickTable::size_type count = 0;
  BrickTable::const_iterator iter = this->bricks.begin();
  for(; iter != this->bricks.end(); ++iter) {
    if(std::get<0>(iter->first) == ts &&
       std::get<1>(iter->first) == lod) {
      ++count;
    }
  }
  return count;
}

size_t BrickedDataset::GetLargestSingleBrickLOD(size_t ts) const {
  const size_t n_lods = this->GetLODLevelCount();
  for(size_t lod=0; lod < n_lods; ++lod) {
    if(this->GetBrickCount(lod, ts) == 1) {
      return lod;
    }
  }
  assert("not reachable");
  return 0;
}

uint64_t BrickedDataset::GetTotalBrickCount() const {
  return static_cast<uint64_t>(this->bricks.size());
}

const BrickMD& BrickedDataset::GetBrickMetadata(const BrickKey& k) const
{
  return this->bricks.find(k)->second;
}

bool
BrickedDataset::BrickIsFirstInDimension(size_t dim, const BrickKey& k) const
{
  assert(dim <= 3);
  const BrickMD& md = this->bricks.find(k)->second;
  for(BrickTable::const_iterator iter = this->BricksBegin();
      iter != this->BricksEnd(); ++iter) {
    if(iter->second.center[dim] < md.center[dim]) {
      return false;
    }
  }
  return true;
}

bool
BrickedDataset::BrickIsLastInDimension(size_t dim, const BrickKey& k) const
{
  assert(dim <= 3);
  const BrickMD& md = this->bricks.find(k)->second;
  for(BrickTable::const_iterator iter = this->BricksBegin();
      iter != this->BricksEnd(); ++iter) {
    if(iter->second.center[dim] > md.center[dim]) {
      return false;
    }
  }
  return true;
}

void BrickedDataset::Clear() {
  MESSAGE("Clearing brick metadata.");
  bricks.clear();
}

} // namespace tuvok
<|endoftext|>


<commit_before>#include "window_handle.hpp"

WindowHandle::WindowHandle() :
  m_hasPendingUpdates(false),
  m_isUpdatesEnabled(true),
  m_needRedraw(true),
  m_stallsCount(0)
{
}

void WindowHandle::setVideoTimer(VideoTimer * videoTimer)
{
  m_videoTimer = videoTimer;
  m_frameFn = videoTimer->frameFn();
  m_videoTimer->setFrameFn(bind(&WindowHandle::checkedFrameFn, this));
  m_stallsCount = 0;
}

void WindowHandle::checkedFrameFn()
{
  if (needRedraw())
    m_stallsCount = 0;
  else
    ++m_stallsCount;

  if (m_stallsCount >= 60)
  {
//    LOG(LINFO, ("PausedDOWN"));
    m_videoTimer->pause();
  }
  else
    m_frameFn();
}

WindowHandle::~WindowHandle() {}

bool WindowHandle::needRedraw() const
{
  return m_isUpdatesEnabled && m_needRedraw;
}

void WindowHandle::checkTimer()
{
  switch (m_videoTimer->state())
  {
  case VideoTimer::EStopped:
    m_videoTimer->start();
    break;
  case VideoTimer::EPaused:
//    LOG(LINFO, ("WokenUP"));
    m_videoTimer->resume();
    break;
  default:
    break;
  }
}

void WindowHandle::setNeedRedraw(bool flag)
{
  m_needRedraw = flag;
  if (m_needRedraw && m_isUpdatesEnabled)
    checkTimer();
}

shared_ptr<yg::gl::RenderContext> const & WindowHandle::renderContext()
{
  return m_renderContext;
}

void WindowHandle::setRenderContext(shared_ptr<yg::gl::RenderContext> const & renderContext)
{
  m_renderContext = renderContext;
}

bool WindowHandle::setUpdatesEnabled(bool doEnable)
{
  bool res = false;

  bool wasUpdatesEnabled = m_isUpdatesEnabled;
  m_isUpdatesEnabled = doEnable;

  if ((!wasUpdatesEnabled) && (doEnable) && (m_hasPendingUpdates))
  {
    setNeedRedraw(true);
    m_hasPendingUpdates = false;
    res = true;
  }

  return res;
}

void WindowHandle::invalidate()
{
  if (m_isUpdatesEnabled)
    setNeedRedraw(true);
  else
    m_hasPendingUpdates = true;
}
<commit_msg>stopping video timer, as the WindowHandle destroys itself.<commit_after>#include "window_handle.hpp"

WindowHandle::WindowHandle() :
  m_hasPendingUpdates(false),
  m_isUpdatesEnabled(true),
  m_needRedraw(true),
  m_stallsCount(0)
{
}

void WindowHandle::setVideoTimer(VideoTimer * videoTimer)
{
  m_videoTimer = videoTimer;
  m_frameFn = videoTimer->frameFn();
  m_videoTimer->setFrameFn(bind(&WindowHandle::checkedFrameFn, this));
  m_stallsCount = 0;
}

void WindowHandle::checkedFrameFn()
{
  if (needRedraw())
    m_stallsCount = 0;
  else
    ++m_stallsCount;

  if (m_stallsCount >= 60)
  {
//    LOG(LINFO, ("PausedDOWN"));
    m_videoTimer->pause();
  }
  else
    m_frameFn();
}

WindowHandle::~WindowHandle()
{
  m_videoTimer->stop();
}

bool WindowHandle::needRedraw() const
{
  return m_isUpdatesEnabled && m_needRedraw;
}

void WindowHandle::checkTimer()
{
  switch (m_videoTimer->state())
  {
  case VideoTimer::EStopped:
    m_videoTimer->start();
    break;
  case VideoTimer::EPaused:
//    LOG(LINFO, ("WokenUP"));
    m_videoTimer->resume();
    break;
  default:
    break;
  }
}

void WindowHandle::setNeedRedraw(bool flag)
{
  m_needRedraw = flag;
  if (m_needRedraw && m_isUpdatesEnabled)
    checkTimer();
}

shared_ptr<yg::gl::RenderContext> const & WindowHandle::renderContext()
{
  return m_renderContext;
}

void WindowHandle::setRenderContext(shared_ptr<yg::gl::RenderContext> const & renderContext)
{
  m_renderContext = renderContext;
}

bool WindowHandle::setUpdatesEnabled(bool doEnable)
{
  bool res = false;

  bool wasUpdatesEnabled = m_isUpdatesEnabled;
  m_isUpdatesEnabled = doEnable;

  if ((!wasUpdatesEnabled) && (doEnable) && (m_hasPendingUpdates))
  {
    setNeedRedraw(true);
    m_hasPendingUpdates = false;
    res = true;
  }

  return res;
}

void WindowHandle::invalidate()
{
  if (m_isUpdatesEnabled)
    setNeedRedraw(true);
  else
    m_hasPendingUpdates = true;
}
<|endoftext|>


<commit_before>void PHOSPbPbQA(const char* dataset="collection.xml")
{
  gSystem->Load("libTree.so");
  gSystem->Load("libGeom.so");
  gSystem->Load("libVMC.so");
  gSystem->Load("libPhysics.so");

  //load analysis framework
  gSystem->Load("libANALYSIS");
  gSystem->Load("libANALYSISalice"); //AliAnalysisTaskSE

  gSystem->Load("libPWG4UserTasks.so");

  gSystem->AddIncludePath("-I$ALICE_ROOT/include -I$ALICE_ROOT/PHOS");

  cout << "PHOSPbPbQA: processing collection " << dataset << endl;

  TString data = dataset;
  TChain* chain = 0;

  if(data.Contains(".xml")) {

    TGrid::Connect("alien://");

    chain = new TChain("esdTree");
    TGridCollection * collection = dynamic_cast<TGridCollection*>(TAlienCollection::Open(dataset));

    TAlienResult* result = collection->GetGridResult("",0 ,0);
    TList* rawFileList = result->GetFileInfoList();

    for (Int_t counter=0 ; counter < rawFileList->GetEntries() ; counter++) {
      TFileInfo * fi =  static_cast<TFileInfo*>(rawFileList->At(counter)) ;
      const char * rawFile = fi->GetCurrentUrl()->GetUrl() ;
      printf("Processing %s\n", rawFile) ;
      chain->Add(rawFile);
      printf("Chain: %d entries.\n",chain->GetEntries());
    }
  }

  if(data.Contains(".txt")) {
    gROOT->LoadMacro("$ALICE_ROOT/PWG0/CreateESDChain.C");
    chain = CreateESDChain(dataset, 300);
  }

  if(data.Contains(".root")) {
    chain = new TChain("esdTree");
    chain->Add(dataset);
  }

  AliLog::SetGlobalLogLevel(AliLog::kError);

  Int_t nentr = chain->GetEntries();
  printf("Number of events in the collection is %d\n",nentr);

  // Make the analysis manager
  AliAnalysisManager *mgr  = new AliAnalysisManager("Manager", "Manager");

    // Input handler
  AliESDInputHandler *esdHandler = new AliESDInputHandler();
  mgr->SetInputEventHandler(esdHandler);

  // Output handler
  AliESDHandler* esdoutHandler   = new AliESDHandler();

  // Debug level
  mgr->SetDebugLevel(0);

  //Add centrality task!
  gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskCentrality.C");
  AliCentralitySelectionTask *taskCentrality = AddTaskCentrality() ;
  // taskCentrality->SetMCInput();

  // Add my task
  AliAnalysisTaskPHOSPbPbQA *task1 = new AliAnalysisTaskPHOSPbPbQA("PbPbQA");
  mgr->AddTask(task1);

  // Create containers for input/output
  AliAnalysisDataContainer *cinput   = mgr->GetCommonInputContainer();
  AliAnalysisDataContainer *coutput = mgr->CreateContainer("histESD",TList::Class(),
							    AliAnalysisManager::kOutputContainer,
							    "PHOSPbPbQA.root");

  // Connect input/output for task1
  mgr->ConnectInput(task1 , 0, cinput);
  mgr->ConnectOutput(task1, 1, coutput);

  if (mgr->InitAnalysis()) {
    mgr->PrintStatus();
    mgr->StartAnalysis("local", chain);
  }

  cout <<" Analysis ended sucessfully "<< endl ;

}
<commit_msg>Moved to macros<commit_after><|endoftext|>


<commit_before><commit_msg>Resolves tdf#72152: respect page orientation of Calc files in recent docs<commit_after><|endoftext|>


<commit_before>/**
 * \file
 * \brief SignalsReceiverControlBlock class header
 *
 * \author Copyright (C) 2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#ifndef INCLUDE_DISTORTOS_INTERNAL_SYNCHRONIZATION_SIGNALSRECEIVERCONTROLBLOCK_HPP_
#define INCLUDE_DISTORTOS_INTERNAL_SYNCHRONIZATION_SIGNALSRECEIVERCONTROLBLOCK_HPP_

#include "distortos/SignalSet.hpp"

#include <cstdint>

union sigval;

namespace distortos
{

class SignalAction;
class SignalInformation;
class SignalInformationQueueWrapper;
class SignalsCatcher;

namespace internal
{

class SignalInformationQueue;
class SignalsCatcherControlBlock;
class ThreadControlBlock;

/// SignalsReceiverControlBlock class is a structure required by threads for "receiving" of signals
class SignalsReceiverControlBlock
{
public:

	/**
	 * \brief SignalsReceiverControlBlock's constructor
	 *
	 * \param [in] signalInformationQueueWrapper is a pointer to SignalInformationQueueWrapper for this receiver,
	 * nullptr to disable queuing of signals for this receiver
	 * \param [in] signalsCatcher is a pointer to SignalsCatcher for this receiver, nullptr if this receiver cannot
	 * catch/handle signals
	 */

	explicit SignalsReceiverControlBlock(SignalInformationQueueWrapper* signalInformationQueueWrapper,
			SignalsCatcher* signalsCatcher);

	/**
	 * \brief Accepts (clears) one of signals that are pending.
	 *
	 * This should be called when the signal is "accepted".
	 *
	 * \param [in] signalNumber is the signal that will be accepted, [0; 31]
	 *
	 * \return pair with return code (0 on success, error code otherwise) and SignalInformation object for accepted
	 * signal; error codes:
	 * - EAGAIN - no signal specified by \a signalNumber was pending;
	 * - EINVAL - \a signalNumber value is invalid;
	 */

	std::pair<int, SignalInformation> acceptPendingSignal(uint8_t signalNumber);

	/**
	 * \brief Hook function executed when delivery of signals is started.
	 *
	 * Calls SignalsCatcherControlBlock::deliveryOfSignalsStartedHook().
	 *
	 * \attention This function should be called only by the function that delivers signals (deliverSignals()).
	 *
	 * \return 0 on success, error code otherwise:
	 * - ENOTSUP - catching/handling of signals is disabled for this receiver;
	 */

	int deliveryOfSignalsStartedHook() const;

	/**
	 * \brief Generates signal for associated thread.
	 *
	 * Similar to pthread_kill() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_kill.html
	 *
	 * Adds the signalNumber to set of pending signals. If associated thread is currently waiting for this signal, it
	 * will be unblocked.
	 *
	 * \param [in] signalNumber is the signal that will be generated, [0; 31]
	 * \param [in] threadControlBlock is a reference to associated ThreadControlBlock
	 *
	 * \return 0 on success, error code otherwise:
	 * - EINVAL - \a signalNumber value is invalid;
	 */

	int generateSignal(uint8_t signalNumber, ThreadControlBlock& threadControlBlock);

	/**
	 * \return set of currently pending signals
	 */

	SignalSet getPendingSignalSet() const;

	/**
	 * \brief Gets SignalAction associated with given signal number.
	 *
	 * Similar to sigaction() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/sigaction.html
	 *
	 * \param [in] signalNumber is the signal for which the association is requested, [0; 31]
	 *
	 * \return pair with return code (0 on success, error code otherwise) and SignalAction that is associated with
	 * \a signalNumber, default-constructed object if no association was found;
	 * error codes:
	 * - EINVAL - \a signalNumber value is invalid;
	 * - ENOTSUP - catching/handling of signals is disabled for this receiver;
	 */

	std::pair<int, SignalAction> getSignalAction(uint8_t signalNumber) const;

	/**
	 * \brief Gets signal mask for associated thread.
	 *
	 * Similar to pthread_sigmask() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_sigmask.html#
	 *
	 * \return SignalSet with signal mask for associated thread
	 */

	SignalSet getSignalMask() const;

	/**
	 * \brief Queues signal for associated thread.
	 *
	 * Similar to sigqueue() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/sigqueue.html
	 *
	 * Queues the signalNumber and signal value (sigval union) in associated SignalInformationQueue object. If
	 * associated thread is currently waiting for this signal, it will be unblocked.
	 *
	 * \param [in] signalNumber is the signal that will be queued, [0; 31]
	 * \param [in] value is the signal value
	 * \param [in] threadControlBlock is a reference to associated ThreadControlBlock
	 *
	 * \return 0 on success, error code otherwise:
	 * - EAGAIN - no resources are available to queue the signal, maximal number of signals is already queued in
	 * associated SignalInformationQueue object;
	 * - EINVAL - \a signalNumber value is invalid;
	 * - ENOTSUP - queuing of signals is disabled for this receiver;
	 */

	int queueSignal(uint8_t signalNumber, sigval value, ThreadControlBlock& threadControlBlock) const;

	/**
	 * \brief Sets association for given signal number.
	 *
	 * Similar to sigaction() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/sigaction.html
	 *
	 * \param [in] signalNumber is the signal for which the association will be set, [0; 31]
	 * \param [in] signalAction is a reference to SignalAction that will be associated with given signal number, object
	 * in internal storage is copy-constructed
	 *
	 * \return pair with return code (0 on success, error code otherwise) and SignalAction that was associated with
	 * \a signalNumber, default-constructed object if no association was found;
	 * error codes:
	 * - EAGAIN - no resources are available to associate \a signalNumber with \a signalAction;
	 * - EINVAL - \a signalNumber value is invalid;
	 * - ENOTSUP - catching/handling of signals is disabled for this receiver;
	 */

	std::pair<int, SignalAction> setSignalAction(uint8_t signalNumber, const SignalAction& signalAction);

	/**
	 * \brief Sets signal mask for associated thread.
	 *
	 * Similar to pthread_sigmask() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_sigmask.html#
	 *
	 * \param [in] signalMask is the SignalSet with new signal mask for associated thread
	 * \param [in] requestDelivery selects whether delivery of signals will be requested if any pending signal is
	 * unblocked (true) or not (false)
	 *
	 * \return 0 on success, error code otherwise:
	 * - ENOTSUP - catching/handling of signals is disabled for this receiver;
	 */

	int setSignalMask(SignalSet signalMask, bool requestDelivery);

	/**
	 * \param [in] signalSet is a pointer to set of signals that will be "waited for", nullptr when wait was terminated
	 */

	void setWaitingSignalSet(const SignalSet* const signalSet)
	{
		waitingSignalSet_ = signalSet;
	}

private:

	/**
	 * \brief Checks whether signal is ignored.
	 *
	 * Signal is ignored if it has no SignalAction object associated. Signal is never ignored if catching/handling of
	 * signals is disabled for this receiver.
	 *
	 * \param [in] signalNumber is the signal for which the check will be performed, [0; 31]
	 *
	 * \return pair with return code (0 on success, error code otherwise) and boolean telling whether the signal is
	 * ignored (true) or not (false);
	 * error codes:
	 * - EINVAL - \a signalNumber value is invalid;
	 */

	std::pair<int, bool> isSignalIgnored(uint8_t signalNumber) const;

	/**
	 * \brief Actions executed after signal is "generated" with generateSignal() or queueSignal().
	 *
	 * If associated thread is currently waiting for the signal that was generated, it will be unblocked.
	 *
	 * \param [in] signalNumber is the signal that was generated, [0; 31]
	 * \param [in] threadControlBlock is a reference to associated ThreadControlBlock
	 *
	 * \return 0 on success, error code otherwise:
	 * - EINVAL - \a signalNumber value is invalid;
	 */

	int postGenerate(uint8_t signalNumber, ThreadControlBlock& threadControlBlock) const;

	/// set of pending signals
	SignalSet pendingSignalSet_;

	/// pointer to set of "waited for" signals, nullptr if associated thread is not waiting for any signals
	const SignalSet* waitingSignalSet_;

	/// pointer to SignalsCatcherControlBlock for this receiver, nullptr if this receiver cannot catch/handle signals
	SignalsCatcherControlBlock* signalsCatcherControlBlock_;

	/// pointer to SignalInformationQueue for this receiver, nullptr if this receiver cannot queue signals
	SignalInformationQueue* signalInformationQueue_;
};

}	// namespace internal

}	// namespace distortos

#endif	// INCLUDE_DISTORTOS_INTERNAL_SYNCHRONIZATION_SIGNALSRECEIVERCONTROLBLOCK_HPP_
<commit_msg>SignalsReceiverControlBlock.hpp: remove trailing whitespace<commit_after>/**
 * \file
 * \brief SignalsReceiverControlBlock class header
 *
 * \author Copyright (C) 2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#ifndef INCLUDE_DISTORTOS_INTERNAL_SYNCHRONIZATION_SIGNALSRECEIVERCONTROLBLOCK_HPP_
#define INCLUDE_DISTORTOS_INTERNAL_SYNCHRONIZATION_SIGNALSRECEIVERCONTROLBLOCK_HPP_

#include "distortos/SignalSet.hpp"

#include <cstdint>

union sigval;

namespace distortos
{

class SignalAction;
class SignalInformation;
class SignalInformationQueueWrapper;
class SignalsCatcher;

namespace internal
{

class SignalInformationQueue;
class SignalsCatcherControlBlock;
class ThreadControlBlock;

/// SignalsReceiverControlBlock class is a structure required by threads for "receiving" of signals
class SignalsReceiverControlBlock
{
public:

	/**
	 * \brief SignalsReceiverControlBlock's constructor
	 *
	 * \param [in] signalInformationQueueWrapper is a pointer to SignalInformationQueueWrapper for this receiver,
	 * nullptr to disable queuing of signals for this receiver
	 * \param [in] signalsCatcher is a pointer to SignalsCatcher for this receiver, nullptr if this receiver cannot
	 * catch/handle signals
	 */

	explicit SignalsReceiverControlBlock(SignalInformationQueueWrapper* signalInformationQueueWrapper,
			SignalsCatcher* signalsCatcher);

	/**
	 * \brief Accepts (clears) one of signals that are pending.
	 *
	 * This should be called when the signal is "accepted".
	 *
	 * \param [in] signalNumber is the signal that will be accepted, [0; 31]
	 *
	 * \return pair with return code (0 on success, error code otherwise) and SignalInformation object for accepted
	 * signal; error codes:
	 * - EAGAIN - no signal specified by \a signalNumber was pending;
	 * - EINVAL - \a signalNumber value is invalid;
	 */

	std::pair<int, SignalInformation> acceptPendingSignal(uint8_t signalNumber);

	/**
	 * \brief Hook function executed when delivery of signals is started.
	 *
	 * Calls SignalsCatcherControlBlock::deliveryOfSignalsStartedHook().
	 *
	 * \attention This function should be called only by the function that delivers signals (deliverSignals()).
	 *
	 * \return 0 on success, error code otherwise:
	 * - ENOTSUP - catching/handling of signals is disabled for this receiver;
	 */

	int deliveryOfSignalsStartedHook() const;

	/**
	 * \brief Generates signal for associated thread.
	 *
	 * Similar to pthread_kill() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_kill.html
	 *
	 * Adds the signalNumber to set of pending signals. If associated thread is currently waiting for this signal, it
	 * will be unblocked.
	 *
	 * \param [in] signalNumber is the signal that will be generated, [0; 31]
	 * \param [in] threadControlBlock is a reference to associated ThreadControlBlock
	 *
	 * \return 0 on success, error code otherwise:
	 * - EINVAL - \a signalNumber value is invalid;
	 */

	int generateSignal(uint8_t signalNumber, ThreadControlBlock& threadControlBlock);

	/**
	 * \return set of currently pending signals
	 */

	SignalSet getPendingSignalSet() const;

	/**
	 * \brief Gets SignalAction associated with given signal number.
	 *
	 * Similar to sigaction() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/sigaction.html
	 *
	 * \param [in] signalNumber is the signal for which the association is requested, [0; 31]
	 *
	 * \return pair with return code (0 on success, error code otherwise) and SignalAction that is associated with
	 * \a signalNumber, default-constructed object if no association was found;
	 * error codes:
	 * - EINVAL - \a signalNumber value is invalid;
	 * - ENOTSUP - catching/handling of signals is disabled for this receiver;
	 */

	std::pair<int, SignalAction> getSignalAction(uint8_t signalNumber) const;

	/**
	 * \brief Gets signal mask for associated thread.
	 *
	 * Similar to pthread_sigmask() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_sigmask.html#
	 *
	 * \return SignalSet with signal mask for associated thread
	 */

	SignalSet getSignalMask() const;

	/**
	 * \brief Queues signal for associated thread.
	 *
	 * Similar to sigqueue() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/sigqueue.html
	 *
	 * Queues the signalNumber and signal value (sigval union) in associated SignalInformationQueue object. If
	 * associated thread is currently waiting for this signal, it will be unblocked.
	 *
	 * \param [in] signalNumber is the signal that will be queued, [0; 31]
	 * \param [in] value is the signal value
	 * \param [in] threadControlBlock is a reference to associated ThreadControlBlock
	 *
	 * \return 0 on success, error code otherwise:
	 * - EAGAIN - no resources are available to queue the signal, maximal number of signals is already queued in
	 * associated SignalInformationQueue object;
	 * - EINVAL - \a signalNumber value is invalid;
	 * - ENOTSUP - queuing of signals is disabled for this receiver;
	 */

	int queueSignal(uint8_t signalNumber, sigval value, ThreadControlBlock& threadControlBlock) const;

	/**
	 * \brief Sets association for given signal number.
	 *
	 * Similar to sigaction() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/sigaction.html
	 *
	 * \param [in] signalNumber is the signal for which the association will be set, [0; 31]
	 * \param [in] signalAction is a reference to SignalAction that will be associated with given signal number, object
	 * in internal storage is copy-constructed
	 *
	 * \return pair with return code (0 on success, error code otherwise) and SignalAction that was associated with
	 * \a signalNumber, default-constructed object if no association was found;
	 * error codes:
	 * - EAGAIN - no resources are available to associate \a signalNumber with \a signalAction;
	 * - EINVAL - \a signalNumber value is invalid;
	 * - ENOTSUP - catching/handling of signals is disabled for this receiver;
	 */

	std::pair<int, SignalAction> setSignalAction(uint8_t signalNumber, const SignalAction& signalAction);

	/**
	 * \brief Sets signal mask for associated thread.
	 *
	 * Similar to pthread_sigmask() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_sigmask.html#
	 *
	 * \param [in] signalMask is the SignalSet with new signal mask for associated thread
	 * \param [in] requestDelivery selects whether delivery of signals will be requested if any pending signal is
	 * unblocked (true) or not (false)
	 *
	 * \return 0 on success, error code otherwise:
	 * - ENOTSUP - catching/handling of signals is disabled for this receiver;
	 */

	int setSignalMask(SignalSet signalMask, bool requestDelivery);

	/**
	 * \param [in] signalSet is a pointer to set of signals that will be "waited for", nullptr when wait was terminated
	 */

	void setWaitingSignalSet(const SignalSet* const signalSet)
	{
		waitingSignalSet_ = signalSet;
	}

private:

	/**
	 * \brief Checks whether signal is ignored.
	 *
	 * Signal is ignored if it has no SignalAction object associated. Signal is never ignored if catching/handling of
	 * signals is disabled for this receiver.
	 *
	 * \param [in] signalNumber is the signal for which the check will be performed, [0; 31]
	 *
	 * \return pair with return code (0 on success, error code otherwise) and boolean telling whether the signal is
	 * ignored (true) or not (false);
	 * error codes:
	 * - EINVAL - \a signalNumber value is invalid;
	 */

	std::pair<int, bool> isSignalIgnored(uint8_t signalNumber) const;

	/**
	 * \brief Actions executed after signal is "generated" with generateSignal() or queueSignal().
	 *
	 * If associated thread is currently waiting for the signal that was generated, it will be unblocked.
	 *
	 * \param [in] signalNumber is the signal that was generated, [0; 31]
	 * \param [in] threadControlBlock is a reference to associated ThreadControlBlock
	 *
	 * \return 0 on success, error code otherwise:
	 * - EINVAL - \a signalNumber value is invalid;
	 */

	int postGenerate(uint8_t signalNumber, ThreadControlBlock& threadControlBlock) const;

	/// set of pending signals
	SignalSet pendingSignalSet_;

	/// pointer to set of "waited for" signals, nullptr if associated thread is not waiting for any signals
	const SignalSet* waitingSignalSet_;

	/// pointer to SignalsCatcherControlBlock for this receiver, nullptr if this receiver cannot catch/handle signals
	SignalsCatcherControlBlock* signalsCatcherControlBlock_;

	/// pointer to SignalInformationQueue for this receiver, nullptr if this receiver cannot queue signals
	SignalInformationQueue* signalInformationQueue_;
};

}	// namespace internal

}	// namespace distortos

#endif	// INCLUDE_DISTORTOS_INTERNAL_SYNCHRONIZATION_SIGNALSRECEIVERCONTROLBLOCK_HPP_
<|endoftext|>